instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(xml_set_object) { xml_parser *parser; zval *pind, *mythis; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ro", &pind, &mythis) == FAILURE) { return; } ZEND_FETCH_RESOURCE(parser,xml_parser *, &pind, -1, "XML Parser", le_xml_parser); /* please leave this commented - or ask [email protected] before doing it (again) */ if (parser->object) { zval_ptr_dtor(&parser->object); } /* please leave this commented - or ask [email protected] before doing it (again) */ /* #ifdef ZEND_ENGINE_2 zval_add_ref(&parser->object); #endif */ ALLOC_ZVAL(parser->object); MAKE_COPY_ZVAL(&mythis, parser->object); RETVAL_TRUE; } Commit Message: CWE ID: CWE-119
PHP_FUNCTION(xml_set_object) { xml_parser *parser; zval *pind, *mythis; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ro", &pind, &mythis) == FAILURE) { return; } ZEND_FETCH_RESOURCE(parser,xml_parser *, &pind, -1, "XML Parser", le_xml_parser); /* please leave this commented - or ask [email protected] before doing it (again) */ if (parser->object) { zval_ptr_dtor(&parser->object); } /* please leave this commented - or ask [email protected] before doing it (again) */ /* #ifdef ZEND_ENGINE_2 zval_add_ref(&parser->object); #endif */ ALLOC_ZVAL(parser->object); MAKE_COPY_ZVAL(&mythis, parser->object); RETVAL_TRUE; }
165,036
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void cirrus_invalidate_region(CirrusVGAState * s, int off_begin, int off_pitch, int bytesperline, int lines) { int y; int off_cur; int off_cur_end; for (y = 0; y < lines; y++) { off_cur = off_begin; off_cur_end = (off_cur + bytesperline) & s->cirrus_addr_mask; memory_region_set_dirty(&s->vga.vram, off_cur, off_cur_end - off_cur); off_begin += off_pitch; } uint8_t *dst; dst = s->vga.vram_ptr + (s->cirrus_blt_dstaddr & s->cirrus_addr_mask); if (blit_is_unsafe(s, false)) return 0; (*s->cirrus_rop) (s, dst, src, s->cirrus_blt_dstpitch, 0, s->cirrus_blt_width, s->cirrus_blt_height); cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_width, s->cirrus_blt_height); return 1; } Commit Message: CWE ID: CWE-125
static void cirrus_invalidate_region(CirrusVGAState * s, int off_begin, int off_pitch, int bytesperline, int lines) { int y; int off_cur; int off_cur_end; if (off_pitch < 0) { off_begin -= bytesperline - 1; } for (y = 0; y < lines; y++) { off_cur = off_begin; off_cur_end = (off_cur + bytesperline) & s->cirrus_addr_mask; assert(off_cur_end >= off_cur); memory_region_set_dirty(&s->vga.vram, off_cur, off_cur_end - off_cur); off_begin += off_pitch; } uint8_t *dst; dst = s->vga.vram_ptr + (s->cirrus_blt_dstaddr & s->cirrus_addr_mask); if (blit_is_unsafe(s, false)) return 0; (*s->cirrus_rop) (s, dst, src, s->cirrus_blt_dstpitch, 0, s->cirrus_blt_width, s->cirrus_blt_height); cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_width, s->cirrus_blt_height); return 1; }
165,388
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_add(PNG_CONST image_transform **this, unsigned int max, png_uint_32 counter, char *name, size_t sizeof_name, size_t *pos, png_byte colour_type, png_byte bit_depth) { for (;;) /* until we manage to add something */ { png_uint_32 mask; image_transform *list; /* Find the next counter value, if the counter is zero this is the start * of the list. This routine always returns the current counter (not the * next) so it returns 0 at the end and expects 0 at the beginning. */ if (counter == 0) /* first time */ { image_transform_reset_count(); if (max <= 1) counter = 1; else counter = random_32(); } else /* advance the counter */ { switch (max) { case 0: ++counter; break; case 1: counter <<= 1; break; default: counter = random_32(); break; } } /* Now add all these items, if possible */ *this = &image_transform_end; list = image_transform_first; mask = 1; /* Go through the whole list adding anything that the counter selects: */ while (list != &image_transform_end) { if ((counter & mask) != 0 && list->enable && (max == 0 || list->local_use < max)) { /* Candidate to add: */ if (list->add(list, this, colour_type, bit_depth) || max == 0) { /* Added, so add to the name too. */ *pos = safecat(name, sizeof_name, *pos, " +"); *pos = safecat(name, sizeof_name, *pos, list->name); } else { /* Not useful and max>0, so remove it from *this: */ *this = list->next; list->next = 0; /* And, since we know it isn't useful, stop it being added again * in this run: */ list->local_use = max; } } mask <<= 1; list = list->list; } /* Now if anything was added we have something to do. */ if (*this != &image_transform_end) return counter; /* Nothing added, but was there anything in there to add? */ if (!image_transform_test_counter(counter, max)) return 0; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_add(PNG_CONST image_transform **this, unsigned int max, image_transform_add(const image_transform **this, unsigned int max, png_uint_32 counter, char *name, size_t sizeof_name, size_t *pos, png_byte colour_type, png_byte bit_depth) { for (;;) /* until we manage to add something */ { png_uint_32 mask; image_transform *list; /* Find the next counter value, if the counter is zero this is the start * of the list. This routine always returns the current counter (not the * next) so it returns 0 at the end and expects 0 at the beginning. */ if (counter == 0) /* first time */ { image_transform_reset_count(); if (max <= 1) counter = 1; else counter = random_32(); } else /* advance the counter */ { switch (max) { case 0: ++counter; break; case 1: counter <<= 1; break; default: counter = random_32(); break; } } /* Now add all these items, if possible */ *this = &image_transform_end; list = image_transform_first; mask = 1; /* Go through the whole list adding anything that the counter selects: */ while (list != &image_transform_end) { if ((counter & mask) != 0 && list->enable && (max == 0 || list->local_use < max)) { /* Candidate to add: */ if (list->add(list, this, colour_type, bit_depth) || max == 0) { /* Added, so add to the name too. */ *pos = safecat(name, sizeof_name, *pos, " +"); *pos = safecat(name, sizeof_name, *pos, list->name); } else { /* Not useful and max>0, so remove it from *this: */ *this = list->next; list->next = 0; /* And, since we know it isn't useful, stop it being added again * in this run: */ list->local_use = max; } } mask <<= 1; list = list->list; } /* Now if anything was added we have something to do. */ if (*this != &image_transform_end) return counter; /* Nothing added, but was there anything in there to add? */ if (!image_transform_test_counter(counter, max)) return 0; } }
173,619
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset, int len) { int r; unsigned long addr; addr = gfn_to_hva(kvm, gfn); if (kvm_is_error_hva(addr)) return -EFAULT; r = copy_from_user(data, (void __user *)addr + offset, len); if (r) return -EFAULT; return 0; } Commit Message: KVM: Validate userspace_addr of memslot when registered This way, we can avoid checking the user space address many times when we read the guest memory. Although we can do the same for write if we check which slots are writable, we do not care write now: reading the guest memory happens more often than writing. [avi: change VERIFY_READ to VERIFY_WRITE] Signed-off-by: Takuya Yoshikawa <[email protected]> Signed-off-by: Avi Kivity <[email protected]> CWE ID: CWE-20
int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset, int len) { int r; unsigned long addr; addr = gfn_to_hva(kvm, gfn); if (kvm_is_error_hva(addr)) return -EFAULT; r = __copy_from_user(data, (void __user *)addr + offset, len); if (r) return -EFAULT; return 0; }
166,100
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void locationWithExceptionAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObject* proxyImp = V8TestObject::toNative(info.Holder()); TestNode* imp = WTF::getPtr(proxyImp->locationWithException()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHrefThrows(cppValue); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static void locationWithExceptionAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObject* proxyImp = V8TestObject::toNative(info.Holder()); RefPtr<TestNode> imp = WTF::getPtr(proxyImp->locationWithException()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHrefThrows(cppValue); }
171,684
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ModuleExport size_t RegisterJPEGImage(void) { char version[MaxTextExtent]; MagickInfo *entry; static const char description[] = "Joint Photographic Experts Group JFIF format"; *version='\0'; #if defined(JPEG_LIB_VERSION) (void) FormatLocaleString(version,MaxTextExtent,"%d",JPEG_LIB_VERSION); #endif entry=SetMagickInfo("JPE"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->magick=(IsImageFormatHandler *) IsJPEG; entry->adjoin=MagickFalse; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPEG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->magick=(IsImageFormatHandler *) IsJPEG; entry->adjoin=MagickFalse; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPS"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PJPEG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } Commit Message: ... CWE ID: CWE-20
ModuleExport size_t RegisterJPEGImage(void) { char version[MaxTextExtent]; MagickInfo *entry; static const char description[] = "Joint Photographic Experts Group JFIF format"; *version='\0'; #if defined(JPEG_LIB_VERSION) (void) FormatLocaleString(version,MaxTextExtent,"%d",JPEG_LIB_VERSION); #endif entry=SetMagickInfo("JPE"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->magick=(IsImageFormatHandler *) IsJPEG; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPEG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->magick=(IsImageFormatHandler *) IsJPEG; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPS"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PJPEG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); }
168,034
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool btsock_thread_remove_fd_and_close(int thread_handle, int fd) { if (thread_handle < 0 || thread_handle >= MAX_THREAD) { APPL_TRACE_ERROR("%s invalid thread handle: %d", __func__, thread_handle); return false; } if (fd == -1) { APPL_TRACE_ERROR("%s invalid file descriptor.", __func__); return false; } sock_cmd_t cmd = {CMD_REMOVE_FD, fd, 0, 0, 0}; return send(ts[thread_handle].cmd_fdw, &cmd, sizeof(cmd), 0) == sizeof(cmd); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
bool btsock_thread_remove_fd_and_close(int thread_handle, int fd) { if (thread_handle < 0 || thread_handle >= MAX_THREAD) { APPL_TRACE_ERROR("%s invalid thread handle: %d", __func__, thread_handle); return false; } if (fd == -1) { APPL_TRACE_ERROR("%s invalid file descriptor.", __func__); return false; } sock_cmd_t cmd = {CMD_REMOVE_FD, fd, 0, 0, 0}; return TEMP_FAILURE_RETRY(send(ts[thread_handle].cmd_fdw, &cmd, sizeof(cmd), 0)) == sizeof(cmd); }
173,463
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool Block::IsInvisible() const { return bool(int(m_flags & 0x08) != 0); } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
bool Block::IsInvisible() const const Block::Frame& Block::GetFrame(int idx) const { assert(idx >= 0); assert(idx < m_frame_count); const Frame& f = m_frames[idx]; assert(f.pos > 0); assert(f.len > 0); return f; }
174,391
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int __init acpi_custom_method_init(void) { if (!acpi_debugfs_dir) return -ENOENT; cm_dentry = debugfs_create_file("custom_method", S_IWUSR, acpi_debugfs_dir, NULL, &cm_fops); if (!cm_dentry) return -ENODEV; return 0; } Commit Message: ACPI: Split out custom_method functionality into an own driver With /sys/kernel/debug/acpi/custom_method root can write to arbitrary memory and increase his priveleges, even if these are restricted. -> Make this an own debug .config option and warn about the security issue in the config description. -> Still keep acpi/debugfs.c which now only creates an empty /sys/kernel/debug/acpi directory. There might be other users of it later. Signed-off-by: Thomas Renninger <[email protected]> Acked-by: Rafael J. Wysocki <[email protected]> Acked-by: [email protected] Signed-off-by: Len Brown <[email protected]> CWE ID: CWE-264
static int __init acpi_custom_method_init(void)
165,901
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SoftAVC::setDecodeArgs( ivd_video_decode_ip_t *ps_dec_ip, ivd_video_decode_op_t *ps_dec_op, OMX_BUFFERHEADERTYPE *inHeader, OMX_BUFFERHEADERTYPE *outHeader, size_t timeStampIx) { size_t sizeY = outputBufferWidth() * outputBufferHeight(); size_t sizeUV; uint8_t *pBuf; ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t); ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE; /* When in flush and after EOS with zero byte input, * inHeader is set to zero. Hence check for non-null */ if (inHeader) { ps_dec_ip->u4_ts = timeStampIx; ps_dec_ip->pv_stream_buffer = inHeader->pBuffer + inHeader->nOffset; ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen; } else { ps_dec_ip->u4_ts = 0; ps_dec_ip->pv_stream_buffer = NULL; ps_dec_ip->u4_num_Bytes = 0; } if (outHeader) { pBuf = outHeader->pBuffer; } else { pBuf = mFlushOutBuffer; } sizeUV = sizeY / 4; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV; ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf; ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY; ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV; ps_dec_ip->s_out_buffer.u4_num_bufs = 3; return; } Commit Message: codecs: check OMX buffer size before use in (avc|hevc|mpeg2)dec Bug: 27833616 Change-Id: Ic4045a3f56f53b08d0b1264b2a91b8f43e91b738 (cherry picked from commit 87fdee0bc9e3ac4d2a88ef0a8e150cfdf08c161d) CWE ID: CWE-20
void SoftAVC::setDecodeArgs( bool SoftAVC::setDecodeArgs( ivd_video_decode_ip_t *ps_dec_ip, ivd_video_decode_op_t *ps_dec_op, OMX_BUFFERHEADERTYPE *inHeader, OMX_BUFFERHEADERTYPE *outHeader, size_t timeStampIx) { size_t sizeY = outputBufferWidth() * outputBufferHeight(); size_t sizeUV; ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t); ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE; /* When in flush and after EOS with zero byte input, * inHeader is set to zero. Hence check for non-null */ if (inHeader) { ps_dec_ip->u4_ts = timeStampIx; ps_dec_ip->pv_stream_buffer = inHeader->pBuffer + inHeader->nOffset; ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen; } else { ps_dec_ip->u4_ts = 0; ps_dec_ip->pv_stream_buffer = NULL; ps_dec_ip->u4_num_Bytes = 0; } sizeUV = sizeY / 4; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV; uint8_t *pBuf; if (outHeader) { if (outHeader->nAllocLen < sizeY + (sizeUV * 2)) { android_errorWriteLog(0x534e4554, "27569635"); return false; } pBuf = outHeader->pBuffer; } else { // mFlushOutBuffer always has the right size. pBuf = mFlushOutBuffer; } ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf; ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY; ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV; ps_dec_ip->s_out_buffer.u4_num_bufs = 3; return true; }
174,180
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int git_pkt_parse_line( git_pkt **head, const char *line, const char **out, size_t bufflen) { int ret; int32_t len; /* Not even enough for the length */ if (bufflen > 0 && bufflen < PKT_LEN_SIZE) return GIT_EBUFS; len = parse_len(line); if (len < 0) { /* * If we fail to parse the length, it might be because the * server is trying to send us the packfile already. */ if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) { giterr_clear(); *out = line; return pack_pkt(head); } return (int)len; } /* * If we were given a buffer length, then make sure there is * enough in the buffer to satisfy this line */ if (bufflen > 0 && bufflen < (size_t)len) return GIT_EBUFS; /* * The length has to be exactly 0 in case of a flush * packet or greater than PKT_LEN_SIZE, as the decoded * length includes its own encoded length of four bytes. */ if (len != 0 && len < PKT_LEN_SIZE) return GIT_ERROR; line += PKT_LEN_SIZE; /* * TODO: How do we deal with empty lines? Try again? with the next * line? */ if (len == PKT_LEN_SIZE) { *head = NULL; *out = line; return 0; } if (len == 0) { /* Flush pkt */ *out = line; return flush_pkt(head); } len -= PKT_LEN_SIZE; /* the encoded length includes its own size */ if (*line == GIT_SIDE_BAND_DATA) ret = data_pkt(head, line, len); else if (*line == GIT_SIDE_BAND_PROGRESS) ret = sideband_progress_pkt(head, line, len); else if (*line == GIT_SIDE_BAND_ERROR) ret = sideband_error_pkt(head, line, len); else if (!git__prefixcmp(line, "ACK")) ret = ack_pkt(head, line, len); else if (!git__prefixcmp(line, "NAK")) ret = nak_pkt(head); else if (!git__prefixcmp(line, "ERR ")) ret = err_pkt(head, line, len); else if (*line == '#') ret = comment_pkt(head, line, len); else if (!git__prefixcmp(line, "ok")) ret = ok_pkt(head, line, len); else if (!git__prefixcmp(line, "ng")) ret = ng_pkt(head, line, len); else if (!git__prefixcmp(line, "unpack")) ret = unpack_pkt(head, line, len); else ret = ref_pkt(head, line, len); *out = line + len; return ret; } Commit Message: smart_pkt: treat empty packet lines as error The Git protocol does not specify what should happen in the case of an empty packet line (that is a packet line "0004"). We currently indicate success, but do not return a packet in the case where we hit an empty line. The smart protocol was not prepared to handle such packets in all cases, though, resulting in a `NULL` pointer dereference. Fix the issue by returning an error instead. As such kind of packets is not even specified by upstream, this is the right thing to do. CWE ID: CWE-476
int git_pkt_parse_line( git_pkt **head, const char *line, const char **out, size_t bufflen) { int ret; int32_t len; /* Not even enough for the length */ if (bufflen > 0 && bufflen < PKT_LEN_SIZE) return GIT_EBUFS; len = parse_len(line); if (len < 0) { /* * If we fail to parse the length, it might be because the * server is trying to send us the packfile already. */ if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) { giterr_clear(); *out = line; return pack_pkt(head); } return (int)len; } /* * If we were given a buffer length, then make sure there is * enough in the buffer to satisfy this line */ if (bufflen > 0 && bufflen < (size_t)len) return GIT_EBUFS; /* * The length has to be exactly 0 in case of a flush * packet or greater than PKT_LEN_SIZE, as the decoded * length includes its own encoded length of four bytes. */ if (len != 0 && len < PKT_LEN_SIZE) return GIT_ERROR; line += PKT_LEN_SIZE; /* * The Git protocol does not specify empty lines as part * of the protocol. Not knowing what to do with an empty * line, we should return an error upon hitting one. */ if (len == PKT_LEN_SIZE) { giterr_set_str(GITERR_NET, "Invalid empty packet"); return GIT_ERROR; } if (len == 0) { /* Flush pkt */ *out = line; return flush_pkt(head); } len -= PKT_LEN_SIZE; /* the encoded length includes its own size */ if (*line == GIT_SIDE_BAND_DATA) ret = data_pkt(head, line, len); else if (*line == GIT_SIDE_BAND_PROGRESS) ret = sideband_progress_pkt(head, line, len); else if (*line == GIT_SIDE_BAND_ERROR) ret = sideband_error_pkt(head, line, len); else if (!git__prefixcmp(line, "ACK")) ret = ack_pkt(head, line, len); else if (!git__prefixcmp(line, "NAK")) ret = nak_pkt(head); else if (!git__prefixcmp(line, "ERR ")) ret = err_pkt(head, line, len); else if (*line == '#') ret = comment_pkt(head, line, len); else if (!git__prefixcmp(line, "ok")) ret = ok_pkt(head, line, len); else if (!git__prefixcmp(line, "ng")) ret = ng_pkt(head, line, len); else if (!git__prefixcmp(line, "unpack")) ret = unpack_pkt(head, line, len); else ret = ref_pkt(head, line, len); *out = line + len; return ret; }
168,527
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int net_get(int s, void *arg, int *len) { struct net_hdr nh; int plen; if (net_read_exact(s, &nh, sizeof(nh)) == -1) { return -1; } plen = ntohl(nh.nh_len); if (!(plen <= *len)) printf("PLEN %d type %d len %d\n", plen, nh.nh_type, *len); assert(plen <= *len); /* XXX */ *len = plen; if ((*len) && (net_read_exact(s, arg, *len) == -1)) { return -1; } return nh.nh_type; } Commit Message: OSdep: Fixed segmentation fault that happens with a malicious server sending a negative length (Closes #16 on GitHub). git-svn-id: http://svn.aircrack-ng.org/trunk@2419 28c6078b-6c39-48e3-add9-af49d547ecab CWE ID: CWE-20
int net_get(int s, void *arg, int *len) { struct net_hdr nh; int plen; if (net_read_exact(s, &nh, sizeof(nh)) == -1) { return -1; } plen = ntohl(nh.nh_len); if (!(plen <= *len)) printf("PLEN %d type %d len %d\n", plen, nh.nh_type, *len); assert(plen <= *len && plen > 0); /* XXX */ *len = plen; if ((*len) && (net_read_exact(s, arg, *len) == -1)) { return -1; } return nh.nh_type; }
168,912
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row) { png_uint_32 i; png_uint_32 row_width = row_info->width; int rgb_error = 0; png_debug(1, "in png_do_rgb_to_gray"); if ( #ifdef PNG_USELESS_TESTS_SUPPORTED row != NULL && row_info != NULL && #endif (row_info->color_type & PNG_COLOR_MASK_COLOR)) { png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff; png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff; png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff; if (row_info->color_type == PNG_COLOR_TYPE_RGB) { if (row_info->bit_depth == 8) { #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL) { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_byte red = png_ptr->gamma_to_1[*(sp++)]; png_byte green = png_ptr->gamma_to_1[*(sp++)]; png_byte blue = png_ptr->gamma_to_1[*(sp++)]; if (red != green || red != blue) { rgb_error |= 1; *(dp++) = png_ptr->gamma_from_1[ (rc*red + gc*green + bc*blue)>>15]; } else *(dp++) = *(sp - 1); } } else #endif { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_byte red = *(sp++); png_byte green = *(sp++); png_byte blue = *(sp++); if (red != green || red != blue) { rgb_error |= 1; *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15); } else *(dp++) = *(sp - 1); } } } else /* RGB bit_depth == 16 */ { #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) if (png_ptr->gamma_16_to_1 != NULL && png_ptr->gamma_16_from_1 != NULL) { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_uint_16 red, green, blue, w; red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; if (red == green && red == blue) w = red; else { png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >> png_ptr->gamma_shift][red>>8]; png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >> png_ptr->gamma_shift][green>>8]; png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >> png_ptr->gamma_shift][blue>>8]; png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1 + bc*blue_1)>>15); w = png_ptr->gamma_16_from_1[(gray16&0xff) >> png_ptr->gamma_shift][gray16 >> 8]; rgb_error |= 1; } *(dp++) = (png_byte)((w>>8) & 0xff); *(dp++) = (png_byte)(w & 0xff); } } else #endif { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_uint_16 red, green, blue, gray16; red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; if (red != green || red != blue) rgb_error |= 1; gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15); *(dp++) = (png_byte)((gray16>>8) & 0xff); *(dp++) = (png_byte)(gray16 & 0xff); } } } } if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) { if (row_info->bit_depth == 8) { #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL) { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_byte red = png_ptr->gamma_to_1[*(sp++)]; png_byte green = png_ptr->gamma_to_1[*(sp++)]; png_byte blue = png_ptr->gamma_to_1[*(sp++)]; if (red != green || red != blue) rgb_error |= 1; *(dp++) = png_ptr->gamma_from_1 [(rc*red + gc*green + bc*blue)>>15]; *(dp++) = *(sp++); /* alpha */ } } else #endif { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_byte red = *(sp++); png_byte green = *(sp++); png_byte blue = *(sp++); if (red != green || red != blue) rgb_error |= 1; *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15); *(dp++) = *(sp++); /* alpha */ } } } else /* RGBA bit_depth == 16 */ { #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) if (png_ptr->gamma_16_to_1 != NULL && png_ptr->gamma_16_from_1 != NULL) { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_uint_16 red, green, blue, w; red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; if (red == green && red == blue) w = red; else { png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >> png_ptr->gamma_shift][red>>8]; png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >> png_ptr->gamma_shift][green>>8]; png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >> png_ptr->gamma_shift][blue>>8]; png_uint_16 gray16 = (png_uint_16)((rc * red_1 + gc * green_1 + bc * blue_1)>>15); w = png_ptr->gamma_16_from_1[(gray16&0xff) >> png_ptr->gamma_shift][gray16 >> 8]; rgb_error |= 1; } *(dp++) = (png_byte)((w>>8) & 0xff); *(dp++) = (png_byte)(w & 0xff); *(dp++) = *(sp++); /* alpha */ *(dp++) = *(sp++); } } else #endif { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_uint_16 red, green, blue, gray16; red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2; green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2; blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2; if (red != green || red != blue) rgb_error |= 1; gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15); *(dp++) = (png_byte)((gray16>>8) & 0xff); *(dp++) = (png_byte)(gray16 & 0xff); *(dp++) = *(sp++); /* alpha */ *(dp++) = *(sp++); } } } } row_info->channels -= (png_byte)2; row_info->color_type &= ~PNG_COLOR_MASK_COLOR; row_info->pixel_depth = (png_byte)(row_info->channels * row_info->bit_depth); row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, row_width); } return rgb_error; } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row) { png_uint_32 i; png_uint_32 row_width = row_info->width; int rgb_error = 0; png_debug(1, "in png_do_rgb_to_gray"); if ( #ifdef PNG_USELESS_TESTS_SUPPORTED row != NULL && row_info != NULL && #endif (row_info->color_type & PNG_COLOR_MASK_COLOR)) { png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff; png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff; png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff; if (row_info->color_type == PNG_COLOR_TYPE_RGB) { if (row_info->bit_depth == 8) { #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL) { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_byte red = png_ptr->gamma_to_1[*(sp++)]; png_byte green = png_ptr->gamma_to_1[*(sp++)]; png_byte blue = png_ptr->gamma_to_1[*(sp++)]; if (red != green || red != blue) { rgb_error |= 1; *(dp++) = png_ptr->gamma_from_1[ (rc*red + gc*green + bc*blue)>>15]; } else *(dp++) = *(sp - 1); } } else #endif { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_byte red = *(sp++); png_byte green = *(sp++); png_byte blue = *(sp++); if (red != green || red != blue) { rgb_error |= 1; *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15); } else *(dp++) = *(sp - 1); } } } else /* RGB bit_depth == 16 */ { #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) if (png_ptr->gamma_16_to_1 != NULL && png_ptr->gamma_16_from_1 != NULL) { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_uint_16 red, green, blue, w; png_byte hi,lo; hi=*(sp)++; lo=*(sp)++; red = (png_uint_16)((hi << 8) | (lo)); hi=*(sp)++; lo=*(sp)++; green = (png_uint_16)((hi << 8) | (lo)); hi=*(sp)++; lo=*(sp)++; blue = (png_uint_16)((hi << 8) | (lo)); if (red == green && red == blue) w = red; else { png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >> png_ptr->gamma_shift][red>>8]; png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >> png_ptr->gamma_shift][green>>8]; png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >> png_ptr->gamma_shift][blue>>8]; png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1 + bc*blue_1)>>15); w = png_ptr->gamma_16_from_1[(gray16&0xff) >> png_ptr->gamma_shift][gray16 >> 8]; rgb_error |= 1; } *(dp++) = (png_byte)((w>>8) & 0xff); *(dp++) = (png_byte)(w & 0xff); } } else #endif { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_uint_16 red, green, blue, gray16; png_byte hi,lo; hi=*(sp)++; lo=*(sp)++; red = (png_uint_16)((hi << 8) | (lo)); hi=*(sp)++; lo=*(sp)++; green = (png_uint_16)((hi << 8) | (lo)); hi=*(sp)++; lo=*(sp)++; blue = (png_uint_16)((hi << 8) | (lo)); if (red != green || red != blue) rgb_error |= 1; gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15); *(dp++) = (png_byte)((gray16>>8) & 0xff); *(dp++) = (png_byte)(gray16 & 0xff); } } } } if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) { if (row_info->bit_depth == 8) { #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL) { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_byte red = png_ptr->gamma_to_1[*(sp++)]; png_byte green = png_ptr->gamma_to_1[*(sp++)]; png_byte blue = png_ptr->gamma_to_1[*(sp++)]; if (red != green || red != blue) rgb_error |= 1; *(dp++) = png_ptr->gamma_from_1 [(rc*red + gc*green + bc*blue)>>15]; *(dp++) = *(sp++); /* alpha */ } } else #endif { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_byte red = *(sp++); png_byte green = *(sp++); png_byte blue = *(sp++); if (red != green || red != blue) rgb_error |= 1; *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15); *(dp++) = *(sp++); /* alpha */ } } } else /* RGBA bit_depth == 16 */ { #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) if (png_ptr->gamma_16_to_1 != NULL && png_ptr->gamma_16_from_1 != NULL) { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_uint_16 red, green, blue, w; png_byte hi,lo; hi=*(sp)++; lo=*(sp)++; red = (png_uint_16)((hi << 8) | (lo)); hi=*(sp)++; lo=*(sp)++; green = (png_uint_16)((hi << 8) | (lo)); hi=*(sp)++; lo=*(sp)++; blue = (png_uint_16)((hi << 8) | (lo)); if (red == green && red == blue) w = red; else { png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >> png_ptr->gamma_shift][red>>8]; png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >> png_ptr->gamma_shift][green>>8]; png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >> png_ptr->gamma_shift][blue>>8]; png_uint_16 gray16 = (png_uint_16)((rc * red_1 + gc * green_1 + bc * blue_1)>>15); w = png_ptr->gamma_16_from_1[(gray16&0xff) >> png_ptr->gamma_shift][gray16 >> 8]; rgb_error |= 1; } *(dp++) = (png_byte)((w>>8) & 0xff); *(dp++) = (png_byte)(w & 0xff); *(dp++) = *(sp++); /* alpha */ *(dp++) = *(sp++); } } else #endif { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_uint_16 red, green, blue, gray16; red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2; green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2; blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2; if (red != green || red != blue) rgb_error |= 1; gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15); *(dp++) = (png_byte)((gray16>>8) & 0xff); *(dp++) = (png_byte)(gray16 & 0xff); *(dp++) = *(sp++); /* alpha */ *(dp++) = *(sp++); } } } } row_info->channels -= (png_byte)2; row_info->color_type &= ~PNG_COLOR_MASK_COLOR; row_info->pixel_depth = (png_byte)(row_info->channels * row_info->bit_depth); row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, row_width); } return rgb_error; }
172,171
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int dalvik_disassemble (RAsm *a, RAsmOp *op, const ut8 *buf, int len) { int vA, vB, vC, payload = 0, i = (int) buf[0]; int size = dalvik_opcodes[i].len; char str[1024], *strasm; ut64 offset; const char *flag_str; op->buf_asm[0] = 0; if (buf[0] == 0x00) { /* nop */ switch (buf[1]) { case 0x01: /* packed-switch-payload */ { unsigned short array_size = buf[2] | (buf[3] << 8); int first_key = buf[4] | (buf[5] << 8) | (buf[6] << 16) | (buf[7] << 24); sprintf (op->buf_asm, "packed-switch-payload %d, %d", array_size, first_key); size = 8; payload = 2 * (array_size * 2); len = 0; } break; case 0x02: /* sparse-switch-payload */ { unsigned short array_size = buf[2] | (buf[3] << 8); sprintf (op->buf_asm, "sparse-switch-payload %d", array_size); size = 4; payload = 2 * (array_size*4); len = 0; } break; case 0x03: /* fill-array-data-payload */ if (len > 7) { unsigned short elem_width = buf[2] | (buf[3] << 8); unsigned int array_size = buf[4] | (buf[5] << 8) | (buf[6] << 16) | (buf[7] << 24); snprintf (op->buf_asm, sizeof (op->buf_asm), "fill-array-data-payload %d, %d", elem_width, array_size); payload = 2 * ((array_size * elem_width+1)/2); } size = 8; len = 0; break; default: /* nop */ break; } } strasm = NULL; if (size <= len) { strncpy (op->buf_asm, dalvik_opcodes[i].name, sizeof (op->buf_asm) - 1); strasm = strdup (op->buf_asm); size = dalvik_opcodes[i].len; switch (dalvik_opcodes[i].fmt) { case fmtop: break; case fmtopvAvB: vA = buf[1] & 0x0f; vB = (buf[1] & 0xf0) >> 4; sprintf (str, " v%i, v%i", vA, vB); strasm = r_str_concat (strasm, str); break; case fmtopvAAvBBBB: vA = (int) buf[1]; vB = (buf[3] << 8) | buf[2]; sprintf (str, " v%i, v%i", vA, vB); strasm = r_str_concat (strasm, str); break; case fmtopvAAAAvBBBB: // buf[1] seems useless :/ vA = (buf[3] << 8) | buf[2]; vB = (buf[5] << 8) | buf[4]; sprintf (str, " v%i, v%i", vA, vB); strasm = r_str_concat (strasm, str); break; case fmtopvAA: vA = (int) buf[1]; sprintf (str, " v%i", vA); strasm = r_str_concat (strasm, str); break; case fmtopvAcB: vA = buf[1] & 0x0f; vB = (buf[1] & 0xf0) >> 4; sprintf (str, " v%i, %#x", vA, vB); strasm = r_str_concat (strasm, str); break; case fmtopvAAcBBBB: vA = (int) buf[1]; { short sB = (buf[3] << 8) | buf[2]; sprintf (str, " v%i, %#04hx", vA, sB); strasm = r_str_concat (strasm, str); } break; case fmtopvAAcBBBBBBBB: vA = (int) buf[1]; vB = buf[2] | (buf[3] << 8) | (buf[4] << 16) | (buf[5] << 24); if (buf[0] == 0x17) { //const-wide/32 snprintf (str, sizeof (str), " v%i:v%i, 0x%08x", vA, vA + 1, vB); } else { //const snprintf (str, sizeof (str), " v%i, 0x%08x", vA, vB); } strasm = r_str_concat (strasm, str); break; case fmtopvAAcBBBB0000: vA = (int) buf[1]; vB = 0 | (buf[2] << 16) | (buf[3] << 24); if (buf[0] == 0x19) { // const-wide/high16 snprintf (str, sizeof (str), " v%i:v%i, 0x%08x", vA, vA + 1, vB); } else { snprintf (str, sizeof (str), " v%i, 0x%08x", vA, vB); } strasm = r_str_concat (strasm, str); break; case fmtopvAAcBBBBBBBBBBBBBBBB: vA = (int) buf[1]; #define llint long long int llint lB = (llint)buf[2] | ((llint)buf[3] << 8)| ((llint)buf[4] << 16) | ((llint)buf[5] << 24)| ((llint)buf[6] << 32) | ((llint)buf[7] << 40)| ((llint)buf[8] << 48) | ((llint)buf[9] << 56); #undef llint sprintf (str, " v%i:v%i, 0x%"PFMT64x, vA, vA + 1, lB); strasm = r_str_concat (strasm, str); break; case fmtopvAAvBBvCC: vA = (int) buf[1]; vB = (int) buf[2]; vC = (int) buf[3]; sprintf (str, " v%i, v%i, v%i", vA, vB, vC); strasm = r_str_concat (strasm, str); break; case fmtopvAAvBBcCC: vA = (int) buf[1]; vB = (int) buf[2]; vC = (int) buf[3]; sprintf (str, " v%i, v%i, %#x", vA, vB, vC); strasm = r_str_concat (strasm, str); break; case fmtopvAvBcCCCC: vA = buf[1] & 0x0f; vB = (buf[1] & 0xf0) >> 4; vC = (buf[3] << 8) | buf[2]; sprintf (str, " v%i, v%i, %#x", vA, vB, vC); strasm = r_str_concat (strasm, str); break; case fmtoppAA: vA = (char) buf[1]; snprintf (str, sizeof (str), " 0x%08"PFMT64x, a->pc + (vA * 2)); // vA : word -> byte strasm = r_str_concat (strasm, str); break; case fmtoppAAAA: vA = (short) (buf[3] << 8 | buf[2]); snprintf (str, sizeof (str), " 0x%08"PFMT64x, a->pc + (vA * 2)); // vA : word -> byte strasm = r_str_concat (strasm, str); break; case fmtopvAApBBBB: // if-*z vA = (int) buf[1]; vB = (int) (buf[3] << 8 | buf[2]); snprintf (str, sizeof (str), " v%i, 0x%08"PFMT64x, vA, a->pc + (vB * 2)); strasm = r_str_concat (strasm, str); break; case fmtoppAAAAAAAA: vA = (int) (buf[2] | (buf[3] << 8) | (buf[4] << 16) | (buf[5] << 24)); snprintf (str, sizeof (str), " 0x%08"PFMT64x, a->pc + (vA*2)); // vA : word -> byte strasm = r_str_concat (strasm, str); break; case fmtopvAvBpCCCC: // if-* vA = buf[1] & 0x0f; vB = (buf[1] & 0xf0) >> 4; vC = (int) (buf[3] << 8 | buf[2]); snprintf (str, sizeof (str)," v%i, v%i, 0x%08"PFMT64x, vA, vB, a->pc + (vC * 2)); strasm = r_str_concat (strasm, str); break; case fmtopvAApBBBBBBBB: vA = (int) buf[1]; vB = (int) (buf[2] | (buf[3] << 8) | (buf[4] << 16) | (buf[5] << 24)); snprintf (str, sizeof (str), " v%i, 0x%08"PFMT64x, vA, a->pc + vB); // + (vB*2)); strasm = r_str_concat (strasm, str); break; case fmtoptinlineI: vA = (int) (buf[1] & 0x0f); vB = (buf[3] << 8) | buf[2]; *str = 0; switch (vA) { case 1: sprintf (str, " {v%i}", buf[4] & 0x0f); break; case 2: sprintf (str, " {v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4); break; case 3: sprintf (str, " {v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f); break; case 4: sprintf (str, " {v%i, v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f, (buf[5] & 0xf0) >> 4); break; default: sprintf (str, " {}"); } strasm = r_str_concat (strasm, str); sprintf (str, ", [%04x]", vB); strasm = r_str_concat (strasm, str); break; case fmtoptinlineIR: case fmtoptinvokeVSR: vA = (int) buf[1]; vB = (buf[3] << 8) | buf[2]; vC = (buf[5] << 8) | buf[4]; sprintf (str, " {v%i..v%i}, [%04x]", vC, vC + vA - 1, vB); strasm = r_str_concat (strasm, str); break; case fmtoptinvokeVS: vA = (int) (buf[1] & 0xf0) >> 4; vB = (buf[3] << 8) | buf[2]; switch (vA) { case 1: sprintf (str, " {v%i}", buf[4] & 0x0f); break; case 2: sprintf (str, " {v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4); break; case 3: sprintf (str, " {v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f); break; case 4: sprintf (str, " {v%i, v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f, (buf[5] & 0xf0) >> 4); break; default: sprintf (str, " {}"); break; } strasm = r_str_concat (strasm, str); sprintf (str, ", [%04x]", vB); strasm = r_str_concat (strasm, str); break; case fmtopvAAtBBBB: // "sput-*" vA = (int) buf[1]; vB = (buf[3] << 8) | buf[2]; if (buf[0] == 0x1a) { offset = R_ASM_GET_OFFSET (a, 's', vB); if (offset == -1) { sprintf (str, " v%i, string+%i", vA, vB); } else { sprintf (str, " v%i, 0x%"PFMT64x, vA, offset); } } else if (buf[0] == 0x1c || buf[0] == 0x1f || buf[0] == 0x22) { flag_str = R_ASM_GET_NAME (a, 'c', vB); if (!flag_str) { sprintf (str, " v%i, class+%i", vA, vB); } else { sprintf (str, " v%i, %s", vA, flag_str); } } else { flag_str = R_ASM_GET_NAME (a, 'f', vB); if (!flag_str) { sprintf (str, " v%i, field+%i", vA, vB); } else { sprintf (str, " v%i, %s", vA, flag_str); } } strasm = r_str_concat (strasm, str); break; case fmtoptopvAvBoCCCC: vA = (buf[1] & 0x0f); vB = (buf[1] & 0xf0) >> 4; vC = (buf[3]<<8) | buf[2]; offset = R_ASM_GET_OFFSET (a, 'o', vC); if (offset == -1) { sprintf (str, " v%i, v%i, [obj+%04x]", vA, vB, vC); } else { sprintf (str, " v%i, v%i, [0x%"PFMT64x"]", vA, vB, offset); } strasm = r_str_concat (strasm, str); break; case fmtopAAtBBBB: vA = (int) buf[1]; vB = (buf[3] << 8) | buf[2]; offset = R_ASM_GET_OFFSET (a, 't', vB); if (offset == -1) { sprintf (str, " v%i, thing+%i", vA, vB); } else { sprintf (str, " v%i, 0x%"PFMT64x, vA, offset); } strasm = r_str_concat (strasm, str); break; case fmtopvAvBtCCCC: vA = (buf[1] & 0x0f); vB = (buf[1] & 0xf0) >> 4; vC = (buf[3] << 8) | buf[2]; if (buf[0] == 0x20 || buf[0] == 0x23) { //instance-of & new-array flag_str = R_ASM_GET_NAME (a, 'c', vC); if (flag_str) { sprintf (str, " v%i, v%i, %s", vA, vB, flag_str); } else { sprintf (str, " v%i, v%i, class+%i", vA, vB, vC); } } else { flag_str = R_ASM_GET_NAME (a, 'f', vC); if (flag_str) { sprintf (str, " v%i, v%i, %s", vA, vB, flag_str); } else { sprintf (str, " v%i, v%i, field+%i", vA, vB, vC); } } strasm = r_str_concat (strasm, str); break; case fmtopvAAtBBBBBBBB: vA = (int) buf[1]; vB = (int) (buf[5] | (buf[4] << 8) | (buf[3] << 16) | (buf[2] << 24)); offset = R_ASM_GET_OFFSET (a, 's', vB); if (offset == -1) { sprintf (str, " v%i, string+%i", vA, vB); } else { sprintf (str, " v%i, 0x%"PFMT64x, vA, offset); } strasm = r_str_concat (strasm, str); break; case fmtopvCCCCmBBBB: vA = (int) buf[1]; vB = (buf[3] << 8) | buf[2]; vC = (buf[5] << 8) | buf[4]; if (buf[0] == 0x25) { // filled-new-array/range flag_str = R_ASM_GET_NAME (a, 'c', vB); if (flag_str) { sprintf (str, " {v%i..v%i}, %s", vC, vC + vA - 1, flag_str); } else { sprintf (str, " {v%i..v%i}, class+%i", vC, vC + vA - 1, vB); } } else { flag_str = R_ASM_GET_NAME (a, 'm', vB); if (flag_str) { sprintf (str, " {v%i..v%i}, %s", vC, vC + vA - 1, flag_str); } else { sprintf (str, " {v%i..v%i}, method+%i", vC, vC + vA - 1, vB); } } strasm = r_str_concat (strasm, str); break; case fmtopvXtBBBB: vA = (int) (buf[1] & 0xf0) >> 4; vB = (buf[3] << 8) | buf[2]; switch (vA) { case 1: sprintf (str, " {v%i}", buf[4] & 0x0f); break; case 2: sprintf (str, " {v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4); break; case 3: sprintf (str, " {v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f); break; case 4: sprintf (str, " {v%i, v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f, (buf[5] & 0xf0) >> 4); break; case 5: sprintf (str, " {v%i, v%i, v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f, (buf[5] & 0xf0) >> 4, buf[1] & 0x0f); // TOODO: recheck this break; default: sprintf (str, " {}"); } strasm = r_str_concat (strasm, str); if (buf[0] == 0x24) { // filled-new-array flag_str = R_ASM_GET_NAME (a, 'c', vB); if (flag_str) { sprintf (str, ", %s ; 0x%x", flag_str, vB); } else { sprintf (str, ", class+%i", vB); } } else { flag_str = R_ASM_GET_NAME (a, 'm', vB); if (flag_str) { sprintf (str, ", %s ; 0x%x", flag_str, vB); } else { sprintf (str, ", method+%i", vB); } } strasm = r_str_concat (strasm, str); break; case fmtoptinvokeI: // Any opcode has this formats case fmtoptinvokeIR: case fmt00: default: strcpy (op->buf_asm, "invalid "); free (strasm); strasm = NULL; size = 2; } if (strasm) { strncpy (op->buf_asm, strasm, sizeof (op->buf_asm) - 1); op->buf_asm[sizeof (op->buf_asm) - 1] = 0; } else { strcpy (op->buf_asm , "invalid"); } } else if (len > 0) { strcpy (op->buf_asm, "invalid "); op->size = len; size = len; } op->payload = payload; size += payload; // XXX op->size = size; free (strasm); return size; } Commit Message: Fix #6885 - oob write in dalvik_disassemble CWE ID: CWE-119
static int dalvik_disassemble (RAsm *a, RAsmOp *op, const ut8 *buf, int len) { int vA, vB, vC, payload = 0, i = (int) buf[0]; int size = dalvik_opcodes[i].len; char str[1024], *strasm; ut64 offset; const char *flag_str; op->buf_asm[0] = 0; if (buf[0] == 0x00) { /* nop */ switch (buf[1]) { case 0x01: /* packed-switch-payload */ { unsigned short array_size = buf[2] | (buf[3] << 8); int first_key = buf[4] | (buf[5] << 8) | (buf[6] << 16) | (buf[7] << 24); snprintf (op->buf_asm, sizeof(op->buf_asm), "packed-switch-payload %d, %d", array_size, first_key); size = 8; payload = 2 * (array_size * 2); len = 0; } break; case 0x02: /* sparse-switch-payload */ { unsigned short array_size = buf[2] | (buf[3] << 8); snprintf (op->buf_asm, sizeof (op->buf_asm), "sparse-switch-payload %d", array_size); size = 4; payload = 2 * (array_size*4); len = 0; } break; case 0x03: /* fill-array-data-payload */ if (len > 7) { unsigned short elem_width = buf[2] | (buf[3] << 8); unsigned int array_size = buf[4] | (buf[5] << 8) | (buf[6] << 16) | (buf[7] << 24); snprintf (op->buf_asm, sizeof (op->buf_asm), "fill-array-data-payload %d, %d", elem_width, array_size); payload = 2 * ((array_size * elem_width+1)/2); } size = 8; len = 0; break; default: /* nop */ break; } } strasm = NULL; if (size <= len) { strncpy (op->buf_asm, dalvik_opcodes[i].name, sizeof (op->buf_asm) - 1); strasm = strdup (op->buf_asm); size = dalvik_opcodes[i].len; switch (dalvik_opcodes[i].fmt) { case fmtop: break; case fmtopvAvB: vA = buf[1] & 0x0f; vB = (buf[1] & 0xf0) >> 4; snprintf (str, sizeof (str), " v%i, v%i", vA, vB); strasm = r_str_concat (strasm, str); break; case fmtopvAAvBBBB: vA = (int) buf[1]; vB = (buf[3] << 8) | buf[2]; snprintf (str, sizeof (str), " v%i, v%i", vA, vB); strasm = r_str_concat (strasm, str); break; case fmtopvAAAAvBBBB: // buf[1] seems useless :/ vA = (buf[3] << 8) | buf[2]; vB = (buf[5] << 8) | buf[4]; snprintf (str, sizeof (str), " v%i, v%i", vA, vB); strasm = r_str_concat (strasm, str); break; case fmtopvAA: vA = (int) buf[1]; snprintf (str, sizeof (str), " v%i", vA); strasm = r_str_concat (strasm, str); break; case fmtopvAcB: vA = buf[1] & 0x0f; vB = (buf[1] & 0xf0) >> 4; snprintf (str, sizeof (str), " v%i, %#x", vA, vB); strasm = r_str_concat (strasm, str); break; case fmtopvAAcBBBB: vA = (int) buf[1]; { short sB = (buf[3] << 8) | buf[2]; snprintf (str, sizeof (str), " v%i, %#04hx", vA, sB); strasm = r_str_concat (strasm, str); } break; case fmtopvAAcBBBBBBBB: vA = (int) buf[1]; vB = buf[2] | (buf[3] << 8) | (buf[4] << 16) | (buf[5] << 24); if (buf[0] == 0x17) { //const-wide/32 snprintf (str, sizeof (str), " v%i:v%i, 0x%08x", vA, vA + 1, vB); } else { //const snprintf (str, sizeof (str), " v%i, 0x%08x", vA, vB); } strasm = r_str_concat (strasm, str); break; case fmtopvAAcBBBB0000: vA = (int) buf[1]; vB = 0 | (buf[2] << 16) | (buf[3] << 24); if (buf[0] == 0x19) { // const-wide/high16 snprintf (str, sizeof (str), " v%i:v%i, 0x%08x", vA, vA + 1, vB); } else { snprintf (str, sizeof (str), " v%i, 0x%08x", vA, vB); } strasm = r_str_concat (strasm, str); break; case fmtopvAAcBBBBBBBBBBBBBBBB: vA = (int) buf[1]; #define llint long long int llint lB = (llint)buf[2] | ((llint)buf[3] << 8)| ((llint)buf[4] << 16) | ((llint)buf[5] << 24)| ((llint)buf[6] << 32) | ((llint)buf[7] << 40)| ((llint)buf[8] << 48) | ((llint)buf[9] << 56); #undef llint snprintf (str, sizeof (str), " v%i:v%i, 0x%"PFMT64x, vA, vA + 1, lB); strasm = r_str_concat (strasm, str); break; case fmtopvAAvBBvCC: vA = (int) buf[1]; vB = (int) buf[2]; vC = (int) buf[3]; snprintf (str, sizeof (str), " v%i, v%i, v%i", vA, vB, vC); strasm = r_str_concat (strasm, str); break; case fmtopvAAvBBcCC: vA = (int) buf[1]; vB = (int) buf[2]; vC = (int) buf[3]; snprintf (str, sizeof (str), " v%i, v%i, %#x", vA, vB, vC); strasm = r_str_concat (strasm, str); break; case fmtopvAvBcCCCC: vA = buf[1] & 0x0f; vB = (buf[1] & 0xf0) >> 4; vC = (buf[3] << 8) | buf[2]; snprintf (str, sizeof (str), " v%i, v%i, %#x", vA, vB, vC); strasm = r_str_concat (strasm, str); break; case fmtoppAA: vA = (char) buf[1]; //snprintf (str, sizeof (str), " %i", vA*2); // vA : word -> byte snprintf (str, sizeof (str), " 0x%08"PFMT64x, a->pc + (vA * 2)); // vA : word -> byte strasm = r_str_concat (strasm, str); break; case fmtoppAAAA: vA = (short) (buf[3] << 8 | buf[2]); snprintf (str, sizeof (str), " 0x%08"PFMT64x, a->pc + (vA * 2)); // vA : word -> byte strasm = r_str_concat (strasm, str); break; case fmtopvAApBBBB: // if-*z vA = (int) buf[1]; vB = (int) (buf[3] << 8 | buf[2]); //snprintf (str, sizeof (str), " v%i, %i", vA, vB); snprintf (str, sizeof (str), " v%i, 0x%08"PFMT64x, vA, a->pc + (vB * 2)); strasm = r_str_concat (strasm, str); break; case fmtoppAAAAAAAA: vA = (int) (buf[2] | (buf[3] << 8) | (buf[4] << 16) | (buf[5] << 24)); //snprintf (str, sizeof (str), " %#08x", vA*2); // vA: word -> byte snprintf (str, sizeof (str), " 0x%08"PFMT64x, a->pc + (vA*2)); // vA : word -> byte strasm = r_str_concat (strasm, str); break; case fmtopvAvBpCCCC: // if-* vA = buf[1] & 0x0f; vB = (buf[1] & 0xf0) >> 4; vC = (int) (buf[3] << 8 | buf[2]); //snprintf (str, sizeof (str), " v%i, v%i, %i", vA, vB, vC); snprintf (str, sizeof (str)," v%i, v%i, 0x%08"PFMT64x, vA, vB, a->pc + (vC * 2)); strasm = r_str_concat (strasm, str); break; case fmtopvAApBBBBBBBB: vA = (int) buf[1]; vB = (int) (buf[2] | (buf[3] << 8) | (buf[4] << 16) | (buf[5] << 24)); snprintf (str, sizeof (str), " v%i, 0x%08"PFMT64x, vA, a->pc + vB); // + (vB*2)); strasm = r_str_concat (strasm, str); break; case fmtoptinlineI: vA = (int) (buf[1] & 0x0f); vB = (buf[3] << 8) | buf[2]; *str = 0; switch (vA) { case 1: snprintf (str, sizeof (str), " {v%i}", buf[4] & 0x0f); break; case 2: snprintf (str, sizeof (str), " {v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4); break; case 3: snprintf (str, sizeof (str), " {v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f); break; case 4: snprintf (str, sizeof (str), " {v%i, v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f, (buf[5] & 0xf0) >> 4); break; default: snprintf (str, sizeof (str), " {}"); } strasm = r_str_concat (strasm, str); snprintf (str, sizeof (str), ", [%04x]", vB); strasm = r_str_concat (strasm, str); break; case fmtoptinlineIR: case fmtoptinvokeVSR: vA = (int) buf[1]; vB = (buf[3] << 8) | buf[2]; vC = (buf[5] << 8) | buf[4]; snprintf (str, sizeof (str), " {v%i..v%i}, [%04x]", vC, vC + vA - 1, vB); strasm = r_str_concat (strasm, str); break; case fmtoptinvokeVS: vA = (int) (buf[1] & 0xf0) >> 4; vB = (buf[3] << 8) | buf[2]; switch (vA) { case 1: snprintf (str, sizeof (str), " {v%i}", buf[4] & 0x0f); break; case 2: snprintf (str, sizeof (str), " {v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4); break; case 3: snprintf (str, sizeof (str), " {v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f); break; case 4: snprintf (str, sizeof (str), " {v%i, v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f, (buf[5] & 0xf0) >> 4); break; default: snprintf (str, sizeof (str), " {}"); break; } strasm = r_str_concat (strasm, str); snprintf (str, sizeof (str), ", [%04x]", vB); strasm = r_str_concat (strasm, str); break; case fmtopvAAtBBBB: // "sput-*" vA = (int) buf[1]; vB = (buf[3] << 8) | buf[2]; if (buf[0] == 0x1a) { offset = R_ASM_GET_OFFSET (a, 's', vB); if (offset == -1) { snprintf (str, sizeof (str), " v%i, string+%i", vA, vB); } else { snprintf (str, sizeof (str), " v%i, 0x%"PFMT64x, vA, offset); } } else if (buf[0] == 0x1c || buf[0] == 0x1f || buf[0] == 0x22) { flag_str = R_ASM_GET_NAME (a, 'c', vB); if (!flag_str) { snprintf (str, sizeof (str), " v%i, class+%i", vA, vB); } else { snprintf (str, sizeof (str), " v%i, %s", vA, flag_str); } } else { flag_str = R_ASM_GET_NAME (a, 'f', vB); if (!flag_str) { snprintf (str, sizeof (str), " v%i, field+%i", vA, vB); } else { snprintf (str, sizeof (str), " v%i, %s", vA, flag_str); } } strasm = r_str_concat (strasm, str); break; case fmtoptopvAvBoCCCC: vA = (buf[1] & 0x0f); vB = (buf[1] & 0xf0) >> 4; vC = (buf[3]<<8) | buf[2]; offset = R_ASM_GET_OFFSET (a, 'o', vC); if (offset == -1) { snprintf (str, sizeof (str), " v%i, v%i, [obj+%04x]", vA, vB, vC); } else { snprintf (str, sizeof (str), " v%i, v%i, [0x%"PFMT64x"]", vA, vB, offset); } strasm = r_str_concat (strasm, str); break; case fmtopAAtBBBB: vA = (int) buf[1]; vB = (buf[3] << 8) | buf[2]; offset = R_ASM_GET_OFFSET (a, 't', vB); if (offset == -1) { snprintf (str, sizeof (str), " v%i, thing+%i", vA, vB); } else { snprintf (str, sizeof (str), " v%i, 0x%"PFMT64x, vA, offset); } strasm = r_str_concat (strasm, str); break; case fmtopvAvBtCCCC: vA = (buf[1] & 0x0f); vB = (buf[1] & 0xf0) >> 4; vC = (buf[3] << 8) | buf[2]; if (buf[0] == 0x20 || buf[0] == 0x23) { //instance-of & new-array flag_str = R_ASM_GET_NAME (a, 'c', vC); if (flag_str) { snprintf (str, sizeof (str), " v%i, v%i, %s", vA, vB, flag_str); } else { snprintf (str, sizeof (str), " v%i, v%i, class+%i", vA, vB, vC); } } else { flag_str = R_ASM_GET_NAME (a, 'f', vC); if (flag_str) { snprintf (str, sizeof (str), " v%i, v%i, %s", vA, vB, flag_str); } else { snprintf (str, sizeof (str), " v%i, v%i, field+%i", vA, vB, vC); } } strasm = r_str_concat (strasm, str); break; case fmtopvAAtBBBBBBBB: vA = (int) buf[1]; vB = (int) (buf[5] | (buf[4] << 8) | (buf[3] << 16) | (buf[2] << 24)); offset = R_ASM_GET_OFFSET (a, 's', vB); if (offset == -1) { snprintf (str, sizeof (str), " v%i, string+%i", vA, vB); } else { snprintf (str, sizeof (str), " v%i, 0x%"PFMT64x, vA, offset); } strasm = r_str_concat (strasm, str); break; case fmtopvCCCCmBBBB: vA = (int) buf[1]; vB = (buf[3] << 8) | buf[2]; vC = (buf[5] << 8) | buf[4]; if (buf[0] == 0x25) { // filled-new-array/range flag_str = R_ASM_GET_NAME (a, 'c', vB); if (flag_str) { snprintf (str, sizeof (str), " {v%i..v%i}, %s", vC, vC + vA - 1, flag_str); } else { snprintf (str, sizeof (str), " {v%i..v%i}, class+%i", vC, vC + vA - 1, vB); } } else { flag_str = R_ASM_GET_NAME (a, 'm', vB); if (flag_str) { snprintf (str, sizeof (str), " {v%i..v%i}, %s", vC, vC + vA - 1, flag_str); } else { snprintf (str, sizeof (str), " {v%i..v%i}, method+%i", vC, vC + vA - 1, vB); } } strasm = r_str_concat (strasm, str); break; case fmtopvXtBBBB: vA = (int) (buf[1] & 0xf0) >> 4; vB = (buf[3] << 8) | buf[2]; switch (vA) { case 1: snprintf (str, sizeof (str), " {v%i}", buf[4] & 0x0f); break; case 2: snprintf (str, sizeof (str), " {v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4); break; case 3: snprintf (str, sizeof (str), " {v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f); break; case 4: snprintf (str, sizeof (str), " {v%i, v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f, (buf[5] & 0xf0) >> 4); break; case 5: snprintf (str, sizeof (str), " {v%i, v%i, v%i, v%i, v%i}", buf[4] & 0x0f, (buf[4] & 0xf0) >> 4, buf[5] & 0x0f, (buf[5] & 0xf0) >> 4, buf[1] & 0x0f); // TOODO: recheck this break; default: snprintf (str, sizeof (str), " {}"); } strasm = r_str_concat (strasm, str); if (buf[0] == 0x24) { // filled-new-array flag_str = R_ASM_GET_NAME (a, 'c', vB); if (flag_str) { snprintf (str, sizeof (str), ", %s ; 0x%x", flag_str, vB); } else { snprintf (str, sizeof (str), ", class+%i", vB); } } else { flag_str = R_ASM_GET_NAME (a, 'm', vB); if (flag_str) { snprintf (str, sizeof (str), ", %s ; 0x%x", flag_str, vB); } else { snprintf (str, sizeof (str), ", method+%i", vB); } } strasm = r_str_concat (strasm, str); break; case fmtoptinvokeI: // Any opcode has this formats case fmtoptinvokeIR: case fmt00: default: strcpy (op->buf_asm, "invalid "); free (strasm); strasm = NULL; size = 2; } if (strasm) { strncpy (op->buf_asm, strasm, sizeof (op->buf_asm) - 1); op->buf_asm[sizeof (op->buf_asm) - 1] = 0; } else { strcpy (op->buf_asm , "invalid"); } } else if (len > 0) { strcpy (op->buf_asm, "invalid "); op->size = len; size = len; } op->payload = payload; size += payload; // XXX op->size = size; free (strasm); return size; }
168,333
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tmsize_t wc = cc / bps; tmsize_t count; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); if((cc%(bps*stride))!=0) { TIFFErrorExt(tif->tif_clientdata, "fpDiff", "%s", "(cc%(bps*stride))!=0"); return 0; } if (!tmp) return 0; _TIFFmemcpy(tmp, cp0, cc); for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[byte * wc + count] = tmp[bps * count + byte]; #else cp[(bps - byte - 1) * wc + count] = tmp[bps * count + byte]; #endif } } _TIFFfree(tmp); cp = (uint8 *) cp0; cp += cc - stride - 1; for (count = cc; count > stride; count -= stride) REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--) return 1; } Commit Message: * libtiff/tif_predic.c: fix memory leaks in error code paths added in previous commit (fix for MSVR 35105) CWE ID: CWE-119
fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tmsize_t wc = cc / bps; tmsize_t count; uint8 *cp = (uint8 *) cp0; uint8 *tmp; if((cc%(bps*stride))!=0) { TIFFErrorExt(tif->tif_clientdata, "fpDiff", "%s", "(cc%(bps*stride))!=0"); return 0; } tmp = (uint8 *)_TIFFmalloc(cc); if (!tmp) return 0; _TIFFmemcpy(tmp, cp0, cc); for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[byte * wc + count] = tmp[bps * count + byte]; #else cp[(bps - byte - 1) * wc + count] = tmp[bps * count + byte]; #endif } } _TIFFfree(tmp); cp = (uint8 *) cp0; cp += cc - stride - 1; for (count = cc; count > stride; count -= stride) REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--) return 1; }
169,939
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int _php_curl_setopt(php_curl *ch, zend_long option, zval *zvalue) /* {{{ */ { CURLcode error = CURLE_OK; switch (option) { /* Long options */ case CURLOPT_SSL_VERIFYHOST: convert_to_long(zvalue); if (Z_LVAL_P(zvalue) == 1) { #if LIBCURL_VERSION_NUM <= 0x071c00 /* 7.28.0 */ php_error_docref(NULL, E_NOTICE, "CURLOPT_SSL_VERIFYHOST with value 1 is deprecated and will be removed as of libcurl 7.28.1. It is recommended to use value 2 instead"); #else php_error_docref(NULL, E_NOTICE, "CURLOPT_SSL_VERIFYHOST no longer accepts the value 1, value 2 will be used instead"); error = curl_easy_setopt(ch->cp, option, 2); break; #endif } case CURLOPT_AUTOREFERER: case CURLOPT_BUFFERSIZE: case CURLOPT_CONNECTTIMEOUT: case CURLOPT_COOKIESESSION: case CURLOPT_CRLF: case CURLOPT_DNS_CACHE_TIMEOUT: case CURLOPT_DNS_USE_GLOBAL_CACHE: case CURLOPT_FAILONERROR: case CURLOPT_FILETIME: case CURLOPT_FORBID_REUSE: case CURLOPT_FRESH_CONNECT: case CURLOPT_FTP_USE_EPRT: case CURLOPT_FTP_USE_EPSV: case CURLOPT_HEADER: case CURLOPT_HTTPGET: case CURLOPT_HTTPPROXYTUNNEL: case CURLOPT_HTTP_VERSION: case CURLOPT_INFILESIZE: case CURLOPT_LOW_SPEED_LIMIT: case CURLOPT_LOW_SPEED_TIME: case CURLOPT_MAXCONNECTS: case CURLOPT_MAXREDIRS: case CURLOPT_NETRC: case CURLOPT_NOBODY: case CURLOPT_NOPROGRESS: case CURLOPT_NOSIGNAL: case CURLOPT_PORT: case CURLOPT_POST: case CURLOPT_PROXYPORT: case CURLOPT_PROXYTYPE: case CURLOPT_PUT: case CURLOPT_RESUME_FROM: case CURLOPT_SSLVERSION: case CURLOPT_SSL_VERIFYPEER: case CURLOPT_TIMECONDITION: case CURLOPT_TIMEOUT: case CURLOPT_TIMEVALUE: case CURLOPT_TRANSFERTEXT: case CURLOPT_UNRESTRICTED_AUTH: case CURLOPT_UPLOAD: case CURLOPT_VERBOSE: #if LIBCURL_VERSION_NUM >= 0x070a06 /* Available since 7.10.6 */ case CURLOPT_HTTPAUTH: #endif #if LIBCURL_VERSION_NUM >= 0x070a07 /* Available since 7.10.7 */ case CURLOPT_FTP_CREATE_MISSING_DIRS: case CURLOPT_PROXYAUTH: #endif #if LIBCURL_VERSION_NUM >= 0x070a08 /* Available since 7.10.8 */ case CURLOPT_FTP_RESPONSE_TIMEOUT: case CURLOPT_IPRESOLVE: case CURLOPT_MAXFILESIZE: #endif #if LIBCURL_VERSION_NUM >= 0x070b02 /* Available since 7.11.2 */ case CURLOPT_TCP_NODELAY: #endif #if LIBCURL_VERSION_NUM >= 0x070c02 /* Available since 7.12.2 */ case CURLOPT_FTPSSLAUTH: #endif #if LIBCURL_VERSION_NUM >= 0x070e01 /* Available since 7.14.1 */ case CURLOPT_IGNORE_CONTENT_LENGTH: #endif #if LIBCURL_VERSION_NUM >= 0x070f00 /* Available since 7.15.0 */ case CURLOPT_FTP_SKIP_PASV_IP: #endif #if LIBCURL_VERSION_NUM >= 0x070f01 /* Available since 7.15.1 */ case CURLOPT_FTP_FILEMETHOD: #endif #if LIBCURL_VERSION_NUM >= 0x070f02 /* Available since 7.15.2 */ case CURLOPT_CONNECT_ONLY: case CURLOPT_LOCALPORT: case CURLOPT_LOCALPORTRANGE: #endif #if LIBCURL_VERSION_NUM >= 0x071000 /* Available since 7.16.0 */ case CURLOPT_SSL_SESSIONID_CACHE: #endif #if LIBCURL_VERSION_NUM >= 0x071001 /* Available since 7.16.1 */ case CURLOPT_FTP_SSL_CCC: case CURLOPT_SSH_AUTH_TYPES: #endif #if LIBCURL_VERSION_NUM >= 0x071002 /* Available since 7.16.2 */ case CURLOPT_CONNECTTIMEOUT_MS: case CURLOPT_HTTP_CONTENT_DECODING: case CURLOPT_HTTP_TRANSFER_DECODING: case CURLOPT_TIMEOUT_MS: #endif #if LIBCURL_VERSION_NUM >= 0x071004 /* Available since 7.16.4 */ case CURLOPT_NEW_DIRECTORY_PERMS: case CURLOPT_NEW_FILE_PERMS: #endif #if LIBCURL_VERSION_NUM >= 0x071100 /* Available since 7.17.0 */ case CURLOPT_USE_SSL: #elif LIBCURL_VERSION_NUM >= 0x070b00 /* Available since 7.11.0 */ case CURLOPT_FTP_SSL: #endif #if LIBCURL_VERSION_NUM >= 0x071100 /* Available since 7.17.0 */ case CURLOPT_APPEND: case CURLOPT_DIRLISTONLY: #else case CURLOPT_FTPAPPEND: case CURLOPT_FTPLISTONLY: #endif #if LIBCURL_VERSION_NUM >= 0x071200 /* Available since 7.18.0 */ case CURLOPT_PROXY_TRANSFER_MODE: #endif #if LIBCURL_VERSION_NUM >= 0x071300 /* Available since 7.19.0 */ case CURLOPT_ADDRESS_SCOPE: #endif #if LIBCURL_VERSION_NUM > 0x071301 /* Available since 7.19.1 */ case CURLOPT_CERTINFO: #endif #if LIBCURL_VERSION_NUM >= 0x071304 /* Available since 7.19.4 */ case CURLOPT_NOPROXY: case CURLOPT_PROTOCOLS: case CURLOPT_REDIR_PROTOCOLS: case CURLOPT_SOCKS5_GSSAPI_NEC: case CURLOPT_TFTP_BLKSIZE: #endif #if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */ case CURLOPT_FTP_USE_PRET: case CURLOPT_RTSP_CLIENT_CSEQ: case CURLOPT_RTSP_REQUEST: case CURLOPT_RTSP_SERVER_CSEQ: #endif #if LIBCURL_VERSION_NUM >= 0x071500 /* Available since 7.21.0 */ case CURLOPT_WILDCARDMATCH: #endif #if LIBCURL_VERSION_NUM >= 0x071504 /* Available since 7.21.4 */ case CURLOPT_TLSAUTH_TYPE: #endif #if LIBCURL_VERSION_NUM >= 0x071600 /* Available since 7.22.0 */ case CURLOPT_GSSAPI_DELEGATION: #endif #if LIBCURL_VERSION_NUM >= 0x071800 /* Available since 7.24.0 */ case CURLOPT_ACCEPTTIMEOUT_MS: #endif #if LIBCURL_VERSION_NUM >= 0x071900 /* Available since 7.25.0 */ case CURLOPT_SSL_OPTIONS: case CURLOPT_TCP_KEEPALIVE: case CURLOPT_TCP_KEEPIDLE: case CURLOPT_TCP_KEEPINTVL: #endif #if CURLOPT_MUTE != 0 case CURLOPT_MUTE: #endif convert_to_long_ex(zvalue); #if LIBCURL_VERSION_NUM >= 0x71304 if ((option == CURLOPT_PROTOCOLS || option == CURLOPT_REDIR_PROTOCOLS) && (PG(open_basedir) && *PG(open_basedir)) && (Z_LVAL_P(zvalue) & CURLPROTO_FILE)) { php_error_docref(NULL, E_WARNING, "CURLPROTO_FILE cannot be activated when an open_basedir is set"); return 1; } #endif error = curl_easy_setopt(ch->cp, option, Z_LVAL_P(zvalue)); break; case CURLOPT_SAFE_UPLOAD: convert_to_long_ex(zvalue); ch->safe_upload = (Z_LVAL_P(zvalue) != 0); break; /* String options */ case CURLOPT_CAINFO: case CURLOPT_CAPATH: case CURLOPT_COOKIE: case CURLOPT_EGDSOCKET: case CURLOPT_INTERFACE: case CURLOPT_PROXY: case CURLOPT_PROXYUSERPWD: case CURLOPT_REFERER: case CURLOPT_SSLCERTTYPE: case CURLOPT_SSLENGINE: case CURLOPT_SSLENGINE_DEFAULT: case CURLOPT_SSLKEY: case CURLOPT_SSLKEYPASSWD: case CURLOPT_SSLKEYTYPE: case CURLOPT_SSL_CIPHER_LIST: case CURLOPT_USERAGENT: case CURLOPT_USERPWD: #if LIBCURL_VERSION_NUM >= 0x070e01 /* Available since 7.14.1 */ case CURLOPT_COOKIELIST: #endif #if LIBCURL_VERSION_NUM >= 0x070f05 /* Available since 7.15.5 */ case CURLOPT_FTP_ALTERNATIVE_TO_USER: #endif #if LIBCURL_VERSION_NUM >= 0x071101 /* Available since 7.17.1 */ case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5: #endif #if LIBCURL_VERSION_NUM >= 0x071301 /* Available since 7.19.1 */ case CURLOPT_PASSWORD: case CURLOPT_PROXYPASSWORD: case CURLOPT_PROXYUSERNAME: case CURLOPT_USERNAME: #endif #if LIBCURL_VERSION_NUM >= 0x071304 /* Available since 7.19.4 */ case CURLOPT_SOCKS5_GSSAPI_SERVICE: #endif #if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */ case CURLOPT_MAIL_FROM: case CURLOPT_RTSP_STREAM_URI: case CURLOPT_RTSP_TRANSPORT: #endif #if LIBCURL_VERSION_NUM >= 0x071504 /* Available since 7.21.4 */ case CURLOPT_TLSAUTH_PASSWORD: case CURLOPT_TLSAUTH_USERNAME: #endif #if LIBCURL_VERSION_NUM >= 0x071506 /* Available since 7.21.6 */ case CURLOPT_ACCEPT_ENCODING: case CURLOPT_TRANSFER_ENCODING: #else case CURLOPT_ENCODING: #endif #if LIBCURL_VERSION_NUM >= 0x071800 /* Available since 7.24.0 */ case CURLOPT_DNS_SERVERS: #endif #if LIBCURL_VERSION_NUM >= 0x071900 /* Available since 7.25.0 */ case CURLOPT_MAIL_AUTH: #endif { convert_to_string_ex(zvalue); return php_curl_option_str(ch, option, Z_STRVAL_P(zvalue), Z_STRLEN_P(zvalue), 0); } /* Curl nullable string options */ case CURLOPT_CUSTOMREQUEST: case CURLOPT_FTPPORT: case CURLOPT_RANGE: #if LIBCURL_VERSION_NUM >= 0x070d00 /* Available since 7.13.0 */ case CURLOPT_FTP_ACCOUNT: #endif #if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */ case CURLOPT_RTSP_SESSION_ID: #endif #if LIBCURL_VERSION_NUM >= 0x071004 /* Available since 7.16.4 */ case CURLOPT_KRBLEVEL: #else case CURLOPT_KRB4LEVEL: #endif { if (Z_ISNULL_P(zvalue)) { error = curl_easy_setopt(ch->cp, option, NULL); } else { convert_to_string_ex(zvalue); return php_curl_option_str(ch, option, Z_STRVAL_P(zvalue), Z_STRLEN_P(zvalue), 0); } break; } /* Curl private option */ case CURLOPT_PRIVATE: convert_to_string_ex(zvalue); return php_curl_option_str(ch, option, Z_STRVAL_P(zvalue), Z_STRLEN_P(zvalue), 1); /* Curl url option */ case CURLOPT_URL: convert_to_string_ex(zvalue); return php_curl_option_url(ch, Z_STRVAL_P(zvalue), Z_STRLEN_P(zvalue)); /* Curl file handle options */ case CURLOPT_FILE: case CURLOPT_INFILE: case CURLOPT_STDERR: case CURLOPT_WRITEHEADER: { FILE *fp = NULL; int type; php_stream *what = NULL; if (Z_TYPE_P(zvalue) != IS_NULL) { what = zend_fetch_resource(zvalue, -1, "File-Handle", &type, 1, php_file_le_stream(), php_file_le_pstream()); if (!what) { return FAILURE; } if (FAILURE == php_stream_cast(what, PHP_STREAM_AS_STDIO, (void *) &fp, REPORT_ERRORS)) { return FAILURE; } if (!fp) { return FAILURE; } } error = CURLE_OK; switch (option) { case CURLOPT_FILE: if (!what) { if (!Z_ISUNDEF(ch->handlers->write->stream)) { zval_ptr_dtor(&ch->handlers->write->stream); ZVAL_UNDEF(&ch->handlers->write->stream); } ch->handlers->write->fp = NULL; ch->handlers->write->method = PHP_CURL_STDOUT; } else if (what->mode[0] != 'r' || what->mode[1] == '+') { zval_ptr_dtor(&ch->handlers->write->stream); ch->handlers->write->fp = fp; ch->handlers->write->method = PHP_CURL_FILE; ZVAL_COPY(&ch->handlers->write->stream, zvalue); } else { php_error_docref(NULL, E_WARNING, "the provided file handle is not writable"); return FAILURE; } break; case CURLOPT_WRITEHEADER: if (!what) { if (!Z_ISUNDEF(ch->handlers->write_header->stream)) { zval_ptr_dtor(&ch->handlers->write_header->stream); ZVAL_UNDEF(&ch->handlers->write_header->stream); } ch->handlers->write_header->fp = NULL; ch->handlers->write_header->method = PHP_CURL_IGNORE; } else if (what->mode[0] != 'r' || what->mode[1] == '+') { zval_ptr_dtor(&ch->handlers->write_header->stream); ch->handlers->write_header->fp = fp; ch->handlers->write_header->method = PHP_CURL_FILE; ZVAL_COPY(&ch->handlers->write_header->stream, zvalue);; } else { php_error_docref(NULL, E_WARNING, "the provided file handle is not writable"); return FAILURE; } break; case CURLOPT_INFILE: if (!what) { if (!Z_ISUNDEF(ch->handlers->read->stream)) { zval_ptr_dtor(&ch->handlers->read->stream); ZVAL_UNDEF(&ch->handlers->read->stream); } ch->handlers->read->fp = NULL; ch->handlers->read->res = NULL; } else { zval_ptr_dtor(&ch->handlers->read->stream); ch->handlers->read->fp = fp; ch->handlers->read->res = Z_RES_P(zvalue); ZVAL_COPY(&ch->handlers->read->stream, zvalue); } break; case CURLOPT_STDERR: if (!what) { if (!Z_ISUNDEF(ch->handlers->std_err)) { zval_ptr_dtor(&ch->handlers->std_err); ZVAL_UNDEF(&ch->handlers->std_err); } } else if (what->mode[0] != 'r' || what->mode[1] == '+') { zval_ptr_dtor(&ch->handlers->std_err); ZVAL_COPY(&ch->handlers->std_err, zvalue); } else { php_error_docref(NULL, E_WARNING, "the provided file handle is not writable"); return FAILURE; } /* break omitted intentionally */ default: error = curl_easy_setopt(ch->cp, option, fp); break; } break; } /* Curl linked list options */ case CURLOPT_HTTP200ALIASES: case CURLOPT_HTTPHEADER: case CURLOPT_POSTQUOTE: case CURLOPT_PREQUOTE: case CURLOPT_QUOTE: case CURLOPT_TELNETOPTIONS: #if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */ case CURLOPT_MAIL_RCPT: #endif #if LIBCURL_VERSION_NUM >= 0x071503 /* Available since 7.21.3 */ case CURLOPT_RESOLVE: #endif { zval *current; HashTable *ph; struct curl_slist *slist = NULL; ph = HASH_OF(zvalue); if (!ph) { char *name = NULL; switch (option) { case CURLOPT_HTTPHEADER: name = "CURLOPT_HTTPHEADER"; break; case CURLOPT_QUOTE: name = "CURLOPT_QUOTE"; break; case CURLOPT_HTTP200ALIASES: name = "CURLOPT_HTTP200ALIASES"; break; case CURLOPT_POSTQUOTE: name = "CURLOPT_POSTQUOTE"; break; case CURLOPT_PREQUOTE: name = "CURLOPT_PREQUOTE"; break; case CURLOPT_TELNETOPTIONS: name = "CURLOPT_TELNETOPTIONS"; break; #if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */ case CURLOPT_MAIL_RCPT: name = "CURLOPT_MAIL_RCPT"; break; #endif #if LIBCURL_VERSION_NUM >= 0x071503 /* Available since 7.21.3 */ case CURLOPT_RESOLVE: name = "CURLOPT_RESOLVE"; break; #endif } php_error_docref(NULL, E_WARNING, "You must pass either an object or an array with the %s argument", name); return FAILURE; } ZEND_HASH_FOREACH_VAL(ph, current) { SEPARATE_ZVAL(current); convert_to_string_ex(current); slist = curl_slist_append(slist, Z_STRVAL_P(current)); if (!slist) { php_error_docref(NULL, E_WARNING, "Could not build curl_slist"); return 1; } } ZEND_HASH_FOREACH_END(); zend_hash_index_update_ptr(ch->to_free->slist, option, slist); error = curl_easy_setopt(ch->cp, option, slist); break; } case CURLOPT_BINARYTRANSFER: /* Do nothing, just backward compatibility */ break; case CURLOPT_FOLLOWLOCATION: convert_to_long_ex(zvalue); #if LIBCURL_VERSION_NUM < 0x071304 if (PG(open_basedir) && *PG(open_basedir)) { if (Z_LVAL_P(zvalue) != 0) { php_error_docref(NULL, E_WARNING, "CURLOPT_FOLLOWLOCATION cannot be activated when an open_basedir is set"); return FAILURE; } } #endif error = curl_easy_setopt(ch->cp, option, Z_LVAL_P(zvalue)); break; case CURLOPT_HEADERFUNCTION: if (!Z_ISUNDEF(ch->handlers->write_header->func_name)) { zval_ptr_dtor(&ch->handlers->write_header->func_name); ch->handlers->write_header->fci_cache = empty_fcall_info_cache; } ZVAL_COPY(&ch->handlers->write_header->func_name, zvalue); ch->handlers->write_header->method = PHP_CURL_USER; break; case CURLOPT_POSTFIELDS: if (Z_TYPE_P(zvalue) == IS_ARRAY || Z_TYPE_P(zvalue) == IS_OBJECT) { zval *current; HashTable *postfields; zend_string *string_key; zend_ulong num_key; struct HttpPost *first = NULL; struct HttpPost *last = NULL; postfields = HASH_OF(zvalue); if (!postfields) { php_error_docref(NULL, E_WARNING, "Couldn't get HashTable in CURLOPT_POSTFIELDS"); return FAILURE; } ZEND_HASH_FOREACH_KEY_VAL(postfields, num_key, string_key, current) { char *postval; /* Pretend we have a string_key here */ if (!string_key) { string_key = zend_long_to_str(num_key); } else { zend_string_addref(string_key); } if (Z_TYPE_P(current) == IS_OBJECT && instanceof_function(Z_OBJCE_P(current), curl_CURLFile_class)) { /* new-style file upload */ zval *prop; char *type = NULL, *filename = NULL; prop = zend_read_property(curl_CURLFile_class, current, "name", sizeof("name")-1, 0); if (Z_TYPE_P(prop) != IS_STRING) { php_error_docref(NULL, E_WARNING, "Invalid filename for key %s", string_key->val); } else { postval = Z_STRVAL_P(prop); if (php_check_open_basedir(postval)) { return 1; } prop = zend_read_property(curl_CURLFile_class, current, "mime", sizeof("mime")-1, 0); if (Z_TYPE_P(prop) == IS_STRING && Z_STRLEN_P(prop) > 0) { type = Z_STRVAL_P(prop); } prop = zend_read_property(curl_CURLFile_class, current, "postname", sizeof("postname")-1, 0); if (Z_TYPE_P(prop) == IS_STRING && Z_STRLEN_P(prop) > 0) { filename = Z_STRVAL_P(prop); } error = curl_formadd(&first, &last, CURLFORM_COPYNAME, string_key->val, CURLFORM_NAMELENGTH, string_key->len, CURLFORM_FILENAME, filename ? filename : postval, CURLFORM_CONTENTTYPE, type ? type : "application/octet-stream", CURLFORM_FILE, postval, CURLFORM_END); } zend_string_release(string_key); continue; } SEPARATE_ZVAL(current); convert_to_string_ex(current); postval = Z_STRVAL_P(current); /* The arguments after _NAMELENGTH and _CONTENTSLENGTH * must be explicitly cast to long in curl_formadd * use since curl needs a long not an int. */ if (!ch->safe_upload && *postval == '@') { char *name, *type, *filename; ++postval; php_error_docref("curl.curlfile", E_DEPRECATED, "The usage of the @filename API for file uploading is deprecated. Please use the CURLFile class instead"); name = estrndup(postval, Z_STRLEN_P(current)); if ((type = (char *)php_memnstr(name, ";type=", sizeof(";type=") - 1, name + Z_STRLEN_P(current)))) { *type = '\0'; } if ((filename = (char *)php_memnstr(name, ";filename=", sizeof(";filename=") - 1, name + Z_STRLEN_P(current)))) { *filename = '\0'; } /* open_basedir check */ if (php_check_open_basedir(name)) { efree(name); return FAILURE; } error = curl_formadd(&first, &last, CURLFORM_COPYNAME, string_key->val, CURLFORM_NAMELENGTH, string_key->len, CURLFORM_FILENAME, filename ? filename + sizeof(";filename=") - 1 : name, CURLFORM_CONTENTTYPE, type ? type + sizeof(";type=") - 1 : "application/octet-stream", CURLFORM_FILE, name, CURLFORM_END); efree(name); } else { error = curl_formadd(&first, &last, CURLFORM_COPYNAME, string_key->val, CURLFORM_NAMELENGTH, (zend_long)string_key->len, CURLFORM_COPYCONTENTS, postval, CURLFORM_CONTENTSLENGTH, (zend_long)Z_STRLEN_P(current), CURLFORM_END); } zend_string_release(string_key); } ZEND_HASH_FOREACH_END(); SAVE_CURL_ERROR(ch, error); if (error != CURLE_OK) { return FAILURE; } if (ch->clone == 0) { zend_llist_clean(&ch->to_free->post); } zend_llist_add_element(&ch->to_free->post, &first); error = curl_easy_setopt(ch->cp, CURLOPT_HTTPPOST, first); } else { #if LIBCURL_VERSION_NUM >= 0x071101 convert_to_string_ex(zvalue); /* with curl 7.17.0 and later, we can use COPYPOSTFIELDS, but we have to provide size before */ error = curl_easy_setopt(ch->cp, CURLOPT_POSTFIELDSIZE, Z_STRLEN_P(zvalue)); error = curl_easy_setopt(ch->cp, CURLOPT_COPYPOSTFIELDS, Z_STRVAL_P(zvalue)); #else char *post = NULL; convert_to_string_ex(zvalue); post = estrndup(Z_STRVAL_P(zvalue), Z_STRLEN_P(zvalue)); zend_llist_add_element(&ch->to_free->str, &post); curl_easy_setopt(ch->cp, CURLOPT_POSTFIELDS, post); error = curl_easy_setopt(ch->cp, CURLOPT_POSTFIELDSIZE, Z_STRLEN_P(zvalue)); #endif } break; case CURLOPT_PROGRESSFUNCTION: curl_easy_setopt(ch->cp, CURLOPT_PROGRESSFUNCTION, curl_progress); curl_easy_setopt(ch->cp, CURLOPT_PROGRESSDATA, ch); if (ch->handlers->progress == NULL) { ch->handlers->progress = ecalloc(1, sizeof(php_curl_progress)); } else if (!Z_ISUNDEF(ch->handlers->progress->func_name)) { zval_ptr_dtor(&ch->handlers->progress->func_name); ch->handlers->progress->fci_cache = empty_fcall_info_cache; } ZVAL_COPY(&ch->handlers->progress->func_name, zvalue); ch->handlers->progress->method = PHP_CURL_USER; break; case CURLOPT_READFUNCTION: if (!Z_ISUNDEF(ch->handlers->read->func_name)) { zval_ptr_dtor(&ch->handlers->read->func_name); ch->handlers->read->fci_cache = empty_fcall_info_cache; } ZVAL_COPY(&ch->handlers->read->func_name, zvalue); ch->handlers->read->method = PHP_CURL_USER; break; case CURLOPT_RETURNTRANSFER: convert_to_long_ex(zvalue); if (Z_LVAL_P(zvalue)) { ch->handlers->write->method = PHP_CURL_RETURN; } else { ch->handlers->write->method = PHP_CURL_STDOUT; } break; case CURLOPT_WRITEFUNCTION: if (!Z_ISUNDEF(ch->handlers->write->func_name)) { zval_ptr_dtor(&ch->handlers->write->func_name); ch->handlers->write->fci_cache = empty_fcall_info_cache; } ZVAL_COPY(&ch->handlers->write->func_name, zvalue); ch->handlers->write->method = PHP_CURL_USER; break; #if LIBCURL_VERSION_NUM >= 0x070f05 /* Available since 7.15.5 */ case CURLOPT_MAX_RECV_SPEED_LARGE: case CURLOPT_MAX_SEND_SPEED_LARGE: convert_to_long_ex(zvalue); error = curl_easy_setopt(ch->cp, option, (curl_off_t)Z_LVAL_P(zvalue)); break; #endif #if LIBCURL_VERSION_NUM >= 0x071301 /* Available since 7.19.1 */ case CURLOPT_POSTREDIR: convert_to_long_ex(zvalue); error = curl_easy_setopt(ch->cp, CURLOPT_POSTREDIR, Z_LVAL_P(zvalue) & CURL_REDIR_POST_ALL); break; #endif #if CURLOPT_PASSWDFUNCTION != 0 case CURLOPT_PASSWDFUNCTION: zval_ptr_dtor(&ch->handlers->passwd); ZVAL_COPY(&ch->handlers->passwd, zvalue); error = curl_easy_setopt(ch->cp, CURLOPT_PASSWDFUNCTION, curl_passwd); error = curl_easy_setopt(ch->cp, CURLOPT_PASSWDDATA, (void *) ch); break; #endif /* the following options deal with files, therefore the open_basedir check * is required. */ case CURLOPT_COOKIEFILE: case CURLOPT_COOKIEJAR: case CURLOPT_RANDOM_FILE: case CURLOPT_SSLCERT: #if LIBCURL_VERSION_NUM >= 0x070b00 /* Available since 7.11.0 */ case CURLOPT_NETRC_FILE: #endif #if LIBCURL_VERSION_NUM >= 0x071001 /* Available since 7.16.1 */ case CURLOPT_SSH_PRIVATE_KEYFILE: case CURLOPT_SSH_PUBLIC_KEYFILE: #endif #if LIBCURL_VERSION_NUM >= 0x071300 /* Available since 7.19.0 */ case CURLOPT_CRLFILE: case CURLOPT_ISSUERCERT: #endif #if LIBCURL_VERSION_NUM >= 0x071306 /* Available since 7.19.6 */ case CURLOPT_SSH_KNOWNHOSTS: #endif { convert_to_string_ex(zvalue); if (Z_STRLEN_P(zvalue) && php_check_open_basedir(Z_STRVAL_P(zvalue))) { return FAILURE; } return php_curl_option_str(ch, option, Z_STRVAL_P(zvalue), Z_STRLEN_P(zvalue), 0); } case CURLINFO_HEADER_OUT: convert_to_long_ex(zvalue); if (Z_LVAL_P(zvalue) == 1) { curl_easy_setopt(ch->cp, CURLOPT_DEBUGFUNCTION, curl_debug); curl_easy_setopt(ch->cp, CURLOPT_DEBUGDATA, (void *)ch); curl_easy_setopt(ch->cp, CURLOPT_VERBOSE, 1); } else { curl_easy_setopt(ch->cp, CURLOPT_DEBUGFUNCTION, NULL); curl_easy_setopt(ch->cp, CURLOPT_DEBUGDATA, NULL); curl_easy_setopt(ch->cp, CURLOPT_VERBOSE, 0); } break; case CURLOPT_SHARE: { php_curlsh *sh = NULL; ZEND_FETCH_RESOURCE_NO_RETURN(sh, php_curlsh *, zvalue, -1, le_curl_share_handle_name, le_curl_share_handle); if (sh) { curl_easy_setopt(ch->cp, CURLOPT_SHARE, sh->share); } } #if LIBCURL_VERSION_NUM >= 0x071500 /* Available since 7.21.0 */ case CURLOPT_FNMATCH_FUNCTION: curl_easy_setopt(ch->cp, CURLOPT_FNMATCH_DATA, ch); if (ch->handlers->fnmatch == NULL) { ch->handlers->fnmatch = ecalloc(1, sizeof(php_curl_fnmatch)); } else if (!Z_ISUNDEF(ch->handlers->fnmatch->func_name)) { zval_ptr_dtor(&ch->handlers->fnmatch->func_name); ch->handlers->fnmatch->fci_cache = empty_fcall_info_cache; } ZVAL_COPY(&ch->handlers->fnmatch->func_name, zvalue); ch->handlers->fnmatch->method = PHP_CURL_USER; break; #endif } SAVE_CURL_ERROR(ch, error); if (error != CURLE_OK) { return FAILURE; } else { return SUCCESS; } } /* }}} */ Commit Message: CWE ID:
static int _php_curl_setopt(php_curl *ch, zend_long option, zval *zvalue) /* {{{ */ { CURLcode error = CURLE_OK; switch (option) { /* Long options */ case CURLOPT_SSL_VERIFYHOST: convert_to_long(zvalue); if (Z_LVAL_P(zvalue) == 1) { #if LIBCURL_VERSION_NUM <= 0x071c00 /* 7.28.0 */ php_error_docref(NULL, E_NOTICE, "CURLOPT_SSL_VERIFYHOST with value 1 is deprecated and will be removed as of libcurl 7.28.1. It is recommended to use value 2 instead"); #else php_error_docref(NULL, E_NOTICE, "CURLOPT_SSL_VERIFYHOST no longer accepts the value 1, value 2 will be used instead"); error = curl_easy_setopt(ch->cp, option, 2); break; #endif } case CURLOPT_AUTOREFERER: case CURLOPT_BUFFERSIZE: case CURLOPT_CONNECTTIMEOUT: case CURLOPT_COOKIESESSION: case CURLOPT_CRLF: case CURLOPT_DNS_CACHE_TIMEOUT: case CURLOPT_DNS_USE_GLOBAL_CACHE: case CURLOPT_FAILONERROR: case CURLOPT_FILETIME: case CURLOPT_FORBID_REUSE: case CURLOPT_FRESH_CONNECT: case CURLOPT_FTP_USE_EPRT: case CURLOPT_FTP_USE_EPSV: case CURLOPT_HEADER: case CURLOPT_HTTPGET: case CURLOPT_HTTPPROXYTUNNEL: case CURLOPT_HTTP_VERSION: case CURLOPT_INFILESIZE: case CURLOPT_LOW_SPEED_LIMIT: case CURLOPT_LOW_SPEED_TIME: case CURLOPT_MAXCONNECTS: case CURLOPT_MAXREDIRS: case CURLOPT_NETRC: case CURLOPT_NOBODY: case CURLOPT_NOPROGRESS: case CURLOPT_NOSIGNAL: case CURLOPT_PORT: case CURLOPT_POST: case CURLOPT_PROXYPORT: case CURLOPT_PROXYTYPE: case CURLOPT_PUT: case CURLOPT_RESUME_FROM: case CURLOPT_SSLVERSION: case CURLOPT_SSL_VERIFYPEER: case CURLOPT_TIMECONDITION: case CURLOPT_TIMEOUT: case CURLOPT_TIMEVALUE: case CURLOPT_TRANSFERTEXT: case CURLOPT_UNRESTRICTED_AUTH: case CURLOPT_UPLOAD: case CURLOPT_VERBOSE: #if LIBCURL_VERSION_NUM >= 0x070a06 /* Available since 7.10.6 */ case CURLOPT_HTTPAUTH: #endif #if LIBCURL_VERSION_NUM >= 0x070a07 /* Available since 7.10.7 */ case CURLOPT_FTP_CREATE_MISSING_DIRS: case CURLOPT_PROXYAUTH: #endif #if LIBCURL_VERSION_NUM >= 0x070a08 /* Available since 7.10.8 */ case CURLOPT_FTP_RESPONSE_TIMEOUT: case CURLOPT_IPRESOLVE: case CURLOPT_MAXFILESIZE: #endif #if LIBCURL_VERSION_NUM >= 0x070b02 /* Available since 7.11.2 */ case CURLOPT_TCP_NODELAY: #endif #if LIBCURL_VERSION_NUM >= 0x070c02 /* Available since 7.12.2 */ case CURLOPT_FTPSSLAUTH: #endif #if LIBCURL_VERSION_NUM >= 0x070e01 /* Available since 7.14.1 */ case CURLOPT_IGNORE_CONTENT_LENGTH: #endif #if LIBCURL_VERSION_NUM >= 0x070f00 /* Available since 7.15.0 */ case CURLOPT_FTP_SKIP_PASV_IP: #endif #if LIBCURL_VERSION_NUM >= 0x070f01 /* Available since 7.15.1 */ case CURLOPT_FTP_FILEMETHOD: #endif #if LIBCURL_VERSION_NUM >= 0x070f02 /* Available since 7.15.2 */ case CURLOPT_CONNECT_ONLY: case CURLOPT_LOCALPORT: case CURLOPT_LOCALPORTRANGE: #endif #if LIBCURL_VERSION_NUM >= 0x071000 /* Available since 7.16.0 */ case CURLOPT_SSL_SESSIONID_CACHE: #endif #if LIBCURL_VERSION_NUM >= 0x071001 /* Available since 7.16.1 */ case CURLOPT_FTP_SSL_CCC: case CURLOPT_SSH_AUTH_TYPES: #endif #if LIBCURL_VERSION_NUM >= 0x071002 /* Available since 7.16.2 */ case CURLOPT_CONNECTTIMEOUT_MS: case CURLOPT_HTTP_CONTENT_DECODING: case CURLOPT_HTTP_TRANSFER_DECODING: case CURLOPT_TIMEOUT_MS: #endif #if LIBCURL_VERSION_NUM >= 0x071004 /* Available since 7.16.4 */ case CURLOPT_NEW_DIRECTORY_PERMS: case CURLOPT_NEW_FILE_PERMS: #endif #if LIBCURL_VERSION_NUM >= 0x071100 /* Available since 7.17.0 */ case CURLOPT_USE_SSL: #elif LIBCURL_VERSION_NUM >= 0x070b00 /* Available since 7.11.0 */ case CURLOPT_FTP_SSL: #endif #if LIBCURL_VERSION_NUM >= 0x071100 /* Available since 7.17.0 */ case CURLOPT_APPEND: case CURLOPT_DIRLISTONLY: #else case CURLOPT_FTPAPPEND: case CURLOPT_FTPLISTONLY: #endif #if LIBCURL_VERSION_NUM >= 0x071200 /* Available since 7.18.0 */ case CURLOPT_PROXY_TRANSFER_MODE: #endif #if LIBCURL_VERSION_NUM >= 0x071300 /* Available since 7.19.0 */ case CURLOPT_ADDRESS_SCOPE: #endif #if LIBCURL_VERSION_NUM > 0x071301 /* Available since 7.19.1 */ case CURLOPT_CERTINFO: #endif #if LIBCURL_VERSION_NUM >= 0x071304 /* Available since 7.19.4 */ case CURLOPT_NOPROXY: case CURLOPT_PROTOCOLS: case CURLOPT_REDIR_PROTOCOLS: case CURLOPT_SOCKS5_GSSAPI_NEC: case CURLOPT_TFTP_BLKSIZE: #endif #if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */ case CURLOPT_FTP_USE_PRET: case CURLOPT_RTSP_CLIENT_CSEQ: case CURLOPT_RTSP_REQUEST: case CURLOPT_RTSP_SERVER_CSEQ: #endif #if LIBCURL_VERSION_NUM >= 0x071500 /* Available since 7.21.0 */ case CURLOPT_WILDCARDMATCH: #endif #if LIBCURL_VERSION_NUM >= 0x071504 /* Available since 7.21.4 */ case CURLOPT_TLSAUTH_TYPE: #endif #if LIBCURL_VERSION_NUM >= 0x071600 /* Available since 7.22.0 */ case CURLOPT_GSSAPI_DELEGATION: #endif #if LIBCURL_VERSION_NUM >= 0x071800 /* Available since 7.24.0 */ case CURLOPT_ACCEPTTIMEOUT_MS: #endif #if LIBCURL_VERSION_NUM >= 0x071900 /* Available since 7.25.0 */ case CURLOPT_SSL_OPTIONS: case CURLOPT_TCP_KEEPALIVE: case CURLOPT_TCP_KEEPIDLE: case CURLOPT_TCP_KEEPINTVL: #endif #if CURLOPT_MUTE != 0 case CURLOPT_MUTE: #endif convert_to_long_ex(zvalue); #if LIBCURL_VERSION_NUM >= 0x71304 if ((option == CURLOPT_PROTOCOLS || option == CURLOPT_REDIR_PROTOCOLS) && (PG(open_basedir) && *PG(open_basedir)) && (Z_LVAL_P(zvalue) & CURLPROTO_FILE)) { php_error_docref(NULL, E_WARNING, "CURLPROTO_FILE cannot be activated when an open_basedir is set"); return 1; } #endif error = curl_easy_setopt(ch->cp, option, Z_LVAL_P(zvalue)); break; case CURLOPT_SAFE_UPLOAD: convert_to_long_ex(zvalue); ch->safe_upload = (Z_LVAL_P(zvalue) != 0); break; /* String options */ case CURLOPT_CAINFO: case CURLOPT_CAPATH: case CURLOPT_COOKIE: case CURLOPT_EGDSOCKET: case CURLOPT_INTERFACE: case CURLOPT_PROXY: case CURLOPT_PROXYUSERPWD: case CURLOPT_REFERER: case CURLOPT_SSLCERTTYPE: case CURLOPT_SSLENGINE: case CURLOPT_SSLENGINE_DEFAULT: case CURLOPT_SSLKEY: case CURLOPT_SSLKEYPASSWD: case CURLOPT_SSLKEYTYPE: case CURLOPT_SSL_CIPHER_LIST: case CURLOPT_USERAGENT: case CURLOPT_USERPWD: #if LIBCURL_VERSION_NUM >= 0x070e01 /* Available since 7.14.1 */ case CURLOPT_COOKIELIST: #endif #if LIBCURL_VERSION_NUM >= 0x070f05 /* Available since 7.15.5 */ case CURLOPT_FTP_ALTERNATIVE_TO_USER: #endif #if LIBCURL_VERSION_NUM >= 0x071101 /* Available since 7.17.1 */ case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5: #endif #if LIBCURL_VERSION_NUM >= 0x071301 /* Available since 7.19.1 */ case CURLOPT_PASSWORD: case CURLOPT_PROXYPASSWORD: case CURLOPT_PROXYUSERNAME: case CURLOPT_USERNAME: #endif #if LIBCURL_VERSION_NUM >= 0x071304 /* Available since 7.19.4 */ case CURLOPT_SOCKS5_GSSAPI_SERVICE: #endif #if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */ case CURLOPT_MAIL_FROM: case CURLOPT_RTSP_STREAM_URI: case CURLOPT_RTSP_TRANSPORT: #endif #if LIBCURL_VERSION_NUM >= 0x071504 /* Available since 7.21.4 */ case CURLOPT_TLSAUTH_PASSWORD: case CURLOPT_TLSAUTH_USERNAME: #endif #if LIBCURL_VERSION_NUM >= 0x071506 /* Available since 7.21.6 */ case CURLOPT_ACCEPT_ENCODING: case CURLOPT_TRANSFER_ENCODING: #else case CURLOPT_ENCODING: #endif #if LIBCURL_VERSION_NUM >= 0x071800 /* Available since 7.24.0 */ case CURLOPT_DNS_SERVERS: #endif #if LIBCURL_VERSION_NUM >= 0x071900 /* Available since 7.25.0 */ case CURLOPT_MAIL_AUTH: #endif { convert_to_string_ex(zvalue); return php_curl_option_str(ch, option, Z_STRVAL_P(zvalue), Z_STRLEN_P(zvalue), 0); } /* Curl nullable string options */ case CURLOPT_CUSTOMREQUEST: case CURLOPT_FTPPORT: case CURLOPT_RANGE: #if LIBCURL_VERSION_NUM >= 0x070d00 /* Available since 7.13.0 */ case CURLOPT_FTP_ACCOUNT: #endif #if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */ case CURLOPT_RTSP_SESSION_ID: #endif #if LIBCURL_VERSION_NUM >= 0x071004 /* Available since 7.16.4 */ case CURLOPT_KRBLEVEL: #else case CURLOPT_KRB4LEVEL: #endif { if (Z_ISNULL_P(zvalue)) { error = curl_easy_setopt(ch->cp, option, NULL); } else { convert_to_string_ex(zvalue); return php_curl_option_str(ch, option, Z_STRVAL_P(zvalue), Z_STRLEN_P(zvalue), 0); } break; } /* Curl private option */ case CURLOPT_PRIVATE: convert_to_string_ex(zvalue); return php_curl_option_str(ch, option, Z_STRVAL_P(zvalue), Z_STRLEN_P(zvalue), 1); /* Curl url option */ case CURLOPT_URL: convert_to_string_ex(zvalue); return php_curl_option_url(ch, Z_STRVAL_P(zvalue), Z_STRLEN_P(zvalue)); /* Curl file handle options */ case CURLOPT_FILE: case CURLOPT_INFILE: case CURLOPT_STDERR: case CURLOPT_WRITEHEADER: { FILE *fp = NULL; int type; php_stream *what = NULL; if (Z_TYPE_P(zvalue) != IS_NULL) { what = zend_fetch_resource(zvalue, -1, "File-Handle", &type, 1, php_file_le_stream(), php_file_le_pstream()); if (!what) { return FAILURE; } if (FAILURE == php_stream_cast(what, PHP_STREAM_AS_STDIO, (void *) &fp, REPORT_ERRORS)) { return FAILURE; } if (!fp) { return FAILURE; } } error = CURLE_OK; switch (option) { case CURLOPT_FILE: if (!what) { if (!Z_ISUNDEF(ch->handlers->write->stream)) { zval_ptr_dtor(&ch->handlers->write->stream); ZVAL_UNDEF(&ch->handlers->write->stream); } ch->handlers->write->fp = NULL; ch->handlers->write->method = PHP_CURL_STDOUT; } else if (what->mode[0] != 'r' || what->mode[1] == '+') { zval_ptr_dtor(&ch->handlers->write->stream); ch->handlers->write->fp = fp; ch->handlers->write->method = PHP_CURL_FILE; ZVAL_COPY(&ch->handlers->write->stream, zvalue); } else { php_error_docref(NULL, E_WARNING, "the provided file handle is not writable"); return FAILURE; } break; case CURLOPT_WRITEHEADER: if (!what) { if (!Z_ISUNDEF(ch->handlers->write_header->stream)) { zval_ptr_dtor(&ch->handlers->write_header->stream); ZVAL_UNDEF(&ch->handlers->write_header->stream); } ch->handlers->write_header->fp = NULL; ch->handlers->write_header->method = PHP_CURL_IGNORE; } else if (what->mode[0] != 'r' || what->mode[1] == '+') { zval_ptr_dtor(&ch->handlers->write_header->stream); ch->handlers->write_header->fp = fp; ch->handlers->write_header->method = PHP_CURL_FILE; ZVAL_COPY(&ch->handlers->write_header->stream, zvalue);; } else { php_error_docref(NULL, E_WARNING, "the provided file handle is not writable"); return FAILURE; } break; case CURLOPT_INFILE: if (!what) { if (!Z_ISUNDEF(ch->handlers->read->stream)) { zval_ptr_dtor(&ch->handlers->read->stream); ZVAL_UNDEF(&ch->handlers->read->stream); } ch->handlers->read->fp = NULL; ch->handlers->read->res = NULL; } else { zval_ptr_dtor(&ch->handlers->read->stream); ch->handlers->read->fp = fp; ch->handlers->read->res = Z_RES_P(zvalue); ZVAL_COPY(&ch->handlers->read->stream, zvalue); } break; case CURLOPT_STDERR: if (!what) { if (!Z_ISUNDEF(ch->handlers->std_err)) { zval_ptr_dtor(&ch->handlers->std_err); ZVAL_UNDEF(&ch->handlers->std_err); } } else if (what->mode[0] != 'r' || what->mode[1] == '+') { zval_ptr_dtor(&ch->handlers->std_err); ZVAL_COPY(&ch->handlers->std_err, zvalue); } else { php_error_docref(NULL, E_WARNING, "the provided file handle is not writable"); return FAILURE; } /* break omitted intentionally */ default: error = curl_easy_setopt(ch->cp, option, fp); break; } break; } /* Curl linked list options */ case CURLOPT_HTTP200ALIASES: case CURLOPT_HTTPHEADER: case CURLOPT_POSTQUOTE: case CURLOPT_PREQUOTE: case CURLOPT_QUOTE: case CURLOPT_TELNETOPTIONS: #if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */ case CURLOPT_MAIL_RCPT: #endif #if LIBCURL_VERSION_NUM >= 0x071503 /* Available since 7.21.3 */ case CURLOPT_RESOLVE: #endif { zval *current; HashTable *ph; struct curl_slist *slist = NULL; ph = HASH_OF(zvalue); if (!ph) { char *name = NULL; switch (option) { case CURLOPT_HTTPHEADER: name = "CURLOPT_HTTPHEADER"; break; case CURLOPT_QUOTE: name = "CURLOPT_QUOTE"; break; case CURLOPT_HTTP200ALIASES: name = "CURLOPT_HTTP200ALIASES"; break; case CURLOPT_POSTQUOTE: name = "CURLOPT_POSTQUOTE"; break; case CURLOPT_PREQUOTE: name = "CURLOPT_PREQUOTE"; break; case CURLOPT_TELNETOPTIONS: name = "CURLOPT_TELNETOPTIONS"; break; #if LIBCURL_VERSION_NUM >= 0x071400 /* Available since 7.20.0 */ case CURLOPT_MAIL_RCPT: name = "CURLOPT_MAIL_RCPT"; break; #endif #if LIBCURL_VERSION_NUM >= 0x071503 /* Available since 7.21.3 */ case CURLOPT_RESOLVE: name = "CURLOPT_RESOLVE"; break; #endif } php_error_docref(NULL, E_WARNING, "You must pass either an object or an array with the %s argument", name); return FAILURE; } ZEND_HASH_FOREACH_VAL(ph, current) { SEPARATE_ZVAL(current); convert_to_string_ex(current); slist = curl_slist_append(slist, Z_STRVAL_P(current)); if (!slist) { php_error_docref(NULL, E_WARNING, "Could not build curl_slist"); return 1; } } ZEND_HASH_FOREACH_END(); zend_hash_index_update_ptr(ch->to_free->slist, option, slist); error = curl_easy_setopt(ch->cp, option, slist); break; } case CURLOPT_BINARYTRANSFER: /* Do nothing, just backward compatibility */ break; case CURLOPT_FOLLOWLOCATION: convert_to_long_ex(zvalue); #if LIBCURL_VERSION_NUM < 0x071304 if (PG(open_basedir) && *PG(open_basedir)) { if (Z_LVAL_P(zvalue) != 0) { php_error_docref(NULL, E_WARNING, "CURLOPT_FOLLOWLOCATION cannot be activated when an open_basedir is set"); return FAILURE; } } #endif error = curl_easy_setopt(ch->cp, option, Z_LVAL_P(zvalue)); break; case CURLOPT_HEADERFUNCTION: if (!Z_ISUNDEF(ch->handlers->write_header->func_name)) { zval_ptr_dtor(&ch->handlers->write_header->func_name); ch->handlers->write_header->fci_cache = empty_fcall_info_cache; } ZVAL_COPY(&ch->handlers->write_header->func_name, zvalue); ch->handlers->write_header->method = PHP_CURL_USER; break; case CURLOPT_POSTFIELDS: if (Z_TYPE_P(zvalue) == IS_ARRAY || Z_TYPE_P(zvalue) == IS_OBJECT) { zval *current; HashTable *postfields; zend_string *string_key; zend_ulong num_key; struct HttpPost *first = NULL; struct HttpPost *last = NULL; postfields = HASH_OF(zvalue); if (!postfields) { php_error_docref(NULL, E_WARNING, "Couldn't get HashTable in CURLOPT_POSTFIELDS"); return FAILURE; } ZEND_HASH_FOREACH_KEY_VAL(postfields, num_key, string_key, current) { char *postval; /* Pretend we have a string_key here */ if (!string_key) { string_key = zend_long_to_str(num_key); } else { zend_string_addref(string_key); } if (Z_TYPE_P(current) == IS_OBJECT && instanceof_function(Z_OBJCE_P(current), curl_CURLFile_class)) { /* new-style file upload */ zval *prop; char *type = NULL, *filename = NULL; prop = zend_read_property(curl_CURLFile_class, current, "name", sizeof("name")-1, 0); if (Z_TYPE_P(prop) != IS_STRING) { php_error_docref(NULL, E_WARNING, "Invalid filename for key %s", string_key->val); } else { postval = Z_STRVAL_P(prop); if (php_check_open_basedir(postval)) { return 1; } prop = zend_read_property(curl_CURLFile_class, current, "mime", sizeof("mime")-1, 0); if (Z_TYPE_P(prop) == IS_STRING && Z_STRLEN_P(prop) > 0) { type = Z_STRVAL_P(prop); } prop = zend_read_property(curl_CURLFile_class, current, "postname", sizeof("postname")-1, 0); if (Z_TYPE_P(prop) == IS_STRING && Z_STRLEN_P(prop) > 0) { filename = Z_STRVAL_P(prop); } error = curl_formadd(&first, &last, CURLFORM_COPYNAME, string_key->val, CURLFORM_NAMELENGTH, string_key->len, CURLFORM_FILENAME, filename ? filename : postval, CURLFORM_CONTENTTYPE, type ? type : "application/octet-stream", CURLFORM_FILE, postval, CURLFORM_END); } zend_string_release(string_key); continue; } SEPARATE_ZVAL(current); convert_to_string_ex(current); postval = Z_STRVAL_P(current); /* The arguments after _NAMELENGTH and _CONTENTSLENGTH * must be explicitly cast to long in curl_formadd * use since curl needs a long not an int. */ if (!ch->safe_upload && *postval == '@') { char *name, *type, *filename; ++postval; php_error_docref("curl.curlfile", E_DEPRECATED, "The usage of the @filename API for file uploading is deprecated. Please use the CURLFile class instead"); name = estrndup(postval, Z_STRLEN_P(current)); if ((type = (char *)php_memnstr(name, ";type=", sizeof(";type=") - 1, name + Z_STRLEN_P(current)))) { *type = '\0'; } if ((filename = (char *)php_memnstr(name, ";filename=", sizeof(";filename=") - 1, name + Z_STRLEN_P(current)))) { *filename = '\0'; } /* open_basedir check */ if (php_check_open_basedir(name)) { efree(name); return FAILURE; } error = curl_formadd(&first, &last, CURLFORM_COPYNAME, string_key->val, CURLFORM_NAMELENGTH, string_key->len, CURLFORM_FILENAME, filename ? filename + sizeof(";filename=") - 1 : name, CURLFORM_CONTENTTYPE, type ? type + sizeof(";type=") - 1 : "application/octet-stream", CURLFORM_FILE, name, CURLFORM_END); efree(name); } else { error = curl_formadd(&first, &last, CURLFORM_COPYNAME, string_key->val, CURLFORM_NAMELENGTH, (zend_long)string_key->len, CURLFORM_COPYCONTENTS, postval, CURLFORM_CONTENTSLENGTH, (zend_long)Z_STRLEN_P(current), CURLFORM_END); } zend_string_release(string_key); } ZEND_HASH_FOREACH_END(); SAVE_CURL_ERROR(ch, error); if (error != CURLE_OK) { return FAILURE; } if (ch->clone == 0) { zend_llist_clean(&ch->to_free->post); } zend_llist_add_element(&ch->to_free->post, &first); error = curl_easy_setopt(ch->cp, CURLOPT_HTTPPOST, first); } else { #if LIBCURL_VERSION_NUM >= 0x071101 convert_to_string_ex(zvalue); /* with curl 7.17.0 and later, we can use COPYPOSTFIELDS, but we have to provide size before */ error = curl_easy_setopt(ch->cp, CURLOPT_POSTFIELDSIZE, Z_STRLEN_P(zvalue)); error = curl_easy_setopt(ch->cp, CURLOPT_COPYPOSTFIELDS, Z_STRVAL_P(zvalue)); #else char *post = NULL; convert_to_string_ex(zvalue); post = estrndup(Z_STRVAL_P(zvalue), Z_STRLEN_P(zvalue)); zend_llist_add_element(&ch->to_free->str, &post); curl_easy_setopt(ch->cp, CURLOPT_POSTFIELDS, post); error = curl_easy_setopt(ch->cp, CURLOPT_POSTFIELDSIZE, Z_STRLEN_P(zvalue)); #endif } break; case CURLOPT_PROGRESSFUNCTION: curl_easy_setopt(ch->cp, CURLOPT_PROGRESSFUNCTION, curl_progress); curl_easy_setopt(ch->cp, CURLOPT_PROGRESSDATA, ch); if (ch->handlers->progress == NULL) { ch->handlers->progress = ecalloc(1, sizeof(php_curl_progress)); } else if (!Z_ISUNDEF(ch->handlers->progress->func_name)) { zval_ptr_dtor(&ch->handlers->progress->func_name); ch->handlers->progress->fci_cache = empty_fcall_info_cache; } ZVAL_COPY(&ch->handlers->progress->func_name, zvalue); ch->handlers->progress->method = PHP_CURL_USER; break; case CURLOPT_READFUNCTION: if (!Z_ISUNDEF(ch->handlers->read->func_name)) { zval_ptr_dtor(&ch->handlers->read->func_name); ch->handlers->read->fci_cache = empty_fcall_info_cache; } ZVAL_COPY(&ch->handlers->read->func_name, zvalue); ch->handlers->read->method = PHP_CURL_USER; break; case CURLOPT_RETURNTRANSFER: convert_to_long_ex(zvalue); if (Z_LVAL_P(zvalue)) { ch->handlers->write->method = PHP_CURL_RETURN; } else { ch->handlers->write->method = PHP_CURL_STDOUT; } break; case CURLOPT_WRITEFUNCTION: if (!Z_ISUNDEF(ch->handlers->write->func_name)) { zval_ptr_dtor(&ch->handlers->write->func_name); ch->handlers->write->fci_cache = empty_fcall_info_cache; } ZVAL_COPY(&ch->handlers->write->func_name, zvalue); ch->handlers->write->method = PHP_CURL_USER; break; #if LIBCURL_VERSION_NUM >= 0x070f05 /* Available since 7.15.5 */ case CURLOPT_MAX_RECV_SPEED_LARGE: case CURLOPT_MAX_SEND_SPEED_LARGE: convert_to_long_ex(zvalue); error = curl_easy_setopt(ch->cp, option, (curl_off_t)Z_LVAL_P(zvalue)); break; #endif #if LIBCURL_VERSION_NUM >= 0x071301 /* Available since 7.19.1 */ case CURLOPT_POSTREDIR: convert_to_long_ex(zvalue); error = curl_easy_setopt(ch->cp, CURLOPT_POSTREDIR, Z_LVAL_P(zvalue) & CURL_REDIR_POST_ALL); break; #endif #if CURLOPT_PASSWDFUNCTION != 0 case CURLOPT_PASSWDFUNCTION: zval_ptr_dtor(&ch->handlers->passwd); ZVAL_COPY(&ch->handlers->passwd, zvalue); error = curl_easy_setopt(ch->cp, CURLOPT_PASSWDFUNCTION, curl_passwd); error = curl_easy_setopt(ch->cp, CURLOPT_PASSWDDATA, (void *) ch); break; #endif /* the following options deal with files, therefore the open_basedir check * is required. */ case CURLOPT_COOKIEFILE: case CURLOPT_COOKIEJAR: case CURLOPT_RANDOM_FILE: case CURLOPT_SSLCERT: #if LIBCURL_VERSION_NUM >= 0x070b00 /* Available since 7.11.0 */ case CURLOPT_NETRC_FILE: #endif #if LIBCURL_VERSION_NUM >= 0x071001 /* Available since 7.16.1 */ case CURLOPT_SSH_PRIVATE_KEYFILE: case CURLOPT_SSH_PUBLIC_KEYFILE: #endif #if LIBCURL_VERSION_NUM >= 0x071300 /* Available since 7.19.0 */ case CURLOPT_CRLFILE: case CURLOPT_ISSUERCERT: #endif #if LIBCURL_VERSION_NUM >= 0x071306 /* Available since 7.19.6 */ case CURLOPT_SSH_KNOWNHOSTS: #endif { convert_to_string_ex(zvalue); if (Z_STRLEN_P(zvalue) && php_check_open_basedir(Z_STRVAL_P(zvalue))) { return FAILURE; } return php_curl_option_str(ch, option, Z_STRVAL_P(zvalue), Z_STRLEN_P(zvalue), 0); } case CURLINFO_HEADER_OUT: convert_to_long_ex(zvalue); if (Z_LVAL_P(zvalue) == 1) { curl_easy_setopt(ch->cp, CURLOPT_DEBUGFUNCTION, curl_debug); curl_easy_setopt(ch->cp, CURLOPT_DEBUGDATA, (void *)ch); curl_easy_setopt(ch->cp, CURLOPT_VERBOSE, 1); } else { curl_easy_setopt(ch->cp, CURLOPT_DEBUGFUNCTION, NULL); curl_easy_setopt(ch->cp, CURLOPT_DEBUGDATA, NULL); curl_easy_setopt(ch->cp, CURLOPT_VERBOSE, 0); } break; case CURLOPT_SHARE: { php_curlsh *sh = NULL; ZEND_FETCH_RESOURCE_NO_RETURN(sh, php_curlsh *, zvalue, -1, le_curl_share_handle_name, le_curl_share_handle); if (sh) { curl_easy_setopt(ch->cp, CURLOPT_SHARE, sh->share); } } break; #if LIBCURL_VERSION_NUM >= 0x071500 /* Available since 7.21.0 */ case CURLOPT_FNMATCH_FUNCTION: curl_easy_setopt(ch->cp, CURLOPT_FNMATCH_DATA, ch); if (ch->handlers->fnmatch == NULL) { ch->handlers->fnmatch = ecalloc(1, sizeof(php_curl_fnmatch)); } else if (!Z_ISUNDEF(ch->handlers->fnmatch->func_name)) { zval_ptr_dtor(&ch->handlers->fnmatch->func_name); ch->handlers->fnmatch->fci_cache = empty_fcall_info_cache; } ZVAL_COPY(&ch->handlers->fnmatch->func_name, zvalue); ch->handlers->fnmatch->method = PHP_CURL_USER; break; #endif } SAVE_CURL_ERROR(ch, error); if (error != CURLE_OK) { return FAILURE; } else { return SUCCESS; } } /* }}} */
164,768
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int khugepaged_enter_vma_merge(struct vm_area_struct *vma) { unsigned long hstart, hend; if (!vma->anon_vma) /* * Not yet faulted in so we will register later in the * page fault if needed. */ return 0; if (vma->vm_file || vma->vm_ops) /* khugepaged not yet working on file or special mappings */ return 0; VM_BUG_ON(is_linear_pfn_mapping(vma) || is_pfn_mapping(vma)); hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK; hend = vma->vm_end & HPAGE_PMD_MASK; if (hstart < hend) return khugepaged_enter(vma); return 0; } Commit Message: mm: thp: fix /dev/zero MAP_PRIVATE and vm_flags cleanups The huge_memory.c THP page fault was allowed to run if vm_ops was null (which would succeed for /dev/zero MAP_PRIVATE, as the f_op->mmap wouldn't setup a special vma->vm_ops and it would fallback to regular anonymous memory) but other THP logics weren't fully activated for vmas with vm_file not NULL (/dev/zero has a not NULL vma->vm_file). So this removes the vm_file checks so that /dev/zero also can safely use THP (the other albeit safer approach to fix this bug would have been to prevent the THP initial page fault to run if vm_file was set). After removing the vm_file checks, this also makes huge_memory.c stricter in khugepaged for the DEBUG_VM=y case. It doesn't replace the vm_file check with a is_pfn_mapping check (but it keeps checking for VM_PFNMAP under VM_BUG_ON) because for a is_cow_mapping() mapping VM_PFNMAP should only be allowed to exist before the first page fault, and in turn when vma->anon_vma is null (so preventing khugepaged registration). So I tend to think the previous comment saying if vm_file was set, VM_PFNMAP might have been set and we could still be registered in khugepaged (despite anon_vma was not NULL to be registered in khugepaged) was too paranoid. The is_linear_pfn_mapping check is also I think superfluous (as described by comment) but under DEBUG_VM it is safe to stay. Addresses https://bugzilla.kernel.org/show_bug.cgi?id=33682 Signed-off-by: Andrea Arcangeli <[email protected]> Reported-by: Caspar Zhang <[email protected]> Acked-by: Mel Gorman <[email protected]> Acked-by: Rik van Riel <[email protected]> Cc: <[email protected]> [2.6.38.x] Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399
int khugepaged_enter_vma_merge(struct vm_area_struct *vma) { unsigned long hstart, hend; if (!vma->anon_vma) /* * Not yet faulted in so we will register later in the * page fault if needed. */ return 0; if (vma->vm_ops) /* khugepaged not yet working on file or special mappings */ return 0; /* * If is_pfn_mapping() is true is_learn_pfn_mapping() must be * true too, verify it here. */ VM_BUG_ON(is_linear_pfn_mapping(vma) || vma->vm_flags & VM_NO_THP); hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK; hend = vma->vm_end & HPAGE_PMD_MASK; if (hstart < hend) return khugepaged_enter(vma); return 0; }
166,227
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void vmxnet3_activate_device(VMXNET3State *s) { int i; VMW_CFPRN("MTU is %u", s->mtu); s->max_rx_frags = VMXNET3_READ_DRV_SHARED16(s->drv_shmem, devRead.misc.maxNumRxSG); if (s->max_rx_frags == 0) { s->max_rx_frags = 1; } VMW_CFPRN("Max RX fragments is %u", s->max_rx_frags); s->event_int_idx = VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.intrConf.eventIntrIdx); assert(vmxnet3_verify_intx(s, s->event_int_idx)); VMW_CFPRN("Events interrupt line is %u", s->event_int_idx); s->auto_int_masking = VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.intrConf.autoMask); VMW_CFPRN("Automatic interrupt masking is %d", (int)s->auto_int_masking); s->txq_num = VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numTxQueues); s->rxq_num = VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numRxQueues); VMW_CFPRN("Number of TX/RX queues %u/%u", s->txq_num, s->rxq_num); assert(s->txq_num <= VMXNET3_DEVICE_MAX_TX_QUEUES); qdescr_table_pa = VMXNET3_READ_DRV_SHARED64(s->drv_shmem, devRead.misc.queueDescPA); VMW_CFPRN("TX queues descriptors table is at 0x%" PRIx64, qdescr_table_pa); /* * Worst-case scenario is a packet that holds all TX rings space so * we calculate total size of all TX rings for max TX fragments number */ s->max_tx_frags = 0; /* TX queues */ for (i = 0; i < s->txq_num; i++) { VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numRxQueues); VMW_CFPRN("Number of TX/RX queues %u/%u", s->txq_num, s->rxq_num); assert(s->txq_num <= VMXNET3_DEVICE_MAX_TX_QUEUES); qdescr_table_pa = VMXNET3_READ_DRV_SHARED64(s->drv_shmem, devRead.misc.queueDescPA); VMW_CFPRN("TX Queue %d interrupt: %d", i, s->txq_descr[i].intr_idx); /* Read rings memory locations for TX queues */ pa = VMXNET3_READ_TX_QUEUE_DESCR64(qdescr_pa, conf.txRingBasePA); size = VMXNET3_READ_TX_QUEUE_DESCR32(qdescr_pa, conf.txRingSize); vmxnet3_ring_init(&s->txq_descr[i].tx_ring, pa, size, sizeof(struct Vmxnet3_TxDesc), false); VMXNET3_RING_DUMP(VMW_CFPRN, "TX", i, &s->txq_descr[i].tx_ring); s->max_tx_frags += size; /* TXC ring */ pa = VMXNET3_READ_TX_QUEUE_DESCR64(qdescr_pa, conf.compRingBasePA); size = VMXNET3_READ_TX_QUEUE_DESCR32(qdescr_pa, conf.compRingSize); vmxnet3_ring_init(&s->txq_descr[i].comp_ring, pa, size, sizeof(struct Vmxnet3_TxCompDesc), true); VMXNET3_RING_DUMP(VMW_CFPRN, "TXC", i, &s->txq_descr[i].comp_ring); s->txq_descr[i].tx_stats_pa = qdescr_pa + offsetof(struct Vmxnet3_TxQueueDesc, stats); memset(&s->txq_descr[i].txq_stats, 0, sizeof(s->txq_descr[i].txq_stats)); /* Fill device-managed parameters for queues */ VMXNET3_WRITE_TX_QUEUE_DESCR32(qdescr_pa, ctrl.txThreshold, VMXNET3_DEF_TX_THRESHOLD); } /* Preallocate TX packet wrapper */ VMW_CFPRN("Max TX fragments is %u", s->max_tx_frags); vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr); vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr); /* Read rings memory locations for RX queues */ for (i = 0; i < s->rxq_num; i++) { int j; hwaddr qd_pa = qdescr_table_pa + s->txq_num * sizeof(struct Vmxnet3_TxQueueDesc) + i * sizeof(struct Vmxnet3_RxQueueDesc); /* Read interrupt number for this RX queue */ s->rxq_descr[i].intr_idx = VMXNET3_READ_TX_QUEUE_DESCR8(qd_pa, conf.intrIdx); assert(vmxnet3_verify_intx(s, s->rxq_descr[i].intr_idx)); VMW_CFPRN("RX Queue %d interrupt: %d", i, s->rxq_descr[i].intr_idx); /* Read rings memory locations */ for (j = 0; j < VMXNET3_RX_RINGS_PER_QUEUE; j++) { /* RX rings */ pa = VMXNET3_READ_RX_QUEUE_DESCR64(qd_pa, conf.rxRingBasePA[j]); size = VMXNET3_READ_RX_QUEUE_DESCR32(qd_pa, conf.rxRingSize[j]); vmxnet3_ring_init(&s->rxq_descr[i].rx_ring[j], pa, size, sizeof(struct Vmxnet3_RxDesc), false); VMW_CFPRN("RX queue %d:%d: Base: %" PRIx64 ", Size: %d", i, j, pa, size); } /* RXC ring */ pa = VMXNET3_READ_RX_QUEUE_DESCR64(qd_pa, conf.compRingBasePA); size = VMXNET3_READ_RX_QUEUE_DESCR32(qd_pa, conf.compRingSize); vmxnet3_ring_init(&s->rxq_descr[i].comp_ring, pa, size, sizeof(struct Vmxnet3_RxCompDesc), true); VMW_CFPRN("RXC queue %d: Base: %" PRIx64 ", Size: %d", i, pa, size); s->rxq_descr[i].rx_stats_pa = qd_pa + offsetof(struct Vmxnet3_RxQueueDesc, stats); memset(&s->rxq_descr[i].rxq_stats, 0, sizeof(s->rxq_descr[i].rxq_stats)); } vmxnet3_validate_interrupts(s); /* Make sure everything is in place before device activation */ smp_wmb(); vmxnet3_reset_mac(s); s->device_active = true; } Commit Message: CWE ID: CWE-20
static void vmxnet3_activate_device(VMXNET3State *s) { int i; VMW_CFPRN("MTU is %u", s->mtu); s->max_rx_frags = VMXNET3_READ_DRV_SHARED16(s->drv_shmem, devRead.misc.maxNumRxSG); if (s->max_rx_frags == 0) { s->max_rx_frags = 1; } VMW_CFPRN("Max RX fragments is %u", s->max_rx_frags); s->event_int_idx = VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.intrConf.eventIntrIdx); assert(vmxnet3_verify_intx(s, s->event_int_idx)); VMW_CFPRN("Events interrupt line is %u", s->event_int_idx); s->auto_int_masking = VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.intrConf.autoMask); VMW_CFPRN("Automatic interrupt masking is %d", (int)s->auto_int_masking); s->txq_num = VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numTxQueues); s->rxq_num = VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numRxQueues); VMW_CFPRN("Number of TX/RX queues %u/%u", s->txq_num, s->rxq_num); assert(s->txq_num <= VMXNET3_DEVICE_MAX_TX_QUEUES); qdescr_table_pa = VMXNET3_READ_DRV_SHARED64(s->drv_shmem, devRead.misc.queueDescPA); VMW_CFPRN("TX queues descriptors table is at 0x%" PRIx64, qdescr_table_pa); /* * Worst-case scenario is a packet that holds all TX rings space so * we calculate total size of all TX rings for max TX fragments number */ s->max_tx_frags = 0; /* TX queues */ for (i = 0; i < s->txq_num; i++) { VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numRxQueues); VMW_CFPRN("Number of TX/RX queues %u/%u", s->txq_num, s->rxq_num); vmxnet3_validate_queues(s); qdescr_table_pa = VMXNET3_READ_DRV_SHARED64(s->drv_shmem, devRead.misc.queueDescPA); VMW_CFPRN("TX Queue %d interrupt: %d", i, s->txq_descr[i].intr_idx); /* Read rings memory locations for TX queues */ pa = VMXNET3_READ_TX_QUEUE_DESCR64(qdescr_pa, conf.txRingBasePA); size = VMXNET3_READ_TX_QUEUE_DESCR32(qdescr_pa, conf.txRingSize); vmxnet3_ring_init(&s->txq_descr[i].tx_ring, pa, size, sizeof(struct Vmxnet3_TxDesc), false); VMXNET3_RING_DUMP(VMW_CFPRN, "TX", i, &s->txq_descr[i].tx_ring); s->max_tx_frags += size; /* TXC ring */ pa = VMXNET3_READ_TX_QUEUE_DESCR64(qdescr_pa, conf.compRingBasePA); size = VMXNET3_READ_TX_QUEUE_DESCR32(qdescr_pa, conf.compRingSize); vmxnet3_ring_init(&s->txq_descr[i].comp_ring, pa, size, sizeof(struct Vmxnet3_TxCompDesc), true); VMXNET3_RING_DUMP(VMW_CFPRN, "TXC", i, &s->txq_descr[i].comp_ring); s->txq_descr[i].tx_stats_pa = qdescr_pa + offsetof(struct Vmxnet3_TxQueueDesc, stats); memset(&s->txq_descr[i].txq_stats, 0, sizeof(s->txq_descr[i].txq_stats)); /* Fill device-managed parameters for queues */ VMXNET3_WRITE_TX_QUEUE_DESCR32(qdescr_pa, ctrl.txThreshold, VMXNET3_DEF_TX_THRESHOLD); } /* Preallocate TX packet wrapper */ VMW_CFPRN("Max TX fragments is %u", s->max_tx_frags); vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr); vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr); /* Read rings memory locations for RX queues */ for (i = 0; i < s->rxq_num; i++) { int j; hwaddr qd_pa = qdescr_table_pa + s->txq_num * sizeof(struct Vmxnet3_TxQueueDesc) + i * sizeof(struct Vmxnet3_RxQueueDesc); /* Read interrupt number for this RX queue */ s->rxq_descr[i].intr_idx = VMXNET3_READ_TX_QUEUE_DESCR8(qd_pa, conf.intrIdx); assert(vmxnet3_verify_intx(s, s->rxq_descr[i].intr_idx)); VMW_CFPRN("RX Queue %d interrupt: %d", i, s->rxq_descr[i].intr_idx); /* Read rings memory locations */ for (j = 0; j < VMXNET3_RX_RINGS_PER_QUEUE; j++) { /* RX rings */ pa = VMXNET3_READ_RX_QUEUE_DESCR64(qd_pa, conf.rxRingBasePA[j]); size = VMXNET3_READ_RX_QUEUE_DESCR32(qd_pa, conf.rxRingSize[j]); vmxnet3_ring_init(&s->rxq_descr[i].rx_ring[j], pa, size, sizeof(struct Vmxnet3_RxDesc), false); VMW_CFPRN("RX queue %d:%d: Base: %" PRIx64 ", Size: %d", i, j, pa, size); } /* RXC ring */ pa = VMXNET3_READ_RX_QUEUE_DESCR64(qd_pa, conf.compRingBasePA); size = VMXNET3_READ_RX_QUEUE_DESCR32(qd_pa, conf.compRingSize); vmxnet3_ring_init(&s->rxq_descr[i].comp_ring, pa, size, sizeof(struct Vmxnet3_RxCompDesc), true); VMW_CFPRN("RXC queue %d: Base: %" PRIx64 ", Size: %d", i, pa, size); s->rxq_descr[i].rx_stats_pa = qd_pa + offsetof(struct Vmxnet3_RxQueueDesc, stats); memset(&s->rxq_descr[i].rxq_stats, 0, sizeof(s->rxq_descr[i].rxq_stats)); } vmxnet3_validate_interrupts(s); /* Make sure everything is in place before device activation */ smp_wmb(); vmxnet3_reset_mac(s); s->device_active = true; }
165,355
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void RegisterPropertiesCallback(IBusPanelService* panel, IBusPropList* prop_list, gpointer user_data) { g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->RegisterProperties(prop_list); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
static void RegisterPropertiesCallback(IBusPanelService* panel, void RegisterProperties(IBusPanelService* panel, IBusPropList* prop_list) { DoRegisterProperties(prop_list); }
170,545
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr) { u16 offset = sizeof(struct ipv6hdr); struct ipv6_opt_hdr *exthdr = (struct ipv6_opt_hdr *)(ipv6_hdr(skb) + 1); unsigned int packet_len = skb_tail_pointer(skb) - skb_network_header(skb); int found_rhdr = 0; *nexthdr = &ipv6_hdr(skb)->nexthdr; while (offset + 1 <= packet_len) { switch (**nexthdr) { case NEXTHDR_HOP: break; case NEXTHDR_ROUTING: found_rhdr = 1; break; case NEXTHDR_DEST: #if IS_ENABLED(CONFIG_IPV6_MIP6) if (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0) break; #endif if (found_rhdr) return offset; break; default: return offset; } offset += ipv6_optlen(exthdr); *nexthdr = &exthdr->nexthdr; exthdr = (struct ipv6_opt_hdr *)(skb_network_header(skb) + offset); } return offset; } Commit Message: ipv6: Prevent overrun when parsing v6 header options The KASAN warning repoted below was discovered with a syzkaller program. The reproducer is basically: int s = socket(AF_INET6, SOCK_RAW, NEXTHDR_HOP); send(s, &one_byte_of_data, 1, MSG_MORE); send(s, &more_than_mtu_bytes_data, 2000, 0); The socket() call sets the nexthdr field of the v6 header to NEXTHDR_HOP, the first send call primes the payload with a non zero byte of data, and the second send call triggers the fragmentation path. The fragmentation code tries to parse the header options in order to figure out where to insert the fragment option. Since nexthdr points to an invalid option, the calculation of the size of the network header can made to be much larger than the linear section of the skb and data is read outside of it. This fix makes ip6_find_1stfrag return an error if it detects running out-of-bounds. [ 42.361487] ================================================================== [ 42.364412] BUG: KASAN: slab-out-of-bounds in ip6_fragment+0x11c8/0x3730 [ 42.365471] Read of size 840 at addr ffff88000969e798 by task ip6_fragment-oo/3789 [ 42.366469] [ 42.366696] CPU: 1 PID: 3789 Comm: ip6_fragment-oo Not tainted 4.11.0+ #41 [ 42.367628] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.1-1ubuntu1 04/01/2014 [ 42.368824] Call Trace: [ 42.369183] dump_stack+0xb3/0x10b [ 42.369664] print_address_description+0x73/0x290 [ 42.370325] kasan_report+0x252/0x370 [ 42.370839] ? ip6_fragment+0x11c8/0x3730 [ 42.371396] check_memory_region+0x13c/0x1a0 [ 42.371978] memcpy+0x23/0x50 [ 42.372395] ip6_fragment+0x11c8/0x3730 [ 42.372920] ? nf_ct_expect_unregister_notifier+0x110/0x110 [ 42.373681] ? ip6_copy_metadata+0x7f0/0x7f0 [ 42.374263] ? ip6_forward+0x2e30/0x2e30 [ 42.374803] ip6_finish_output+0x584/0x990 [ 42.375350] ip6_output+0x1b7/0x690 [ 42.375836] ? ip6_finish_output+0x990/0x990 [ 42.376411] ? ip6_fragment+0x3730/0x3730 [ 42.376968] ip6_local_out+0x95/0x160 [ 42.377471] ip6_send_skb+0xa1/0x330 [ 42.377969] ip6_push_pending_frames+0xb3/0xe0 [ 42.378589] rawv6_sendmsg+0x2051/0x2db0 [ 42.379129] ? rawv6_bind+0x8b0/0x8b0 [ 42.379633] ? _copy_from_user+0x84/0xe0 [ 42.380193] ? debug_check_no_locks_freed+0x290/0x290 [ 42.380878] ? ___sys_sendmsg+0x162/0x930 [ 42.381427] ? rcu_read_lock_sched_held+0xa3/0x120 [ 42.382074] ? sock_has_perm+0x1f6/0x290 [ 42.382614] ? ___sys_sendmsg+0x167/0x930 [ 42.383173] ? lock_downgrade+0x660/0x660 [ 42.383727] inet_sendmsg+0x123/0x500 [ 42.384226] ? inet_sendmsg+0x123/0x500 [ 42.384748] ? inet_recvmsg+0x540/0x540 [ 42.385263] sock_sendmsg+0xca/0x110 [ 42.385758] SYSC_sendto+0x217/0x380 [ 42.386249] ? SYSC_connect+0x310/0x310 [ 42.386783] ? __might_fault+0x110/0x1d0 [ 42.387324] ? lock_downgrade+0x660/0x660 [ 42.387880] ? __fget_light+0xa1/0x1f0 [ 42.388403] ? __fdget+0x18/0x20 [ 42.388851] ? sock_common_setsockopt+0x95/0xd0 [ 42.389472] ? SyS_setsockopt+0x17f/0x260 [ 42.390021] ? entry_SYSCALL_64_fastpath+0x5/0xbe [ 42.390650] SyS_sendto+0x40/0x50 [ 42.391103] entry_SYSCALL_64_fastpath+0x1f/0xbe [ 42.391731] RIP: 0033:0x7fbbb711e383 [ 42.392217] RSP: 002b:00007ffff4d34f28 EFLAGS: 00000246 ORIG_RAX: 000000000000002c [ 42.393235] RAX: ffffffffffffffda RBX: 0000000000000000 RCX: 00007fbbb711e383 [ 42.394195] RDX: 0000000000001000 RSI: 00007ffff4d34f60 RDI: 0000000000000003 [ 42.395145] RBP: 0000000000000046 R08: 00007ffff4d34f40 R09: 0000000000000018 [ 42.396056] R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000400aad [ 42.396598] R13: 0000000000000066 R14: 00007ffff4d34ee0 R15: 00007fbbb717af00 [ 42.397257] [ 42.397411] Allocated by task 3789: [ 42.397702] save_stack_trace+0x16/0x20 [ 42.398005] save_stack+0x46/0xd0 [ 42.398267] kasan_kmalloc+0xad/0xe0 [ 42.398548] kasan_slab_alloc+0x12/0x20 [ 42.398848] __kmalloc_node_track_caller+0xcb/0x380 [ 42.399224] __kmalloc_reserve.isra.32+0x41/0xe0 [ 42.399654] __alloc_skb+0xf8/0x580 [ 42.400003] sock_wmalloc+0xab/0xf0 [ 42.400346] __ip6_append_data.isra.41+0x2472/0x33d0 [ 42.400813] ip6_append_data+0x1a8/0x2f0 [ 42.401122] rawv6_sendmsg+0x11ee/0x2db0 [ 42.401505] inet_sendmsg+0x123/0x500 [ 42.401860] sock_sendmsg+0xca/0x110 [ 42.402209] ___sys_sendmsg+0x7cb/0x930 [ 42.402582] __sys_sendmsg+0xd9/0x190 [ 42.402941] SyS_sendmsg+0x2d/0x50 [ 42.403273] entry_SYSCALL_64_fastpath+0x1f/0xbe [ 42.403718] [ 42.403871] Freed by task 1794: [ 42.404146] save_stack_trace+0x16/0x20 [ 42.404515] save_stack+0x46/0xd0 [ 42.404827] kasan_slab_free+0x72/0xc0 [ 42.405167] kfree+0xe8/0x2b0 [ 42.405462] skb_free_head+0x74/0xb0 [ 42.405806] skb_release_data+0x30e/0x3a0 [ 42.406198] skb_release_all+0x4a/0x60 [ 42.406563] consume_skb+0x113/0x2e0 [ 42.406910] skb_free_datagram+0x1a/0xe0 [ 42.407288] netlink_recvmsg+0x60d/0xe40 [ 42.407667] sock_recvmsg+0xd7/0x110 [ 42.408022] ___sys_recvmsg+0x25c/0x580 [ 42.408395] __sys_recvmsg+0xd6/0x190 [ 42.408753] SyS_recvmsg+0x2d/0x50 [ 42.409086] entry_SYSCALL_64_fastpath+0x1f/0xbe [ 42.409513] [ 42.409665] The buggy address belongs to the object at ffff88000969e780 [ 42.409665] which belongs to the cache kmalloc-512 of size 512 [ 42.410846] The buggy address is located 24 bytes inside of [ 42.410846] 512-byte region [ffff88000969e780, ffff88000969e980) [ 42.411941] The buggy address belongs to the page: [ 42.412405] page:ffffea000025a780 count:1 mapcount:0 mapping: (null) index:0x0 compound_mapcount: 0 [ 42.413298] flags: 0x100000000008100(slab|head) [ 42.413729] raw: 0100000000008100 0000000000000000 0000000000000000 00000001800c000c [ 42.414387] raw: ffffea00002a9500 0000000900000007 ffff88000c401280 0000000000000000 [ 42.415074] page dumped because: kasan: bad access detected [ 42.415604] [ 42.415757] Memory state around the buggy address: [ 42.416222] ffff88000969e880: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 42.416904] ffff88000969e900: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 42.417591] >ffff88000969e980: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc [ 42.418273] ^ [ 42.418588] ffff88000969ea00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb [ 42.419273] ffff88000969ea80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb [ 42.419882] ================================================================== Reported-by: Andrey Konovalov <[email protected]> Signed-off-by: Craig Gallek <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-125
int ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr) { u16 offset = sizeof(struct ipv6hdr); unsigned int packet_len = skb_tail_pointer(skb) - skb_network_header(skb); int found_rhdr = 0; *nexthdr = &ipv6_hdr(skb)->nexthdr; while (offset <= packet_len) { struct ipv6_opt_hdr *exthdr; switch (**nexthdr) { case NEXTHDR_HOP: break; case NEXTHDR_ROUTING: found_rhdr = 1; break; case NEXTHDR_DEST: #if IS_ENABLED(CONFIG_IPV6_MIP6) if (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0) break; #endif if (found_rhdr) return offset; break; default: return offset; } if (offset + sizeof(struct ipv6_opt_hdr) > packet_len) return -EINVAL; exthdr = (struct ipv6_opt_hdr *)(skb_network_header(skb) + offset); offset += ipv6_optlen(exthdr); *nexthdr = &exthdr->nexthdr; } return -EINVAL; }
168,132
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool FakeCentral::IsPowered() const { switch (state_) { case mojom::CentralState::POWERED_OFF: return false; case mojom::CentralState::POWERED_ON: return true; case mojom::CentralState::ABSENT: NOTREACHED(); return false; } NOTREACHED(); return false; } Commit Message: bluetooth: Implement getAvailability() This change implements the getAvailability() method for navigator.bluetooth as defined in the specification. Bug: 707640 Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516 Reviewed-by: Chris Harrelson <[email protected]> Reviewed-by: Giovanni Ortuño Urquidi <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Cr-Commit-Position: refs/heads/master@{#688987} CWE ID: CWE-119
bool FakeCentral::IsPowered() const { switch (state_) { case mojom::CentralState::ABSENT: // SetState() calls IsPowered() to notify observers properly when an adapter // being removed is simulated, so it should return false. case mojom::CentralState::POWERED_OFF: return false; case mojom::CentralState::POWERED_ON: return true; } NOTREACHED(); return false; }
172,447
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void t1_check_unusual_charstring(void) { char *p = strstr(t1_line_array, charstringname) + strlen(charstringname); int i; /* if no number follows "/CharStrings", let's read the next line */ if (sscanf(p, "%i", &i) != 1) { /* pdftex_warn("no number found after `%s', I assume it's on the next line", charstringname); */ strcpy(t1_buf_array, t1_line_array); /* t1_getline always appends EOL to t1_line_array; let's change it to * space before appending the next line */ *(strend(t1_buf_array) - 1) = ' '; t1_getline(); strcat(t1_buf_array, t1_line_array); strcpy(t1_line_array, t1_buf_array); t1_line_ptr = eol(t1_line_array); } } Commit Message: writet1 protection against buffer overflow git-svn-id: svn://tug.org/texlive/trunk/Build/source@48697 c570f23f-e606-0410-a88d-b1316a301751 CWE ID: CWE-119
static void t1_check_unusual_charstring(void) { char *p = strstr(t1_line_array, charstringname) + strlen(charstringname); int i; /* if no number follows "/CharStrings", let's read the next line */ if (sscanf(p, "%i", &i) != 1) { /* pdftex_warn("no number found after `%s', I assume it's on the next line", charstringname); */ strcpy(t1_buf_array, t1_line_array); /* t1_getline always appends EOL to t1_line_array; let's change it to * space before appending the next line */ *(strend(t1_buf_array) - 1) = ' '; t1_getline(); alloc_array(t1_buf, strlen(t1_line_array) + strlen(t1_buf_array) + 1, T1_BUF_SIZE); strcat(t1_buf_array, t1_line_array); alloc_array(t1_line, strlen(t1_buf_array) + 1, T1_BUF_SIZE); strcpy(t1_line_array, t1_buf_array); t1_line_ptr = eol(t1_line_array); } }
169,020
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t CameraDeviceClient::dump(int fd, const Vector<String16>& args) { String8 result; result.appendFormat("CameraDeviceClient[%d] (%p) PID: %d, dump:\n", mCameraId, getRemoteCallback()->asBinder().get(), mClientPid); result.append(" State: "); mFrameProcessor->dump(fd, args); return dumpDevice(fd, args); } Commit Message: Camera: Disallow dumping clients directly Camera service dumps should only be initiated through ICameraService::dump. Bug: 26265403 Change-Id: If3ca4718ed74bf33ad8a416192689203029e2803 CWE ID: CWE-264
status_t CameraDeviceClient::dump(int fd, const Vector<String16>& args) { return BasicClient::dump(fd, args); } status_t CameraDeviceClient::dumpClient(int fd, const Vector<String16>& args) { String8 result; result.appendFormat("CameraDeviceClient[%d] (%p) PID: %d, dump:\n", mCameraId, getRemoteCallback()->asBinder().get(), mClientPid); result.append(" State: "); mFrameProcessor->dump(fd, args); return dumpDevice(fd, args); }
173,939
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char *argv[]) { libettercap_init(); ef_globals_alloc(); select_text_interface(); libettercap_ui_init(); /* etterfilter copyright */ fprintf(stdout, "\n" EC_COLOR_BOLD "%s %s" EC_COLOR_END " copyright %s %s\n\n", PROGRAM, EC_VERSION, EC_COPYRIGHT, EC_AUTHORS); /* initialize the line number */ EF_GBL->lineno = 1; /* getopt related parsing... */ parse_options(argc, argv); /* set the input for source file */ if (EF_GBL_OPTIONS->source_file) { yyin = fopen(EF_GBL_OPTIONS->source_file, "r"); if (yyin == NULL) FATAL_ERROR("Input file not found !"); } else { FATAL_ERROR("No source file."); } /* no buffering */ setbuf(yyin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); /* load the tables in etterfilter.tbl */ load_tables(); /* load the constants in etterfilter.cnt */ load_constants(); /* print the message */ fprintf(stdout, "\n Parsing source file \'%s\' ", EF_GBL_OPTIONS->source_file); fflush(stdout); ef_debug(1, "\n"); /* begin the parsing */ if (yyparse() == 0) fprintf(stdout, " done.\n\n"); else fprintf(stdout, "\n\nThe script contains errors...\n\n"); /* write to file */ if (write_output() != E_SUCCESS) FATAL_ERROR("Cannot write output file (%s)", EF_GBL_OPTIONS->output_file); ef_globals_free(); return 0; } Commit Message: Exit gracefully in case of corrupted filters (Closes issue #782) CWE ID: CWE-125
int main(int argc, char *argv[]) { int ret_value = 0; libettercap_init(); ef_globals_alloc(); select_text_interface(); libettercap_ui_init(); /* etterfilter copyright */ fprintf(stdout, "\n" EC_COLOR_BOLD "%s %s" EC_COLOR_END " copyright %s %s\n\n", PROGRAM, EC_VERSION, EC_COPYRIGHT, EC_AUTHORS); /* initialize the line number */ EF_GBL->lineno = 1; /* getopt related parsing... */ parse_options(argc, argv); /* set the input for source file */ if (EF_GBL_OPTIONS->source_file) { yyin = fopen(EF_GBL_OPTIONS->source_file, "r"); if (yyin == NULL) FATAL_ERROR("Input file not found !"); } else { FATAL_ERROR("No source file."); } /* no buffering */ setbuf(yyin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); /* load the tables in etterfilter.tbl */ load_tables(); /* load the constants in etterfilter.cnt */ load_constants(); /* print the message */ fprintf(stdout, "\n Parsing source file \'%s\' ", EF_GBL_OPTIONS->source_file); fflush(stdout); ef_debug(1, "\n"); /* begin the parsing */ if (yyparse() == 0) fprintf(stdout, " done.\n\n"); else fprintf(stdout, "\n\nThe script contains errors...\n\n"); /* write to file */ ret_value = write_output(); if (ret_value == -E_NOTHANDLED) FATAL_ERROR("Cannot write output file (%s): the filter is not correctly handled.", EF_GBL_OPTIONS->output_file); else if (ret_value == -E_INVALID) FATAL_ERROR("Cannot write output file (%s): the filter format is not correct. ", EF_GBL_OPTIONS->output_file); ef_globals_free(); return 0; }
168,337
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int encode_msg(struct sip_msg *msg,char *payload,int len) { int i,j,k,u,request; unsigned short int h; struct hdr_field* hf; struct msg_start* ms; struct sip_uri miuri; char *myerror=NULL; ptrdiff_t diff; if(len < MAX_ENCODED_MSG + MAX_MESSAGE_LEN) return -1; if(parse_headers(msg,HDR_EOH_F,0)<0){ myerror="in parse_headers"; goto error; } memset(payload,0,len); ms=&msg->first_line; if(ms->type == SIP_REQUEST) request=1; else if(ms->type == SIP_REPLY) request=0; else{ myerror="message is neither request nor response"; goto error; } if(request) { for(h=0;h<32;j=(0x01<<h),h++) if(j & ms->u.request.method_value) break; } else { h=(unsigned short)(ms->u.reply.statuscode); } if(h==32){/*statuscode wont be 32...*/ myerror="unknown message type\n"; goto error; } h=htons(h); /*first goes the message code type*/ memcpy(payload,&h,2); h=htons((unsigned short int)msg->len); /*then goes the message start idx, but we'll put it later*/ /*then goes the message length (we hope it to be less than 65535 bytes...)*/ memcpy(&payload[MSG_LEN_IDX],&h,2); /*then goes the content start index (starting from SIP MSG START)*/ if(0>(diff=(get_body(msg)-(msg->buf)))){ myerror="body starts before the message (uh ?)"; goto error; }else h=htons((unsigned short int)diff); memcpy(payload+CONTENT_IDX,&h,2); payload[METHOD_CODE_IDX]=(unsigned char)(request? (ms->u.request.method.s-msg->buf): (ms->u.reply.status.s-msg->buf)); payload[METHOD_CODE_IDX+1]=(unsigned char)(request? (ms->u.request.method.len): (ms->u.reply.status.len)); payload[URI_REASON_IDX]=(unsigned char)(request? (ms->u.request.uri.s-msg->buf): (ms->u.reply.reason.s-msg->buf)); payload[URI_REASON_IDX+1]=(unsigned char)(request? (ms->u.request.uri.len): (ms->u.reply.reason.len)); payload[VERSION_IDX]=(unsigned char)(request? (ms->u.request.version.s-msg->buf): (ms->u.reply.version.s-msg->buf)); if(request){ if (parse_uri(ms->u.request.uri.s,ms->u.request.uri.len, &miuri)<0){ LM_ERR("<%.*s>\n",ms->u.request.uri.len,ms->u.request.uri.s); myerror="while parsing the R-URI"; goto error; } if(0>(j=encode_uri2(msg->buf, ms->u.request.method.s-msg->buf+ms->len, ms->u.request.uri,&miuri, (unsigned char*)&payload[REQUEST_URI_IDX+1]))) { myerror="ENCODE_MSG: ERROR while encoding the R-URI"; goto error; } payload[REQUEST_URI_IDX]=(unsigned char)j; k=REQUEST_URI_IDX+1+j; }else k=REQUEST_URI_IDX; u=k; k++; for(i=0,hf=msg->headers;hf;hf=hf->next,i++); i++;/*we do as if there was an extra header, that marks the end of the previous header in the headers hashtable(read below)*/ j=k+3*i; for(i=0,hf=msg->headers;hf;hf=hf->next,k+=3){ payload[k]=(unsigned char)(hf->type & 0xFF); h=htons(j); /*now goes a payload-based-ptr to where the header-code starts*/ memcpy(&payload[k+1],&h,2); /*TODO fix this... fixed with k-=3?*/ if(0>(i=encode_header(msg,hf,(unsigned char*)(payload+j),MAX_ENCODED_MSG+MAX_MESSAGE_LEN-j))){ LM_ERR("encoding header %.*s\n",hf->name.len,hf->name.s); goto error; k-=3; continue; } j+=(unsigned short int)i; } /*now goes the number of headers that have been found, right after the meta-msg-section*/ payload[u]=(unsigned char)((k-u-1)/3); j=htons(j); /*now copy the number of bytes that the headers-meta-section has occupied,right afther * headers-meta-section(the array with ['v',[2:where],'r',[2:where],'R',[2:where],...] * this is to know where the LAST header ends, since the length of each header-struct * is calculated substracting the nextHeaderStart - presentHeaderStart * the k+1 is because payload[k] is usually the letter*/ memcpy(&payload[k+1],&j,2); k+=3; j=ntohs(j); /*now we copy the headers-meta-section after the msg-headers-meta-section*/ /*memcpy(&payload[k],payload2,j);*/ /*j+=k;*/ /*pkg_free(payload2);*/ /*now we copy the actual message after the headers-meta-section*/ memcpy(&payload[j],msg->buf,msg->len); LM_DBG("msglen = %d,msg starts at %d\n",msg->len,j); j=htons(j); /*now we copy at the beginning, the index to where the actual message starts*/ memcpy(&payload[MSG_START_IDX],&j,2); return GET_PAY_SIZE( payload ); error: LM_ERR("%s\n",myerror); return -1; } Commit Message: seas: safety check for target buffer size before copying message in encode_msg() - avoid buffer overflow for large SIP messages - reported by Stelios Tsampas CWE ID: CWE-119
int encode_msg(struct sip_msg *msg,char *payload,int len) { int i,j,k,u,request; unsigned short int h; struct hdr_field* hf; struct msg_start* ms; struct sip_uri miuri; char *myerror=NULL; ptrdiff_t diff; if(len < MAX_ENCODED_MSG + MAX_MESSAGE_LEN) return -1; if(parse_headers(msg,HDR_EOH_F,0)<0){ myerror="in parse_headers"; goto error; } memset(payload,0,len); ms=&msg->first_line; if(ms->type == SIP_REQUEST) request=1; else if(ms->type == SIP_REPLY) request=0; else{ myerror="message is neither request nor response"; goto error; } if(request) { for(h=0;h<32;j=(0x01<<h),h++) if(j & ms->u.request.method_value) break; } else { h=(unsigned short)(ms->u.reply.statuscode); } if(h==32){/*statuscode wont be 32...*/ myerror="unknown message type\n"; goto error; } h=htons(h); /*first goes the message code type*/ memcpy(payload,&h,2); h=htons((unsigned short int)msg->len); /*then goes the message start idx, but we'll put it later*/ /*then goes the message length (we hope it to be less than 65535 bytes...)*/ memcpy(&payload[MSG_LEN_IDX],&h,2); /*then goes the content start index (starting from SIP MSG START)*/ if(0>(diff=(get_body(msg)-(msg->buf)))){ myerror="body starts before the message (uh ?)"; goto error; }else h=htons((unsigned short int)diff); memcpy(payload+CONTENT_IDX,&h,2); payload[METHOD_CODE_IDX]=(unsigned char)(request? (ms->u.request.method.s-msg->buf): (ms->u.reply.status.s-msg->buf)); payload[METHOD_CODE_IDX+1]=(unsigned char)(request? (ms->u.request.method.len): (ms->u.reply.status.len)); payload[URI_REASON_IDX]=(unsigned char)(request? (ms->u.request.uri.s-msg->buf): (ms->u.reply.reason.s-msg->buf)); payload[URI_REASON_IDX+1]=(unsigned char)(request? (ms->u.request.uri.len): (ms->u.reply.reason.len)); payload[VERSION_IDX]=(unsigned char)(request? (ms->u.request.version.s-msg->buf): (ms->u.reply.version.s-msg->buf)); if(request){ if (parse_uri(ms->u.request.uri.s,ms->u.request.uri.len, &miuri)<0){ LM_ERR("<%.*s>\n",ms->u.request.uri.len,ms->u.request.uri.s); myerror="while parsing the R-URI"; goto error; } if(0>(j=encode_uri2(msg->buf, ms->u.request.method.s-msg->buf+ms->len, ms->u.request.uri,&miuri, (unsigned char*)&payload[REQUEST_URI_IDX+1]))) { myerror="ENCODE_MSG: ERROR while encoding the R-URI"; goto error; } payload[REQUEST_URI_IDX]=(unsigned char)j; k=REQUEST_URI_IDX+1+j; }else k=REQUEST_URI_IDX; u=k; k++; for(i=0,hf=msg->headers;hf;hf=hf->next,i++); i++;/*we do as if there was an extra header, that marks the end of the previous header in the headers hashtable(read below)*/ j=k+3*i; for(i=0,hf=msg->headers;hf;hf=hf->next,k+=3){ payload[k]=(unsigned char)(hf->type & 0xFF); h=htons(j); /*now goes a payload-based-ptr to where the header-code starts*/ memcpy(&payload[k+1],&h,2); /*TODO fix this... fixed with k-=3?*/ if(0>(i=encode_header(msg,hf,(unsigned char*)(payload+j),MAX_ENCODED_MSG+MAX_MESSAGE_LEN-j))){ LM_ERR("encoding header %.*s\n",hf->name.len,hf->name.s); goto error; k-=3; continue; } j+=(unsigned short int)i; } /*now goes the number of headers that have been found, right after the meta-msg-section*/ payload[u]=(unsigned char)((k-u-1)/3); j=htons(j); /*now copy the number of bytes that the headers-meta-section has occupied,right afther * headers-meta-section(the array with ['v',[2:where],'r',[2:where],'R',[2:where],...] * this is to know where the LAST header ends, since the length of each header-struct * is calculated substracting the nextHeaderStart - presentHeaderStart * the k+1 is because payload[k] is usually the letter*/ memcpy(&payload[k+1],&j,2); k+=3; j=ntohs(j); /*now we copy the headers-meta-section after the msg-headers-meta-section*/ /*memcpy(&payload[k],payload2,j);*/ /*j+=k;*/ /*pkg_free(payload2);*/ /*now we copy the actual message after the headers-meta-section*/ if(len < j + msg->len + 1) { LM_ERR("not enough space to encode sip message\n"); return -1; } memcpy(&payload[j],msg->buf,msg->len); LM_DBG("msglen = %d,msg starts at %d\n",msg->len,j); j=htons(j); /*now we copy at the beginning, the index to where the actual message starts*/ memcpy(&payload[MSG_START_IDX],&j,2); return GET_PAY_SIZE( payload ); error: LM_ERR("%s\n",myerror); return -1; }
167,411
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: m_authenticate(struct Client *client_p, struct Client *source_p, int parc, const char *parv[]) { struct Client *agent_p = NULL; struct Client *saslserv_p = NULL; /* They really should use CAP for their own sake. */ if(!IsCapable(source_p, CLICAP_SASL)) return 0; if (strlen(client_p->id) == 3) { exit_client(client_p, client_p, client_p, "Mixing client and server protocol"); return 0; } saslserv_p = find_named_client(ConfigFileEntry.sasl_service); if (saslserv_p == NULL || !IsService(saslserv_p)) { sendto_one(source_p, form_str(ERR_SASLABORTED), me.name, EmptyString(source_p->name) ? "*" : source_p->name); return 0; } if(source_p->localClient->sasl_complete) { *source_p->localClient->sasl_agent = '\0'; source_p->localClient->sasl_complete = 0; } if(strlen(parv[1]) > 400) { sendto_one(source_p, form_str(ERR_SASLTOOLONG), me.name, EmptyString(source_p->name) ? "*" : source_p->name); return 0; } if(!*source_p->id) { /* Allocate a UID. */ strcpy(source_p->id, generate_uid()); add_to_id_hash(source_p->id, source_p); } if(*source_p->localClient->sasl_agent) agent_p = find_id(source_p->localClient->sasl_agent); if(agent_p == NULL) { sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s H %s %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, source_p->host, source_p->sockhost); if (!strcmp(parv[1], "EXTERNAL") && source_p->certfp != NULL) sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s S %s %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, parv[1], source_p->certfp); else sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s S %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, parv[1]); rb_strlcpy(source_p->localClient->sasl_agent, saslserv_p->id, IDLEN); } else sendto_one(agent_p, ":%s ENCAP %s SASL %s %s C %s", me.id, agent_p->servptr->name, source_p->id, agent_p->id, parv[1]); source_p->localClient->sasl_out++; return 0; } Commit Message: SASL: Disallow beginning : and space anywhere in AUTHENTICATE parameter This is a FIX FOR A SECURITY VULNERABILITY. All Charybdis users must apply this fix if you support SASL on your servers, or unload m_sasl.so in the meantime. CWE ID: CWE-285
m_authenticate(struct Client *client_p, struct Client *source_p, int parc, const char *parv[]) { struct Client *agent_p = NULL; struct Client *saslserv_p = NULL; /* They really should use CAP for their own sake. */ if(!IsCapable(source_p, CLICAP_SASL)) return 0; if (strlen(client_p->id) == 3) { exit_client(client_p, client_p, client_p, "Mixing client and server protocol"); return 0; } if (*parv[1] == ':' || strchr(parv[1], ' ')) { exit_client(client_p, client_p, client_p, "Malformed AUTHENTICATE"); return 0; } saslserv_p = find_named_client(ConfigFileEntry.sasl_service); if (saslserv_p == NULL || !IsService(saslserv_p)) { sendto_one(source_p, form_str(ERR_SASLABORTED), me.name, EmptyString(source_p->name) ? "*" : source_p->name); return 0; } if(source_p->localClient->sasl_complete) { *source_p->localClient->sasl_agent = '\0'; source_p->localClient->sasl_complete = 0; } if(strlen(parv[1]) > 400) { sendto_one(source_p, form_str(ERR_SASLTOOLONG), me.name, EmptyString(source_p->name) ? "*" : source_p->name); return 0; } if(!*source_p->id) { /* Allocate a UID. */ strcpy(source_p->id, generate_uid()); add_to_id_hash(source_p->id, source_p); } if(*source_p->localClient->sasl_agent) agent_p = find_id(source_p->localClient->sasl_agent); if(agent_p == NULL) { sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s H %s %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, source_p->host, source_p->sockhost); if (!strcmp(parv[1], "EXTERNAL") && source_p->certfp != NULL) sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s S %s %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, parv[1], source_p->certfp); else sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s S %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, parv[1]); rb_strlcpy(source_p->localClient->sasl_agent, saslserv_p->id, IDLEN); } else sendto_one(agent_p, ":%s ENCAP %s SASL %s %s C %s", me.id, agent_p->servptr->name, source_p->id, agent_p->id, parv[1]); source_p->localClient->sasl_out++; return 0; }
166,944
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool Performance::PassesTimingAllowCheck( const ResourceResponse& response, const SecurityOrigin& initiator_security_origin, const AtomicString& original_timing_allow_origin, ExecutionContext* context) { scoped_refptr<const SecurityOrigin> resource_origin = SecurityOrigin::Create(response.Url()); if (resource_origin->IsSameSchemeHostPort(&initiator_security_origin)) return true; const AtomicString& timing_allow_origin_string = original_timing_allow_origin.IsEmpty() ? response.HttpHeaderField(HTTPNames::Timing_Allow_Origin) : original_timing_allow_origin; if (timing_allow_origin_string.IsEmpty() || EqualIgnoringASCIICase(timing_allow_origin_string, "null")) return false; if (timing_allow_origin_string == "*") { UseCounter::Count(context, WebFeature::kStarInTimingAllowOrigin); return true; } const String& security_origin = initiator_security_origin.ToString(); Vector<String> timing_allow_origins; timing_allow_origin_string.GetString().Split(',', timing_allow_origins); if (timing_allow_origins.size() > 1) { UseCounter::Count(context, WebFeature::kMultipleOriginsInTimingAllowOrigin); } else if (timing_allow_origins.size() == 1 && timing_allow_origin_string != "*") { UseCounter::Count(context, WebFeature::kSingleOriginInTimingAllowOrigin); } for (const String& allow_origin : timing_allow_origins) { const String allow_origin_stripped = allow_origin.StripWhiteSpace(); if (allow_origin_stripped == security_origin || allow_origin_stripped == "*") { return true; } } return false; } Commit Message: Fix timing allow check algorithm for service workers This CL uses the OriginalURLViaServiceWorker() in the timing allow check algorithm if the response WasFetchedViaServiceWorker(). This way, if a service worker changes a same origin request to become cross origin, then the timing allow check algorithm will still fail. resource-timing-worker.js is changed so it avoids an empty Response, which is an odd case in terms of same origin checks. Bug: 837275 Change-Id: I7e497a6fcc2ee14244121b915ca5f5cceded417a Reviewed-on: https://chromium-review.googlesource.com/1038229 Commit-Queue: Nicolás Peña Moreno <[email protected]> Reviewed-by: Yoav Weiss <[email protected]> Reviewed-by: Timothy Dresser <[email protected]> Cr-Commit-Position: refs/heads/master@{#555476} CWE ID: CWE-200
bool Performance::PassesTimingAllowCheck( const ResourceResponse& response, const SecurityOrigin& initiator_security_origin, const AtomicString& original_timing_allow_origin, ExecutionContext* context) { const KURL& response_url = response.WasFetchedViaServiceWorker() ? response.OriginalURLViaServiceWorker() : response.Url(); scoped_refptr<const SecurityOrigin> resource_origin = SecurityOrigin::Create(response_url); if (resource_origin->IsSameSchemeHostPort(&initiator_security_origin)) return true; const AtomicString& timing_allow_origin_string = original_timing_allow_origin.IsEmpty() ? response.HttpHeaderField(HTTPNames::Timing_Allow_Origin) : original_timing_allow_origin; if (timing_allow_origin_string.IsEmpty() || EqualIgnoringASCIICase(timing_allow_origin_string, "null")) return false; if (timing_allow_origin_string == "*") { UseCounter::Count(context, WebFeature::kStarInTimingAllowOrigin); return true; } const String& security_origin = initiator_security_origin.ToString(); Vector<String> timing_allow_origins; timing_allow_origin_string.GetString().Split(',', timing_allow_origins); if (timing_allow_origins.size() > 1) { UseCounter::Count(context, WebFeature::kMultipleOriginsInTimingAllowOrigin); } else if (timing_allow_origins.size() == 1 && timing_allow_origin_string != "*") { UseCounter::Count(context, WebFeature::kSingleOriginInTimingAllowOrigin); } for (const String& allow_origin : timing_allow_origins) { const String allow_origin_stripped = allow_origin.StripWhiteSpace(); if (allow_origin_stripped == security_origin || allow_origin_stripped == "*") { return true; } } return false; }
173,143
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void NavigationRequest::OnRequestRedirected( const net::RedirectInfo& redirect_info, const scoped_refptr<network::ResourceResponse>& response) { response_ = response; ssl_info_ = response->head.ssl_info; #if defined(OS_ANDROID) base::WeakPtr<NavigationRequest> this_ptr(weak_factory_.GetWeakPtr()); bool should_override_url_loading = false; if (!GetContentClient()->browser()->ShouldOverrideUrlLoading( frame_tree_node_->frame_tree_node_id(), browser_initiated_, redirect_info.new_url, redirect_info.new_method, false, true, frame_tree_node_->IsMainFrame(), common_params_.transition, &should_override_url_loading)) { return; } if (!this_ptr) return; if (should_override_url_loading) { navigation_handle_->set_net_error_code(net::ERR_ABORTED); common_params_.url = redirect_info.new_url; common_params_.method = redirect_info.new_method; navigation_handle_->UpdateStateFollowingRedirect( GURL(redirect_info.new_referrer), base::Bind(&NavigationRequest::OnRedirectChecksComplete, base::Unretained(this))); frame_tree_node_->ResetNavigationRequest(false, true); return; } #endif if (!ChildProcessSecurityPolicyImpl::GetInstance()->CanRedirectToURL( redirect_info.new_url)) { DVLOG(1) << "Denied redirect for " << redirect_info.new_url.possibly_invalid_spec(); navigation_handle_->set_net_error_code(net::ERR_UNSAFE_REDIRECT); frame_tree_node_->ResetNavigationRequest(false, true); return; } if (!browser_initiated_ && source_site_instance() && !ChildProcessSecurityPolicyImpl::GetInstance()->CanRequestURL( source_site_instance()->GetProcess()->GetID(), redirect_info.new_url)) { DVLOG(1) << "Denied unauthorized redirect for " << redirect_info.new_url.possibly_invalid_spec(); navigation_handle_->set_net_error_code(net::ERR_UNSAFE_REDIRECT); frame_tree_node_->ResetNavigationRequest(false, true); return; } if (redirect_info.new_method != "POST") common_params_.post_data = nullptr; if (commit_params_.navigation_timing.redirect_start.is_null()) { commit_params_.navigation_timing.redirect_start = commit_params_.navigation_timing.fetch_start; } commit_params_.navigation_timing.redirect_end = base::TimeTicks::Now(); commit_params_.navigation_timing.fetch_start = base::TimeTicks::Now(); commit_params_.redirect_response.push_back(response->head); commit_params_.redirect_infos.push_back(redirect_info); if (commit_params_.origin_to_commit) commit_params_.origin_to_commit.reset(); commit_params_.redirects.push_back(common_params_.url); common_params_.url = redirect_info.new_url; common_params_.method = redirect_info.new_method; common_params_.referrer.url = GURL(redirect_info.new_referrer); common_params_.referrer = Referrer::SanitizeForRequest(common_params_.url, common_params_.referrer); net::Error net_error = CheckContentSecurityPolicy(true /* has_followed_redirect */, redirect_info.insecure_scheme_was_upgraded, false /* is_response_check */); if (net_error != net::OK) { OnRequestFailedInternal( network::URLLoaderCompletionStatus(net_error), false /*skip_throttles*/, base::nullopt /*error_page_content*/, false /*collapse_frame*/); return; } if (CheckCredentialedSubresource() == CredentialedSubresourceCheckResult::BLOCK_REQUEST || CheckLegacyProtocolInSubresource() == LegacyProtocolInSubresourceCheckResult::BLOCK_REQUEST) { OnRequestFailedInternal( network::URLLoaderCompletionStatus(net::ERR_ABORTED), false /*skip_throttles*/, base::nullopt /*error_page_content*/, false /*collapse_frame*/); return; } scoped_refptr<SiteInstance> site_instance = frame_tree_node_->render_manager()->GetSiteInstanceForNavigationRequest( *this); speculative_site_instance_ = site_instance->HasProcess() ? site_instance : nullptr; if (!site_instance->HasProcess()) { RenderProcessHostImpl::NotifySpareManagerAboutRecentlyUsedBrowserContext( site_instance->GetBrowserContext()); } common_params_.previews_state = GetContentClient()->browser()->DetermineAllowedPreviews( common_params_.previews_state, navigation_handle_.get(), common_params_.url); RenderProcessHost* expected_process = site_instance->HasProcess() ? site_instance->GetProcess() : nullptr; navigation_handle_->WillRedirectRequest( common_params_.referrer.url, expected_process, base::Bind(&NavigationRequest::OnRedirectChecksComplete, base::Unretained(this))); } Commit Message: Show an error page if a URL redirects to a javascript: URL. BUG=935175 Change-Id: Id4a9198d5dff823bc3d324b9de9bff2ee86dc499 Reviewed-on: https://chromium-review.googlesource.com/c/1488152 Commit-Queue: Charlie Reis <[email protected]> Reviewed-by: Arthur Sonzogni <[email protected]> Cr-Commit-Position: refs/heads/master@{#635848} CWE ID: CWE-20
void NavigationRequest::OnRequestRedirected( const net::RedirectInfo& redirect_info, const scoped_refptr<network::ResourceResponse>& response) { response_ = response; ssl_info_ = response->head.ssl_info; #if defined(OS_ANDROID) base::WeakPtr<NavigationRequest> this_ptr(weak_factory_.GetWeakPtr()); bool should_override_url_loading = false; if (!GetContentClient()->browser()->ShouldOverrideUrlLoading( frame_tree_node_->frame_tree_node_id(), browser_initiated_, redirect_info.new_url, redirect_info.new_method, false, true, frame_tree_node_->IsMainFrame(), common_params_.transition, &should_override_url_loading)) { return; } if (!this_ptr) return; if (should_override_url_loading) { navigation_handle_->set_net_error_code(net::ERR_ABORTED); common_params_.url = redirect_info.new_url; common_params_.method = redirect_info.new_method; navigation_handle_->UpdateStateFollowingRedirect( GURL(redirect_info.new_referrer), base::Bind(&NavigationRequest::OnRedirectChecksComplete, base::Unretained(this))); frame_tree_node_->ResetNavigationRequest(false, true); return; } #endif if (!ChildProcessSecurityPolicyImpl::GetInstance()->CanRedirectToURL( redirect_info.new_url)) { DVLOG(1) << "Denied redirect for " << redirect_info.new_url.possibly_invalid_spec(); // Show an error page rather than leaving the previous page in place. OnRequestFailedInternal( network::URLLoaderCompletionStatus(net::ERR_UNSAFE_REDIRECT), false /* skip_throttles */, base::nullopt /* error_page_content */, false /* collapse_frame */); // DO NOT ADD CODE after this. The previous call to OnRequestFailedInternal // has destroyed the NavigationRequest. return; } if (!browser_initiated_ && source_site_instance() && !ChildProcessSecurityPolicyImpl::GetInstance()->CanRequestURL( source_site_instance()->GetProcess()->GetID(), redirect_info.new_url)) { DVLOG(1) << "Denied unauthorized redirect for " << redirect_info.new_url.possibly_invalid_spec(); // Show an error page rather than leaving the previous page in place. OnRequestFailedInternal( network::URLLoaderCompletionStatus(net::ERR_UNSAFE_REDIRECT), false /* skip_throttles */, base::nullopt /* error_page_content */, false /* collapse_frame */); // DO NOT ADD CODE after this. The previous call to OnRequestFailedInternal // has destroyed the NavigationRequest. return; } if (redirect_info.new_method != "POST") common_params_.post_data = nullptr; if (commit_params_.navigation_timing.redirect_start.is_null()) { commit_params_.navigation_timing.redirect_start = commit_params_.navigation_timing.fetch_start; } commit_params_.navigation_timing.redirect_end = base::TimeTicks::Now(); commit_params_.navigation_timing.fetch_start = base::TimeTicks::Now(); commit_params_.redirect_response.push_back(response->head); commit_params_.redirect_infos.push_back(redirect_info); if (commit_params_.origin_to_commit) commit_params_.origin_to_commit.reset(); commit_params_.redirects.push_back(common_params_.url); common_params_.url = redirect_info.new_url; common_params_.method = redirect_info.new_method; common_params_.referrer.url = GURL(redirect_info.new_referrer); common_params_.referrer = Referrer::SanitizeForRequest(common_params_.url, common_params_.referrer); net::Error net_error = CheckContentSecurityPolicy(true /* has_followed_redirect */, redirect_info.insecure_scheme_was_upgraded, false /* is_response_check */); if (net_error != net::OK) { OnRequestFailedInternal( network::URLLoaderCompletionStatus(net_error), false /*skip_throttles*/, base::nullopt /*error_page_content*/, false /*collapse_frame*/); return; } if (CheckCredentialedSubresource() == CredentialedSubresourceCheckResult::BLOCK_REQUEST || CheckLegacyProtocolInSubresource() == LegacyProtocolInSubresourceCheckResult::BLOCK_REQUEST) { OnRequestFailedInternal( network::URLLoaderCompletionStatus(net::ERR_ABORTED), false /*skip_throttles*/, base::nullopt /*error_page_content*/, false /*collapse_frame*/); return; } scoped_refptr<SiteInstance> site_instance = frame_tree_node_->render_manager()->GetSiteInstanceForNavigationRequest( *this); speculative_site_instance_ = site_instance->HasProcess() ? site_instance : nullptr; if (!site_instance->HasProcess()) { RenderProcessHostImpl::NotifySpareManagerAboutRecentlyUsedBrowserContext( site_instance->GetBrowserContext()); } common_params_.previews_state = GetContentClient()->browser()->DetermineAllowedPreviews( common_params_.previews_state, navigation_handle_.get(), common_params_.url); RenderProcessHost* expected_process = site_instance->HasProcess() ? site_instance->GetProcess() : nullptr; navigation_handle_->WillRedirectRequest( common_params_.referrer.url, expected_process, base::Bind(&NavigationRequest::OnRedirectChecksComplete, base::Unretained(this))); }
173,034
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char **argv) { FILE *infile = NULL; vpx_codec_ctx_t codec; vpx_codec_enc_cfg_t cfg; int frame_count = 0; vpx_image_t raw; vpx_codec_err_t res; VpxVideoInfo info = {0}; VpxVideoWriter *writer = NULL; const VpxInterface *encoder = NULL; const int fps = 30; // TODO(dkovalev) add command line argument const int bitrate = 200; // kbit/s TODO(dkovalev) add command line argument int keyframe_interval = 0; const char *codec_arg = NULL; const char *width_arg = NULL; const char *height_arg = NULL; const char *infile_arg = NULL; const char *outfile_arg = NULL; const char *keyframe_interval_arg = NULL; exec_name = argv[0]; if (argc < 7) die("Invalid number of arguments"); codec_arg = argv[1]; width_arg = argv[2]; height_arg = argv[3]; infile_arg = argv[4]; outfile_arg = argv[5]; keyframe_interval_arg = argv[6]; encoder = get_vpx_encoder_by_name(codec_arg); if (!encoder) die("Unsupported codec."); info.codec_fourcc = encoder->fourcc; info.frame_width = strtol(width_arg, NULL, 0); info.frame_height = strtol(height_arg, NULL, 0); info.time_base.numerator = 1; info.time_base.denominator = fps; if (info.frame_width <= 0 || info.frame_height <= 0 || (info.frame_width % 2) != 0 || (info.frame_height % 2) != 0) { die("Invalid frame size: %dx%d", info.frame_width, info.frame_height); } if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, info.frame_width, info.frame_height, 1)) { die("Failed to allocate image."); } keyframe_interval = strtol(keyframe_interval_arg, NULL, 0); if (keyframe_interval < 0) die("Invalid keyframe interval value."); printf("Using %s\n", vpx_codec_iface_name(encoder->interface())); res = vpx_codec_enc_config_default(encoder->interface(), &cfg, 0); if (res) die_codec(&codec, "Failed to get default codec config."); cfg.g_w = info.frame_width; cfg.g_h = info.frame_height; cfg.g_timebase.num = info.time_base.numerator; cfg.g_timebase.den = info.time_base.denominator; cfg.rc_target_bitrate = bitrate; cfg.g_error_resilient = argc > 7 ? strtol(argv[7], NULL, 0) : 0; writer = vpx_video_writer_open(outfile_arg, kContainerIVF, &info); if (!writer) die("Failed to open %s for writing.", outfile_arg); if (!(infile = fopen(infile_arg, "rb"))) die("Failed to open %s for reading.", infile_arg); if (vpx_codec_enc_init(&codec, encoder->interface(), &cfg, 0)) die_codec(&codec, "Failed to initialize encoder"); while (vpx_img_read(&raw, infile)) { int flags = 0; if (keyframe_interval > 0 && frame_count % keyframe_interval == 0) flags |= VPX_EFLAG_FORCE_KF; encode_frame(&codec, &raw, frame_count++, flags, writer); } encode_frame(&codec, NULL, -1, 0, writer); // flush the encoder printf("\n"); fclose(infile); printf("Processed %d frames.\n", frame_count); vpx_img_free(&raw); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec."); vpx_video_writer_close(writer); return EXIT_SUCCESS; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
int main(int argc, char **argv) { FILE *infile = NULL; vpx_codec_ctx_t codec; vpx_codec_enc_cfg_t cfg; int frame_count = 0; vpx_image_t raw; vpx_codec_err_t res; VpxVideoInfo info = {0}; VpxVideoWriter *writer = NULL; const VpxInterface *encoder = NULL; const int fps = 30; // TODO(dkovalev) add command line argument const int bitrate = 200; // kbit/s TODO(dkovalev) add command line argument int keyframe_interval = 0; const char *codec_arg = NULL; const char *width_arg = NULL; const char *height_arg = NULL; const char *infile_arg = NULL; const char *outfile_arg = NULL; const char *keyframe_interval_arg = NULL; exec_name = argv[0]; if (argc < 7) die("Invalid number of arguments"); codec_arg = argv[1]; width_arg = argv[2]; height_arg = argv[3]; infile_arg = argv[4]; outfile_arg = argv[5]; keyframe_interval_arg = argv[6]; encoder = get_vpx_encoder_by_name(codec_arg); if (!encoder) die("Unsupported codec."); info.codec_fourcc = encoder->fourcc; info.frame_width = strtol(width_arg, NULL, 0); info.frame_height = strtol(height_arg, NULL, 0); info.time_base.numerator = 1; info.time_base.denominator = fps; if (info.frame_width <= 0 || info.frame_height <= 0 || (info.frame_width % 2) != 0 || (info.frame_height % 2) != 0) { die("Invalid frame size: %dx%d", info.frame_width, info.frame_height); } if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, info.frame_width, info.frame_height, 1)) { die("Failed to allocate image."); } keyframe_interval = strtol(keyframe_interval_arg, NULL, 0); if (keyframe_interval < 0) die("Invalid keyframe interval value."); printf("Using %s\n", vpx_codec_iface_name(encoder->codec_interface())); res = vpx_codec_enc_config_default(encoder->codec_interface(), &cfg, 0); if (res) die_codec(&codec, "Failed to get default codec config."); cfg.g_w = info.frame_width; cfg.g_h = info.frame_height; cfg.g_timebase.num = info.time_base.numerator; cfg.g_timebase.den = info.time_base.denominator; cfg.rc_target_bitrate = bitrate; cfg.g_error_resilient = argc > 7 ? strtol(argv[7], NULL, 0) : 0; writer = vpx_video_writer_open(outfile_arg, kContainerIVF, &info); if (!writer) die("Failed to open %s for writing.", outfile_arg); if (!(infile = fopen(infile_arg, "rb"))) die("Failed to open %s for reading.", infile_arg); if (vpx_codec_enc_init(&codec, encoder->codec_interface(), &cfg, 0)) die_codec(&codec, "Failed to initialize encoder"); // Encode frames. while (vpx_img_read(&raw, infile)) { int flags = 0; if (keyframe_interval > 0 && frame_count % keyframe_interval == 0) flags |= VPX_EFLAG_FORCE_KF; encode_frame(&codec, &raw, frame_count++, flags, writer); } // Flush encoder. while (encode_frame(&codec, NULL, -1, 0, writer)) {}; printf("\n"); fclose(infile); printf("Processed %d frames.\n", frame_count); vpx_img_free(&raw); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec."); vpx_video_writer_close(writer); return EXIT_SUCCESS; }
174,489
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void *listen_fn_(UNUSED_ATTR void *context) { prctl(PR_SET_NAME, (unsigned long)LISTEN_THREAD_NAME_, 0, 0, 0); listen_socket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listen_socket_ == -1) { LOG_ERROR("%s socket creation failed: %s", __func__, strerror(errno)); goto cleanup; } int enable = 1; if (setsockopt(listen_socket_, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == -1) { LOG_ERROR("%s unable to set SO_REUSEADDR: %s", __func__, strerror(errno)); goto cleanup; } struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(LOCALHOST_); addr.sin_port = htons(LISTEN_PORT_); if (bind(listen_socket_, (struct sockaddr *)&addr, sizeof(addr)) == -1) { LOG_ERROR("%s unable to bind listen socket: %s", __func__, strerror(errno)); goto cleanup; } if (listen(listen_socket_, 10) == -1) { LOG_ERROR("%s unable to listen: %s", __func__, strerror(errno)); goto cleanup; } for (;;) { int client_socket = accept(listen_socket_, NULL, NULL); if (client_socket == -1) { if (errno == EINVAL || errno == EBADF) { break; } LOG_WARN("%s error accepting socket: %s", __func__, strerror(errno)); continue; } /* When a new client connects, we have to send the btsnoop file header. This allows a decoder to treat the session as a new, valid btsnoop file. */ pthread_mutex_lock(&client_socket_lock_); safe_close_(&client_socket_); client_socket_ = client_socket; send(client_socket_, "btsnoop\0\0\0\0\1\0\0\x3\xea", 16, 0); pthread_mutex_unlock(&client_socket_lock_); } cleanup: safe_close_(&listen_socket_); return NULL; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static void *listen_fn_(UNUSED_ATTR void *context) { prctl(PR_SET_NAME, (unsigned long)LISTEN_THREAD_NAME_, 0, 0, 0); listen_socket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listen_socket_ == -1) { LOG_ERROR("%s socket creation failed: %s", __func__, strerror(errno)); goto cleanup; } int enable = 1; if (setsockopt(listen_socket_, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == -1) { LOG_ERROR("%s unable to set SO_REUSEADDR: %s", __func__, strerror(errno)); goto cleanup; } struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(LOCALHOST_); addr.sin_port = htons(LISTEN_PORT_); if (bind(listen_socket_, (struct sockaddr *)&addr, sizeof(addr)) == -1) { LOG_ERROR("%s unable to bind listen socket: %s", __func__, strerror(errno)); goto cleanup; } if (listen(listen_socket_, 10) == -1) { LOG_ERROR("%s unable to listen: %s", __func__, strerror(errno)); goto cleanup; } for (;;) { int client_socket = TEMP_FAILURE_RETRY(accept(listen_socket_, NULL, NULL)); if (client_socket == -1) { if (errno == EINVAL || errno == EBADF) { break; } LOG_WARN("%s error accepting socket: %s", __func__, strerror(errno)); continue; } /* When a new client connects, we have to send the btsnoop file header. This allows a decoder to treat the session as a new, valid btsnoop file. */ pthread_mutex_lock(&client_socket_lock_); safe_close_(&client_socket_); client_socket_ = client_socket; TEMP_FAILURE_RETRY(send(client_socket_, "btsnoop\0\0\0\0\1\0\0\x3\xea", 16, 0)); pthread_mutex_unlock(&client_socket_lock_); } cleanup: safe_close_(&listen_socket_); return NULL; }
173,475
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, const char *path, const char *mode, int options, char **opened_path, php_stream_context *context, int redirect_max, int flags STREAMS_DC TSRMLS_DC) /* {{{ */ { php_stream *stream = NULL; php_url *resource = NULL; int use_ssl; int use_proxy = 0; char *scratch = NULL; char *tmp = NULL; char *ua_str = NULL; zval **ua_zval = NULL, **tmpzval = NULL, *ssl_proxy_peer_name = NULL; int scratch_len = 0; int body = 0; char location[HTTP_HEADER_BLOCK_SIZE]; zval *response_header = NULL; int reqok = 0; char *http_header_line = NULL; char tmp_line[128]; size_t chunk_size = 0, file_size = 0; int eol_detect = 0; char *transport_string, *errstr = NULL; int transport_len, have_header = 0, request_fulluri = 0, ignore_errors = 0; char *protocol_version = NULL; int protocol_version_len = 3; /* Default: "1.0" */ struct timeval timeout; char *user_headers = NULL; int header_init = ((flags & HTTP_WRAPPER_HEADER_INIT) != 0); int redirected = ((flags & HTTP_WRAPPER_REDIRECTED) != 0); int follow_location = 1; php_stream_filter *transfer_encoding = NULL; int response_code; tmp_line[0] = '\0'; if (redirect_max < 1) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Redirection limit reached, aborting"); return NULL; } resource = php_url_parse(path); if (resource == NULL) { return NULL; } if (strncasecmp(resource->scheme, "http", sizeof("http")) && strncasecmp(resource->scheme, "https", sizeof("https"))) { if (!context || php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == FAILURE || Z_TYPE_PP(tmpzval) != IS_STRING || Z_STRLEN_PP(tmpzval) <= 0) { php_url_free(resource); return php_stream_open_wrapper_ex(path, mode, REPORT_ERRORS, NULL, context); } /* Called from a non-http wrapper with http proxying requested (i.e. ftp) */ request_fulluri = 1; use_ssl = 0; use_proxy = 1; transport_len = Z_STRLEN_PP(tmpzval); transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); } else { /* Normal http request (possibly with proxy) */ if (strpbrk(mode, "awx+")) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP wrapper does not support writeable connections"); php_url_free(resource); return NULL; } use_ssl = resource->scheme && (strlen(resource->scheme) > 4) && resource->scheme[4] == 's'; /* choose default ports */ if (use_ssl && resource->port == 0) resource->port = 443; else if (resource->port == 0) resource->port = 80; if (context && php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { use_proxy = 1; transport_len = Z_STRLEN_PP(tmpzval); transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); } else { transport_len = spprintf(&transport_string, 0, "%s://%s:%d", use_ssl ? "ssl" : "tcp", resource->host, resource->port); } } if (context && php_stream_context_get_option(context, wrapper->wops->label, "timeout", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_double_ex(tmpzval); timeout.tv_sec = (time_t) Z_DVAL_PP(tmpzval); timeout.tv_usec = (size_t) ((Z_DVAL_PP(tmpzval) - timeout.tv_sec) * 1000000); } else { timeout.tv_sec = FG(default_socket_timeout); timeout.tv_usec = 0; } stream = php_stream_xport_create(transport_string, transport_len, options, STREAM_XPORT_CLIENT | STREAM_XPORT_CONNECT, NULL, &timeout, context, &errstr, NULL); if (stream) { php_stream_set_option(stream, PHP_STREAM_OPTION_READ_TIMEOUT, 0, &timeout); } if (errstr) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "%s", errstr); efree(errstr); errstr = NULL; } efree(transport_string); if (stream && use_proxy && use_ssl) { smart_str header = {0}; /* Set peer_name or name verification will try to use the proxy server name */ if (!context || php_stream_context_get_option(context, "ssl", "peer_name", &tmpzval) == FAILURE) { MAKE_STD_ZVAL(ssl_proxy_peer_name); ZVAL_STRING(ssl_proxy_peer_name, resource->host, 1); php_stream_context_set_option(stream->context, "ssl", "peer_name", ssl_proxy_peer_name); } smart_str_appendl(&header, "CONNECT ", sizeof("CONNECT ")-1); smart_str_appends(&header, resource->host); smart_str_appendc(&header, ':'); smart_str_append_unsigned(&header, resource->port); smart_str_appendl(&header, " HTTP/1.0\r\n", sizeof(" HTTP/1.0\r\n")-1); /* check if we have Proxy-Authorization header */ if (context && php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS) { char *s, *p; if (Z_TYPE_PP(tmpzval) == IS_ARRAY) { HashPosition pos; zval **tmpheader = NULL; for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(tmpzval), &pos); SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(tmpzval), (void *)&tmpheader, &pos); zend_hash_move_forward_ex(Z_ARRVAL_PP(tmpzval), &pos)) { if (Z_TYPE_PP(tmpheader) == IS_STRING) { s = Z_STRVAL_PP(tmpheader); do { while (*s == ' ' || *s == '\t') s++; p = s; while (*p != 0 && *p != ':' && *p != '\r' && *p !='\n') p++; if (*p == ':') { p++; if (p - s == sizeof("Proxy-Authorization:") - 1 && zend_binary_strcasecmp(s, sizeof("Proxy-Authorization:") - 1, "Proxy-Authorization:", sizeof("Proxy-Authorization:") - 1) == 0) { while (*p != 0 && *p != '\r' && *p !='\n') p++; smart_str_appendl(&header, s, p - s); smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1); goto finish; } else { while (*p != 0 && *p != '\r' && *p !='\n') p++; } } s = p; while (*s == '\r' || *s == '\n') s++; } while (*s != 0); } } } else if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) { s = Z_STRVAL_PP(tmpzval); do { while (*s == ' ' || *s == '\t') s++; p = s; while (*p != 0 && *p != ':' && *p != '\r' && *p !='\n') p++; if (*p == ':') { p++; if (p - s == sizeof("Proxy-Authorization:") - 1 && zend_binary_strcasecmp(s, sizeof("Proxy-Authorization:") - 1, "Proxy-Authorization:", sizeof("Proxy-Authorization:") - 1) == 0) { while (*p != 0 && *p != '\r' && *p !='\n') p++; smart_str_appendl(&header, s, p - s); smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1); goto finish; } else { while (*p != 0 && *p != '\r' && *p !='\n') p++; } } s = p; while (*s == '\r' || *s == '\n') s++; } while (*s != 0); } } finish: smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1); if (php_stream_write(stream, header.c, header.len) != header.len) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy"); php_stream_close(stream); stream = NULL; } smart_str_free(&header); if (stream) { char header_line[HTTP_HEADER_BLOCK_SIZE]; /* get response header */ while (php_stream_gets(stream, header_line, HTTP_HEADER_BLOCK_SIZE-1) != NULL) { if (header_line[0] == '\n' || header_line[0] == '\r' || header_line[0] == '\0') { break; } } } /* enable SSL transport layer */ if (stream) { if (php_stream_xport_crypto_setup(stream, STREAM_CRYPTO_METHOD_SSLv23_CLIENT, NULL TSRMLS_CC) < 0 || php_stream_xport_crypto_enable(stream, 1 TSRMLS_CC) < 0) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy"); php_stream_close(stream); stream = NULL; } } } if (stream == NULL) goto out; /* avoid buffering issues while reading header */ if (options & STREAM_WILL_CAST) chunk_size = php_stream_set_chunk_size(stream, 1); /* avoid problems with auto-detecting when reading the headers -> the headers * are always in canonical \r\n format */ eol_detect = stream->flags & (PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC); stream->flags &= ~(PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC); php_stream_context_set(stream, context); php_stream_notify_info(context, PHP_STREAM_NOTIFY_CONNECT, NULL, 0); if (header_init && context && php_stream_context_get_option(context, "http", "max_redirects", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_long_ex(tmpzval); redirect_max = Z_LVAL_PP(tmpzval); } if (context && php_stream_context_get_option(context, "http", "method", &tmpzval) == SUCCESS) { if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { /* As per the RFC, automatically redirected requests MUST NOT use other methods than * GET and HEAD unless it can be confirmed by the user */ if (!redirected || (Z_STRLEN_PP(tmpzval) == 3 && memcmp("GET", Z_STRVAL_PP(tmpzval), 3) == 0) || (Z_STRLEN_PP(tmpzval) == 4 && memcmp("HEAD",Z_STRVAL_PP(tmpzval), 4) == 0) ) { scratch_len = strlen(path) + 29 + Z_STRLEN_PP(tmpzval); scratch = emalloc(scratch_len); strlcpy(scratch, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval) + 1); strncat(scratch, " ", 1); } } } if (context && php_stream_context_get_option(context, "http", "protocol_version", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_double_ex(tmpzval); protocol_version_len = spprintf(&protocol_version, 0, "%.1F", Z_DVAL_PP(tmpzval)); } if (!scratch) { scratch_len = strlen(path) + 29 + protocol_version_len; scratch = emalloc(scratch_len); strncpy(scratch, "GET ", scratch_len); } /* Should we send the entire path in the request line, default to no. */ if (!request_fulluri && context && php_stream_context_get_option(context, "http", "request_fulluri", &tmpzval) == SUCCESS) { zval ztmp = **tmpzval; zval_copy_ctor(&ztmp); convert_to_boolean(&ztmp); request_fulluri = Z_BVAL(ztmp) ? 1 : 0; zval_dtor(&ztmp); } if (request_fulluri) { /* Ask for everything */ strcat(scratch, path); } else { /* Send the traditional /path/to/file?query_string */ /* file */ if (resource->path && *resource->path) { strlcat(scratch, resource->path, scratch_len); } else { strlcat(scratch, "/", scratch_len); } /* query string */ if (resource->query) { strlcat(scratch, "?", scratch_len); strlcat(scratch, resource->query, scratch_len); } } /* protocol version we are speaking */ if (protocol_version) { strlcat(scratch, " HTTP/", scratch_len); strlcat(scratch, protocol_version, scratch_len); strlcat(scratch, "\r\n", scratch_len); } else { strlcat(scratch, " HTTP/1.0\r\n", scratch_len); } /* send it */ php_stream_write(stream, scratch, strlen(scratch)); if (context && php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS) { tmp = NULL; if (Z_TYPE_PP(tmpzval) == IS_ARRAY) { HashPosition pos; zval **tmpheader = NULL; smart_str tmpstr = {0}; for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(tmpzval), &pos); SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(tmpzval), (void *)&tmpheader, &pos); zend_hash_move_forward_ex(Z_ARRVAL_PP(tmpzval), &pos) ) { if (Z_TYPE_PP(tmpheader) == IS_STRING) { smart_str_appendl(&tmpstr, Z_STRVAL_PP(tmpheader), Z_STRLEN_PP(tmpheader)); smart_str_appendl(&tmpstr, "\r\n", sizeof("\r\n") - 1); } } smart_str_0(&tmpstr); /* Remove newlines and spaces from start and end. there's at least one extra \r\n at the end that needs to go. */ if (tmpstr.c) { tmp = php_trim(tmpstr.c, strlen(tmpstr.c), NULL, 0, NULL, 3 TSRMLS_CC); smart_str_free(&tmpstr); } } if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) { /* Remove newlines and spaces from start and end php_trim will estrndup() */ tmp = php_trim(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval), NULL, 0, NULL, 3 TSRMLS_CC); } if (tmp && strlen(tmp) > 0) { char *s; user_headers = estrdup(tmp); /* Make lowercase for easy comparison against 'standard' headers */ php_strtolower(tmp, strlen(tmp)); if (!header_init) { /* strip POST headers on redirect */ strip_header(user_headers, tmp, "content-length:"); strip_header(user_headers, tmp, "content-type:"); } if ((s = strstr(tmp, "user-agent:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_USER_AGENT; } if ((s = strstr(tmp, "host:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_HOST; } if ((s = strstr(tmp, "from:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_FROM; } if ((s = strstr(tmp, "authorization:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_AUTH; } if ((s = strstr(tmp, "content-length:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_CONTENT_LENGTH; } if ((s = strstr(tmp, "content-type:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_TYPE; } if ((s = strstr(tmp, "connection:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_CONNECTION; } /* remove Proxy-Authorization header */ if (use_proxy && use_ssl && (s = strstr(tmp, "proxy-authorization:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { char *p = s + sizeof("proxy-authorization:") - 1; while (s > tmp && (*(s-1) == ' ' || *(s-1) == '\t')) s--; while (*p != 0 && *p != '\r' && *p != '\n') p++; while (*p == '\r' || *p == '\n') p++; if (*p == 0) { if (s == tmp) { efree(user_headers); user_headers = NULL; } else { while (s > tmp && (*(s-1) == '\r' || *(s-1) == '\n')) s--; user_headers[s - tmp] = 0; } } else { memmove(user_headers + (s - tmp), user_headers + (p - tmp), strlen(p) + 1); } } } if (tmp) { efree(tmp); } } /* auth header if it was specified */ if (((have_header & HTTP_HEADER_AUTH) == 0) && resource->user) { /* decode the strings first */ php_url_decode(resource->user, strlen(resource->user)); /* scratch is large enough, since it was made large enough for the whole URL */ strcpy(scratch, resource->user); strcat(scratch, ":"); /* Note: password is optional! */ if (resource->pass) { php_url_decode(resource->pass, strlen(resource->pass)); strcat(scratch, resource->pass); } tmp = (char*)php_base64_encode((unsigned char*)scratch, strlen(scratch), NULL); if (snprintf(scratch, scratch_len, "Authorization: Basic %s\r\n", tmp) > 0) { php_stream_write(stream, scratch, strlen(scratch)); php_stream_notify_info(context, PHP_STREAM_NOTIFY_AUTH_REQUIRED, NULL, 0); } efree(tmp); tmp = NULL; } /* if the user has configured who they are, send a From: line */ if (((have_header & HTTP_HEADER_FROM) == 0) && FG(from_address)) { if (snprintf(scratch, scratch_len, "From: %s\r\n", FG(from_address)) > 0) php_stream_write(stream, scratch, strlen(scratch)); } /* Send Host: header so name-based virtual hosts work */ if ((have_header & HTTP_HEADER_HOST) == 0) { if ((use_ssl && resource->port != 443 && resource->port != 0) || (!use_ssl && resource->port != 80 && resource->port != 0)) { if (snprintf(scratch, scratch_len, "Host: %s:%i\r\n", resource->host, resource->port) > 0) php_stream_write(stream, scratch, strlen(scratch)); } else { if (snprintf(scratch, scratch_len, "Host: %s\r\n", resource->host) > 0) { php_stream_write(stream, scratch, strlen(scratch)); } } } /* Send a Connection: close header to avoid hanging when the server * interprets the RFC literally and establishes a keep-alive connection, * unless the user specifically requests something else by specifying a * Connection header in the context options. Send that header even for * HTTP/1.0 to avoid issues when the server respond with a HTTP/1.1 * keep-alive response, which is the preferred response type. */ if ((have_header & HTTP_HEADER_CONNECTION) == 0) { php_stream_write_string(stream, "Connection: close\r\n"); } if (context && php_stream_context_get_option(context, "http", "user_agent", &ua_zval) == SUCCESS && Z_TYPE_PP(ua_zval) == IS_STRING) { ua_str = Z_STRVAL_PP(ua_zval); } else if (FG(user_agent)) { ua_str = FG(user_agent); } if (((have_header & HTTP_HEADER_USER_AGENT) == 0) && ua_str) { #define _UA_HEADER "User-Agent: %s\r\n" char *ua; size_t ua_len; ua_len = sizeof(_UA_HEADER) + strlen(ua_str); /* ensure the header is only sent if user_agent is not blank */ if (ua_len > sizeof(_UA_HEADER)) { ua = emalloc(ua_len + 1); if ((ua_len = slprintf(ua, ua_len, _UA_HEADER, ua_str)) > 0) { ua[ua_len] = 0; php_stream_write(stream, ua, ua_len); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot construct User-agent header"); } if (ua) { efree(ua); } } } if (user_headers) { /* A bit weird, but some servers require that Content-Length be sent prior to Content-Type for POST * see bug #44603 for details. Since Content-Type maybe part of user's headers we need to do this check first. */ if ( header_init && context && !(have_header & HTTP_HEADER_CONTENT_LENGTH) && php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0 ) { scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval)); php_stream_write(stream, scratch, scratch_len); have_header |= HTTP_HEADER_CONTENT_LENGTH; } php_stream_write(stream, user_headers, strlen(user_headers)); php_stream_write(stream, "\r\n", sizeof("\r\n")-1); efree(user_headers); } /* Request content, such as for POST requests */ if (header_init && context && php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { if (!(have_header & HTTP_HEADER_CONTENT_LENGTH)) { scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval)); php_stream_write(stream, scratch, scratch_len); } if (!(have_header & HTTP_HEADER_TYPE)) { php_stream_write(stream, "Content-Type: application/x-www-form-urlencoded\r\n", sizeof("Content-Type: application/x-www-form-urlencoded\r\n") - 1); php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Content-type not specified assuming application/x-www-form-urlencoded"); } php_stream_write(stream, "\r\n", sizeof("\r\n")-1); php_stream_write(stream, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); } else { php_stream_write(stream, "\r\n", sizeof("\r\n")-1); } location[0] = '\0'; if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } if (header_init) { zval *ztmp; MAKE_STD_ZVAL(ztmp); array_init(ztmp); ZEND_SET_SYMBOL(EG(active_symbol_table), "http_response_header", ztmp); } { zval **rh; if(zend_hash_find(EG(active_symbol_table), "http_response_header", sizeof("http_response_header"), (void **) &rh) != SUCCESS || Z_TYPE_PP(rh) != IS_ARRAY) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed, http_response_header overwritten"); goto out; } response_header = *rh; Z_ADDREF_P(response_header); } if (!php_stream_eof(stream)) { size_t tmp_line_len; /* get response header */ if (php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL) { zval *http_response; if (tmp_line_len > 9) { response_code = atoi(tmp_line + 9); } else { response_code = 0; } if (context && SUCCESS==php_stream_context_get_option(context, "http", "ignore_errors", &tmpzval)) { ignore_errors = zend_is_true(*tmpzval); } /* when we request only the header, don't fail even on error codes */ if ((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) { reqok = 1; } /* status codes of 1xx are "informational", and will be followed by a real response * e.g "100 Continue". RFC 7231 states that unexpected 1xx status MUST be parsed, * and MAY be ignored. As such, we need to skip ahead to the "real" status*/ if (response_code >= 100 && response_code < 200) { /* consume lines until we find a line starting 'HTTP/1' */ while ( !php_stream_eof(stream) && php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL && ( tmp_line_len < sizeof("HTTP/1") - 1 || strncasecmp(tmp_line, "HTTP/1", sizeof("HTTP/1") - 1) ) ); if (tmp_line_len > 9) { response_code = atoi(tmp_line + 9); } else { response_code = 0; } } /* all status codes in the 2xx range are defined by the specification as successful; * all status codes in the 3xx range are for redirection, and so also should never * fail */ if (response_code >= 200 && response_code < 400) { reqok = 1; } else { switch(response_code) { case 403: php_stream_notify_error(context, PHP_STREAM_NOTIFY_AUTH_RESULT, tmp_line, response_code); break; default: /* safety net in the event tmp_line == NULL */ if (!tmp_line_len) { tmp_line[0] = '\0'; } php_stream_notify_error(context, PHP_STREAM_NOTIFY_FAILURE, tmp_line, response_code); } } if (tmp_line[tmp_line_len - 1] == '\n') { --tmp_line_len; if (tmp_line[tmp_line_len - 1] == '\r') { --tmp_line_len; } } MAKE_STD_ZVAL(http_response); ZVAL_STRINGL(http_response, tmp_line, tmp_line_len, 1); zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_response, sizeof(zval *), NULL); } } else { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed, unexpected end of socket!"); goto out; } /* read past HTTP headers */ http_header_line = emalloc(HTTP_HEADER_BLOCK_SIZE); while (!body && !php_stream_eof(stream)) { size_t http_header_line_length; if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) && *http_header_line != '\n' && *http_header_line != '\r') { char *e = http_header_line + http_header_line_length - 1; if (*e != '\n') { do { /* partial header */ if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) == NULL) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Failed to read HTTP headers"); goto out; } e = http_header_line + http_header_line_length - 1; } while (*e != '\n'); continue; } while (*e == '\n' || *e == '\r') { e--; } http_header_line_length = e - http_header_line + 1; http_header_line[http_header_line_length] = '\0'; if (!strncasecmp(http_header_line, "Location: ", 10)) { if (context && php_stream_context_get_option(context, "http", "follow_location", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_long_ex(tmpzval); follow_location = Z_LVAL_PP(tmpzval); } else if (!(response_code >= 300 && response_code < 304 || 307 == response_code || 308 == response_code)) { /* we shouldn't redirect automatically if follow_location isn't set and response_code not in (300, 301, 302, 303 and 307) see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.1 RFC 7238 defines 308: http://tools.ietf.org/html/rfc7238 */ follow_location = 0; } strlcpy(location, http_header_line + 10, sizeof(location)); } else if (!strncasecmp(http_header_line, "Content-Type: ", 14)) { php_stream_notify_info(context, PHP_STREAM_NOTIFY_MIME_TYPE_IS, http_header_line + 14, 0); } else if (!strncasecmp(http_header_line, "Content-Length: ", 16)) { file_size = atoi(http_header_line + 16); php_stream_notify_file_size(context, file_size, http_header_line, 0); } else if (!strncasecmp(http_header_line, "Transfer-Encoding: chunked", sizeof("Transfer-Encoding: chunked"))) { /* create filter to decode response body */ if (!(options & STREAM_ONLY_GET_HEADERS)) { long decode = 1; if (context && php_stream_context_get_option(context, "http", "auto_decode", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_boolean(*tmpzval); decode = Z_LVAL_PP(tmpzval); } if (decode) { transfer_encoding = php_stream_filter_create("dechunk", NULL, php_stream_is_persistent(stream) TSRMLS_CC); if (transfer_encoding) { /* don't store transfer-encodeing header */ continue; } } } } if (http_header_line[0] == '\0') { body = 1; } else { zval *http_header; MAKE_STD_ZVAL(http_header); ZVAL_STRINGL(http_header, http_header_line, http_header_line_length, 1); zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_header, sizeof(zval *), NULL); } } else { break; } } if (!reqok || (location[0] != '\0' && follow_location)) { if (!follow_location || (((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) && redirect_max <= 1)) { goto out; } if (location[0] != '\0') php_stream_notify_info(context, PHP_STREAM_NOTIFY_REDIRECTED, location, 0); php_stream_close(stream); stream = NULL; if (location[0] != '\0') { char new_path[HTTP_HEADER_BLOCK_SIZE]; char loc_path[HTTP_HEADER_BLOCK_SIZE]; *new_path='\0'; if (strlen(location)<8 || (strncasecmp(location, "http://", sizeof("http://")-1) && strncasecmp(location, "https://", sizeof("https://")-1) && strncasecmp(location, "ftp://", sizeof("ftp://")-1) && strncasecmp(location, "ftps://", sizeof("ftps://")-1))) { if (*location != '/') { if (*(location+1) != '\0' && resource->path) { char *s = strrchr(resource->path, '/'); if (!s) { s = resource->path; if (!s[0]) { efree(s); s = resource->path = estrdup("/"); } else { *s = '/'; } } s[1] = '\0'; if (resource->path && *(resource->path) == '/' && *(resource->path + 1) == '\0') { snprintf(loc_path, sizeof(loc_path) - 1, "%s%s", resource->path, location); } else { snprintf(loc_path, sizeof(loc_path) - 1, "%s/%s", resource->path, location); } } else { snprintf(loc_path, sizeof(loc_path) - 1, "/%s", location); } } else { strlcpy(loc_path, location, sizeof(loc_path)); } if ((use_ssl && resource->port != 443) || (!use_ssl && resource->port != 80)) { snprintf(new_path, sizeof(new_path) - 1, "%s://%s:%d%s", resource->scheme, resource->host, resource->port, loc_path); } else { snprintf(new_path, sizeof(new_path) - 1, "%s://%s%s", resource->scheme, resource->host, loc_path); } } else { strlcpy(new_path, location, sizeof(new_path)); } php_url_free(resource); /* check for invalid redirection URLs */ if ((resource = php_url_parse(new_path)) == NULL) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path); goto out; } #define CHECK_FOR_CNTRL_CHARS(val) { \ if (val) { \ unsigned char *s, *e; \ int l; \ l = php_url_decode(val, strlen(val)); \ s = (unsigned char*)val; e = s + l; \ while (s < e) { \ if (iscntrl(*s)) { \ php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path); \ goto out; \ } \ s++; \ } \ } \ } /* check for control characters in login, password & path */ if (strncasecmp(new_path, "http://", sizeof("http://") - 1) || strncasecmp(new_path, "https://", sizeof("https://") - 1)) { CHECK_FOR_CNTRL_CHARS(resource->user) CHECK_FOR_CNTRL_CHARS(resource->pass) CHECK_FOR_CNTRL_CHARS(resource->path) } stream = php_stream_url_wrap_http_ex(wrapper, new_path, mode, options, opened_path, context, --redirect_max, HTTP_WRAPPER_REDIRECTED STREAMS_CC TSRMLS_CC); } else { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed! %s", tmp_line); } } out: if (protocol_version) { efree(protocol_version); } if (http_header_line) { efree(http_header_line); } if (scratch) { efree(scratch); } if (resource) { php_url_free(resource); } if (stream) { if (header_init) { stream->wrapperdata = response_header; } else { if(response_header) { Z_DELREF_P(response_header); } } php_stream_notify_progress_init(context, 0, file_size); /* Restore original chunk size now that we're done with headers */ if (options & STREAM_WILL_CAST) php_stream_set_chunk_size(stream, chunk_size); /* restore the users auto-detect-line-endings setting */ stream->flags |= eol_detect; /* as far as streams are concerned, we are now at the start of * the stream */ stream->position = 0; /* restore mode */ strlcpy(stream->mode, mode, sizeof(stream->mode)); if (transfer_encoding) { php_stream_filter_append(&stream->readfilters, transfer_encoding); } } else { if(response_header) { Z_DELREF_P(response_header); } if (transfer_encoding) { php_stream_filter_free(transfer_encoding TSRMLS_CC); } } return stream; } /* }}} */ Commit Message: Fix bug #75981: prevent reading beyond buffer start CWE ID: CWE-119
php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, const char *path, const char *mode, int options, char **opened_path, php_stream_context *context, int redirect_max, int flags STREAMS_DC TSRMLS_DC) /* {{{ */ { php_stream *stream = NULL; php_url *resource = NULL; int use_ssl; int use_proxy = 0; char *scratch = NULL; char *tmp = NULL; char *ua_str = NULL; zval **ua_zval = NULL, **tmpzval = NULL, *ssl_proxy_peer_name = NULL; int scratch_len = 0; int body = 0; char location[HTTP_HEADER_BLOCK_SIZE]; zval *response_header = NULL; int reqok = 0; char *http_header_line = NULL; char tmp_line[128]; size_t chunk_size = 0, file_size = 0; int eol_detect = 0; char *transport_string, *errstr = NULL; int transport_len, have_header = 0, request_fulluri = 0, ignore_errors = 0; char *protocol_version = NULL; int protocol_version_len = 3; /* Default: "1.0" */ struct timeval timeout; char *user_headers = NULL; int header_init = ((flags & HTTP_WRAPPER_HEADER_INIT) != 0); int redirected = ((flags & HTTP_WRAPPER_REDIRECTED) != 0); int follow_location = 1; php_stream_filter *transfer_encoding = NULL; int response_code; tmp_line[0] = '\0'; if (redirect_max < 1) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Redirection limit reached, aborting"); return NULL; } resource = php_url_parse(path); if (resource == NULL) { return NULL; } if (strncasecmp(resource->scheme, "http", sizeof("http")) && strncasecmp(resource->scheme, "https", sizeof("https"))) { if (!context || php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == FAILURE || Z_TYPE_PP(tmpzval) != IS_STRING || Z_STRLEN_PP(tmpzval) <= 0) { php_url_free(resource); return php_stream_open_wrapper_ex(path, mode, REPORT_ERRORS, NULL, context); } /* Called from a non-http wrapper with http proxying requested (i.e. ftp) */ request_fulluri = 1; use_ssl = 0; use_proxy = 1; transport_len = Z_STRLEN_PP(tmpzval); transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); } else { /* Normal http request (possibly with proxy) */ if (strpbrk(mode, "awx+")) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP wrapper does not support writeable connections"); php_url_free(resource); return NULL; } use_ssl = resource->scheme && (strlen(resource->scheme) > 4) && resource->scheme[4] == 's'; /* choose default ports */ if (use_ssl && resource->port == 0) resource->port = 443; else if (resource->port == 0) resource->port = 80; if (context && php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { use_proxy = 1; transport_len = Z_STRLEN_PP(tmpzval); transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); } else { transport_len = spprintf(&transport_string, 0, "%s://%s:%d", use_ssl ? "ssl" : "tcp", resource->host, resource->port); } } if (context && php_stream_context_get_option(context, wrapper->wops->label, "timeout", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_double_ex(tmpzval); timeout.tv_sec = (time_t) Z_DVAL_PP(tmpzval); timeout.tv_usec = (size_t) ((Z_DVAL_PP(tmpzval) - timeout.tv_sec) * 1000000); } else { timeout.tv_sec = FG(default_socket_timeout); timeout.tv_usec = 0; } stream = php_stream_xport_create(transport_string, transport_len, options, STREAM_XPORT_CLIENT | STREAM_XPORT_CONNECT, NULL, &timeout, context, &errstr, NULL); if (stream) { php_stream_set_option(stream, PHP_STREAM_OPTION_READ_TIMEOUT, 0, &timeout); } if (errstr) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "%s", errstr); efree(errstr); errstr = NULL; } efree(transport_string); if (stream && use_proxy && use_ssl) { smart_str header = {0}; /* Set peer_name or name verification will try to use the proxy server name */ if (!context || php_stream_context_get_option(context, "ssl", "peer_name", &tmpzval) == FAILURE) { MAKE_STD_ZVAL(ssl_proxy_peer_name); ZVAL_STRING(ssl_proxy_peer_name, resource->host, 1); php_stream_context_set_option(stream->context, "ssl", "peer_name", ssl_proxy_peer_name); } smart_str_appendl(&header, "CONNECT ", sizeof("CONNECT ")-1); smart_str_appends(&header, resource->host); smart_str_appendc(&header, ':'); smart_str_append_unsigned(&header, resource->port); smart_str_appendl(&header, " HTTP/1.0\r\n", sizeof(" HTTP/1.0\r\n")-1); /* check if we have Proxy-Authorization header */ if (context && php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS) { char *s, *p; if (Z_TYPE_PP(tmpzval) == IS_ARRAY) { HashPosition pos; zval **tmpheader = NULL; for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(tmpzval), &pos); SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(tmpzval), (void *)&tmpheader, &pos); zend_hash_move_forward_ex(Z_ARRVAL_PP(tmpzval), &pos)) { if (Z_TYPE_PP(tmpheader) == IS_STRING) { s = Z_STRVAL_PP(tmpheader); do { while (*s == ' ' || *s == '\t') s++; p = s; while (*p != 0 && *p != ':' && *p != '\r' && *p !='\n') p++; if (*p == ':') { p++; if (p - s == sizeof("Proxy-Authorization:") - 1 && zend_binary_strcasecmp(s, sizeof("Proxy-Authorization:") - 1, "Proxy-Authorization:", sizeof("Proxy-Authorization:") - 1) == 0) { while (*p != 0 && *p != '\r' && *p !='\n') p++; smart_str_appendl(&header, s, p - s); smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1); goto finish; } else { while (*p != 0 && *p != '\r' && *p !='\n') p++; } } s = p; while (*s == '\r' || *s == '\n') s++; } while (*s != 0); } } } else if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) { s = Z_STRVAL_PP(tmpzval); do { while (*s == ' ' || *s == '\t') s++; p = s; while (*p != 0 && *p != ':' && *p != '\r' && *p !='\n') p++; if (*p == ':') { p++; if (p - s == sizeof("Proxy-Authorization:") - 1 && zend_binary_strcasecmp(s, sizeof("Proxy-Authorization:") - 1, "Proxy-Authorization:", sizeof("Proxy-Authorization:") - 1) == 0) { while (*p != 0 && *p != '\r' && *p !='\n') p++; smart_str_appendl(&header, s, p - s); smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1); goto finish; } else { while (*p != 0 && *p != '\r' && *p !='\n') p++; } } s = p; while (*s == '\r' || *s == '\n') s++; } while (*s != 0); } } finish: smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1); if (php_stream_write(stream, header.c, header.len) != header.len) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy"); php_stream_close(stream); stream = NULL; } smart_str_free(&header); if (stream) { char header_line[HTTP_HEADER_BLOCK_SIZE]; /* get response header */ while (php_stream_gets(stream, header_line, HTTP_HEADER_BLOCK_SIZE-1) != NULL) { if (header_line[0] == '\n' || header_line[0] == '\r' || header_line[0] == '\0') { break; } } } /* enable SSL transport layer */ if (stream) { if (php_stream_xport_crypto_setup(stream, STREAM_CRYPTO_METHOD_SSLv23_CLIENT, NULL TSRMLS_CC) < 0 || php_stream_xport_crypto_enable(stream, 1 TSRMLS_CC) < 0) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy"); php_stream_close(stream); stream = NULL; } } } if (stream == NULL) goto out; /* avoid buffering issues while reading header */ if (options & STREAM_WILL_CAST) chunk_size = php_stream_set_chunk_size(stream, 1); /* avoid problems with auto-detecting when reading the headers -> the headers * are always in canonical \r\n format */ eol_detect = stream->flags & (PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC); stream->flags &= ~(PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC); php_stream_context_set(stream, context); php_stream_notify_info(context, PHP_STREAM_NOTIFY_CONNECT, NULL, 0); if (header_init && context && php_stream_context_get_option(context, "http", "max_redirects", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_long_ex(tmpzval); redirect_max = Z_LVAL_PP(tmpzval); } if (context && php_stream_context_get_option(context, "http", "method", &tmpzval) == SUCCESS) { if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { /* As per the RFC, automatically redirected requests MUST NOT use other methods than * GET and HEAD unless it can be confirmed by the user */ if (!redirected || (Z_STRLEN_PP(tmpzval) == 3 && memcmp("GET", Z_STRVAL_PP(tmpzval), 3) == 0) || (Z_STRLEN_PP(tmpzval) == 4 && memcmp("HEAD",Z_STRVAL_PP(tmpzval), 4) == 0) ) { scratch_len = strlen(path) + 29 + Z_STRLEN_PP(tmpzval); scratch = emalloc(scratch_len); strlcpy(scratch, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval) + 1); strncat(scratch, " ", 1); } } } if (context && php_stream_context_get_option(context, "http", "protocol_version", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_double_ex(tmpzval); protocol_version_len = spprintf(&protocol_version, 0, "%.1F", Z_DVAL_PP(tmpzval)); } if (!scratch) { scratch_len = strlen(path) + 29 + protocol_version_len; scratch = emalloc(scratch_len); strncpy(scratch, "GET ", scratch_len); } /* Should we send the entire path in the request line, default to no. */ if (!request_fulluri && context && php_stream_context_get_option(context, "http", "request_fulluri", &tmpzval) == SUCCESS) { zval ztmp = **tmpzval; zval_copy_ctor(&ztmp); convert_to_boolean(&ztmp); request_fulluri = Z_BVAL(ztmp) ? 1 : 0; zval_dtor(&ztmp); } if (request_fulluri) { /* Ask for everything */ strcat(scratch, path); } else { /* Send the traditional /path/to/file?query_string */ /* file */ if (resource->path && *resource->path) { strlcat(scratch, resource->path, scratch_len); } else { strlcat(scratch, "/", scratch_len); } /* query string */ if (resource->query) { strlcat(scratch, "?", scratch_len); strlcat(scratch, resource->query, scratch_len); } } /* protocol version we are speaking */ if (protocol_version) { strlcat(scratch, " HTTP/", scratch_len); strlcat(scratch, protocol_version, scratch_len); strlcat(scratch, "\r\n", scratch_len); } else { strlcat(scratch, " HTTP/1.0\r\n", scratch_len); } /* send it */ php_stream_write(stream, scratch, strlen(scratch)); if (context && php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS) { tmp = NULL; if (Z_TYPE_PP(tmpzval) == IS_ARRAY) { HashPosition pos; zval **tmpheader = NULL; smart_str tmpstr = {0}; for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(tmpzval), &pos); SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(tmpzval), (void *)&tmpheader, &pos); zend_hash_move_forward_ex(Z_ARRVAL_PP(tmpzval), &pos) ) { if (Z_TYPE_PP(tmpheader) == IS_STRING) { smart_str_appendl(&tmpstr, Z_STRVAL_PP(tmpheader), Z_STRLEN_PP(tmpheader)); smart_str_appendl(&tmpstr, "\r\n", sizeof("\r\n") - 1); } } smart_str_0(&tmpstr); /* Remove newlines and spaces from start and end. there's at least one extra \r\n at the end that needs to go. */ if (tmpstr.c) { tmp = php_trim(tmpstr.c, strlen(tmpstr.c), NULL, 0, NULL, 3 TSRMLS_CC); smart_str_free(&tmpstr); } } if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) { /* Remove newlines and spaces from start and end php_trim will estrndup() */ tmp = php_trim(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval), NULL, 0, NULL, 3 TSRMLS_CC); } if (tmp && strlen(tmp) > 0) { char *s; user_headers = estrdup(tmp); /* Make lowercase for easy comparison against 'standard' headers */ php_strtolower(tmp, strlen(tmp)); if (!header_init) { /* strip POST headers on redirect */ strip_header(user_headers, tmp, "content-length:"); strip_header(user_headers, tmp, "content-type:"); } if ((s = strstr(tmp, "user-agent:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_USER_AGENT; } if ((s = strstr(tmp, "host:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_HOST; } if ((s = strstr(tmp, "from:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_FROM; } if ((s = strstr(tmp, "authorization:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_AUTH; } if ((s = strstr(tmp, "content-length:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_CONTENT_LENGTH; } if ((s = strstr(tmp, "content-type:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_TYPE; } if ((s = strstr(tmp, "connection:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { have_header |= HTTP_HEADER_CONNECTION; } /* remove Proxy-Authorization header */ if (use_proxy && use_ssl && (s = strstr(tmp, "proxy-authorization:")) && (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' || *(s-1) == '\t' || *(s-1) == ' ')) { char *p = s + sizeof("proxy-authorization:") - 1; while (s > tmp && (*(s-1) == ' ' || *(s-1) == '\t')) s--; while (*p != 0 && *p != '\r' && *p != '\n') p++; while (*p == '\r' || *p == '\n') p++; if (*p == 0) { if (s == tmp) { efree(user_headers); user_headers = NULL; } else { while (s > tmp && (*(s-1) == '\r' || *(s-1) == '\n')) s--; user_headers[s - tmp] = 0; } } else { memmove(user_headers + (s - tmp), user_headers + (p - tmp), strlen(p) + 1); } } } if (tmp) { efree(tmp); } } /* auth header if it was specified */ if (((have_header & HTTP_HEADER_AUTH) == 0) && resource->user) { /* decode the strings first */ php_url_decode(resource->user, strlen(resource->user)); /* scratch is large enough, since it was made large enough for the whole URL */ strcpy(scratch, resource->user); strcat(scratch, ":"); /* Note: password is optional! */ if (resource->pass) { php_url_decode(resource->pass, strlen(resource->pass)); strcat(scratch, resource->pass); } tmp = (char*)php_base64_encode((unsigned char*)scratch, strlen(scratch), NULL); if (snprintf(scratch, scratch_len, "Authorization: Basic %s\r\n", tmp) > 0) { php_stream_write(stream, scratch, strlen(scratch)); php_stream_notify_info(context, PHP_STREAM_NOTIFY_AUTH_REQUIRED, NULL, 0); } efree(tmp); tmp = NULL; } /* if the user has configured who they are, send a From: line */ if (((have_header & HTTP_HEADER_FROM) == 0) && FG(from_address)) { if (snprintf(scratch, scratch_len, "From: %s\r\n", FG(from_address)) > 0) php_stream_write(stream, scratch, strlen(scratch)); } /* Send Host: header so name-based virtual hosts work */ if ((have_header & HTTP_HEADER_HOST) == 0) { if ((use_ssl && resource->port != 443 && resource->port != 0) || (!use_ssl && resource->port != 80 && resource->port != 0)) { if (snprintf(scratch, scratch_len, "Host: %s:%i\r\n", resource->host, resource->port) > 0) php_stream_write(stream, scratch, strlen(scratch)); } else { if (snprintf(scratch, scratch_len, "Host: %s\r\n", resource->host) > 0) { php_stream_write(stream, scratch, strlen(scratch)); } } } /* Send a Connection: close header to avoid hanging when the server * interprets the RFC literally and establishes a keep-alive connection, * unless the user specifically requests something else by specifying a * Connection header in the context options. Send that header even for * HTTP/1.0 to avoid issues when the server respond with a HTTP/1.1 * keep-alive response, which is the preferred response type. */ if ((have_header & HTTP_HEADER_CONNECTION) == 0) { php_stream_write_string(stream, "Connection: close\r\n"); } if (context && php_stream_context_get_option(context, "http", "user_agent", &ua_zval) == SUCCESS && Z_TYPE_PP(ua_zval) == IS_STRING) { ua_str = Z_STRVAL_PP(ua_zval); } else if (FG(user_agent)) { ua_str = FG(user_agent); } if (((have_header & HTTP_HEADER_USER_AGENT) == 0) && ua_str) { #define _UA_HEADER "User-Agent: %s\r\n" char *ua; size_t ua_len; ua_len = sizeof(_UA_HEADER) + strlen(ua_str); /* ensure the header is only sent if user_agent is not blank */ if (ua_len > sizeof(_UA_HEADER)) { ua = emalloc(ua_len + 1); if ((ua_len = slprintf(ua, ua_len, _UA_HEADER, ua_str)) > 0) { ua[ua_len] = 0; php_stream_write(stream, ua, ua_len); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot construct User-agent header"); } if (ua) { efree(ua); } } } if (user_headers) { /* A bit weird, but some servers require that Content-Length be sent prior to Content-Type for POST * see bug #44603 for details. Since Content-Type maybe part of user's headers we need to do this check first. */ if ( header_init && context && !(have_header & HTTP_HEADER_CONTENT_LENGTH) && php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0 ) { scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval)); php_stream_write(stream, scratch, scratch_len); have_header |= HTTP_HEADER_CONTENT_LENGTH; } php_stream_write(stream, user_headers, strlen(user_headers)); php_stream_write(stream, "\r\n", sizeof("\r\n")-1); efree(user_headers); } /* Request content, such as for POST requests */ if (header_init && context && php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS && Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) { if (!(have_header & HTTP_HEADER_CONTENT_LENGTH)) { scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval)); php_stream_write(stream, scratch, scratch_len); } if (!(have_header & HTTP_HEADER_TYPE)) { php_stream_write(stream, "Content-Type: application/x-www-form-urlencoded\r\n", sizeof("Content-Type: application/x-www-form-urlencoded\r\n") - 1); php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Content-type not specified assuming application/x-www-form-urlencoded"); } php_stream_write(stream, "\r\n", sizeof("\r\n")-1); php_stream_write(stream, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval)); } else { php_stream_write(stream, "\r\n", sizeof("\r\n")-1); } location[0] = '\0'; if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } if (header_init) { zval *ztmp; MAKE_STD_ZVAL(ztmp); array_init(ztmp); ZEND_SET_SYMBOL(EG(active_symbol_table), "http_response_header", ztmp); } { zval **rh; if(zend_hash_find(EG(active_symbol_table), "http_response_header", sizeof("http_response_header"), (void **) &rh) != SUCCESS || Z_TYPE_PP(rh) != IS_ARRAY) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed, http_response_header overwritten"); goto out; } response_header = *rh; Z_ADDREF_P(response_header); } if (!php_stream_eof(stream)) { size_t tmp_line_len; /* get response header */ if (php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL) { zval *http_response; if (tmp_line_len > 9) { response_code = atoi(tmp_line + 9); } else { response_code = 0; } if (context && SUCCESS==php_stream_context_get_option(context, "http", "ignore_errors", &tmpzval)) { ignore_errors = zend_is_true(*tmpzval); } /* when we request only the header, don't fail even on error codes */ if ((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) { reqok = 1; } /* status codes of 1xx are "informational", and will be followed by a real response * e.g "100 Continue". RFC 7231 states that unexpected 1xx status MUST be parsed, * and MAY be ignored. As such, we need to skip ahead to the "real" status*/ if (response_code >= 100 && response_code < 200) { /* consume lines until we find a line starting 'HTTP/1' */ while ( !php_stream_eof(stream) && php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL && ( tmp_line_len < sizeof("HTTP/1") - 1 || strncasecmp(tmp_line, "HTTP/1", sizeof("HTTP/1") - 1) ) ); if (tmp_line_len > 9) { response_code = atoi(tmp_line + 9); } else { response_code = 0; } } /* all status codes in the 2xx range are defined by the specification as successful; * all status codes in the 3xx range are for redirection, and so also should never * fail */ if (response_code >= 200 && response_code < 400) { reqok = 1; } else { switch(response_code) { case 403: php_stream_notify_error(context, PHP_STREAM_NOTIFY_AUTH_RESULT, tmp_line, response_code); break; default: /* safety net in the event tmp_line == NULL */ if (!tmp_line_len) { tmp_line[0] = '\0'; } php_stream_notify_error(context, PHP_STREAM_NOTIFY_FAILURE, tmp_line, response_code); } } if (tmp_line_len >= 1 && tmp_line[tmp_line_len - 1] == '\n') { --tmp_line_len; if (tmp_line_len >= 1 &&tmp_line[tmp_line_len - 1] == '\r') { --tmp_line_len; } } MAKE_STD_ZVAL(http_response); ZVAL_STRINGL(http_response, tmp_line, tmp_line_len, 1); zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_response, sizeof(zval *), NULL); } } else { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed, unexpected end of socket!"); goto out; } /* read past HTTP headers */ http_header_line = emalloc(HTTP_HEADER_BLOCK_SIZE); while (!body && !php_stream_eof(stream)) { size_t http_header_line_length; if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) && *http_header_line != '\n' && *http_header_line != '\r') { char *e = http_header_line + http_header_line_length - 1; if (*e != '\n') { do { /* partial header */ if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) == NULL) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Failed to read HTTP headers"); goto out; } e = http_header_line + http_header_line_length - 1; } while (*e != '\n'); continue; } while (*e == '\n' || *e == '\r') { e--; } http_header_line_length = e - http_header_line + 1; http_header_line[http_header_line_length] = '\0'; if (!strncasecmp(http_header_line, "Location: ", 10)) { if (context && php_stream_context_get_option(context, "http", "follow_location", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_long_ex(tmpzval); follow_location = Z_LVAL_PP(tmpzval); } else if (!(response_code >= 300 && response_code < 304 || 307 == response_code || 308 == response_code)) { /* we shouldn't redirect automatically if follow_location isn't set and response_code not in (300, 301, 302, 303 and 307) see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.1 RFC 7238 defines 308: http://tools.ietf.org/html/rfc7238 */ follow_location = 0; } strlcpy(location, http_header_line + 10, sizeof(location)); } else if (!strncasecmp(http_header_line, "Content-Type: ", 14)) { php_stream_notify_info(context, PHP_STREAM_NOTIFY_MIME_TYPE_IS, http_header_line + 14, 0); } else if (!strncasecmp(http_header_line, "Content-Length: ", 16)) { file_size = atoi(http_header_line + 16); php_stream_notify_file_size(context, file_size, http_header_line, 0); } else if (!strncasecmp(http_header_line, "Transfer-Encoding: chunked", sizeof("Transfer-Encoding: chunked"))) { /* create filter to decode response body */ if (!(options & STREAM_ONLY_GET_HEADERS)) { long decode = 1; if (context && php_stream_context_get_option(context, "http", "auto_decode", &tmpzval) == SUCCESS) { SEPARATE_ZVAL(tmpzval); convert_to_boolean(*tmpzval); decode = Z_LVAL_PP(tmpzval); } if (decode) { transfer_encoding = php_stream_filter_create("dechunk", NULL, php_stream_is_persistent(stream) TSRMLS_CC); if (transfer_encoding) { /* don't store transfer-encodeing header */ continue; } } } } if (http_header_line[0] == '\0') { body = 1; } else { zval *http_header; MAKE_STD_ZVAL(http_header); ZVAL_STRINGL(http_header, http_header_line, http_header_line_length, 1); zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_header, sizeof(zval *), NULL); } } else { break; } } if (!reqok || (location[0] != '\0' && follow_location)) { if (!follow_location || (((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) && redirect_max <= 1)) { goto out; } if (location[0] != '\0') php_stream_notify_info(context, PHP_STREAM_NOTIFY_REDIRECTED, location, 0); php_stream_close(stream); stream = NULL; if (location[0] != '\0') { char new_path[HTTP_HEADER_BLOCK_SIZE]; char loc_path[HTTP_HEADER_BLOCK_SIZE]; *new_path='\0'; if (strlen(location)<8 || (strncasecmp(location, "http://", sizeof("http://")-1) && strncasecmp(location, "https://", sizeof("https://")-1) && strncasecmp(location, "ftp://", sizeof("ftp://")-1) && strncasecmp(location, "ftps://", sizeof("ftps://")-1))) { if (*location != '/') { if (*(location+1) != '\0' && resource->path) { char *s = strrchr(resource->path, '/'); if (!s) { s = resource->path; if (!s[0]) { efree(s); s = resource->path = estrdup("/"); } else { *s = '/'; } } s[1] = '\0'; if (resource->path && *(resource->path) == '/' && *(resource->path + 1) == '\0') { snprintf(loc_path, sizeof(loc_path) - 1, "%s%s", resource->path, location); } else { snprintf(loc_path, sizeof(loc_path) - 1, "%s/%s", resource->path, location); } } else { snprintf(loc_path, sizeof(loc_path) - 1, "/%s", location); } } else { strlcpy(loc_path, location, sizeof(loc_path)); } if ((use_ssl && resource->port != 443) || (!use_ssl && resource->port != 80)) { snprintf(new_path, sizeof(new_path) - 1, "%s://%s:%d%s", resource->scheme, resource->host, resource->port, loc_path); } else { snprintf(new_path, sizeof(new_path) - 1, "%s://%s%s", resource->scheme, resource->host, loc_path); } } else { strlcpy(new_path, location, sizeof(new_path)); } php_url_free(resource); /* check for invalid redirection URLs */ if ((resource = php_url_parse(new_path)) == NULL) { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path); goto out; } #define CHECK_FOR_CNTRL_CHARS(val) { \ if (val) { \ unsigned char *s, *e; \ int l; \ l = php_url_decode(val, strlen(val)); \ s = (unsigned char*)val; e = s + l; \ while (s < e) { \ if (iscntrl(*s)) { \ php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path); \ goto out; \ } \ s++; \ } \ } \ } /* check for control characters in login, password & path */ if (strncasecmp(new_path, "http://", sizeof("http://") - 1) || strncasecmp(new_path, "https://", sizeof("https://") - 1)) { CHECK_FOR_CNTRL_CHARS(resource->user) CHECK_FOR_CNTRL_CHARS(resource->pass) CHECK_FOR_CNTRL_CHARS(resource->path) } stream = php_stream_url_wrap_http_ex(wrapper, new_path, mode, options, opened_path, context, --redirect_max, HTTP_WRAPPER_REDIRECTED STREAMS_CC TSRMLS_CC); } else { php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed! %s", tmp_line); } } out: if (protocol_version) { efree(protocol_version); } if (http_header_line) { efree(http_header_line); } if (scratch) { efree(scratch); } if (resource) { php_url_free(resource); } if (stream) { if (header_init) { stream->wrapperdata = response_header; } else { if(response_header) { Z_DELREF_P(response_header); } } php_stream_notify_progress_init(context, 0, file_size); /* Restore original chunk size now that we're done with headers */ if (options & STREAM_WILL_CAST) php_stream_set_chunk_size(stream, chunk_size); /* restore the users auto-detect-line-endings setting */ stream->flags |= eol_detect; /* as far as streams are concerned, we are now at the start of * the stream */ stream->position = 0; /* restore mode */ strlcpy(stream->mode, mode, sizeof(stream->mode)); if (transfer_encoding) { php_stream_filter_append(&stream->readfilters, transfer_encoding); } } else { if(response_header) { Z_DELREF_P(response_header); } if (transfer_encoding) { php_stream_filter_free(transfer_encoding TSRMLS_CC); } } return stream; } /* }}} */
169,308
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int rpmPackageFilesInstall(rpmts ts, rpmte te, rpmfiles files, rpmpsm psm, char ** failedFile) { FD_t payload = rpmtePayload(te); rpmfi fi = rpmfiNewArchiveReader(payload, files, RPMFI_ITER_READ_ARCHIVE); rpmfs fs = rpmteGetFileStates(te); rpmPlugins plugins = rpmtsPlugins(ts); struct stat sb; int saveerrno = errno; int rc = 0; int nodigest = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOFILEDIGEST) ? 1 : 0; int nofcaps = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOCAPS) ? 1 : 0; int firsthardlink = -1; int skip; rpmFileAction action; char *tid = NULL; const char *suffix; char *fpath = NULL; if (fi == NULL) { rc = RPMERR_BAD_MAGIC; goto exit; } /* transaction id used for temporary path suffix while installing */ rasprintf(&tid, ";%08x", (unsigned)rpmtsGetTid(ts)); /* Detect and create directories not explicitly in package. */ rc = fsmMkdirs(files, fs, plugins); while (!rc) { /* Read next payload header. */ rc = rpmfiNext(fi); if (rc < 0) { if (rc == RPMERR_ITER_END) rc = 0; break; } action = rpmfsGetAction(fs, rpmfiFX(fi)); skip = XFA_SKIPPING(action); suffix = S_ISDIR(rpmfiFMode(fi)) ? NULL : tid; if (action != FA_TOUCH) { fpath = fsmFsPath(fi, suffix); } else { fpath = fsmFsPath(fi, ""); } /* Remap file perms, owner, and group. */ rc = rpmfiStat(fi, 1, &sb); fsmDebug(fpath, action, &sb); /* Exit on error. */ if (rc) break; /* Run fsm file pre hook for all plugins */ rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath, sb.st_mode, action); if (rc) { skip = 1; } else { setFileState(fs, rpmfiFX(fi)); } if (!skip) { int setmeta = 1; /* Directories replacing something need early backup */ if (!suffix) { rc = fsmBackup(fi, action); } /* Assume file does't exist when tmp suffix is in use */ if (!suffix) { rc = fsmVerify(fpath, fi); } else { rc = (action == FA_TOUCH) ? 0 : RPMERR_ENOENT; } if (S_ISREG(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmMkfile(fi, fpath, files, psm, nodigest, &setmeta, &firsthardlink); } } else if (S_ISDIR(sb.st_mode)) { if (rc == RPMERR_ENOENT) { mode_t mode = sb.st_mode; mode &= ~07777; mode |= 00700; rc = fsmMkdir(fpath, mode); } } else if (S_ISLNK(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmSymlink(rpmfiFLink(fi), fpath); } } else if (S_ISFIFO(sb.st_mode)) { /* This mimics cpio S_ISSOCK() behavior but probably isn't right */ if (rc == RPMERR_ENOENT) { rc = fsmMkfifo(fpath, 0000); } } else if (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode) || S_ISSOCK(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmMknod(fpath, sb.st_mode, sb.st_rdev); } } else { /* XXX Special case /dev/log, which shouldn't be packaged anyways */ if (!IS_DEV_LOG(fpath)) rc = RPMERR_UNKNOWN_FILETYPE; } /* Set permissions, timestamps etc for non-hardlink entries */ if (!rc && setmeta) { rc = fsmSetmeta(fpath, fi, plugins, action, &sb, nofcaps); } } else if (firsthardlink >= 0 && rpmfiArchiveHasContent(fi)) { /* we skip the hard linked file containing the content */ /* write the content to the first used instead */ char *fn = rpmfilesFN(files, firsthardlink); rc = expandRegular(fi, fn, psm, 0, nodigest, 0); firsthardlink = -1; free(fn); } if (rc) { if (!skip) { /* XXX only erase if temp fn w suffix is in use */ if (suffix && (action != FA_TOUCH)) { (void) fsmRemove(fpath, sb.st_mode); } errno = saveerrno; } } else { /* Notify on success. */ rpmpsmNotify(psm, RPMCALLBACK_INST_PROGRESS, rpmfiArchiveTell(fi)); if (!skip) { /* Backup file if needed. Directories are handled earlier */ if (suffix) rc = fsmBackup(fi, action); if (!rc) rc = fsmCommit(&fpath, fi, action, suffix); } } if (rc) *failedFile = xstrdup(fpath); /* Run fsm file post hook for all plugins */ rpmpluginsCallFsmFilePost(plugins, fi, fpath, sb.st_mode, action, rc); fpath = _free(fpath); } rpmswAdd(rpmtsOp(ts, RPMTS_OP_UNCOMPRESS), fdOp(payload, FDSTAT_READ)); rpmswAdd(rpmtsOp(ts, RPMTS_OP_DIGEST), fdOp(payload, FDSTAT_DIGEST)); exit: /* No need to bother with close errors on read */ rpmfiArchiveClose(fi); rpmfiFree(fi); Fclose(payload); free(tid); free(fpath); return rc; } Commit Message: Restrict following symlinks to directories by ownership (CVE-2017-7500) Only follow directory symlinks owned by target directory owner or root. This prevents privilege escalation from user-writable directories via directory symlinks to privileged directories on package upgrade, while still allowing admin to arrange disk usage with symlinks. The rationale is that if you can create symlinks owned by user X you *are* user X (or root), and if you also own directory Y you can do whatever with it already, including change permissions. So when you create a symlink to that directory, the link ownership acts as a simple stamp of authority that you indeed want rpm to treat this symlink as it were the directory that you own. Such a permission can only be given by you or root, which is just the way we want it. Plus it's almost ridiculously simple as far as rules go, compared to trying to calculate something from the source vs destination directory permissions etc. In the normal case, the user arranging diskspace with symlinks is indeed root so nothing changes, the only real change here is to links created by non-privileged users which should be few and far between in practise. Unfortunately our test-suite runs as a regular user via fakechroot and thus the testcase for this fails under the new rules. Adjust the testcase to get the ownership straight and add a second case for the illegal behavior, basically the same as the old one but with different expectations. CWE ID: CWE-59
int rpmPackageFilesInstall(rpmts ts, rpmte te, rpmfiles files, rpmpsm psm, char ** failedFile) { FD_t payload = rpmtePayload(te); rpmfi fi = rpmfiNewArchiveReader(payload, files, RPMFI_ITER_READ_ARCHIVE); rpmfs fs = rpmteGetFileStates(te); rpmPlugins plugins = rpmtsPlugins(ts); struct stat sb; int saveerrno = errno; int rc = 0; int nodigest = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOFILEDIGEST) ? 1 : 0; int nofcaps = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOCAPS) ? 1 : 0; int firsthardlink = -1; int skip; rpmFileAction action; char *tid = NULL; const char *suffix; char *fpath = NULL; if (fi == NULL) { rc = RPMERR_BAD_MAGIC; goto exit; } /* transaction id used for temporary path suffix while installing */ rasprintf(&tid, ";%08x", (unsigned)rpmtsGetTid(ts)); /* Detect and create directories not explicitly in package. */ rc = fsmMkdirs(files, fs, plugins); while (!rc) { /* Read next payload header. */ rc = rpmfiNext(fi); if (rc < 0) { if (rc == RPMERR_ITER_END) rc = 0; break; } action = rpmfsGetAction(fs, rpmfiFX(fi)); skip = XFA_SKIPPING(action); suffix = S_ISDIR(rpmfiFMode(fi)) ? NULL : tid; if (action != FA_TOUCH) { fpath = fsmFsPath(fi, suffix); } else { fpath = fsmFsPath(fi, ""); } /* Remap file perms, owner, and group. */ rc = rpmfiStat(fi, 1, &sb); fsmDebug(fpath, action, &sb); /* Exit on error. */ if (rc) break; /* Run fsm file pre hook for all plugins */ rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath, sb.st_mode, action); if (rc) { skip = 1; } else { setFileState(fs, rpmfiFX(fi)); } if (!skip) { int setmeta = 1; /* Directories replacing something need early backup */ if (!suffix) { rc = fsmBackup(fi, action); } /* Assume file does't exist when tmp suffix is in use */ if (!suffix) { rc = fsmVerify(fpath, fi, &sb); } else { rc = (action == FA_TOUCH) ? 0 : RPMERR_ENOENT; } if (S_ISREG(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmMkfile(fi, fpath, files, psm, nodigest, &setmeta, &firsthardlink); } } else if (S_ISDIR(sb.st_mode)) { if (rc == RPMERR_ENOENT) { mode_t mode = sb.st_mode; mode &= ~07777; mode |= 00700; rc = fsmMkdir(fpath, mode); } } else if (S_ISLNK(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmSymlink(rpmfiFLink(fi), fpath); } } else if (S_ISFIFO(sb.st_mode)) { /* This mimics cpio S_ISSOCK() behavior but probably isn't right */ if (rc == RPMERR_ENOENT) { rc = fsmMkfifo(fpath, 0000); } } else if (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode) || S_ISSOCK(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmMknod(fpath, sb.st_mode, sb.st_rdev); } } else { /* XXX Special case /dev/log, which shouldn't be packaged anyways */ if (!IS_DEV_LOG(fpath)) rc = RPMERR_UNKNOWN_FILETYPE; } /* Set permissions, timestamps etc for non-hardlink entries */ if (!rc && setmeta) { rc = fsmSetmeta(fpath, fi, plugins, action, &sb, nofcaps); } } else if (firsthardlink >= 0 && rpmfiArchiveHasContent(fi)) { /* we skip the hard linked file containing the content */ /* write the content to the first used instead */ char *fn = rpmfilesFN(files, firsthardlink); rc = expandRegular(fi, fn, psm, 0, nodigest, 0); firsthardlink = -1; free(fn); } if (rc) { if (!skip) { /* XXX only erase if temp fn w suffix is in use */ if (suffix && (action != FA_TOUCH)) { (void) fsmRemove(fpath, sb.st_mode); } errno = saveerrno; } } else { /* Notify on success. */ rpmpsmNotify(psm, RPMCALLBACK_INST_PROGRESS, rpmfiArchiveTell(fi)); if (!skip) { /* Backup file if needed. Directories are handled earlier */ if (suffix) rc = fsmBackup(fi, action); if (!rc) rc = fsmCommit(&fpath, fi, action, suffix); } } if (rc) *failedFile = xstrdup(fpath); /* Run fsm file post hook for all plugins */ rpmpluginsCallFsmFilePost(plugins, fi, fpath, sb.st_mode, action, rc); fpath = _free(fpath); } rpmswAdd(rpmtsOp(ts, RPMTS_OP_UNCOMPRESS), fdOp(payload, FDSTAT_READ)); rpmswAdd(rpmtsOp(ts, RPMTS_OP_DIGEST), fdOp(payload, FDSTAT_DIGEST)); exit: /* No need to bother with close errors on read */ rpmfiArchiveClose(fi); rpmfiFree(fi); Fclose(payload); free(tid); free(fpath); return rc; }
170,177
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void install_local_socket(asocket* s) { adb_mutex_lock(&socket_list_lock); s->id = local_socket_next_id++; if (local_socket_next_id == 0) { local_socket_next_id = 1; } insert_local_socket(s, &local_socket_list); adb_mutex_unlock(&socket_list_lock); } Commit Message: adb: switch the socket list mutex to a recursive_mutex. sockets.cpp was branching on whether a socket close function was local_socket_close in order to avoid a potential deadlock if the socket list lock was held while closing a peer socket. Bug: http://b/28347842 Change-Id: I5e56f17fa54275284787f0f1dc150d1960256ab3 (cherry picked from commit 9b587dec6d0a57c8fe1083c1c543fbeb163d65fa) CWE ID: CWE-264
void install_local_socket(asocket* s) { std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock); s->id = local_socket_next_id++; if (local_socket_next_id == 0) { fatal("local socket id overflow"); } insert_local_socket(s, &local_socket_list); }
174,152
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MockPrinter::UpdateSettings(int cookie, PrintMsg_PrintPages_Params* params, const std::vector<int>& pages) { EXPECT_EQ(document_cookie_, cookie); params->Reset(); params->pages = pages; SetPrintParams(&(params->params)); printer_status_ = PRINTER_PRINTING; } Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void MockPrinter::UpdateSettings(int cookie, PrintMsg_PrintPages_Params* params, const std::vector<int>& pages) { if (document_cookie_ == -1) { document_cookie_ = CreateDocumentCookie(); } params->Reset(); params->pages = pages; SetPrintParams(&(params->params)); printer_status_ = PRINTER_PRINTING; }
170,257
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int opl3_load_patch(int dev, int format, const char __user *addr, int offs, int count, int pmgr_flag) { struct sbi_instrument ins; if (count <sizeof(ins)) { printk(KERN_WARNING "FM Error: Patch record too short\n"); return -EINVAL; } /* * What the fuck is going on here? We leave junk in the beginning * of ins and then check the field pretty close to that beginning? */ if(copy_from_user(&((char *) &ins)[offs], addr + offs, sizeof(ins) - offs)) return -EFAULT; if (ins.channel < 0 || ins.channel >= SBFM_MAXINSTR) { printk(KERN_WARNING "FM Error: Invalid instrument number %d\n", ins.channel); return -EINVAL; } ins.key = format; return store_instr(ins.channel, &ins); } Commit Message: sound/oss: remove offset from load_patch callbacks Was: [PATCH] sound/oss/midi_synth: prevent underflow, use of uninitialized value, and signedness issue The offset passed to midi_synth_load_patch() can be essentially arbitrary. If it's greater than the header length, this will result in a copy_from_user(dst, src, negative_val). While this will just return -EFAULT on x86, on other architectures this may cause memory corruption. Additionally, the length field of the sysex_info structure may not be initialized prior to its use. Finally, a signed comparison may result in an unintentionally large loop. On suggestion by Takashi Iwai, version two removes the offset argument from the load_patch callbacks entirely, which also resolves similar issues in opl3. Compile tested only. v3 adjusts comments and hopefully gets copy offsets right. Signed-off-by: Dan Rosenberg <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-189
static int opl3_load_patch(int dev, int format, const char __user *addr, int count, int pmgr_flag) { struct sbi_instrument ins; if (count <sizeof(ins)) { printk(KERN_WARNING "FM Error: Patch record too short\n"); return -EINVAL; } if (copy_from_user(&ins, addr, sizeof(ins))) return -EFAULT; if (ins.channel < 0 || ins.channel >= SBFM_MAXINSTR) { printk(KERN_WARNING "FM Error: Invalid instrument number %d\n", ins.channel); return -EINVAL; } ins.key = format; return store_instr(ins.channel, &ins); }
165,893
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void vmx_set_msr_bitmap(struct kvm_vcpu *vcpu) { unsigned long *msr_bitmap; if (is_guest_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_nested; else if (vcpu->arch.apic_base & X2APIC_ENABLE) { if (is_long_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_longmode_x2apic; else msr_bitmap = vmx_msr_bitmap_legacy_x2apic; } else { if (is_long_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_longmode; else msr_bitmap = vmx_msr_bitmap_legacy; } vmcs_write64(MSR_BITMAP, __pa(msr_bitmap)); } Commit Message: kvm:vmx: more complete state update on APICv on/off The function to update APICv on/off state (in particular, to deactivate it when enabling Hyper-V SynIC) is incomplete: it doesn't adjust APICv-related fields among secondary processor-based VM-execution controls. As a result, Windows 2012 guests get stuck when SynIC-based auto-EOI interrupt intersected with e.g. an IPI in the guest. In addition, the MSR intercept bitmap isn't updated every time "virtualize x2APIC mode" is toggled. This path can only be triggered by a malicious guest, because Windows didn't use x2APIC but rather their own synthetic APIC access MSRs; however a guest running in a SynIC-enabled VM could switch to x2APIC and thus obtain direct access to host APIC MSRs (CVE-2016-4440). The patch fixes those omissions. Signed-off-by: Roman Kagan <[email protected]> Reported-by: Steve Rutherford <[email protected]> Reported-by: Yang Zhang <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-264
static void vmx_set_msr_bitmap(struct kvm_vcpu *vcpu) { unsigned long *msr_bitmap; if (is_guest_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_nested; else if (cpu_has_secondary_exec_ctrls() && (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) & SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) { if (is_long_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_longmode_x2apic; else msr_bitmap = vmx_msr_bitmap_legacy_x2apic; } else { if (is_long_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_longmode; else msr_bitmap = vmx_msr_bitmap_legacy; } vmcs_write64(MSR_BITMAP, __pa(msr_bitmap)); }
167,264
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) { int al,i,j,ret; unsigned int n; SSL3_RECORD *rr; void (*cb)(const SSL *ssl,int type2,int val)=NULL; if (s->s3->rbuf.buf == NULL) /* Not initialized yet */ if (!ssl3_setup_buffers(s)) return(-1); if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE)) || (peek && (type != SSL3_RT_APPLICATION_DATA))) { SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; } /* check whether there's a handshake message (client hello?) waiting */ if ( (ret = have_handshake_fragment(s, type, buf, len, peek))) return ret; /* Now s->d1->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */ #ifndef OPENSSL_NO_SCTP /* Continue handshake if it had to be interrupted to read * app data with SCTP. */ if ((!s->in_handshake && SSL_in_init(s)) || (BIO_dgram_is_sctp(SSL_get_rbio(s)) && (s->state == DTLS1_SCTP_ST_SR_READ_SOCK || s->state == DTLS1_SCTP_ST_CR_READ_SOCK) && s->s3->in_read_app_data != 2)) #else if (!s->in_handshake && SSL_in_init(s)) #endif { /* type == SSL3_RT_APPLICATION_DATA */ i=s->handshake_func(s); if (i < 0) return(i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); return(-1); } } start: s->rwstate=SSL_NOTHING; /*- * s->s3->rrec.type - is the type of record * s->s3->rrec.data, - data * s->s3->rrec.off, - offset into 'data' for next read * s->s3->rrec.length, - number of bytes. */ rr = &(s->s3->rrec); /* We are not handshaking and have no data yet, * so process data buffered during the last handshake * in advance, if any. */ if (s->state == SSL_ST_OK && rr->length == 0) { pitem *item; item = pqueue_pop(s->d1->buffered_app_data.q); if (item) { #ifndef OPENSSL_NO_SCTP /* Restore bio_dgram_sctp_rcvinfo struct */ if (BIO_dgram_is_sctp(SSL_get_rbio(s))) { DTLS1_RECORD_DATA *rdata = (DTLS1_RECORD_DATA *) item->data; BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_SET_RCVINFO, sizeof(rdata->recordinfo), &rdata->recordinfo); } #endif dtls1_copy_record(s, item); OPENSSL_free(item->data); pitem_free(item); } } /* Check for timeout */ if (dtls1_handle_timeout(s) > 0) goto start; /* get new packet if necessary */ if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) { ret=dtls1_get_record(s); if (ret <= 0) { ret = dtls1_read_failed(s, ret); /* anything other than a timeout is an error */ if (ret <= 0) return(ret); else goto start; } } if (s->d1->listen && rr->type != SSL3_RT_HANDSHAKE) { rr->length = 0; goto start; } /* we now have a packet which can be read and processed */ if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec, * reset by ssl3_get_finished */ && (rr->type != SSL3_RT_HANDSHAKE)) { /* We now have application data between CCS and Finished. * Most likely the packets were reordered on their way, so * buffer the application data for later processing rather * than dropping the connection. */ dtls1_buffer_record(s, &(s->d1->buffered_app_data), rr->seq_num); rr->length = 0; goto start; } /* If the other end has shut down, throw anything we read away * (even in 'peek' mode) */ if (s->shutdown & SSL_RECEIVED_SHUTDOWN) { rr->length=0; s->rwstate=SSL_NOTHING; return(0); } if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */ { /* make sure that we are not getting application data when we * are doing a handshake for the first time */ if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) && (s->enc_read_ctx == NULL)) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_APP_DATA_IN_HANDSHAKE); goto f_err; } if (len <= 0) return(len); if ((unsigned int)len > rr->length) n = rr->length; else n = (unsigned int)len; memcpy(buf,&(rr->data[rr->off]),n); if (!peek) { rr->length-=n; rr->off+=n; if (rr->length == 0) { s->rstate=SSL_ST_READ_HEADER; rr->off=0; } } #ifndef OPENSSL_NO_SCTP /* We were about to renegotiate but had to read * belated application data first, so retry. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && rr->type == SSL3_RT_APPLICATION_DATA && (s->state == DTLS1_SCTP_ST_SR_READ_SOCK || s->state == DTLS1_SCTP_ST_CR_READ_SOCK)) { s->rwstate=SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); } /* We might had to delay a close_notify alert because * of reordered app data. If there was an alert and there * is no message to read anymore, finally set shutdown. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && s->d1->shutdown_received && !BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) { s->shutdown |= SSL_RECEIVED_SHUTDOWN; return(0); } #endif return(n); } /* If we get here, then type != rr->type; if we have a handshake * message, then it was unexpected (Hello Request or Client Hello). */ /* In case of record types for which we have 'fragment' storage, * fill that so that we can process the data at a fixed place. */ { unsigned int k, dest_maxlen = 0; unsigned char *dest = NULL; unsigned int *dest_len = NULL; if (rr->type == SSL3_RT_HANDSHAKE) { dest_maxlen = sizeof s->d1->handshake_fragment; dest = s->d1->handshake_fragment; dest_len = &s->d1->handshake_fragment_len; } else if (rr->type == SSL3_RT_ALERT) { dest_maxlen = sizeof(s->d1->alert_fragment); dest = s->d1->alert_fragment; dest_len = &s->d1->alert_fragment_len; } #ifndef OPENSSL_NO_HEARTBEATS else if (rr->type == TLS1_RT_HEARTBEAT) { dtls1_process_heartbeat(s); /* Exit and notify application to read again */ rr->length = 0; s->rwstate=SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); return(-1); } #endif /* else it's a CCS message, or application data or wrong */ else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC) { /* Application data while renegotiating * is allowed. Try again reading. */ if (rr->type == SSL3_RT_APPLICATION_DATA) { BIO *bio; s->s3->in_read_app_data=2; bio=SSL_get_rbio(s); s->rwstate=SSL_READING; BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return(-1); } /* Not certain if this is the right error handling */ al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD); goto f_err; } if (dest_maxlen > 0) { /* XDTLS: In a pathalogical case, the Client Hello * may be fragmented--don't always expect dest_maxlen bytes */ if ( rr->length < dest_maxlen) { #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE /* * for normal alerts rr->length is 2, while * dest_maxlen is 7 if we were to handle this * non-existing alert... */ FIX ME #endif s->rstate=SSL_ST_READ_HEADER; rr->length = 0; goto start; } /* now move 'n' bytes: */ for ( k = 0; k < dest_maxlen; k++) { dest[k] = rr->data[rr->off++]; rr->length--; } *dest_len = dest_maxlen; } } /* s->d1->handshake_fragment_len == 12 iff rr->type == SSL3_RT_HANDSHAKE; * s->d1->alert_fragment_len == 7 iff rr->type == SSL3_RT_ALERT. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */ /* If we are a client, check for an incoming 'Hello Request': */ if ((!s->server) && (s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && (s->d1->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) && (s->session != NULL) && (s->session->cipher != NULL)) { s->d1->handshake_fragment_len = 0; if ((s->d1->handshake_fragment[1] != 0) || (s->d1->handshake_fragment[2] != 0) || (s->d1->handshake_fragment[3] != 0)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_BAD_HELLO_REQUEST); goto err; } /* no need to check sequence number on HELLO REQUEST messages */ if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->d1->handshake_fragment, 4, s, s->msg_callback_arg); if (SSL_is_init_finished(s) && !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) && !s->s3->renegotiate) { s->d1->handshake_read_seq++; s->new_session = 1; ssl3_renegotiate(s); if (ssl3_renegotiate_check(s)) { i=s->handshake_func(s); if (i < 0) return(i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); return(-1); } if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (s->s3->rbuf.left == 0) /* no read-ahead left? */ { BIO *bio; /* In the case where we try to read application data, * but we trigger an SSL handshake, we return -1 with * the retry option set. Otherwise renegotiation may * cause nasty problems in the blocking world */ s->rwstate=SSL_READING; bio=SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return(-1); } } } } /* we either finished a handshake or ignored the request, * now try again to obtain the (application) data we were asked for */ goto start; } if (s->d1->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) { int alert_level = s->d1->alert_fragment[0]; int alert_descr = s->d1->alert_fragment[1]; s->d1->alert_fragment_len = 0; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_ALERT, s->d1->alert_fragment, 2, s, s->msg_callback_arg); if (s->info_callback != NULL) cb=s->info_callback; else if (s->ctx->info_callback != NULL) cb=s->ctx->info_callback; if (cb != NULL) { j = (alert_level << 8) | alert_descr; cb(s, SSL_CB_READ_ALERT, j); } if (alert_level == 1) /* warning */ { s->s3->warn_alert = alert_descr; if (alert_descr == SSL_AD_CLOSE_NOTIFY) { #ifndef OPENSSL_NO_SCTP /* With SCTP and streams the socket may deliver app data * after a close_notify alert. We have to check this * first so that nothing gets discarded. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) { s->d1->shutdown_received = 1; s->rwstate=SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); return -1; } #endif s->shutdown |= SSL_RECEIVED_SHUTDOWN; return(0); } #if 0 /* XXX: this is a possible improvement in the future */ /* now check if it's a missing record */ if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) { unsigned short seq; unsigned int frag_off; unsigned char *p = &(s->d1->alert_fragment[2]); n2s(p, seq); n2l3(p, frag_off); dtls1_retransmit_message(s, dtls1_get_queue_priority(frag->msg_header.seq, 0), frag_off, &found); if ( ! found && SSL_in_init(s)) { /* fprintf( stderr,"in init = %d\n", SSL_in_init(s)); */ /* requested a message not yet sent, send an alert ourselves */ ssl3_send_alert(s,SSL3_AL_WARNING, DTLS1_AD_MISSING_HANDSHAKE_MESSAGE); } } #endif } else if (alert_level == 2) /* fatal */ { char tmp[16]; s->rwstate=SSL_NOTHING; s->s3->fatal_alert = alert_descr; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr); BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr); ERR_add_error_data(2,"SSL alert number ",tmp); s->shutdown|=SSL_RECEIVED_SHUTDOWN; SSL_CTX_remove_session(s->ctx,s->session); return(0); } else { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNKNOWN_ALERT_TYPE); goto f_err; } goto start; } if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */ { s->rwstate=SSL_NOTHING; rr->length=0; return(0); } if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) { struct ccs_header_st ccs_hdr; unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH; dtls1_get_ccs_header(rr->data, &ccs_hdr); if (s->version == DTLS1_BAD_VER) ccs_hdr_len = 3; /* 'Change Cipher Spec' is just a single byte, so we know * exactly what the record payload has to look like */ /* XDTLS: check that epoch is consistent */ if ( (rr->length != ccs_hdr_len) || (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) { i=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_BAD_CHANGE_CIPHER_SPEC); goto err; } rr->length=0; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s, s->msg_callback_arg); /* We can't process a CCS now, because previous handshake * messages are still missing, so just drop it. */ if (!s->d1->change_cipher_spec_ok) { goto start; } s->d1->change_cipher_spec_ok = 0; s->s3->change_cipher_spec=1; if (!ssl3_do_change_cipher_spec(s)) goto err; /* do this whenever CCS is processed */ dtls1_reset_seq_numbers(s, SSL3_CC_READ); if (s->version == DTLS1_BAD_VER) s->d1->handshake_read_seq++; #ifndef OPENSSL_NO_SCTP /* Remember that a CCS has been received, * so that an old key of SCTP-Auth can be * deleted when a CCS is sent. Will be ignored * if no SCTP is used */ BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL); #endif goto start; } /* Unexpected handshake message (Client Hello, or protocol violation) */ if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && !s->in_handshake) { struct hm_header_st msg_hdr; /* this may just be a stale retransmit */ dtls1_get_message_header(rr->data, &msg_hdr); if( rr->epoch != s->d1->r_epoch) { rr->length = 0; goto start; } /* If we are server, we may have a repeated FINISHED of the * client here, then retransmit our CCS and FINISHED. */ if (msg_hdr.type == SSL3_MT_FINISHED) { if (dtls1_check_timeout_num(s) < 0) return -1; dtls1_retransmit_buffered_messages(s); rr->length = 0; goto start; } if (((s->state&SSL_ST_MASK) == SSL_ST_OK) && !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) { #if 0 /* worked only because C operator preferences are not as expected (and * because this is not really needed for clients except for detecting * protocol violations): */ s->state=SSL_ST_BEFORE|(s->server) ?SSL_ST_ACCEPT :SSL_ST_CONNECT; #else s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT; #endif s->renegotiate=1; s->new_session=1; } i=s->handshake_func(s); if (i < 0) return(i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); return(-1); } if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (s->s3->rbuf.left == 0) /* no read-ahead left? */ { BIO *bio; /* In the case where we try to read application data, * but we trigger an SSL handshake, we return -1 with * the retry option set. Otherwise renegotiation may * cause nasty problems in the blocking world */ s->rwstate=SSL_READING; bio=SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return(-1); } } goto start; } switch (rr->type) { default: #ifndef OPENSSL_NO_TLS /* TLS just ignores unknown message types */ if (s->version == TLS1_VERSION) { rr->length = 0; goto start; } #endif al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD); goto f_err; case SSL3_RT_CHANGE_CIPHER_SPEC: case SSL3_RT_ALERT: case SSL3_RT_HANDSHAKE: /* we already handled all of these, with the possible exception * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that * should not happen when type != rr->type */ al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES,ERR_R_INTERNAL_ERROR); goto f_err; case SSL3_RT_APPLICATION_DATA: /* At this point, we were expecting handshake data, * but have application data. If the library was * running inside ssl3_read() (i.e. in_read_app_data * is set) and it makes sense to read application data * at this point (session renegotiation not yet started), * we will indulge it. */ if (s->s3->in_read_app_data && (s->s3->total_renegotiations != 0) && (( (s->state & SSL_ST_CONNECT) && (s->state >= SSL3_ST_CW_CLNT_HELLO_A) && (s->state <= SSL3_ST_CR_SRVR_HELLO_A) ) || ( (s->state & SSL_ST_ACCEPT) && (s->state <= SSL3_ST_SW_HELLO_REQ_A) && (s->state >= SSL3_ST_SR_CLNT_HELLO_A) ) )) { s->s3->in_read_app_data=2; return(-1); } else { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD); goto f_err; } } /* not reached */ f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(-1); } Commit Message: A memory leak can occur in dtls1_buffer_record if either of the calls to ssl3_setup_buffers or pqueue_insert fail. The former will fail if there is a malloc failure, whilst the latter will fail if attempting to add a duplicate record to the queue. This should never happen because duplicate records should be detected and dropped before any attempt to add them to the queue. Unfortunately records that arrive that are for the next epoch are not being recorded correctly, and therefore replays are not being detected. Additionally, these "should not happen" failures that can occur in dtls1_buffer_record are not being treated as fatal and therefore an attacker could exploit this by sending repeated replay records for the next epoch, eventually causing a DoS through memory exhaustion. Thanks to Chris Mueller for reporting this issue and providing initial analysis and a patch. Further analysis and the final patch was performed by Matt Caswell from the OpenSSL development team. CVE-2015-0206 Reviewed-by: Dr Stephen Henson <[email protected]> CWE ID: CWE-119
int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) { int al,i,j,ret; unsigned int n; SSL3_RECORD *rr; void (*cb)(const SSL *ssl,int type2,int val)=NULL; if (s->s3->rbuf.buf == NULL) /* Not initialized yet */ if (!ssl3_setup_buffers(s)) return(-1); if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE)) || (peek && (type != SSL3_RT_APPLICATION_DATA))) { SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; } /* check whether there's a handshake message (client hello?) waiting */ if ( (ret = have_handshake_fragment(s, type, buf, len, peek))) return ret; /* Now s->d1->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */ #ifndef OPENSSL_NO_SCTP /* Continue handshake if it had to be interrupted to read * app data with SCTP. */ if ((!s->in_handshake && SSL_in_init(s)) || (BIO_dgram_is_sctp(SSL_get_rbio(s)) && (s->state == DTLS1_SCTP_ST_SR_READ_SOCK || s->state == DTLS1_SCTP_ST_CR_READ_SOCK) && s->s3->in_read_app_data != 2)) #else if (!s->in_handshake && SSL_in_init(s)) #endif { /* type == SSL3_RT_APPLICATION_DATA */ i=s->handshake_func(s); if (i < 0) return(i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); return(-1); } } start: s->rwstate=SSL_NOTHING; /*- * s->s3->rrec.type - is the type of record * s->s3->rrec.data, - data * s->s3->rrec.off, - offset into 'data' for next read * s->s3->rrec.length, - number of bytes. */ rr = &(s->s3->rrec); /* We are not handshaking and have no data yet, * so process data buffered during the last handshake * in advance, if any. */ if (s->state == SSL_ST_OK && rr->length == 0) { pitem *item; item = pqueue_pop(s->d1->buffered_app_data.q); if (item) { #ifndef OPENSSL_NO_SCTP /* Restore bio_dgram_sctp_rcvinfo struct */ if (BIO_dgram_is_sctp(SSL_get_rbio(s))) { DTLS1_RECORD_DATA *rdata = (DTLS1_RECORD_DATA *) item->data; BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_SET_RCVINFO, sizeof(rdata->recordinfo), &rdata->recordinfo); } #endif dtls1_copy_record(s, item); OPENSSL_free(item->data); pitem_free(item); } } /* Check for timeout */ if (dtls1_handle_timeout(s) > 0) goto start; /* get new packet if necessary */ if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) { ret=dtls1_get_record(s); if (ret <= 0) { ret = dtls1_read_failed(s, ret); /* anything other than a timeout is an error */ if (ret <= 0) return(ret); else goto start; } } if (s->d1->listen && rr->type != SSL3_RT_HANDSHAKE) { rr->length = 0; goto start; } /* we now have a packet which can be read and processed */ if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec, * reset by ssl3_get_finished */ && (rr->type != SSL3_RT_HANDSHAKE)) { /* We now have application data between CCS and Finished. * Most likely the packets were reordered on their way, so * buffer the application data for later processing rather * than dropping the connection. */ if(dtls1_buffer_record(s, &(s->d1->buffered_app_data), rr->seq_num)<0) { SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; } rr->length = 0; goto start; } /* If the other end has shut down, throw anything we read away * (even in 'peek' mode) */ if (s->shutdown & SSL_RECEIVED_SHUTDOWN) { rr->length=0; s->rwstate=SSL_NOTHING; return(0); } if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */ { /* make sure that we are not getting application data when we * are doing a handshake for the first time */ if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) && (s->enc_read_ctx == NULL)) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_APP_DATA_IN_HANDSHAKE); goto f_err; } if (len <= 0) return(len); if ((unsigned int)len > rr->length) n = rr->length; else n = (unsigned int)len; memcpy(buf,&(rr->data[rr->off]),n); if (!peek) { rr->length-=n; rr->off+=n; if (rr->length == 0) { s->rstate=SSL_ST_READ_HEADER; rr->off=0; } } #ifndef OPENSSL_NO_SCTP /* We were about to renegotiate but had to read * belated application data first, so retry. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && rr->type == SSL3_RT_APPLICATION_DATA && (s->state == DTLS1_SCTP_ST_SR_READ_SOCK || s->state == DTLS1_SCTP_ST_CR_READ_SOCK)) { s->rwstate=SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); } /* We might had to delay a close_notify alert because * of reordered app data. If there was an alert and there * is no message to read anymore, finally set shutdown. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && s->d1->shutdown_received && !BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) { s->shutdown |= SSL_RECEIVED_SHUTDOWN; return(0); } #endif return(n); } /* If we get here, then type != rr->type; if we have a handshake * message, then it was unexpected (Hello Request or Client Hello). */ /* In case of record types for which we have 'fragment' storage, * fill that so that we can process the data at a fixed place. */ { unsigned int k, dest_maxlen = 0; unsigned char *dest = NULL; unsigned int *dest_len = NULL; if (rr->type == SSL3_RT_HANDSHAKE) { dest_maxlen = sizeof s->d1->handshake_fragment; dest = s->d1->handshake_fragment; dest_len = &s->d1->handshake_fragment_len; } else if (rr->type == SSL3_RT_ALERT) { dest_maxlen = sizeof(s->d1->alert_fragment); dest = s->d1->alert_fragment; dest_len = &s->d1->alert_fragment_len; } #ifndef OPENSSL_NO_HEARTBEATS else if (rr->type == TLS1_RT_HEARTBEAT) { dtls1_process_heartbeat(s); /* Exit and notify application to read again */ rr->length = 0; s->rwstate=SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); return(-1); } #endif /* else it's a CCS message, or application data or wrong */ else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC) { /* Application data while renegotiating * is allowed. Try again reading. */ if (rr->type == SSL3_RT_APPLICATION_DATA) { BIO *bio; s->s3->in_read_app_data=2; bio=SSL_get_rbio(s); s->rwstate=SSL_READING; BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return(-1); } /* Not certain if this is the right error handling */ al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD); goto f_err; } if (dest_maxlen > 0) { /* XDTLS: In a pathalogical case, the Client Hello * may be fragmented--don't always expect dest_maxlen bytes */ if ( rr->length < dest_maxlen) { #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE /* * for normal alerts rr->length is 2, while * dest_maxlen is 7 if we were to handle this * non-existing alert... */ FIX ME #endif s->rstate=SSL_ST_READ_HEADER; rr->length = 0; goto start; } /* now move 'n' bytes: */ for ( k = 0; k < dest_maxlen; k++) { dest[k] = rr->data[rr->off++]; rr->length--; } *dest_len = dest_maxlen; } } /* s->d1->handshake_fragment_len == 12 iff rr->type == SSL3_RT_HANDSHAKE; * s->d1->alert_fragment_len == 7 iff rr->type == SSL3_RT_ALERT. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */ /* If we are a client, check for an incoming 'Hello Request': */ if ((!s->server) && (s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && (s->d1->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) && (s->session != NULL) && (s->session->cipher != NULL)) { s->d1->handshake_fragment_len = 0; if ((s->d1->handshake_fragment[1] != 0) || (s->d1->handshake_fragment[2] != 0) || (s->d1->handshake_fragment[3] != 0)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_BAD_HELLO_REQUEST); goto err; } /* no need to check sequence number on HELLO REQUEST messages */ if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->d1->handshake_fragment, 4, s, s->msg_callback_arg); if (SSL_is_init_finished(s) && !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) && !s->s3->renegotiate) { s->d1->handshake_read_seq++; s->new_session = 1; ssl3_renegotiate(s); if (ssl3_renegotiate_check(s)) { i=s->handshake_func(s); if (i < 0) return(i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); return(-1); } if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (s->s3->rbuf.left == 0) /* no read-ahead left? */ { BIO *bio; /* In the case where we try to read application data, * but we trigger an SSL handshake, we return -1 with * the retry option set. Otherwise renegotiation may * cause nasty problems in the blocking world */ s->rwstate=SSL_READING; bio=SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return(-1); } } } } /* we either finished a handshake or ignored the request, * now try again to obtain the (application) data we were asked for */ goto start; } if (s->d1->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) { int alert_level = s->d1->alert_fragment[0]; int alert_descr = s->d1->alert_fragment[1]; s->d1->alert_fragment_len = 0; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_ALERT, s->d1->alert_fragment, 2, s, s->msg_callback_arg); if (s->info_callback != NULL) cb=s->info_callback; else if (s->ctx->info_callback != NULL) cb=s->ctx->info_callback; if (cb != NULL) { j = (alert_level << 8) | alert_descr; cb(s, SSL_CB_READ_ALERT, j); } if (alert_level == 1) /* warning */ { s->s3->warn_alert = alert_descr; if (alert_descr == SSL_AD_CLOSE_NOTIFY) { #ifndef OPENSSL_NO_SCTP /* With SCTP and streams the socket may deliver app data * after a close_notify alert. We have to check this * first so that nothing gets discarded. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) { s->d1->shutdown_received = 1; s->rwstate=SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); return -1; } #endif s->shutdown |= SSL_RECEIVED_SHUTDOWN; return(0); } #if 0 /* XXX: this is a possible improvement in the future */ /* now check if it's a missing record */ if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) { unsigned short seq; unsigned int frag_off; unsigned char *p = &(s->d1->alert_fragment[2]); n2s(p, seq); n2l3(p, frag_off); dtls1_retransmit_message(s, dtls1_get_queue_priority(frag->msg_header.seq, 0), frag_off, &found); if ( ! found && SSL_in_init(s)) { /* fprintf( stderr,"in init = %d\n", SSL_in_init(s)); */ /* requested a message not yet sent, send an alert ourselves */ ssl3_send_alert(s,SSL3_AL_WARNING, DTLS1_AD_MISSING_HANDSHAKE_MESSAGE); } } #endif } else if (alert_level == 2) /* fatal */ { char tmp[16]; s->rwstate=SSL_NOTHING; s->s3->fatal_alert = alert_descr; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr); BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr); ERR_add_error_data(2,"SSL alert number ",tmp); s->shutdown|=SSL_RECEIVED_SHUTDOWN; SSL_CTX_remove_session(s->ctx,s->session); return(0); } else { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNKNOWN_ALERT_TYPE); goto f_err; } goto start; } if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */ { s->rwstate=SSL_NOTHING; rr->length=0; return(0); } if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) { struct ccs_header_st ccs_hdr; unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH; dtls1_get_ccs_header(rr->data, &ccs_hdr); if (s->version == DTLS1_BAD_VER) ccs_hdr_len = 3; /* 'Change Cipher Spec' is just a single byte, so we know * exactly what the record payload has to look like */ /* XDTLS: check that epoch is consistent */ if ( (rr->length != ccs_hdr_len) || (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) { i=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_BAD_CHANGE_CIPHER_SPEC); goto err; } rr->length=0; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s, s->msg_callback_arg); /* We can't process a CCS now, because previous handshake * messages are still missing, so just drop it. */ if (!s->d1->change_cipher_spec_ok) { goto start; } s->d1->change_cipher_spec_ok = 0; s->s3->change_cipher_spec=1; if (!ssl3_do_change_cipher_spec(s)) goto err; /* do this whenever CCS is processed */ dtls1_reset_seq_numbers(s, SSL3_CC_READ); if (s->version == DTLS1_BAD_VER) s->d1->handshake_read_seq++; #ifndef OPENSSL_NO_SCTP /* Remember that a CCS has been received, * so that an old key of SCTP-Auth can be * deleted when a CCS is sent. Will be ignored * if no SCTP is used */ BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL); #endif goto start; } /* Unexpected handshake message (Client Hello, or protocol violation) */ if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && !s->in_handshake) { struct hm_header_st msg_hdr; /* this may just be a stale retransmit */ dtls1_get_message_header(rr->data, &msg_hdr); if( rr->epoch != s->d1->r_epoch) { rr->length = 0; goto start; } /* If we are server, we may have a repeated FINISHED of the * client here, then retransmit our CCS and FINISHED. */ if (msg_hdr.type == SSL3_MT_FINISHED) { if (dtls1_check_timeout_num(s) < 0) return -1; dtls1_retransmit_buffered_messages(s); rr->length = 0; goto start; } if (((s->state&SSL_ST_MASK) == SSL_ST_OK) && !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) { #if 0 /* worked only because C operator preferences are not as expected (and * because this is not really needed for clients except for detecting * protocol violations): */ s->state=SSL_ST_BEFORE|(s->server) ?SSL_ST_ACCEPT :SSL_ST_CONNECT; #else s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT; #endif s->renegotiate=1; s->new_session=1; } i=s->handshake_func(s); if (i < 0) return(i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE); return(-1); } if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (s->s3->rbuf.left == 0) /* no read-ahead left? */ { BIO *bio; /* In the case where we try to read application data, * but we trigger an SSL handshake, we return -1 with * the retry option set. Otherwise renegotiation may * cause nasty problems in the blocking world */ s->rwstate=SSL_READING; bio=SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return(-1); } } goto start; } switch (rr->type) { default: #ifndef OPENSSL_NO_TLS /* TLS just ignores unknown message types */ if (s->version == TLS1_VERSION) { rr->length = 0; goto start; } #endif al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD); goto f_err; case SSL3_RT_CHANGE_CIPHER_SPEC: case SSL3_RT_ALERT: case SSL3_RT_HANDSHAKE: /* we already handled all of these, with the possible exception * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that * should not happen when type != rr->type */ al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES,ERR_R_INTERNAL_ERROR); goto f_err; case SSL3_RT_APPLICATION_DATA: /* At this point, we were expecting handshake data, * but have application data. If the library was * running inside ssl3_read() (i.e. in_read_app_data * is set) and it makes sense to read application data * at this point (session renegotiation not yet started), * we will indulge it. */ if (s->s3->in_read_app_data && (s->s3->total_renegotiations != 0) && (( (s->state & SSL_ST_CONNECT) && (s->state >= SSL3_ST_CW_CLNT_HELLO_A) && (s->state <= SSL3_ST_CR_SRVR_HELLO_A) ) || ( (s->state & SSL_ST_ACCEPT) && (s->state <= SSL3_ST_SW_HELLO_REQ_A) && (s->state >= SSL3_ST_SR_CLNT_HELLO_A) ) )) { s->s3->in_read_app_data=2; return(-1); } else { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD); goto f_err; } } /* not reached */ f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(-1); }
166,749
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PersistentHistogramAllocator::RecordCreateHistogramResult( CreateHistogramResultType result) { HistogramBase* result_histogram = GetCreateHistogramResultHistogram(); if (result_histogram) result_histogram->Add(result); } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <[email protected]> Reviewed-by: Alexei Svitkine <[email protected]> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264
void PersistentHistogramAllocator::RecordCreateHistogramResult(
172,135
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ChromeMockRenderThread::OnDidPreviewPage( const PrintHostMsg_DidPreviewPage_Params& params) { DCHECK(params.page_number >= printing::FIRST_PAGE_INDEX); print_preview_pages_remaining_--; } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void ChromeMockRenderThread::OnDidPreviewPage( const PrintHostMsg_DidPreviewPage_Params& params) { DCHECK_GE(params.page_number, printing::FIRST_PAGE_INDEX); print_preview_pages_remaining_--; }
170,849
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: php_http_url_t *php_http_url_parse(const char *str, size_t len, unsigned flags TSRMLS_DC) { size_t maxlen = 3 * len; struct parse_state *state = ecalloc(1, sizeof(*state) + maxlen); state->end = str + len; state->ptr = str; state->flags = flags; state->maxlen = maxlen; TSRMLS_SET_CTX(state->ts); if (!parse_scheme(state)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL scheme: '%s'", state->ptr); efree(state); return NULL; } if (!parse_hier(state)) { efree(state); return NULL; } if (!parse_query(state)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL query: '%s'", state->ptr); efree(state); return NULL; } if (!parse_fragment(state)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL fragment: '%s'", state->ptr); efree(state); return NULL; } return (php_http_url_t *) state; } Commit Message: fix bug #71719 (Buffer overflow in HTTP url parsing functions) The parser's offset was not reset when we softfail in scheme parsing and continue to parse a path. Thanks to hlt99 at blinkenshell dot org for the report. CWE ID: CWE-119
php_http_url_t *php_http_url_parse(const char *str, size_t len, unsigned flags TSRMLS_DC) { size_t maxlen = 3 * len + 8 /* null bytes for all components */; struct parse_state *state = ecalloc(1, sizeof(*state) + maxlen); state->end = str + len; state->ptr = str; state->flags = flags; state->maxlen = maxlen; TSRMLS_SET_CTX(state->ts); if (!parse_scheme(state)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL scheme: '%s'", state->ptr); efree(state); return NULL; } if (!parse_hier(state)) { efree(state); return NULL; } if (!parse_query(state)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL query: '%s'", state->ptr); efree(state); return NULL; } if (!parse_fragment(state)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL fragment: '%s'", state->ptr); efree(state); return NULL; } return (php_http_url_t *) state; }
168,834
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: tight_detect_smooth_image(VncState *vs, int w, int h) { unsigned int errors; int compression = vs->tight.compression; int quality = vs->tight.quality; if (!vs->vd->lossy) { return 0; } if (ds_get_bytes_per_pixel(vs->ds) == 1 || vs->clientds.pf.bytes_per_pixel == 1 || w < VNC_TIGHT_DETECT_MIN_WIDTH || h < VNC_TIGHT_DETECT_MIN_HEIGHT) { return 0; } if (vs->tight.quality != (uint8_t)-1) { if (w * h < VNC_TIGHT_JPEG_MIN_RECT_SIZE) { return 0; } } else { if (w * h < tight_conf[compression].gradient_min_rect_size) { return 0; } } if (vs->clientds.pf.bytes_per_pixel == 4) { if (vs->tight.pixel24) { errors = tight_detect_smooth_image24(vs, w, h); if (vs->tight.quality != (uint8_t)-1) { return (errors < tight_conf[quality].jpeg_threshold24); } return (errors < tight_conf[compression].gradient_threshold24); } else { errors = tight_detect_smooth_image32(vs, w, h); } } else { errors = tight_detect_smooth_image16(vs, w, h); } if (quality != -1) { return (errors < tight_conf[quality].jpeg_threshold); } return (errors < tight_conf[compression].gradient_threshold); } Commit Message: CWE ID: CWE-125
tight_detect_smooth_image(VncState *vs, int w, int h) { unsigned int errors; int compression = vs->tight.compression; int quality = vs->tight.quality; if (!vs->vd->lossy) { return 0; } if (ds_get_bytes_per_pixel(vs->ds) == 1 || vs->client_pf.bytes_per_pixel == 1 || w < VNC_TIGHT_DETECT_MIN_WIDTH || h < VNC_TIGHT_DETECT_MIN_HEIGHT) { return 0; } if (vs->tight.quality != (uint8_t)-1) { if (w * h < VNC_TIGHT_JPEG_MIN_RECT_SIZE) { return 0; } } else { if (w * h < tight_conf[compression].gradient_min_rect_size) { return 0; } } if (vs->client_pf.bytes_per_pixel == 4) { if (vs->tight.pixel24) { errors = tight_detect_smooth_image24(vs, w, h); if (vs->tight.quality != (uint8_t)-1) { return (errors < tight_conf[quality].jpeg_threshold24); } return (errors < tight_conf[compression].gradient_threshold24); } else { errors = tight_detect_smooth_image32(vs, w, h); } } else { errors = tight_detect_smooth_image16(vs, w, h); } if (quality != -1) { return (errors < tight_conf[quality].jpeg_threshold); } return (errors < tight_conf[compression].gradient_threshold); }
165,464
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void OpenTwoTabs(const GURL& first_url, const GURL& second_url) { content::WindowedNotificationObserver load1( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); OpenURLParams open1(first_url, content::Referrer(), WindowOpenDisposition::CURRENT_TAB, ui::PAGE_TRANSITION_TYPED, false); browser()->OpenURL(open1); load1.Wait(); content::WindowedNotificationObserver load2( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); OpenURLParams open2(second_url, content::Referrer(), WindowOpenDisposition::NEW_BACKGROUND_TAB, ui::PAGE_TRANSITION_TYPED, false); browser()->OpenURL(open2); load2.Wait(); ASSERT_EQ(2, tsm()->count()); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
void OpenTwoTabs(const GURL& first_url, const GURL& second_url) { content::WindowedNotificationObserver load1( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); OpenURLParams open1(first_url, content::Referrer(), WindowOpenDisposition::CURRENT_TAB, ui::PAGE_TRANSITION_TYPED, false); content::WebContents* web_contents = browser()->OpenURL(open1); load1.Wait(); if (URLShouldBeStoredInLocalDatabase(first_url)) testing::ExpireLocalDBObservationWindows(web_contents); content::WindowedNotificationObserver load2( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); OpenURLParams open2(second_url, content::Referrer(), WindowOpenDisposition::NEW_BACKGROUND_TAB, ui::PAGE_TRANSITION_TYPED, false); web_contents = browser()->OpenURL(open2); load2.Wait(); // Expire all the observation windows to prevent the discarding and freezing // interventions to fail because of a lack of observations. if (URLShouldBeStoredInLocalDatabase(second_url)) testing::ExpireLocalDBObservationWindows(web_contents); ASSERT_EQ(2, tsm()->count()); }
172,228
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static double outerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth) { /* There is a serious error in the 2 and 4 bit grayscale transform because * the gamma table value (8 bits) is simply shifted, not rounded, so the * error in 4 bit grayscale gamma is up to the value below. This is a hack * to allow pngvalid to succeed: * * TODO: fix this in libpng */ if (out_depth == 2) return .73182-.5; if (out_depth == 4) return .90644-.5; if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16) return pm->maxout16; /* This is the case where the value was calculated at 8-bit precision then * scaled to 16 bits. */ else if (out_depth == 16) return pm->maxout8 * 257; else return pm->maxout8; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
static double outerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth) static double outerr(const png_modifier *pm, int in_depth, int out_depth) { /* There is a serious error in the 2 and 4 bit grayscale transform because * the gamma table value (8 bits) is simply shifted, not rounded, so the * error in 4 bit grayscale gamma is up to the value below. This is a hack * to allow pngvalid to succeed: * * TODO: fix this in libpng */ if (out_depth == 2) return .73182-.5; if (out_depth == 4) return .90644-.5; if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16) return pm->maxout16; /* This is the case where the value was calculated at 8-bit precision then * scaled to 16 bits. */ else if (out_depth == 16) return pm->maxout8 * 257; else return pm->maxout8; }
173,674
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ShellSurface::OnSurfaceCommit() { surface_->CheckIfSurfaceHierarchyNeedsCommitToNewSurfaces(); surface_->CommitSurfaceHierarchy(); if (enabled() && !widget_) CreateShellSurfaceWidget(ui::SHOW_STATE_NORMAL); origin_ += pending_origin_offset_; pending_origin_offset_ = gfx::Vector2d(); resize_component_ = pending_resize_component_; if (widget_) { geometry_ = pending_geometry_; UpdateWidgetBounds(); gfx::Point surface_origin = GetSurfaceOrigin(); gfx::Rect hit_test_bounds = surface_->GetHitTestBounds() + surface_origin.OffsetFromOrigin(); bool activatable = activatable_ && !hit_test_bounds.IsEmpty(); if (activatable != CanActivate()) { set_can_activate(activatable); aura::client::ActivationClient* activation_client = ash::Shell::GetInstance()->activation_client(); if (activatable) activation_client->ActivateWindow(widget_->GetNativeWindow()); else if (widget_->IsActive()) activation_client->DeactivateWindow(widget_->GetNativeWindow()); } surface_->window()->SetBounds( gfx::Rect(surface_origin, surface_->window()->layer()->size())); if (pending_scale_ != scale_) { gfx::Transform transform; DCHECK_NE(pending_scale_, 0.0); transform.Scale(1.0 / pending_scale_, 1.0 / pending_scale_); surface_->window()->SetTransform(transform); scale_ = pending_scale_; } if (pending_show_widget_) { DCHECK(!widget_->IsClosed()); DCHECK(!widget_->IsVisible()); pending_show_widget_ = false; widget_->Show(); } } } Commit Message: exo: Reduce side-effects of dynamic activation code. This code exists for clients that need to managed their own system modal dialogs. Since the addition of the remote surface API we can limit the impact of this to surfaces created for system modal container. BUG=29528396 Review-Url: https://codereview.chromium.org/2084023003 Cr-Commit-Position: refs/heads/master@{#401115} CWE ID: CWE-416
void ShellSurface::OnSurfaceCommit() { surface_->CheckIfSurfaceHierarchyNeedsCommitToNewSurfaces(); surface_->CommitSurfaceHierarchy(); if (enabled() && !widget_) CreateShellSurfaceWidget(ui::SHOW_STATE_NORMAL); origin_ += pending_origin_offset_; pending_origin_offset_ = gfx::Vector2d(); resize_component_ = pending_resize_component_; if (widget_) { geometry_ = pending_geometry_; UpdateWidgetBounds(); gfx::Point surface_origin = GetSurfaceOrigin(); // System modal container is used by clients to implement client side // managed system modal dialogs using a single ShellSurface instance. // Hit-test region will be non-empty when at least one dialog exists on // the client side. Here we detect the transition between no client side // dialog and at least one dialog so activatable state is properly // updated. if (container_ == ash::kShellWindowId_SystemModalContainer) { gfx::Rect hit_test_bounds = surface_->GetHitTestBounds() + surface_origin.OffsetFromOrigin(); // Prevent window from being activated when hit test bounds are empty. bool activatable = activatable_ && !hit_test_bounds.IsEmpty(); if (activatable != CanActivate()) { set_can_activate(activatable); // Activate or deactivate window if activation state changed. aura::client::ActivationClient* activation_client = ash::Shell::GetInstance()->activation_client(); if (activatable) activation_client->ActivateWindow(widget_->GetNativeWindow()); else if (widget_->IsActive()) activation_client->DeactivateWindow(widget_->GetNativeWindow()); } } surface_->window()->SetBounds( gfx::Rect(surface_origin, surface_->window()->layer()->size())); if (pending_scale_ != scale_) { gfx::Transform transform; DCHECK_NE(pending_scale_, 0.0); transform.Scale(1.0 / pending_scale_, 1.0 / pending_scale_); surface_->window()->SetTransform(transform); scale_ = pending_scale_; } if (pending_show_widget_) { DCHECK(!widget_->IsClosed()); DCHECK(!widget_->IsVisible()); pending_show_widget_ = false; widget_->Show(); } } }
171,639
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: mapi_attr_read (size_t len, unsigned char *buf) { size_t idx = 0; uint32 i,j; assert(len > 4); uint32 num_properties = GETINT32(buf+idx); MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1)); idx += 4; if (!attrs) return NULL; for (i = 0; i < num_properties; i++) { MAPI_Attr* a = attrs[i] = CHECKED_XCALLOC(MAPI_Attr, 1); MAPI_Value* v = NULL; CHECKINT16(idx, len); a->type = GETINT16(buf+idx); idx += 2; CHECKINT16(idx, len); a->name = GETINT16(buf+idx); idx += 2; /* handle special case of GUID prefixed properties */ if (a->name & GUID_EXISTS_FLAG) { /* copy GUID */ a->guid = CHECKED_XMALLOC(GUID, 1); copy_guid_from_buf(a->guid, buf+idx, len); idx += sizeof (GUID); CHECKINT32(idx, len); a->num_names = GETINT32(buf+idx); idx += 4; if (a->num_names > 0) { /* FIXME: do something useful here! */ size_t i; a->names = CHECKED_XCALLOC(VarLenData, a->num_names); for (i = 0; i < a->num_names; i++) { size_t j; CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4; /* read the data into a buffer */ a->names[i].data = CHECKED_XMALLOC(unsigned char, a->names[i].len); for (j = 0; j < (a->names[i].len >> 1); j++) a->names[i].data[j] = (buf+idx)[j*2]; /* But what are we going to do with it? */ idx += pad_to_4byte(a->names[i].len); } } else { /* get the 'real' name */ CHECKINT32(idx, len); a->name = GETINT32(buf+idx); idx+= 4; } } /* * Multi-value types and string/object/binary types have * multiple values */ if (a->type & MULTI_VALUE_FLAG || a->type == szMAPI_STRING || a->type == szMAPI_UNICODE_STRING || a->type == szMAPI_OBJECT || a->type == szMAPI_BINARY) { CHECKINT32(idx, len); a->num_values = GETINT32(buf+idx); idx += 4; } else { a->num_values = 1; } /* Amend the type in case of multi-value type */ if (a->type & MULTI_VALUE_FLAG) { a->type -= MULTI_VALUE_FLAG; } v = alloc_mapi_values (a); for (j = 0; j < a->num_values; j++) { switch (a->type) { case szMAPI_SHORT: /* 2 bytes */ v->len = 2; CHECKINT16(idx, len); v->data.bytes2 = GETINT16(buf+idx); idx += 4; /* assume padding of 2, advance by 4! */ break; case szMAPI_INT: /* 4 bytes */ v->len = 4; CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); idx += 4; v++; break; case szMAPI_FLOAT: /* 4 bytes */ case szMAPI_BOOLEAN: /* this should be 2 bytes + 2 padding */ v->len = 4; CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); idx += v->len; break; case szMAPI_SYSTIME: /* 8 bytes */ v->len = 8; CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); idx += 8; v++; break; case szMAPI_DOUBLE: /* 8 bytes */ case szMAPI_APPTIME: case szMAPI_CURRENCY: case szMAPI_INT8BYTE: v->len = 8; CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); idx += v->len; break; case szMAPI_CLSID: v->len = sizeof (GUID); copy_guid_from_buf(&v->data.guid, buf+idx, len); idx += v->len; break; case szMAPI_STRING: case szMAPI_UNICODE_STRING: case szMAPI_OBJECT: case szMAPI_BINARY: CHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4; if (a->type == szMAPI_UNICODE_STRING) { v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx); } else { v->data.buf = CHECKED_XMALLOC(unsigned char, v->len); memmove (v->data.buf, buf+idx, v->len); } idx += pad_to_4byte(v->len); v++; break; case szMAPI_NULL: /* illegal in input tnef streams */ case szMAPI_ERROR: case szMAPI_UNSPECIFIED: fprintf (stderr, "Invalid attribute, input file may be corrupted\n"); if (!ENCODE_SKIP) exit (1); return NULL; default: /* should never get here */ fprintf (stderr, "Undefined attribute, input file may be corrupted\n"); if (!ENCODE_SKIP) exit (1); return NULL; } if (DEBUG_ON) mapi_attr_dump (attrs[i]); } } attrs[i] = NULL; return attrs; } Commit Message: Use asserts on lengths to prevent invalid reads/writes. CWE ID: CWE-125
mapi_attr_read (size_t len, unsigned char *buf) { size_t idx = 0; uint32 i,j; assert(len > 4); uint32 num_properties = GETINT32(buf+idx); assert((num_properties+1) != 0); MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1)); idx += 4; if (!attrs) return NULL; for (i = 0; i < num_properties; i++) { MAPI_Attr* a = attrs[i] = CHECKED_XCALLOC(MAPI_Attr, 1); MAPI_Value* v = NULL; CHECKINT16(idx, len); a->type = GETINT16(buf+idx); idx += 2; CHECKINT16(idx, len); a->name = GETINT16(buf+idx); idx += 2; /* handle special case of GUID prefixed properties */ if (a->name & GUID_EXISTS_FLAG) { /* copy GUID */ a->guid = CHECKED_XMALLOC(GUID, 1); copy_guid_from_buf(a->guid, buf+idx, len); idx += sizeof (GUID); CHECKINT32(idx, len); a->num_names = GETINT32(buf+idx); idx += 4; if (a->num_names > 0) { /* FIXME: do something useful here! */ size_t i; a->names = CHECKED_XCALLOC(VarLenData, a->num_names); for (i = 0; i < a->num_names; i++) { size_t j; CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4; /* read the data into a buffer */ a->names[i].data = CHECKED_XMALLOC(unsigned char, a->names[i].len); assert((idx+(a->names[i].len*2)) <= len); for (j = 0; j < (a->names[i].len >> 1); j++) a->names[i].data[j] = (buf+idx)[j*2]; /* But what are we going to do with it? */ idx += pad_to_4byte(a->names[i].len); } } else { /* get the 'real' name */ CHECKINT32(idx, len); a->name = GETINT32(buf+idx); idx+= 4; } } /* * Multi-value types and string/object/binary types have * multiple values */ if (a->type & MULTI_VALUE_FLAG || a->type == szMAPI_STRING || a->type == szMAPI_UNICODE_STRING || a->type == szMAPI_OBJECT || a->type == szMAPI_BINARY) { CHECKINT32(idx, len); a->num_values = GETINT32(buf+idx); idx += 4; } else { a->num_values = 1; } /* Amend the type in case of multi-value type */ if (a->type & MULTI_VALUE_FLAG) { a->type -= MULTI_VALUE_FLAG; } v = alloc_mapi_values (a); for (j = 0; j < a->num_values; j++) { switch (a->type) { case szMAPI_SHORT: /* 2 bytes */ v->len = 2; CHECKINT16(idx, len); v->data.bytes2 = GETINT16(buf+idx); idx += 4; /* assume padding of 2, advance by 4! */ break; case szMAPI_INT: /* 4 bytes */ v->len = 4; CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); idx += 4; v++; break; case szMAPI_FLOAT: /* 4 bytes */ case szMAPI_BOOLEAN: /* this should be 2 bytes + 2 padding */ v->len = 4; CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); idx += v->len; break; case szMAPI_SYSTIME: /* 8 bytes */ v->len = 8; CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); idx += 8; v++; break; case szMAPI_DOUBLE: /* 8 bytes */ case szMAPI_APPTIME: case szMAPI_CURRENCY: case szMAPI_INT8BYTE: v->len = 8; CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); idx += v->len; break; case szMAPI_CLSID: v->len = sizeof (GUID); copy_guid_from_buf(&v->data.guid, buf+idx, len); idx += v->len; break; case szMAPI_STRING: case szMAPI_UNICODE_STRING: case szMAPI_OBJECT: case szMAPI_BINARY: CHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4; assert(v->len + idx <= len); if (a->type == szMAPI_UNICODE_STRING) { assert(v->len != 0); v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx); } else { v->data.buf = CHECKED_XMALLOC(unsigned char, v->len); memmove (v->data.buf, buf+idx, v->len); } idx += pad_to_4byte(v->len); v++; break; case szMAPI_NULL: /* illegal in input tnef streams */ case szMAPI_ERROR: case szMAPI_UNSPECIFIED: fprintf (stderr, "Invalid attribute, input file may be corrupted\n"); if (!ENCODE_SKIP) exit (1); return NULL; default: /* should never get here */ fprintf (stderr, "Undefined attribute, input file may be corrupted\n"); if (!ENCODE_SKIP) exit (1); return NULL; } if (DEBUG_ON) mapi_attr_dump (attrs[i]); } } attrs[i] = NULL; return attrs; }
168,360
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int WebContentsImpl::DownloadImage( const GURL& url, bool is_favicon, uint32_t max_bitmap_size, bool bypass_cache, const WebContents::ImageDownloadCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); static int next_image_download_id = 0; const image_downloader::ImageDownloaderPtr& mojo_image_downloader = GetMainFrame()->GetMojoImageDownloader(); const int download_id = ++next_image_download_id; if (!mojo_image_downloader) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&WebContents::ImageDownloadCallback::Run, base::Owned(new ImageDownloadCallback(callback)), download_id, 400, url, std::vector<SkBitmap>(), std::vector<gfx::Size>())); return download_id; } image_downloader::DownloadRequestPtr req = image_downloader::DownloadRequest::New(); req->url = mojo::String::From(url); req->is_favicon = is_favicon; req->max_bitmap_size = max_bitmap_size; req->bypass_cache = bypass_cache; mojo_image_downloader->DownloadImage( std::move(req), base::Bind(&DidDownloadImage, callback, download_id, url)); return download_id; } Commit Message: Don't call WebContents::DownloadImage() callback if the WebContents were deleted BUG=583718 Review URL: https://codereview.chromium.org/1685343004 Cr-Commit-Position: refs/heads/master@{#375700} CWE ID:
int WebContentsImpl::DownloadImage( const GURL& url, bool is_favicon, uint32_t max_bitmap_size, bool bypass_cache, const WebContents::ImageDownloadCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); static int next_image_download_id = 0; const image_downloader::ImageDownloaderPtr& mojo_image_downloader = GetMainFrame()->GetMojoImageDownloader(); const int download_id = ++next_image_download_id; if (!mojo_image_downloader) { image_downloader::DownloadResultPtr result = image_downloader::DownloadResult::New(); result->http_status_code = 400; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&WebContentsImpl::OnDidDownloadImage, weak_factory_.GetWeakPtr(), callback, download_id, url, base::Passed(&result))); return download_id; } image_downloader::DownloadRequestPtr req = image_downloader::DownloadRequest::New(); req->url = mojo::String::From(url); req->is_favicon = is_favicon; req->max_bitmap_size = max_bitmap_size; req->bypass_cache = bypass_cache; mojo_image_downloader->DownloadImage( std::move(req), base::Bind(&WebContentsImpl::OnDidDownloadImage, weak_factory_.GetWeakPtr(), callback, download_id, url)); return download_id; }
172,210
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int PDFiumEngine::GetMostVisiblePage() { if (in_flight_visible_page_) return *in_flight_visible_page_; CalculateVisiblePages(); return most_visible_page_; } Commit Message: [pdf] Defer page unloading in JS callback. One of the callbacks from PDFium JavaScript into the embedder is to get the current page number. In Chromium, this will trigger a call to CalculateMostVisiblePage that method will determine the visible pages and unload any non-visible pages. But, if the originating JS is on a non-visible page we'll delete the page and annotations associated with that page. This will cause issues as we are currently working with those objects when the JavaScript returns. This Cl defers the page unloading triggered by getting the most visible page until the next event is handled by the Chromium embedder. BUG=chromium:653090 Review-Url: https://codereview.chromium.org/2418533002 Cr-Commit-Position: refs/heads/master@{#424781} CWE ID: CWE-416
int PDFiumEngine::GetMostVisiblePage() { if (in_flight_visible_page_) return *in_flight_visible_page_; // We can call GetMostVisiblePage through a callback from PDFium. We have // to defer the page deletion otherwise we could potentially delete the page // that originated the calling JS request and destroy the objects that are // currently being used. defer_page_unload_ = true; CalculateVisiblePages(); defer_page_unload_ = false; return most_visible_page_; }
172,514
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SyncManager::SyncInternal::OnIPAddressChanged() { DVLOG(1) << "IP address change detected"; if (!observing_ip_address_changes_) { DVLOG(1) << "IP address change dropped."; return; } #if defined (OS_CHROMEOS) MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&SyncInternal::OnIPAddressChangedImpl, weak_ptr_factory_.GetWeakPtr()), kChromeOSNetworkChangeReactionDelayHackMsec); #else OnIPAddressChangedImpl(); #endif // defined(OS_CHROMEOS) } Commit Message: sync: remove Chrome OS specific logic to deal with flimflam shutdown / sync race. No longer necessary as the ProfileSyncService now aborts sync network traffic on shutdown. BUG=chromium-os:20841 Review URL: http://codereview.chromium.org/9358007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@120912 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void SyncManager::SyncInternal::OnIPAddressChanged() { DVLOG(1) << "IP address change detected"; if (!observing_ip_address_changes_) { DVLOG(1) << "IP address change dropped."; return; } OnIPAddressChangedImpl(); }
170,987
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int arch_dup_task_struct(struct task_struct *dst, struct task_struct *src) { flush_fp_to_thread(src); flush_altivec_to_thread(src); flush_vsx_to_thread(src); flush_spe_to_thread(src); *dst = *src; clear_task_ebb(dst); return 0; } Commit Message: powerpc/tm: Fix crash when forking inside a transaction When we fork/clone we currently don't copy any of the TM state to the new thread. This results in a TM bad thing (program check) when the new process is switched in as the kernel does a tmrechkpt with TEXASR FS not set. Also, since R1 is from userspace, we trigger the bad kernel stack pointer detection. So we end up with something like this: Bad kernel stack pointer 0 at c0000000000404fc cpu 0x2: Vector: 700 (Program Check) at [c00000003ffefd40] pc: c0000000000404fc: restore_gprs+0xc0/0x148 lr: 0000000000000000 sp: 0 msr: 9000000100201030 current = 0xc000001dd1417c30 paca = 0xc00000000fe00800 softe: 0 irq_happened: 0x01 pid = 0, comm = swapper/2 WARNING: exception is not recoverable, can't continue The below fixes this by flushing the TM state before we copy the task_struct to the clone. To do this we go through the tmreclaim patch, which removes the checkpointed registers from the CPU and transitions the CPU out of TM suspend mode. Hence we need to call tmrechkpt after to restore the checkpointed state and the TM mode for the current task. To make this fail from userspace is simply: tbegin li r0, 2 sc <boom> Kudos to Adhemerval Zanella Neto for finding this. Signed-off-by: Michael Neuling <[email protected]> cc: Adhemerval Zanella Neto <[email protected]> cc: [email protected] Signed-off-by: Benjamin Herrenschmidt <[email protected]> CWE ID: CWE-20
int arch_dup_task_struct(struct task_struct *dst, struct task_struct *src) { flush_fp_to_thread(src); flush_altivec_to_thread(src); flush_vsx_to_thread(src); flush_spe_to_thread(src); /* * Flush TM state out so we can copy it. __switch_to_tm() does this * flush but it removes the checkpointed state from the current CPU and * transitions the CPU out of TM mode. Hence we need to call * tm_recheckpoint_new_task() (on the same task) to restore the * checkpointed state back and the TM mode. */ __switch_to_tm(src); tm_recheckpoint_new_task(src); *dst = *src; clear_task_ebb(dst); return 0; }
166,394
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Tracks::ParseTrackEntry( long long track_start, long long track_size, long long element_start, long long element_size, Track*& pResult) const { if (pResult) return -1; IMkvReader* const pReader = m_pSegment->m_pReader; long long pos = track_start; const long long track_stop = track_start + track_size; Track::Info info; info.type = 0; info.number = 0; info.uid = 0; info.defaultDuration = 0; Track::Settings v; v.start = -1; v.size = -1; Track::Settings a; a.start = -1; a.size = -1; Track::Settings e; //content_encodings_settings; e.start = -1; e.size = -1; long long lacing = 1; //default is true while (pos < track_stop) { long long id, size; const long status = ParseElementHeader( pReader, pos, track_stop, id, size); if (status < 0) //error return status; if (size < 0) return E_FILE_FORMAT_INVALID; const long long start = pos; if (id == 0x60) // VideoSettings ID { v.start = start; v.size = size; } else if (id == 0x61) // AudioSettings ID { a.start = start; a.size = size; } else if (id == 0x2D80) // ContentEncodings ID { e.start = start; e.size = size; } else if (id == 0x33C5) //Track UID { if (size > 8) return E_FILE_FORMAT_INVALID; info.uid = 0; long long pos_ = start; const long long pos_end = start + size; while (pos_ != pos_end) { unsigned char b; const int status = pReader->Read(pos_, 1, &b); if (status) return status; info.uid <<= 8; info.uid |= b; ++pos_; } } else if (id == 0x57) //Track Number { const long long num = UnserializeUInt(pReader, pos, size); if ((num <= 0) || (num > 127)) return E_FILE_FORMAT_INVALID; info.number = static_cast<long>(num); } else if (id == 0x03) //Track Type { const long long type = UnserializeUInt(pReader, pos, size); if ((type <= 0) || (type > 254)) return E_FILE_FORMAT_INVALID; info.type = static_cast<long>(type); } else if (id == 0x136E) //Track Name { const long status = UnserializeString( pReader, pos, size, info.nameAsUTF8); if (status) return status; } else if (id == 0x02B59C) //Track Language { const long status = UnserializeString( pReader, pos, size, info.language); if (status) return status; } else if (id == 0x03E383) //Default Duration { const long long duration = UnserializeUInt(pReader, pos, size); if (duration < 0) return E_FILE_FORMAT_INVALID; info.defaultDuration = static_cast<unsigned long long>(duration); } else if (id == 0x06) //CodecID { const long status = UnserializeString( pReader, pos, size, info.codecId); if (status) return status; } else if (id == 0x1C) //lacing { lacing = UnserializeUInt(pReader, pos, size); if ((lacing < 0) || (lacing > 1)) return E_FILE_FORMAT_INVALID; } else if (id == 0x23A2) //Codec Private { delete[] info.codecPrivate; info.codecPrivate = NULL; info.codecPrivateSize = 0; const size_t buflen = static_cast<size_t>(size); if (buflen) { typedef unsigned char* buf_t; const buf_t buf = new (std::nothrow) unsigned char[buflen]; if (buf == NULL) return -1; const int status = pReader->Read(pos, buflen, buf); if (status) { delete[] buf; return status; } info.codecPrivate = buf; info.codecPrivateSize = buflen; } } else if (id == 0x058688) //Codec Name { const long status = UnserializeString( pReader, pos, size, info.codecNameAsUTF8); if (status) return status; } else if (id == 0x16AA) //Codec Delay { info.codecDelay = UnserializeUInt(pReader, pos, size); } else if (id == 0x16BB) //Seek Pre Roll { info.seekPreRoll = UnserializeUInt(pReader, pos, size); } pos += size; //consume payload assert(pos <= track_stop); } assert(pos == track_stop); if (info.number <= 0) //not specified return E_FILE_FORMAT_INVALID; if (GetTrackByNumber(info.number)) return E_FILE_FORMAT_INVALID; if (info.type <= 0) //not specified return E_FILE_FORMAT_INVALID; info.lacing = (lacing > 0) ? true : false; if (info.type == Track::kVideo) { if (v.start < 0) return E_FILE_FORMAT_INVALID; if (a.start >= 0) return E_FILE_FORMAT_INVALID; info.settings = v; VideoTrack* pTrack = NULL; const long status = VideoTrack::Parse(m_pSegment, info, element_start, element_size, pTrack); if (status) return status; pResult = pTrack; assert(pResult); if (e.start >= 0) pResult->ParseContentEncodingsEntry(e.start, e.size); } else if (info.type == Track::kAudio) { if (a.start < 0) return E_FILE_FORMAT_INVALID; if (v.start >= 0) return E_FILE_FORMAT_INVALID; info.settings = a; AudioTrack* pTrack = NULL; const long status = AudioTrack::Parse(m_pSegment, info, element_start, element_size, pTrack); if (status) return status; pResult = pTrack; assert(pResult); if (e.start >= 0) pResult->ParseContentEncodingsEntry(e.start, e.size); } else { if (a.start >= 0) return E_FILE_FORMAT_INVALID; if (v.start >= 0) return E_FILE_FORMAT_INVALID; if (e.start >= 0) return E_FILE_FORMAT_INVALID; info.settings.start = -1; info.settings.size = 0; Track* pTrack = NULL; const long status = Track::Create(m_pSegment, info, element_start, element_size, pTrack); if (status) return status; pResult = pTrack; assert(pResult); } return 0; //success } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Tracks::ParseTrackEntry(
174,430
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ras_getcmap(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap) { int i; int j; int x; int c; int numcolors; int actualnumcolors; switch (hdr->maptype) { case RAS_MT_NONE: break; case RAS_MT_EQUALRGB: { jas_eprintf("warning: palettized images not fully supported\n"); numcolors = 1 << hdr->depth; assert(numcolors <= RAS_CMAP_MAXSIZ); actualnumcolors = hdr->maplength / 3; for (i = 0; i < numcolors; i++) { cmap->data[i] = 0; } if ((hdr->maplength % 3) || hdr->maplength < 0 || hdr->maplength > 3 * numcolors) { return -1; } for (i = 0; i < 3; i++) { for (j = 0; j < actualnumcolors; j++) { if ((c = jas_stream_getc(in)) == EOF) { return -1; } x = 0; switch (i) { case 0: x = RAS_RED(c); break; case 1: x = RAS_GREEN(c); break; case 2: x = RAS_BLUE(c); break; } cmap->data[j] |= x; } } } break; default: return -1; break; } return 0; } Commit Message: Fixed a few bugs in the RAS encoder and decoder where errors were tested with assertions instead of being gracefully handled. CWE ID:
static int ras_getcmap(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap) { int i; int j; int x; int c; int numcolors; int actualnumcolors; switch (hdr->maptype) { case RAS_MT_NONE: break; case RAS_MT_EQUALRGB: { jas_eprintf("warning: palettized images not fully supported\n"); numcolors = 1 << hdr->depth; if (numcolors > RAS_CMAP_MAXSIZ) { return -1; } actualnumcolors = hdr->maplength / 3; for (i = 0; i < numcolors; i++) { cmap->data[i] = 0; } if ((hdr->maplength % 3) || hdr->maplength < 0 || hdr->maplength > 3 * numcolors) { return -1; } for (i = 0; i < 3; i++) { for (j = 0; j < actualnumcolors; j++) { if ((c = jas_stream_getc(in)) == EOF) { return -1; } x = 0; switch (i) { case 0: x = RAS_RED(c); break; case 1: x = RAS_GREEN(c); break; case 2: x = RAS_BLUE(c); break; } cmap->data[j] |= x; } } } break; default: return -1; break; } return 0; }
168,739
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintPreviewUI::OnPrintPreviewRequest(int request_id) { g_print_preview_request_id_map.Get().Set(preview_ui_addr_str_, request_id); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void PrintPreviewUI::OnPrintPreviewRequest(int request_id) { g_print_preview_request_id_map.Get().Set(id_, request_id); }
170,839
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long Block::GetTime(const Cluster* pCluster) const { assert(pCluster); const long long tc = GetTimeCode(pCluster); const Segment* const pSegment = pCluster->m_pSegment; const SegmentInfo* const pInfo = pSegment->GetInfo(); assert(pInfo); const long long scale = pInfo->GetTimeCodeScale(); assert(scale >= 1); const long long ns = tc * scale; return ns; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long Block::GetTime(const Cluster* pCluster) const const long long tc = GetTimeCode(pCluster); const Segment* const pSegment = pCluster->m_pSegment; const SegmentInfo* const pInfo = pSegment->GetInfo(); assert(pInfo); const long long scale = pInfo->GetTimeCodeScale(); assert(scale >= 1); const long long ns = tc * scale; return ns; }
174,363
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *run) { int ret; sigset_t sigsaved; /* Make sure they initialize the vcpu with KVM_ARM_VCPU_INIT */ if (unlikely(vcpu->arch.target < 0)) return -ENOEXEC; ret = kvm_vcpu_first_run_init(vcpu); if (ret) return ret; if (run->exit_reason == KVM_EXIT_MMIO) { ret = kvm_handle_mmio_return(vcpu, vcpu->run); if (ret) return ret; } if (vcpu->sigset_active) sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved); ret = 1; run->exit_reason = KVM_EXIT_UNKNOWN; while (ret > 0) { /* * Check conditions before entering the guest */ cond_resched(); update_vttbr(vcpu->kvm); if (vcpu->arch.pause) vcpu_pause(vcpu); kvm_vgic_flush_hwstate(vcpu); kvm_timer_flush_hwstate(vcpu); local_irq_disable(); /* * Re-check atomic conditions */ if (signal_pending(current)) { ret = -EINTR; run->exit_reason = KVM_EXIT_INTR; } if (ret <= 0 || need_new_vmid_gen(vcpu->kvm)) { local_irq_enable(); kvm_timer_sync_hwstate(vcpu); kvm_vgic_sync_hwstate(vcpu); continue; } /************************************************************** * Enter the guest */ trace_kvm_entry(*vcpu_pc(vcpu)); kvm_guest_enter(); vcpu->mode = IN_GUEST_MODE; ret = kvm_call_hyp(__kvm_vcpu_run, vcpu); vcpu->mode = OUTSIDE_GUEST_MODE; vcpu->arch.last_pcpu = smp_processor_id(); kvm_guest_exit(); trace_kvm_exit(*vcpu_pc(vcpu)); /* * We may have taken a host interrupt in HYP mode (ie * while executing the guest). This interrupt is still * pending, as we haven't serviced it yet! * * We're now back in SVC mode, with interrupts * disabled. Enabling the interrupts now will have * the effect of taking the interrupt again, in SVC * mode this time. */ local_irq_enable(); /* * Back from guest *************************************************************/ kvm_timer_sync_hwstate(vcpu); kvm_vgic_sync_hwstate(vcpu); ret = handle_exit(vcpu, run, ret); } if (vcpu->sigset_active) sigprocmask(SIG_SETMASK, &sigsaved, NULL); return ret; } Commit Message: ARM: KVM: prevent NULL pointer dereferences with KVM VCPU ioctl Some ARM KVM VCPU ioctls require the vCPU to be properly initialized with the KVM_ARM_VCPU_INIT ioctl before being used with further requests. KVM_RUN checks whether this initialization has been done, but other ioctls do not. Namely KVM_GET_REG_LIST will dereference an array with index -1 without initialization and thus leads to a kernel oops. Fix this by adding checks before executing the ioctl handlers. [ Removed superflous comment from static function - Christoffer ] Changes from v1: * moved check into a static function with a meaningful name Signed-off-by: Andre Przywara <[email protected]> Signed-off-by: Christoffer Dall <[email protected]> CWE ID: CWE-399
int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *run) { int ret; sigset_t sigsaved; if (unlikely(!kvm_vcpu_initialized(vcpu))) return -ENOEXEC; ret = kvm_vcpu_first_run_init(vcpu); if (ret) return ret; if (run->exit_reason == KVM_EXIT_MMIO) { ret = kvm_handle_mmio_return(vcpu, vcpu->run); if (ret) return ret; } if (vcpu->sigset_active) sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved); ret = 1; run->exit_reason = KVM_EXIT_UNKNOWN; while (ret > 0) { /* * Check conditions before entering the guest */ cond_resched(); update_vttbr(vcpu->kvm); if (vcpu->arch.pause) vcpu_pause(vcpu); kvm_vgic_flush_hwstate(vcpu); kvm_timer_flush_hwstate(vcpu); local_irq_disable(); /* * Re-check atomic conditions */ if (signal_pending(current)) { ret = -EINTR; run->exit_reason = KVM_EXIT_INTR; } if (ret <= 0 || need_new_vmid_gen(vcpu->kvm)) { local_irq_enable(); kvm_timer_sync_hwstate(vcpu); kvm_vgic_sync_hwstate(vcpu); continue; } /************************************************************** * Enter the guest */ trace_kvm_entry(*vcpu_pc(vcpu)); kvm_guest_enter(); vcpu->mode = IN_GUEST_MODE; ret = kvm_call_hyp(__kvm_vcpu_run, vcpu); vcpu->mode = OUTSIDE_GUEST_MODE; vcpu->arch.last_pcpu = smp_processor_id(); kvm_guest_exit(); trace_kvm_exit(*vcpu_pc(vcpu)); /* * We may have taken a host interrupt in HYP mode (ie * while executing the guest). This interrupt is still * pending, as we haven't serviced it yet! * * We're now back in SVC mode, with interrupts * disabled. Enabling the interrupts now will have * the effect of taking the interrupt again, in SVC * mode this time. */ local_irq_enable(); /* * Back from guest *************************************************************/ kvm_timer_sync_hwstate(vcpu); kvm_vgic_sync_hwstate(vcpu); ret = handle_exit(vcpu, run, ret); } if (vcpu->sigset_active) sigprocmask(SIG_SETMASK, &sigsaved, NULL); return ret; }
165,953
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_MODERATELY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet(icu::UnicodeString("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; transliterator_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d; ӏ > l; [кĸκ] > k; п > n;"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); } Commit Message: Change the script mixing policy to highly restrictive The current script mixing policy (moderately restricitive) allows mixing of Latin-ASCII and one non-Latin script (unless the non-Latin script is Cyrillic or Greek). This CL tightens up the policy to block mixing of Latin-ASCII and a non-Latin script unless the non-Latin script is Chinese (Hanzi, Bopomofo), Japanese (Kanji, Hiragana, Katakana) or Korean (Hangul, Hanja). Major gTLDs (.net/.org/.com) do not allow the registration of a domain that has both Latin and a non-Latin script. The only exception is names with Latin + Chinese/Japanese/Korean scripts. The same is true of ccTLDs with IDNs. Given the above registration rules of major gTLDs and ccTLDs, allowing mixing of Latin and non-Latin other than CJK has no practical effect. In the meantime, domain names in TLDs with a laxer policy on script mixing would be subject to a potential spoofing attempt with the current moderately restrictive script mixing policy. To protect users from those risks, there are a few ad-hoc rules in place. By switching to highly restrictive those ad-hoc rules can be removed simplifying the IDN display policy implementation a bit. This is also coordinated with Mozilla. See https://bugzilla.mozilla.org/show_bug.cgi?id=1399939 . BUG=726950, 756226, 756456, 756735, 770465 TEST=components_unittests --gtest_filter=*IDN* Change-Id: Ib96d0d588f7fcda38ffa0ce59e98a5bd5b439116 Reviewed-on: https://chromium-review.googlesource.com/688825 Reviewed-by: Brett Wilson <[email protected]> Reviewed-by: Lucas Garron <[email protected]> Commit-Queue: Jungshik Shin <[email protected]> Cr-Commit-Position: refs/heads/master@{#506561} CWE ID: CWE-20
IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } // Set the restriction level to high. It allows mixing Latin with one logical // CJK script (+ COMMON and INHERITED), but does not allow any other script // mixing (e.g. Latin + Cyrillic, Latin + Armenian, Cyrillic + Greek). Note // that each of {Han + Bopomofo} for Chinese, {Hiragana, Katakana, Han} for // Japanese, and {Hangul, Han} for Korean is treated as a single logical // script. uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet(icu::UnicodeString("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; transliterator_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d; ӏ > l; [кĸκ] > k; п > n;"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); }
172,935
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void __init setup_arch(char **cmdline_p) { memblock_reserve(__pa_symbol(_text), (unsigned long)__bss_stop - (unsigned long)_text); early_reserve_initrd(); /* * At this point everything still needed from the boot loader * or BIOS or kernel text should be early reserved or marked not * RAM in e820. All other memory is free game. */ #ifdef CONFIG_X86_32 memcpy(&boot_cpu_data, &new_cpu_data, sizeof(new_cpu_data)); /* * copy kernel address range established so far and switch * to the proper swapper page table */ clone_pgd_range(swapper_pg_dir + KERNEL_PGD_BOUNDARY, initial_page_table + KERNEL_PGD_BOUNDARY, KERNEL_PGD_PTRS); load_cr3(swapper_pg_dir); /* * Note: Quark X1000 CPUs advertise PGE incorrectly and require * a cr3 based tlb flush, so the following __flush_tlb_all() * will not flush anything because the cpu quirk which clears * X86_FEATURE_PGE has not been invoked yet. Though due to the * load_cr3() above the TLB has been flushed already. The * quirk is invoked before subsequent calls to __flush_tlb_all() * so proper operation is guaranteed. */ __flush_tlb_all(); #else printk(KERN_INFO "Command line: %s\n", boot_command_line); #endif /* * If we have OLPC OFW, we might end up relocating the fixmap due to * reserve_top(), so do this before touching the ioremap area. */ olpc_ofw_detect(); early_trap_init(); early_cpu_init(); early_ioremap_init(); setup_olpc_ofw_pgd(); ROOT_DEV = old_decode_dev(boot_params.hdr.root_dev); screen_info = boot_params.screen_info; edid_info = boot_params.edid_info; #ifdef CONFIG_X86_32 apm_info.bios = boot_params.apm_bios_info; ist_info = boot_params.ist_info; #endif saved_video_mode = boot_params.hdr.vid_mode; bootloader_type = boot_params.hdr.type_of_loader; if ((bootloader_type >> 4) == 0xe) { bootloader_type &= 0xf; bootloader_type |= (boot_params.hdr.ext_loader_type+0x10) << 4; } bootloader_version = bootloader_type & 0xf; bootloader_version |= boot_params.hdr.ext_loader_ver << 4; #ifdef CONFIG_BLK_DEV_RAM rd_image_start = boot_params.hdr.ram_size & RAMDISK_IMAGE_START_MASK; rd_prompt = ((boot_params.hdr.ram_size & RAMDISK_PROMPT_FLAG) != 0); rd_doload = ((boot_params.hdr.ram_size & RAMDISK_LOAD_FLAG) != 0); #endif #ifdef CONFIG_EFI if (!strncmp((char *)&boot_params.efi_info.efi_loader_signature, EFI32_LOADER_SIGNATURE, 4)) { set_bit(EFI_BOOT, &efi.flags); } else if (!strncmp((char *)&boot_params.efi_info.efi_loader_signature, EFI64_LOADER_SIGNATURE, 4)) { set_bit(EFI_BOOT, &efi.flags); set_bit(EFI_64BIT, &efi.flags); } if (efi_enabled(EFI_BOOT)) efi_memblock_x86_reserve_range(); #endif x86_init.oem.arch_setup(); iomem_resource.end = (1ULL << boot_cpu_data.x86_phys_bits) - 1; setup_memory_map(); parse_setup_data(); copy_edd(); if (!boot_params.hdr.root_flags) root_mountflags &= ~MS_RDONLY; init_mm.start_code = (unsigned long) _text; init_mm.end_code = (unsigned long) _etext; init_mm.end_data = (unsigned long) _edata; init_mm.brk = _brk_end; mpx_mm_init(&init_mm); code_resource.start = __pa_symbol(_text); code_resource.end = __pa_symbol(_etext)-1; data_resource.start = __pa_symbol(_etext); data_resource.end = __pa_symbol(_edata)-1; bss_resource.start = __pa_symbol(__bss_start); bss_resource.end = __pa_symbol(__bss_stop)-1; #ifdef CONFIG_CMDLINE_BOOL #ifdef CONFIG_CMDLINE_OVERRIDE strlcpy(boot_command_line, builtin_cmdline, COMMAND_LINE_SIZE); #else if (builtin_cmdline[0]) { /* append boot loader cmdline to builtin */ strlcat(builtin_cmdline, " ", COMMAND_LINE_SIZE); strlcat(builtin_cmdline, boot_command_line, COMMAND_LINE_SIZE); strlcpy(boot_command_line, builtin_cmdline, COMMAND_LINE_SIZE); } #endif #endif strlcpy(command_line, boot_command_line, COMMAND_LINE_SIZE); *cmdline_p = command_line; /* * x86_configure_nx() is called before parse_early_param() to detect * whether hardware doesn't support NX (so that the early EHCI debug * console setup can safely call set_fixmap()). It may then be called * again from within noexec_setup() during parsing early parameters * to honor the respective command line option. */ x86_configure_nx(); parse_early_param(); x86_report_nx(); /* after early param, so could get panic from serial */ memblock_x86_reserve_range_setup_data(); if (acpi_mps_check()) { #ifdef CONFIG_X86_LOCAL_APIC disable_apic = 1; #endif setup_clear_cpu_cap(X86_FEATURE_APIC); } #ifdef CONFIG_PCI if (pci_early_dump_regs) early_dump_pci_devices(); #endif /* update the e820_saved too */ e820_reserve_setup_data(); finish_e820_parsing(); if (efi_enabled(EFI_BOOT)) efi_init(); dmi_scan_machine(); dmi_memdev_walk(); dmi_set_dump_stack_arch_desc(); /* * VMware detection requires dmi to be available, so this * needs to be done after dmi_scan_machine, for the BP. */ init_hypervisor_platform(); x86_init.resources.probe_roms(); /* after parse_early_param, so could debug it */ insert_resource(&iomem_resource, &code_resource); insert_resource(&iomem_resource, &data_resource); insert_resource(&iomem_resource, &bss_resource); e820_add_kernel_range(); trim_bios_range(); #ifdef CONFIG_X86_32 if (ppro_with_ram_bug()) { e820_update_range(0x70000000ULL, 0x40000ULL, E820_RAM, E820_RESERVED); sanitize_e820_map(e820.map, ARRAY_SIZE(e820.map), &e820.nr_map); printk(KERN_INFO "fixed physical RAM map:\n"); e820_print_map("bad_ppro"); } #else early_gart_iommu_check(); #endif /* * partially used pages are not usable - thus * we are rounding upwards: */ max_pfn = e820_end_of_ram_pfn(); /* update e820 for memory not covered by WB MTRRs */ mtrr_bp_init(); if (mtrr_trim_uncached_memory(max_pfn)) max_pfn = e820_end_of_ram_pfn(); max_possible_pfn = max_pfn; #ifdef CONFIG_X86_32 /* max_low_pfn get updated here */ find_low_pfn_range(); #else check_x2apic(); /* How many end-of-memory variables you have, grandma! */ /* need this before calling reserve_initrd */ if (max_pfn > (1UL<<(32 - PAGE_SHIFT))) max_low_pfn = e820_end_of_low_ram_pfn(); else max_low_pfn = max_pfn; high_memory = (void *)__va(max_pfn * PAGE_SIZE - 1) + 1; #endif /* * Find and reserve possible boot-time SMP configuration: */ find_smp_config(); reserve_ibft_region(); early_alloc_pgt_buf(); /* * Need to conclude brk, before memblock_x86_fill() * it could use memblock_find_in_range, could overlap with * brk area. */ reserve_brk(); cleanup_highmap(); memblock_set_current_limit(ISA_END_ADDRESS); memblock_x86_fill(); if (efi_enabled(EFI_BOOT)) { efi_fake_memmap(); efi_find_mirror(); } /* * The EFI specification says that boot service code won't be called * after ExitBootServices(). This is, in fact, a lie. */ if (efi_enabled(EFI_MEMMAP)) efi_reserve_boot_services(); /* preallocate 4k for mptable mpc */ early_reserve_e820_mpc_new(); #ifdef CONFIG_X86_CHECK_BIOS_CORRUPTION setup_bios_corruption_check(); #endif #ifdef CONFIG_X86_32 printk(KERN_DEBUG "initial memory mapped: [mem 0x00000000-%#010lx]\n", (max_pfn_mapped<<PAGE_SHIFT) - 1); #endif reserve_real_mode(); trim_platform_memory_ranges(); trim_low_memory_range(); init_mem_mapping(); early_trap_pf_init(); setup_real_mode(); memblock_set_current_limit(get_max_mapped()); /* * NOTE: On x86-32, only from this point on, fixmaps are ready for use. */ #ifdef CONFIG_PROVIDE_OHCI1394_DMA_INIT if (init_ohci1394_dma_early) init_ohci1394_dma_on_all_controllers(); #endif /* Allocate bigger log buffer */ setup_log_buf(1); reserve_initrd(); #if defined(CONFIG_ACPI) && defined(CONFIG_BLK_DEV_INITRD) acpi_initrd_override((void *)initrd_start, initrd_end - initrd_start); #endif vsmp_init(); io_delay_init(); #ifdef CONFIG_EFI_SECURE_BOOT_SECURELEVEL if (boot_params.secure_boot) { set_securelevel(1); } #endif /* * Parse the ACPI tables for possible boot-time SMP configuration. */ acpi_boot_table_init(); early_acpi_boot_init(); initmem_init(); dma_contiguous_reserve(max_pfn_mapped << PAGE_SHIFT); /* * Reserve memory for crash kernel after SRAT is parsed so that it * won't consume hotpluggable memory. */ reserve_crashkernel(); memblock_find_dma_reserve(); #ifdef CONFIG_KVM_GUEST kvmclock_init(); #endif x86_init.paging.pagetable_init(); kasan_init(); if (boot_cpu_data.cpuid_level >= 0) { /* A CPU has %cr4 if and only if it has CPUID */ mmu_cr4_features = __read_cr4(); if (trampoline_cr4_features) *trampoline_cr4_features = mmu_cr4_features; } #ifdef CONFIG_X86_32 /* sync back kernel address range */ clone_pgd_range(initial_page_table + KERNEL_PGD_BOUNDARY, swapper_pg_dir + KERNEL_PGD_BOUNDARY, KERNEL_PGD_PTRS); /* * sync back low identity map too. It is used for example * in the 32-bit EFI stub. */ clone_pgd_range(initial_page_table, swapper_pg_dir + KERNEL_PGD_BOUNDARY, min(KERNEL_PGD_PTRS, KERNEL_PGD_BOUNDARY)); #endif tboot_probe(); map_vsyscall(); generic_apic_probe(); early_quirks(); /* * Read APIC and some other early information from ACPI tables. */ acpi_boot_init(); sfi_init(); x86_dtb_init(); /* * get boot-time SMP configuration: */ if (smp_found_config) get_smp_config(); prefill_possible_map(); init_cpu_to_node(); init_apic_mappings(); io_apic_init_mappings(); kvm_guest_init(); e820_reserve_resources(); e820_mark_nosave_regions(max_low_pfn); x86_init.resources.reserve_resources(); e820_setup_gap(); #ifdef CONFIG_VT #if defined(CONFIG_VGA_CONSOLE) if (!efi_enabled(EFI_BOOT) || (efi_mem_type(0xa0000) != EFI_CONVENTIONAL_MEMORY)) conswitchp = &vga_con; #elif defined(CONFIG_DUMMY_CONSOLE) conswitchp = &dummy_con; #endif #endif x86_init.oem.banner(); x86_init.timers.wallclock_init(); mcheck_init(); arch_init_ideal_nops(); register_refined_jiffies(CLOCK_TICK_RATE); #ifdef CONFIG_EFI if (efi_enabled(EFI_BOOT)) efi_apply_memmap_quirks(); #endif } Commit Message: acpi: Disable ACPI table override if securelevel is set From the kernel documentation (initrd_table_override.txt): If the ACPI_INITRD_TABLE_OVERRIDE compile option is true, it is possible to override nearly any ACPI table provided by the BIOS with an instrumented, modified one. When securelevel is set, the kernel should disallow any unauthenticated changes to kernel space. ACPI tables contain code invoked by the kernel, so do not allow ACPI tables to be overridden if securelevel is set. Signed-off-by: Linn Crosetto <[email protected]> CWE ID: CWE-264
void __init setup_arch(char **cmdline_p) { memblock_reserve(__pa_symbol(_text), (unsigned long)__bss_stop - (unsigned long)_text); early_reserve_initrd(); /* * At this point everything still needed from the boot loader * or BIOS or kernel text should be early reserved or marked not * RAM in e820. All other memory is free game. */ #ifdef CONFIG_X86_32 memcpy(&boot_cpu_data, &new_cpu_data, sizeof(new_cpu_data)); /* * copy kernel address range established so far and switch * to the proper swapper page table */ clone_pgd_range(swapper_pg_dir + KERNEL_PGD_BOUNDARY, initial_page_table + KERNEL_PGD_BOUNDARY, KERNEL_PGD_PTRS); load_cr3(swapper_pg_dir); /* * Note: Quark X1000 CPUs advertise PGE incorrectly and require * a cr3 based tlb flush, so the following __flush_tlb_all() * will not flush anything because the cpu quirk which clears * X86_FEATURE_PGE has not been invoked yet. Though due to the * load_cr3() above the TLB has been flushed already. The * quirk is invoked before subsequent calls to __flush_tlb_all() * so proper operation is guaranteed. */ __flush_tlb_all(); #else printk(KERN_INFO "Command line: %s\n", boot_command_line); #endif /* * If we have OLPC OFW, we might end up relocating the fixmap due to * reserve_top(), so do this before touching the ioremap area. */ olpc_ofw_detect(); early_trap_init(); early_cpu_init(); early_ioremap_init(); setup_olpc_ofw_pgd(); ROOT_DEV = old_decode_dev(boot_params.hdr.root_dev); screen_info = boot_params.screen_info; edid_info = boot_params.edid_info; #ifdef CONFIG_X86_32 apm_info.bios = boot_params.apm_bios_info; ist_info = boot_params.ist_info; #endif saved_video_mode = boot_params.hdr.vid_mode; bootloader_type = boot_params.hdr.type_of_loader; if ((bootloader_type >> 4) == 0xe) { bootloader_type &= 0xf; bootloader_type |= (boot_params.hdr.ext_loader_type+0x10) << 4; } bootloader_version = bootloader_type & 0xf; bootloader_version |= boot_params.hdr.ext_loader_ver << 4; #ifdef CONFIG_BLK_DEV_RAM rd_image_start = boot_params.hdr.ram_size & RAMDISK_IMAGE_START_MASK; rd_prompt = ((boot_params.hdr.ram_size & RAMDISK_PROMPT_FLAG) != 0); rd_doload = ((boot_params.hdr.ram_size & RAMDISK_LOAD_FLAG) != 0); #endif #ifdef CONFIG_EFI if (!strncmp((char *)&boot_params.efi_info.efi_loader_signature, EFI32_LOADER_SIGNATURE, 4)) { set_bit(EFI_BOOT, &efi.flags); } else if (!strncmp((char *)&boot_params.efi_info.efi_loader_signature, EFI64_LOADER_SIGNATURE, 4)) { set_bit(EFI_BOOT, &efi.flags); set_bit(EFI_64BIT, &efi.flags); } if (efi_enabled(EFI_BOOT)) efi_memblock_x86_reserve_range(); #endif x86_init.oem.arch_setup(); iomem_resource.end = (1ULL << boot_cpu_data.x86_phys_bits) - 1; setup_memory_map(); parse_setup_data(); copy_edd(); if (!boot_params.hdr.root_flags) root_mountflags &= ~MS_RDONLY; init_mm.start_code = (unsigned long) _text; init_mm.end_code = (unsigned long) _etext; init_mm.end_data = (unsigned long) _edata; init_mm.brk = _brk_end; mpx_mm_init(&init_mm); code_resource.start = __pa_symbol(_text); code_resource.end = __pa_symbol(_etext)-1; data_resource.start = __pa_symbol(_etext); data_resource.end = __pa_symbol(_edata)-1; bss_resource.start = __pa_symbol(__bss_start); bss_resource.end = __pa_symbol(__bss_stop)-1; #ifdef CONFIG_CMDLINE_BOOL #ifdef CONFIG_CMDLINE_OVERRIDE strlcpy(boot_command_line, builtin_cmdline, COMMAND_LINE_SIZE); #else if (builtin_cmdline[0]) { /* append boot loader cmdline to builtin */ strlcat(builtin_cmdline, " ", COMMAND_LINE_SIZE); strlcat(builtin_cmdline, boot_command_line, COMMAND_LINE_SIZE); strlcpy(boot_command_line, builtin_cmdline, COMMAND_LINE_SIZE); } #endif #endif strlcpy(command_line, boot_command_line, COMMAND_LINE_SIZE); *cmdline_p = command_line; /* * x86_configure_nx() is called before parse_early_param() to detect * whether hardware doesn't support NX (so that the early EHCI debug * console setup can safely call set_fixmap()). It may then be called * again from within noexec_setup() during parsing early parameters * to honor the respective command line option. */ x86_configure_nx(); parse_early_param(); x86_report_nx(); /* after early param, so could get panic from serial */ memblock_x86_reserve_range_setup_data(); if (acpi_mps_check()) { #ifdef CONFIG_X86_LOCAL_APIC disable_apic = 1; #endif setup_clear_cpu_cap(X86_FEATURE_APIC); } #ifdef CONFIG_PCI if (pci_early_dump_regs) early_dump_pci_devices(); #endif /* update the e820_saved too */ e820_reserve_setup_data(); finish_e820_parsing(); if (efi_enabled(EFI_BOOT)) efi_init(); dmi_scan_machine(); dmi_memdev_walk(); dmi_set_dump_stack_arch_desc(); /* * VMware detection requires dmi to be available, so this * needs to be done after dmi_scan_machine, for the BP. */ init_hypervisor_platform(); x86_init.resources.probe_roms(); /* after parse_early_param, so could debug it */ insert_resource(&iomem_resource, &code_resource); insert_resource(&iomem_resource, &data_resource); insert_resource(&iomem_resource, &bss_resource); e820_add_kernel_range(); trim_bios_range(); #ifdef CONFIG_X86_32 if (ppro_with_ram_bug()) { e820_update_range(0x70000000ULL, 0x40000ULL, E820_RAM, E820_RESERVED); sanitize_e820_map(e820.map, ARRAY_SIZE(e820.map), &e820.nr_map); printk(KERN_INFO "fixed physical RAM map:\n"); e820_print_map("bad_ppro"); } #else early_gart_iommu_check(); #endif /* * partially used pages are not usable - thus * we are rounding upwards: */ max_pfn = e820_end_of_ram_pfn(); /* update e820 for memory not covered by WB MTRRs */ mtrr_bp_init(); if (mtrr_trim_uncached_memory(max_pfn)) max_pfn = e820_end_of_ram_pfn(); max_possible_pfn = max_pfn; #ifdef CONFIG_X86_32 /* max_low_pfn get updated here */ find_low_pfn_range(); #else check_x2apic(); /* How many end-of-memory variables you have, grandma! */ /* need this before calling reserve_initrd */ if (max_pfn > (1UL<<(32 - PAGE_SHIFT))) max_low_pfn = e820_end_of_low_ram_pfn(); else max_low_pfn = max_pfn; high_memory = (void *)__va(max_pfn * PAGE_SIZE - 1) + 1; #endif /* * Find and reserve possible boot-time SMP configuration: */ find_smp_config(); reserve_ibft_region(); early_alloc_pgt_buf(); /* * Need to conclude brk, before memblock_x86_fill() * it could use memblock_find_in_range, could overlap with * brk area. */ reserve_brk(); cleanup_highmap(); memblock_set_current_limit(ISA_END_ADDRESS); memblock_x86_fill(); if (efi_enabled(EFI_BOOT)) { efi_fake_memmap(); efi_find_mirror(); } /* * The EFI specification says that boot service code won't be called * after ExitBootServices(). This is, in fact, a lie. */ if (efi_enabled(EFI_MEMMAP)) efi_reserve_boot_services(); /* preallocate 4k for mptable mpc */ early_reserve_e820_mpc_new(); #ifdef CONFIG_X86_CHECK_BIOS_CORRUPTION setup_bios_corruption_check(); #endif #ifdef CONFIG_X86_32 printk(KERN_DEBUG "initial memory mapped: [mem 0x00000000-%#010lx]\n", (max_pfn_mapped<<PAGE_SHIFT) - 1); #endif reserve_real_mode(); trim_platform_memory_ranges(); trim_low_memory_range(); init_mem_mapping(); early_trap_pf_init(); setup_real_mode(); memblock_set_current_limit(get_max_mapped()); /* * NOTE: On x86-32, only from this point on, fixmaps are ready for use. */ #ifdef CONFIG_PROVIDE_OHCI1394_DMA_INIT if (init_ohci1394_dma_early) init_ohci1394_dma_on_all_controllers(); #endif /* Allocate bigger log buffer */ setup_log_buf(1); #ifdef CONFIG_EFI_SECURE_BOOT_SECURELEVEL if (boot_params.secure_boot) { set_securelevel(1); } #endif reserve_initrd(); #if defined(CONFIG_ACPI) && defined(CONFIG_BLK_DEV_INITRD) acpi_initrd_override((void *)initrd_start, initrd_end - initrd_start); #endif vsmp_init(); io_delay_init(); /* * Parse the ACPI tables for possible boot-time SMP configuration. */ acpi_boot_table_init(); early_acpi_boot_init(); initmem_init(); dma_contiguous_reserve(max_pfn_mapped << PAGE_SHIFT); /* * Reserve memory for crash kernel after SRAT is parsed so that it * won't consume hotpluggable memory. */ reserve_crashkernel(); memblock_find_dma_reserve(); #ifdef CONFIG_KVM_GUEST kvmclock_init(); #endif x86_init.paging.pagetable_init(); kasan_init(); if (boot_cpu_data.cpuid_level >= 0) { /* A CPU has %cr4 if and only if it has CPUID */ mmu_cr4_features = __read_cr4(); if (trampoline_cr4_features) *trampoline_cr4_features = mmu_cr4_features; } #ifdef CONFIG_X86_32 /* sync back kernel address range */ clone_pgd_range(initial_page_table + KERNEL_PGD_BOUNDARY, swapper_pg_dir + KERNEL_PGD_BOUNDARY, KERNEL_PGD_PTRS); /* * sync back low identity map too. It is used for example * in the 32-bit EFI stub. */ clone_pgd_range(initial_page_table, swapper_pg_dir + KERNEL_PGD_BOUNDARY, min(KERNEL_PGD_PTRS, KERNEL_PGD_BOUNDARY)); #endif tboot_probe(); map_vsyscall(); generic_apic_probe(); early_quirks(); /* * Read APIC and some other early information from ACPI tables. */ acpi_boot_init(); sfi_init(); x86_dtb_init(); /* * get boot-time SMP configuration: */ if (smp_found_config) get_smp_config(); prefill_possible_map(); init_cpu_to_node(); init_apic_mappings(); io_apic_init_mappings(); kvm_guest_init(); e820_reserve_resources(); e820_mark_nosave_regions(max_low_pfn); x86_init.resources.reserve_resources(); e820_setup_gap(); #ifdef CONFIG_VT #if defined(CONFIG_VGA_CONSOLE) if (!efi_enabled(EFI_BOOT) || (efi_mem_type(0xa0000) != EFI_CONVENTIONAL_MEMORY)) conswitchp = &vga_con; #elif defined(CONFIG_DUMMY_CONSOLE) conswitchp = &dummy_con; #endif #endif x86_init.oem.banner(); x86_init.timers.wallclock_init(); mcheck_init(); arch_init_ideal_nops(); register_refined_jiffies(CLOCK_TICK_RATE); #ifdef CONFIG_EFI if (efi_enabled(EFI_BOOT)) efi_apply_memmap_quirks(); #endif }
167,346
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cp2112_gpio_direction_input(struct gpio_chip *chip, unsigned offset) { struct cp2112_device *dev = gpiochip_get_data(chip); struct hid_device *hdev = dev->hdev; u8 *buf = dev->in_out_buffer; int ret; mutex_lock(&dev->lock); ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_GET_REPORT); if (ret != CP2112_GPIO_CONFIG_LENGTH) { hid_err(hdev, "error requesting GPIO config: %d\n", ret); goto exit; } buf[1] &= ~(1 << offset); buf[2] = gpio_push_pull; ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_SET_REPORT); if (ret < 0) { hid_err(hdev, "error setting GPIO config: %d\n", ret); goto exit; } ret = 0; exit: mutex_unlock(&dev->lock); return ret <= 0 ? ret : -EIO; } Commit Message: HID: cp2112: fix gpio-callback error handling In case of a zero-length report, the gpio direction_input callback would currently return success instead of an errno. Fixes: 1ffb3c40ffb5 ("HID: cp2112: make transfer buffers DMA capable") Cc: stable <[email protected]> # 4.9 Signed-off-by: Johan Hovold <[email protected]> Reviewed-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-388
static int cp2112_gpio_direction_input(struct gpio_chip *chip, unsigned offset) { struct cp2112_device *dev = gpiochip_get_data(chip); struct hid_device *hdev = dev->hdev; u8 *buf = dev->in_out_buffer; int ret; mutex_lock(&dev->lock); ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_GET_REPORT); if (ret != CP2112_GPIO_CONFIG_LENGTH) { hid_err(hdev, "error requesting GPIO config: %d\n", ret); goto exit; } buf[1] &= ~(1 << offset); buf[2] = gpio_push_pull; ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_SET_REPORT); if (ret < 0) { hid_err(hdev, "error setting GPIO config: %d\n", ret); goto exit; } ret = 0; exit: mutex_unlock(&dev->lock); return ret < 0 ? ret : -EIO; }
168,207
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: const Cues* Segment::GetCues() const { return m_pCues; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
const Cues* Segment::GetCues() const
174,301
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void uwbd_start(struct uwb_rc *rc) { rc->uwbd.task = kthread_run(uwbd, rc, "uwbd"); if (rc->uwbd.task == NULL) printk(KERN_ERR "UWB: Cannot start management daemon; " "UWB won't work\n"); else rc->uwbd.pid = rc->uwbd.task->pid; } Commit Message: uwb: properly check kthread_run return value uwbd_start() calls kthread_run() and checks that the return value is not NULL. But the return value is not NULL in case kthread_run() fails, it takes the form of ERR_PTR(-EINTR). Use IS_ERR() instead. Also add a check to uwbd_stop(). Signed-off-by: Andrey Konovalov <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-119
void uwbd_start(struct uwb_rc *rc) { struct task_struct *task = kthread_run(uwbd, rc, "uwbd"); if (IS_ERR(task)) { rc->uwbd.task = NULL; printk(KERN_ERR "UWB: Cannot start management daemon; " "UWB won't work\n"); } else { rc->uwbd.task = task; rc->uwbd.pid = rc->uwbd.task->pid; } }
167,685
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ParseRiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int is_rf64 = !strncmp (fourcc, "RF64", 4), got_ds64 = 0; int64_t total_samples = 0, infilesize; RiffChunkHeader riff_chunk_header; ChunkHeader chunk_header; WaveHeader WaveHeader; DS64Chunk ds64_chunk; uint32_t bcount; CLEAR (WaveHeader); CLEAR (ds64_chunk); infilesize = DoGetFileSize (infile); if (!is_rf64 && infilesize >= 4294967296LL && !(config->qmode & QMODE_IGNORE_LENGTH)) { error_line ("can't handle .WAV files larger than 4 GB (non-standard)!"); return WAVPACK_SOFT_ERROR; } memcpy (&riff_chunk_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &riff_chunk_header) + 4, sizeof (RiffChunkHeader) - 4, &bcount) || bcount != sizeof (RiffChunkHeader) - 4 || strncmp (riff_chunk_header.formType, "WAVE", 4))) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &riff_chunk_header, sizeof (RiffChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (ChunkHeader), &bcount) || bcount != sizeof (ChunkHeader)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, ChunkHeaderFormat); if (!strncmp (chunk_header.ckID, "ds64", 4)) { if (chunk_header.ckSize < sizeof (DS64Chunk) || !DoReadFile (infile, &ds64_chunk, sizeof (DS64Chunk), &bcount) || bcount != sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &ds64_chunk, sizeof (DS64Chunk))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } got_ds64 = 1; WavpackLittleEndianToNative (&ds64_chunk, DS64ChunkFormat); if (debug_logging_mode) error_line ("DS64: riffSize = %lld, dataSize = %lld, sampleCount = %lld, table_length = %d", (long long) ds64_chunk.riffSize64, (long long) ds64_chunk.dataSize64, (long long) ds64_chunk.sampleCount64, ds64_chunk.tableLength); if (ds64_chunk.tableLength * sizeof (CS64Chunk) != chunk_header.ckSize - sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } while (ds64_chunk.tableLength--) { CS64Chunk cs64_chunk; if (!DoReadFile (infile, &cs64_chunk, sizeof (CS64Chunk), &bcount) || bcount != sizeof (CS64Chunk) || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &cs64_chunk, sizeof (CS64Chunk)))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } } } else if (!strncmp (chunk_header.ckID, "fmt ", 4)) { // if it's the format chunk, we want to get some info out of there and int supported = TRUE, format; // make sure it's a .wav file we can handle if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .WAV format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this WAV file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else if (config->float_norm_exp) error_line ("data format: 32-bit floating point (Audition %d:%d float type 1)", config->float_norm_exp - 126, 150 - config->float_norm_exp); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!strncmp (chunk_header.ckID, "data", 4)) { // on the data chunk, get size and exit loop int64_t data_chunk_size = (got_ds64 && chunk_header.ckSize == (uint32_t) -1) ? ds64_chunk.dataSize64 : chunk_header.ckSize; if (!WaveHeader.NumChannels || (is_rf64 && !got_ds64)) { // make sure we saw "fmt" and "ds64" chunks (if required) error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && infilesize - data_chunk_size > 16777216) { error_line ("this .WAV file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (config->qmode & QMODE_IGNORE_LENGTH) { if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { total_samples = data_chunk_size / WaveHeader.BlockAlign; if (got_ds64 && total_samples != ds64_chunk.sampleCount64) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (!total_samples) { error_line ("this .WAV file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 1) & ~1L; char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } Commit Message: issue #33, sanitize size of unknown chunks before malloc() CWE ID: CWE-787
int ParseRiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int is_rf64 = !strncmp (fourcc, "RF64", 4), got_ds64 = 0; int64_t total_samples = 0, infilesize; RiffChunkHeader riff_chunk_header; ChunkHeader chunk_header; WaveHeader WaveHeader; DS64Chunk ds64_chunk; uint32_t bcount; CLEAR (WaveHeader); CLEAR (ds64_chunk); infilesize = DoGetFileSize (infile); if (!is_rf64 && infilesize >= 4294967296LL && !(config->qmode & QMODE_IGNORE_LENGTH)) { error_line ("can't handle .WAV files larger than 4 GB (non-standard)!"); return WAVPACK_SOFT_ERROR; } memcpy (&riff_chunk_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &riff_chunk_header) + 4, sizeof (RiffChunkHeader) - 4, &bcount) || bcount != sizeof (RiffChunkHeader) - 4 || strncmp (riff_chunk_header.formType, "WAVE", 4))) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &riff_chunk_header, sizeof (RiffChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (ChunkHeader), &bcount) || bcount != sizeof (ChunkHeader)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, ChunkHeaderFormat); if (!strncmp (chunk_header.ckID, "ds64", 4)) { if (chunk_header.ckSize < sizeof (DS64Chunk) || !DoReadFile (infile, &ds64_chunk, sizeof (DS64Chunk), &bcount) || bcount != sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &ds64_chunk, sizeof (DS64Chunk))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } got_ds64 = 1; WavpackLittleEndianToNative (&ds64_chunk, DS64ChunkFormat); if (debug_logging_mode) error_line ("DS64: riffSize = %lld, dataSize = %lld, sampleCount = %lld, table_length = %d", (long long) ds64_chunk.riffSize64, (long long) ds64_chunk.dataSize64, (long long) ds64_chunk.sampleCount64, ds64_chunk.tableLength); if (ds64_chunk.tableLength * sizeof (CS64Chunk) != chunk_header.ckSize - sizeof (DS64Chunk)) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } while (ds64_chunk.tableLength--) { CS64Chunk cs64_chunk; if (!DoReadFile (infile, &cs64_chunk, sizeof (CS64Chunk), &bcount) || bcount != sizeof (CS64Chunk) || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &cs64_chunk, sizeof (CS64Chunk)))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } } } else if (!strncmp (chunk_header.ckID, "fmt ", 4)) { // if it's the format chunk, we want to get some info out of there and int supported = TRUE, format; // make sure it's a .wav file we can handle if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .WAV format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this WAV file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else if (config->float_norm_exp) error_line ("data format: 32-bit floating point (Audition %d:%d float type 1)", config->float_norm_exp - 126, 150 - config->float_norm_exp); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!strncmp (chunk_header.ckID, "data", 4)) { // on the data chunk, get size and exit loop int64_t data_chunk_size = (got_ds64 && chunk_header.ckSize == (uint32_t) -1) ? ds64_chunk.dataSize64 : chunk_header.ckSize; if (!WaveHeader.NumChannels || (is_rf64 && !got_ds64)) { // make sure we saw "fmt" and "ds64" chunks (if required) error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && infilesize - data_chunk_size > 16777216) { error_line ("this .WAV file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (config->qmode & QMODE_IGNORE_LENGTH) { if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { total_samples = data_chunk_size / WaveHeader.BlockAlign; if (got_ds64 && total_samples != ds64_chunk.sampleCount64) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } if (!total_samples) { error_line ("this .WAV file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 1) & ~1L; char *buff; if (bytes_to_copy < 0 || bytes_to_copy > 4194304) { error_line ("%s is not a valid .WAV file!", infilename); return WAVPACK_SOFT_ERROR; } buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; }
169,250
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: expand_string_internal(uschar *string, BOOL ket_ends, uschar **left, BOOL skipping, BOOL honour_dollar, BOOL *resetok_p) { int ptr = 0; int size = Ustrlen(string)+ 64; int item_type; uschar *yield = store_get(size); uschar *s = string; uschar *save_expand_nstring[EXPAND_MAXN+1]; int save_expand_nlength[EXPAND_MAXN+1]; BOOL resetok = TRUE; expand_string_forcedfail = FALSE; expand_string_message = US""; while (*s != 0) { uschar *value; uschar name[256]; /* \ escapes the next character, which must exist, or else the expansion fails. There's a special escape, \N, which causes copying of the subject verbatim up to the next \N. Otherwise, the escapes are the standard set. */ if (*s == '\\') { if (s[1] == 0) { expand_string_message = US"\\ at end of string"; goto EXPAND_FAILED; } if (s[1] == 'N') { uschar *t = s + 2; for (s = t; *s != 0; s++) if (*s == '\\' && s[1] == 'N') break; yield = string_cat(yield, &size, &ptr, t, s - t); if (*s != 0) s += 2; } else { uschar ch[1]; ch[0] = string_interpret_escape(&s); s++; yield = string_cat(yield, &size, &ptr, ch, 1); } continue; } /*{*/ /* Anything other than $ is just copied verbatim, unless we are looking for a terminating } character. */ /*{*/ if (ket_ends && *s == '}') break; if (*s != '$' || !honour_dollar) { yield = string_cat(yield, &size, &ptr, s++, 1); continue; } /* No { after the $ - must be a plain name or a number for string match variable. There has to be a fudge for variables that are the names of header fields preceded by "$header_" because header field names can contain any printing characters except space and colon. For those that don't like typing this much, "$h_" is a synonym for "$header_". A non-existent header yields a NULL value; nothing is inserted. */ /*}*/ if (isalpha((*(++s)))) { int len; int newsize = 0; s = read_name(name, sizeof(name), s, US"_"); /* If this is the first thing to be expanded, release the pre-allocated buffer. */ if (ptr == 0 && yield != NULL) { if (resetok) store_reset(yield); yield = NULL; size = 0; } /* Header */ if (Ustrncmp(name, "h_", 2) == 0 || Ustrncmp(name, "rh_", 3) == 0 || Ustrncmp(name, "bh_", 3) == 0 || Ustrncmp(name, "header_", 7) == 0 || Ustrncmp(name, "rheader_", 8) == 0 || Ustrncmp(name, "bheader_", 8) == 0) { BOOL want_raw = (name[0] == 'r')? TRUE : FALSE; uschar *charset = (name[0] == 'b')? NULL : headers_charset; s = read_header_name(name, sizeof(name), s); value = find_header(name, FALSE, &newsize, want_raw, charset); /* If we didn't find the header, and the header contains a closing brace character, this may be a user error where the terminating colon has been omitted. Set a flag to adjust the error message in this case. But there is no error here - nothing gets inserted. */ if (value == NULL) { if (Ustrchr(name, '}') != NULL) malformed_header = TRUE; continue; } } /* Variable */ else { value = find_variable(name, FALSE, skipping, &newsize); if (value == NULL) { expand_string_message = string_sprintf("unknown variable name \"%s\"", name); check_variable_error_message(name); goto EXPAND_FAILED; } } /* If the data is known to be in a new buffer, newsize will be set to the size of that buffer. If this is the first thing in an expansion string, yield will be NULL; just point it at the new store instead of copying. Many expansion strings contain just one reference, so this is a useful optimization, especially for humungous headers. */ len = Ustrlen(value); if (yield == NULL && newsize != 0) { yield = value; size = newsize; ptr = len; } else yield = string_cat(yield, &size, &ptr, value, len); continue; } if (isdigit(*s)) { int n; s = read_number(&n, s); if (n >= 0 && n <= expand_nmax) yield = string_cat(yield, &size, &ptr, expand_nstring[n], expand_nlength[n]); continue; } /* Otherwise, if there's no '{' after $ it's an error. */ /*}*/ if (*s != '{') /*}*/ { expand_string_message = US"$ not followed by letter, digit, or {"; /*}*/ goto EXPAND_FAILED; } /* After { there can be various things, but they all start with an initial word, except for a number for a string match variable. */ if (isdigit((*(++s)))) { int n; s = read_number(&n, s); /*{*/ if (*s++ != '}') { /*{*/ expand_string_message = US"} expected after number"; goto EXPAND_FAILED; } if (n >= 0 && n <= expand_nmax) yield = string_cat(yield, &size, &ptr, expand_nstring[n], expand_nlength[n]); continue; } if (!isalpha(*s)) { expand_string_message = US"letter or digit expected after ${"; /*}*/ goto EXPAND_FAILED; } /* Allow "-" in names to cater for substrings with negative arguments. Since we are checking for known names after { this is OK. */ s = read_name(name, sizeof(name), s, US"_-"); item_type = chop_match(name, item_table, sizeof(item_table)/sizeof(uschar *)); switch(item_type) { /* Call an ACL from an expansion. We feed data in via $acl_arg1 - $acl_arg9. If the ACL returns accept or reject we return content set by "message =" There is currently no limit on recursion; this would have us call acl_check_internal() directly and get a current level from somewhere. See also the acl expansion condition ECOND_ACL and the traditional acl modifier ACLC_ACL. Assume that the function has side-effects on the store that must be preserved. */ case EITEM_ACL: /* ${acl {name} {arg1}{arg2}...} */ { uschar *sub[10]; /* name + arg1-arg9 (which must match number of acl_arg[]) */ uschar *user_msg; switch(read_subs(sub, 10, 1, &s, skipping, TRUE, US"acl", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } if (skipping) continue; resetok = FALSE; switch(eval_acl(sub, sizeof(sub)/sizeof(*sub), &user_msg)) { case OK: case FAIL: DEBUG(D_expand) debug_printf("acl expansion yield: %s\n", user_msg); if (user_msg) yield = string_cat(yield, &size, &ptr, user_msg, Ustrlen(user_msg)); continue; case DEFER: expand_string_forcedfail = TRUE; default: expand_string_message = string_sprintf("error from acl \"%s\"", sub[0]); goto EXPAND_FAILED; } } /* Handle conditionals - preserve the values of the numerical expansion variables in case they get changed by a regular expression match in the condition. If not, they retain their external settings. At the end of this "if" section, they get restored to their previous values. */ case EITEM_IF: { BOOL cond = FALSE; uschar *next_s; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); while (isspace(*s)) s++; next_s = eval_condition(s, &resetok, skipping? NULL : &cond); if (next_s == NULL) goto EXPAND_FAILED; /* message already set */ DEBUG(D_expand) debug_printf("condition: %.*s\n result: %s\n", (int)(next_s - s), s, cond? "true" : "false"); s = next_s; /* The handling of "yes" and "no" result strings is now in a separate function that is also used by ${lookup} and ${extract} and ${run}. */ switch(process_yesno( skipping, /* were previously skipping */ cond, /* success/failure indicator */ lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"if", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } /* Restore external setting of expansion variables for continuation at this level. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } /* Handle database lookups unless locked out. If "skipping" is TRUE, we are expanding an internal string that isn't actually going to be used. All we need to do is check the syntax, so don't do a lookup at all. Preserve the values of the numerical expansion variables in case they get changed by a partial lookup. If not, they retain their external settings. At the end of this "lookup" section, they get restored to their previous values. */ case EITEM_LOOKUP: { int stype, partial, affixlen, starflags; int expand_setup = 0; int nameptr = 0; uschar *key, *filename, *affix; uschar *save_lookup_value = lookup_value; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); if ((expand_forbid & RDO_LOOKUP) != 0) { expand_string_message = US"lookup expansions are not permitted"; goto EXPAND_FAILED; } /* Get the key we are to look up for single-key+file style lookups. Otherwise set the key NULL pro-tem. */ while (isspace(*s)) s++; if (*s == '{') /*}*/ { key = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (key == NULL) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; while (isspace(*s)) s++; } else key = NULL; /* Find out the type of database */ if (!isalpha(*s)) { expand_string_message = US"missing lookup type"; goto EXPAND_FAILED; } /* The type is a string that may contain special characters of various kinds. Allow everything except space or { to appear; the actual content is checked by search_findtype_partial. */ /*}*/ while (*s != 0 && *s != '{' && !isspace(*s)) /*}*/ { if (nameptr < sizeof(name) - 1) name[nameptr++] = *s; s++; } name[nameptr] = 0; while (isspace(*s)) s++; /* Now check for the individual search type and any partial or default options. Only those types that are actually in the binary are valid. */ stype = search_findtype_partial(name, &partial, &affix, &affixlen, &starflags); if (stype < 0) { expand_string_message = search_error_message; goto EXPAND_FAILED; } /* Check that a key was provided for those lookup types that need it, and was not supplied for those that use the query style. */ if (!mac_islookup(stype, lookup_querystyle|lookup_absfilequery)) { if (key == NULL) { expand_string_message = string_sprintf("missing {key} for single-" "key \"%s\" lookup", name); goto EXPAND_FAILED; } } else { if (key != NULL) { expand_string_message = string_sprintf("a single key was given for " "lookup type \"%s\", which is not a single-key lookup type", name); goto EXPAND_FAILED; } } /* Get the next string in brackets and expand it. It is the file name for single-key+file lookups, and the whole query otherwise. In the case of queries that also require a file name (e.g. sqlite), the file name comes first. */ if (*s != '{') goto EXPAND_FAILED_CURLY; filename = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (filename == NULL) goto EXPAND_FAILED; if (*s++ != '}') goto EXPAND_FAILED_CURLY; while (isspace(*s)) s++; /* If this isn't a single-key+file lookup, re-arrange the variables to be appropriate for the search_ functions. For query-style lookups, there is just a "key", and no file name. For the special query-style + file types, the query (i.e. "key") starts with a file name. */ if (key == NULL) { while (isspace(*filename)) filename++; key = filename; if (mac_islookup(stype, lookup_querystyle)) { filename = NULL; } else { if (*filename != '/') { expand_string_message = string_sprintf( "absolute file name expected for \"%s\" lookup", name); goto EXPAND_FAILED; } while (*key != 0 && !isspace(*key)) key++; if (*key != 0) *key++ = 0; } } /* If skipping, don't do the next bit - just lookup_value == NULL, as if the entry was not found. Note that there is no search_close() function. Files are left open in case of re-use. At suitable places in higher logic, search_tidyup() is called to tidy all open files. This can save opening the same file several times. However, files may also get closed when others are opened, if too many are open at once. The rule is that a handle should not be used after a second search_open(). Request that a partial search sets up $1 and maybe $2 by passing expand_setup containing zero. If its value changes, reset expand_nmax, since new variables will have been set. Note that at the end of this "lookup" section, the old numeric variables are restored. */ if (skipping) lookup_value = NULL; else { void *handle = search_open(filename, stype, 0, NULL, NULL); if (handle == NULL) { expand_string_message = search_error_message; goto EXPAND_FAILED; } lookup_value = search_find(handle, filename, key, partial, affix, affixlen, starflags, &expand_setup); if (search_find_defer) { expand_string_message = string_sprintf("lookup of \"%s\" gave DEFER: %s", string_printing2(key, FALSE), search_error_message); goto EXPAND_FAILED; } if (expand_setup > 0) expand_nmax = expand_setup; } /* The handling of "yes" and "no" result strings is now in a separate function that is also used by ${if} and ${extract}. */ switch(process_yesno( skipping, /* were previously skipping */ lookup_value != NULL, /* success/failure indicator */ save_lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"lookup", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } /* Restore external setting of expansion variables for carrying on at this level, and continue. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } /* If Perl support is configured, handle calling embedded perl subroutines, unless locked out at this time. Syntax is ${perl{sub}} or ${perl{sub}{arg}} or ${perl{sub}{arg1}{arg2}} or up to a maximum of EXIM_PERL_MAX_ARGS arguments (defined below). */ #define EXIM_PERL_MAX_ARGS 8 case EITEM_PERL: #ifndef EXIM_PERL expand_string_message = US"\"${perl\" encountered, but this facility " /*}*/ "is not included in this binary"; goto EXPAND_FAILED; #else /* EXIM_PERL */ { uschar *sub_arg[EXIM_PERL_MAX_ARGS + 2]; uschar *new_yield; if ((expand_forbid & RDO_PERL) != 0) { expand_string_message = US"Perl calls are not permitted"; goto EXPAND_FAILED; } switch(read_subs(sub_arg, EXIM_PERL_MAX_ARGS + 1, 1, &s, skipping, TRUE, US"perl", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* If skipping, we don't actually do anything */ if (skipping) continue; /* Start the interpreter if necessary */ if (!opt_perl_started) { uschar *initerror; if (opt_perl_startup == NULL) { expand_string_message = US"A setting of perl_startup is needed when " "using the Perl interpreter"; goto EXPAND_FAILED; } DEBUG(D_any) debug_printf("Starting Perl interpreter\n"); initerror = init_perl(opt_perl_startup); if (initerror != NULL) { expand_string_message = string_sprintf("error in perl_startup code: %s\n", initerror); goto EXPAND_FAILED; } opt_perl_started = TRUE; } /* Call the function */ sub_arg[EXIM_PERL_MAX_ARGS + 1] = NULL; new_yield = call_perl_cat(yield, &size, &ptr, &expand_string_message, sub_arg[0], sub_arg + 1); /* NULL yield indicates failure; if the message pointer has been set to NULL, the yield was undef, indicating a forced failure. Otherwise the message will indicate some kind of Perl error. */ if (new_yield == NULL) { if (expand_string_message == NULL) { expand_string_message = string_sprintf("Perl subroutine \"%s\" returned undef to force " "failure", sub_arg[0]); expand_string_forcedfail = TRUE; } goto EXPAND_FAILED; } /* Yield succeeded. Ensure forcedfail is unset, just in case it got set during a callback from Perl. */ expand_string_forcedfail = FALSE; yield = new_yield; continue; } #endif /* EXIM_PERL */ /* Transform email address to "prvs" scheme to use as BATV-signed return path */ case EITEM_PRVS: { uschar *sub_arg[3]; uschar *p,*domain; switch(read_subs(sub_arg, 3, 2, &s, skipping, TRUE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* If skipping, we don't actually do anything */ if (skipping) continue; /* sub_arg[0] is the address */ domain = Ustrrchr(sub_arg[0],'@'); if ( (domain == NULL) || (domain == sub_arg[0]) || (Ustrlen(domain) == 1) ) { expand_string_message = US"prvs first argument must be a qualified email address"; goto EXPAND_FAILED; } /* Calculate the hash. The second argument must be a single-digit key number, or unset. */ if (sub_arg[2] != NULL && (!isdigit(sub_arg[2][0]) || sub_arg[2][1] != 0)) { expand_string_message = US"prvs second argument must be a single digit"; goto EXPAND_FAILED; } p = prvs_hmac_sha1(sub_arg[0],sub_arg[1],sub_arg[2],prvs_daystamp(7)); if (p == NULL) { expand_string_message = US"prvs hmac-sha1 conversion failed"; goto EXPAND_FAILED; } /* Now separate the domain from the local part */ *domain++ = '\0'; yield = string_cat(yield,&size,&ptr,US"prvs=",5); string_cat(yield,&size,&ptr,(sub_arg[2] != NULL) ? sub_arg[2] : US"0", 1); string_cat(yield,&size,&ptr,prvs_daystamp(7),3); string_cat(yield,&size,&ptr,p,6); string_cat(yield,&size,&ptr,US"=",1); string_cat(yield,&size,&ptr,sub_arg[0],Ustrlen(sub_arg[0])); string_cat(yield,&size,&ptr,US"@",1); string_cat(yield,&size,&ptr,domain,Ustrlen(domain)); continue; } /* Check a prvs-encoded address for validity */ case EITEM_PRVSCHECK: { uschar *sub_arg[3]; int mysize = 0, myptr = 0; const pcre *re; uschar *p; /* TF: Ugliness: We want to expand parameter 1 first, then set up expansion variables that are used in the expansion of parameter 2. So we clone the string for the first expansion, where we only expand parameter 1. PH: Actually, that isn't necessary. The read_subs() function is designed to work this way for the ${if and ${lookup expansions. I've tidied the code. */ /* Reset expansion variables */ prvscheck_result = NULL; prvscheck_address = NULL; prvscheck_keynum = NULL; switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } re = regex_must_compile(US"^prvs\\=([0-9])([0-9]{3})([A-F0-9]{6})\\=(.+)\\@(.+)$", TRUE,FALSE); if (regex_match_and_setup(re,sub_arg[0],0,-1)) { uschar *local_part = string_copyn(expand_nstring[4],expand_nlength[4]); uschar *key_num = string_copyn(expand_nstring[1],expand_nlength[1]); uschar *daystamp = string_copyn(expand_nstring[2],expand_nlength[2]); uschar *hash = string_copyn(expand_nstring[3],expand_nlength[3]); uschar *domain = string_copyn(expand_nstring[5],expand_nlength[5]); DEBUG(D_expand) debug_printf("prvscheck localpart: %s\n", local_part); DEBUG(D_expand) debug_printf("prvscheck key number: %s\n", key_num); DEBUG(D_expand) debug_printf("prvscheck daystamp: %s\n", daystamp); DEBUG(D_expand) debug_printf("prvscheck hash: %s\n", hash); DEBUG(D_expand) debug_printf("prvscheck domain: %s\n", domain); /* Set up expansion variables */ prvscheck_address = string_cat(NULL, &mysize, &myptr, local_part, Ustrlen(local_part)); string_cat(prvscheck_address,&mysize,&myptr,US"@",1); string_cat(prvscheck_address,&mysize,&myptr,domain,Ustrlen(domain)); prvscheck_address[myptr] = '\0'; prvscheck_keynum = string_copy(key_num); /* Now expand the second argument */ switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* Now we have the key and can check the address. */ p = prvs_hmac_sha1(prvscheck_address, sub_arg[0], prvscheck_keynum, daystamp); if (p == NULL) { expand_string_message = US"hmac-sha1 conversion failed"; goto EXPAND_FAILED; } DEBUG(D_expand) debug_printf("prvscheck: received hash is %s\n", hash); DEBUG(D_expand) debug_printf("prvscheck: own hash is %s\n", p); if (Ustrcmp(p,hash) == 0) { /* Success, valid BATV address. Now check the expiry date. */ uschar *now = prvs_daystamp(0); unsigned int inow = 0,iexpire = 1; (void)sscanf(CS now,"%u",&inow); (void)sscanf(CS daystamp,"%u",&iexpire); /* When "iexpire" is < 7, a "flip" has occured. Adjust "inow" accordingly. */ if ( (iexpire < 7) && (inow >= 993) ) inow = 0; if (iexpire >= inow) { prvscheck_result = US"1"; DEBUG(D_expand) debug_printf("prvscheck: success, $pvrs_result set to 1\n"); } else { prvscheck_result = NULL; DEBUG(D_expand) debug_printf("prvscheck: signature expired, $pvrs_result unset\n"); } } else { prvscheck_result = NULL; DEBUG(D_expand) debug_printf("prvscheck: hash failure, $pvrs_result unset\n"); } /* Now expand the final argument. We leave this till now so that it can include $prvscheck_result. */ switch(read_subs(sub_arg, 1, 0, &s, skipping, TRUE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } if (sub_arg[0] == NULL || *sub_arg[0] == '\0') yield = string_cat(yield,&size,&ptr,prvscheck_address,Ustrlen(prvscheck_address)); else yield = string_cat(yield,&size,&ptr,sub_arg[0],Ustrlen(sub_arg[0])); /* Reset the "internal" variables afterwards, because they are in dynamic store that will be reclaimed if the expansion succeeded. */ prvscheck_address = NULL; prvscheck_keynum = NULL; } else { /* Does not look like a prvs encoded address, return the empty string. We need to make sure all subs are expanded first, so as to skip over the entire item. */ switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } } continue; } /* Handle "readfile" to insert an entire file */ case EITEM_READFILE: { FILE *f; uschar *sub_arg[2]; if ((expand_forbid & RDO_READFILE) != 0) { expand_string_message = US"file insertions are not permitted"; goto EXPAND_FAILED; } switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US"readfile", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* If skipping, we don't actually do anything */ if (skipping) continue; /* Open the file and read it */ f = Ufopen(sub_arg[0], "rb"); if (f == NULL) { expand_string_message = string_open_failed(errno, "%s", sub_arg[0]); goto EXPAND_FAILED; } yield = cat_file(f, yield, &size, &ptr, sub_arg[1]); (void)fclose(f); continue; } /* Handle "readsocket" to insert data from a Unix domain socket */ case EITEM_READSOCK: { int fd; int timeout = 5; int save_ptr = ptr; FILE *f; struct sockaddr_un sockun; /* don't call this "sun" ! */ uschar *arg; uschar *sub_arg[4]; if ((expand_forbid & RDO_READSOCK) != 0) { expand_string_message = US"socket insertions are not permitted"; goto EXPAND_FAILED; } /* Read up to 4 arguments, but don't do the end of item check afterwards, because there may be a string for expansion on failure. */ switch(read_subs(sub_arg, 4, 2, &s, skipping, FALSE, US"readsocket", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: /* Won't occur: no end check */ case 3: goto EXPAND_FAILED; } /* Sort out timeout, if given */ if (sub_arg[2] != NULL) { timeout = readconf_readtime(sub_arg[2], 0, FALSE); if (timeout < 0) { expand_string_message = string_sprintf("bad time value %s", sub_arg[2]); goto EXPAND_FAILED; } } else sub_arg[3] = NULL; /* No eol if no timeout */ /* If skipping, we don't actually do anything. Otherwise, arrange to connect to either an IP or a Unix socket. */ if (!skipping) { /* Handle an IP (internet) domain */ if (Ustrncmp(sub_arg[0], "inet:", 5) == 0) { int port; uschar *server_name = sub_arg[0] + 5; uschar *port_name = Ustrrchr(server_name, ':'); /* Sort out the port */ if (port_name == NULL) { expand_string_message = string_sprintf("missing port for readsocket %s", sub_arg[0]); goto EXPAND_FAILED; } *port_name++ = 0; /* Terminate server name */ if (isdigit(*port_name)) { uschar *end; port = Ustrtol(port_name, &end, 0); if (end != port_name + Ustrlen(port_name)) { expand_string_message = string_sprintf("invalid port number %s", port_name); goto EXPAND_FAILED; } } else { struct servent *service_info = getservbyname(CS port_name, "tcp"); if (service_info == NULL) { expand_string_message = string_sprintf("unknown port \"%s\"", port_name); goto EXPAND_FAILED; } port = ntohs(service_info->s_port); } if ((fd = ip_connectedsocket(SOCK_STREAM, server_name, port, port, timeout, NULL, &expand_string_message)) < 0) goto SOCK_FAIL; } /* Handle a Unix domain socket */ else { int rc; if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) { expand_string_message = string_sprintf("failed to create socket: %s", strerror(errno)); goto SOCK_FAIL; } sockun.sun_family = AF_UNIX; sprintf(sockun.sun_path, "%.*s", (int)(sizeof(sockun.sun_path)-1), sub_arg[0]); sigalrm_seen = FALSE; alarm(timeout); rc = connect(fd, (struct sockaddr *)(&sockun), sizeof(sockun)); alarm(0); if (sigalrm_seen) { expand_string_message = US "socket connect timed out"; goto SOCK_FAIL; } if (rc < 0) { expand_string_message = string_sprintf("failed to connect to socket " "%s: %s", sub_arg[0], strerror(errno)); goto SOCK_FAIL; } } DEBUG(D_expand) debug_printf("connected to socket %s\n", sub_arg[0]); /* Allow sequencing of test actions */ if (running_in_test_harness) millisleep(100); /* Write the request string, if not empty */ if (sub_arg[1][0] != 0) { int len = Ustrlen(sub_arg[1]); DEBUG(D_expand) debug_printf("writing \"%s\" to socket\n", sub_arg[1]); if (write(fd, sub_arg[1], len) != len) { expand_string_message = string_sprintf("request write to socket " "failed: %s", strerror(errno)); goto SOCK_FAIL; } } /* Shut down the sending side of the socket. This helps some servers to recognise that it is their turn to do some work. Just in case some system doesn't have this function, make it conditional. */ #ifdef SHUT_WR shutdown(fd, SHUT_WR); #endif if (running_in_test_harness) millisleep(100); /* Now we need to read from the socket, under a timeout. The function that reads a file can be used. */ f = fdopen(fd, "rb"); sigalrm_seen = FALSE; alarm(timeout); yield = cat_file(f, yield, &size, &ptr, sub_arg[3]); alarm(0); (void)fclose(f); /* After a timeout, we restore the pointer in the result, that is, make sure we add nothing from the socket. */ if (sigalrm_seen) { ptr = save_ptr; expand_string_message = US "socket read timed out"; goto SOCK_FAIL; } } /* The whole thing has worked (or we were skipping). If there is a failure string following, we need to skip it. */ if (*s == '{') { if (expand_string_internal(s+1, TRUE, &s, TRUE, TRUE, &resetok) == NULL) goto EXPAND_FAILED; if (*s++ != '}') goto EXPAND_FAILED_CURLY; while (isspace(*s)) s++; } if (*s++ != '}') goto EXPAND_FAILED_CURLY; continue; /* Come here on failure to create socket, connect socket, write to the socket, or timeout on reading. If another substring follows, expand and use it. Otherwise, those conditions give expand errors. */ SOCK_FAIL: if (*s != '{') goto EXPAND_FAILED; DEBUG(D_any) debug_printf("%s\n", expand_string_message); arg = expand_string_internal(s+1, TRUE, &s, FALSE, TRUE, &resetok); if (arg == NULL) goto EXPAND_FAILED; yield = string_cat(yield, &size, &ptr, arg, Ustrlen(arg)); if (*s++ != '}') goto EXPAND_FAILED_CURLY; while (isspace(*s)) s++; if (*s++ != '}') goto EXPAND_FAILED_CURLY; continue; } /* Handle "run" to execute a program. */ case EITEM_RUN: { FILE *f; uschar *arg; uschar **argv; pid_t pid; int fd_in, fd_out; int lsize = 0; int lptr = 0; if ((expand_forbid & RDO_RUN) != 0) { expand_string_message = US"running a command is not permitted"; goto EXPAND_FAILED; } while (isspace(*s)) s++; if (*s != '{') goto EXPAND_FAILED_CURLY; arg = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (arg == NULL) goto EXPAND_FAILED; while (isspace(*s)) s++; if (*s++ != '}') goto EXPAND_FAILED_CURLY; if (skipping) /* Just pretend it worked when we're skipping */ { runrc = 0; } else { if (!transport_set_up_command(&argv, /* anchor for arg list */ arg, /* raw command */ FALSE, /* don't expand the arguments */ 0, /* not relevant when... */ NULL, /* no transporting address */ US"${run} expansion", /* for error messages */ &expand_string_message)) /* where to put error message */ { goto EXPAND_FAILED; } /* Create the child process, making it a group leader. */ pid = child_open(argv, NULL, 0077, &fd_in, &fd_out, TRUE); if (pid < 0) { expand_string_message = string_sprintf("couldn't create child process: %s", strerror(errno)); goto EXPAND_FAILED; } /* Nothing is written to the standard input. */ (void)close(fd_in); /* Read the pipe to get the command's output into $value (which is kept in lookup_value). Read during execution, so that if the output exceeds the OS pipe buffer limit, we don't block forever. */ f = fdopen(fd_out, "rb"); sigalrm_seen = FALSE; alarm(60); lookup_value = cat_file(f, lookup_value, &lsize, &lptr, NULL); alarm(0); (void)fclose(f); /* Wait for the process to finish, applying the timeout, and inspect its return code for serious disasters. Simple non-zero returns are passed on. */ if (sigalrm_seen == TRUE || (runrc = child_close(pid, 30)) < 0) { if (sigalrm_seen == TRUE || runrc == -256) { expand_string_message = string_sprintf("command timed out"); killpg(pid, SIGKILL); /* Kill the whole process group */ } else if (runrc == -257) expand_string_message = string_sprintf("wait() failed: %s", strerror(errno)); else expand_string_message = string_sprintf("command killed by signal %d", -runrc); goto EXPAND_FAILED; } } /* Process the yes/no strings; $value may be useful in both cases */ switch(process_yesno( skipping, /* were previously skipping */ runrc == 0, /* success/failure indicator */ lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"run", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } continue; } /* Handle character translation for "tr" */ case EITEM_TR: { int oldptr = ptr; int o2m; uschar *sub[3]; switch(read_subs(sub, 3, 3, &s, skipping, TRUE, US"tr", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } yield = string_cat(yield, &size, &ptr, sub[0], Ustrlen(sub[0])); o2m = Ustrlen(sub[2]) - 1; if (o2m >= 0) for (; oldptr < ptr; oldptr++) { uschar *m = Ustrrchr(sub[1], yield[oldptr]); if (m != NULL) { int o = m - sub[1]; yield[oldptr] = sub[2][(o < o2m)? o : o2m]; } } continue; } /* Handle "hash", "length", "nhash", and "substr" when they are given with expanded arguments. */ case EITEM_HASH: case EITEM_LENGTH: case EITEM_NHASH: case EITEM_SUBSTR: { int i; int len; uschar *ret; int val[2] = { 0, -1 }; uschar *sub[3]; /* "length" takes only 2 arguments whereas the others take 2 or 3. Ensure that sub[2] is set in the ${length } case. */ sub[2] = NULL; switch(read_subs(sub, (item_type == EITEM_LENGTH)? 2:3, 2, &s, skipping, TRUE, name, &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* Juggle the arguments if there are only two of them: always move the string to the last position and make ${length{n}{str}} equivalent to ${substr{0}{n}{str}}. See the defaults for val[] above. */ if (sub[2] == NULL) { sub[2] = sub[1]; sub[1] = NULL; if (item_type == EITEM_LENGTH) { sub[1] = sub[0]; sub[0] = NULL; } } for (i = 0; i < 2; i++) { if (sub[i] == NULL) continue; val[i] = (int)Ustrtol(sub[i], &ret, 10); if (*ret != 0 || (i != 0 && val[i] < 0)) { expand_string_message = string_sprintf("\"%s\" is not a%s number " "(in \"%s\" expansion)", sub[i], (i != 0)? " positive" : "", name); goto EXPAND_FAILED; } } ret = (item_type == EITEM_HASH)? compute_hash(sub[2], val[0], val[1], &len) : (item_type == EITEM_NHASH)? compute_nhash(sub[2], val[0], val[1], &len) : extract_substr(sub[2], val[0], val[1], &len); if (ret == NULL) goto EXPAND_FAILED; yield = string_cat(yield, &size, &ptr, ret, len); continue; } /* Handle HMAC computation: ${hmac{<algorithm>}{<secret>}{<text>}} This code originally contributed by Steve Haslam. It currently supports the use of MD5 and SHA-1 hashes. We need some workspace that is large enough to handle all the supported hash types. Use macros to set the sizes rather than be too elaborate. */ #define MAX_HASHLEN 20 #define MAX_HASHBLOCKLEN 64 case EITEM_HMAC: { uschar *sub[3]; md5 md5_base; sha1 sha1_base; void *use_base; int type, i; int hashlen; /* Number of octets for the hash algorithm's output */ int hashblocklen; /* Number of octets the hash algorithm processes */ uschar *keyptr, *p; unsigned int keylen; uschar keyhash[MAX_HASHLEN]; uschar innerhash[MAX_HASHLEN]; uschar finalhash[MAX_HASHLEN]; uschar finalhash_hex[2*MAX_HASHLEN]; uschar innerkey[MAX_HASHBLOCKLEN]; uschar outerkey[MAX_HASHBLOCKLEN]; switch (read_subs(sub, 3, 3, &s, skipping, TRUE, name, &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } if (Ustrcmp(sub[0], "md5") == 0) { type = HMAC_MD5; use_base = &md5_base; hashlen = 16; hashblocklen = 64; } else if (Ustrcmp(sub[0], "sha1") == 0) { type = HMAC_SHA1; use_base = &sha1_base; hashlen = 20; hashblocklen = 64; } else { expand_string_message = string_sprintf("hmac algorithm \"%s\" is not recognised", sub[0]); goto EXPAND_FAILED; } keyptr = sub[1]; keylen = Ustrlen(keyptr); /* If the key is longer than the hash block length, then hash the key first */ if (keylen > hashblocklen) { chash_start(type, use_base); chash_end(type, use_base, keyptr, keylen, keyhash); keyptr = keyhash; keylen = hashlen; } /* Now make the inner and outer key values */ memset(innerkey, 0x36, hashblocklen); memset(outerkey, 0x5c, hashblocklen); for (i = 0; i < keylen; i++) { innerkey[i] ^= keyptr[i]; outerkey[i] ^= keyptr[i]; } /* Now do the hashes */ chash_start(type, use_base); chash_mid(type, use_base, innerkey); chash_end(type, use_base, sub[2], Ustrlen(sub[2]), innerhash); chash_start(type, use_base); chash_mid(type, use_base, outerkey); chash_end(type, use_base, innerhash, hashlen, finalhash); /* Encode the final hash as a hex string */ p = finalhash_hex; for (i = 0; i < hashlen; i++) { *p++ = hex_digits[(finalhash[i] & 0xf0) >> 4]; *p++ = hex_digits[finalhash[i] & 0x0f]; } DEBUG(D_any) debug_printf("HMAC[%s](%.*s,%.*s)=%.*s\n", sub[0], (int)keylen, keyptr, Ustrlen(sub[2]), sub[2], hashlen*2, finalhash_hex); yield = string_cat(yield, &size, &ptr, finalhash_hex, hashlen*2); } continue; /* Handle global substitution for "sg" - like Perl's s/xxx/yyy/g operator. We have to save the numerical variables and restore them afterwards. */ case EITEM_SG: { const pcre *re; int moffset, moffsetextra, slen; int roffset; int emptyopt; const uschar *rerror; uschar *subject; uschar *sub[3]; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); switch(read_subs(sub, 3, 3, &s, skipping, TRUE, US"sg", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* Compile the regular expression */ re = pcre_compile(CS sub[1], PCRE_COPT, (const char **)&rerror, &roffset, NULL); if (re == NULL) { expand_string_message = string_sprintf("regular expression error in " "\"%s\": %s at offset %d", sub[1], rerror, roffset); goto EXPAND_FAILED; } /* Now run a loop to do the substitutions as often as necessary. It ends when there are no more matches. Take care over matches of the null string; do the same thing as Perl does. */ subject = sub[0]; slen = Ustrlen(sub[0]); moffset = moffsetextra = 0; emptyopt = 0; for (;;) { int ovector[3*(EXPAND_MAXN+1)]; int n = pcre_exec(re, NULL, CS subject, slen, moffset + moffsetextra, PCRE_EOPT | emptyopt, ovector, sizeof(ovector)/sizeof(int)); int nn; uschar *insert; /* No match - if we previously set PCRE_NOTEMPTY after a null match, this is not necessarily the end. We want to repeat the match from one character further along, but leaving the basic offset the same (for copying below). We can't be at the end of the string - that was checked before setting PCRE_NOTEMPTY. If PCRE_NOTEMPTY is not set, we are finished; copy the remaining string and end the loop. */ if (n < 0) { if (emptyopt != 0) { moffsetextra = 1; emptyopt = 0; continue; } yield = string_cat(yield, &size, &ptr, subject+moffset, slen-moffset); break; } /* Match - set up for expanding the replacement. */ if (n == 0) n = EXPAND_MAXN + 1; expand_nmax = 0; for (nn = 0; nn < n*2; nn += 2) { expand_nstring[expand_nmax] = subject + ovector[nn]; expand_nlength[expand_nmax++] = ovector[nn+1] - ovector[nn]; } expand_nmax--; /* Copy the characters before the match, plus the expanded insertion. */ yield = string_cat(yield, &size, &ptr, subject + moffset, ovector[0] - moffset); insert = expand_string(sub[2]); if (insert == NULL) goto EXPAND_FAILED; yield = string_cat(yield, &size, &ptr, insert, Ustrlen(insert)); moffset = ovector[1]; moffsetextra = 0; emptyopt = 0; /* If we have matched an empty string, first check to see if we are at the end of the subject. If so, the loop is over. Otherwise, mimic what Perl's /g options does. This turns out to be rather cunning. First we set PCRE_NOTEMPTY and PCRE_ANCHORED and try the match a non-empty string at the same point. If this fails (picked up above) we advance to the next character. */ if (ovector[0] == ovector[1]) { if (ovector[0] == slen) break; emptyopt = PCRE_NOTEMPTY | PCRE_ANCHORED; } } /* All done - restore numerical variables. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } /* Handle keyed and numbered substring extraction. If the first argument consists entirely of digits, then a numerical extraction is assumed. */ case EITEM_EXTRACT: { int i; int j = 2; int field_number = 1; BOOL field_number_set = FALSE; uschar *save_lookup_value = lookup_value; uschar *sub[3]; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); /* Read the arguments */ for (i = 0; i < j; i++) { while (isspace(*s)) s++; if (*s == '{') /*}*/ { sub[i] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (sub[i] == NULL) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; /* After removal of leading and trailing white space, the first argument must not be empty; if it consists entirely of digits (optionally preceded by a minus sign), this is a numerical extraction, and we expect 3 arguments. */ if (i == 0) { int len; int x = 0; uschar *p = sub[0]; while (isspace(*p)) p++; sub[0] = p; len = Ustrlen(p); while (len > 0 && isspace(p[len-1])) len--; p[len] = 0; if (*p == 0 && !skipping) { expand_string_message = US"first argument of \"extract\" must " "not be empty"; goto EXPAND_FAILED; } if (*p == '-') { field_number = -1; p++; } while (*p != 0 && isdigit(*p)) x = x * 10 + *p++ - '0'; if (*p == 0) { field_number *= x; j = 3; /* Need 3 args */ field_number_set = TRUE; } } } else goto EXPAND_FAILED_CURLY; } /* Extract either the numbered or the keyed substring into $value. If skipping, just pretend the extraction failed. */ lookup_value = skipping? NULL : field_number_set? expand_gettokened(field_number, sub[1], sub[2]) : expand_getkeyed(sub[0], sub[1]); /* If no string follows, $value gets substituted; otherwise there can be yes/no strings, as for lookup or if. */ switch(process_yesno( skipping, /* were previously skipping */ lookup_value != NULL, /* success/failure indicator */ save_lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"extract", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } /* All done - restore numerical variables. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } /* return the Nth item from a list */ case EITEM_LISTEXTRACT: { int i; int field_number = 1; uschar *save_lookup_value = lookup_value; uschar *sub[2]; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); /* Read the field & list arguments */ for (i = 0; i < 2; i++) { while (isspace(*s)) s++; if (*s != '{') /*}*/ goto EXPAND_FAILED_CURLY; sub[i] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (!sub[i]) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; /* After removal of leading and trailing white space, the first argument must be numeric and nonempty. */ if (i == 0) { int len; int x = 0; uschar *p = sub[0]; while (isspace(*p)) p++; sub[0] = p; len = Ustrlen(p); while (len > 0 && isspace(p[len-1])) len--; p[len] = 0; if (!*p && !skipping) { expand_string_message = US"first argument of \"listextract\" must " "not be empty"; goto EXPAND_FAILED; } if (*p == '-') { field_number = -1; p++; } while (*p && isdigit(*p)) x = x * 10 + *p++ - '0'; if (*p) { expand_string_message = US"first argument of \"listextract\" must " "be numeric"; goto EXPAND_FAILED; } field_number *= x; } } /* Extract the numbered element into $value. If skipping, just pretend the extraction failed. */ lookup_value = skipping? NULL : expand_getlistele(field_number, sub[1]); /* If no string follows, $value gets substituted; otherwise there can be yes/no strings, as for lookup or if. */ switch(process_yesno( skipping, /* were previously skipping */ lookup_value != NULL, /* success/failure indicator */ save_lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"extract", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } /* All done - restore numerical variables. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } #ifdef SUPPORT_TLS case EITEM_CERTEXTRACT: { uschar *save_lookup_value = lookup_value; uschar *sub[2]; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); /* Read the field argument */ while (isspace(*s)) s++; if (*s != '{') /*}*/ goto EXPAND_FAILED_CURLY; sub[0] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (!sub[0]) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; /* strip spaces fore & aft */ { int len; uschar *p = sub[0]; while (isspace(*p)) p++; sub[0] = p; len = Ustrlen(p); while (len > 0 && isspace(p[len-1])) len--; p[len] = 0; } /* inspect the cert argument */ while (isspace(*s)) s++; if (*s != '{') /*}*/ goto EXPAND_FAILED_CURLY; if (*++s != '$') { expand_string_message = US"second argument of \"certextract\" must " "be a certificate variable"; goto EXPAND_FAILED; } sub[1] = expand_string_internal(s+1, TRUE, &s, skipping, FALSE, &resetok); if (!sub[1]) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; if (skipping) lookup_value = NULL; else { lookup_value = expand_getcertele(sub[0], sub[1]); if (*expand_string_message) goto EXPAND_FAILED; } switch(process_yesno( skipping, /* were previously skipping */ lookup_value != NULL, /* success/failure indicator */ save_lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"extract", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } #endif /*SUPPORT_TLS*/ /* Handle list operations */ case EITEM_FILTER: case EITEM_MAP: case EITEM_REDUCE: { int sep = 0; int save_ptr = ptr; uschar outsep[2] = { '\0', '\0' }; uschar *list, *expr, *temp; uschar *save_iterate_item = iterate_item; uschar *save_lookup_value = lookup_value; while (isspace(*s)) s++; if (*s++ != '{') goto EXPAND_FAILED_CURLY; list = expand_string_internal(s, TRUE, &s, skipping, TRUE, &resetok); if (list == NULL) goto EXPAND_FAILED; if (*s++ != '}') goto EXPAND_FAILED_CURLY; if (item_type == EITEM_REDUCE) { while (isspace(*s)) s++; if (*s++ != '{') goto EXPAND_FAILED_CURLY; temp = expand_string_internal(s, TRUE, &s, skipping, TRUE, &resetok); if (temp == NULL) goto EXPAND_FAILED; lookup_value = temp; if (*s++ != '}') goto EXPAND_FAILED_CURLY; } while (isspace(*s)) s++; if (*s++ != '{') goto EXPAND_FAILED_CURLY; expr = s; /* For EITEM_FILTER, call eval_condition once, with result discarded (as if scanning a "false" part). This allows us to find the end of the condition, because if the list is empty, we won't actually evaluate the condition for real. For EITEM_MAP and EITEM_REDUCE, do the same, using the normal internal expansion function. */ if (item_type == EITEM_FILTER) { temp = eval_condition(expr, &resetok, NULL); if (temp != NULL) s = temp; } else { temp = expand_string_internal(s, TRUE, &s, TRUE, TRUE, &resetok); } if (temp == NULL) { expand_string_message = string_sprintf("%s inside \"%s\" item", expand_string_message, name); goto EXPAND_FAILED; } while (isspace(*s)) s++; if (*s++ != '}') { /*{*/ expand_string_message = string_sprintf("missing } at end of condition " "or expression inside \"%s\"", name); goto EXPAND_FAILED; } while (isspace(*s)) s++; /*{*/ if (*s++ != '}') { /*{*/ expand_string_message = string_sprintf("missing } at end of \"%s\"", name); goto EXPAND_FAILED; } /* If we are skipping, we can now just move on to the next item. When processing for real, we perform the iteration. */ if (skipping) continue; while ((iterate_item = string_nextinlist(&list, &sep, NULL, 0)) != NULL) { *outsep = (uschar)sep; /* Separator as a string */ DEBUG(D_expand) debug_printf("%s: $item = \"%s\"\n", name, iterate_item); if (item_type == EITEM_FILTER) { BOOL condresult; if (eval_condition(expr, &resetok, &condresult) == NULL) { iterate_item = save_iterate_item; lookup_value = save_lookup_value; expand_string_message = string_sprintf("%s inside \"%s\" condition", expand_string_message, name); goto EXPAND_FAILED; } DEBUG(D_expand) debug_printf("%s: condition is %s\n", name, condresult? "true":"false"); if (condresult) temp = iterate_item; /* TRUE => include this item */ else continue; /* FALSE => skip this item */ } /* EITEM_MAP and EITEM_REDUCE */ else { temp = expand_string_internal(expr, TRUE, NULL, skipping, TRUE, &resetok); if (temp == NULL) { iterate_item = save_iterate_item; expand_string_message = string_sprintf("%s inside \"%s\" item", expand_string_message, name); goto EXPAND_FAILED; } if (item_type == EITEM_REDUCE) { lookup_value = temp; /* Update the value of $value */ continue; /* and continue the iteration */ } } /* We reach here for FILTER if the condition is true, always for MAP, and never for REDUCE. The value in "temp" is to be added to the output list that is being created, ensuring that any occurrences of the separator character are doubled. Unless we are dealing with the first item of the output list, add in a space if the new item begins with the separator character, or is an empty string. */ if (ptr != save_ptr && (temp[0] == *outsep || temp[0] == 0)) yield = string_cat(yield, &size, &ptr, US" ", 1); /* Add the string in "temp" to the output list that we are building, This is done in chunks by searching for the separator character. */ for (;;) { size_t seglen = Ustrcspn(temp, outsep); yield = string_cat(yield, &size, &ptr, temp, seglen + 1); /* If we got to the end of the string we output one character too many; backup and end the loop. Otherwise arrange to double the separator. */ if (temp[seglen] == '\0') { ptr--; break; } yield = string_cat(yield, &size, &ptr, outsep, 1); temp += seglen + 1; } /* Output a separator after the string: we will remove the redundant final one at the end. */ yield = string_cat(yield, &size, &ptr, outsep, 1); } /* End of iteration over the list loop */ /* REDUCE has generated no output above: output the final value of $value. */ if (item_type == EITEM_REDUCE) { yield = string_cat(yield, &size, &ptr, lookup_value, Ustrlen(lookup_value)); lookup_value = save_lookup_value; /* Restore $value */ } /* FILTER and MAP generate lists: if they have generated anything, remove the redundant final separator. Even though an empty item at the end of a list does not count, this is tidier. */ else if (ptr != save_ptr) ptr--; /* Restore preserved $item */ iterate_item = save_iterate_item; continue; } /* If ${dlfunc } support is configured, handle calling dynamically-loaded functions, unless locked out at this time. Syntax is ${dlfunc{file}{func}} or ${dlfunc{file}{func}{arg}} or ${dlfunc{file}{func}{arg1}{arg2}} or up to a maximum of EXPAND_DLFUNC_MAX_ARGS arguments (defined below). */ #define EXPAND_DLFUNC_MAX_ARGS 8 case EITEM_DLFUNC: #ifndef EXPAND_DLFUNC expand_string_message = US"\"${dlfunc\" encountered, but this facility " /*}*/ "is not included in this binary"; goto EXPAND_FAILED; #else /* EXPAND_DLFUNC */ { tree_node *t; exim_dlfunc_t *func; uschar *result; int status, argc; uschar *argv[EXPAND_DLFUNC_MAX_ARGS + 3]; if ((expand_forbid & RDO_DLFUNC) != 0) { expand_string_message = US"dynamically-loaded functions are not permitted"; goto EXPAND_FAILED; } switch(read_subs(argv, EXPAND_DLFUNC_MAX_ARGS + 2, 2, &s, skipping, TRUE, US"dlfunc", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* If skipping, we don't actually do anything */ if (skipping) continue; /* Look up the dynamically loaded object handle in the tree. If it isn't found, dlopen() the file and put the handle in the tree for next time. */ t = tree_search(dlobj_anchor, argv[0]); if (t == NULL) { void *handle = dlopen(CS argv[0], RTLD_LAZY); if (handle == NULL) { expand_string_message = string_sprintf("dlopen \"%s\" failed: %s", argv[0], dlerror()); log_write(0, LOG_MAIN|LOG_PANIC, "%s", expand_string_message); goto EXPAND_FAILED; } t = store_get_perm(sizeof(tree_node) + Ustrlen(argv[0])); Ustrcpy(t->name, argv[0]); t->data.ptr = handle; (void)tree_insertnode(&dlobj_anchor, t); } /* Having obtained the dynamically loaded object handle, look up the function pointer. */ func = (exim_dlfunc_t *)dlsym(t->data.ptr, CS argv[1]); if (func == NULL) { expand_string_message = string_sprintf("dlsym \"%s\" in \"%s\" failed: " "%s", argv[1], argv[0], dlerror()); log_write(0, LOG_MAIN|LOG_PANIC, "%s", expand_string_message); goto EXPAND_FAILED; } /* Call the function and work out what to do with the result. If it returns OK, we have a replacement string; if it returns DEFER then expansion has failed in a non-forced manner; if it returns FAIL then failure was forced; if it returns ERROR or any other value there's a problem, so panic slightly. In any case, assume that the function has side-effects on the store that must be preserved. */ resetok = FALSE; result = NULL; for (argc = 0; argv[argc] != NULL; argc++); status = func(&result, argc - 2, &argv[2]); if(status == OK) { if (result == NULL) result = US""; yield = string_cat(yield, &size, &ptr, result, Ustrlen(result)); continue; } else { expand_string_message = result == NULL ? US"(no message)" : result; if(status == FAIL_FORCED) expand_string_forcedfail = TRUE; else if(status != FAIL) log_write(0, LOG_MAIN|LOG_PANIC, "dlfunc{%s}{%s} failed (%d): %s", argv[0], argv[1], status, expand_string_message); goto EXPAND_FAILED; } } #endif /* EXPAND_DLFUNC */ } /* EITEM_* switch */ /* Control reaches here if the name is not recognized as one of the more complicated expansion items. Check for the "operator" syntax (name terminated by a colon). Some of the operators have arguments, separated by _ from the name. */ if (*s == ':') { int c; uschar *arg = NULL; uschar *sub; var_entry *vp = NULL; /* Owing to an historical mis-design, an underscore may be part of the operator name, or it may introduce arguments. We therefore first scan the table of names that contain underscores. If there is no match, we cut off the arguments and then scan the main table. */ if ((c = chop_match(name, op_table_underscore, sizeof(op_table_underscore)/sizeof(uschar *))) < 0) { arg = Ustrchr(name, '_'); if (arg != NULL) *arg = 0; c = chop_match(name, op_table_main, sizeof(op_table_main)/sizeof(uschar *)); if (c >= 0) c += sizeof(op_table_underscore)/sizeof(uschar *); if (arg != NULL) *arg++ = '_'; /* Put back for error messages */ } /* Deal specially with operators that might take a certificate variable as we do not want to do the usual expansion. For most, expand the string.*/ switch(c) { #ifdef SUPPORT_TLS case EOP_MD5: case EOP_SHA1: case EOP_SHA256: if (s[1] == '$') { uschar * s1 = s; sub = expand_string_internal(s+2, TRUE, &s1, skipping, FALSE, &resetok); if (!sub) goto EXPAND_FAILED; /*{*/ if (*s1 != '}') goto EXPAND_FAILED_CURLY; if ((vp = find_var_ent(sub)) && vp->type == vtype_cert) { s = s1+1; break; } vp = NULL; } /*FALLTHROUGH*/ #endif default: sub = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (!sub) goto EXPAND_FAILED; s++; break; } /* If we are skipping, we don't need to perform the operation at all. This matters for operations like "mask", because the data may not be in the correct format when skipping. For example, the expression may test for the existence of $sender_host_address before trying to mask it. For other operations, doing them may not fail, but it is a waste of time. */ if (skipping && c >= 0) continue; /* Otherwise, switch on the operator type */ switch(c) { case EOP_BASE62: { uschar *t; unsigned long int n = Ustrtoul(sub, &t, 10); if (*t != 0) { expand_string_message = string_sprintf("argument for base62 " "operator is \"%s\", which is not a decimal number", sub); goto EXPAND_FAILED; } t = string_base62(n); yield = string_cat(yield, &size, &ptr, t, Ustrlen(t)); continue; } /* Note that for Darwin and Cygwin, BASE_62 actually has the value 36 */ case EOP_BASE62D: { uschar buf[16]; uschar *tt = sub; unsigned long int n = 0; while (*tt != 0) { uschar *t = Ustrchr(base62_chars, *tt++); if (t == NULL) { expand_string_message = string_sprintf("argument for base62d " "operator is \"%s\", which is not a base %d number", sub, BASE_62); goto EXPAND_FAILED; } n = n * BASE_62 + (t - base62_chars); } (void)sprintf(CS buf, "%ld", n); yield = string_cat(yield, &size, &ptr, buf, Ustrlen(buf)); continue; } case EOP_EXPAND: { uschar *expanded = expand_string_internal(sub, FALSE, NULL, skipping, TRUE, &resetok); if (expanded == NULL) { expand_string_message = string_sprintf("internal expansion of \"%s\" failed: %s", sub, expand_string_message); goto EXPAND_FAILED; } yield = string_cat(yield, &size, &ptr, expanded, Ustrlen(expanded)); continue; } case EOP_LC: { int count = 0; uschar *t = sub - 1; while (*(++t) != 0) { *t = tolower(*t); count++; } yield = string_cat(yield, &size, &ptr, sub, count); continue; } case EOP_UC: { int count = 0; uschar *t = sub - 1; while (*(++t) != 0) { *t = toupper(*t); count++; } yield = string_cat(yield, &size, &ptr, sub, count); continue; } case EOP_MD5: #ifdef SUPPORT_TLS if (vp && *(void **)vp->value) { uschar * cp = tls_cert_fprt_md5(*(void **)vp->value); yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp)); } else #endif { md5 base; uschar digest[16]; int j; char st[33]; md5_start(&base); md5_end(&base, sub, Ustrlen(sub), digest); for(j = 0; j < 16; j++) sprintf(st+2*j, "%02x", digest[j]); yield = string_cat(yield, &size, &ptr, US st, (int)strlen(st)); } continue; case EOP_SHA1: #ifdef SUPPORT_TLS if (vp && *(void **)vp->value) { uschar * cp = tls_cert_fprt_sha1(*(void **)vp->value); yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp)); } else #endif { sha1 base; uschar digest[20]; int j; char st[41]; sha1_start(&base); sha1_end(&base, sub, Ustrlen(sub), digest); for(j = 0; j < 20; j++) sprintf(st+2*j, "%02X", digest[j]); yield = string_cat(yield, &size, &ptr, US st, (int)strlen(st)); } continue; case EOP_SHA256: #ifdef SUPPORT_TLS if (vp && *(void **)vp->value) { uschar * cp = tls_cert_fprt_sha256(*(void **)vp->value); yield = string_cat(yield, &size, &ptr, cp, (int)Ustrlen(cp)); } else #endif expand_string_message = US"sha256 only supported for certificates"; continue; /* Convert hex encoding to base64 encoding */ case EOP_HEX2B64: { int c = 0; int b = -1; uschar *in = sub; uschar *out = sub; uschar *enc; for (enc = sub; *enc != 0; enc++) { if (!isxdigit(*enc)) { expand_string_message = string_sprintf("\"%s\" is not a hex " "string", sub); goto EXPAND_FAILED; } c++; } if ((c & 1) != 0) { expand_string_message = string_sprintf("\"%s\" contains an odd " "number of characters", sub); goto EXPAND_FAILED; } while ((c = *in++) != 0) { if (isdigit(c)) c -= '0'; else c = toupper(c) - 'A' + 10; if (b == -1) { b = c << 4; } else { *out++ = b | c; b = -1; } } enc = auth_b64encode(sub, out - sub); yield = string_cat(yield, &size, &ptr, enc, Ustrlen(enc)); continue; } /* Convert octets outside 0x21..0x7E to \xXX form */ case EOP_HEXQUOTE: { uschar *t = sub - 1; while (*(++t) != 0) { if (*t < 0x21 || 0x7E < *t) yield = string_cat(yield, &size, &ptr, string_sprintf("\\x%02x", *t), 4); else yield = string_cat(yield, &size, &ptr, t, 1); } continue; } /* count the number of list elements */ case EOP_LISTCOUNT: { int cnt = 0; int sep = 0; uschar * cp; uschar buffer[256]; while (string_nextinlist(&sub, &sep, buffer, sizeof(buffer)) != NULL) cnt++; cp = string_sprintf("%d", cnt); yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp)); continue; } /* expand a named list given the name */ /* handles nested named lists; requotes as colon-sep list */ case EOP_LISTNAMED: { tree_node *t = NULL; uschar * list; int sep = 0; uschar * item; uschar * suffix = US""; BOOL needsep = FALSE; uschar buffer[256]; if (*sub == '+') sub++; if (arg == NULL) /* no-argument version */ { if (!(t = tree_search(addresslist_anchor, sub)) && !(t = tree_search(domainlist_anchor, sub)) && !(t = tree_search(hostlist_anchor, sub))) t = tree_search(localpartlist_anchor, sub); } else switch(*arg) /* specific list-type version */ { case 'a': t = tree_search(addresslist_anchor, sub); suffix = US"_a"; break; case 'd': t = tree_search(domainlist_anchor, sub); suffix = US"_d"; break; case 'h': t = tree_search(hostlist_anchor, sub); suffix = US"_h"; break; case 'l': t = tree_search(localpartlist_anchor, sub); suffix = US"_l"; break; default: expand_string_message = string_sprintf("bad suffix on \"list\" operator"); goto EXPAND_FAILED; } if(!t) { expand_string_message = string_sprintf("\"%s\" is not a %snamed list", sub, !arg?"" : *arg=='a'?"address " : *arg=='d'?"domain " : *arg=='h'?"host " : *arg=='l'?"localpart " : 0); goto EXPAND_FAILED; } list = ((namedlist_block *)(t->data.ptr))->string; while ((item = string_nextinlist(&list, &sep, buffer, sizeof(buffer))) != NULL) { uschar * buf = US" : "; if (needsep) yield = string_cat(yield, &size, &ptr, buf, 3); else needsep = TRUE; if (*item == '+') /* list item is itself a named list */ { uschar * sub = string_sprintf("${listnamed%s:%s}", suffix, item); item = expand_string_internal(sub, FALSE, NULL, FALSE, TRUE, &resetok); } else if (sep != ':') /* item from non-colon-sep list, re-quote for colon list-separator */ { char * cp; char tok[3]; tok[0] = sep; tok[1] = ':'; tok[2] = 0; while ((cp= strpbrk((const char *)item, tok))) { yield = string_cat(yield, &size, &ptr, item, cp-(char *)item); if (*cp++ == ':') /* colon in a non-colon-sep list item, needs doubling */ { yield = string_cat(yield, &size, &ptr, US"::", 2); item = (uschar *)cp; } else /* sep in item; should already be doubled; emit once */ { yield = string_cat(yield, &size, &ptr, (uschar *)tok, 1); if (*cp == sep) cp++; item = (uschar *)cp; } } } yield = string_cat(yield, &size, &ptr, item, Ustrlen(item)); } continue; } /* mask applies a mask to an IP address; for example the result of ${mask:131.111.10.206/28} is 131.111.10.192/28. */ case EOP_MASK: { int count; uschar *endptr; int binary[4]; int mask, maskoffset; int type = string_is_ip_address(sub, &maskoffset); uschar buffer[64]; if (type == 0) { expand_string_message = string_sprintf("\"%s\" is not an IP address", sub); goto EXPAND_FAILED; } if (maskoffset == 0) { expand_string_message = string_sprintf("missing mask value in \"%s\"", sub); goto EXPAND_FAILED; } mask = Ustrtol(sub + maskoffset + 1, &endptr, 10); if (*endptr != 0 || mask < 0 || mask > ((type == 4)? 32 : 128)) { expand_string_message = string_sprintf("mask value too big in \"%s\"", sub); goto EXPAND_FAILED; } /* Convert the address to binary integer(s) and apply the mask */ sub[maskoffset] = 0; count = host_aton(sub, binary); host_mask(count, binary, mask); /* Convert to masked textual format and add to output. */ yield = string_cat(yield, &size, &ptr, buffer, host_nmtoa(count, binary, mask, buffer, '.')); continue; } case EOP_ADDRESS: case EOP_LOCAL_PART: case EOP_DOMAIN: { uschar *error; int start, end, domain; uschar *t = parse_extract_address(sub, &error, &start, &end, &domain, FALSE); if (t != NULL) { if (c != EOP_DOMAIN) { if (c == EOP_LOCAL_PART && domain != 0) end = start + domain - 1; yield = string_cat(yield, &size, &ptr, sub+start, end-start); } else if (domain != 0) { domain += start; yield = string_cat(yield, &size, &ptr, sub+domain, end-domain); } } continue; } case EOP_ADDRESSES: { uschar outsep[2] = { ':', '\0' }; uschar *address, *error; int save_ptr = ptr; int start, end, domain; /* Not really used */ while (isspace(*sub)) sub++; if (*sub == '>') { *outsep = *++sub; ++sub; } parse_allow_group = TRUE; for (;;) { uschar *p = parse_find_address_end(sub, FALSE); uschar saveend = *p; *p = '\0'; address = parse_extract_address(sub, &error, &start, &end, &domain, FALSE); *p = saveend; /* Add the address to the output list that we are building. This is done in chunks by searching for the separator character. At the start, unless we are dealing with the first address of the output list, add in a space if the new address begins with the separator character, or is an empty string. */ if (address != NULL) { if (ptr != save_ptr && address[0] == *outsep) yield = string_cat(yield, &size, &ptr, US" ", 1); for (;;) { size_t seglen = Ustrcspn(address, outsep); yield = string_cat(yield, &size, &ptr, address, seglen + 1); /* If we got to the end of the string we output one character too many. */ if (address[seglen] == '\0') { ptr--; break; } yield = string_cat(yield, &size, &ptr, outsep, 1); address += seglen + 1; } /* Output a separator after the string: we will remove the redundant final one at the end. */ yield = string_cat(yield, &size, &ptr, outsep, 1); } if (saveend == '\0') break; sub = p + 1; } /* If we have generated anything, remove the redundant final separator. */ if (ptr != save_ptr) ptr--; parse_allow_group = FALSE; continue; } /* quote puts a string in quotes if it is empty or contains anything other than alphamerics, underscore, dot, or hyphen. quote_local_part puts a string in quotes if RFC 2821/2822 requires it to be quoted in order to be a valid local part. In both cases, newlines and carriage returns are converted into \n and \r respectively */ case EOP_QUOTE: case EOP_QUOTE_LOCAL_PART: if (arg == NULL) { BOOL needs_quote = (*sub == 0); /* TRUE for empty string */ uschar *t = sub - 1; if (c == EOP_QUOTE) { while (!needs_quote && *(++t) != 0) needs_quote = !isalnum(*t) && !strchr("_-.", *t); } else /* EOP_QUOTE_LOCAL_PART */ { while (!needs_quote && *(++t) != 0) needs_quote = !isalnum(*t) && strchr("!#$%&'*+-/=?^_`{|}~", *t) == NULL && (*t != '.' || t == sub || t[1] == 0); } if (needs_quote) { yield = string_cat(yield, &size, &ptr, US"\"", 1); t = sub - 1; while (*(++t) != 0) { if (*t == '\n') yield = string_cat(yield, &size, &ptr, US"\\n", 2); else if (*t == '\r') yield = string_cat(yield, &size, &ptr, US"\\r", 2); else { if (*t == '\\' || *t == '"') yield = string_cat(yield, &size, &ptr, US"\\", 1); yield = string_cat(yield, &size, &ptr, t, 1); } } yield = string_cat(yield, &size, &ptr, US"\"", 1); } else yield = string_cat(yield, &size, &ptr, sub, Ustrlen(sub)); continue; } /* quote_lookuptype does lookup-specific quoting */ else { int n; uschar *opt = Ustrchr(arg, '_'); if (opt != NULL) *opt++ = 0; n = search_findtype(arg, Ustrlen(arg)); if (n < 0) { expand_string_message = search_error_message; goto EXPAND_FAILED; } if (lookup_list[n]->quote != NULL) sub = (lookup_list[n]->quote)(sub, opt); else if (opt != NULL) sub = NULL; if (sub == NULL) { expand_string_message = string_sprintf( "\"%s\" unrecognized after \"${quote_%s\"", opt, arg); goto EXPAND_FAILED; } yield = string_cat(yield, &size, &ptr, sub, Ustrlen(sub)); continue; } /* rx quote sticks in \ before any non-alphameric character so that the insertion works in a regular expression. */ case EOP_RXQUOTE: { uschar *t = sub - 1; while (*(++t) != 0) { if (!isalnum(*t)) yield = string_cat(yield, &size, &ptr, US"\\", 1); yield = string_cat(yield, &size, &ptr, t, 1); } continue; } /* RFC 2047 encodes, assuming headers_charset (default ISO 8859-1) as prescribed by the RFC, if there are characters that need to be encoded */ case EOP_RFC2047: { uschar buffer[2048]; uschar *string = parse_quote_2047(sub, Ustrlen(sub), headers_charset, buffer, sizeof(buffer), FALSE); yield = string_cat(yield, &size, &ptr, string, Ustrlen(string)); continue; } /* RFC 2047 decode */ case EOP_RFC2047D: { int len; uschar *error; uschar *decoded = rfc2047_decode(sub, check_rfc2047_length, headers_charset, '?', &len, &error); if (error != NULL) { expand_string_message = error; goto EXPAND_FAILED; } yield = string_cat(yield, &size, &ptr, decoded, len); continue; } /* from_utf8 converts UTF-8 to 8859-1, turning non-existent chars into underscores */ case EOP_FROM_UTF8: { while (*sub != 0) { int c; uschar buff[4]; GETUTF8INC(c, sub); if (c > 255) c = '_'; buff[0] = c; yield = string_cat(yield, &size, &ptr, buff, 1); } continue; } /* replace illegal UTF-8 sequences by replacement character */ #define UTF8_REPLACEMENT_CHAR US"?" case EOP_UTF8CLEAN: { int seq_len, index = 0; int bytes_left = 0; uschar seq_buff[4]; /* accumulate utf-8 here */ while (*sub != 0) { int complete; long codepoint; uschar c; complete = 0; c = *sub++; if (bytes_left) { if ((c & 0xc0) != 0x80) { /* wrong continuation byte; invalidate all bytes */ complete = 1; /* error */ } else { codepoint = (codepoint << 6) | (c & 0x3f); seq_buff[index++] = c; if (--bytes_left == 0) /* codepoint complete */ { if(codepoint > 0x10FFFF) /* is it too large? */ complete = -1; /* error */ else { /* finished; output utf-8 sequence */ yield = string_cat(yield, &size, &ptr, seq_buff, seq_len); index = 0; } } } } else /* no bytes left: new sequence */ { if((c & 0x80) == 0) /* 1-byte sequence, US-ASCII, keep it */ { yield = string_cat(yield, &size, &ptr, &c, 1); continue; } if((c & 0xe0) == 0xc0) /* 2-byte sequence */ { if(c == 0xc0 || c == 0xc1) /* 0xc0 and 0xc1 are illegal */ complete = -1; else { bytes_left = 1; codepoint = c & 0x1f; } } else if((c & 0xf0) == 0xe0) /* 3-byte sequence */ { bytes_left = 2; codepoint = c & 0x0f; } else if((c & 0xf8) == 0xf0) /* 4-byte sequence */ { bytes_left = 3; codepoint = c & 0x07; } else /* invalid or too long (RFC3629 allows only 4 bytes) */ complete = -1; seq_buff[index++] = c; seq_len = bytes_left + 1; } /* if(bytes_left) */ if (complete != 0) { bytes_left = index = 0; yield = string_cat(yield, &size, &ptr, UTF8_REPLACEMENT_CHAR, 1); } if ((complete == 1) && ((c & 0x80) == 0)) { /* ASCII character follows incomplete sequence */ yield = string_cat(yield, &size, &ptr, &c, 1); } } continue; } /* escape turns all non-printing characters into escape sequences. */ case EOP_ESCAPE: { uschar *t = string_printing(sub); yield = string_cat(yield, &size, &ptr, t, Ustrlen(t)); continue; } /* Handle numeric expression evaluation */ case EOP_EVAL: case EOP_EVAL10: { uschar *save_sub = sub; uschar *error = NULL; int_eximarith_t n = eval_expr(&sub, (c == EOP_EVAL10), &error, FALSE); if (error != NULL) { expand_string_message = string_sprintf("error in expression " "evaluation: %s (after processing \"%.*s\")", error, sub-save_sub, save_sub); goto EXPAND_FAILED; } sprintf(CS var_buffer, PR_EXIM_ARITH, n); yield = string_cat(yield, &size, &ptr, var_buffer, Ustrlen(var_buffer)); continue; } /* Handle time period formating */ case EOP_TIME_EVAL: { int n = readconf_readtime(sub, 0, FALSE); if (n < 0) { expand_string_message = string_sprintf("string \"%s\" is not an " "Exim time interval in \"%s\" operator", sub, name); goto EXPAND_FAILED; } sprintf(CS var_buffer, "%d", n); yield = string_cat(yield, &size, &ptr, var_buffer, Ustrlen(var_buffer)); continue; } case EOP_TIME_INTERVAL: { int n; uschar *t = read_number(&n, sub); if (*t != 0) /* Not A Number*/ { expand_string_message = string_sprintf("string \"%s\" is not a " "positive number in \"%s\" operator", sub, name); goto EXPAND_FAILED; } t = readconf_printtime(n); yield = string_cat(yield, &size, &ptr, t, Ustrlen(t)); continue; } /* Convert string to base64 encoding */ case EOP_STR2B64: { uschar *encstr = auth_b64encode(sub, Ustrlen(sub)); yield = string_cat(yield, &size, &ptr, encstr, Ustrlen(encstr)); continue; } /* strlen returns the length of the string */ case EOP_STRLEN: { uschar buff[24]; (void)sprintf(CS buff, "%d", Ustrlen(sub)); yield = string_cat(yield, &size, &ptr, buff, Ustrlen(buff)); continue; } /* length_n or l_n takes just the first n characters or the whole string, whichever is the shorter; substr_m_n, and s_m_n take n characters from offset m; negative m take from the end; l_n is synonymous with s_0_n. If n is omitted in substr it takes the rest, either to the right or to the left. hash_n or h_n makes a hash of length n from the string, yielding n characters from the set a-z; hash_n_m makes a hash of length n, but uses m characters from the set a-zA-Z0-9. nhash_n returns a single number between 0 and n-1 (in text form), while nhash_n_m returns a div/mod hash as two numbers "a/b". The first lies between 0 and n-1 and the second between 0 and m-1. */ case EOP_LENGTH: case EOP_L: case EOP_SUBSTR: case EOP_S: case EOP_HASH: case EOP_H: case EOP_NHASH: case EOP_NH: { int sign = 1; int value1 = 0; int value2 = -1; int *pn; int len; uschar *ret; if (arg == NULL) { expand_string_message = string_sprintf("missing values after %s", name); goto EXPAND_FAILED; } /* "length" has only one argument, effectively being synonymous with substr_0_n. */ if (c == EOP_LENGTH || c == EOP_L) { pn = &value2; value2 = 0; } /* The others have one or two arguments; for "substr" the first may be negative. The second being negative means "not supplied". */ else { pn = &value1; if (name[0] == 's' && *arg == '-') { sign = -1; arg++; } } /* Read up to two numbers, separated by underscores */ ret = arg; while (*arg != 0) { if (arg != ret && *arg == '_' && pn == &value1) { pn = &value2; value2 = 0; if (arg[1] != 0) arg++; } else if (!isdigit(*arg)) { expand_string_message = string_sprintf("non-digit after underscore in \"%s\"", name); goto EXPAND_FAILED; } else *pn = (*pn)*10 + *arg++ - '0'; } value1 *= sign; /* Perform the required operation */ ret = (c == EOP_HASH || c == EOP_H)? compute_hash(sub, value1, value2, &len) : (c == EOP_NHASH || c == EOP_NH)? compute_nhash(sub, value1, value2, &len) : extract_substr(sub, value1, value2, &len); if (ret == NULL) goto EXPAND_FAILED; yield = string_cat(yield, &size, &ptr, ret, len); continue; } /* Stat a path */ case EOP_STAT: { uschar *s; uschar smode[12]; uschar **modetable[3]; int i; mode_t mode; struct stat st; if ((expand_forbid & RDO_EXISTS) != 0) { expand_string_message = US"Use of the stat() expansion is not permitted"; goto EXPAND_FAILED; } if (stat(CS sub, &st) < 0) { expand_string_message = string_sprintf("stat(%s) failed: %s", sub, strerror(errno)); goto EXPAND_FAILED; } mode = st.st_mode; switch (mode & S_IFMT) { case S_IFIFO: smode[0] = 'p'; break; case S_IFCHR: smode[0] = 'c'; break; case S_IFDIR: smode[0] = 'd'; break; case S_IFBLK: smode[0] = 'b'; break; case S_IFREG: smode[0] = '-'; break; default: smode[0] = '?'; break; } modetable[0] = ((mode & 01000) == 0)? mtable_normal : mtable_sticky; modetable[1] = ((mode & 02000) == 0)? mtable_normal : mtable_setid; modetable[2] = ((mode & 04000) == 0)? mtable_normal : mtable_setid; for (i = 0; i < 3; i++) { memcpy(CS(smode + 7 - i*3), CS(modetable[i][mode & 7]), 3); mode >>= 3; } smode[10] = 0; s = string_sprintf("mode=%04lo smode=%s inode=%ld device=%ld links=%ld " "uid=%ld gid=%ld size=" OFF_T_FMT " atime=%ld mtime=%ld ctime=%ld", (long)(st.st_mode & 077777), smode, (long)st.st_ino, (long)st.st_dev, (long)st.st_nlink, (long)st.st_uid, (long)st.st_gid, st.st_size, (long)st.st_atime, (long)st.st_mtime, (long)st.st_ctime); yield = string_cat(yield, &size, &ptr, s, Ustrlen(s)); continue; } /* vaguely random number less than N */ case EOP_RANDINT: { int_eximarith_t max; uschar *s; max = expand_string_integer(sub, TRUE); if (expand_string_message != NULL) goto EXPAND_FAILED; s = string_sprintf("%d", vaguely_random_number((int)max)); yield = string_cat(yield, &size, &ptr, s, Ustrlen(s)); continue; } /* Reverse IP, including IPv6 to dotted-nibble */ case EOP_REVERSE_IP: { int family, maskptr; uschar reversed[128]; family = string_is_ip_address(sub, &maskptr); if (family == 0) { expand_string_message = string_sprintf( "reverse_ip() not given an IP address [%s]", sub); goto EXPAND_FAILED; } invert_address(reversed, sub); yield = string_cat(yield, &size, &ptr, reversed, Ustrlen(reversed)); continue; } /* Unknown operator */ default: expand_string_message = string_sprintf("unknown expansion operator \"%s\"", name); goto EXPAND_FAILED; } } /* Handle a plain name. If this is the first thing in the expansion, release the pre-allocated buffer. If the result data is known to be in a new buffer, newsize will be set to the size of that buffer, and we can just point at that store instead of copying. Many expansion strings contain just one reference, so this is a useful optimization, especially for humungous headers ($message_headers). */ /*{*/ if (*s++ == '}') { int len; int newsize = 0; if (ptr == 0) { if (resetok) store_reset(yield); yield = NULL; size = 0; } value = find_variable(name, FALSE, skipping, &newsize); if (value == NULL) { expand_string_message = string_sprintf("unknown variable in \"${%s}\"", name); check_variable_error_message(name); goto EXPAND_FAILED; } len = Ustrlen(value); if (yield == NULL && newsize != 0) { yield = value; size = newsize; ptr = len; } else yield = string_cat(yield, &size, &ptr, value, len); continue; } /* Else there's something wrong */ expand_string_message = string_sprintf("\"${%s\" is not a known operator (or a } is missing " "in a variable reference)", name); goto EXPAND_FAILED; } /* If we hit the end of the string when ket_ends is set, there is a missing terminating brace. */ if (ket_ends && *s == 0) { expand_string_message = malformed_header? US"missing } at end of string - could be header name not terminated by colon" : US"missing } at end of string"; goto EXPAND_FAILED; } /* Expansion succeeded; yield may still be NULL here if nothing was actually added to the string. If so, set up an empty string. Add a terminating zero. If left != NULL, return a pointer to the terminator. */ if (yield == NULL) yield = store_get(1); yield[ptr] = 0; if (left != NULL) *left = s; /* Any stacking store that was used above the final string is no longer needed. In many cases the final string will be the first one that was got and so there will be optimal store usage. */ if (resetok) store_reset(yield + ptr + 1); else if (resetok_p) *resetok_p = FALSE; DEBUG(D_expand) { debug_printf("expanding: %.*s\n result: %s\n", (int)(s - string), string, yield); if (skipping) debug_printf("skipping: result is not used\n"); } return yield; /* This is the failure exit: easiest to program with a goto. We still need to update the pointer to the terminator, for cases of nested calls with "fail". */ EXPAND_FAILED_CURLY: expand_string_message = malformed_header? US"missing or misplaced { or } - could be header name not terminated by colon" : US"missing or misplaced { or }"; /* At one point, Exim reset the store to yield (if yield was not NULL), but that is a bad idea, because expand_string_message is in dynamic store. */ EXPAND_FAILED: if (left != NULL) *left = s; DEBUG(D_expand) { debug_printf("failed to expand: %s\n", string); debug_printf(" error message: %s\n", expand_string_message); if (expand_string_forcedfail) debug_printf("failure was forced\n"); } if (resetok_p) *resetok_p = resetok; return NULL; } Commit Message: CWE ID: CWE-189
expand_string_internal(uschar *string, BOOL ket_ends, uschar **left, BOOL skipping, BOOL honour_dollar, BOOL *resetok_p) { int ptr = 0; int size = Ustrlen(string)+ 64; int item_type; uschar *yield = store_get(size); uschar *s = string; uschar *save_expand_nstring[EXPAND_MAXN+1]; int save_expand_nlength[EXPAND_MAXN+1]; BOOL resetok = TRUE; expand_string_forcedfail = FALSE; expand_string_message = US""; while (*s != 0) { uschar *value; uschar name[256]; /* \ escapes the next character, which must exist, or else the expansion fails. There's a special escape, \N, which causes copying of the subject verbatim up to the next \N. Otherwise, the escapes are the standard set. */ if (*s == '\\') { if (s[1] == 0) { expand_string_message = US"\\ at end of string"; goto EXPAND_FAILED; } if (s[1] == 'N') { uschar *t = s + 2; for (s = t; *s != 0; s++) if (*s == '\\' && s[1] == 'N') break; yield = string_cat(yield, &size, &ptr, t, s - t); if (*s != 0) s += 2; } else { uschar ch[1]; ch[0] = string_interpret_escape(&s); s++; yield = string_cat(yield, &size, &ptr, ch, 1); } continue; } /*{*/ /* Anything other than $ is just copied verbatim, unless we are looking for a terminating } character. */ /*{*/ if (ket_ends && *s == '}') break; if (*s != '$' || !honour_dollar) { yield = string_cat(yield, &size, &ptr, s++, 1); continue; } /* No { after the $ - must be a plain name or a number for string match variable. There has to be a fudge for variables that are the names of header fields preceded by "$header_" because header field names can contain any printing characters except space and colon. For those that don't like typing this much, "$h_" is a synonym for "$header_". A non-existent header yields a NULL value; nothing is inserted. */ /*}*/ if (isalpha((*(++s)))) { int len; int newsize = 0; s = read_name(name, sizeof(name), s, US"_"); /* If this is the first thing to be expanded, release the pre-allocated buffer. */ if (ptr == 0 && yield != NULL) { if (resetok) store_reset(yield); yield = NULL; size = 0; } /* Header */ if (Ustrncmp(name, "h_", 2) == 0 || Ustrncmp(name, "rh_", 3) == 0 || Ustrncmp(name, "bh_", 3) == 0 || Ustrncmp(name, "header_", 7) == 0 || Ustrncmp(name, "rheader_", 8) == 0 || Ustrncmp(name, "bheader_", 8) == 0) { BOOL want_raw = (name[0] == 'r')? TRUE : FALSE; uschar *charset = (name[0] == 'b')? NULL : headers_charset; s = read_header_name(name, sizeof(name), s); value = find_header(name, FALSE, &newsize, want_raw, charset); /* If we didn't find the header, and the header contains a closing brace character, this may be a user error where the terminating colon has been omitted. Set a flag to adjust the error message in this case. But there is no error here - nothing gets inserted. */ if (value == NULL) { if (Ustrchr(name, '}') != NULL) malformed_header = TRUE; continue; } } /* Variable */ else { value = find_variable(name, FALSE, skipping, &newsize); if (value == NULL) { expand_string_message = string_sprintf("unknown variable name \"%s\"", name); check_variable_error_message(name); goto EXPAND_FAILED; } } /* If the data is known to be in a new buffer, newsize will be set to the size of that buffer. If this is the first thing in an expansion string, yield will be NULL; just point it at the new store instead of copying. Many expansion strings contain just one reference, so this is a useful optimization, especially for humungous headers. */ len = Ustrlen(value); if (yield == NULL && newsize != 0) { yield = value; size = newsize; ptr = len; } else yield = string_cat(yield, &size, &ptr, value, len); continue; } if (isdigit(*s)) { int n; s = read_number(&n, s); if (n >= 0 && n <= expand_nmax) yield = string_cat(yield, &size, &ptr, expand_nstring[n], expand_nlength[n]); continue; } /* Otherwise, if there's no '{' after $ it's an error. */ /*}*/ if (*s != '{') /*}*/ { expand_string_message = US"$ not followed by letter, digit, or {"; /*}*/ goto EXPAND_FAILED; } /* After { there can be various things, but they all start with an initial word, except for a number for a string match variable. */ if (isdigit((*(++s)))) { int n; s = read_number(&n, s); /*{*/ if (*s++ != '}') { /*{*/ expand_string_message = US"} expected after number"; goto EXPAND_FAILED; } if (n >= 0 && n <= expand_nmax) yield = string_cat(yield, &size, &ptr, expand_nstring[n], expand_nlength[n]); continue; } if (!isalpha(*s)) { expand_string_message = US"letter or digit expected after ${"; /*}*/ goto EXPAND_FAILED; } /* Allow "-" in names to cater for substrings with negative arguments. Since we are checking for known names after { this is OK. */ s = read_name(name, sizeof(name), s, US"_-"); item_type = chop_match(name, item_table, sizeof(item_table)/sizeof(uschar *)); switch(item_type) { /* Call an ACL from an expansion. We feed data in via $acl_arg1 - $acl_arg9. If the ACL returns accept or reject we return content set by "message =" There is currently no limit on recursion; this would have us call acl_check_internal() directly and get a current level from somewhere. See also the acl expansion condition ECOND_ACL and the traditional acl modifier ACLC_ACL. Assume that the function has side-effects on the store that must be preserved. */ case EITEM_ACL: /* ${acl {name} {arg1}{arg2}...} */ { uschar *sub[10]; /* name + arg1-arg9 (which must match number of acl_arg[]) */ uschar *user_msg; switch(read_subs(sub, 10, 1, &s, skipping, TRUE, US"acl", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } if (skipping) continue; resetok = FALSE; switch(eval_acl(sub, sizeof(sub)/sizeof(*sub), &user_msg)) { case OK: case FAIL: DEBUG(D_expand) debug_printf("acl expansion yield: %s\n", user_msg); if (user_msg) yield = string_cat(yield, &size, &ptr, user_msg, Ustrlen(user_msg)); continue; case DEFER: expand_string_forcedfail = TRUE; default: expand_string_message = string_sprintf("error from acl \"%s\"", sub[0]); goto EXPAND_FAILED; } } /* Handle conditionals - preserve the values of the numerical expansion variables in case they get changed by a regular expression match in the condition. If not, they retain their external settings. At the end of this "if" section, they get restored to their previous values. */ case EITEM_IF: { BOOL cond = FALSE; uschar *next_s; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); while (isspace(*s)) s++; next_s = eval_condition(s, &resetok, skipping? NULL : &cond); if (next_s == NULL) goto EXPAND_FAILED; /* message already set */ DEBUG(D_expand) debug_printf("condition: %.*s\n result: %s\n", (int)(next_s - s), s, cond? "true" : "false"); s = next_s; /* The handling of "yes" and "no" result strings is now in a separate function that is also used by ${lookup} and ${extract} and ${run}. */ switch(process_yesno( skipping, /* were previously skipping */ cond, /* success/failure indicator */ lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"if", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } /* Restore external setting of expansion variables for continuation at this level. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } /* Handle database lookups unless locked out. If "skipping" is TRUE, we are expanding an internal string that isn't actually going to be used. All we need to do is check the syntax, so don't do a lookup at all. Preserve the values of the numerical expansion variables in case they get changed by a partial lookup. If not, they retain their external settings. At the end of this "lookup" section, they get restored to their previous values. */ case EITEM_LOOKUP: { int stype, partial, affixlen, starflags; int expand_setup = 0; int nameptr = 0; uschar *key, *filename, *affix; uschar *save_lookup_value = lookup_value; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); if ((expand_forbid & RDO_LOOKUP) != 0) { expand_string_message = US"lookup expansions are not permitted"; goto EXPAND_FAILED; } /* Get the key we are to look up for single-key+file style lookups. Otherwise set the key NULL pro-tem. */ while (isspace(*s)) s++; if (*s == '{') /*}*/ { key = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (key == NULL) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; while (isspace(*s)) s++; } else key = NULL; /* Find out the type of database */ if (!isalpha(*s)) { expand_string_message = US"missing lookup type"; goto EXPAND_FAILED; } /* The type is a string that may contain special characters of various kinds. Allow everything except space or { to appear; the actual content is checked by search_findtype_partial. */ /*}*/ while (*s != 0 && *s != '{' && !isspace(*s)) /*}*/ { if (nameptr < sizeof(name) - 1) name[nameptr++] = *s; s++; } name[nameptr] = 0; while (isspace(*s)) s++; /* Now check for the individual search type and any partial or default options. Only those types that are actually in the binary are valid. */ stype = search_findtype_partial(name, &partial, &affix, &affixlen, &starflags); if (stype < 0) { expand_string_message = search_error_message; goto EXPAND_FAILED; } /* Check that a key was provided for those lookup types that need it, and was not supplied for those that use the query style. */ if (!mac_islookup(stype, lookup_querystyle|lookup_absfilequery)) { if (key == NULL) { expand_string_message = string_sprintf("missing {key} for single-" "key \"%s\" lookup", name); goto EXPAND_FAILED; } } else { if (key != NULL) { expand_string_message = string_sprintf("a single key was given for " "lookup type \"%s\", which is not a single-key lookup type", name); goto EXPAND_FAILED; } } /* Get the next string in brackets and expand it. It is the file name for single-key+file lookups, and the whole query otherwise. In the case of queries that also require a file name (e.g. sqlite), the file name comes first. */ if (*s != '{') goto EXPAND_FAILED_CURLY; filename = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (filename == NULL) goto EXPAND_FAILED; if (*s++ != '}') goto EXPAND_FAILED_CURLY; while (isspace(*s)) s++; /* If this isn't a single-key+file lookup, re-arrange the variables to be appropriate for the search_ functions. For query-style lookups, there is just a "key", and no file name. For the special query-style + file types, the query (i.e. "key") starts with a file name. */ if (key == NULL) { while (isspace(*filename)) filename++; key = filename; if (mac_islookup(stype, lookup_querystyle)) { filename = NULL; } else { if (*filename != '/') { expand_string_message = string_sprintf( "absolute file name expected for \"%s\" lookup", name); goto EXPAND_FAILED; } while (*key != 0 && !isspace(*key)) key++; if (*key != 0) *key++ = 0; } } /* If skipping, don't do the next bit - just lookup_value == NULL, as if the entry was not found. Note that there is no search_close() function. Files are left open in case of re-use. At suitable places in higher logic, search_tidyup() is called to tidy all open files. This can save opening the same file several times. However, files may also get closed when others are opened, if too many are open at once. The rule is that a handle should not be used after a second search_open(). Request that a partial search sets up $1 and maybe $2 by passing expand_setup containing zero. If its value changes, reset expand_nmax, since new variables will have been set. Note that at the end of this "lookup" section, the old numeric variables are restored. */ if (skipping) lookup_value = NULL; else { void *handle = search_open(filename, stype, 0, NULL, NULL); if (handle == NULL) { expand_string_message = search_error_message; goto EXPAND_FAILED; } lookup_value = search_find(handle, filename, key, partial, affix, affixlen, starflags, &expand_setup); if (search_find_defer) { expand_string_message = string_sprintf("lookup of \"%s\" gave DEFER: %s", string_printing2(key, FALSE), search_error_message); goto EXPAND_FAILED; } if (expand_setup > 0) expand_nmax = expand_setup; } /* The handling of "yes" and "no" result strings is now in a separate function that is also used by ${if} and ${extract}. */ switch(process_yesno( skipping, /* were previously skipping */ lookup_value != NULL, /* success/failure indicator */ save_lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"lookup", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } /* Restore external setting of expansion variables for carrying on at this level, and continue. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } /* If Perl support is configured, handle calling embedded perl subroutines, unless locked out at this time. Syntax is ${perl{sub}} or ${perl{sub}{arg}} or ${perl{sub}{arg1}{arg2}} or up to a maximum of EXIM_PERL_MAX_ARGS arguments (defined below). */ #define EXIM_PERL_MAX_ARGS 8 case EITEM_PERL: #ifndef EXIM_PERL expand_string_message = US"\"${perl\" encountered, but this facility " /*}*/ "is not included in this binary"; goto EXPAND_FAILED; #else /* EXIM_PERL */ { uschar *sub_arg[EXIM_PERL_MAX_ARGS + 2]; uschar *new_yield; if ((expand_forbid & RDO_PERL) != 0) { expand_string_message = US"Perl calls are not permitted"; goto EXPAND_FAILED; } switch(read_subs(sub_arg, EXIM_PERL_MAX_ARGS + 1, 1, &s, skipping, TRUE, US"perl", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* If skipping, we don't actually do anything */ if (skipping) continue; /* Start the interpreter if necessary */ if (!opt_perl_started) { uschar *initerror; if (opt_perl_startup == NULL) { expand_string_message = US"A setting of perl_startup is needed when " "using the Perl interpreter"; goto EXPAND_FAILED; } DEBUG(D_any) debug_printf("Starting Perl interpreter\n"); initerror = init_perl(opt_perl_startup); if (initerror != NULL) { expand_string_message = string_sprintf("error in perl_startup code: %s\n", initerror); goto EXPAND_FAILED; } opt_perl_started = TRUE; } /* Call the function */ sub_arg[EXIM_PERL_MAX_ARGS + 1] = NULL; new_yield = call_perl_cat(yield, &size, &ptr, &expand_string_message, sub_arg[0], sub_arg + 1); /* NULL yield indicates failure; if the message pointer has been set to NULL, the yield was undef, indicating a forced failure. Otherwise the message will indicate some kind of Perl error. */ if (new_yield == NULL) { if (expand_string_message == NULL) { expand_string_message = string_sprintf("Perl subroutine \"%s\" returned undef to force " "failure", sub_arg[0]); expand_string_forcedfail = TRUE; } goto EXPAND_FAILED; } /* Yield succeeded. Ensure forcedfail is unset, just in case it got set during a callback from Perl. */ expand_string_forcedfail = FALSE; yield = new_yield; continue; } #endif /* EXIM_PERL */ /* Transform email address to "prvs" scheme to use as BATV-signed return path */ case EITEM_PRVS: { uschar *sub_arg[3]; uschar *p,*domain; switch(read_subs(sub_arg, 3, 2, &s, skipping, TRUE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* If skipping, we don't actually do anything */ if (skipping) continue; /* sub_arg[0] is the address */ domain = Ustrrchr(sub_arg[0],'@'); if ( (domain == NULL) || (domain == sub_arg[0]) || (Ustrlen(domain) == 1) ) { expand_string_message = US"prvs first argument must be a qualified email address"; goto EXPAND_FAILED; } /* Calculate the hash. The second argument must be a single-digit key number, or unset. */ if (sub_arg[2] != NULL && (!isdigit(sub_arg[2][0]) || sub_arg[2][1] != 0)) { expand_string_message = US"prvs second argument must be a single digit"; goto EXPAND_FAILED; } p = prvs_hmac_sha1(sub_arg[0],sub_arg[1],sub_arg[2],prvs_daystamp(7)); if (p == NULL) { expand_string_message = US"prvs hmac-sha1 conversion failed"; goto EXPAND_FAILED; } /* Now separate the domain from the local part */ *domain++ = '\0'; yield = string_cat(yield,&size,&ptr,US"prvs=",5); string_cat(yield,&size,&ptr,(sub_arg[2] != NULL) ? sub_arg[2] : US"0", 1); string_cat(yield,&size,&ptr,prvs_daystamp(7),3); string_cat(yield,&size,&ptr,p,6); string_cat(yield,&size,&ptr,US"=",1); string_cat(yield,&size,&ptr,sub_arg[0],Ustrlen(sub_arg[0])); string_cat(yield,&size,&ptr,US"@",1); string_cat(yield,&size,&ptr,domain,Ustrlen(domain)); continue; } /* Check a prvs-encoded address for validity */ case EITEM_PRVSCHECK: { uschar *sub_arg[3]; int mysize = 0, myptr = 0; const pcre *re; uschar *p; /* TF: Ugliness: We want to expand parameter 1 first, then set up expansion variables that are used in the expansion of parameter 2. So we clone the string for the first expansion, where we only expand parameter 1. PH: Actually, that isn't necessary. The read_subs() function is designed to work this way for the ${if and ${lookup expansions. I've tidied the code. */ /* Reset expansion variables */ prvscheck_result = NULL; prvscheck_address = NULL; prvscheck_keynum = NULL; switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } re = regex_must_compile(US"^prvs\\=([0-9])([0-9]{3})([A-F0-9]{6})\\=(.+)\\@(.+)$", TRUE,FALSE); if (regex_match_and_setup(re,sub_arg[0],0,-1)) { uschar *local_part = string_copyn(expand_nstring[4],expand_nlength[4]); uschar *key_num = string_copyn(expand_nstring[1],expand_nlength[1]); uschar *daystamp = string_copyn(expand_nstring[2],expand_nlength[2]); uschar *hash = string_copyn(expand_nstring[3],expand_nlength[3]); uschar *domain = string_copyn(expand_nstring[5],expand_nlength[5]); DEBUG(D_expand) debug_printf("prvscheck localpart: %s\n", local_part); DEBUG(D_expand) debug_printf("prvscheck key number: %s\n", key_num); DEBUG(D_expand) debug_printf("prvscheck daystamp: %s\n", daystamp); DEBUG(D_expand) debug_printf("prvscheck hash: %s\n", hash); DEBUG(D_expand) debug_printf("prvscheck domain: %s\n", domain); /* Set up expansion variables */ prvscheck_address = string_cat(NULL, &mysize, &myptr, local_part, Ustrlen(local_part)); string_cat(prvscheck_address,&mysize,&myptr,US"@",1); string_cat(prvscheck_address,&mysize,&myptr,domain,Ustrlen(domain)); prvscheck_address[myptr] = '\0'; prvscheck_keynum = string_copy(key_num); /* Now expand the second argument */ switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* Now we have the key and can check the address. */ p = prvs_hmac_sha1(prvscheck_address, sub_arg[0], prvscheck_keynum, daystamp); if (p == NULL) { expand_string_message = US"hmac-sha1 conversion failed"; goto EXPAND_FAILED; } DEBUG(D_expand) debug_printf("prvscheck: received hash is %s\n", hash); DEBUG(D_expand) debug_printf("prvscheck: own hash is %s\n", p); if (Ustrcmp(p,hash) == 0) { /* Success, valid BATV address. Now check the expiry date. */ uschar *now = prvs_daystamp(0); unsigned int inow = 0,iexpire = 1; (void)sscanf(CS now,"%u",&inow); (void)sscanf(CS daystamp,"%u",&iexpire); /* When "iexpire" is < 7, a "flip" has occured. Adjust "inow" accordingly. */ if ( (iexpire < 7) && (inow >= 993) ) inow = 0; if (iexpire >= inow) { prvscheck_result = US"1"; DEBUG(D_expand) debug_printf("prvscheck: success, $pvrs_result set to 1\n"); } else { prvscheck_result = NULL; DEBUG(D_expand) debug_printf("prvscheck: signature expired, $pvrs_result unset\n"); } } else { prvscheck_result = NULL; DEBUG(D_expand) debug_printf("prvscheck: hash failure, $pvrs_result unset\n"); } /* Now expand the final argument. We leave this till now so that it can include $prvscheck_result. */ switch(read_subs(sub_arg, 1, 0, &s, skipping, TRUE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } if (sub_arg[0] == NULL || *sub_arg[0] == '\0') yield = string_cat(yield,&size,&ptr,prvscheck_address,Ustrlen(prvscheck_address)); else yield = string_cat(yield,&size,&ptr,sub_arg[0],Ustrlen(sub_arg[0])); /* Reset the "internal" variables afterwards, because they are in dynamic store that will be reclaimed if the expansion succeeded. */ prvscheck_address = NULL; prvscheck_keynum = NULL; } else { /* Does not look like a prvs encoded address, return the empty string. We need to make sure all subs are expanded first, so as to skip over the entire item. */ switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } } continue; } /* Handle "readfile" to insert an entire file */ case EITEM_READFILE: { FILE *f; uschar *sub_arg[2]; if ((expand_forbid & RDO_READFILE) != 0) { expand_string_message = US"file insertions are not permitted"; goto EXPAND_FAILED; } switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US"readfile", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* If skipping, we don't actually do anything */ if (skipping) continue; /* Open the file and read it */ f = Ufopen(sub_arg[0], "rb"); if (f == NULL) { expand_string_message = string_open_failed(errno, "%s", sub_arg[0]); goto EXPAND_FAILED; } yield = cat_file(f, yield, &size, &ptr, sub_arg[1]); (void)fclose(f); continue; } /* Handle "readsocket" to insert data from a Unix domain socket */ case EITEM_READSOCK: { int fd; int timeout = 5; int save_ptr = ptr; FILE *f; struct sockaddr_un sockun; /* don't call this "sun" ! */ uschar *arg; uschar *sub_arg[4]; if ((expand_forbid & RDO_READSOCK) != 0) { expand_string_message = US"socket insertions are not permitted"; goto EXPAND_FAILED; } /* Read up to 4 arguments, but don't do the end of item check afterwards, because there may be a string for expansion on failure. */ switch(read_subs(sub_arg, 4, 2, &s, skipping, FALSE, US"readsocket", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: /* Won't occur: no end check */ case 3: goto EXPAND_FAILED; } /* Sort out timeout, if given */ if (sub_arg[2] != NULL) { timeout = readconf_readtime(sub_arg[2], 0, FALSE); if (timeout < 0) { expand_string_message = string_sprintf("bad time value %s", sub_arg[2]); goto EXPAND_FAILED; } } else sub_arg[3] = NULL; /* No eol if no timeout */ /* If skipping, we don't actually do anything. Otherwise, arrange to connect to either an IP or a Unix socket. */ if (!skipping) { /* Handle an IP (internet) domain */ if (Ustrncmp(sub_arg[0], "inet:", 5) == 0) { int port; uschar *server_name = sub_arg[0] + 5; uschar *port_name = Ustrrchr(server_name, ':'); /* Sort out the port */ if (port_name == NULL) { expand_string_message = string_sprintf("missing port for readsocket %s", sub_arg[0]); goto EXPAND_FAILED; } *port_name++ = 0; /* Terminate server name */ if (isdigit(*port_name)) { uschar *end; port = Ustrtol(port_name, &end, 0); if (end != port_name + Ustrlen(port_name)) { expand_string_message = string_sprintf("invalid port number %s", port_name); goto EXPAND_FAILED; } } else { struct servent *service_info = getservbyname(CS port_name, "tcp"); if (service_info == NULL) { expand_string_message = string_sprintf("unknown port \"%s\"", port_name); goto EXPAND_FAILED; } port = ntohs(service_info->s_port); } if ((fd = ip_connectedsocket(SOCK_STREAM, server_name, port, port, timeout, NULL, &expand_string_message)) < 0) goto SOCK_FAIL; } /* Handle a Unix domain socket */ else { int rc; if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) { expand_string_message = string_sprintf("failed to create socket: %s", strerror(errno)); goto SOCK_FAIL; } sockun.sun_family = AF_UNIX; sprintf(sockun.sun_path, "%.*s", (int)(sizeof(sockun.sun_path)-1), sub_arg[0]); sigalrm_seen = FALSE; alarm(timeout); rc = connect(fd, (struct sockaddr *)(&sockun), sizeof(sockun)); alarm(0); if (sigalrm_seen) { expand_string_message = US "socket connect timed out"; goto SOCK_FAIL; } if (rc < 0) { expand_string_message = string_sprintf("failed to connect to socket " "%s: %s", sub_arg[0], strerror(errno)); goto SOCK_FAIL; } } DEBUG(D_expand) debug_printf("connected to socket %s\n", sub_arg[0]); /* Allow sequencing of test actions */ if (running_in_test_harness) millisleep(100); /* Write the request string, if not empty */ if (sub_arg[1][0] != 0) { int len = Ustrlen(sub_arg[1]); DEBUG(D_expand) debug_printf("writing \"%s\" to socket\n", sub_arg[1]); if (write(fd, sub_arg[1], len) != len) { expand_string_message = string_sprintf("request write to socket " "failed: %s", strerror(errno)); goto SOCK_FAIL; } } /* Shut down the sending side of the socket. This helps some servers to recognise that it is their turn to do some work. Just in case some system doesn't have this function, make it conditional. */ #ifdef SHUT_WR shutdown(fd, SHUT_WR); #endif if (running_in_test_harness) millisleep(100); /* Now we need to read from the socket, under a timeout. The function that reads a file can be used. */ f = fdopen(fd, "rb"); sigalrm_seen = FALSE; alarm(timeout); yield = cat_file(f, yield, &size, &ptr, sub_arg[3]); alarm(0); (void)fclose(f); /* After a timeout, we restore the pointer in the result, that is, make sure we add nothing from the socket. */ if (sigalrm_seen) { ptr = save_ptr; expand_string_message = US "socket read timed out"; goto SOCK_FAIL; } } /* The whole thing has worked (or we were skipping). If there is a failure string following, we need to skip it. */ if (*s == '{') { if (expand_string_internal(s+1, TRUE, &s, TRUE, TRUE, &resetok) == NULL) goto EXPAND_FAILED; if (*s++ != '}') goto EXPAND_FAILED_CURLY; while (isspace(*s)) s++; } if (*s++ != '}') goto EXPAND_FAILED_CURLY; continue; /* Come here on failure to create socket, connect socket, write to the socket, or timeout on reading. If another substring follows, expand and use it. Otherwise, those conditions give expand errors. */ SOCK_FAIL: if (*s != '{') goto EXPAND_FAILED; DEBUG(D_any) debug_printf("%s\n", expand_string_message); arg = expand_string_internal(s+1, TRUE, &s, FALSE, TRUE, &resetok); if (arg == NULL) goto EXPAND_FAILED; yield = string_cat(yield, &size, &ptr, arg, Ustrlen(arg)); if (*s++ != '}') goto EXPAND_FAILED_CURLY; while (isspace(*s)) s++; if (*s++ != '}') goto EXPAND_FAILED_CURLY; continue; } /* Handle "run" to execute a program. */ case EITEM_RUN: { FILE *f; uschar *arg; uschar **argv; pid_t pid; int fd_in, fd_out; int lsize = 0; int lptr = 0; if ((expand_forbid & RDO_RUN) != 0) { expand_string_message = US"running a command is not permitted"; goto EXPAND_FAILED; } while (isspace(*s)) s++; if (*s != '{') goto EXPAND_FAILED_CURLY; arg = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (arg == NULL) goto EXPAND_FAILED; while (isspace(*s)) s++; if (*s++ != '}') goto EXPAND_FAILED_CURLY; if (skipping) /* Just pretend it worked when we're skipping */ { runrc = 0; } else { if (!transport_set_up_command(&argv, /* anchor for arg list */ arg, /* raw command */ FALSE, /* don't expand the arguments */ 0, /* not relevant when... */ NULL, /* no transporting address */ US"${run} expansion", /* for error messages */ &expand_string_message)) /* where to put error message */ { goto EXPAND_FAILED; } /* Create the child process, making it a group leader. */ pid = child_open(argv, NULL, 0077, &fd_in, &fd_out, TRUE); if (pid < 0) { expand_string_message = string_sprintf("couldn't create child process: %s", strerror(errno)); goto EXPAND_FAILED; } /* Nothing is written to the standard input. */ (void)close(fd_in); /* Read the pipe to get the command's output into $value (which is kept in lookup_value). Read during execution, so that if the output exceeds the OS pipe buffer limit, we don't block forever. */ f = fdopen(fd_out, "rb"); sigalrm_seen = FALSE; alarm(60); lookup_value = cat_file(f, lookup_value, &lsize, &lptr, NULL); alarm(0); (void)fclose(f); /* Wait for the process to finish, applying the timeout, and inspect its return code for serious disasters. Simple non-zero returns are passed on. */ if (sigalrm_seen == TRUE || (runrc = child_close(pid, 30)) < 0) { if (sigalrm_seen == TRUE || runrc == -256) { expand_string_message = string_sprintf("command timed out"); killpg(pid, SIGKILL); /* Kill the whole process group */ } else if (runrc == -257) expand_string_message = string_sprintf("wait() failed: %s", strerror(errno)); else expand_string_message = string_sprintf("command killed by signal %d", -runrc); goto EXPAND_FAILED; } } /* Process the yes/no strings; $value may be useful in both cases */ switch(process_yesno( skipping, /* were previously skipping */ runrc == 0, /* success/failure indicator */ lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"run", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } continue; } /* Handle character translation for "tr" */ case EITEM_TR: { int oldptr = ptr; int o2m; uschar *sub[3]; switch(read_subs(sub, 3, 3, &s, skipping, TRUE, US"tr", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } yield = string_cat(yield, &size, &ptr, sub[0], Ustrlen(sub[0])); o2m = Ustrlen(sub[2]) - 1; if (o2m >= 0) for (; oldptr < ptr; oldptr++) { uschar *m = Ustrrchr(sub[1], yield[oldptr]); if (m != NULL) { int o = m - sub[1]; yield[oldptr] = sub[2][(o < o2m)? o : o2m]; } } continue; } /* Handle "hash", "length", "nhash", and "substr" when they are given with expanded arguments. */ case EITEM_HASH: case EITEM_LENGTH: case EITEM_NHASH: case EITEM_SUBSTR: { int i; int len; uschar *ret; int val[2] = { 0, -1 }; uschar *sub[3]; /* "length" takes only 2 arguments whereas the others take 2 or 3. Ensure that sub[2] is set in the ${length } case. */ sub[2] = NULL; switch(read_subs(sub, (item_type == EITEM_LENGTH)? 2:3, 2, &s, skipping, TRUE, name, &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* Juggle the arguments if there are only two of them: always move the string to the last position and make ${length{n}{str}} equivalent to ${substr{0}{n}{str}}. See the defaults for val[] above. */ if (sub[2] == NULL) { sub[2] = sub[1]; sub[1] = NULL; if (item_type == EITEM_LENGTH) { sub[1] = sub[0]; sub[0] = NULL; } } for (i = 0; i < 2; i++) { if (sub[i] == NULL) continue; val[i] = (int)Ustrtol(sub[i], &ret, 10); if (*ret != 0 || (i != 0 && val[i] < 0)) { expand_string_message = string_sprintf("\"%s\" is not a%s number " "(in \"%s\" expansion)", sub[i], (i != 0)? " positive" : "", name); goto EXPAND_FAILED; } } ret = (item_type == EITEM_HASH)? compute_hash(sub[2], val[0], val[1], &len) : (item_type == EITEM_NHASH)? compute_nhash(sub[2], val[0], val[1], &len) : extract_substr(sub[2], val[0], val[1], &len); if (ret == NULL) goto EXPAND_FAILED; yield = string_cat(yield, &size, &ptr, ret, len); continue; } /* Handle HMAC computation: ${hmac{<algorithm>}{<secret>}{<text>}} This code originally contributed by Steve Haslam. It currently supports the use of MD5 and SHA-1 hashes. We need some workspace that is large enough to handle all the supported hash types. Use macros to set the sizes rather than be too elaborate. */ #define MAX_HASHLEN 20 #define MAX_HASHBLOCKLEN 64 case EITEM_HMAC: { uschar *sub[3]; md5 md5_base; sha1 sha1_base; void *use_base; int type, i; int hashlen; /* Number of octets for the hash algorithm's output */ int hashblocklen; /* Number of octets the hash algorithm processes */ uschar *keyptr, *p; unsigned int keylen; uschar keyhash[MAX_HASHLEN]; uschar innerhash[MAX_HASHLEN]; uschar finalhash[MAX_HASHLEN]; uschar finalhash_hex[2*MAX_HASHLEN]; uschar innerkey[MAX_HASHBLOCKLEN]; uschar outerkey[MAX_HASHBLOCKLEN]; switch (read_subs(sub, 3, 3, &s, skipping, TRUE, name, &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } if (Ustrcmp(sub[0], "md5") == 0) { type = HMAC_MD5; use_base = &md5_base; hashlen = 16; hashblocklen = 64; } else if (Ustrcmp(sub[0], "sha1") == 0) { type = HMAC_SHA1; use_base = &sha1_base; hashlen = 20; hashblocklen = 64; } else { expand_string_message = string_sprintf("hmac algorithm \"%s\" is not recognised", sub[0]); goto EXPAND_FAILED; } keyptr = sub[1]; keylen = Ustrlen(keyptr); /* If the key is longer than the hash block length, then hash the key first */ if (keylen > hashblocklen) { chash_start(type, use_base); chash_end(type, use_base, keyptr, keylen, keyhash); keyptr = keyhash; keylen = hashlen; } /* Now make the inner and outer key values */ memset(innerkey, 0x36, hashblocklen); memset(outerkey, 0x5c, hashblocklen); for (i = 0; i < keylen; i++) { innerkey[i] ^= keyptr[i]; outerkey[i] ^= keyptr[i]; } /* Now do the hashes */ chash_start(type, use_base); chash_mid(type, use_base, innerkey); chash_end(type, use_base, sub[2], Ustrlen(sub[2]), innerhash); chash_start(type, use_base); chash_mid(type, use_base, outerkey); chash_end(type, use_base, innerhash, hashlen, finalhash); /* Encode the final hash as a hex string */ p = finalhash_hex; for (i = 0; i < hashlen; i++) { *p++ = hex_digits[(finalhash[i] & 0xf0) >> 4]; *p++ = hex_digits[finalhash[i] & 0x0f]; } DEBUG(D_any) debug_printf("HMAC[%s](%.*s,%.*s)=%.*s\n", sub[0], (int)keylen, keyptr, Ustrlen(sub[2]), sub[2], hashlen*2, finalhash_hex); yield = string_cat(yield, &size, &ptr, finalhash_hex, hashlen*2); } continue; /* Handle global substitution for "sg" - like Perl's s/xxx/yyy/g operator. We have to save the numerical variables and restore them afterwards. */ case EITEM_SG: { const pcre *re; int moffset, moffsetextra, slen; int roffset; int emptyopt; const uschar *rerror; uschar *subject; uschar *sub[3]; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); switch(read_subs(sub, 3, 3, &s, skipping, TRUE, US"sg", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* Compile the regular expression */ re = pcre_compile(CS sub[1], PCRE_COPT, (const char **)&rerror, &roffset, NULL); if (re == NULL) { expand_string_message = string_sprintf("regular expression error in " "\"%s\": %s at offset %d", sub[1], rerror, roffset); goto EXPAND_FAILED; } /* Now run a loop to do the substitutions as often as necessary. It ends when there are no more matches. Take care over matches of the null string; do the same thing as Perl does. */ subject = sub[0]; slen = Ustrlen(sub[0]); moffset = moffsetextra = 0; emptyopt = 0; for (;;) { int ovector[3*(EXPAND_MAXN+1)]; int n = pcre_exec(re, NULL, CS subject, slen, moffset + moffsetextra, PCRE_EOPT | emptyopt, ovector, sizeof(ovector)/sizeof(int)); int nn; uschar *insert; /* No match - if we previously set PCRE_NOTEMPTY after a null match, this is not necessarily the end. We want to repeat the match from one character further along, but leaving the basic offset the same (for copying below). We can't be at the end of the string - that was checked before setting PCRE_NOTEMPTY. If PCRE_NOTEMPTY is not set, we are finished; copy the remaining string and end the loop. */ if (n < 0) { if (emptyopt != 0) { moffsetextra = 1; emptyopt = 0; continue; } yield = string_cat(yield, &size, &ptr, subject+moffset, slen-moffset); break; } /* Match - set up for expanding the replacement. */ if (n == 0) n = EXPAND_MAXN + 1; expand_nmax = 0; for (nn = 0; nn < n*2; nn += 2) { expand_nstring[expand_nmax] = subject + ovector[nn]; expand_nlength[expand_nmax++] = ovector[nn+1] - ovector[nn]; } expand_nmax--; /* Copy the characters before the match, plus the expanded insertion. */ yield = string_cat(yield, &size, &ptr, subject + moffset, ovector[0] - moffset); insert = expand_string(sub[2]); if (insert == NULL) goto EXPAND_FAILED; yield = string_cat(yield, &size, &ptr, insert, Ustrlen(insert)); moffset = ovector[1]; moffsetextra = 0; emptyopt = 0; /* If we have matched an empty string, first check to see if we are at the end of the subject. If so, the loop is over. Otherwise, mimic what Perl's /g options does. This turns out to be rather cunning. First we set PCRE_NOTEMPTY and PCRE_ANCHORED and try the match a non-empty string at the same point. If this fails (picked up above) we advance to the next character. */ if (ovector[0] == ovector[1]) { if (ovector[0] == slen) break; emptyopt = PCRE_NOTEMPTY | PCRE_ANCHORED; } } /* All done - restore numerical variables. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } /* Handle keyed and numbered substring extraction. If the first argument consists entirely of digits, then a numerical extraction is assumed. */ case EITEM_EXTRACT: { int i; int j = 2; int field_number = 1; BOOL field_number_set = FALSE; uschar *save_lookup_value = lookup_value; uschar *sub[3]; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); /* Read the arguments */ for (i = 0; i < j; i++) { while (isspace(*s)) s++; if (*s == '{') /*}*/ { sub[i] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (sub[i] == NULL) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; /* After removal of leading and trailing white space, the first argument must not be empty; if it consists entirely of digits (optionally preceded by a minus sign), this is a numerical extraction, and we expect 3 arguments. */ if (i == 0) { int len; int x = 0; uschar *p = sub[0]; while (isspace(*p)) p++; sub[0] = p; len = Ustrlen(p); while (len > 0 && isspace(p[len-1])) len--; p[len] = 0; if (*p == 0 && !skipping) { expand_string_message = US"first argument of \"extract\" must " "not be empty"; goto EXPAND_FAILED; } if (*p == '-') { field_number = -1; p++; } while (*p != 0 && isdigit(*p)) x = x * 10 + *p++ - '0'; if (*p == 0) { field_number *= x; j = 3; /* Need 3 args */ field_number_set = TRUE; } } } else goto EXPAND_FAILED_CURLY; } /* Extract either the numbered or the keyed substring into $value. If skipping, just pretend the extraction failed. */ lookup_value = skipping? NULL : field_number_set? expand_gettokened(field_number, sub[1], sub[2]) : expand_getkeyed(sub[0], sub[1]); /* If no string follows, $value gets substituted; otherwise there can be yes/no strings, as for lookup or if. */ switch(process_yesno( skipping, /* were previously skipping */ lookup_value != NULL, /* success/failure indicator */ save_lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"extract", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } /* All done - restore numerical variables. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } /* return the Nth item from a list */ case EITEM_LISTEXTRACT: { int i; int field_number = 1; uschar *save_lookup_value = lookup_value; uschar *sub[2]; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); /* Read the field & list arguments */ for (i = 0; i < 2; i++) { while (isspace(*s)) s++; if (*s != '{') /*}*/ goto EXPAND_FAILED_CURLY; sub[i] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (!sub[i]) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; /* After removal of leading and trailing white space, the first argument must be numeric and nonempty. */ if (i == 0) { int len; int x = 0; uschar *p = sub[0]; while (isspace(*p)) p++; sub[0] = p; len = Ustrlen(p); while (len > 0 && isspace(p[len-1])) len--; p[len] = 0; if (!*p && !skipping) { expand_string_message = US"first argument of \"listextract\" must " "not be empty"; goto EXPAND_FAILED; } if (*p == '-') { field_number = -1; p++; } while (*p && isdigit(*p)) x = x * 10 + *p++ - '0'; if (*p) { expand_string_message = US"first argument of \"listextract\" must " "be numeric"; goto EXPAND_FAILED; } field_number *= x; } } /* Extract the numbered element into $value. If skipping, just pretend the extraction failed. */ lookup_value = skipping? NULL : expand_getlistele(field_number, sub[1]); /* If no string follows, $value gets substituted; otherwise there can be yes/no strings, as for lookup or if. */ switch(process_yesno( skipping, /* were previously skipping */ lookup_value != NULL, /* success/failure indicator */ save_lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"extract", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } /* All done - restore numerical variables. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } #ifdef SUPPORT_TLS case EITEM_CERTEXTRACT: { uschar *save_lookup_value = lookup_value; uschar *sub[2]; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); /* Read the field argument */ while (isspace(*s)) s++; if (*s != '{') /*}*/ goto EXPAND_FAILED_CURLY; sub[0] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (!sub[0]) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; /* strip spaces fore & aft */ { int len; uschar *p = sub[0]; while (isspace(*p)) p++; sub[0] = p; len = Ustrlen(p); while (len > 0 && isspace(p[len-1])) len--; p[len] = 0; } /* inspect the cert argument */ while (isspace(*s)) s++; if (*s != '{') /*}*/ goto EXPAND_FAILED_CURLY; if (*++s != '$') { expand_string_message = US"second argument of \"certextract\" must " "be a certificate variable"; goto EXPAND_FAILED; } sub[1] = expand_string_internal(s+1, TRUE, &s, skipping, FALSE, &resetok); if (!sub[1]) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; if (skipping) lookup_value = NULL; else { lookup_value = expand_getcertele(sub[0], sub[1]); if (*expand_string_message) goto EXPAND_FAILED; } switch(process_yesno( skipping, /* were previously skipping */ lookup_value != NULL, /* success/failure indicator */ save_lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"extract", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } #endif /*SUPPORT_TLS*/ /* Handle list operations */ case EITEM_FILTER: case EITEM_MAP: case EITEM_REDUCE: { int sep = 0; int save_ptr = ptr; uschar outsep[2] = { '\0', '\0' }; uschar *list, *expr, *temp; uschar *save_iterate_item = iterate_item; uschar *save_lookup_value = lookup_value; while (isspace(*s)) s++; if (*s++ != '{') goto EXPAND_FAILED_CURLY; list = expand_string_internal(s, TRUE, &s, skipping, TRUE, &resetok); if (list == NULL) goto EXPAND_FAILED; if (*s++ != '}') goto EXPAND_FAILED_CURLY; if (item_type == EITEM_REDUCE) { while (isspace(*s)) s++; if (*s++ != '{') goto EXPAND_FAILED_CURLY; temp = expand_string_internal(s, TRUE, &s, skipping, TRUE, &resetok); if (temp == NULL) goto EXPAND_FAILED; lookup_value = temp; if (*s++ != '}') goto EXPAND_FAILED_CURLY; } while (isspace(*s)) s++; if (*s++ != '{') goto EXPAND_FAILED_CURLY; expr = s; /* For EITEM_FILTER, call eval_condition once, with result discarded (as if scanning a "false" part). This allows us to find the end of the condition, because if the list is empty, we won't actually evaluate the condition for real. For EITEM_MAP and EITEM_REDUCE, do the same, using the normal internal expansion function. */ if (item_type == EITEM_FILTER) { temp = eval_condition(expr, &resetok, NULL); if (temp != NULL) s = temp; } else { temp = expand_string_internal(s, TRUE, &s, TRUE, TRUE, &resetok); } if (temp == NULL) { expand_string_message = string_sprintf("%s inside \"%s\" item", expand_string_message, name); goto EXPAND_FAILED; } while (isspace(*s)) s++; if (*s++ != '}') { /*{*/ expand_string_message = string_sprintf("missing } at end of condition " "or expression inside \"%s\"", name); goto EXPAND_FAILED; } while (isspace(*s)) s++; /*{*/ if (*s++ != '}') { /*{*/ expand_string_message = string_sprintf("missing } at end of \"%s\"", name); goto EXPAND_FAILED; } /* If we are skipping, we can now just move on to the next item. When processing for real, we perform the iteration. */ if (skipping) continue; while ((iterate_item = string_nextinlist(&list, &sep, NULL, 0)) != NULL) { *outsep = (uschar)sep; /* Separator as a string */ DEBUG(D_expand) debug_printf("%s: $item = \"%s\"\n", name, iterate_item); if (item_type == EITEM_FILTER) { BOOL condresult; if (eval_condition(expr, &resetok, &condresult) == NULL) { iterate_item = save_iterate_item; lookup_value = save_lookup_value; expand_string_message = string_sprintf("%s inside \"%s\" condition", expand_string_message, name); goto EXPAND_FAILED; } DEBUG(D_expand) debug_printf("%s: condition is %s\n", name, condresult? "true":"false"); if (condresult) temp = iterate_item; /* TRUE => include this item */ else continue; /* FALSE => skip this item */ } /* EITEM_MAP and EITEM_REDUCE */ else { temp = expand_string_internal(expr, TRUE, NULL, skipping, TRUE, &resetok); if (temp == NULL) { iterate_item = save_iterate_item; expand_string_message = string_sprintf("%s inside \"%s\" item", expand_string_message, name); goto EXPAND_FAILED; } if (item_type == EITEM_REDUCE) { lookup_value = temp; /* Update the value of $value */ continue; /* and continue the iteration */ } } /* We reach here for FILTER if the condition is true, always for MAP, and never for REDUCE. The value in "temp" is to be added to the output list that is being created, ensuring that any occurrences of the separator character are doubled. Unless we are dealing with the first item of the output list, add in a space if the new item begins with the separator character, or is an empty string. */ if (ptr != save_ptr && (temp[0] == *outsep || temp[0] == 0)) yield = string_cat(yield, &size, &ptr, US" ", 1); /* Add the string in "temp" to the output list that we are building, This is done in chunks by searching for the separator character. */ for (;;) { size_t seglen = Ustrcspn(temp, outsep); yield = string_cat(yield, &size, &ptr, temp, seglen + 1); /* If we got to the end of the string we output one character too many; backup and end the loop. Otherwise arrange to double the separator. */ if (temp[seglen] == '\0') { ptr--; break; } yield = string_cat(yield, &size, &ptr, outsep, 1); temp += seglen + 1; } /* Output a separator after the string: we will remove the redundant final one at the end. */ yield = string_cat(yield, &size, &ptr, outsep, 1); } /* End of iteration over the list loop */ /* REDUCE has generated no output above: output the final value of $value. */ if (item_type == EITEM_REDUCE) { yield = string_cat(yield, &size, &ptr, lookup_value, Ustrlen(lookup_value)); lookup_value = save_lookup_value; /* Restore $value */ } /* FILTER and MAP generate lists: if they have generated anything, remove the redundant final separator. Even though an empty item at the end of a list does not count, this is tidier. */ else if (ptr != save_ptr) ptr--; /* Restore preserved $item */ iterate_item = save_iterate_item; continue; } /* If ${dlfunc } support is configured, handle calling dynamically-loaded functions, unless locked out at this time. Syntax is ${dlfunc{file}{func}} or ${dlfunc{file}{func}{arg}} or ${dlfunc{file}{func}{arg1}{arg2}} or up to a maximum of EXPAND_DLFUNC_MAX_ARGS arguments (defined below). */ #define EXPAND_DLFUNC_MAX_ARGS 8 case EITEM_DLFUNC: #ifndef EXPAND_DLFUNC expand_string_message = US"\"${dlfunc\" encountered, but this facility " /*}*/ "is not included in this binary"; goto EXPAND_FAILED; #else /* EXPAND_DLFUNC */ { tree_node *t; exim_dlfunc_t *func; uschar *result; int status, argc; uschar *argv[EXPAND_DLFUNC_MAX_ARGS + 3]; if ((expand_forbid & RDO_DLFUNC) != 0) { expand_string_message = US"dynamically-loaded functions are not permitted"; goto EXPAND_FAILED; } switch(read_subs(argv, EXPAND_DLFUNC_MAX_ARGS + 2, 2, &s, skipping, TRUE, US"dlfunc", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* If skipping, we don't actually do anything */ if (skipping) continue; /* Look up the dynamically loaded object handle in the tree. If it isn't found, dlopen() the file and put the handle in the tree for next time. */ t = tree_search(dlobj_anchor, argv[0]); if (t == NULL) { void *handle = dlopen(CS argv[0], RTLD_LAZY); if (handle == NULL) { expand_string_message = string_sprintf("dlopen \"%s\" failed: %s", argv[0], dlerror()); log_write(0, LOG_MAIN|LOG_PANIC, "%s", expand_string_message); goto EXPAND_FAILED; } t = store_get_perm(sizeof(tree_node) + Ustrlen(argv[0])); Ustrcpy(t->name, argv[0]); t->data.ptr = handle; (void)tree_insertnode(&dlobj_anchor, t); } /* Having obtained the dynamically loaded object handle, look up the function pointer. */ func = (exim_dlfunc_t *)dlsym(t->data.ptr, CS argv[1]); if (func == NULL) { expand_string_message = string_sprintf("dlsym \"%s\" in \"%s\" failed: " "%s", argv[1], argv[0], dlerror()); log_write(0, LOG_MAIN|LOG_PANIC, "%s", expand_string_message); goto EXPAND_FAILED; } /* Call the function and work out what to do with the result. If it returns OK, we have a replacement string; if it returns DEFER then expansion has failed in a non-forced manner; if it returns FAIL then failure was forced; if it returns ERROR or any other value there's a problem, so panic slightly. In any case, assume that the function has side-effects on the store that must be preserved. */ resetok = FALSE; result = NULL; for (argc = 0; argv[argc] != NULL; argc++); status = func(&result, argc - 2, &argv[2]); if(status == OK) { if (result == NULL) result = US""; yield = string_cat(yield, &size, &ptr, result, Ustrlen(result)); continue; } else { expand_string_message = result == NULL ? US"(no message)" : result; if(status == FAIL_FORCED) expand_string_forcedfail = TRUE; else if(status != FAIL) log_write(0, LOG_MAIN|LOG_PANIC, "dlfunc{%s}{%s} failed (%d): %s", argv[0], argv[1], status, expand_string_message); goto EXPAND_FAILED; } } #endif /* EXPAND_DLFUNC */ } /* EITEM_* switch */ /* Control reaches here if the name is not recognized as one of the more complicated expansion items. Check for the "operator" syntax (name terminated by a colon). Some of the operators have arguments, separated by _ from the name. */ if (*s == ':') { int c; uschar *arg = NULL; uschar *sub; var_entry *vp = NULL; /* Owing to an historical mis-design, an underscore may be part of the operator name, or it may introduce arguments. We therefore first scan the table of names that contain underscores. If there is no match, we cut off the arguments and then scan the main table. */ if ((c = chop_match(name, op_table_underscore, sizeof(op_table_underscore)/sizeof(uschar *))) < 0) { arg = Ustrchr(name, '_'); if (arg != NULL) *arg = 0; c = chop_match(name, op_table_main, sizeof(op_table_main)/sizeof(uschar *)); if (c >= 0) c += sizeof(op_table_underscore)/sizeof(uschar *); if (arg != NULL) *arg++ = '_'; /* Put back for error messages */ } /* Deal specially with operators that might take a certificate variable as we do not want to do the usual expansion. For most, expand the string.*/ switch(c) { #ifdef SUPPORT_TLS case EOP_MD5: case EOP_SHA1: case EOP_SHA256: if (s[1] == '$') { uschar * s1 = s; sub = expand_string_internal(s+2, TRUE, &s1, skipping, FALSE, &resetok); if (!sub) goto EXPAND_FAILED; /*{*/ if (*s1 != '}') goto EXPAND_FAILED_CURLY; if ((vp = find_var_ent(sub)) && vp->type == vtype_cert) { s = s1+1; break; } vp = NULL; } /*FALLTHROUGH*/ #endif default: sub = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (!sub) goto EXPAND_FAILED; s++; break; } /* If we are skipping, we don't need to perform the operation at all. This matters for operations like "mask", because the data may not be in the correct format when skipping. For example, the expression may test for the existence of $sender_host_address before trying to mask it. For other operations, doing them may not fail, but it is a waste of time. */ if (skipping && c >= 0) continue; /* Otherwise, switch on the operator type */ switch(c) { case EOP_BASE62: { uschar *t; unsigned long int n = Ustrtoul(sub, &t, 10); if (*t != 0) { expand_string_message = string_sprintf("argument for base62 " "operator is \"%s\", which is not a decimal number", sub); goto EXPAND_FAILED; } t = string_base62(n); yield = string_cat(yield, &size, &ptr, t, Ustrlen(t)); continue; } /* Note that for Darwin and Cygwin, BASE_62 actually has the value 36 */ case EOP_BASE62D: { uschar buf[16]; uschar *tt = sub; unsigned long int n = 0; while (*tt != 0) { uschar *t = Ustrchr(base62_chars, *tt++); if (t == NULL) { expand_string_message = string_sprintf("argument for base62d " "operator is \"%s\", which is not a base %d number", sub, BASE_62); goto EXPAND_FAILED; } n = n * BASE_62 + (t - base62_chars); } (void)sprintf(CS buf, "%ld", n); yield = string_cat(yield, &size, &ptr, buf, Ustrlen(buf)); continue; } case EOP_EXPAND: { uschar *expanded = expand_string_internal(sub, FALSE, NULL, skipping, TRUE, &resetok); if (expanded == NULL) { expand_string_message = string_sprintf("internal expansion of \"%s\" failed: %s", sub, expand_string_message); goto EXPAND_FAILED; } yield = string_cat(yield, &size, &ptr, expanded, Ustrlen(expanded)); continue; } case EOP_LC: { int count = 0; uschar *t = sub - 1; while (*(++t) != 0) { *t = tolower(*t); count++; } yield = string_cat(yield, &size, &ptr, sub, count); continue; } case EOP_UC: { int count = 0; uschar *t = sub - 1; while (*(++t) != 0) { *t = toupper(*t); count++; } yield = string_cat(yield, &size, &ptr, sub, count); continue; } case EOP_MD5: #ifdef SUPPORT_TLS if (vp && *(void **)vp->value) { uschar * cp = tls_cert_fprt_md5(*(void **)vp->value); yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp)); } else #endif { md5 base; uschar digest[16]; int j; char st[33]; md5_start(&base); md5_end(&base, sub, Ustrlen(sub), digest); for(j = 0; j < 16; j++) sprintf(st+2*j, "%02x", digest[j]); yield = string_cat(yield, &size, &ptr, US st, (int)strlen(st)); } continue; case EOP_SHA1: #ifdef SUPPORT_TLS if (vp && *(void **)vp->value) { uschar * cp = tls_cert_fprt_sha1(*(void **)vp->value); yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp)); } else #endif { sha1 base; uschar digest[20]; int j; char st[41]; sha1_start(&base); sha1_end(&base, sub, Ustrlen(sub), digest); for(j = 0; j < 20; j++) sprintf(st+2*j, "%02X", digest[j]); yield = string_cat(yield, &size, &ptr, US st, (int)strlen(st)); } continue; case EOP_SHA256: #ifdef SUPPORT_TLS if (vp && *(void **)vp->value) { uschar * cp = tls_cert_fprt_sha256(*(void **)vp->value); yield = string_cat(yield, &size, &ptr, cp, (int)Ustrlen(cp)); } else #endif expand_string_message = US"sha256 only supported for certificates"; continue; /* Convert hex encoding to base64 encoding */ case EOP_HEX2B64: { int c = 0; int b = -1; uschar *in = sub; uschar *out = sub; uschar *enc; for (enc = sub; *enc != 0; enc++) { if (!isxdigit(*enc)) { expand_string_message = string_sprintf("\"%s\" is not a hex " "string", sub); goto EXPAND_FAILED; } c++; } if ((c & 1) != 0) { expand_string_message = string_sprintf("\"%s\" contains an odd " "number of characters", sub); goto EXPAND_FAILED; } while ((c = *in++) != 0) { if (isdigit(c)) c -= '0'; else c = toupper(c) - 'A' + 10; if (b == -1) { b = c << 4; } else { *out++ = b | c; b = -1; } } enc = auth_b64encode(sub, out - sub); yield = string_cat(yield, &size, &ptr, enc, Ustrlen(enc)); continue; } /* Convert octets outside 0x21..0x7E to \xXX form */ case EOP_HEXQUOTE: { uschar *t = sub - 1; while (*(++t) != 0) { if (*t < 0x21 || 0x7E < *t) yield = string_cat(yield, &size, &ptr, string_sprintf("\\x%02x", *t), 4); else yield = string_cat(yield, &size, &ptr, t, 1); } continue; } /* count the number of list elements */ case EOP_LISTCOUNT: { int cnt = 0; int sep = 0; uschar * cp; uschar buffer[256]; while (string_nextinlist(&sub, &sep, buffer, sizeof(buffer)) != NULL) cnt++; cp = string_sprintf("%d", cnt); yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp)); continue; } /* expand a named list given the name */ /* handles nested named lists; requotes as colon-sep list */ case EOP_LISTNAMED: { tree_node *t = NULL; uschar * list; int sep = 0; uschar * item; uschar * suffix = US""; BOOL needsep = FALSE; uschar buffer[256]; if (*sub == '+') sub++; if (arg == NULL) /* no-argument version */ { if (!(t = tree_search(addresslist_anchor, sub)) && !(t = tree_search(domainlist_anchor, sub)) && !(t = tree_search(hostlist_anchor, sub))) t = tree_search(localpartlist_anchor, sub); } else switch(*arg) /* specific list-type version */ { case 'a': t = tree_search(addresslist_anchor, sub); suffix = US"_a"; break; case 'd': t = tree_search(domainlist_anchor, sub); suffix = US"_d"; break; case 'h': t = tree_search(hostlist_anchor, sub); suffix = US"_h"; break; case 'l': t = tree_search(localpartlist_anchor, sub); suffix = US"_l"; break; default: expand_string_message = string_sprintf("bad suffix on \"list\" operator"); goto EXPAND_FAILED; } if(!t) { expand_string_message = string_sprintf("\"%s\" is not a %snamed list", sub, !arg?"" : *arg=='a'?"address " : *arg=='d'?"domain " : *arg=='h'?"host " : *arg=='l'?"localpart " : 0); goto EXPAND_FAILED; } list = ((namedlist_block *)(t->data.ptr))->string; while ((item = string_nextinlist(&list, &sep, buffer, sizeof(buffer))) != NULL) { uschar * buf = US" : "; if (needsep) yield = string_cat(yield, &size, &ptr, buf, 3); else needsep = TRUE; if (*item == '+') /* list item is itself a named list */ { uschar * sub = string_sprintf("${listnamed%s:%s}", suffix, item); item = expand_string_internal(sub, FALSE, NULL, FALSE, TRUE, &resetok); } else if (sep != ':') /* item from non-colon-sep list, re-quote for colon list-separator */ { char * cp; char tok[3]; tok[0] = sep; tok[1] = ':'; tok[2] = 0; while ((cp= strpbrk((const char *)item, tok))) { yield = string_cat(yield, &size, &ptr, item, cp-(char *)item); if (*cp++ == ':') /* colon in a non-colon-sep list item, needs doubling */ { yield = string_cat(yield, &size, &ptr, US"::", 2); item = (uschar *)cp; } else /* sep in item; should already be doubled; emit once */ { yield = string_cat(yield, &size, &ptr, (uschar *)tok, 1); if (*cp == sep) cp++; item = (uschar *)cp; } } } yield = string_cat(yield, &size, &ptr, item, Ustrlen(item)); } continue; } /* mask applies a mask to an IP address; for example the result of ${mask:131.111.10.206/28} is 131.111.10.192/28. */ case EOP_MASK: { int count; uschar *endptr; int binary[4]; int mask, maskoffset; int type = string_is_ip_address(sub, &maskoffset); uschar buffer[64]; if (type == 0) { expand_string_message = string_sprintf("\"%s\" is not an IP address", sub); goto EXPAND_FAILED; } if (maskoffset == 0) { expand_string_message = string_sprintf("missing mask value in \"%s\"", sub); goto EXPAND_FAILED; } mask = Ustrtol(sub + maskoffset + 1, &endptr, 10); if (*endptr != 0 || mask < 0 || mask > ((type == 4)? 32 : 128)) { expand_string_message = string_sprintf("mask value too big in \"%s\"", sub); goto EXPAND_FAILED; } /* Convert the address to binary integer(s) and apply the mask */ sub[maskoffset] = 0; count = host_aton(sub, binary); host_mask(count, binary, mask); /* Convert to masked textual format and add to output. */ yield = string_cat(yield, &size, &ptr, buffer, host_nmtoa(count, binary, mask, buffer, '.')); continue; } case EOP_ADDRESS: case EOP_LOCAL_PART: case EOP_DOMAIN: { uschar *error; int start, end, domain; uschar *t = parse_extract_address(sub, &error, &start, &end, &domain, FALSE); if (t != NULL) { if (c != EOP_DOMAIN) { if (c == EOP_LOCAL_PART && domain != 0) end = start + domain - 1; yield = string_cat(yield, &size, &ptr, sub+start, end-start); } else if (domain != 0) { domain += start; yield = string_cat(yield, &size, &ptr, sub+domain, end-domain); } } continue; } case EOP_ADDRESSES: { uschar outsep[2] = { ':', '\0' }; uschar *address, *error; int save_ptr = ptr; int start, end, domain; /* Not really used */ while (isspace(*sub)) sub++; if (*sub == '>') { *outsep = *++sub; ++sub; } parse_allow_group = TRUE; for (;;) { uschar *p = parse_find_address_end(sub, FALSE); uschar saveend = *p; *p = '\0'; address = parse_extract_address(sub, &error, &start, &end, &domain, FALSE); *p = saveend; /* Add the address to the output list that we are building. This is done in chunks by searching for the separator character. At the start, unless we are dealing with the first address of the output list, add in a space if the new address begins with the separator character, or is an empty string. */ if (address != NULL) { if (ptr != save_ptr && address[0] == *outsep) yield = string_cat(yield, &size, &ptr, US" ", 1); for (;;) { size_t seglen = Ustrcspn(address, outsep); yield = string_cat(yield, &size, &ptr, address, seglen + 1); /* If we got to the end of the string we output one character too many. */ if (address[seglen] == '\0') { ptr--; break; } yield = string_cat(yield, &size, &ptr, outsep, 1); address += seglen + 1; } /* Output a separator after the string: we will remove the redundant final one at the end. */ yield = string_cat(yield, &size, &ptr, outsep, 1); } if (saveend == '\0') break; sub = p + 1; } /* If we have generated anything, remove the redundant final separator. */ if (ptr != save_ptr) ptr--; parse_allow_group = FALSE; continue; } /* quote puts a string in quotes if it is empty or contains anything other than alphamerics, underscore, dot, or hyphen. quote_local_part puts a string in quotes if RFC 2821/2822 requires it to be quoted in order to be a valid local part. In both cases, newlines and carriage returns are converted into \n and \r respectively */ case EOP_QUOTE: case EOP_QUOTE_LOCAL_PART: if (arg == NULL) { BOOL needs_quote = (*sub == 0); /* TRUE for empty string */ uschar *t = sub - 1; if (c == EOP_QUOTE) { while (!needs_quote && *(++t) != 0) needs_quote = !isalnum(*t) && !strchr("_-.", *t); } else /* EOP_QUOTE_LOCAL_PART */ { while (!needs_quote && *(++t) != 0) needs_quote = !isalnum(*t) && strchr("!#$%&'*+-/=?^_`{|}~", *t) == NULL && (*t != '.' || t == sub || t[1] == 0); } if (needs_quote) { yield = string_cat(yield, &size, &ptr, US"\"", 1); t = sub - 1; while (*(++t) != 0) { if (*t == '\n') yield = string_cat(yield, &size, &ptr, US"\\n", 2); else if (*t == '\r') yield = string_cat(yield, &size, &ptr, US"\\r", 2); else { if (*t == '\\' || *t == '"') yield = string_cat(yield, &size, &ptr, US"\\", 1); yield = string_cat(yield, &size, &ptr, t, 1); } } yield = string_cat(yield, &size, &ptr, US"\"", 1); } else yield = string_cat(yield, &size, &ptr, sub, Ustrlen(sub)); continue; } /* quote_lookuptype does lookup-specific quoting */ else { int n; uschar *opt = Ustrchr(arg, '_'); if (opt != NULL) *opt++ = 0; n = search_findtype(arg, Ustrlen(arg)); if (n < 0) { expand_string_message = search_error_message; goto EXPAND_FAILED; } if (lookup_list[n]->quote != NULL) sub = (lookup_list[n]->quote)(sub, opt); else if (opt != NULL) sub = NULL; if (sub == NULL) { expand_string_message = string_sprintf( "\"%s\" unrecognized after \"${quote_%s\"", opt, arg); goto EXPAND_FAILED; } yield = string_cat(yield, &size, &ptr, sub, Ustrlen(sub)); continue; } /* rx quote sticks in \ before any non-alphameric character so that the insertion works in a regular expression. */ case EOP_RXQUOTE: { uschar *t = sub - 1; while (*(++t) != 0) { if (!isalnum(*t)) yield = string_cat(yield, &size, &ptr, US"\\", 1); yield = string_cat(yield, &size, &ptr, t, 1); } continue; } /* RFC 2047 encodes, assuming headers_charset (default ISO 8859-1) as prescribed by the RFC, if there are characters that need to be encoded */ case EOP_RFC2047: { uschar buffer[2048]; uschar *string = parse_quote_2047(sub, Ustrlen(sub), headers_charset, buffer, sizeof(buffer), FALSE); yield = string_cat(yield, &size, &ptr, string, Ustrlen(string)); continue; } /* RFC 2047 decode */ case EOP_RFC2047D: { int len; uschar *error; uschar *decoded = rfc2047_decode(sub, check_rfc2047_length, headers_charset, '?', &len, &error); if (error != NULL) { expand_string_message = error; goto EXPAND_FAILED; } yield = string_cat(yield, &size, &ptr, decoded, len); continue; } /* from_utf8 converts UTF-8 to 8859-1, turning non-existent chars into underscores */ case EOP_FROM_UTF8: { while (*sub != 0) { int c; uschar buff[4]; GETUTF8INC(c, sub); if (c > 255) c = '_'; buff[0] = c; yield = string_cat(yield, &size, &ptr, buff, 1); } continue; } /* replace illegal UTF-8 sequences by replacement character */ #define UTF8_REPLACEMENT_CHAR US"?" case EOP_UTF8CLEAN: { int seq_len, index = 0; int bytes_left = 0; uschar seq_buff[4]; /* accumulate utf-8 here */ while (*sub != 0) { int complete; long codepoint; uschar c; complete = 0; c = *sub++; if (bytes_left) { if ((c & 0xc0) != 0x80) { /* wrong continuation byte; invalidate all bytes */ complete = 1; /* error */ } else { codepoint = (codepoint << 6) | (c & 0x3f); seq_buff[index++] = c; if (--bytes_left == 0) /* codepoint complete */ { if(codepoint > 0x10FFFF) /* is it too large? */ complete = -1; /* error */ else { /* finished; output utf-8 sequence */ yield = string_cat(yield, &size, &ptr, seq_buff, seq_len); index = 0; } } } } else /* no bytes left: new sequence */ { if((c & 0x80) == 0) /* 1-byte sequence, US-ASCII, keep it */ { yield = string_cat(yield, &size, &ptr, &c, 1); continue; } if((c & 0xe0) == 0xc0) /* 2-byte sequence */ { if(c == 0xc0 || c == 0xc1) /* 0xc0 and 0xc1 are illegal */ complete = -1; else { bytes_left = 1; codepoint = c & 0x1f; } } else if((c & 0xf0) == 0xe0) /* 3-byte sequence */ { bytes_left = 2; codepoint = c & 0x0f; } else if((c & 0xf8) == 0xf0) /* 4-byte sequence */ { bytes_left = 3; codepoint = c & 0x07; } else /* invalid or too long (RFC3629 allows only 4 bytes) */ complete = -1; seq_buff[index++] = c; seq_len = bytes_left + 1; } /* if(bytes_left) */ if (complete != 0) { bytes_left = index = 0; yield = string_cat(yield, &size, &ptr, UTF8_REPLACEMENT_CHAR, 1); } if ((complete == 1) && ((c & 0x80) == 0)) { /* ASCII character follows incomplete sequence */ yield = string_cat(yield, &size, &ptr, &c, 1); } } continue; } /* escape turns all non-printing characters into escape sequences. */ case EOP_ESCAPE: { uschar *t = string_printing(sub); yield = string_cat(yield, &size, &ptr, t, Ustrlen(t)); continue; } /* Handle numeric expression evaluation */ case EOP_EVAL: case EOP_EVAL10: { uschar *save_sub = sub; uschar *error = NULL; int_eximarith_t n = eval_expr(&sub, (c == EOP_EVAL10), &error, FALSE); if (error != NULL) { expand_string_message = string_sprintf("error in expression " "evaluation: %s (after processing \"%.*s\")", error, sub-save_sub, save_sub); goto EXPAND_FAILED; } sprintf(CS var_buffer, PR_EXIM_ARITH, n); yield = string_cat(yield, &size, &ptr, var_buffer, Ustrlen(var_buffer)); continue; } /* Handle time period formating */ case EOP_TIME_EVAL: { int n = readconf_readtime(sub, 0, FALSE); if (n < 0) { expand_string_message = string_sprintf("string \"%s\" is not an " "Exim time interval in \"%s\" operator", sub, name); goto EXPAND_FAILED; } sprintf(CS var_buffer, "%d", n); yield = string_cat(yield, &size, &ptr, var_buffer, Ustrlen(var_buffer)); continue; } case EOP_TIME_INTERVAL: { int n; uschar *t = read_number(&n, sub); if (*t != 0) /* Not A Number*/ { expand_string_message = string_sprintf("string \"%s\" is not a " "positive number in \"%s\" operator", sub, name); goto EXPAND_FAILED; } t = readconf_printtime(n); yield = string_cat(yield, &size, &ptr, t, Ustrlen(t)); continue; } /* Convert string to base64 encoding */ case EOP_STR2B64: { uschar *encstr = auth_b64encode(sub, Ustrlen(sub)); yield = string_cat(yield, &size, &ptr, encstr, Ustrlen(encstr)); continue; } /* strlen returns the length of the string */ case EOP_STRLEN: { uschar buff[24]; (void)sprintf(CS buff, "%d", Ustrlen(sub)); yield = string_cat(yield, &size, &ptr, buff, Ustrlen(buff)); continue; } /* length_n or l_n takes just the first n characters or the whole string, whichever is the shorter; substr_m_n, and s_m_n take n characters from offset m; negative m take from the end; l_n is synonymous with s_0_n. If n is omitted in substr it takes the rest, either to the right or to the left. hash_n or h_n makes a hash of length n from the string, yielding n characters from the set a-z; hash_n_m makes a hash of length n, but uses m characters from the set a-zA-Z0-9. nhash_n returns a single number between 0 and n-1 (in text form), while nhash_n_m returns a div/mod hash as two numbers "a/b". The first lies between 0 and n-1 and the second between 0 and m-1. */ case EOP_LENGTH: case EOP_L: case EOP_SUBSTR: case EOP_S: case EOP_HASH: case EOP_H: case EOP_NHASH: case EOP_NH: { int sign = 1; int value1 = 0; int value2 = -1; int *pn; int len; uschar *ret; if (arg == NULL) { expand_string_message = string_sprintf("missing values after %s", name); goto EXPAND_FAILED; } /* "length" has only one argument, effectively being synonymous with substr_0_n. */ if (c == EOP_LENGTH || c == EOP_L) { pn = &value2; value2 = 0; } /* The others have one or two arguments; for "substr" the first may be negative. The second being negative means "not supplied". */ else { pn = &value1; if (name[0] == 's' && *arg == '-') { sign = -1; arg++; } } /* Read up to two numbers, separated by underscores */ ret = arg; while (*arg != 0) { if (arg != ret && *arg == '_' && pn == &value1) { pn = &value2; value2 = 0; if (arg[1] != 0) arg++; } else if (!isdigit(*arg)) { expand_string_message = string_sprintf("non-digit after underscore in \"%s\"", name); goto EXPAND_FAILED; } else *pn = (*pn)*10 + *arg++ - '0'; } value1 *= sign; /* Perform the required operation */ ret = (c == EOP_HASH || c == EOP_H)? compute_hash(sub, value1, value2, &len) : (c == EOP_NHASH || c == EOP_NH)? compute_nhash(sub, value1, value2, &len) : extract_substr(sub, value1, value2, &len); if (ret == NULL) goto EXPAND_FAILED; yield = string_cat(yield, &size, &ptr, ret, len); continue; } /* Stat a path */ case EOP_STAT: { uschar *s; uschar smode[12]; uschar **modetable[3]; int i; mode_t mode; struct stat st; if ((expand_forbid & RDO_EXISTS) != 0) { expand_string_message = US"Use of the stat() expansion is not permitted"; goto EXPAND_FAILED; } if (stat(CS sub, &st) < 0) { expand_string_message = string_sprintf("stat(%s) failed: %s", sub, strerror(errno)); goto EXPAND_FAILED; } mode = st.st_mode; switch (mode & S_IFMT) { case S_IFIFO: smode[0] = 'p'; break; case S_IFCHR: smode[0] = 'c'; break; case S_IFDIR: smode[0] = 'd'; break; case S_IFBLK: smode[0] = 'b'; break; case S_IFREG: smode[0] = '-'; break; default: smode[0] = '?'; break; } modetable[0] = ((mode & 01000) == 0)? mtable_normal : mtable_sticky; modetable[1] = ((mode & 02000) == 0)? mtable_normal : mtable_setid; modetable[2] = ((mode & 04000) == 0)? mtable_normal : mtable_setid; for (i = 0; i < 3; i++) { memcpy(CS(smode + 7 - i*3), CS(modetable[i][mode & 7]), 3); mode >>= 3; } smode[10] = 0; s = string_sprintf("mode=%04lo smode=%s inode=%ld device=%ld links=%ld " "uid=%ld gid=%ld size=" OFF_T_FMT " atime=%ld mtime=%ld ctime=%ld", (long)(st.st_mode & 077777), smode, (long)st.st_ino, (long)st.st_dev, (long)st.st_nlink, (long)st.st_uid, (long)st.st_gid, st.st_size, (long)st.st_atime, (long)st.st_mtime, (long)st.st_ctime); yield = string_cat(yield, &size, &ptr, s, Ustrlen(s)); continue; } /* vaguely random number less than N */ case EOP_RANDINT: { int_eximarith_t max; uschar *s; max = expanded_string_integer(sub, TRUE); if (expand_string_message != NULL) goto EXPAND_FAILED; s = string_sprintf("%d", vaguely_random_number((int)max)); yield = string_cat(yield, &size, &ptr, s, Ustrlen(s)); continue; } /* Reverse IP, including IPv6 to dotted-nibble */ case EOP_REVERSE_IP: { int family, maskptr; uschar reversed[128]; family = string_is_ip_address(sub, &maskptr); if (family == 0) { expand_string_message = string_sprintf( "reverse_ip() not given an IP address [%s]", sub); goto EXPAND_FAILED; } invert_address(reversed, sub); yield = string_cat(yield, &size, &ptr, reversed, Ustrlen(reversed)); continue; } /* Unknown operator */ default: expand_string_message = string_sprintf("unknown expansion operator \"%s\"", name); goto EXPAND_FAILED; } } /* Handle a plain name. If this is the first thing in the expansion, release the pre-allocated buffer. If the result data is known to be in a new buffer, newsize will be set to the size of that buffer, and we can just point at that store instead of copying. Many expansion strings contain just one reference, so this is a useful optimization, especially for humungous headers ($message_headers). */ /*{*/ if (*s++ == '}') { int len; int newsize = 0; if (ptr == 0) { if (resetok) store_reset(yield); yield = NULL; size = 0; } value = find_variable(name, FALSE, skipping, &newsize); if (value == NULL) { expand_string_message = string_sprintf("unknown variable in \"${%s}\"", name); check_variable_error_message(name); goto EXPAND_FAILED; } len = Ustrlen(value); if (yield == NULL && newsize != 0) { yield = value; size = newsize; ptr = len; } else yield = string_cat(yield, &size, &ptr, value, len); continue; } /* Else there's something wrong */ expand_string_message = string_sprintf("\"${%s\" is not a known operator (or a } is missing " "in a variable reference)", name); goto EXPAND_FAILED; } /* If we hit the end of the string when ket_ends is set, there is a missing terminating brace. */ if (ket_ends && *s == 0) { expand_string_message = malformed_header? US"missing } at end of string - could be header name not terminated by colon" : US"missing } at end of string"; goto EXPAND_FAILED; } /* Expansion succeeded; yield may still be NULL here if nothing was actually added to the string. If so, set up an empty string. Add a terminating zero. If left != NULL, return a pointer to the terminator. */ if (yield == NULL) yield = store_get(1); yield[ptr] = 0; if (left != NULL) *left = s; /* Any stacking store that was used above the final string is no longer needed. In many cases the final string will be the first one that was got and so there will be optimal store usage. */ if (resetok) store_reset(yield + ptr + 1); else if (resetok_p) *resetok_p = FALSE; DEBUG(D_expand) { debug_printf("expanding: %.*s\n result: %s\n", (int)(s - string), string, yield); if (skipping) debug_printf("skipping: result is not used\n"); } return yield; /* This is the failure exit: easiest to program with a goto. We still need to update the pointer to the terminator, for cases of nested calls with "fail". */ EXPAND_FAILED_CURLY: expand_string_message = malformed_header? US"missing or misplaced { or } - could be header name not terminated by colon" : US"missing or misplaced { or }"; /* At one point, Exim reset the store to yield (if yield was not NULL), but that is a bad idea, because expand_string_message is in dynamic store. */ EXPAND_FAILED: if (left != NULL) *left = s; DEBUG(D_expand) { debug_printf("failed to expand: %s\n", string); debug_printf(" error message: %s\n", expand_string_message); if (expand_string_forcedfail) debug_printf("failure was forced\n"); } if (resetok_p) *resetok_p = resetok; return NULL; }
165,192
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { #define CFormat "/Filter [ /%s ]\n" #define ObjectsPerImage 14 #define ThrowPDFException(exception,message) \ { \ if (xref != (MagickOffsetType *) NULL) \ xref=(MagickOffsetType *) RelinquishMagickMemory(xref); \ ThrowWriterException((exception),(message)); \ } DisableMSCWarning(4310) static const char XMPProfile[]= { "<?xpacket begin=\"%s\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n" "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"Adobe XMP Core 4.0-c316 44.253921, Sun Oct 01 2006 17:08:23\">\n" " <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:xap=\"http://ns.adobe.com/xap/1.0/\">\n" " <xap:ModifyDate>%s</xap:ModifyDate>\n" " <xap:CreateDate>%s</xap:CreateDate>\n" " <xap:MetadataDate>%s</xap:MetadataDate>\n" " <xap:CreatorTool>%s</xap:CreatorTool>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n" " <dc:format>application/pdf</dc:format>\n" " <dc:title>\n" " <rdf:Alt>\n" " <rdf:li xml:lang=\"x-default\">%s</rdf:li>\n" " </rdf:Alt>\n" " </dc:title>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:xapMM=\"http://ns.adobe.com/xap/1.0/mm/\">\n" " <xapMM:DocumentID>uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf</xapMM:DocumentID>\n" " <xapMM:InstanceID>uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb</xapMM:InstanceID>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\">\n" " <pdf:Producer>%s</pdf:Producer>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\">\n" " <pdfaid:part>3</pdfaid:part>\n" " <pdfaid:conformance>B</pdfaid:conformance>\n" " </rdf:Description>\n" " </rdf:RDF>\n" "</x:xmpmeta>\n" "<?xpacket end=\"w\"?>\n" }, XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 }; RestoreMSCWarning char basename[MagickPathExtent], buffer[MagickPathExtent], *escape, date[MagickPathExtent], **labels, page_geometry[MagickPathExtent], *url; CompressionType compression; const char *device, *option, *value; const StringInfo *profile; double pointsize; GeometryInfo geometry_info; Image *next, *tile_image; MagickBooleanType status; MagickOffsetType offset, scene, *xref; MagickSizeType number_pixels; MagickStatusType flags; PointInfo delta, resolution, scale; RectangleInfo geometry, media_info, page_info; register const Quantum *p; register unsigned char *q; register ssize_t i, x; size_t channels, imageListLength, info_id, length, object, pages_id, root_id, text_size, version; ssize_t count, page_count, y; struct tm local_time; time_t seconds; unsigned char *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); /* Allocate X ref memory. */ xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(xref,0,2048UL*sizeof(*xref)); /* Write Info object. */ object=0; version=3; if (image_info->compression == JPEG2000Compression) version=(size_t) MagickMax(version,5); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) if (next->alpha_trait != UndefinedPixelTrait) version=(size_t) MagickMax(version,4); if (LocaleCompare(image_info->magick,"PDFA") == 0) version=(size_t) MagickMax(version,6); profile=GetImageProfile(image,"icc"); if (profile != (StringInfo *) NULL) version=(size_t) MagickMax(version,7); (void) FormatLocaleString(buffer,MagickPathExtent,"%%PDF-1.%.20g \n",(double) version); (void) WriteBlobString(image,buffer); if (LocaleCompare(image_info->magick,"PDFA") == 0) { (void) WriteBlobByte(image,'%'); (void) WriteBlobByte(image,0xe2); (void) WriteBlobByte(image,0xe3); (void) WriteBlobByte(image,0xcf); (void) WriteBlobByte(image,0xd3); (void) WriteBlobByte(image,'\n'); } /* Write Catalog object. */ xref[object++]=TellBlob(image); root_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (LocaleCompare(image_info->magick,"PDFA") != 0) (void) FormatLocaleString(buffer,MagickPathExtent,"/Pages %.20g 0 R\n", (double) object+1); else { (void) FormatLocaleString(buffer,MagickPathExtent,"/Metadata %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Pages %.20g 0 R\n", (double) object+2); } (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/Type /Catalog"); option=GetImageOption(image_info,"pdf:page-direction"); if ((option != (const char *) NULL) && (LocaleCompare(option,"right-to-left") == 0)) (void) WriteBlobString(image,"/ViewerPreferences<</PageDirection/R2L>>\n"); (void) WriteBlobString(image,"\n"); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); GetPathComponent(image->filename,BasePath,basename); if (LocaleCompare(image_info->magick,"PDFA") == 0) { char create_date[MagickPathExtent], modify_date[MagickPathExtent], timestamp[MagickPathExtent], *url, xmp_profile[MagickPathExtent]; /* Write XMP object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Subtype /XML\n"); *modify_date='\0'; value=GetImageProperty(image,"date:modify",exception); if (value != (const char *) NULL) (void) CopyMagickString(modify_date,value,MagickPathExtent); *create_date='\0'; value=GetImageProperty(image,"date:create",exception); if (value != (const char *) NULL) (void) CopyMagickString(create_date,value,MagickPathExtent); (void) FormatMagickTime(time((time_t *) NULL),MagickPathExtent,timestamp); url=(char *) MagickAuthoritativeURL; escape=EscapeParenthesis(basename); i=FormatLocaleString(xmp_profile,MagickPathExtent,XMPProfile, XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url); escape=DestroyString(escape); (void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g\n", (double) i); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/Type /Metadata\n"); (void) WriteBlobString(image,">>\nstream\n"); (void) WriteBlobString(image,xmp_profile); (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); } /* Write Pages object. */ xref[object++]=TellBlob(image); pages_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Type /Pages\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Kids [ %.20g 0 R ", (double) object+1); (void) WriteBlobString(image,buffer); count=(ssize_t) (pages_id+ObjectsPerImage+1); page_count=1; if (image_info->adjoin != MagickFalse) { Image *kid_image; /* Predict page object id's. */ kid_image=image; for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage) { page_count++; profile=GetImageProfile(kid_image,"icc"); if (profile != (StringInfo *) NULL) count+=2; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 R ",(double) count); (void) WriteBlobString(image,buffer); kid_image=GetNextImageInList(kid_image); } xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL, sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } (void) WriteBlobString(image,"]\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Count %.20g\n",(double) page_count); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); scene=0; imageListLength=GetImageListLength(image); do { MagickBooleanType has_icc_profile; profile=GetImageProfile(image,"icc"); has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse; compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { if ((SetImageMonochrome(image,exception) == MagickFalse) || (image->alpha_trait != UndefinedPixelTrait)) compression=RLECompression; break; } #if !defined(MAGICKCORE_JPEG_DELEGATE) case JPEGCompression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JPEG)", image->filename); break; } #endif #if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE) case JPEG2000Compression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JP2)", image->filename); break; } #endif #if !defined(MAGICKCORE_ZLIB_DELEGATE) case ZipCompression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (ZLIB)", image->filename); break; } #endif case LZWCompression: { if (LocaleCompare(image_info->magick,"PDFA") == 0) compression=RLECompression; /* LZW compression is forbidden */ break; } case NoCompression: { if (LocaleCompare(image_info->magick,"PDFA") == 0) compression=RLECompression; /* ASCII 85 compression is forbidden */ break; } default: break; } if (compression == JPEG2000Compression) (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Scale relative to dots-per-inch. */ delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->resolution.x; resolution.y=image->resolution.y; if ((resolution.x == 0.0) || (resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image->units == PixelsPerCentimeterResolution) { resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0); resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0); } SetGeometry(image,&geometry); (void) FormatLocaleString(page_geometry,MagickPathExtent,"%.20gx%.20g", (double) image->columns,(double) image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatLocaleString(page_geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); else if ((image->gravity != UndefinedGravity) && (LocaleCompare(image_info->magick,"PDF") == 0)) (void) CopyMagickString(page_geometry,PSPageGeometry, MagickPathExtent); (void) ConcatenateMagickString(page_geometry,">",MagickPathExtent); (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); scale.x=(double) (geometry.width*delta.x)/resolution.x; geometry.width=(size_t) floor(scale.x+0.5); scale.y=(double) (geometry.height*delta.y)/resolution.y; geometry.height=(size_t) floor(scale.y+0.5); (void) ParseAbsoluteGeometry(page_geometry,&media_info); (void) ParseGravityGeometry(image,page_geometry,&page_info,exception); if (image->gravity != UndefinedGravity) { geometry.x=(-page_info.x); geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows); } pointsize=12.0; if (image_info->pointsize != 0.0) pointsize=image_info->pointsize; text_size=0; value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) text_size=(size_t) (MultilineCensus(value)*pointsize+12); (void) text_size; /* Write Page object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Type /Page\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Parent %.20g 0 R\n", (double) pages_id); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/Resources <<\n"); labels=(char **) NULL; value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { (void) FormatLocaleString(buffer,MagickPathExtent, "/Font << /F%.20g %.20g 0 R >>\n",(double) image->scene,(double) object+4); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MagickPathExtent, "/XObject << /Im%.20g %.20g 0 R >>\n",(double) image->scene,(double) object+5); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/ProcSet %.20g 0 R >>\n", (double) object+3); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "/MediaBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x, 72.0*media_info.height/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "/CropBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x, 72.0*media_info.height/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Contents %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Thumb %.20g 0 R\n", (double) object+(has_icc_profile != MagickFalse ? 10 : 8)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Contents object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); (void) WriteBlobString(image,"q\n"); if (labels != (char **) NULL) for (i=0; labels[i] != (char *) NULL; i++) { (void) WriteBlobString(image,"BT\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/F%.20g %g Tf\n", (double) image->scene,pointsize); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g Td\n", (double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+ 12)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"(%s) Tj\n", labels[i]); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"ET\n"); labels[i]=DestroyString(labels[i]); } (void) FormatLocaleString(buffer,MagickPathExtent, "%g 0 0 %g %.20g %.20g cm\n",scale.x,scale.y,(double) geometry.x, (double) geometry.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Im%.20g Do\n",(double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"Q\n"); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write Procset object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) CopyMagickString(buffer,"[ /PDF /Text /ImageC",MagickPathExtent); else if ((compression == FaxCompression) || (compression == Group4Compression)) (void) CopyMagickString(buffer,"[ /PDF /Text /ImageB",MagickPathExtent); else (void) CopyMagickString(buffer,"[ /PDF /Text /ImageI",MagickPathExtent); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image," ]\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Font object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (labels != (char **) NULL) { (void) WriteBlobString(image,"/Type /Font\n"); (void) WriteBlobString(image,"/Subtype /Type1\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Name /F%.20g\n", (double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/BaseFont /Helvetica\n"); (void) WriteBlobString(image,"/Encoding /MacRomanEncoding\n"); labels=(char **) RelinquishMagickMemory(labels); } (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); /* Write XObject object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Type /XObject\n"); (void) WriteBlobString(image,"/Subtype /Image\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Name /Im%.20g\n", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "ASCII85Decode"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"DCTDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MagickPathExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"JPXDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MagickPathExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "FlateDecode"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/DecodeParms [ << " "/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam, (double) image->columns,(double) image->rows); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Width %.20g\n",(double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Height %.20g\n",(double) image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/ColorSpace %.20g 0 R\n", (double) object+2); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/BitsPerComponent %d\n", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); if (image->alpha_trait != UndefinedPixelTrait) { (void) FormatLocaleString(buffer,MagickPathExtent,"/SMask %.20g 0 R\n", (double) object+(has_icc_profile != MagickFalse ? 9 : 7)); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels))) ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,"0") == 0) { (void) HuffmanEncodeImage(image_info,image,image,exception); break; } (void) Huffman2DEncodeImage(image_info,image,image,exception); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,image,"jpeg",exception); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,"jp2",exception); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(image,p))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p)))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,image,"jpeg",exception); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,"jp2",exception); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; length*=image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runoffset encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); if (image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelBlack(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed DirectColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(GetPixelRed(image,p))); Ascii85Encode(image,ScaleQuantumToChar(GetPixelGreen(image,p))); Ascii85Encode(image,ScaleQuantumToChar(GetPixelBlue(image,p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlack(image,p))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } else { /* Dump number of colors and colormap. */ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); ThrowPDFException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,(unsigned char) GetPixelIndex(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write Colorspace object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); device="DeviceRGB"; channels=0; if (image->colorspace == CMYKColorspace) { device="DeviceCMYK"; channels=4; } else if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse))) { device="DeviceGray"; channels=1; } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) { device="DeviceRGB"; channels=3; } profile=GetImageProfile(image,"icc"); if ((profile == (StringInfo *) NULL) || (channels == 0)) { if (channels != 0) (void) FormatLocaleString(buffer,MagickPathExtent,"/%s\n",device); else (void) FormatLocaleString(buffer,MagickPathExtent, "[ /Indexed /%s %.20g %.20g 0 R ]\n",device,(double) image->colors- 1,(double) object+3); (void) WriteBlobString(image,buffer); } else { const unsigned char *p; /* Write ICC profile. */ (void) FormatLocaleString(buffer,MagickPathExtent, "[/ICCBased %.20g 0 R]\n",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"<<\n/N %.20g\n" "/Filter /ASCII85Decode\n/Length %.20g 0 R\n/Alternate /%s\n>>\n" "stream\n",(double) channels,(double) object+1,device); (void) WriteBlobString(image,buffer); offset=TellBlob(image); Ascii85Initialize(image); p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) Ascii85Encode(image,(unsigned char) *p++); Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"endstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"endobj\n"); /* Write Thumb object. */ SetGeometry(image,&geometry); (void) ParseMetaGeometry("106x106+0+0>",&geometry.x,&geometry.y, &geometry.width,&geometry.height); tile_image=ThumbnailImage(image,geometry.width,geometry.height,exception); if (tile_image == (Image *) NULL) return(MagickFalse); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "ASCII85Decode"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"DCTDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MagickPathExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"JPXDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MagickPathExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "FlateDecode"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/DecodeParms [ << " "/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam, (double) tile_image->columns,(double) tile_image->rows); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Width %.20g\n",(double) tile_image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Height %.20g\n",(double) tile_image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/ColorSpace %.20g 0 R\n", (double) object-(has_icc_profile != MagickFalse ? 3 : 1)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/BitsPerComponent %d\n", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows; if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(tile_image,exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,"0") == 0) { (void) HuffmanEncodeImage(image_info,image,tile_image, exception); break; } (void) Huffman2DEncodeImage(image_info,image,tile_image,exception); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,"jpeg", exception); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,"jp2",exception); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma( tile_image,p))); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(tile_image,p)))); p+=GetPixelChannels(tile_image); } } Ascii85Flush(image); break; } } } else if ((tile_image->storage_class == DirectClass) || (tile_image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,"jpeg", exception); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,"jp2",exception); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(tile_image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(tile_image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(tile_image,p)); if (tile_image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelBlack(tile_image,p)); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed DirectColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(tile_image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(tile_image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(tile_image,p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlack(tile_image,p))); p+=GetPixelChannels(tile_image); } } Ascii85Flush(image); break; } } else { /* Dump number of colors and colormap. */ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=(unsigned char) GetPixelIndex(tile_image,p); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,(unsigned char) GetPixelIndex(tile_image,p)); p+=GetPixelChannels(image); } } Ascii85Flush(image); break; } } } tile_image=DestroyImage(tile_image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == FaxCompression) || (compression == Group4Compression)) (void) WriteBlobString(image,">>\n"); else { /* Write Colormap object. */ if (compression == NoCompression) (void) WriteBlobString(image,"/Filter [ /ASCII85Decode ]\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); if (compression == NoCompression) Ascii85Initialize(image); for (i=0; i < (ssize_t) image->colors; i++) { if (compression == NoCompression) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].red))); Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].green))); Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].blue))); continue; } (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].red))); (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].green))); (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].blue))); } if (compression == NoCompression) Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); } (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write softmask object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (image->alpha_trait == UndefinedPixelTrait) (void) WriteBlobString(image,">>\n"); else { (void) WriteBlobString(image,"/Type /XObject\n"); (void) WriteBlobString(image,"/Subtype /Image\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Name /Ma%.20g\n", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "ASCII85Decode"); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "FlateDecode"); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Width %.20g\n", (double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Height %.20g\n", (double) image->rows); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/ColorSpace /DeviceGray\n"); (void) FormatLocaleString(buffer,MagickPathExtent, "/BitsPerComponent %d\n",(compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { image=DestroyImage(image); ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(GetPixelAlpha(image,p))); p+=GetPixelChannels(image); } } Ascii85Flush(image); break; } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); } (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); /* Write Metadata object. */ xref[object++]=TellBlob(image); info_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (LocaleCompare(image_info->magick,"PDFA") == 0) (void) FormatLocaleString(buffer,MagickPathExtent,"/Title (%s)\n", EscapeParenthesis(basename)); else { wchar_t *utf16; utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length); if (utf16 != (wchar_t *) NULL) { (void) FormatLocaleString(buffer,MagickPathExtent,"/Title (\xfe\xff"); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) length; i++) (void) WriteBlobMSBShort(image,(unsigned short) utf16[i]); (void) FormatLocaleString(buffer,MagickPathExtent,")\n"); utf16=(wchar_t *) RelinquishMagickMemory(utf16); } } (void) WriteBlobString(image,buffer); seconds=time((time_t *) NULL); #if defined(MAGICKCORE_HAVE_LOCALTIME_R) (void) localtime_r(&seconds,&local_time); #else (void) memcpy(&local_time,localtime(&seconds),sizeof(local_time)); #endif (void) FormatLocaleString(date,MagickPathExtent,"D:%04d%02d%02d%02d%02d%02d", local_time.tm_year+1900,local_time.tm_mon+1,local_time.tm_mday, local_time.tm_hour,local_time.tm_min,local_time.tm_sec); (void) FormatLocaleString(buffer,MagickPathExtent,"/CreationDate (%s)\n", date); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/ModDate (%s)\n",date); (void) WriteBlobString(image,buffer); url=(char *) MagickAuthoritativeURL; escape=EscapeParenthesis(url); (void) FormatLocaleString(buffer,MagickPathExtent,"/Producer (%s)\n",escape); escape=DestroyString(escape); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Xref object. */ offset=TellBlob(image)-xref[0]+ (LocaleCompare(image_info->magick,"PDFA") == 0 ? 6 : 0)+10; (void) WriteBlobString(image,"xref\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"0 %.20g\n",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"0000000000 65535 f \n"); for (i=0; i < (ssize_t) object; i++) { (void) FormatLocaleString(buffer,MagickPathExtent,"%010lu 00000 n \n", (unsigned long) xref[i]); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"trailer\n"); (void) WriteBlobString(image,"<<\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Size %.20g\n",(double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Info %.20g 0 R\n",(double) info_id); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Root %.20g 0 R\n",(double) root_id); (void) WriteBlobString(image,buffer); (void) SignatureImage(image,exception); (void) FormatLocaleString(buffer,MagickPathExtent,"/ID [<%s> <%s>]\n", GetImageProperty(image,"signature",exception), GetImageProperty(image,"signature",exception)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"startxref\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"%%EOF\n"); xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickTrue); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1454 CWE ID: CWE-399
static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { #define CFormat "/Filter [ /%s ]\n" #define ObjectsPerImage 14 #define ThrowPDFException(exception,message) \ { \ if (xref != (MagickOffsetType *) NULL) \ xref=(MagickOffsetType *) RelinquishMagickMemory(xref); \ ThrowWriterException((exception),(message)); \ } DisableMSCWarning(4310) static const char XMPProfile[]= { "<?xpacket begin=\"%s\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n" "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"Adobe XMP Core 4.0-c316 44.253921, Sun Oct 01 2006 17:08:23\">\n" " <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:xap=\"http://ns.adobe.com/xap/1.0/\">\n" " <xap:ModifyDate>%s</xap:ModifyDate>\n" " <xap:CreateDate>%s</xap:CreateDate>\n" " <xap:MetadataDate>%s</xap:MetadataDate>\n" " <xap:CreatorTool>%s</xap:CreatorTool>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n" " <dc:format>application/pdf</dc:format>\n" " <dc:title>\n" " <rdf:Alt>\n" " <rdf:li xml:lang=\"x-default\">%s</rdf:li>\n" " </rdf:Alt>\n" " </dc:title>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:xapMM=\"http://ns.adobe.com/xap/1.0/mm/\">\n" " <xapMM:DocumentID>uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf</xapMM:DocumentID>\n" " <xapMM:InstanceID>uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb</xapMM:InstanceID>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\">\n" " <pdf:Producer>%s</pdf:Producer>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\">\n" " <pdfaid:part>3</pdfaid:part>\n" " <pdfaid:conformance>B</pdfaid:conformance>\n" " </rdf:Description>\n" " </rdf:RDF>\n" "</x:xmpmeta>\n" "<?xpacket end=\"w\"?>\n" }, XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 }; RestoreMSCWarning char basename[MagickPathExtent], buffer[MagickPathExtent], *escape, date[MagickPathExtent], **labels, page_geometry[MagickPathExtent], *url; CompressionType compression; const char *device, *option, *value; const StringInfo *profile; double pointsize; GeometryInfo geometry_info; Image *next, *tile_image; MagickBooleanType status; MagickOffsetType offset, scene, *xref; MagickSizeType number_pixels; MagickStatusType flags; PointInfo delta, resolution, scale; RectangleInfo geometry, media_info, page_info; register const Quantum *p; register unsigned char *q; register ssize_t i, x; size_t channels, imageListLength, info_id, length, object, pages_id, root_id, text_size, version; ssize_t count, page_count, y; struct tm local_time; time_t seconds; unsigned char *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); /* Allocate X ref memory. */ xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(xref,0,2048UL*sizeof(*xref)); /* Write Info object. */ object=0; version=3; if (image_info->compression == JPEG2000Compression) version=(size_t) MagickMax(version,5); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) if (next->alpha_trait != UndefinedPixelTrait) version=(size_t) MagickMax(version,4); if (LocaleCompare(image_info->magick,"PDFA") == 0) version=(size_t) MagickMax(version,6); profile=GetImageProfile(image,"icc"); if (profile != (StringInfo *) NULL) version=(size_t) MagickMax(version,7); (void) FormatLocaleString(buffer,MagickPathExtent,"%%PDF-1.%.20g \n",(double) version); (void) WriteBlobString(image,buffer); if (LocaleCompare(image_info->magick,"PDFA") == 0) { (void) WriteBlobByte(image,'%'); (void) WriteBlobByte(image,0xe2); (void) WriteBlobByte(image,0xe3); (void) WriteBlobByte(image,0xcf); (void) WriteBlobByte(image,0xd3); (void) WriteBlobByte(image,'\n'); } /* Write Catalog object. */ xref[object++]=TellBlob(image); root_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (LocaleCompare(image_info->magick,"PDFA") != 0) (void) FormatLocaleString(buffer,MagickPathExtent,"/Pages %.20g 0 R\n", (double) object+1); else { (void) FormatLocaleString(buffer,MagickPathExtent,"/Metadata %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Pages %.20g 0 R\n", (double) object+2); } (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/Type /Catalog"); option=GetImageOption(image_info,"pdf:page-direction"); if ((option != (const char *) NULL) && (LocaleCompare(option,"right-to-left") == 0)) (void) WriteBlobString(image,"/ViewerPreferences<</PageDirection/R2L>>\n"); (void) WriteBlobString(image,"\n"); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); GetPathComponent(image->filename,BasePath,basename); if (LocaleCompare(image_info->magick,"PDFA") == 0) { char create_date[MagickPathExtent], modify_date[MagickPathExtent], timestamp[MagickPathExtent], *url, xmp_profile[MagickPathExtent]; /* Write XMP object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Subtype /XML\n"); *modify_date='\0'; value=GetImageProperty(image,"date:modify",exception); if (value != (const char *) NULL) (void) CopyMagickString(modify_date,value,MagickPathExtent); *create_date='\0'; value=GetImageProperty(image,"date:create",exception); if (value != (const char *) NULL) (void) CopyMagickString(create_date,value,MagickPathExtent); (void) FormatMagickTime(time((time_t *) NULL),MagickPathExtent,timestamp); url=(char *) MagickAuthoritativeURL; escape=EscapeParenthesis(basename); i=FormatLocaleString(xmp_profile,MagickPathExtent,XMPProfile, XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url); escape=DestroyString(escape); (void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g\n", (double) i); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/Type /Metadata\n"); (void) WriteBlobString(image,">>\nstream\n"); (void) WriteBlobString(image,xmp_profile); (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); } /* Write Pages object. */ xref[object++]=TellBlob(image); pages_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Type /Pages\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Kids [ %.20g 0 R ", (double) object+1); (void) WriteBlobString(image,buffer); count=(ssize_t) (pages_id+ObjectsPerImage+1); page_count=1; if (image_info->adjoin != MagickFalse) { Image *kid_image; /* Predict page object id's. */ kid_image=image; for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage) { page_count++; profile=GetImageProfile(kid_image,"icc"); if (profile != (StringInfo *) NULL) count+=2; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 R ",(double) count); (void) WriteBlobString(image,buffer); kid_image=GetNextImageInList(kid_image); } xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL, sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } (void) WriteBlobString(image,"]\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Count %.20g\n",(double) page_count); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); scene=0; imageListLength=GetImageListLength(image); do { MagickBooleanType has_icc_profile; profile=GetImageProfile(image,"icc"); has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse; compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { if ((SetImageMonochrome(image,exception) == MagickFalse) || (image->alpha_trait != UndefinedPixelTrait)) compression=RLECompression; break; } #if !defined(MAGICKCORE_JPEG_DELEGATE) case JPEGCompression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JPEG)", image->filename); break; } #endif #if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE) case JPEG2000Compression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JP2)", image->filename); break; } #endif #if !defined(MAGICKCORE_ZLIB_DELEGATE) case ZipCompression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (ZLIB)", image->filename); break; } #endif case LZWCompression: { if (LocaleCompare(image_info->magick,"PDFA") == 0) compression=RLECompression; /* LZW compression is forbidden */ break; } case NoCompression: { if (LocaleCompare(image_info->magick,"PDFA") == 0) compression=RLECompression; /* ASCII 85 compression is forbidden */ break; } default: break; } if (compression == JPEG2000Compression) (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Scale relative to dots-per-inch. */ delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->resolution.x; resolution.y=image->resolution.y; if ((resolution.x == 0.0) || (resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image->units == PixelsPerCentimeterResolution) { resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0); resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0); } SetGeometry(image,&geometry); (void) FormatLocaleString(page_geometry,MagickPathExtent,"%.20gx%.20g", (double) image->columns,(double) image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatLocaleString(page_geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); else if ((image->gravity != UndefinedGravity) && (LocaleCompare(image_info->magick,"PDF") == 0)) (void) CopyMagickString(page_geometry,PSPageGeometry, MagickPathExtent); (void) ConcatenateMagickString(page_geometry,">",MagickPathExtent); (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); scale.x=(double) (geometry.width*delta.x)/resolution.x; geometry.width=(size_t) floor(scale.x+0.5); scale.y=(double) (geometry.height*delta.y)/resolution.y; geometry.height=(size_t) floor(scale.y+0.5); (void) ParseAbsoluteGeometry(page_geometry,&media_info); (void) ParseGravityGeometry(image,page_geometry,&page_info,exception); if (image->gravity != UndefinedGravity) { geometry.x=(-page_info.x); geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows); } pointsize=12.0; if (image_info->pointsize != 0.0) pointsize=image_info->pointsize; text_size=0; value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) text_size=(size_t) (MultilineCensus(value)*pointsize+12); (void) text_size; /* Write Page object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Type /Page\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Parent %.20g 0 R\n", (double) pages_id); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/Resources <<\n"); labels=(char **) NULL; value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { (void) FormatLocaleString(buffer,MagickPathExtent, "/Font << /F%.20g %.20g 0 R >>\n",(double) image->scene,(double) object+4); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MagickPathExtent, "/XObject << /Im%.20g %.20g 0 R >>\n",(double) image->scene,(double) object+5); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/ProcSet %.20g 0 R >>\n", (double) object+3); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "/MediaBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x, 72.0*media_info.height/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "/CropBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x, 72.0*media_info.height/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Contents %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Thumb %.20g 0 R\n", (double) object+(has_icc_profile != MagickFalse ? 10 : 8)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Contents object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); (void) WriteBlobString(image,"q\n"); if (labels != (char **) NULL) for (i=0; labels[i] != (char *) NULL; i++) { (void) WriteBlobString(image,"BT\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/F%.20g %g Tf\n", (double) image->scene,pointsize); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g Td\n", (double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+ 12)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"(%s) Tj\n", labels[i]); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"ET\n"); labels[i]=DestroyString(labels[i]); } (void) FormatLocaleString(buffer,MagickPathExtent, "%g 0 0 %g %.20g %.20g cm\n",scale.x,scale.y,(double) geometry.x, (double) geometry.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Im%.20g Do\n",(double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"Q\n"); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write Procset object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) CopyMagickString(buffer,"[ /PDF /Text /ImageC",MagickPathExtent); else if ((compression == FaxCompression) || (compression == Group4Compression)) (void) CopyMagickString(buffer,"[ /PDF /Text /ImageB",MagickPathExtent); else (void) CopyMagickString(buffer,"[ /PDF /Text /ImageI",MagickPathExtent); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image," ]\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Font object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (labels != (char **) NULL) { (void) WriteBlobString(image,"/Type /Font\n"); (void) WriteBlobString(image,"/Subtype /Type1\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Name /F%.20g\n", (double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/BaseFont /Helvetica\n"); (void) WriteBlobString(image,"/Encoding /MacRomanEncoding\n"); labels=(char **) RelinquishMagickMemory(labels); } (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); /* Write XObject object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Type /XObject\n"); (void) WriteBlobString(image,"/Subtype /Image\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Name /Im%.20g\n", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "ASCII85Decode"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"DCTDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MagickPathExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"JPXDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MagickPathExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "FlateDecode"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/DecodeParms [ << " "/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam, (double) image->columns,(double) image->rows); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Width %.20g\n",(double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Height %.20g\n",(double) image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/ColorSpace %.20g 0 R\n", (double) object+2); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/BitsPerComponent %d\n", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); if (image->alpha_trait != UndefinedPixelTrait) { (void) FormatLocaleString(buffer,MagickPathExtent,"/SMask %.20g 0 R\n", (double) object+(has_icc_profile != MagickFalse ? 9 : 7)); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels))) ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,"0") == 0) { (void) HuffmanEncodeImage(image_info,image,image,exception); break; } (void) Huffman2DEncodeImage(image_info,image,image,exception); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,image,"jpeg",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,"jp2",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(image,p))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p)))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,image,"jpeg",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,"jp2",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; length*=image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runoffset encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); if (image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelBlack(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed DirectColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(GetPixelRed(image,p))); Ascii85Encode(image,ScaleQuantumToChar(GetPixelGreen(image,p))); Ascii85Encode(image,ScaleQuantumToChar(GetPixelBlue(image,p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlack(image,p))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } else { /* Dump number of colors and colormap. */ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,(unsigned char) GetPixelIndex(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write Colorspace object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); device="DeviceRGB"; channels=0; if (image->colorspace == CMYKColorspace) { device="DeviceCMYK"; channels=4; } else if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse))) { device="DeviceGray"; channels=1; } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) { device="DeviceRGB"; channels=3; } profile=GetImageProfile(image,"icc"); if ((profile == (StringInfo *) NULL) || (channels == 0)) { if (channels != 0) (void) FormatLocaleString(buffer,MagickPathExtent,"/%s\n",device); else (void) FormatLocaleString(buffer,MagickPathExtent, "[ /Indexed /%s %.20g %.20g 0 R ]\n",device,(double) image->colors- 1,(double) object+3); (void) WriteBlobString(image,buffer); } else { const unsigned char *p; /* Write ICC profile. */ (void) FormatLocaleString(buffer,MagickPathExtent, "[/ICCBased %.20g 0 R]\n",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"<<\n/N %.20g\n" "/Filter /ASCII85Decode\n/Length %.20g 0 R\n/Alternate /%s\n>>\n" "stream\n",(double) channels,(double) object+1,device); (void) WriteBlobString(image,buffer); offset=TellBlob(image); Ascii85Initialize(image); p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) Ascii85Encode(image,(unsigned char) *p++); Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"endstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"endobj\n"); /* Write Thumb object. */ SetGeometry(image,&geometry); (void) ParseMetaGeometry("106x106+0+0>",&geometry.x,&geometry.y, &geometry.width,&geometry.height); tile_image=ThumbnailImage(image,geometry.width,geometry.height,exception); if (tile_image == (Image *) NULL) return(MagickFalse); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "ASCII85Decode"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"DCTDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MagickPathExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"JPXDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MagickPathExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "FlateDecode"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/DecodeParms [ << " "/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam, (double) tile_image->columns,(double) tile_image->rows); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Width %.20g\n",(double) tile_image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Height %.20g\n",(double) tile_image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/ColorSpace %.20g 0 R\n", (double) object-(has_icc_profile != MagickFalse ? 3 : 1)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/BitsPerComponent %d\n", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows; if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(tile_image,exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,"0") == 0) { (void) HuffmanEncodeImage(image_info,image,tile_image, exception); break; } (void) Huffman2DEncodeImage(image_info,image,tile_image,exception); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,"jpeg", exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,"jp2",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma( tile_image,p))); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(tile_image,p)))); p+=GetPixelChannels(tile_image); } } Ascii85Flush(image); break; } } } else if ((tile_image->storage_class == DirectClass) || (tile_image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,"jpeg", exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,"jp2",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(tile_image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(tile_image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(tile_image,p)); if (tile_image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelBlack(tile_image,p)); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed DirectColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(tile_image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(tile_image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(tile_image,p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlack(tile_image,p))); p+=GetPixelChannels(tile_image); } } Ascii85Flush(image); break; } } else { /* Dump number of colors and colormap. */ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=(unsigned char) GetPixelIndex(tile_image,p); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,(unsigned char) GetPixelIndex(tile_image,p)); p+=GetPixelChannels(image); } } Ascii85Flush(image); break; } } } tile_image=DestroyImage(tile_image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == FaxCompression) || (compression == Group4Compression)) (void) WriteBlobString(image,">>\n"); else { /* Write Colormap object. */ if (compression == NoCompression) (void) WriteBlobString(image,"/Filter [ /ASCII85Decode ]\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); if (compression == NoCompression) Ascii85Initialize(image); for (i=0; i < (ssize_t) image->colors; i++) { if (compression == NoCompression) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].red))); Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].green))); Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].blue))); continue; } (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].red))); (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].green))); (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].blue))); } if (compression == NoCompression) Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); } (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write softmask object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (image->alpha_trait == UndefinedPixelTrait) (void) WriteBlobString(image,">>\n"); else { (void) WriteBlobString(image,"/Type /XObject\n"); (void) WriteBlobString(image,"/Subtype /Image\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Name /Ma%.20g\n", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "ASCII85Decode"); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "FlateDecode"); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Width %.20g\n", (double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Height %.20g\n", (double) image->rows); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/ColorSpace /DeviceGray\n"); (void) FormatLocaleString(buffer,MagickPathExtent, "/BitsPerComponent %d\n",(compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { image=DestroyImage(image); ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(GetPixelAlpha(image,p))); p+=GetPixelChannels(image); } } Ascii85Flush(image); break; } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); } (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); /* Write Metadata object. */ xref[object++]=TellBlob(image); info_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (LocaleCompare(image_info->magick,"PDFA") == 0) (void) FormatLocaleString(buffer,MagickPathExtent,"/Title (%s)\n", EscapeParenthesis(basename)); else { wchar_t *utf16; utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length); if (utf16 != (wchar_t *) NULL) { (void) FormatLocaleString(buffer,MagickPathExtent,"/Title (\xfe\xff"); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) length; i++) (void) WriteBlobMSBShort(image,(unsigned short) utf16[i]); (void) FormatLocaleString(buffer,MagickPathExtent,")\n"); utf16=(wchar_t *) RelinquishMagickMemory(utf16); } } (void) WriteBlobString(image,buffer); seconds=time((time_t *) NULL); #if defined(MAGICKCORE_HAVE_LOCALTIME_R) (void) localtime_r(&seconds,&local_time); #else (void) memcpy(&local_time,localtime(&seconds),sizeof(local_time)); #endif (void) FormatLocaleString(date,MagickPathExtent,"D:%04d%02d%02d%02d%02d%02d", local_time.tm_year+1900,local_time.tm_mon+1,local_time.tm_mday, local_time.tm_hour,local_time.tm_min,local_time.tm_sec); (void) FormatLocaleString(buffer,MagickPathExtent,"/CreationDate (%s)\n", date); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/ModDate (%s)\n",date); (void) WriteBlobString(image,buffer); url=(char *) MagickAuthoritativeURL; escape=EscapeParenthesis(url); (void) FormatLocaleString(buffer,MagickPathExtent,"/Producer (%s)\n",escape); escape=DestroyString(escape); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Xref object. */ offset=TellBlob(image)-xref[0]+ (LocaleCompare(image_info->magick,"PDFA") == 0 ? 6 : 0)+10; (void) WriteBlobString(image,"xref\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"0 %.20g\n",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"0000000000 65535 f \n"); for (i=0; i < (ssize_t) object; i++) { (void) FormatLocaleString(buffer,MagickPathExtent,"%010lu 00000 n \n", (unsigned long) xref[i]); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"trailer\n"); (void) WriteBlobString(image,"<<\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Size %.20g\n",(double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Info %.20g 0 R\n",(double) info_id); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Root %.20g 0 R\n",(double) root_id); (void) WriteBlobString(image,buffer); (void) SignatureImage(image,exception); (void) FormatLocaleString(buffer,MagickPathExtent,"/ID [<%s> <%s>]\n", GetImageProperty(image,"signature",exception), GetImageProperty(image,"signature",exception)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"startxref\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"%%EOF\n"); xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickTrue); }
169,728
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int cap_bprm_set_creds(struct linux_binprm *bprm) { const struct cred *old = current_cred(); struct cred *new = bprm->cred; bool effective, has_cap = false; int ret; effective = false; ret = get_file_caps(bprm, &effective, &has_cap); if (ret < 0) return ret; if (!issecure(SECURE_NOROOT)) { /* * If the legacy file capability is set, then don't set privs * for a setuid root binary run by a non-root user. Do set it * for a root user just to cause least surprise to an admin. */ if (has_cap && new->uid != 0 && new->euid == 0) { warn_setuid_and_fcaps_mixed(bprm->filename); goto skip; } /* * To support inheritance of root-permissions and suid-root * executables under compatibility mode, we override the * capability sets for the file. * * If only the real uid is 0, we do not set the effective bit. */ if (new->euid == 0 || new->uid == 0) { /* pP' = (cap_bset & ~0) | (pI & ~0) */ new->cap_permitted = cap_combine(old->cap_bset, old->cap_inheritable); } if (new->euid == 0) effective = true; } skip: /* Don't let someone trace a set[ug]id/setpcap binary with the revised * credentials unless they have the appropriate permit */ if ((new->euid != old->uid || new->egid != old->gid || !cap_issubset(new->cap_permitted, old->cap_permitted)) && bprm->unsafe & ~LSM_UNSAFE_PTRACE_CAP) { /* downgrade; they get no more than they had, and maybe less */ if (!capable(CAP_SETUID)) { new->euid = new->uid; new->egid = new->gid; } new->cap_permitted = cap_intersect(new->cap_permitted, old->cap_permitted); } new->suid = new->fsuid = new->euid; new->sgid = new->fsgid = new->egid; if (effective) new->cap_effective = new->cap_permitted; else cap_clear(new->cap_effective); bprm->cap_effective = effective; /* * Audit candidate if current->cap_effective is set * * We do not bother to audit if 3 things are true: * 1) cap_effective has all caps * 2) we are root * 3) root is supposed to have all caps (SECURE_NOROOT) * Since this is just a normal root execing a process. * * Number 1 above might fail if you don't have a full bset, but I think * that is interesting information to audit. */ if (!cap_isclear(new->cap_effective)) { if (!cap_issubset(CAP_FULL_SET, new->cap_effective) || new->euid != 0 || new->uid != 0 || issecure(SECURE_NOROOT)) { ret = audit_log_bprm_fcaps(bprm, new, old); if (ret < 0) return ret; } } new->securebits &= ~issecure_mask(SECURE_KEEP_CAPS); return 0; } Commit Message: fcaps: clear the same personality flags as suid when fcaps are used If a process increases permissions using fcaps all of the dangerous personality flags which are cleared for suid apps should also be cleared. Thus programs given priviledge with fcaps will continue to have address space randomization enabled even if the parent tried to disable it to make it easier to attack. Signed-off-by: Eric Paris <[email protected]> Reviewed-by: Serge Hallyn <[email protected]> Signed-off-by: James Morris <[email protected]> CWE ID: CWE-264
int cap_bprm_set_creds(struct linux_binprm *bprm) { const struct cred *old = current_cred(); struct cred *new = bprm->cred; bool effective, has_cap = false; int ret; effective = false; ret = get_file_caps(bprm, &effective, &has_cap); if (ret < 0) return ret; if (!issecure(SECURE_NOROOT)) { /* * If the legacy file capability is set, then don't set privs * for a setuid root binary run by a non-root user. Do set it * for a root user just to cause least surprise to an admin. */ if (has_cap && new->uid != 0 && new->euid == 0) { warn_setuid_and_fcaps_mixed(bprm->filename); goto skip; } /* * To support inheritance of root-permissions and suid-root * executables under compatibility mode, we override the * capability sets for the file. * * If only the real uid is 0, we do not set the effective bit. */ if (new->euid == 0 || new->uid == 0) { /* pP' = (cap_bset & ~0) | (pI & ~0) */ new->cap_permitted = cap_combine(old->cap_bset, old->cap_inheritable); } if (new->euid == 0) effective = true; } skip: /* if we have fs caps, clear dangerous personality flags */ if (!cap_issubset(new->cap_permitted, old->cap_permitted)) bprm->per_clear |= PER_CLEAR_ON_SETID; /* Don't let someone trace a set[ug]id/setpcap binary with the revised * credentials unless they have the appropriate permit */ if ((new->euid != old->uid || new->egid != old->gid || !cap_issubset(new->cap_permitted, old->cap_permitted)) && bprm->unsafe & ~LSM_UNSAFE_PTRACE_CAP) { /* downgrade; they get no more than they had, and maybe less */ if (!capable(CAP_SETUID)) { new->euid = new->uid; new->egid = new->gid; } new->cap_permitted = cap_intersect(new->cap_permitted, old->cap_permitted); } new->suid = new->fsuid = new->euid; new->sgid = new->fsgid = new->egid; if (effective) new->cap_effective = new->cap_permitted; else cap_clear(new->cap_effective); bprm->cap_effective = effective; /* * Audit candidate if current->cap_effective is set * * We do not bother to audit if 3 things are true: * 1) cap_effective has all caps * 2) we are root * 3) root is supposed to have all caps (SECURE_NOROOT) * Since this is just a normal root execing a process. * * Number 1 above might fail if you don't have a full bset, but I think * that is interesting information to audit. */ if (!cap_isclear(new->cap_effective)) { if (!cap_issubset(CAP_FULL_SET, new->cap_effective) || new->euid != 0 || new->uid != 0 || issecure(SECURE_NOROOT)) { ret = audit_log_bprm_fcaps(bprm, new, old); if (ret < 0) return ret; } } new->securebits &= ~issecure_mask(SECURE_KEEP_CAPS); return 0; }
165,616
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: QuicErrorCode QuicStreamSequencerBuffer::OnStreamData( QuicStreamOffset starting_offset, QuicStringPiece data, QuicTime timestamp, size_t* const bytes_buffered, std::string* error_details) { CHECK_EQ(destruction_indicator_, 123456) << "This object has been destructed"; *bytes_buffered = 0; QuicStreamOffset offset = starting_offset; size_t size = data.size(); if (size == 0) { *error_details = "Received empty stream frame without FIN."; return QUIC_EMPTY_STREAM_FRAME_NO_FIN; } std::list<Gap>::iterator current_gap = gaps_.begin(); while (current_gap != gaps_.end() && current_gap->end_offset <= offset) { ++current_gap; } DCHECK(current_gap != gaps_.end()); if (offset < current_gap->begin_offset && offset + size <= current_gap->begin_offset) { QUIC_DVLOG(1) << "Duplicated data at offset: " << offset << " length: " << size; return QUIC_NO_ERROR; } if (offset < current_gap->begin_offset && offset + size > current_gap->begin_offset) { string prefix(data.data(), data.length() < 128 ? data.length() : 128); *error_details = QuicStrCat("Beginning of received data overlaps with buffered data.\n", "New frame range [", offset, ", ", offset + size, ") with first 128 bytes: ", prefix, "\n", "Currently received frames: ", GapsDebugString(), "\n", "Current gaps: ", ReceivedFramesDebugString()); return QUIC_OVERLAPPING_STREAM_DATA; } if (offset + size > current_gap->end_offset) { string prefix(data.data(), data.length() < 128 ? data.length() : 128); *error_details = QuicStrCat( "End of received data overlaps with buffered data.\nNew frame range [", offset, ", ", offset + size, ") with first 128 bytes: ", prefix, "\n", "Currently received frames: ", ReceivedFramesDebugString(), "\n", "Current gaps: ", GapsDebugString()); return QUIC_OVERLAPPING_STREAM_DATA; } if (offset + size > total_bytes_read_ + max_buffer_capacity_bytes_) { *error_details = "Received data beyond available range."; return QUIC_INTERNAL_ERROR; } if (current_gap->begin_offset != starting_offset && current_gap->end_offset != starting_offset + data.length() && gaps_.size() >= kMaxNumGapsAllowed) { *error_details = "Too many gaps created for this stream."; return QUIC_TOO_MANY_FRAME_GAPS; } size_t total_written = 0; size_t source_remaining = size; const char* source = data.data(); while (source_remaining > 0) { const size_t write_block_num = GetBlockIndex(offset); const size_t write_block_offset = GetInBlockOffset(offset); DCHECK_GT(blocks_count_, write_block_num); size_t block_capacity = GetBlockCapacity(write_block_num); size_t bytes_avail = block_capacity - write_block_offset; if (offset + bytes_avail > total_bytes_read_ + max_buffer_capacity_bytes_) { bytes_avail = total_bytes_read_ + max_buffer_capacity_bytes_ - offset; } if (blocks_ == nullptr) { blocks_.reset(new BufferBlock*[blocks_count_]()); for (size_t i = 0; i < blocks_count_; ++i) { blocks_[i] = nullptr; } } if (write_block_num >= blocks_count_) { *error_details = QuicStrCat( "QuicStreamSequencerBuffer error: OnStreamData() exceed array bounds." "write offset = ", offset, " write_block_num = ", write_block_num, " blocks_count_ = ", blocks_count_); return QUIC_STREAM_SEQUENCER_INVALID_STATE; } if (blocks_ == nullptr) { *error_details = "QuicStreamSequencerBuffer error: OnStreamData() blocks_ is null"; return QUIC_STREAM_SEQUENCER_INVALID_STATE; } if (blocks_[write_block_num] == nullptr) { blocks_[write_block_num] = new BufferBlock(); } const size_t bytes_to_copy = std::min<size_t>(bytes_avail, source_remaining); char* dest = blocks_[write_block_num]->buffer + write_block_offset; QUIC_DVLOG(1) << "Write at offset: " << offset << " length: " << bytes_to_copy; if (dest == nullptr || source == nullptr) { *error_details = QuicStrCat( "QuicStreamSequencerBuffer error: OnStreamData()" " dest == nullptr: ", (dest == nullptr), " source == nullptr: ", (source == nullptr), " Writing at offset ", offset, " Gaps: ", GapsDebugString(), " Remaining frames: ", ReceivedFramesDebugString(), " total_bytes_read_ = ", total_bytes_read_); return QUIC_STREAM_SEQUENCER_INVALID_STATE; } memcpy(dest, source, bytes_to_copy); source += bytes_to_copy; source_remaining -= bytes_to_copy; offset += bytes_to_copy; total_written += bytes_to_copy; } DCHECK_GT(total_written, 0u); *bytes_buffered = total_written; UpdateGapList(current_gap, starting_offset, total_written); frame_arrival_time_map_.insert( std::make_pair(starting_offset, FrameInfo(size, timestamp))); num_bytes_buffered_ += total_written; return QUIC_NO_ERROR; } Commit Message: Fix OOB Write in QuicStreamSequencerBuffer::OnStreamData BUG=778505 Cq-Include-Trybots: master.tryserver.chromium.android:android_cronet_tester;master.tryserver.chromium.mac:ios-simulator-cronet Change-Id: I1dfd1d26a2c7ee8fe047f7fe6e4ac2e9b97efa52 Reviewed-on: https://chromium-review.googlesource.com/748282 Commit-Queue: Ryan Hamilton <[email protected]> Reviewed-by: Zhongyi Shi <[email protected]> Cr-Commit-Position: refs/heads/master@{#513144} CWE ID: CWE-787
QuicErrorCode QuicStreamSequencerBuffer::OnStreamData( QuicStreamOffset starting_offset, QuicStringPiece data, QuicTime timestamp, size_t* const bytes_buffered, std::string* error_details) { CHECK_EQ(destruction_indicator_, 123456) << "This object has been destructed"; *bytes_buffered = 0; QuicStreamOffset offset = starting_offset; size_t size = data.size(); if (size == 0) { *error_details = "Received empty stream frame without FIN."; return QUIC_EMPTY_STREAM_FRAME_NO_FIN; } std::list<Gap>::iterator current_gap = gaps_.begin(); while (current_gap != gaps_.end() && current_gap->end_offset <= offset) { ++current_gap; } if (current_gap == gaps_.end()) { *error_details = "Received stream data outside of maximum range."; return QUIC_INTERNAL_ERROR; } if (offset < current_gap->begin_offset && offset + size <= current_gap->begin_offset) { QUIC_DVLOG(1) << "Duplicated data at offset: " << offset << " length: " << size; return QUIC_NO_ERROR; } if (offset < current_gap->begin_offset && offset + size > current_gap->begin_offset) { string prefix(data.data(), data.length() < 128 ? data.length() : 128); *error_details = QuicStrCat("Beginning of received data overlaps with buffered data.\n", "New frame range [", offset, ", ", offset + size, ") with first 128 bytes: ", prefix, "\n", "Currently received frames: ", GapsDebugString(), "\n", "Current gaps: ", ReceivedFramesDebugString()); return QUIC_OVERLAPPING_STREAM_DATA; } if (offset + size > current_gap->end_offset) { string prefix(data.data(), data.length() < 128 ? data.length() : 128); *error_details = QuicStrCat( "End of received data overlaps with buffered data.\nNew frame range [", offset, ", ", offset + size, ") with first 128 bytes: ", prefix, "\n", "Currently received frames: ", ReceivedFramesDebugString(), "\n", "Current gaps: ", GapsDebugString()); return QUIC_OVERLAPPING_STREAM_DATA; } if (offset + size > total_bytes_read_ + max_buffer_capacity_bytes_ || offset + size < offset) { *error_details = "Received data beyond available range."; return QUIC_INTERNAL_ERROR; } if (current_gap->begin_offset != starting_offset && current_gap->end_offset != starting_offset + data.length() && gaps_.size() >= kMaxNumGapsAllowed) { *error_details = "Too many gaps created for this stream."; return QUIC_TOO_MANY_FRAME_GAPS; } size_t total_written = 0; size_t source_remaining = size; const char* source = data.data(); while (source_remaining > 0) { const size_t write_block_num = GetBlockIndex(offset); const size_t write_block_offset = GetInBlockOffset(offset); DCHECK_GT(blocks_count_, write_block_num); size_t block_capacity = GetBlockCapacity(write_block_num); size_t bytes_avail = block_capacity - write_block_offset; if (offset + bytes_avail > total_bytes_read_ + max_buffer_capacity_bytes_) { bytes_avail = total_bytes_read_ + max_buffer_capacity_bytes_ - offset; } if (blocks_ == nullptr) { blocks_.reset(new BufferBlock*[blocks_count_]()); for (size_t i = 0; i < blocks_count_; ++i) { blocks_[i] = nullptr; } } if (write_block_num >= blocks_count_) { *error_details = QuicStrCat( "QuicStreamSequencerBuffer error: OnStreamData() exceed array bounds." "write offset = ", offset, " write_block_num = ", write_block_num, " blocks_count_ = ", blocks_count_); return QUIC_STREAM_SEQUENCER_INVALID_STATE; } if (blocks_ == nullptr) { *error_details = "QuicStreamSequencerBuffer error: OnStreamData() blocks_ is null"; return QUIC_STREAM_SEQUENCER_INVALID_STATE; } if (blocks_[write_block_num] == nullptr) { blocks_[write_block_num] = new BufferBlock(); } const size_t bytes_to_copy = std::min<size_t>(bytes_avail, source_remaining); char* dest = blocks_[write_block_num]->buffer + write_block_offset; QUIC_DVLOG(1) << "Write at offset: " << offset << " length: " << bytes_to_copy; if (dest == nullptr || source == nullptr) { *error_details = QuicStrCat( "QuicStreamSequencerBuffer error: OnStreamData()" " dest == nullptr: ", (dest == nullptr), " source == nullptr: ", (source == nullptr), " Writing at offset ", offset, " Gaps: ", GapsDebugString(), " Remaining frames: ", ReceivedFramesDebugString(), " total_bytes_read_ = ", total_bytes_read_); return QUIC_STREAM_SEQUENCER_INVALID_STATE; } memcpy(dest, source, bytes_to_copy); source += bytes_to_copy; source_remaining -= bytes_to_copy; offset += bytes_to_copy; total_written += bytes_to_copy; } DCHECK_GT(total_written, 0u); *bytes_buffered = total_written; UpdateGapList(current_gap, starting_offset, total_written); frame_arrival_time_map_.insert( std::make_pair(starting_offset, FrameInfo(size, timestamp))); num_bytes_buffered_ += total_written; return QUIC_NO_ERROR; }
172,923
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ubik_print(netdissect_options *ndo, register const u_char *bp) { int ubik_op; int32_t temp; /* * Print out the afs call we're invoking. The table used here was * gleaned from ubik/ubik_int.xg */ ubik_op = EXTRACT_32BITS(bp + sizeof(struct rx_header)); ND_PRINT((ndo, " ubik call %s", tok2str(ubik_req, "op#%d", ubik_op))); /* * Decode some of the arguments to the Ubik calls */ bp += sizeof(struct rx_header) + 4; switch (ubik_op) { case 10000: /* Beacon */ ND_TCHECK2(bp[0], 4); temp = EXTRACT_32BITS(bp); bp += sizeof(int32_t); ND_PRINT((ndo, " syncsite %s", temp ? "yes" : "no")); ND_PRINT((ndo, " votestart")); DATEOUT(); ND_PRINT((ndo, " dbversion")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); break; case 10003: /* Get sync site */ ND_PRINT((ndo, " site")); UINTOUT(); break; case 20000: /* Begin */ case 20001: /* Commit */ case 20007: /* Abort */ case 20008: /* Release locks */ case 20010: /* Writev */ ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); break; case 20002: /* Lock */ ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " file")); INTOUT(); ND_PRINT((ndo, " pos")); INTOUT(); ND_PRINT((ndo, " length")); INTOUT(); temp = EXTRACT_32BITS(bp); bp += sizeof(int32_t); tok2str(ubik_lock_types, "type %d", temp); break; case 20003: /* Write */ ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " file")); INTOUT(); ND_PRINT((ndo, " pos")); INTOUT(); break; case 20005: /* Get file */ ND_PRINT((ndo, " file")); INTOUT(); break; case 20006: /* Send file */ ND_PRINT((ndo, " file")); INTOUT(); ND_PRINT((ndo, " length")); INTOUT(); ND_PRINT((ndo, " dbversion")); UBIK_VERSIONOUT(); break; case 20009: /* Truncate */ ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " file")); INTOUT(); ND_PRINT((ndo, " length")); INTOUT(); break; case 20012: /* Set version */ ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " oldversion")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " newversion")); UBIK_VERSIONOUT(); break; default: ; } return; trunc: ND_PRINT((ndo, " [|ubik]")); } Commit Message: CVE-2017-13049/Rx: add a missing bounds check for Ubik One of the case blocks in ubik_print() didn't check bounds before fetching 32 bits of packet data and could overread past the captured packet data by that amount. This fixes a buffer over-read discovered by Henri Salo from Nixu Corporation. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
ubik_print(netdissect_options *ndo, register const u_char *bp) { int ubik_op; int32_t temp; /* * Print out the afs call we're invoking. The table used here was * gleaned from ubik/ubik_int.xg */ ubik_op = EXTRACT_32BITS(bp + sizeof(struct rx_header)); ND_PRINT((ndo, " ubik call %s", tok2str(ubik_req, "op#%d", ubik_op))); /* * Decode some of the arguments to the Ubik calls */ bp += sizeof(struct rx_header) + 4; switch (ubik_op) { case 10000: /* Beacon */ ND_TCHECK2(bp[0], 4); temp = EXTRACT_32BITS(bp); bp += sizeof(int32_t); ND_PRINT((ndo, " syncsite %s", temp ? "yes" : "no")); ND_PRINT((ndo, " votestart")); DATEOUT(); ND_PRINT((ndo, " dbversion")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); break; case 10003: /* Get sync site */ ND_PRINT((ndo, " site")); UINTOUT(); break; case 20000: /* Begin */ case 20001: /* Commit */ case 20007: /* Abort */ case 20008: /* Release locks */ case 20010: /* Writev */ ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); break; case 20002: /* Lock */ ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " file")); INTOUT(); ND_PRINT((ndo, " pos")); INTOUT(); ND_PRINT((ndo, " length")); INTOUT(); ND_TCHECK_32BITS(bp); temp = EXTRACT_32BITS(bp); bp += sizeof(int32_t); tok2str(ubik_lock_types, "type %d", temp); break; case 20003: /* Write */ ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " file")); INTOUT(); ND_PRINT((ndo, " pos")); INTOUT(); break; case 20005: /* Get file */ ND_PRINT((ndo, " file")); INTOUT(); break; case 20006: /* Send file */ ND_PRINT((ndo, " file")); INTOUT(); ND_PRINT((ndo, " length")); INTOUT(); ND_PRINT((ndo, " dbversion")); UBIK_VERSIONOUT(); break; case 20009: /* Truncate */ ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " file")); INTOUT(); ND_PRINT((ndo, " length")); INTOUT(); break; case 20012: /* Set version */ ND_PRINT((ndo, " tid")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " oldversion")); UBIK_VERSIONOUT(); ND_PRINT((ndo, " newversion")); UBIK_VERSIONOUT(); break; default: ; } return; trunc: ND_PRINT((ndo, " [|ubik]")); }
167,826
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintPreviewUI::OnCancelPendingPreviewRequest() { g_print_preview_request_id_map.Get().Set(preview_ui_addr_str_, -1); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void PrintPreviewUI::OnCancelPendingPreviewRequest() { g_print_preview_request_id_map.Get().Set(id_, -1); }
170,836
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: V8ContextNativeHandler::V8ContextNativeHandler(ScriptContext* context) : ObjectBackedNativeHandler(context), context_(context) { RouteFunction("GetAvailability", base::Bind(&V8ContextNativeHandler::GetAvailability, base::Unretained(this))); RouteFunction("GetModuleSystem", base::Bind(&V8ContextNativeHandler::GetModuleSystem, base::Unretained(this))); RouteFunction( "RunWithNativesEnabled", base::Bind(&V8ContextNativeHandler::RunWithNativesEnabled, base::Unretained(this))); } Commit Message: [Extensions] Expand bindings access checks BUG=601149 BUG=601073 Review URL: https://codereview.chromium.org/1866103002 Cr-Commit-Position: refs/heads/master@{#387710} CWE ID: CWE-284
V8ContextNativeHandler::V8ContextNativeHandler(ScriptContext* context) : ObjectBackedNativeHandler(context), context_(context) { RouteFunction("GetAvailability", base::Bind(&V8ContextNativeHandler::GetAvailability, base::Unretained(this))); RouteFunction("GetModuleSystem", base::Bind(&V8ContextNativeHandler::GetModuleSystem, base::Unretained(this))); RouteFunction("RunWithNativesEnabled", "test", base::Bind(&V8ContextNativeHandler::RunWithNativesEnabled, base::Unretained(this))); }
172,256
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int enable(void) { LOG_INFO("%s", __func__); if (!interface_ready()) return BT_STATUS_NOT_READY; stack_manager_get_interface()->start_up_stack_async(); return BT_STATUS_SUCCESS; } Commit Message: Add guest mode functionality (2/3) Add a flag to enable() to start Bluetooth in restricted mode. In restricted mode, all devices that are paired during restricted mode are deleted upon leaving restricted mode. Right now restricted mode is only entered while a guest user is active. Bug: 27410683 Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19 CWE ID: CWE-20
static int enable(void) { static int enable(bool start_restricted) { LOG_INFO(LOG_TAG, "%s: start restricted = %d", __func__, start_restricted); restricted_mode = start_restricted; if (!interface_ready()) return BT_STATUS_NOT_READY; stack_manager_get_interface()->start_up_stack_async(); return BT_STATUS_SUCCESS; }
173,551
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static uint8_t excluded_channels(bitfile *ld, drc_info *drc) { uint8_t i, n = 0; uint8_t num_excl_chan = 7; for (i = 0; i < 7; i++) { drc->exclude_mask[i] = faad_get1bit(ld DEBUGVAR(1,103,"excluded_channels(): exclude_mask")); } n++; while ((drc->additional_excluded_chns[n-1] = faad_get1bit(ld DEBUGVAR(1,104,"excluded_channels(): additional_excluded_chns"))) == 1) { for (i = num_excl_chan; i < num_excl_chan+7; i++) { drc->exclude_mask[i] = faad_get1bit(ld DEBUGVAR(1,105,"excluded_channels(): exclude_mask")); } n++; num_excl_chan += 7; } return n; } Commit Message: Fix a couple buffer overflows https://hackerone.com/reports/502816 https://hackerone.com/reports/507858 https://github.com/videolan/vlc/blob/master/contrib/src/faad2/faad2-fix-overflows.patch CWE ID: CWE-119
static uint8_t excluded_channels(bitfile *ld, drc_info *drc) { uint8_t i, n = 0; uint8_t num_excl_chan = 7; for (i = 0; i < 7; i++) { drc->exclude_mask[i] = faad_get1bit(ld DEBUGVAR(1,103,"excluded_channels(): exclude_mask")); } n++; while ((drc->additional_excluded_chns[n-1] = faad_get1bit(ld DEBUGVAR(1,104,"excluded_channels(): additional_excluded_chns"))) == 1) { if (i >= MAX_CHANNELS - num_excl_chan - 7) return n; for (i = num_excl_chan; i < num_excl_chan+7; i++) { drc->exclude_mask[i] = faad_get1bit(ld DEBUGVAR(1,105,"excluded_channels(): exclude_mask")); } n++; num_excl_chan += 7; } return n; }
169,536
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t BnOMX::onTransact( uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { switch (code) { case LIVES_LOCALLY: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); pid_t pid = (pid_t)data.readInt32(); reply->writeInt32(livesLocally(node, pid)); return OK; } case LIST_NODES: { CHECK_OMX_INTERFACE(IOMX, data, reply); List<ComponentInfo> list; listNodes(&list); reply->writeInt32(list.size()); for (List<ComponentInfo>::iterator it = list.begin(); it != list.end(); ++it) { ComponentInfo &cur = *it; reply->writeString8(cur.mName); reply->writeInt32(cur.mRoles.size()); for (List<String8>::iterator role_it = cur.mRoles.begin(); role_it != cur.mRoles.end(); ++role_it) { reply->writeString8(*role_it); } } return NO_ERROR; } case ALLOCATE_NODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); const char *name = data.readCString(); sp<IOMXObserver> observer = interface_cast<IOMXObserver>(data.readStrongBinder()); node_id node; status_t err = allocateNode(name, observer, &node); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)node); } return NO_ERROR; } case FREE_NODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); reply->writeInt32(freeNode(node)); return NO_ERROR; } case SEND_COMMAND: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_COMMANDTYPE cmd = static_cast<OMX_COMMANDTYPE>(data.readInt32()); OMX_S32 param = data.readInt32(); reply->writeInt32(sendCommand(node, cmd, param)); return NO_ERROR; } case GET_PARAMETER: case SET_PARAMETER: case GET_CONFIG: case SET_CONFIG: case SET_INTERNAL_OPTION: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_INDEXTYPE index = static_cast<OMX_INDEXTYPE>(data.readInt32()); size_t size = data.readInt64(); void *params = malloc(size); data.read(params, size); status_t err; switch (code) { case GET_PARAMETER: err = getParameter(node, index, params, size); break; case SET_PARAMETER: err = setParameter(node, index, params, size); break; case GET_CONFIG: err = getConfig(node, index, params, size); break; case SET_CONFIG: err = setConfig(node, index, params, size); break; case SET_INTERNAL_OPTION: { InternalOptionType type = (InternalOptionType)data.readInt32(); err = setInternalOption(node, index, type, params, size); break; } default: TRESPASS(); } reply->writeInt32(err); if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) { reply->write(params, size); } free(params); params = NULL; return NO_ERROR; } case GET_STATE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_STATETYPE state = OMX_StateInvalid; status_t err = getState(node, &state); reply->writeInt32(state); reply->writeInt32(err); return NO_ERROR; } case ENABLE_GRAPHIC_BUFFERS: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); status_t err = enableGraphicBuffers(node, port_index, enable); reply->writeInt32(err); return NO_ERROR; } case GET_GRAPHIC_BUFFER_USAGE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_U32 usage = 0; status_t err = getGraphicBufferUsage(node, port_index, &usage); reply->writeInt32(err); reply->writeInt32(usage); return NO_ERROR; } case USE_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IMemory> params = interface_cast<IMemory>(data.readStrongBinder()); buffer_id buffer; status_t err = useBuffer(node, port_index, params, &buffer); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case USE_GRAPHIC_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); buffer_id buffer; status_t err = useGraphicBuffer( node, port_index, graphicBuffer, &buffer); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case UPDATE_GRAPHIC_BUFFER_IN_META: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); buffer_id buffer = (buffer_id)data.readInt32(); status_t err = updateGraphicBufferInMeta( node, port_index, graphicBuffer, buffer); reply->writeInt32(err); return NO_ERROR; } case CREATE_INPUT_SURFACE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IGraphicBufferProducer> bufferProducer; status_t err = createInputSurface(node, port_index, &bufferProducer); reply->writeInt32(err); if (err == OK) { reply->writeStrongBinder(bufferProducer->asBinder()); } return NO_ERROR; } case SIGNAL_END_OF_INPUT_STREAM: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); status_t err = signalEndOfInputStream(node); reply->writeInt32(err); return NO_ERROR; } case STORE_META_DATA_IN_BUFFERS: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); status_t err = storeMetaDataInBuffers(node, port_index, enable); reply->writeInt32(err); return NO_ERROR; } case PREPARE_FOR_ADAPTIVE_PLAYBACK: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); OMX_U32 max_width = data.readInt32(); OMX_U32 max_height = data.readInt32(); status_t err = prepareForAdaptivePlayback( node, port_index, enable, max_width, max_height); reply->writeInt32(err); return NO_ERROR; } case CONFIGURE_VIDEO_TUNNEL_MODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL tunneled = (OMX_BOOL)data.readInt32(); OMX_U32 audio_hw_sync = data.readInt32(); native_handle_t *sideband_handle; status_t err = configureVideoTunnelMode( node, port_index, tunneled, audio_hw_sync, &sideband_handle); reply->writeInt32(err); reply->writeNativeHandle(sideband_handle); return NO_ERROR; } case ALLOC_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); if (!isSecure(node) || port_index != 0 /* kPortIndexInput */) { ALOGE("b/24310423"); reply->writeInt32(INVALID_OPERATION); return NO_ERROR; } size_t size = data.readInt64(); buffer_id buffer; void *buffer_data; status_t err = allocateBuffer( node, port_index, size, &buffer, &buffer_data); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); reply->writeInt64((uintptr_t)buffer_data); } return NO_ERROR; } case ALLOC_BUFFER_WITH_BACKUP: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IMemory> params = interface_cast<IMemory>(data.readStrongBinder()); buffer_id buffer; status_t err = allocateBufferWithBackup( node, port_index, params, &buffer); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case FREE_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); reply->writeInt32(freeBuffer(node, port_index, buffer)); return NO_ERROR; } case FILL_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); reply->writeInt32(fillBuffer(node, buffer)); return NO_ERROR; } case EMPTY_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); OMX_U32 range_offset = data.readInt32(); OMX_U32 range_length = data.readInt32(); OMX_U32 flags = data.readInt32(); OMX_TICKS timestamp = data.readInt64(); reply->writeInt32( emptyBuffer( node, buffer, range_offset, range_length, flags, timestamp)); return NO_ERROR; } case GET_EXTENSION_INDEX: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); const char *parameter_name = data.readCString(); OMX_INDEXTYPE index; status_t err = getExtensionIndex(node, parameter_name, &index); reply->writeInt32(err); if (err == OK) { reply->writeInt32(index); } return OK; } default: return BBinder::onTransact(code, data, reply, flags); } } Commit Message: IOMX.cpp uninitialized pointer in BnOMX::onTransact This can lead to local code execution in media server. Fix initializes the pointer and checks the error conditions before returning Bug: 26403627 Change-Id: I7fa90682060148448dba01d6acbe3471d1ddb500 CWE ID: CWE-264
status_t BnOMX::onTransact( uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { switch (code) { case LIVES_LOCALLY: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); pid_t pid = (pid_t)data.readInt32(); reply->writeInt32(livesLocally(node, pid)); return OK; } case LIST_NODES: { CHECK_OMX_INTERFACE(IOMX, data, reply); List<ComponentInfo> list; listNodes(&list); reply->writeInt32(list.size()); for (List<ComponentInfo>::iterator it = list.begin(); it != list.end(); ++it) { ComponentInfo &cur = *it; reply->writeString8(cur.mName); reply->writeInt32(cur.mRoles.size()); for (List<String8>::iterator role_it = cur.mRoles.begin(); role_it != cur.mRoles.end(); ++role_it) { reply->writeString8(*role_it); } } return NO_ERROR; } case ALLOCATE_NODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); const char *name = data.readCString(); sp<IOMXObserver> observer = interface_cast<IOMXObserver>(data.readStrongBinder()); node_id node; status_t err = allocateNode(name, observer, &node); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)node); } return NO_ERROR; } case FREE_NODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); reply->writeInt32(freeNode(node)); return NO_ERROR; } case SEND_COMMAND: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_COMMANDTYPE cmd = static_cast<OMX_COMMANDTYPE>(data.readInt32()); OMX_S32 param = data.readInt32(); reply->writeInt32(sendCommand(node, cmd, param)); return NO_ERROR; } case GET_PARAMETER: case SET_PARAMETER: case GET_CONFIG: case SET_CONFIG: case SET_INTERNAL_OPTION: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_INDEXTYPE index = static_cast<OMX_INDEXTYPE>(data.readInt32()); size_t size = data.readInt64(); void *params = malloc(size); data.read(params, size); status_t err; switch (code) { case GET_PARAMETER: err = getParameter(node, index, params, size); break; case SET_PARAMETER: err = setParameter(node, index, params, size); break; case GET_CONFIG: err = getConfig(node, index, params, size); break; case SET_CONFIG: err = setConfig(node, index, params, size); break; case SET_INTERNAL_OPTION: { InternalOptionType type = (InternalOptionType)data.readInt32(); err = setInternalOption(node, index, type, params, size); break; } default: TRESPASS(); } reply->writeInt32(err); if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) { reply->write(params, size); } free(params); params = NULL; return NO_ERROR; } case GET_STATE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_STATETYPE state = OMX_StateInvalid; status_t err = getState(node, &state); reply->writeInt32(state); reply->writeInt32(err); return NO_ERROR; } case ENABLE_GRAPHIC_BUFFERS: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); status_t err = enableGraphicBuffers(node, port_index, enable); reply->writeInt32(err); return NO_ERROR; } case GET_GRAPHIC_BUFFER_USAGE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_U32 usage = 0; status_t err = getGraphicBufferUsage(node, port_index, &usage); reply->writeInt32(err); reply->writeInt32(usage); return NO_ERROR; } case USE_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IMemory> params = interface_cast<IMemory>(data.readStrongBinder()); buffer_id buffer; status_t err = useBuffer(node, port_index, params, &buffer); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case USE_GRAPHIC_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); buffer_id buffer; status_t err = useGraphicBuffer( node, port_index, graphicBuffer, &buffer); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case UPDATE_GRAPHIC_BUFFER_IN_META: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); buffer_id buffer = (buffer_id)data.readInt32(); status_t err = updateGraphicBufferInMeta( node, port_index, graphicBuffer, buffer); reply->writeInt32(err); return NO_ERROR; } case CREATE_INPUT_SURFACE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IGraphicBufferProducer> bufferProducer; status_t err = createInputSurface(node, port_index, &bufferProducer); reply->writeInt32(err); if (err == OK) { reply->writeStrongBinder(bufferProducer->asBinder()); } return NO_ERROR; } case SIGNAL_END_OF_INPUT_STREAM: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); status_t err = signalEndOfInputStream(node); reply->writeInt32(err); return NO_ERROR; } case STORE_META_DATA_IN_BUFFERS: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); status_t err = storeMetaDataInBuffers(node, port_index, enable); reply->writeInt32(err); return NO_ERROR; } case PREPARE_FOR_ADAPTIVE_PLAYBACK: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); OMX_U32 max_width = data.readInt32(); OMX_U32 max_height = data.readInt32(); status_t err = prepareForAdaptivePlayback( node, port_index, enable, max_width, max_height); reply->writeInt32(err); return NO_ERROR; } case CONFIGURE_VIDEO_TUNNEL_MODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL tunneled = (OMX_BOOL)data.readInt32(); OMX_U32 audio_hw_sync = data.readInt32(); native_handle_t *sideband_handle = NULL; status_t err = configureVideoTunnelMode( node, port_index, tunneled, audio_hw_sync, &sideband_handle); reply->writeInt32(err); if(err == OK){ reply->writeNativeHandle(sideband_handle); } return NO_ERROR; } case ALLOC_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); if (!isSecure(node) || port_index != 0 /* kPortIndexInput */) { ALOGE("b/24310423"); reply->writeInt32(INVALID_OPERATION); return NO_ERROR; } size_t size = data.readInt64(); buffer_id buffer; void *buffer_data; status_t err = allocateBuffer( node, port_index, size, &buffer, &buffer_data); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); reply->writeInt64((uintptr_t)buffer_data); } return NO_ERROR; } case ALLOC_BUFFER_WITH_BACKUP: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IMemory> params = interface_cast<IMemory>(data.readStrongBinder()); buffer_id buffer; status_t err = allocateBufferWithBackup( node, port_index, params, &buffer); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case FREE_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); reply->writeInt32(freeBuffer(node, port_index, buffer)); return NO_ERROR; } case FILL_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); reply->writeInt32(fillBuffer(node, buffer)); return NO_ERROR; } case EMPTY_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); OMX_U32 range_offset = data.readInt32(); OMX_U32 range_length = data.readInt32(); OMX_U32 flags = data.readInt32(); OMX_TICKS timestamp = data.readInt64(); reply->writeInt32( emptyBuffer( node, buffer, range_offset, range_length, flags, timestamp)); return NO_ERROR; } case GET_EXTENSION_INDEX: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); const char *parameter_name = data.readCString(); OMX_INDEXTYPE index; status_t err = getExtensionIndex(node, parameter_name, &index); reply->writeInt32(err); if (err == OK) { reply->writeInt32(index); } return OK; } default: return BBinder::onTransact(code, data, reply, flags); } }
173,898
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ChromeMockRenderThread::print_preview_pages_remaining() { return print_preview_pages_remaining_; } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
int ChromeMockRenderThread::print_preview_pages_remaining() { int ChromeMockRenderThread::print_preview_pages_remaining() const { return print_preview_pages_remaining_; }
170,855
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderMessageFilter::GetPluginsCallback( IPC::Message* reply_msg, const std::vector<webkit::WebPluginInfo>& all_plugins) { PluginServiceFilter* filter = PluginServiceImpl::GetInstance()->GetFilter(); std::vector<webkit::WebPluginInfo> plugins; int child_process_id = -1; int routing_id = MSG_ROUTING_NONE; for (size_t i = 0; i < all_plugins.size(); ++i) { webkit::WebPluginInfo plugin(all_plugins[i]); if (!filter || filter->IsPluginEnabled(child_process_id, routing_id, resource_context_, GURL(), GURL(), &plugin)) { plugins.push_back(plugin); } } ViewHostMsg_GetPlugins::WriteReplyParams(reply_msg, plugins); Send(reply_msg); } Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/ BUG=172573 Review URL: https://codereview.chromium.org/12177018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-287
void RenderMessageFilter::GetPluginsCallback( IPC::Message* reply_msg, const std::vector<webkit::WebPluginInfo>& all_plugins) { PluginServiceFilter* filter = PluginServiceImpl::GetInstance()->GetFilter(); std::vector<webkit::WebPluginInfo> plugins; int child_process_id = -1; int routing_id = MSG_ROUTING_NONE; for (size_t i = 0; i < all_plugins.size(); ++i) { webkit::WebPluginInfo plugin(all_plugins[i]); if (!filter || filter->IsPluginAvailable(child_process_id, routing_id, resource_context_, GURL(), GURL(), &plugin)) { plugins.push_back(plugin); } } ViewHostMsg_GetPlugins::WriteReplyParams(reply_msg, plugins); Send(reply_msg); }
171,476
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ChromeOSChangeInputMethod( InputMethodStatusConnection* connection, const char* name) { DCHECK(name); DLOG(INFO) << "ChangeInputMethod: " << name; g_return_val_if_fail(connection, false); return connection->ChangeInputMethod(name); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool ChromeOSChangeInputMethod(
170,521
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int fscrypt_get_encryption_info(struct inode *inode) { struct fscrypt_info *ci = inode->i_crypt_info; if (!ci || (ci->ci_keyring_key && (ci->ci_keyring_key->flags & ((1 << KEY_FLAG_INVALIDATED) | (1 << KEY_FLAG_REVOKED) | (1 << KEY_FLAG_DEAD))))) return fscrypt_get_crypt_info(inode); return 0; } Commit Message: fscrypt: remove broken support for detecting keyring key revocation Filesystem encryption ostensibly supported revoking a keyring key that had been used to "unlock" encrypted files, causing those files to become "locked" again. This was, however, buggy for several reasons, the most severe of which was that when key revocation happened to be detected for an inode, its fscrypt_info was immediately freed, even while other threads could be using it for encryption or decryption concurrently. This could be exploited to crash the kernel or worse. This patch fixes the use-after-free by removing the code which detects the keyring key having been revoked, invalidated, or expired. Instead, an encrypted inode that is "unlocked" now simply remains unlocked until it is evicted from memory. Note that this is no worse than the case for block device-level encryption, e.g. dm-crypt, and it still remains possible for a privileged user to evict unused pages, inodes, and dentries by running 'sync; echo 3 > /proc/sys/vm/drop_caches', or by simply unmounting the filesystem. In fact, one of those actions was already needed anyway for key revocation to work even somewhat sanely. This change is not expected to break any applications. In the future I'd like to implement a real API for fscrypt key revocation that interacts sanely with ongoing filesystem operations --- waiting for existing operations to complete and blocking new operations, and invalidating and sanitizing key material and plaintext from the VFS caches. But this is a hard problem, and for now this bug must be fixed. This bug affected almost all versions of ext4, f2fs, and ubifs encryption, and it was potentially reachable in any kernel configured with encryption support (CONFIG_EXT4_ENCRYPTION=y, CONFIG_EXT4_FS_ENCRYPTION=y, CONFIG_F2FS_FS_ENCRYPTION=y, or CONFIG_UBIFS_FS_ENCRYPTION=y). Note that older kernels did not use the shared fs/crypto/ code, but due to the potential security implications of this bug, it may still be worthwhile to backport this fix to them. Fixes: b7236e21d55f ("ext4 crypto: reorganize how we store keys in the inode") Cc: [email protected] # v4.2+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> Acked-by: Michael Halcrow <[email protected]> CWE ID: CWE-416
int fscrypt_get_encryption_info(struct inode *inode)
168,282
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_ENCODED 2 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register Quantum *q; register ssize_t i, x; register unsigned char *p; size_t bytes_per_line, extent, height, length; ssize_t count, y; SUNInfo sun_info; unsigned char *sun_data, *sun_pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SUN raster header. */ (void) ResetMagickMemory(&sun_info,0,sizeof(sun_info)); sun_info.magic=ReadBlobMSBLong(image); do { /* Verify SUN identifier. */ if (sun_info.magic != 0x59a66a95) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); sun_info.width=ReadBlobMSBLong(image); sun_info.height=ReadBlobMSBLong(image); sun_info.depth=ReadBlobMSBLong(image); sun_info.length=ReadBlobMSBLong(image); sun_info.type=ReadBlobMSBLong(image); sun_info.maptype=ReadBlobMSBLong(image); sun_info.maplength=ReadBlobMSBLong(image); extent=sun_info.height*sun_info.width; if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) && (sun_info.type != RT_FORMAT_RGB)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.depth == 0) || (sun_info.depth > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) && (sun_info.maptype != RMT_RAW)) ThrowReaderException(CoderError,"ColormapTypeNotSupported"); image->columns=sun_info.width; image->rows=sun_info.height; image->depth=sun_info.depth <= 8 ? sun_info.depth : MAGICKCORE_QUANTUM_DEPTH; if (sun_info.depth < 24) { size_t one; image->colors=sun_info.maplength; one=1; if (sun_info.maptype == RMT_NONE) image->colors=one << sun_info.depth; if (sun_info.maptype == RMT_EQUAL_RGB) image->colors=sun_info.maplength/3; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } switch (sun_info.maptype) { case RMT_NONE: break; case RMT_EQUAL_RGB: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } case RMT_RAW: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,sun_info.maplength,sun_colormap); if (count != (ssize_t) sun_info.maplength) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } default: ThrowReaderException(CoderError,"ColormapTypeNotSupported"); } image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait : UndefinedPixelTrait; image->columns=sun_info.width; image->rows=sun_info.height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) != sun_info.length || !sun_info.length) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); number_pixels=(MagickSizeType) image->columns*image->rows; if ((sun_info.type != RT_ENCODED) && ((number_pixels*sun_info.depth) > (8*sun_info.length))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bytes_per_line=sun_info.width*sun_info.depth; sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax( sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data)); if (sun_data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=(ssize_t) ReadBlob(image,sun_info.length,sun_data); if (count != (ssize_t) sun_info.length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); height=sun_info.height; if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) || ((bytes_per_line/sun_info.depth) != sun_info.width)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bytes_per_line+=15; bytes_per_line<<=1; if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bytes_per_line>>=4; sun_pixels=(unsigned char *) AcquireQuantumMemory(height, bytes_per_line*sizeof(*sun_pixels)); if (sun_pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (sun_info.type == RT_ENCODED) (void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line* height); sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); /* Convert SUN raster image to pixel packets. */ p=sun_pixels; if (sun_info.depth == 1) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=7; bit >= 0; bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01), q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),q); q+=GetPixelChannels(image); } p++; } if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (image->storage_class == PseudoClass) { if (bytes_per_line == 0) bytes_per_line=image->columns; length=image->rows*(image->columns+image->columns % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if ((image->columns % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { size_t bytes_per_pixel; bytes_per_pixel=3; if (image->alpha_trait != UndefinedPixelTrait) bytes_per_pixel++; if (bytes_per_line == 0) bytes_per_line=bytes_per_pixel*image->columns; length=image->rows*(bytes_per_line+bytes_per_line % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); if (sun_info.type == RT_STANDARD) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); } else { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); } if (image->colors != 0) { SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelRed(image,q)].red),q); SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelGreen(image,q)].green),q); SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelBlue(image,q)].blue),q); } q+=GetPixelChannels(image); } if (((bytes_per_pixel*image->columns) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (image->storage_class == PseudoClass) (void) SyncImage(image,exception); sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; sun_info.magic=ReadBlobMSBLong(image); if (sun_info.magic == 0x59a66a95) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (sun_info.magic == 0x59a66a95); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-125
static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_ENCODED 2 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register Quantum *q; register ssize_t i, x; register unsigned char *p; size_t bytes_per_line, extent, height, length; ssize_t count, y; SUNInfo sun_info; unsigned char *sun_data, *sun_pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SUN raster header. */ (void) ResetMagickMemory(&sun_info,0,sizeof(sun_info)); sun_info.magic=ReadBlobMSBLong(image); do { /* Verify SUN identifier. */ if (sun_info.magic != 0x59a66a95) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); sun_info.width=ReadBlobMSBLong(image); sun_info.height=ReadBlobMSBLong(image); sun_info.depth=ReadBlobMSBLong(image); sun_info.length=ReadBlobMSBLong(image); sun_info.type=ReadBlobMSBLong(image); sun_info.maptype=ReadBlobMSBLong(image); sun_info.maplength=ReadBlobMSBLong(image); extent=sun_info.height*sun_info.width; if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) && (sun_info.type != RT_FORMAT_RGB)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.depth == 0) || (sun_info.depth > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) && (sun_info.maptype != RMT_RAW)) ThrowReaderException(CoderError,"ColormapTypeNotSupported"); image->columns=sun_info.width; image->rows=sun_info.height; image->depth=sun_info.depth <= 8 ? sun_info.depth : MAGICKCORE_QUANTUM_DEPTH; if (sun_info.depth < 24) { size_t one; image->colors=sun_info.maplength; one=1; if (sun_info.maptype == RMT_NONE) image->colors=one << sun_info.depth; if (sun_info.maptype == RMT_EQUAL_RGB) image->colors=sun_info.maplength/3; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } switch (sun_info.maptype) { case RMT_NONE: break; case RMT_EQUAL_RGB: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } case RMT_RAW: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,sun_info.maplength,sun_colormap); if (count != (ssize_t) sun_info.maplength) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } default: ThrowReaderException(CoderError,"ColormapTypeNotSupported"); } image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait : UndefinedPixelTrait; image->columns=sun_info.width; image->rows=sun_info.height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) != sun_info.length || !sun_info.length) ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); number_pixels=(MagickSizeType) image->columns*image->rows; if ((sun_info.type != RT_ENCODED) && ((number_pixels*sun_info.depth) > (8*sun_info.length))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bytes_per_line=sun_info.width*sun_info.depth; sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax( sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data)); if (sun_data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=(ssize_t) ReadBlob(image,sun_info.length,sun_data); if (count != (ssize_t) sun_info.length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); height=sun_info.height; if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) || ((bytes_per_line/sun_info.depth) != sun_info.width)) ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); bytes_per_line+=15; bytes_per_line<<=1; if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15)) ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); bytes_per_line>>=4; sun_pixels=(unsigned char *) AcquireQuantumMemory(height, bytes_per_line*sizeof(*sun_pixels)); if (sun_pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (sun_info.type == RT_ENCODED) (void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line* height); else { if (sun_info.length > (height*bytes_per_line)) ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); (void) CopyMagickMemory(sun_pixels,sun_data,sun_info.length); } sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); /* Convert SUN raster image to pixel packets. */ p=sun_pixels; if (sun_info.depth == 1) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=7; bit >= 0; bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01), q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),q); q+=GetPixelChannels(image); } p++; } if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (image->storage_class == PseudoClass) { if (bytes_per_line == 0) bytes_per_line=image->columns; length=image->rows*(image->columns+image->columns % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if ((image->columns % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { size_t bytes_per_pixel; bytes_per_pixel=3; if (image->alpha_trait != UndefinedPixelTrait) bytes_per_pixel++; if (bytes_per_line == 0) bytes_per_line=bytes_per_pixel*image->columns; length=image->rows*(bytes_per_line+bytes_per_line % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); if (sun_info.type == RT_STANDARD) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); } else { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); } if (image->colors != 0) { SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelRed(image,q)].red),q); SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelGreen(image,q)].green),q); SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelBlue(image,q)].blue),q); } q+=GetPixelChannels(image); } if (((bytes_per_pixel*image->columns) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (image->storage_class == PseudoClass) (void) SyncImage(image,exception); sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; sun_info.magic=ReadBlobMSBLong(image); if (sun_info.magic == 0x59a66a95) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (sun_info.magic == 0x59a66a95); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
170,125
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: XFixesFetchRegionAndBounds (Display *dpy, XserverRegion region, int *nrectanglesRet, XRectangle *bounds) { XFixesExtDisplayInfo *info = XFixesFindDisplay (dpy); xXFixesFetchRegionReq *req; xXFixesFetchRegionReply rep; XRectangle *rects; int nrects; long nbytes; long nread; XFixesCheckExtension (dpy, info, NULL); LockDisplay (dpy); GetReq (XFixesFetchRegion, req); req->reqType = info->codes->major_opcode; req->xfixesReqType = X_XFixesFetchRegion; req->region = region; *nrectanglesRet = 0; if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) { UnlockDisplay (dpy); SyncHandle (); return NULL; } bounds->x = rep.x; bounds->y = rep.y; bounds->y = rep.y; bounds->width = rep.width; bounds->height = rep.height; nbytes = (long) rep.length << 2; nrects = rep.length >> 1; rects = Xmalloc (nrects * sizeof (XRectangle)); if (!rects) { _XEatDataWords(dpy, rep.length); _XEatData (dpy, (unsigned long) (nbytes - nread)); } UnlockDisplay (dpy); SyncHandle(); *nrectanglesRet = nrects; return rects; } Commit Message: CWE ID: CWE-190
XFixesFetchRegionAndBounds (Display *dpy, XserverRegion region, int *nrectanglesRet, XRectangle *bounds) { XFixesExtDisplayInfo *info = XFixesFindDisplay (dpy); xXFixesFetchRegionReq *req; xXFixesFetchRegionReply rep; XRectangle *rects; int nrects; long nbytes; long nread; XFixesCheckExtension (dpy, info, NULL); LockDisplay (dpy); GetReq (XFixesFetchRegion, req); req->reqType = info->codes->major_opcode; req->xfixesReqType = X_XFixesFetchRegion; req->region = region; *nrectanglesRet = 0; if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) { UnlockDisplay (dpy); SyncHandle (); return NULL; } bounds->x = rep.x; bounds->y = rep.y; bounds->y = rep.y; bounds->width = rep.width; bounds->height = rep.height; if (rep.length < (INT_MAX >> 2)) { nbytes = (long) rep.length << 2; nrects = rep.length >> 1; rects = Xmalloc (nrects * sizeof (XRectangle)); } else { nbytes = 0; nrects = 0; rects = NULL; } if (!rects) { _XEatDataWords(dpy, rep.length); _XEatData (dpy, (unsigned long) (nbytes - nread)); } UnlockDisplay (dpy); SyncHandle(); *nrectanglesRet = nrects; return rects; }
164,922
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SampleTable::SampleTable(const sp<DataSource> &source) : mDataSource(source), mChunkOffsetOffset(-1), mChunkOffsetType(0), mNumChunkOffsets(0), mSampleToChunkOffset(-1), mNumSampleToChunkOffsets(0), mSampleSizeOffset(-1), mSampleSizeFieldSize(0), mDefaultSampleSize(0), mNumSampleSizes(0), mTimeToSampleCount(0), mTimeToSample(NULL), mSampleTimeEntries(NULL), mCompositionTimeDeltaEntries(NULL), mNumCompositionTimeDeltaEntries(0), mCompositionDeltaLookup(new CompositionDeltaLookup), mSyncSampleOffset(-1), mNumSyncSamples(0), mSyncSamples(NULL), mLastSyncSampleIndex(0), mSampleToChunkEntries(NULL) { mSampleIterator = new SampleIterator(this); } Commit Message: Resolve merge conflict when cp'ing ag/931301 to mnc-mr1-release Change-Id: I079d1db2d30d126f8aed348bd62451acf741037d CWE ID: CWE-20
SampleTable::SampleTable(const sp<DataSource> &source) : mDataSource(source), mChunkOffsetOffset(-1), mChunkOffsetType(0), mNumChunkOffsets(0), mSampleToChunkOffset(-1), mNumSampleToChunkOffsets(0), mSampleSizeOffset(-1), mSampleSizeFieldSize(0), mDefaultSampleSize(0), mNumSampleSizes(0), mTimeToSampleCount(0), mTimeToSample(), mSampleTimeEntries(NULL), mCompositionTimeDeltaEntries(NULL), mNumCompositionTimeDeltaEntries(0), mCompositionDeltaLookup(new CompositionDeltaLookup), mSyncSampleOffset(-1), mNumSyncSamples(0), mSyncSamples(NULL), mLastSyncSampleIndex(0), mSampleToChunkEntries(NULL) { mSampleIterator = new SampleIterator(this); }
174,171
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WM_SYMBOL midi *WildMidi_Open(const char *midifile) { uint8_t *mididata = NULL; uint32_t midisize = 0; uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A }; uint8_t xmi_hdr[] = { 'F', 'O', 'R', 'M' }; midi * ret = NULL; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (NULL); } if (midifile == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL filename)", 0); return (NULL); } if ((mididata = (uint8_t *) _WM_BufferFile(midifile, &midisize)) == NULL) { return (NULL); } if (memcmp(mididata,"HMIMIDIP", 8) == 0) { ret = (void *) _WM_ParseNewHmp(mididata, midisize); } else if (memcmp(mididata, "HMI-MIDISONG061595", 18) == 0) { ret = (void *) _WM_ParseNewHmi(mididata, midisize); } else if (memcmp(mididata, mus_hdr, 4) == 0) { ret = (void *) _WM_ParseNewMus(mididata, midisize); } else if (memcmp(mididata, xmi_hdr, 4) == 0) { ret = (void *) _WM_ParseNewXmi(mididata, midisize); } else { ret = (void *) _WM_ParseNewMidi(mididata, midisize); } free(mididata); if (ret) { if (add_handle(ret) != 0) { WildMidi_Close(ret); ret = NULL; } } return (ret); } Commit Message: wildmidi_lib.c (WildMidi_Open, WildMidi_OpenBuffer): refuse to proceed if less then 18 bytes of input Fixes bug #178. CWE ID: CWE-119
WM_SYMBOL midi *WildMidi_Open(const char *midifile) { uint8_t *mididata = NULL; uint32_t midisize = 0; uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A }; uint8_t xmi_hdr[] = { 'F', 'O', 'R', 'M' }; midi * ret = NULL; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (NULL); } if (midifile == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL filename)", 0); return (NULL); } if ((mididata = (uint8_t *) _WM_BufferFile(midifile, &midisize)) == NULL) { return (NULL); } if (midisize < 18) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0); return (NULL); } if (memcmp(mididata,"HMIMIDIP", 8) == 0) { ret = (void *) _WM_ParseNewHmp(mididata, midisize); } else if (memcmp(mididata, "HMI-MIDISONG061595", 18) == 0) { ret = (void *) _WM_ParseNewHmi(mididata, midisize); } else if (memcmp(mididata, mus_hdr, 4) == 0) { ret = (void *) _WM_ParseNewMus(mididata, midisize); } else if (memcmp(mididata, xmi_hdr, 4) == 0) { ret = (void *) _WM_ParseNewXmi(mididata, midisize); } else { ret = (void *) _WM_ParseNewMidi(mididata, midisize); } free(mididata); if (ret) { if (add_handle(ret) != 0) { WildMidi_Close(ret); ret = NULL; } } return (ret); }
169,369
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void test_burl_normalize (void) { buffer *psrc = buffer_init(); buffer *ptmp = buffer_init(); int flags; flags = HTTP_PARSEOPT_URL_NORMALIZE_UNRESERVED; run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("no-slash"), CONST_STR_LEN("no-slash")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/"), CONST_STR_LEN("/")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc"), CONST_STR_LEN("/abc")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/"), CONST_STR_LEN("/abc/")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/def"), CONST_STR_LEN("/abc/def")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?"), CONST_STR_LEN("/abc?")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d"), CONST_STR_LEN("/abc?d")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d="), CONST_STR_LEN("/abc?d=")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e"), CONST_STR_LEN("/abc?d=e")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&"), CONST_STR_LEN("/abc?d=e&")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f"), CONST_STR_LEN("/abc?d=e&f")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g"), CONST_STR_LEN("/abc?d=e&f=g")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#"), CONST_STR_LEN("/abc?d=e&f=g")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#any"), CONST_STR_LEN("/abc?d=e&f=g")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2F"), CONST_STR_LEN("/%2F")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2f"), CONST_STR_LEN("/%2F")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%20"), CONST_STR_LEN("/%20")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2b"), CONST_STR_LEN("/%2B")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2B"), CONST_STR_LEN("/%2B")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3a"), CONST_STR_LEN("/%3A")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3A"), CONST_STR_LEN("/%3A")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/~test%20ä_"), CONST_STR_LEN("/~test%20%C3%A4_")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\375"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\376"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\377"), "", (size_t)-2); flags = HTTP_PARSEOPT_URL_NORMALIZE_REQUIRED; run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/"), CONST_STR_LEN("/")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc"), CONST_STR_LEN("/abc")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/"), CONST_STR_LEN("/abc/")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/def"), CONST_STR_LEN("/abc/def")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?"), CONST_STR_LEN("/abc?")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d"), CONST_STR_LEN("/abc?d")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d="), CONST_STR_LEN("/abc?d=")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e"), CONST_STR_LEN("/abc?d=e")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&"), CONST_STR_LEN("/abc?d=e&")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f"), CONST_STR_LEN("/abc?d=e&f")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g"), CONST_STR_LEN("/abc?d=e&f=g")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#"), CONST_STR_LEN("/abc?d=e&f=g")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#any"), CONST_STR_LEN("/abc?d=e&f=g")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2F"), CONST_STR_LEN("/%2F")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2f"), CONST_STR_LEN("/%2F")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%20"), CONST_STR_LEN("/%20")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2b"), CONST_STR_LEN("/+")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2B"), CONST_STR_LEN("/+")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3a"), CONST_STR_LEN("/:")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3A"), CONST_STR_LEN("/:")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/~test%20ä_"), CONST_STR_LEN("/~test%20%C3%A4_")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\375"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\376"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\377"), "", (size_t)-2); flags |= HTTP_PARSEOPT_URL_NORMALIZE_CTRLS_REJECT; run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\a"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\t"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\r"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\177"), "", (size_t)-2); #if defined(__WIN32) || defined(__CYGWIN__) flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_BACKSLASH_TRANS; run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a\\b"), CONST_STR_LEN("/a/b")); #endif flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE; run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=/"), CONST_STR_LEN("/a/b?c=/")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=%2f"), CONST_STR_LEN("/a/b?c=/")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb"), CONST_STR_LEN("/a/b")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2Fb"), CONST_STR_LEN("/a/b")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb?c=/"), CONST_STR_LEN("/a/b?c=/")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb?c=%2f"), CONST_STR_LEN("/a/b?c=/")); flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE; flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_REJECT; run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2Fb"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=%2f"), CONST_STR_LEN("/a/b?c=/")); flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_REJECT; flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE; run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("./a/b"), CONST_STR_LEN("/a/b")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("../a/b"), CONST_STR_LEN("/a/b")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/./b"), CONST_STR_LEN("/a/b")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/../b"), CONST_STR_LEN("/b")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/."), CONST_STR_LEN("/a/b/")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/.."), CONST_STR_LEN("/a/")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/../b/.."), CONST_STR_LEN("/")); flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE; flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REJECT; run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("./a/b"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("../a/b"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/./b"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/../b"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/."), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/.."), "", (size_t)-2); flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REJECT; flags |= HTTP_PARSEOPT_URL_NORMALIZE_QUERY_20_PLUS; run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=d+e"), CONST_STR_LEN("/a/b?c=d+e")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=d%20e"), CONST_STR_LEN("/a/b?c=d+e")); flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_QUERY_20_PLUS; buffer_free(psrc); buffer_free(ptmp); } Commit Message: [core] fix abort in http-parseopts (fixes #2945) fix abort in server.http-parseopts with url-path-2f-decode enabled (thx stze) x-ref: "Security - SIGABRT during GET request handling with url-path-2f-decode enabled" https://redmine.lighttpd.net/issues/2945 CWE ID: CWE-190
static void test_burl_normalize (void) { buffer *psrc = buffer_init(); buffer *ptmp = buffer_init(); int flags; flags = HTTP_PARSEOPT_URL_NORMALIZE_UNRESERVED; run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("no-slash"), CONST_STR_LEN("no-slash")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/"), CONST_STR_LEN("/")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc"), CONST_STR_LEN("/abc")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/"), CONST_STR_LEN("/abc/")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/def"), CONST_STR_LEN("/abc/def")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?"), CONST_STR_LEN("/abc?")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d"), CONST_STR_LEN("/abc?d")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d="), CONST_STR_LEN("/abc?d=")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e"), CONST_STR_LEN("/abc?d=e")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&"), CONST_STR_LEN("/abc?d=e&")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f"), CONST_STR_LEN("/abc?d=e&f")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g"), CONST_STR_LEN("/abc?d=e&f=g")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#"), CONST_STR_LEN("/abc?d=e&f=g")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#any"), CONST_STR_LEN("/abc?d=e&f=g")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2F"), CONST_STR_LEN("/%2F")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2f"), CONST_STR_LEN("/%2F")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%20"), CONST_STR_LEN("/%20")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2b"), CONST_STR_LEN("/%2B")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2B"), CONST_STR_LEN("/%2B")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3a"), CONST_STR_LEN("/%3A")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3A"), CONST_STR_LEN("/%3A")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/~test%20ä_"), CONST_STR_LEN("/~test%20%C3%A4_")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\375"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\376"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\377"), "", (size_t)-2); flags = HTTP_PARSEOPT_URL_NORMALIZE_REQUIRED; run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/"), CONST_STR_LEN("/")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc"), CONST_STR_LEN("/abc")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/"), CONST_STR_LEN("/abc/")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/def"), CONST_STR_LEN("/abc/def")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?"), CONST_STR_LEN("/abc?")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d"), CONST_STR_LEN("/abc?d")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d="), CONST_STR_LEN("/abc?d=")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e"), CONST_STR_LEN("/abc?d=e")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&"), CONST_STR_LEN("/abc?d=e&")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f"), CONST_STR_LEN("/abc?d=e&f")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g"), CONST_STR_LEN("/abc?d=e&f=g")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#"), CONST_STR_LEN("/abc?d=e&f=g")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#any"), CONST_STR_LEN("/abc?d=e&f=g")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2F"), CONST_STR_LEN("/%2F")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2f"), CONST_STR_LEN("/%2F")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%20"), CONST_STR_LEN("/%20")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2b"), CONST_STR_LEN("/+")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2B"), CONST_STR_LEN("/+")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3a"), CONST_STR_LEN("/:")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3A"), CONST_STR_LEN("/:")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/~test%20ä_"), CONST_STR_LEN("/~test%20%C3%A4_")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\375"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\376"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\377"), "", (size_t)-2); flags |= HTTP_PARSEOPT_URL_NORMALIZE_CTRLS_REJECT; run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\a"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\t"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\r"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\177"), "", (size_t)-2); #if defined(__WIN32) || defined(__CYGWIN__) flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_BACKSLASH_TRANS; run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a\\b"), CONST_STR_LEN("/a/b")); #endif flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE; run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=/"), CONST_STR_LEN("/a/b?c=/")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=%2f"), CONST_STR_LEN("/a/b?c=/")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("%2f?"), CONST_STR_LEN("/?")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2f?"), CONST_STR_LEN("//?")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb"), CONST_STR_LEN("/a/b")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2Fb"), CONST_STR_LEN("/a/b")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb?c=/"), CONST_STR_LEN("/a/b?c=/")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb?c=%2f"), CONST_STR_LEN("/a/b?c=/")); flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE; flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_REJECT; run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2Fb"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=%2f"), CONST_STR_LEN("/a/b?c=/")); flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_REJECT; flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE; run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("./a/b"), CONST_STR_LEN("/a/b")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("../a/b"), CONST_STR_LEN("/a/b")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/./b"), CONST_STR_LEN("/a/b")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/../b"), CONST_STR_LEN("/b")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/."), CONST_STR_LEN("/a/b/")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/.."), CONST_STR_LEN("/a/")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/../b/.."), CONST_STR_LEN("/")); flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE; flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REJECT; run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("./a/b"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("../a/b"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/./b"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/../b"), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/."), "", (size_t)-2); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/.."), "", (size_t)-2); flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REJECT; flags |= HTTP_PARSEOPT_URL_NORMALIZE_QUERY_20_PLUS; run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=d+e"), CONST_STR_LEN("/a/b?c=d+e")); run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=d%20e"), CONST_STR_LEN("/a/b?c=d+e")); flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_QUERY_20_PLUS; buffer_free(psrc); buffer_free(ptmp); }
169,710
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: dissect_rpcap_packet (tvbuff_t *tvb, packet_info *pinfo, proto_tree *top_tree, proto_tree *parent_tree, gint offset, proto_item *top_item) { proto_tree *tree; proto_item *ti; nstime_t ts; tvbuff_t *new_tvb; guint caplen, len, frame_no; gint reported_length_remaining; ti = proto_tree_add_item (parent_tree, hf_packet, tvb, offset, 20, ENC_NA); tree = proto_item_add_subtree (ti, ett_packet); ts.secs = tvb_get_ntohl (tvb, offset); ts.nsecs = tvb_get_ntohl (tvb, offset + 4) * 1000; proto_tree_add_time(tree, hf_timestamp, tvb, offset, 8, &ts); offset += 8; caplen = tvb_get_ntohl (tvb, offset); ti = proto_tree_add_item (tree, hf_caplen, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; len = tvb_get_ntohl (tvb, offset); proto_tree_add_item (tree, hf_len, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; frame_no = tvb_get_ntohl (tvb, offset); proto_tree_add_item (tree, hf_npkt, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; proto_item_append_text (ti, ", Frame %u", frame_no); proto_item_append_text (top_item, " Frame %u", frame_no); /* * reported_length_remaining should not be -1, as offset is at * most right past the end of the available data in the packet. */ reported_length_remaining = tvb_reported_length_remaining (tvb, offset); if (caplen > (guint)reported_length_remaining) { expert_add_info(pinfo, ti, &ei_caplen_too_big); return; } new_tvb = tvb_new_subset (tvb, offset, caplen, len); if (decode_content && linktype != WTAP_ENCAP_UNKNOWN) { dissector_try_uint(wtap_encap_dissector_table, linktype, new_tvb, pinfo, top_tree); if (!info_added) { /* Only indicate when not added before */ /* Indicate RPCAP in the protocol column */ col_prepend_fence_fstr(pinfo->cinfo, COL_PROTOCOL, "R|"); /* Indicate RPCAP in the info column */ col_prepend_fence_fstr (pinfo->cinfo, COL_INFO, "Remote | "); info_added = TRUE; register_frame_end_routine(pinfo, rpcap_frame_end); } } else { if (linktype == WTAP_ENCAP_UNKNOWN) { proto_item_append_text (ti, ", Unknown link-layer type"); } call_dissector (data_handle, new_tvb, pinfo, top_tree); } } Commit Message: The WTAP_ENCAP_ETHERNET dissector needs to be passed a struct eth_phdr. We now require that. Make it so. Bug: 12440 Change-Id: Iffee520976b013800699bde3c6092a3e86be0d76 Reviewed-on: https://code.wireshark.org/review/15424 Reviewed-by: Guy Harris <[email protected]> CWE ID: CWE-20
dissect_rpcap_packet (tvbuff_t *tvb, packet_info *pinfo, proto_tree *top_tree, proto_tree *parent_tree, gint offset, proto_item *top_item) { proto_tree *tree; proto_item *ti; nstime_t ts; tvbuff_t *new_tvb; guint caplen, len, frame_no; gint reported_length_remaining; struct eth_phdr eth; void *phdr; ti = proto_tree_add_item (parent_tree, hf_packet, tvb, offset, 20, ENC_NA); tree = proto_item_add_subtree (ti, ett_packet); ts.secs = tvb_get_ntohl (tvb, offset); ts.nsecs = tvb_get_ntohl (tvb, offset + 4) * 1000; proto_tree_add_time(tree, hf_timestamp, tvb, offset, 8, &ts); offset += 8; caplen = tvb_get_ntohl (tvb, offset); ti = proto_tree_add_item (tree, hf_caplen, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; len = tvb_get_ntohl (tvb, offset); proto_tree_add_item (tree, hf_len, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; frame_no = tvb_get_ntohl (tvb, offset); proto_tree_add_item (tree, hf_npkt, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; proto_item_append_text (ti, ", Frame %u", frame_no); proto_item_append_text (top_item, " Frame %u", frame_no); /* * reported_length_remaining should not be -1, as offset is at * most right past the end of the available data in the packet. */ reported_length_remaining = tvb_reported_length_remaining (tvb, offset); if (caplen > (guint)reported_length_remaining) { expert_add_info(pinfo, ti, &ei_caplen_too_big); return; } new_tvb = tvb_new_subset (tvb, offset, caplen, len); if (decode_content && linktype != WTAP_ENCAP_UNKNOWN) { switch (linktype) { case WTAP_ENCAP_ETHERNET: eth.fcs_len = -1; /* Unknown whether we have an FCS */ phdr = &eth; break; default: phdr = NULL; break; } dissector_try_uint_new(wtap_encap_dissector_table, linktype, new_tvb, pinfo, top_tree, TRUE, phdr); if (!info_added) { /* Only indicate when not added before */ /* Indicate RPCAP in the protocol column */ col_prepend_fence_fstr(pinfo->cinfo, COL_PROTOCOL, "R|"); /* Indicate RPCAP in the info column */ col_prepend_fence_fstr (pinfo->cinfo, COL_INFO, "Remote | "); info_added = TRUE; register_frame_end_routine(pinfo, rpcap_frame_end); } } else { if (linktype == WTAP_ENCAP_UNKNOWN) { proto_item_append_text (ti, ", Unknown link-layer type"); } call_dissector (data_handle, new_tvb, pinfo, top_tree); } }
167,145
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool WebviewInfo::IsResourceWebviewAccessible( const Extension* extension, const std::string& partition_id, const std::string& relative_path) { if (!extension) return false; const WebviewInfo* info = GetResourcesInfo(*extension); if (!info) return false; bool partition_is_privileged = false; for (size_t i = 0; i < info->webview_privileged_partitions_.size(); ++i) { if (MatchPattern(partition_id, info->webview_privileged_partitions_[i])) { partition_is_privileged = true; break; } } return partition_is_privileged && extension->ResourceMatches( info->webview_accessible_resources_, relative_path); } Commit Message: <webview>: Update format for local file access in manifest.json The new format is: "webview" : { "partitions" : [ { "name" : "foo*", "accessible_resources" : ["a.html", "b.html"] }, { "name" : "bar", "accessible_resources" : ["a.html", "c.html"] } ] } BUG=340291 Review URL: https://codereview.chromium.org/151923005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@249640 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool WebviewInfo::IsResourceWebviewAccessible( const Extension* extension, const std::string& partition_id, const std::string& relative_path) { if (!extension) return false; const WebviewInfo* info = GetResourcesInfo(*extension); if (!info) return false; for (size_t i = 0; i < info->partition_items_.size(); ++i) { const PartitionItem* const item = info->partition_items_[i]; if (item->Matches(partition_id) && extension->ResourceMatches(item->accessible_resources(), relative_path)) { return true; } } return false; } void WebviewInfo::AddPartitionItem(scoped_ptr<PartitionItem> item) { partition_items_.push_back(item.release()); }
171,208
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int copy_verifier_state(struct bpf_verifier_state *dst_state, const struct bpf_verifier_state *src) { struct bpf_func_state *dst; int i, err; /* if dst has more stack frames then src frame, free them */ for (i = src->curframe + 1; i <= dst_state->curframe; i++) { free_func_state(dst_state->frame[i]); dst_state->frame[i] = NULL; } dst_state->curframe = src->curframe; for (i = 0; i <= src->curframe; i++) { dst = dst_state->frame[i]; if (!dst) { dst = kzalloc(sizeof(*dst), GFP_KERNEL); if (!dst) return -ENOMEM; dst_state->frame[i] = dst; } err = copy_func_state(dst, src->frame[i]); if (err) return err; } return 0; } Commit Message: bpf: prevent out of bounds speculation on pointer arithmetic Jann reported that the original commit back in b2157399cc98 ("bpf: prevent out-of-bounds speculation") was not sufficient to stop CPU from speculating out of bounds memory access: While b2157399cc98 only focussed on masking array map access for unprivileged users for tail calls and data access such that the user provided index gets sanitized from BPF program and syscall side, there is still a more generic form affected from BPF programs that applies to most maps that hold user data in relation to dynamic map access when dealing with unknown scalars or "slow" known scalars as access offset, for example: - Load a map value pointer into R6 - Load an index into R7 - Do a slow computation (e.g. with a memory dependency) that loads a limit into R8 (e.g. load the limit from a map for high latency, then mask it to make the verifier happy) - Exit if R7 >= R8 (mispredicted branch) - Load R0 = R6[R7] - Load R0 = R6[R0] For unknown scalars there are two options in the BPF verifier where we could derive knowledge from in order to guarantee safe access to the memory: i) While </>/<=/>= variants won't allow to derive any lower or upper bounds from the unknown scalar where it would be safe to add it to the map value pointer, it is possible through ==/!= test however. ii) another option is to transform the unknown scalar into a known scalar, for example, through ALU ops combination such as R &= <imm> followed by R |= <imm> or any similar combination where the original information from the unknown scalar would be destroyed entirely leaving R with a constant. The initial slow load still precedes the latter ALU ops on that register, so the CPU executes speculatively from that point. Once we have the known scalar, any compare operation would work then. A third option only involving registers with known scalars could be crafted as described in [0] where a CPU port (e.g. Slow Int unit) would be filled with many dependent computations such that the subsequent condition depending on its outcome has to wait for evaluation on its execution port and thereby executing speculatively if the speculated code can be scheduled on a different execution port, or any other form of mistraining as described in [1], for example. Given this is not limited to only unknown scalars, not only map but also stack access is affected since both is accessible for unprivileged users and could potentially be used for out of bounds access under speculation. In order to prevent any of these cases, the verifier is now sanitizing pointer arithmetic on the offset such that any out of bounds speculation would be masked in a way where the pointer arithmetic result in the destination register will stay unchanged, meaning offset masked into zero similar as in array_index_nospec() case. With regards to implementation, there are three options that were considered: i) new insn for sanitation, ii) push/pop insn and sanitation as inlined BPF, iii) reuse of ax register and sanitation as inlined BPF. Option i) has the downside that we end up using from reserved bits in the opcode space, but also that we would require each JIT to emit masking as native arch opcodes meaning mitigation would have slow adoption till everyone implements it eventually which is counter-productive. Option ii) and iii) have both in common that a temporary register is needed in order to implement the sanitation as inlined BPF since we are not allowed to modify the source register. While a push / pop insn in ii) would be useful to have in any case, it requires once again that every JIT needs to implement it first. While possible, amount of changes needed would also be unsuitable for a -stable patch. Therefore, the path which has fewer changes, less BPF instructions for the mitigation and does not require anything to be changed in the JITs is option iii) which this work is pursuing. The ax register is already mapped to a register in all JITs (modulo arm32 where it's mapped to stack as various other BPF registers there) and used in constant blinding for JITs-only so far. It can be reused for verifier rewrites under certain constraints. The interpreter's tmp "register" has therefore been remapped into extending the register set with hidden ax register and reusing that for a number of instructions that needed the prior temporary variable internally (e.g. div, mod). This allows for zero increase in stack space usage in the interpreter, and enables (restricted) generic use in rewrites otherwise as long as such a patchlet does not make use of these instructions. The sanitation mask is dynamic and relative to the offset the map value or stack pointer currently holds. There are various cases that need to be taken under consideration for the masking, e.g. such operation could look as follows: ptr += val or val += ptr or ptr -= val. Thus, the value to be sanitized could reside either in source or in destination register, and the limit is different depending on whether the ALU op is addition or subtraction and depending on the current known and bounded offset. The limit is derived as follows: limit := max_value_size - (smin_value + off). For subtraction: limit := umax_value + off. This holds because we do not allow any pointer arithmetic that would temporarily go out of bounds or would have an unknown value with mixed signed bounds where it is unclear at verification time whether the actual runtime value would be either negative or positive. For example, we have a derived map pointer value with constant offset and bounded one, so limit based on smin_value works because the verifier requires that statically analyzed arithmetic on the pointer must be in bounds, and thus it checks if resulting smin_value + off and umax_value + off is still within map value bounds at time of arithmetic in addition to time of access. Similarly, for the case of stack access we derive the limit as follows: MAX_BPF_STACK + off for subtraction and -off for the case of addition where off := ptr_reg->off + ptr_reg->var_off.value. Subtraction is a special case for the masking which can be in form of ptr += -val, ptr -= -val, or ptr -= val. In the first two cases where we know that the value is negative, we need to temporarily negate the value in order to do the sanitation on a positive value where we later swap the ALU op, and restore original source register if the value was in source. The sanitation of pointer arithmetic alone is still not fully sufficient as is, since a scenario like the following could happen ... PTR += 0x1000 (e.g. K-based imm) PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON PTR += 0x1000 PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON [...] ... which under speculation could end up as ... PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] [...] ... and therefore still access out of bounds. To prevent such case, the verifier is also analyzing safety for potential out of bounds access under speculative execution. Meaning, it is also simulating pointer access under truncation. We therefore "branch off" and push the current verification state after the ALU operation with known 0 to the verification stack for later analysis. Given the current path analysis succeeded it is likely that the one under speculation can be pruned. In any case, it is also subject to existing complexity limits and therefore anything beyond this point will be rejected. In terms of pruning, it needs to be ensured that the verification state from speculative execution simulation must never prune a non-speculative execution path, therefore, we mark verifier state accordingly at the time of push_stack(). If verifier detects out of bounds access under speculative execution from one of the possible paths that includes a truncation, it will reject such program. Given we mask every reg-based pointer arithmetic for unprivileged programs, we've been looking into how it could affect real-world programs in terms of size increase. As the majority of programs are targeted for privileged-only use case, we've unconditionally enabled masking (with its alu restrictions on top of it) for privileged programs for the sake of testing in order to check i) whether they get rejected in its current form, and ii) by how much the number of instructions and size will increase. We've tested this by using Katran, Cilium and test_l4lb from the kernel selftests. For Katran we've evaluated balancer_kern.o, Cilium bpf_lxc.o and an older test object bpf_lxc_opt_-DUNKNOWN.o and l4lb we've used test_l4lb.o as well as test_l4lb_noinline.o. We found that none of the programs got rejected by the verifier with this change, and that impact is rather minimal to none. balancer_kern.o had 13,904 bytes (1,738 insns) xlated and 7,797 bytes JITed before and after the change. Most complex program in bpf_lxc.o had 30,544 bytes (3,817 insns) xlated and 18,538 bytes JITed before and after and none of the other tail call programs in bpf_lxc.o had any changes either. For the older bpf_lxc_opt_-DUNKNOWN.o object we found a small increase from 20,616 bytes (2,576 insns) and 12,536 bytes JITed before to 20,664 bytes (2,582 insns) and 12,558 bytes JITed after the change. Other programs from that object file had similar small increase. Both test_l4lb.o had no change and remained at 6,544 bytes (817 insns) xlated and 3,401 bytes JITed and for test_l4lb_noinline.o constant at 5,080 bytes (634 insns) xlated and 3,313 bytes JITed. This can be explained in that LLVM typically optimizes stack based pointer arithmetic by using K-based operations and that use of dynamic map access is not overly frequent. However, in future we may decide to optimize the algorithm further under known guarantees from branch and value speculation. Latter seems also unclear in terms of prediction heuristics that today's CPUs apply as well as whether there could be collisions in e.g. the predictor's Value History/Pattern Table for triggering out of bounds access, thus masking is performed unconditionally at this point but could be subject to relaxation later on. We were generally also brainstorming various other approaches for mitigation, but the blocker was always lack of available registers at runtime and/or overhead for runtime tracking of limits belonging to a specific pointer. Thus, we found this to be minimally intrusive under given constraints. With that in place, a simple example with sanitized access on unprivileged load at post-verification time looks as follows: # bpftool prog dump xlated id 282 [...] 28: (79) r1 = *(u64 *)(r7 +0) 29: (79) r2 = *(u64 *)(r7 +8) 30: (57) r1 &= 15 31: (79) r3 = *(u64 *)(r0 +4608) 32: (57) r3 &= 1 33: (47) r3 |= 1 34: (2d) if r2 > r3 goto pc+19 35: (b4) (u32) r11 = (u32) 20479 | 36: (1f) r11 -= r2 | Dynamic sanitation for pointer 37: (4f) r11 |= r2 | arithmetic with registers 38: (87) r11 = -r11 | containing bounded or known 39: (c7) r11 s>>= 63 | scalars in order to prevent 40: (5f) r11 &= r2 | out of bounds speculation. 41: (0f) r4 += r11 | 42: (71) r4 = *(u8 *)(r4 +0) 43: (6f) r4 <<= r1 [...] For the case where the scalar sits in the destination register as opposed to the source register, the following code is emitted for the above example: [...] 16: (b4) (u32) r11 = (u32) 20479 17: (1f) r11 -= r2 18: (4f) r11 |= r2 19: (87) r11 = -r11 20: (c7) r11 s>>= 63 21: (5f) r2 &= r11 22: (0f) r2 += r0 23: (61) r0 = *(u32 *)(r2 +0) [...] JIT blinding example with non-conflicting use of r10: [...] d5: je 0x0000000000000106 _ d7: mov 0x0(%rax),%edi | da: mov $0xf153246,%r10d | Index load from map value and e0: xor $0xf153259,%r10 | (const blinded) mask with 0x1f. e7: and %r10,%rdi |_ ea: mov $0x2f,%r10d | f0: sub %rdi,%r10 | Sanitized addition. Both use r10 f3: or %rdi,%r10 | but do not interfere with each f6: neg %r10 | other. (Neither do these instructions f9: sar $0x3f,%r10 | interfere with the use of ax as temp fd: and %r10,%rdi | in interpreter.) 100: add %rax,%rdi |_ 103: mov 0x0(%rdi),%eax [...] Tested that it fixes Jann's reproducer, and also checked that test_verifier and test_progs suite with interpreter, JIT and JIT with hardening enabled on x86-64 and arm64 runs successfully. [0] Speculose: Analyzing the Security Implications of Speculative Execution in CPUs, Giorgi Maisuradze and Christian Rossow, https://arxiv.org/pdf/1801.04084.pdf [1] A Systematic Evaluation of Transient Execution Attacks and Defenses, Claudio Canella, Jo Van Bulck, Michael Schwarz, Moritz Lipp, Benjamin von Berg, Philipp Ortner, Frank Piessens, Dmitry Evtyushkin, Daniel Gruss, https://arxiv.org/pdf/1811.05441.pdf Fixes: b2157399cc98 ("bpf: prevent out-of-bounds speculation") Reported-by: Jann Horn <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Acked-by: Alexei Starovoitov <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> CWE ID: CWE-189
static int copy_verifier_state(struct bpf_verifier_state *dst_state, const struct bpf_verifier_state *src) { struct bpf_func_state *dst; int i, err; /* if dst has more stack frames then src frame, free them */ for (i = src->curframe + 1; i <= dst_state->curframe; i++) { free_func_state(dst_state->frame[i]); dst_state->frame[i] = NULL; } dst_state->speculative = src->speculative; dst_state->curframe = src->curframe; for (i = 0; i <= src->curframe; i++) { dst = dst_state->frame[i]; if (!dst) { dst = kzalloc(sizeof(*dst), GFP_KERNEL); if (!dst) return -ENOMEM; dst_state->frame[i] = dst; } err = copy_func_state(dst, src->frame[i]); if (err) return err; } return 0; }
170,241
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void *load_bytes(RBinFile *arch, const ut8 *buf, ut64 sz, ut64 loaddr, Sdb *sdb) { if (!buf || !sz || sz == UT64_MAX) { return NULL; } RBuffer *tbuf = r_buf_new (); r_buf_set_bytes (tbuf, buf, sz); struct r_bin_bflt_obj *res = r_bin_bflt_new_buf (tbuf); r_buf_free (tbuf); return res ? res : NULL; } Commit Message: Fix #6829 oob write because of using wrong struct CWE ID: CWE-119
static void *load_bytes(RBinFile *arch, const ut8 *buf, ut64 sz, ut64 loaddr, Sdb *sdb) { if (!buf || !sz || sz == UT64_MAX) { return NULL; } RBuffer *tbuf = r_buf_new (); if (!tbuf) { return NULL; } r_buf_set_bytes (tbuf, buf, sz); struct r_bin_bflt_obj *res = r_bin_bflt_new_buf (tbuf); r_buf_free (tbuf); return res ? res : NULL; }
168,363
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::unique_ptr<JSONObject> TransformPaintPropertyNode::ToJSON() const { auto json = JSONObject::Create(); if (Parent()) json->SetString("parent", String::Format("%p", Parent())); if (!state_.matrix.IsIdentity()) json->SetString("matrix", state_.matrix.ToString()); if (!state_.matrix.IsIdentityOrTranslation()) json->SetString("origin", state_.origin.ToString()); if (!state_.flattens_inherited_transform) json->SetBoolean("flattensInheritedTransform", false); if (state_.backface_visibility != BackfaceVisibility::kInherited) { json->SetString("backface", state_.backface_visibility == BackfaceVisibility::kVisible ? "visible" : "hidden"); } if (state_.rendering_context_id) { json->SetString("renderingContextId", String::Format("%x", state_.rendering_context_id)); } if (state_.direct_compositing_reasons != CompositingReason::kNone) { json->SetString( "directCompositingReasons", CompositingReason::ToString(state_.direct_compositing_reasons)); } if (state_.compositor_element_id) { json->SetString("compositorElementId", state_.compositor_element_id.ToString().c_str()); } if (state_.scroll) json->SetString("scroll", String::Format("%p", state_.scroll.get())); return json; } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID:
std::unique_ptr<JSONObject> TransformPaintPropertyNode::ToJSON() const { auto json = JSONObject::Create(); if (Parent()) json->SetString("parent", String::Format("%p", Parent())); if (!state_.matrix.IsIdentity()) json->SetString("matrix", state_.matrix.ToString()); if (!state_.matrix.IsIdentityOrTranslation()) json->SetString("origin", state_.origin.ToString()); if (!state_.flattens_inherited_transform) json->SetBoolean("flattensInheritedTransform", false); if (state_.backface_visibility != BackfaceVisibility::kInherited) { json->SetString("backface", state_.backface_visibility == BackfaceVisibility::kVisible ? "visible" : "hidden"); } if (state_.rendering_context_id) { json->SetString("renderingContextId", String::Format("%x", state_.rendering_context_id)); } if (state_.direct_compositing_reasons != CompositingReason::kNone) { json->SetString( "directCompositingReasons", CompositingReason::ToString(state_.direct_compositing_reasons)); } if (state_.compositor_element_id) { json->SetString("compositorElementId", state_.compositor_element_id.ToString().c_str()); } if (state_.scroll) json->SetString("scroll", String::Format("%p", state_.scroll)); return json; }
171,845
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: untrusted_launcher_response_callback (GtkDialog *dialog, int response_id, ActivateParametersDesktop *parameters) { GdkScreen *screen; char *uri; GFile *file; switch (response_id) { case RESPONSE_RUN: { screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window)); uri = nautilus_file_get_uri (parameters->file); DEBUG ("Launching untrusted launcher %s", uri); nautilus_launch_desktop_file (screen, uri, NULL, parameters->parent_window); g_free (uri); } break; case RESPONSE_MARK_TRUSTED: { file = nautilus_file_get_location (parameters->file); nautilus_file_mark_desktop_file_trusted (file, parameters->parent_window, TRUE, NULL, NULL); g_object_unref (file); } break; default: { /* Just destroy dialog */ } break; } gtk_widget_destroy (GTK_WIDGET (dialog)); activate_parameters_desktop_free (parameters); } Commit Message: mime-actions: use file metadata for trusting desktop files Currently we only trust desktop files that have the executable bit set, and don't replace the displayed icon or the displayed name until it's trusted, which prevents for running random programs by a malicious desktop file. However, the executable permission is preserved if the desktop file comes from a compressed file. To prevent this, add a metadata::trusted metadata to the file once the user acknowledges the file as trusted. This adds metadata to the file, which cannot be added unless it has access to the computer. Also remove the SHEBANG "trusted" content we were putting inside the desktop file, since that doesn't add more security since it can come with the file itself. https://bugzilla.gnome.org/show_bug.cgi?id=777991 CWE ID: CWE-20
untrusted_launcher_response_callback (GtkDialog *dialog, int response_id, ActivateParametersDesktop *parameters) { GdkScreen *screen; char *uri; GFile *file; switch (response_id) { case GTK_RESPONSE_OK: { file = nautilus_file_get_location (parameters->file); /* We need to do this in order to prevent malicious desktop files * with the executable bit already set. * See https://bugzilla.gnome.org/show_bug.cgi?id=777991 */ nautilus_file_set_metadata (parameters->file, NAUTILUS_METADATA_KEY_DESKTOP_FILE_TRUSTED, NULL, "yes"); nautilus_file_mark_desktop_file_executable (file, parameters->parent_window, TRUE, NULL, NULL); /* Need to force a reload of the attributes so is_trusted is marked * correctly. Not sure why the general monitor doesn't fire in this * case when setting the metadata */ nautilus_file_invalidate_all_attributes (parameters->file); screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window)); uri = nautilus_file_get_uri (parameters->file); DEBUG ("Launching untrusted launcher %s", uri); nautilus_launch_desktop_file (screen, uri, NULL, parameters->parent_window); g_free (uri); g_object_unref (file); } break; default: { /* Just destroy dialog */ } break; } gtk_widget_destroy (GTK_WIDGET (dialog)); activate_parameters_desktop_free (parameters); }
167,753
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: explicit CancelAndIgnoreNavigationForPluginFrameThrottle( NavigationHandle* handle) : NavigationThrottle(handle) {} Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper This CL is for the most part a mechanical change which extracts almost all the frame-based MimeHandlerView code out of ExtensionsGuestViewMessageFilter. This change both removes the current clutter form EGVMF as well as fixesa race introduced when the frame-based logic was added to EGVMF. The reason for the race was that EGVMF is destroyed on IO thread but all the access to it (for frame-based MHV) are from UI. [email protected],[email protected] Bug: 659750, 896679, 911161, 918861 Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda Reviewed-on: https://chromium-review.googlesource.com/c/1401451 Commit-Queue: Ehsan Karamad <[email protected]> Reviewed-by: James MacLean <[email protected]> Reviewed-by: Ehsan Karamad <[email protected]> Cr-Commit-Position: refs/heads/master@{#621155} CWE ID: CWE-362
explicit CancelAndIgnoreNavigationForPluginFrameThrottle(
173,036
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(FilesystemIterator, getFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(intern->flags & (SPL_FILE_DIR_KEY_MODE_MASK | SPL_FILE_DIR_CURRENT_MODE_MASK | SPL_FILE_DIR_OTHERS_MASK)); } /* }}} */ /* {{{ proto void FilesystemIterator::setFlags(long $flags) Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(FilesystemIterator, getFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(intern->flags & (SPL_FILE_DIR_KEY_MODE_MASK | SPL_FILE_DIR_CURRENT_MODE_MASK | SPL_FILE_DIR_OTHERS_MASK)); } /* }}} */ /* {{{ proto void FilesystemIterator::setFlags(long $flags)
167,044
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool DownloadItemImpl::CanOpenDownload() { const bool is_complete = GetState() == DownloadItem::COMPLETE; return (!IsDone() || is_complete) && !IsTemporary() && !file_externally_removed_; } Commit Message: Downloads : Fixed an issue of opening incorrect download file When one download overwrites another completed download, calling download.open in the old download causes the new download to open, which could be dangerous and undesirable. In this CL, we are trying to avoid this by blocking the opening of the old download. Bug: 793620 Change-Id: Ic948175756700ad7c08489c3cc347330daedb6f8 Reviewed-on: https://chromium-review.googlesource.com/826477 Reviewed-by: David Trainor <[email protected]> Reviewed-by: Xing Liu <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Commit-Queue: Shakti Sahu <[email protected]> Cr-Commit-Position: refs/heads/master@{#525810} CWE ID: CWE-20
bool DownloadItemImpl::CanOpenDownload() { const bool is_complete = GetState() == DownloadItem::COMPLETE; return (!IsDone() || is_complete) && !IsTemporary() && !file_externally_removed_ && delegate_->IsMostRecentDownloadItemAtFilePath(this); }
172,666
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PermissionsRemoveFunction::RunImpl() { scoped_ptr<Remove::Params> params(Remove::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); scoped_refptr<PermissionSet> permissions = helpers::UnpackPermissionSet(params->permissions, &error_); if (!permissions.get()) return false; const extensions::Extension* extension = GetExtension(); APIPermissionSet apis = permissions->apis(); for (APIPermissionSet::const_iterator i = apis.begin(); i != apis.end(); ++i) { if (!i->info()->supports_optional()) { error_ = ErrorUtils::FormatErrorMessage( kNotWhitelistedError, i->name()); return false; } } const PermissionSet* required = extension->required_permission_set(); scoped_refptr<PermissionSet> intersection( PermissionSet::CreateIntersection(permissions.get(), required)); if (!intersection->IsEmpty()) { error_ = kCantRemoveRequiredPermissionsError; results_ = Remove::Results::Create(false); return false; } PermissionsUpdater(profile()).RemovePermissions(extension, permissions.get()); results_ = Remove::Results::Create(true); return true; } Commit Message: Check prefs before allowing extension file access in the permissions API. [email protected] BUG=169632 Review URL: https://chromiumcodereview.appspot.com/11884008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176853 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool PermissionsRemoveFunction::RunImpl() { scoped_ptr<Remove::Params> params(Remove::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); ExtensionPrefs* prefs = ExtensionSystem::Get(profile_)->extension_prefs(); scoped_refptr<PermissionSet> permissions = helpers::UnpackPermissionSet(params->permissions, prefs->AllowFileAccess(extension_->id()), &error_); if (!permissions.get()) return false; const extensions::Extension* extension = GetExtension(); APIPermissionSet apis = permissions->apis(); for (APIPermissionSet::const_iterator i = apis.begin(); i != apis.end(); ++i) { if (!i->info()->supports_optional()) { error_ = ErrorUtils::FormatErrorMessage( kNotWhitelistedError, i->name()); return false; } } const PermissionSet* required = extension->required_permission_set(); scoped_refptr<PermissionSet> intersection( PermissionSet::CreateIntersection(permissions.get(), required)); if (!intersection->IsEmpty()) { error_ = kCantRemoveRequiredPermissionsError; results_ = Remove::Results::Create(false); return false; } PermissionsUpdater(profile()).RemovePermissions(extension, permissions.get()); results_ = Remove::Results::Create(true); return true; }
171,443
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void nfs4_open_release(void *calldata) { struct nfs4_opendata *data = calldata; struct nfs4_state *state = NULL; /* If this request hasn't been cancelled, do nothing */ if (data->cancelled == 0) goto out_free; /* In case of error, no cleanup! */ if (data->rpc_status != 0 || !data->rpc_done) goto out_free; /* In case we need an open_confirm, no cleanup! */ if (data->o_res.rflags & NFS4_OPEN_RESULT_CONFIRM) goto out_free; state = nfs4_opendata_to_nfs4_state(data); if (!IS_ERR(state)) nfs4_close_state(&data->path, state, data->o_arg.open_flags); out_free: nfs4_opendata_put(data); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
static void nfs4_open_release(void *calldata) { struct nfs4_opendata *data = calldata; struct nfs4_state *state = NULL; /* If this request hasn't been cancelled, do nothing */ if (data->cancelled == 0) goto out_free; /* In case of error, no cleanup! */ if (data->rpc_status != 0 || !data->rpc_done) goto out_free; /* In case we need an open_confirm, no cleanup! */ if (data->o_res.rflags & NFS4_OPEN_RESULT_CONFIRM) goto out_free; state = nfs4_opendata_to_nfs4_state(data); if (!IS_ERR(state)) nfs4_close_state(&data->path, state, data->o_arg.fmode); out_free: nfs4_opendata_put(data); }
165,698
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd, void *dummy, const char *arg) { const char *endp = ap_strrchr_c(arg, '>'); const char *limited_methods; void *tog = cmd->cmd->cmd_data; apr_int64_t limited = 0; apr_int64_t old_limited = cmd->limited; const char *errmsg; if (endp == NULL) { return unclosed_directive(cmd); } limited_methods = apr_pstrmemdup(cmd->temp_pool, arg, endp - arg); if (!limited_methods[0]) { return missing_container_arg(cmd); } while (limited_methods[0]) { char *method = ap_getword_conf(cmd->temp_pool, &limited_methods); int methnum; /* check for builtin or module registered method number */ methnum = ap_method_number_of(method); if (methnum == M_TRACE && !tog) { return "TRACE cannot be controlled by <Limit>, see TraceEnable"; } else if (methnum == M_INVALID) { /* method has not been registered yet, but resource restriction * is always checked before method handling, so register it. */ methnum = ap_method_register(cmd->pool, apr_pstrdup(cmd->pool, method)); } limited |= (AP_METHOD_BIT << methnum); } /* Killing two features with one function, * if (tog == NULL) <Limit>, else <LimitExcept> */ limited = tog ? ~limited : limited; if (!(old_limited & limited)) { return apr_pstrcat(cmd->pool, cmd->cmd->name, "> directive excludes all methods", NULL); } else if ((old_limited & limited) == old_limited) { return apr_pstrcat(cmd->pool, cmd->cmd->name, "> directive specifies methods already excluded", NULL); } cmd->limited &= limited; errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context); cmd->limited = old_limited; return errmsg; } Commit Message: core: Disallow Methods' registration at run time (.htaccess), they may be used only if registered at init time (httpd.conf). Calling ap_method_register() in children processes is not the right scope since it won't be shared for all requests. git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1807655 13f79535-47bb-0310-9956-ffa450edef68 CWE ID: CWE-416
AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd, void *dummy, const char *arg) { const char *endp = ap_strrchr_c(arg, '>'); const char *limited_methods; void *tog = cmd->cmd->cmd_data; apr_int64_t limited = 0; apr_int64_t old_limited = cmd->limited; const char *errmsg; if (endp == NULL) { return unclosed_directive(cmd); } limited_methods = apr_pstrmemdup(cmd->temp_pool, arg, endp - arg); if (!limited_methods[0]) { return missing_container_arg(cmd); } while (limited_methods[0]) { char *method = ap_getword_conf(cmd->temp_pool, &limited_methods); int methnum; /* check for builtin or module registered method number */ methnum = ap_method_number_of(method); if (methnum == M_TRACE && !tog) { return "TRACE cannot be controlled by <Limit>, see TraceEnable"; } else if (methnum == M_INVALID) { /* method has not been registered yet, but resource restriction * is always checked before method handling, so register it. */ if (cmd->pool == cmd->temp_pool) { /* In .htaccess, we can't globally register new methods. */ return apr_psprintf(cmd->pool, "Could not register method '%s' " "for %s from .htaccess configuration", method, cmd->cmd->name); } methnum = ap_method_register(cmd->pool, apr_pstrdup(cmd->pool, method)); } limited |= (AP_METHOD_BIT << methnum); } /* Killing two features with one function, * if (tog == NULL) <Limit>, else <LimitExcept> */ limited = tog ? ~limited : limited; if (!(old_limited & limited)) { return apr_pstrcat(cmd->pool, cmd->cmd->name, "> directive excludes all methods", NULL); } else if ((old_limited & limited) == old_limited) { return apr_pstrcat(cmd->pool, cmd->cmd->name, "> directive specifies methods already excluded", NULL); } cmd->limited &= limited; errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context); cmd->limited = old_limited; return errmsg; }
168,085
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: const std::string& AppControllerImpl::MaybeGetAndroidPackageName( const std::string& app_id) { const auto& package_name_it = android_package_map_.find(app_id); if (package_name_it != android_package_map_.end()) { return package_name_it->second; } ArcAppListPrefs* arc_prefs_ = ArcAppListPrefs::Get(profile_); if (!arc_prefs_) { return base::EmptyString(); } std::unique_ptr<ArcAppListPrefs::AppInfo> arc_info = arc_prefs_->GetApp(app_id); if (!arc_info) { return base::EmptyString(); } android_package_map_[app_id] = arc_info->package_name; return android_package_map_[app_id]; } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <[email protected]> Commit-Queue: Lucas Tenório <[email protected]> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416
const std::string& AppControllerImpl::MaybeGetAndroidPackageName( const std::string& AppControllerService::MaybeGetAndroidPackageName( const std::string& app_id) { const auto& package_name_it = android_package_map_.find(app_id); if (package_name_it != android_package_map_.end()) { return package_name_it->second; } ArcAppListPrefs* arc_prefs_ = ArcAppListPrefs::Get(profile_); if (!arc_prefs_) { return base::EmptyString(); } std::unique_ptr<ArcAppListPrefs::AppInfo> arc_info = arc_prefs_->GetApp(app_id); if (!arc_info) { return base::EmptyString(); } android_package_map_[app_id] = arc_info->package_name; return android_package_map_[app_id]; }
172,086
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur, struct idpair *idmap) { if (!(rold->live & REG_LIVE_READ)) /* explored state didn't use this */ return true; if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0) return true; if (rold->type == NOT_INIT) /* explored state can't have used this */ return true; if (rcur->type == NOT_INIT) return false; switch (rold->type) { case SCALAR_VALUE: if (rcur->type == SCALAR_VALUE) { /* new val must satisfy old val knowledge */ return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); } else { /* if we knew anything about the old value, we're not * equal, because we can't know anything about the * scalar value of the pointer in the new value. */ return rold->umin_value == 0 && rold->umax_value == U64_MAX && rold->smin_value == S64_MIN && rold->smax_value == S64_MAX && tnum_is_unknown(rold->var_off); } case PTR_TO_MAP_VALUE: /* If the new min/max/var_off satisfy the old ones and * everything else matches, we are OK. * We don't care about the 'id' value, because nothing * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL) */ return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); case PTR_TO_MAP_VALUE_OR_NULL: /* a PTR_TO_MAP_VALUE could be safe to use as a * PTR_TO_MAP_VALUE_OR_NULL into the same map. * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- * checked, doing so could have affected others with the same * id, and we can't check for that because we lost the id when * we converted to a PTR_TO_MAP_VALUE. */ if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL) return false; if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) return false; /* Check our ids match any regs they're supposed to */ return check_ids(rold->id, rcur->id, idmap); case PTR_TO_PACKET_META: case PTR_TO_PACKET: if (rcur->type != rold->type) return false; /* We must have at least as much range as the old ptr * did, so that any accesses which were safe before are * still safe. This is true even if old range < old off, * since someone could have accessed through (ptr - k), or * even done ptr -= k in a register, to get a safe access. */ if (rold->range > rcur->range) return false; /* If the offsets don't match, we can't trust our alignment; * nor can we be sure that we won't fall out of range. */ if (rold->off != rcur->off) return false; /* id relations must be preserved */ if (rold->id && !check_ids(rold->id, rcur->id, idmap)) return false; /* new val must satisfy old val knowledge */ return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); case PTR_TO_CTX: case CONST_PTR_TO_MAP: case PTR_TO_STACK: case PTR_TO_PACKET_END: /* Only valid matches are exact, which memcmp() above * would have accepted */ default: /* Don't know what's going on, just say it's not safe */ return false; } /* Shouldn't get here; if we do, say it's not safe */ WARN_ON_ONCE(1); return false; } Commit Message: bpf: don't prune branches when a scalar is replaced with a pointer This could be made safe by passing through a reference to env and checking for env->allow_ptr_leaks, but it would only work one way and is probably not worth the hassle - not doing it will not directly lead to program rejection. Fixes: f1174f77b50c ("bpf/verifier: rework value tracking") Signed-off-by: Jann Horn <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> CWE ID: CWE-119
static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur, struct idpair *idmap) { if (!(rold->live & REG_LIVE_READ)) /* explored state didn't use this */ return true; if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0) return true; if (rold->type == NOT_INIT) /* explored state can't have used this */ return true; if (rcur->type == NOT_INIT) return false; switch (rold->type) { case SCALAR_VALUE: if (rcur->type == SCALAR_VALUE) { /* new val must satisfy old val knowledge */ return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); } else { /* We're trying to use a pointer in place of a scalar. * Even if the scalar was unbounded, this could lead to * pointer leaks because scalars are allowed to leak * while pointers are not. We could make this safe in * special cases if root is calling us, but it's * probably not worth the hassle. */ return false; } case PTR_TO_MAP_VALUE: /* If the new min/max/var_off satisfy the old ones and * everything else matches, we are OK. * We don't care about the 'id' value, because nothing * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL) */ return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); case PTR_TO_MAP_VALUE_OR_NULL: /* a PTR_TO_MAP_VALUE could be safe to use as a * PTR_TO_MAP_VALUE_OR_NULL into the same map. * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- * checked, doing so could have affected others with the same * id, and we can't check for that because we lost the id when * we converted to a PTR_TO_MAP_VALUE. */ if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL) return false; if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) return false; /* Check our ids match any regs they're supposed to */ return check_ids(rold->id, rcur->id, idmap); case PTR_TO_PACKET_META: case PTR_TO_PACKET: if (rcur->type != rold->type) return false; /* We must have at least as much range as the old ptr * did, so that any accesses which were safe before are * still safe. This is true even if old range < old off, * since someone could have accessed through (ptr - k), or * even done ptr -= k in a register, to get a safe access. */ if (rold->range > rcur->range) return false; /* If the offsets don't match, we can't trust our alignment; * nor can we be sure that we won't fall out of range. */ if (rold->off != rcur->off) return false; /* id relations must be preserved */ if (rold->id && !check_ids(rold->id, rcur->id, idmap)) return false; /* new val must satisfy old val knowledge */ return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); case PTR_TO_CTX: case CONST_PTR_TO_MAP: case PTR_TO_STACK: case PTR_TO_PACKET_END: /* Only valid matches are exact, which memcmp() above * would have accepted */ default: /* Don't know what's going on, just say it's not safe */ return false; } /* Shouldn't get here; if we do, say it's not safe */ WARN_ON_ONCE(1); return false; }
167,642
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: GF_Err gf_isom_oinf_read_entry(void *entry, GF_BitStream *bs) { GF_OperatingPointsInformation* ptr = (GF_OperatingPointsInformation *)entry; u32 i, j, count; if (!ptr) return GF_BAD_PARAM; ptr->scalability_mask = gf_bs_read_u16(bs); gf_bs_read_int(bs, 2);//reserved count = gf_bs_read_int(bs, 6); for (i = 0; i < count; i++) { LHEVC_ProfileTierLevel *ptl; GF_SAFEALLOC(ptl, LHEVC_ProfileTierLevel); if (!ptl) return GF_OUT_OF_MEM; ptl->general_profile_space = gf_bs_read_int(bs, 2); ptl->general_tier_flag= gf_bs_read_int(bs, 1); ptl->general_profile_idc = gf_bs_read_int(bs, 5); ptl->general_profile_compatibility_flags = gf_bs_read_u32(bs); ptl->general_constraint_indicator_flags = gf_bs_read_long_int(bs, 48); ptl->general_level_idc = gf_bs_read_u8(bs); gf_list_add(ptr->profile_tier_levels, ptl); } count = gf_bs_read_u16(bs); for (i = 0; i < count; i++) { LHEVC_OperatingPoint *op; GF_SAFEALLOC(op, LHEVC_OperatingPoint); if (!op) return GF_OUT_OF_MEM; op->output_layer_set_idx = gf_bs_read_u16(bs); op->max_temporal_id = gf_bs_read_u8(bs); op->layer_count = gf_bs_read_u8(bs); for (j = 0; j < op->layer_count; j++) { op->layers_info[j].ptl_idx = gf_bs_read_u8(bs); op->layers_info[j].layer_id = gf_bs_read_int(bs, 6); op->layers_info[j].is_outputlayer = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE; op->layers_info[j].is_alternate_outputlayer = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE; } op->minPicWidth = gf_bs_read_u16(bs); op->minPicHeight = gf_bs_read_u16(bs); op->maxPicWidth = gf_bs_read_u16(bs); op->maxPicHeight = gf_bs_read_u16(bs); op->maxChromaFormat = gf_bs_read_int(bs, 2); op->maxBitDepth = gf_bs_read_int(bs, 3) + 8; gf_bs_read_int(bs, 1);//reserved op->frame_rate_info_flag = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE; op->bit_rate_info_flag = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE; if (op->frame_rate_info_flag) { op->avgFrameRate = gf_bs_read_u16(bs); gf_bs_read_int(bs, 6); //reserved op->constantFrameRate = gf_bs_read_int(bs, 2); } if (op->bit_rate_info_flag) { op->maxBitRate = gf_bs_read_u32(bs); op->avgBitRate = gf_bs_read_u32(bs); } gf_list_add(ptr->operating_points, op); } count = gf_bs_read_u8(bs); for (i = 0; i < count; i++) { LHEVC_DependentLayer *dep; GF_SAFEALLOC(dep, LHEVC_DependentLayer); if (!dep) return GF_OUT_OF_MEM; dep->dependent_layerID = gf_bs_read_u8(bs); dep->num_layers_dependent_on = gf_bs_read_u8(bs); for (j = 0; j < dep->num_layers_dependent_on; j++) dep->dependent_on_layerID[j] = gf_bs_read_u8(bs); for (j = 0; j < 16; j++) { if (ptr->scalability_mask & (1 << j)) dep->dimension_identifier[j] = gf_bs_read_u8(bs); } gf_list_add(ptr->dependency_layers, dep); } return GF_OK; } Commit Message: fix some exploitable overflows (#994, #997) CWE ID: CWE-119
GF_Err gf_isom_oinf_read_entry(void *entry, GF_BitStream *bs) { GF_OperatingPointsInformation* ptr = (GF_OperatingPointsInformation *)entry; u32 i, j, count; if (!ptr) return GF_BAD_PARAM; ptr->scalability_mask = gf_bs_read_u16(bs); gf_bs_read_int(bs, 2);//reserved count = gf_bs_read_int(bs, 6); for (i = 0; i < count; i++) { LHEVC_ProfileTierLevel *ptl; GF_SAFEALLOC(ptl, LHEVC_ProfileTierLevel); if (!ptl) return GF_OUT_OF_MEM; ptl->general_profile_space = gf_bs_read_int(bs, 2); ptl->general_tier_flag= gf_bs_read_int(bs, 1); ptl->general_profile_idc = gf_bs_read_int(bs, 5); ptl->general_profile_compatibility_flags = gf_bs_read_u32(bs); ptl->general_constraint_indicator_flags = gf_bs_read_long_int(bs, 48); ptl->general_level_idc = gf_bs_read_u8(bs); gf_list_add(ptr->profile_tier_levels, ptl); } count = gf_bs_read_u16(bs); for (i = 0; i < count; i++) { LHEVC_OperatingPoint *op; GF_SAFEALLOC(op, LHEVC_OperatingPoint); if (!op) return GF_OUT_OF_MEM; op->output_layer_set_idx = gf_bs_read_u16(bs); op->max_temporal_id = gf_bs_read_u8(bs); op->layer_count = gf_bs_read_u8(bs); if (op->layer_count > ARRAY_LENGTH(op->layers_info)) return GF_NON_COMPLIANT_BITSTREAM; for (j = 0; j < op->layer_count; j++) { op->layers_info[j].ptl_idx = gf_bs_read_u8(bs); op->layers_info[j].layer_id = gf_bs_read_int(bs, 6); op->layers_info[j].is_outputlayer = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE; op->layers_info[j].is_alternate_outputlayer = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE; } op->minPicWidth = gf_bs_read_u16(bs); op->minPicHeight = gf_bs_read_u16(bs); op->maxPicWidth = gf_bs_read_u16(bs); op->maxPicHeight = gf_bs_read_u16(bs); op->maxChromaFormat = gf_bs_read_int(bs, 2); op->maxBitDepth = gf_bs_read_int(bs, 3) + 8; gf_bs_read_int(bs, 1);//reserved op->frame_rate_info_flag = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE; op->bit_rate_info_flag = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE; if (op->frame_rate_info_flag) { op->avgFrameRate = gf_bs_read_u16(bs); gf_bs_read_int(bs, 6); //reserved op->constantFrameRate = gf_bs_read_int(bs, 2); } if (op->bit_rate_info_flag) { op->maxBitRate = gf_bs_read_u32(bs); op->avgBitRate = gf_bs_read_u32(bs); } gf_list_add(ptr->operating_points, op); } count = gf_bs_read_u8(bs); for (i = 0; i < count; i++) { LHEVC_DependentLayer *dep; GF_SAFEALLOC(dep, LHEVC_DependentLayer); if (!dep) return GF_OUT_OF_MEM; dep->dependent_layerID = gf_bs_read_u8(bs); dep->num_layers_dependent_on = gf_bs_read_u8(bs); for (j = 0; j < dep->num_layers_dependent_on; j++) dep->dependent_on_layerID[j] = gf_bs_read_u8(bs); for (j = 0; j < 16; j++) { if (ptr->scalability_mask & (1 << j)) dep->dimension_identifier[j] = gf_bs_read_u8(bs); } gf_list_add(ptr->dependency_layers, dep); } return GF_OK; }
169,306
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool GraphicsContext3D::getImageData(Image* image, GC3Denum format, GC3Denum type, bool premultiplyAlpha, bool ignoreGammaAndColorProfile, Vector<uint8_t>& outputVector) { if (!image) return false; CGImageRef cgImage; RetainPtr<CGImageRef> decodedImage; bool hasAlpha = image->isBitmapImage() ? static_cast<BitmapImage*>(image)->frameHasAlphaAtIndex(0) : true; if ((ignoreGammaAndColorProfile || (hasAlpha && !premultiplyAlpha)) && image->data()) { ImageSource decoder(ImageSource::AlphaNotPremultiplied, ignoreGammaAndColorProfile ? ImageSource::GammaAndColorProfileIgnored : ImageSource::GammaAndColorProfileApplied); decoder.setData(image->data(), true); if (!decoder.frameCount()) return false; decodedImage.adoptCF(decoder.createFrameAtIndex(0)); cgImage = decodedImage.get(); } else cgImage = image->nativeImageForCurrentFrame(); if (!cgImage) return false; size_t width = CGImageGetWidth(cgImage); size_t height = CGImageGetHeight(cgImage); if (!width || !height) return false; CGColorSpaceRef colorSpace = CGImageGetColorSpace(cgImage); CGColorSpaceModel model = CGColorSpaceGetModel(colorSpace); if (model == kCGColorSpaceModelIndexed) { RetainPtr<CGContextRef> bitmapContext; bitmapContext.adoptCF(CGBitmapContextCreate(0, width, height, 8, width * 4, deviceRGBColorSpaceRef(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host)); if (!bitmapContext) return false; CGContextSetBlendMode(bitmapContext.get(), kCGBlendModeCopy); CGContextSetInterpolationQuality(bitmapContext.get(), kCGInterpolationNone); CGContextDrawImage(bitmapContext.get(), CGRectMake(0, 0, width, height), cgImage); decodedImage.adoptCF(CGBitmapContextCreateImage(bitmapContext.get())); cgImage = decodedImage.get(); } size_t bitsPerComponent = CGImageGetBitsPerComponent(cgImage); size_t bitsPerPixel = CGImageGetBitsPerPixel(cgImage); if (bitsPerComponent != 8 && bitsPerComponent != 16) return false; if (bitsPerPixel % bitsPerComponent) return false; size_t componentsPerPixel = bitsPerPixel / bitsPerComponent; CGBitmapInfo bitInfo = CGImageGetBitmapInfo(cgImage); bool bigEndianSource = false; if (bitsPerComponent == 16) { switch (bitInfo & kCGBitmapByteOrderMask) { case kCGBitmapByteOrder16Big: bigEndianSource = true; break; case kCGBitmapByteOrder16Little: bigEndianSource = false; break; case kCGBitmapByteOrderDefault: bigEndianSource = true; break; default: return false; } } else { switch (bitInfo & kCGBitmapByteOrderMask) { case kCGBitmapByteOrder32Big: bigEndianSource = true; break; case kCGBitmapByteOrder32Little: bigEndianSource = false; break; case kCGBitmapByteOrderDefault: bigEndianSource = true; break; default: return false; } } AlphaOp neededAlphaOp = AlphaDoNothing; AlphaFormat alphaFormat = AlphaFormatNone; switch (CGImageGetAlphaInfo(cgImage)) { case kCGImageAlphaPremultipliedFirst: if (!premultiplyAlpha) neededAlphaOp = AlphaDoUnmultiply; alphaFormat = AlphaFormatFirst; break; case kCGImageAlphaFirst: if (premultiplyAlpha) neededAlphaOp = AlphaDoPremultiply; alphaFormat = AlphaFormatFirst; break; case kCGImageAlphaNoneSkipFirst: alphaFormat = AlphaFormatFirst; break; case kCGImageAlphaPremultipliedLast: if (!premultiplyAlpha) neededAlphaOp = AlphaDoUnmultiply; alphaFormat = AlphaFormatLast; break; case kCGImageAlphaLast: if (premultiplyAlpha) neededAlphaOp = AlphaDoPremultiply; alphaFormat = AlphaFormatLast; break; case kCGImageAlphaNoneSkipLast: alphaFormat = AlphaFormatLast; break; case kCGImageAlphaNone: alphaFormat = AlphaFormatNone; break; default: return false; } SourceDataFormat srcDataFormat = getSourceDataFormat(componentsPerPixel, alphaFormat, bitsPerComponent == 16, bigEndianSource); if (srcDataFormat == SourceFormatNumFormats) return false; RetainPtr<CFDataRef> pixelData; pixelData.adoptCF(CGDataProviderCopyData(CGImageGetDataProvider(cgImage))); if (!pixelData) return false; const UInt8* rgba = CFDataGetBytePtr(pixelData.get()); unsigned int packedSize; if (computeImageSizeInBytes(format, type, width, height, 1, &packedSize, 0) != GraphicsContext3D::NO_ERROR) return false; outputVector.resize(packedSize); unsigned int srcUnpackAlignment = 0; size_t bytesPerRow = CGImageGetBytesPerRow(cgImage); unsigned int padding = bytesPerRow - bitsPerPixel / 8 * width; if (padding) { srcUnpackAlignment = padding + 1; while (bytesPerRow % srcUnpackAlignment) ++srcUnpackAlignment; } bool rt = packPixels(rgba, srcDataFormat, width, height, srcUnpackAlignment, format, type, neededAlphaOp, outputVector.data()); return rt; } Commit Message: Set the access qualifier of two methods to query frame specific info of BitmapImage to protected. https://bugs.webkit.org/show_bug.cgi?id=90505 Patch by Huang Dongsung <[email protected]> on 2012-08-12 Reviewed by Eric Seidel. Following 4 methods are protected. size_t frameCount(); NativeImagePtr frameAtIndex(size_t); bool frameIsCompleteAtIndex(size_t); float frameDurationAtIndex(size_t); So, 2 methds also should be protected because the frame info is only specific of BitmapImage. bool frameHasAlphaAtIndex(size_t); ImageOrientation frameOrientationAtIndex(size_t); On the other hand, this patch amended GraphicsContext3DCG. - static_cast<BitmapImage*>(image)->frameHasAlphaAtIndex(0) + image->currentFrameHasAlpha() This patch does not affect PNG, JPEG, BMP, and WEBP because those images have only 0 indexed frame. Thus, GIF, and ICO are affected. However, an above query to get Alpha is for the image that is created by image->nativeImageForCurrentFrame(), so it is proper to use image->currentFrameHasAlpha() instead of image->frameHasAlphaAtIndex(0). No new tests, because it is hard to test. We need an animated GIF that one frame has alpha and another frame does not have alpha. However, I cannot find the animated GIF file that suffices the requirement. * platform/graphics/BitmapImage.h: (BitmapImage): * platform/graphics/cg/GraphicsContext3DCG.cpp: (WebCore::GraphicsContext3D::getImageData): git-svn-id: svn://svn.chromium.org/blink/trunk@125374 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
bool GraphicsContext3D::getImageData(Image* image, GC3Denum format, GC3Denum type, bool premultiplyAlpha, bool ignoreGammaAndColorProfile, Vector<uint8_t>& outputVector) { if (!image) return false; CGImageRef cgImage; RetainPtr<CGImageRef> decodedImage; bool hasAlpha = image->isBitmapImage() ? image->currentFrameHasAlpha() : true; if ((ignoreGammaAndColorProfile || (hasAlpha && !premultiplyAlpha)) && image->data()) { ImageSource decoder(ImageSource::AlphaNotPremultiplied, ignoreGammaAndColorProfile ? ImageSource::GammaAndColorProfileIgnored : ImageSource::GammaAndColorProfileApplied); decoder.setData(image->data(), true); if (!decoder.frameCount()) return false; decodedImage.adoptCF(decoder.createFrameAtIndex(0)); cgImage = decodedImage.get(); } else cgImage = image->nativeImageForCurrentFrame(); if (!cgImage) return false; size_t width = CGImageGetWidth(cgImage); size_t height = CGImageGetHeight(cgImage); if (!width || !height) return false; CGColorSpaceRef colorSpace = CGImageGetColorSpace(cgImage); CGColorSpaceModel model = CGColorSpaceGetModel(colorSpace); if (model == kCGColorSpaceModelIndexed) { RetainPtr<CGContextRef> bitmapContext; bitmapContext.adoptCF(CGBitmapContextCreate(0, width, height, 8, width * 4, deviceRGBColorSpaceRef(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host)); if (!bitmapContext) return false; CGContextSetBlendMode(bitmapContext.get(), kCGBlendModeCopy); CGContextSetInterpolationQuality(bitmapContext.get(), kCGInterpolationNone); CGContextDrawImage(bitmapContext.get(), CGRectMake(0, 0, width, height), cgImage); decodedImage.adoptCF(CGBitmapContextCreateImage(bitmapContext.get())); cgImage = decodedImage.get(); } size_t bitsPerComponent = CGImageGetBitsPerComponent(cgImage); size_t bitsPerPixel = CGImageGetBitsPerPixel(cgImage); if (bitsPerComponent != 8 && bitsPerComponent != 16) return false; if (bitsPerPixel % bitsPerComponent) return false; size_t componentsPerPixel = bitsPerPixel / bitsPerComponent; CGBitmapInfo bitInfo = CGImageGetBitmapInfo(cgImage); bool bigEndianSource = false; if (bitsPerComponent == 16) { switch (bitInfo & kCGBitmapByteOrderMask) { case kCGBitmapByteOrder16Big: bigEndianSource = true; break; case kCGBitmapByteOrder16Little: bigEndianSource = false; break; case kCGBitmapByteOrderDefault: bigEndianSource = true; break; default: return false; } } else { switch (bitInfo & kCGBitmapByteOrderMask) { case kCGBitmapByteOrder32Big: bigEndianSource = true; break; case kCGBitmapByteOrder32Little: bigEndianSource = false; break; case kCGBitmapByteOrderDefault: bigEndianSource = true; break; default: return false; } } AlphaOp neededAlphaOp = AlphaDoNothing; AlphaFormat alphaFormat = AlphaFormatNone; switch (CGImageGetAlphaInfo(cgImage)) { case kCGImageAlphaPremultipliedFirst: if (!premultiplyAlpha) neededAlphaOp = AlphaDoUnmultiply; alphaFormat = AlphaFormatFirst; break; case kCGImageAlphaFirst: if (premultiplyAlpha) neededAlphaOp = AlphaDoPremultiply; alphaFormat = AlphaFormatFirst; break; case kCGImageAlphaNoneSkipFirst: alphaFormat = AlphaFormatFirst; break; case kCGImageAlphaPremultipliedLast: if (!premultiplyAlpha) neededAlphaOp = AlphaDoUnmultiply; alphaFormat = AlphaFormatLast; break; case kCGImageAlphaLast: if (premultiplyAlpha) neededAlphaOp = AlphaDoPremultiply; alphaFormat = AlphaFormatLast; break; case kCGImageAlphaNoneSkipLast: alphaFormat = AlphaFormatLast; break; case kCGImageAlphaNone: alphaFormat = AlphaFormatNone; break; default: return false; } SourceDataFormat srcDataFormat = getSourceDataFormat(componentsPerPixel, alphaFormat, bitsPerComponent == 16, bigEndianSource); if (srcDataFormat == SourceFormatNumFormats) return false; RetainPtr<CFDataRef> pixelData; pixelData.adoptCF(CGDataProviderCopyData(CGImageGetDataProvider(cgImage))); if (!pixelData) return false; const UInt8* rgba = CFDataGetBytePtr(pixelData.get()); unsigned int packedSize; if (computeImageSizeInBytes(format, type, width, height, 1, &packedSize, 0) != GraphicsContext3D::NO_ERROR) return false; outputVector.resize(packedSize); unsigned int srcUnpackAlignment = 0; size_t bytesPerRow = CGImageGetBytesPerRow(cgImage); unsigned int padding = bytesPerRow - bitsPerPixel / 8 * width; if (padding) { srcUnpackAlignment = padding + 1; while (bytesPerRow % srcUnpackAlignment) ++srcUnpackAlignment; } bool rt = packPixels(rgba, srcDataFormat, width, height, srcUnpackAlignment, format, type, neededAlphaOp, outputVector.data()); return rt; }
170,960
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct sock *tcp_v6_syn_recv_sock(const struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst, struct request_sock *req_unhash, bool *own_req) { struct inet_request_sock *ireq; struct ipv6_pinfo *newnp; const struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6_txoptions *opt; struct tcp6_sock *newtcp6sk; struct inet_sock *newinet; struct tcp_sock *newtp; struct sock *newsk; #ifdef CONFIG_TCP_MD5SIG struct tcp_md5sig_key *key; #endif struct flowi6 fl6; if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = tcp_v4_syn_recv_sock(sk, skb, req, dst, req_unhash, own_req); if (!newsk) return NULL; newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newinet = inet_sk(newsk); newnp = inet6_sk(newsk); newtp = tcp_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->saddr = newsk->sk_v6_rcv_saddr; inet_csk(newsk)->icsk_af_ops = &ipv6_mapped; newsk->sk_backlog_rcv = tcp_v4_do_rcv; #ifdef CONFIG_TCP_MD5SIG newtp->af_specific = &tcp_sock_ipv6_mapped_specific; #endif newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = tcp_v6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb)); if (np->repflow) newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb)); /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, tcp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ tcp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } ireq = inet_rsk(req); if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_TCP); if (!dst) goto out; } newsk = tcp_create_openreq_child(sk, req, skb); if (!newsk) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, tcp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ newsk->sk_gso_type = SKB_GSO_TCPV6; ip6_dst_store(newsk, dst, NULL, NULL); inet6_sk_rx_dst_set(newsk, skb); newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newtp = tcp_sk(newsk); newinet = inet_sk(newsk); newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr; newnp->saddr = ireq->ir_v6_loc_addr; newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr; newsk->sk_bound_dev_if = ireq->ir_iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = tcp_v6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb)); if (np->repflow) newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb)); /* Clone native IPv6 options from listening socket (if any) Yes, keeping reference count would be much more clever, but we make one more one thing there: reattach optmem to newsk. */ opt = ireq->ipv6_opt; if (!opt) opt = rcu_dereference(np->opt); if (opt) { opt = ipv6_dup_options(newsk, opt); RCU_INIT_POINTER(newnp->opt, opt); } inet_csk(newsk)->icsk_ext_hdr_len = 0; if (opt) inet_csk(newsk)->icsk_ext_hdr_len = opt->opt_nflen + opt->opt_flen; tcp_ca_openreq_child(newsk, dst); tcp_sync_mss(newsk, dst_mtu(dst)); newtp->advmss = tcp_mss_clamp(tcp_sk(sk), dst_metric_advmss(dst)); tcp_initialize_rcv_mss(newsk); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; #ifdef CONFIG_TCP_MD5SIG /* Copy over the MD5 key from the original socket */ key = tcp_v6_md5_do_lookup(sk, &newsk->sk_v6_daddr); if (key) { /* We're using one, so create a matching key * on the newsk structure. If we fail to get * memory, then we end up not copying the key * across. Shucks. */ tcp_md5_do_add(newsk, (union tcp_md5_addr *)&newsk->sk_v6_daddr, AF_INET6, key->key, key->keylen, sk_gfp_mask(sk, GFP_ATOMIC)); } #endif if (__inet_inherit_port(sk, newsk) < 0) { inet_csk_prepare_forced_close(newsk); tcp_done(newsk); goto out; } *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash)); if (*own_req) { tcp_move_syn(newtp, req); /* Clone pktoptions received with SYN, if we own the req */ if (ireq->pktopts) { newnp->pktoptions = skb_clone(ireq->pktopts, sk_gfp_mask(sk, GFP_ATOMIC)); consume_skb(ireq->pktopts); ireq->pktopts = NULL; if (newnp->pktoptions) { tcp_v6_restore_cb(newnp->pktoptions); skb_set_owner_r(newnp->pktoptions, newsk); } } } return newsk; out_overflow: __NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: dst_release(dst); out: tcp_listendrop(sk); return NULL; } Commit Message: ipv6/dccp: do not inherit ipv6_mc_list from parent Like commit 657831ffc38e ("dccp/tcp: do not inherit mc_list from parent") we should clear ipv6_mc_list etc. for IPv6 sockets too. Cc: Eric Dumazet <[email protected]> Signed-off-by: Cong Wang <[email protected]> Acked-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static struct sock *tcp_v6_syn_recv_sock(const struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst, struct request_sock *req_unhash, bool *own_req) { struct inet_request_sock *ireq; struct ipv6_pinfo *newnp; const struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6_txoptions *opt; struct tcp6_sock *newtcp6sk; struct inet_sock *newinet; struct tcp_sock *newtp; struct sock *newsk; #ifdef CONFIG_TCP_MD5SIG struct tcp_md5sig_key *key; #endif struct flowi6 fl6; if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = tcp_v4_syn_recv_sock(sk, skb, req, dst, req_unhash, own_req); if (!newsk) return NULL; newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newinet = inet_sk(newsk); newnp = inet6_sk(newsk); newtp = tcp_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->saddr = newsk->sk_v6_rcv_saddr; inet_csk(newsk)->icsk_af_ops = &ipv6_mapped; newsk->sk_backlog_rcv = tcp_v4_do_rcv; #ifdef CONFIG_TCP_MD5SIG newtp->af_specific = &tcp_sock_ipv6_mapped_specific; #endif newnp->ipv6_mc_list = NULL; newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = tcp_v6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb)); if (np->repflow) newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb)); /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, tcp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ tcp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } ireq = inet_rsk(req); if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_TCP); if (!dst) goto out; } newsk = tcp_create_openreq_child(sk, req, skb); if (!newsk) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, tcp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ newsk->sk_gso_type = SKB_GSO_TCPV6; ip6_dst_store(newsk, dst, NULL, NULL); inet6_sk_rx_dst_set(newsk, skb); newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newtp = tcp_sk(newsk); newinet = inet_sk(newsk); newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr; newnp->saddr = ireq->ir_v6_loc_addr; newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr; newsk->sk_bound_dev_if = ireq->ir_iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; newnp->ipv6_mc_list = NULL; newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = tcp_v6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb)); if (np->repflow) newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb)); /* Clone native IPv6 options from listening socket (if any) Yes, keeping reference count would be much more clever, but we make one more one thing there: reattach optmem to newsk. */ opt = ireq->ipv6_opt; if (!opt) opt = rcu_dereference(np->opt); if (opt) { opt = ipv6_dup_options(newsk, opt); RCU_INIT_POINTER(newnp->opt, opt); } inet_csk(newsk)->icsk_ext_hdr_len = 0; if (opt) inet_csk(newsk)->icsk_ext_hdr_len = opt->opt_nflen + opt->opt_flen; tcp_ca_openreq_child(newsk, dst); tcp_sync_mss(newsk, dst_mtu(dst)); newtp->advmss = tcp_mss_clamp(tcp_sk(sk), dst_metric_advmss(dst)); tcp_initialize_rcv_mss(newsk); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; #ifdef CONFIG_TCP_MD5SIG /* Copy over the MD5 key from the original socket */ key = tcp_v6_md5_do_lookup(sk, &newsk->sk_v6_daddr); if (key) { /* We're using one, so create a matching key * on the newsk structure. If we fail to get * memory, then we end up not copying the key * across. Shucks. */ tcp_md5_do_add(newsk, (union tcp_md5_addr *)&newsk->sk_v6_daddr, AF_INET6, key->key, key->keylen, sk_gfp_mask(sk, GFP_ATOMIC)); } #endif if (__inet_inherit_port(sk, newsk) < 0) { inet_csk_prepare_forced_close(newsk); tcp_done(newsk); goto out; } *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash)); if (*own_req) { tcp_move_syn(newtp, req); /* Clone pktoptions received with SYN, if we own the req */ if (ireq->pktopts) { newnp->pktoptions = skb_clone(ireq->pktopts, sk_gfp_mask(sk, GFP_ATOMIC)); consume_skb(ireq->pktopts); ireq->pktopts = NULL; if (newnp->pktoptions) { tcp_v6_restore_cb(newnp->pktoptions); skb_set_owner_r(newnp->pktoptions, newsk); } } } return newsk; out_overflow: __NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: dst_release(dst); out: tcp_listendrop(sk); return NULL; }
168,128
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: jpc_ms_t *jpc_getms(jas_stream_t *in, jpc_cstate_t *cstate) { jpc_ms_t *ms; jpc_mstabent_t *mstabent; jas_stream_t *tmpstream; if (!(ms = jpc_ms_create(0))) { return 0; } /* Get the marker type. */ if (jpc_getuint16(in, &ms->id) || ms->id < JPC_MS_MIN || ms->id > JPC_MS_MAX) { jpc_ms_destroy(ms); return 0; } mstabent = jpc_mstab_lookup(ms->id); ms->ops = &mstabent->ops; /* Get the marker segment length and parameters if present. */ /* Note: It is tacitly assumed that a marker segment cannot have parameters unless it has a length field. That is, there cannot be a parameters field without a length field and vice versa. */ if (JPC_MS_HASPARMS(ms->id)) { /* Get the length of the marker segment. */ if (jpc_getuint16(in, &ms->len) || ms->len < 3) { jpc_ms_destroy(ms); return 0; } /* Calculate the length of the marker segment parameters. */ ms->len -= 2; /* Create and prepare a temporary memory stream from which to read the marker segment parameters. */ /* Note: This approach provides a simple way of ensuring that we never read beyond the end of the marker segment (even if the marker segment length is errantly set too small). */ if (!(tmpstream = jas_stream_memopen(0, 0))) { jpc_ms_destroy(ms); return 0; } if (jas_stream_copy(tmpstream, in, ms->len) || jas_stream_seek(tmpstream, 0, SEEK_SET) < 0) { jas_stream_close(tmpstream); jpc_ms_destroy(ms); return 0; } /* Get the marker segment parameters. */ if ((*ms->ops->getparms)(ms, cstate, tmpstream)) { ms->ops = 0; jpc_ms_destroy(ms); jas_stream_close(tmpstream); return 0; } if (jas_getdbglevel() > 0) { jpc_ms_dump(ms, stderr); } if (JAS_CAST(ulong, jas_stream_tell(tmpstream)) != ms->len) { jas_eprintf( "warning: trailing garbage in marker segment (%ld bytes)\n", ms->len - jas_stream_tell(tmpstream)); } /* Close the temporary stream. */ jas_stream_close(tmpstream); } else { /* There are no marker segment parameters. */ ms->len = 0; if (jas_getdbglevel() > 0) { jpc_ms_dump(ms, stderr); } } /* Update the code stream state information based on the type of marker segment read. */ /* Note: This is a bit of a hack, but I'm not going to define another type of virtual function for this one special case. */ if (ms->id == JPC_MS_SIZ) { cstate->numcomps = ms->parms.siz.numcomps; } return ms; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190
jpc_ms_t *jpc_getms(jas_stream_t *in, jpc_cstate_t *cstate) { jpc_ms_t *ms; jpc_mstabent_t *mstabent; jas_stream_t *tmpstream; if (!(ms = jpc_ms_create(0))) { return 0; } /* Get the marker type. */ if (jpc_getuint16(in, &ms->id) || ms->id < JPC_MS_MIN || ms->id > JPC_MS_MAX) { jpc_ms_destroy(ms); return 0; } mstabent = jpc_mstab_lookup(ms->id); ms->ops = &mstabent->ops; /* Get the marker segment length and parameters if present. */ /* Note: It is tacitly assumed that a marker segment cannot have parameters unless it has a length field. That is, there cannot be a parameters field without a length field and vice versa. */ if (JPC_MS_HASPARMS(ms->id)) { /* Get the length of the marker segment. */ if (jpc_getuint16(in, &ms->len) || ms->len < 3) { jpc_ms_destroy(ms); return 0; } /* Calculate the length of the marker segment parameters. */ ms->len -= 2; /* Create and prepare a temporary memory stream from which to read the marker segment parameters. */ /* Note: This approach provides a simple way of ensuring that we never read beyond the end of the marker segment (even if the marker segment length is errantly set too small). */ if (!(tmpstream = jas_stream_memopen(0, 0))) { jpc_ms_destroy(ms); return 0; } if (jas_stream_copy(tmpstream, in, ms->len) || jas_stream_seek(tmpstream, 0, SEEK_SET) < 0) { jas_stream_close(tmpstream); jpc_ms_destroy(ms); return 0; } /* Get the marker segment parameters. */ if ((*ms->ops->getparms)(ms, cstate, tmpstream)) { ms->ops = 0; jpc_ms_destroy(ms); jas_stream_close(tmpstream); return 0; } if (jas_getdbglevel() > 0) { jpc_ms_dump(ms, stderr); } if (JAS_CAST(jas_ulong, jas_stream_tell(tmpstream)) != ms->len) { jas_eprintf( "warning: trailing garbage in marker segment (%ld bytes)\n", ms->len - jas_stream_tell(tmpstream)); } /* Close the temporary stream. */ jas_stream_close(tmpstream); } else { /* There are no marker segment parameters. */ ms->len = 0; if (jas_getdbglevel() > 0) { jpc_ms_dump(ms, stderr); } } /* Update the code stream state information based on the type of marker segment read. */ /* Note: This is a bit of a hack, but I'm not going to define another type of virtual function for this one special case. */ if (ms->id == JPC_MS_SIZ) { cstate->numcomps = ms->parms.siz.numcomps; } return ms; }
168,716
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int em_grp45(struct x86_emulate_ctxt *ctxt) { int rc = X86EMUL_CONTINUE; switch (ctxt->modrm_reg) { case 2: /* call near abs */ { long int old_eip; old_eip = ctxt->_eip; ctxt->_eip = ctxt->src.val; ctxt->src.val = old_eip; rc = em_push(ctxt); break; } case 4: /* jmp abs */ ctxt->_eip = ctxt->src.val; break; case 5: /* jmp far */ rc = em_jmp_far(ctxt); break; case 6: /* push */ rc = em_push(ctxt); break; } return rc; } Commit Message: KVM: x86: Emulator fixes for eip canonical checks on near branches Before changing rip (during jmp, call, ret, etc.) the target should be asserted to be canonical one, as real CPUs do. During sysret, both target rsp and rip should be canonical. If any of these values is noncanonical, a #GP exception should occur. The exception to this rule are syscall and sysenter instructions in which the assigned rip is checked during the assignment to the relevant MSRs. This patch fixes the emulator to behave as real CPUs do for near branches. Far branches are handled by the next patch. This fixes CVE-2014-3647. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-264
static int em_grp45(struct x86_emulate_ctxt *ctxt) { int rc = X86EMUL_CONTINUE; switch (ctxt->modrm_reg) { case 2: /* call near abs */ { long int old_eip; old_eip = ctxt->_eip; rc = assign_eip_near(ctxt, ctxt->src.val); if (rc != X86EMUL_CONTINUE) break; ctxt->src.val = old_eip; rc = em_push(ctxt); break; } case 4: /* jmp abs */ rc = assign_eip_near(ctxt, ctxt->src.val); break; case 5: /* jmp far */ rc = em_jmp_far(ctxt); break; case 6: /* push */ rc = em_push(ctxt); break; } return rc; }
169,910
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int uhid_event(btif_hh_device_t *p_dev) { struct uhid_event ev; ssize_t ret; memset(&ev, 0, sizeof(ev)); if(!p_dev) { APPL_TRACE_ERROR("%s: Device not found",__FUNCTION__) return -1; } ret = read(p_dev->fd, &ev, sizeof(ev)); if (ret == 0) { APPL_TRACE_ERROR("%s: Read HUP on uhid-cdev %s", __FUNCTION__, strerror(errno)); return -EFAULT; } else if (ret < 0) { APPL_TRACE_ERROR("%s: Cannot read uhid-cdev: %s", __FUNCTION__, strerror(errno)); return -errno; } else if ((ev.type == UHID_OUTPUT) || (ev.type==UHID_OUTPUT_EV)) { if (ret < (ssize_t)sizeof(ev)) { APPL_TRACE_ERROR("%s: Invalid size read from uhid-dev: %ld != %lu", __FUNCTION__, ret, sizeof(ev.type)); return -EFAULT; } } switch (ev.type) { case UHID_START: APPL_TRACE_DEBUG("UHID_START from uhid-dev\n"); p_dev->ready_for_data = TRUE; break; case UHID_STOP: APPL_TRACE_DEBUG("UHID_STOP from uhid-dev\n"); p_dev->ready_for_data = FALSE; break; case UHID_OPEN: APPL_TRACE_DEBUG("UHID_OPEN from uhid-dev\n"); break; case UHID_CLOSE: APPL_TRACE_DEBUG("UHID_CLOSE from uhid-dev\n"); p_dev->ready_for_data = FALSE; break; case UHID_OUTPUT: if (ret < (ssize_t)(sizeof(ev.type) + sizeof(ev.u.output))) { APPL_TRACE_ERROR("%s: Invalid size read from uhid-dev: %zd < %zu", __FUNCTION__, ret, sizeof(ev.type) + sizeof(ev.u.output)); return -EFAULT; } APPL_TRACE_DEBUG("UHID_OUTPUT: Report type = %d, report_size = %d" ,ev.u.output.rtype, ev.u.output.size); if(ev.u.output.rtype == UHID_FEATURE_REPORT) btif_hh_setreport(p_dev, BTHH_FEATURE_REPORT, ev.u.output.size, ev.u.output.data); else if(ev.u.output.rtype == UHID_OUTPUT_REPORT) btif_hh_setreport(p_dev, BTHH_OUTPUT_REPORT, ev.u.output.size, ev.u.output.data); else btif_hh_setreport(p_dev, BTHH_INPUT_REPORT, ev.u.output.size, ev.u.output.data); break; case UHID_OUTPUT_EV: APPL_TRACE_DEBUG("UHID_OUTPUT_EV from uhid-dev\n"); break; case UHID_FEATURE: APPL_TRACE_DEBUG("UHID_FEATURE from uhid-dev\n"); break; case UHID_FEATURE_ANSWER: APPL_TRACE_DEBUG("UHID_FEATURE_ANSWER from uhid-dev\n"); break; default: APPL_TRACE_DEBUG("Invalid event from uhid-dev: %u\n", ev.type); } return 0; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static int uhid_event(btif_hh_device_t *p_dev) { struct uhid_event ev; ssize_t ret; memset(&ev, 0, sizeof(ev)); if(!p_dev) { APPL_TRACE_ERROR("%s: Device not found",__FUNCTION__) return -1; } ret = TEMP_FAILURE_RETRY(read(p_dev->fd, &ev, sizeof(ev))); if (ret == 0) { APPL_TRACE_ERROR("%s: Read HUP on uhid-cdev %s", __FUNCTION__, strerror(errno)); return -EFAULT; } else if (ret < 0) { APPL_TRACE_ERROR("%s: Cannot read uhid-cdev: %s", __FUNCTION__, strerror(errno)); return -errno; } else if ((ev.type == UHID_OUTPUT) || (ev.type==UHID_OUTPUT_EV)) { if (ret < (ssize_t)sizeof(ev)) { APPL_TRACE_ERROR("%s: Invalid size read from uhid-dev: %ld != %lu", __FUNCTION__, ret, sizeof(ev.type)); return -EFAULT; } } switch (ev.type) { case UHID_START: APPL_TRACE_DEBUG("UHID_START from uhid-dev\n"); p_dev->ready_for_data = TRUE; break; case UHID_STOP: APPL_TRACE_DEBUG("UHID_STOP from uhid-dev\n"); p_dev->ready_for_data = FALSE; break; case UHID_OPEN: APPL_TRACE_DEBUG("UHID_OPEN from uhid-dev\n"); break; case UHID_CLOSE: APPL_TRACE_DEBUG("UHID_CLOSE from uhid-dev\n"); p_dev->ready_for_data = FALSE; break; case UHID_OUTPUT: if (ret < (ssize_t)(sizeof(ev.type) + sizeof(ev.u.output))) { APPL_TRACE_ERROR("%s: Invalid size read from uhid-dev: %zd < %zu", __FUNCTION__, ret, sizeof(ev.type) + sizeof(ev.u.output)); return -EFAULT; } APPL_TRACE_DEBUG("UHID_OUTPUT: Report type = %d, report_size = %d" ,ev.u.output.rtype, ev.u.output.size); if(ev.u.output.rtype == UHID_FEATURE_REPORT) btif_hh_setreport(p_dev, BTHH_FEATURE_REPORT, ev.u.output.size, ev.u.output.data); else if(ev.u.output.rtype == UHID_OUTPUT_REPORT) btif_hh_setreport(p_dev, BTHH_OUTPUT_REPORT, ev.u.output.size, ev.u.output.data); else btif_hh_setreport(p_dev, BTHH_INPUT_REPORT, ev.u.output.size, ev.u.output.data); break; case UHID_OUTPUT_EV: APPL_TRACE_DEBUG("UHID_OUTPUT_EV from uhid-dev\n"); break; case UHID_FEATURE: APPL_TRACE_DEBUG("UHID_FEATURE from uhid-dev\n"); break; case UHID_FEATURE_ANSWER: APPL_TRACE_DEBUG("UHID_FEATURE_ANSWER from uhid-dev\n"); break; default: APPL_TRACE_DEBUG("Invalid event from uhid-dev: %u\n", ev.type); } return 0; }
173,432
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(xml_parser_create) { php_xml_parser_create_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } Commit Message: CWE ID: CWE-119
PHP_FUNCTION(xml_parser_create) { php_xml_parser_create_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); }
165,035