instruction
stringclasses
1 value
input
stringlengths
386
112k
output
stringclasses
3 values
__index_level_0__
int64
15
30k
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: status_t OMXNodeInstance::fillBuffer(OMX::buffer_id buffer, int fenceFd) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer); header->nFilledLen = 0; header->nOffset = 0; header->nFlags = 0; status_t res = storeFenceInMeta_l(header, fenceFd, kPortIndexOutput); if (res != OK) { CLOG_ERROR(fillBuffer::storeFenceInMeta, res, EMPTY_BUFFER(buffer, header, fenceFd)); return res; } { Mutex::Autolock _l(mDebugLock); mOutputBuffersWithCodec.add(header); CLOG_BUMPED_BUFFER(fillBuffer, WITH_STATS(EMPTY_BUFFER(buffer, header, fenceFd))); } OMX_ERRORTYPE err = OMX_FillThisBuffer(mHandle, header); if (err != OMX_ErrorNone) { CLOG_ERROR(fillBuffer, err, EMPTY_BUFFER(buffer, header, fenceFd)); Mutex::Autolock _l(mDebugLock); mOutputBuffersWithCodec.remove(header); } return StatusFromOMXError(err); } Vulnerability Type: Overflow +Priv CWE ID: CWE-119 Summary: omx/OMXNodeInstance.cpp in libstagefright in mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-08-01 does not validate the buffer port, which allows attackers to gain privileges via a crafted application, aka internal bug 28816827. Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
Medium
21,038
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: bool mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_, unsigned char*& buf, size_t& buflen) { assert(pReader); assert(pos >= 0); long long total, available; long status = pReader->Length(&total, &available); assert(status >= 0); assert((total < 0) || (available <= total)); if (status < 0) return false; long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); assert(len > 0); assert(len <= 8); assert((pos + len) <= available); if ((unsigned long)id != id_) return false; pos += len; // consume id const long long size_ = ReadUInt(pReader, pos, len); assert(size_ >= 0); assert(len > 0); assert(len <= 8); assert((pos + len) <= available); pos += len; // consume length of size of payload assert((pos + size_) <= available); const long buflen_ = static_cast<long>(size_); buf = new (std::nothrow) unsigned char[buflen_]; assert(buf); // TODO status = pReader->Read(pos, buflen_, buf); assert(status == 0); // TODO buflen = buflen_; pos += size_; // consume size of payload return true; } Vulnerability Type: DoS Exec Code Mem. Corr. CWE ID: CWE-20 Summary: libvpx in libwebm in mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-06-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted mkv file, aka internal bug 23167726. Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
High
15
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static void ParseCommon(map_string_t *settings, const char *conf_filename) { const char *value; value = get_map_string_item_or_NULL(settings, "WatchCrashdumpArchiveDir"); if (value) { g_settings_sWatchCrashdumpArchiveDir = xstrdup(value); remove_map_string_item(settings, "WatchCrashdumpArchiveDir"); } value = get_map_string_item_or_NULL(settings, "MaxCrashReportsSize"); if (value) { char *end; errno = 0; unsigned long ul = strtoul(value, &end, 10); if (errno || end == value || *end != '\0' || ul > INT_MAX) error_msg("Error parsing %s setting: '%s'", "MaxCrashReportsSize", value); else g_settings_nMaxCrashReportsSize = ul; remove_map_string_item(settings, "MaxCrashReportsSize"); } value = get_map_string_item_or_NULL(settings, "DumpLocation"); if (value) { g_settings_dump_location = xstrdup(value); remove_map_string_item(settings, "DumpLocation"); } else g_settings_dump_location = xstrdup(DEFAULT_DUMP_LOCATION); value = get_map_string_item_or_NULL(settings, "DeleteUploaded"); if (value) { g_settings_delete_uploaded = string_to_bool(value); remove_map_string_item(settings, "DeleteUploaded"); } value = get_map_string_item_or_NULL(settings, "AutoreportingEnabled"); if (value) { g_settings_autoreporting = string_to_bool(value); remove_map_string_item(settings, "AutoreportingEnabled"); } value = get_map_string_item_or_NULL(settings, "AutoreportingEvent"); if (value) { g_settings_autoreporting_event = xstrdup(value); remove_map_string_item(settings, "AutoreportingEvent"); } else g_settings_autoreporting_event = xstrdup("report_uReport"); value = get_map_string_item_or_NULL(settings, "ShortenedReporting"); if (value) { g_settings_shortenedreporting = string_to_bool(value); remove_map_string_item(settings, "ShortenedReporting"); } else g_settings_shortenedreporting = 0; GHashTableIter iter; const char *name; /*char *value; - already declared */ init_map_string_iter(&iter, settings); while (next_map_string_iter(&iter, &name, &value)) { error_msg("Unrecognized variable '%s' in '%s'", name, conf_filename); } } Vulnerability Type: +Info CWE ID: CWE-200 Summary: The event scripts in Automatic Bug Reporting Tool (ABRT) uses world-readable permission on a copy of sosreport file in problem directories, which allows local users to obtain sensitive information from /var/log/messages via unspecified vectors. Commit Message: make the dump directories owned by root by default It was discovered that the abrt event scripts create a user-readable copy of a sosreport file in abrt problem directories, and include excerpts of /var/log/messages selected by the user-controlled process name, leading to an information disclosure. This issue was discovered by Florian Weimer of Red Hat Product Security. Related: #1212868 Signed-off-by: Jakub Filak <[email protected]>
Low
14,260
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int cp2112_gpio_direction_output(struct gpio_chip *chip, unsigned offset, int value) { struct cp2112_device *dev = gpiochip_get_data(chip); struct hid_device *hdev = dev->hdev; u8 *buf = dev->in_out_buffer; unsigned long flags; int ret; spin_lock_irqsave(&dev->lock, flags); 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 fail; } 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 fail; } spin_unlock_irqrestore(&dev->lock, flags); /* * Set gpio value when output direction is already set, * as specified in AN495, Rev. 0.2, cpt. 4.4 */ cp2112_gpio_set(chip, offset, value); return 0; fail: spin_unlock_irqrestore(&dev->lock, flags); return ret < 0 ? ret : -EIO; } Vulnerability Type: DoS CWE ID: CWE-404 Summary: drivers/hid/hid-cp2112.c in the Linux kernel 4.9.x before 4.9.9 uses a spinlock without considering that sleeping is possible in a USB HID request callback, which allows local users to cause a denial of service (deadlock) via unspecified vectors. Commit Message: HID: cp2112: fix sleep-while-atomic A recent commit fixing DMA-buffers on stack added a shared transfer buffer protected by a spinlock. This is broken as the USB HID request callbacks can sleep. Fix this up by replacing the spinlock with a mutex. 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]>
Low
8,316
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static void jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf, int bufsize) { /* If this function is being called, the buffer should not have been initialized yet. */ assert(!stream->bufbase_); if (bufmode != JAS_STREAM_UNBUF) { /* The full- or line-buffered mode is being employed. */ if (!buf) { /* The caller has not specified a buffer to employ, so allocate one. */ if ((stream->bufbase_ = jas_malloc(JAS_STREAM_BUFSIZE + JAS_STREAM_MAXPUTBACK))) { stream->bufmode_ |= JAS_STREAM_FREEBUF; stream->bufsize_ = JAS_STREAM_BUFSIZE; } else { /* The buffer allocation has failed. Resort to unbuffered operation. */ stream->bufbase_ = stream->tinybuf_; stream->bufsize_ = 1; } } else { /* The caller has specified a buffer to employ. */ /* The buffer must be large enough to accommodate maximum putback. */ assert(bufsize > JAS_STREAM_MAXPUTBACK); stream->bufbase_ = JAS_CAST(uchar *, buf); stream->bufsize_ = bufsize - JAS_STREAM_MAXPUTBACK; } } else { /* The unbuffered mode is being employed. */ /* A buffer should not have been supplied by the caller. */ assert(!buf); /* Use a trivial one-character buffer. */ stream->bufbase_ = stream->tinybuf_; stream->bufsize_ = 1; } stream->bufstart_ = &stream->bufbase_[JAS_STREAM_MAXPUTBACK]; stream->ptr_ = stream->bufstart_; stream->cnt_ = 0; stream->bufmode_ |= bufmode & JAS_STREAM_BUFMODEMASK; } Vulnerability Type: DoS Overflow CWE ID: CWE-190 Summary: Integer overflow in jas_image.c in JasPer before 1.900.25 allows remote attackers to cause a denial of service (application crash) via a crafted file. 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.
Medium
23,747
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void CrosLibrary::TestApi::SetLoginLibrary( LoginLibrary* library, bool own) { library_->login_lib_.SetImpl(library, own); } Vulnerability Type: Exec Code CWE ID: CWE-189 Summary: The Program::getActiveUniformMaxLength function in libGLESv2/Program.cpp in libGLESv2.dll in the WebGLES library in Almost Native Graphics Layer Engine (ANGLE), as used in Mozilla Firefox 4.x before 4.0.1 on Windows and in the GPU process in Google Chrome before 10.0.648.205 on Windows, allows remote attackers to execute arbitrary code via unspecified vectors, related to an *off-by-three* error. Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
High
15,862
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void DatabaseImpl::IDBThreadHelper::CreateTransaction( int64_t transaction_id, const std::vector<int64_t>& object_store_ids, blink::WebIDBTransactionMode mode) { DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; connection_->database()->CreateTransaction(transaction_id, connection_.get(), object_store_ids, mode); } Vulnerability Type: CWE ID: CWE-416 Summary: A use after free in Blink in Google Chrome prior to 59.0.3071.104 for Mac, Windows, and Linux, and 59.0.3071.117 for Android, allowed a remote attacker to perform an out of bounds memory read via a crafted HTML page, aka an IndexedDB sandbox escape. Commit Message: [IndexedDB] Fixed transaction use-after-free vuln Bug: 725032 Change-Id: I689ded6c74d5563403587b149c3f3e02e807e4aa Reviewed-on: https://chromium-review.googlesource.com/518483 Reviewed-by: Joshua Bell <[email protected]> Commit-Queue: Daniel Murphy <[email protected]> Cr-Commit-Position: refs/heads/master@{#475952}
Medium
7,549
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: int lzxd_decompress(struct lzxd_stream *lzx, off_t out_bytes) { /* bitstream and huffman reading variables */ register unsigned int bit_buffer; register int bits_left, i=0; unsigned char *i_ptr, *i_end; register unsigned short sym; int match_length, length_footer, extra, verbatim_bits, bytes_todo; int this_run, main_element, aligned_bits, j; unsigned char *window, *runsrc, *rundest, buf[12]; unsigned int frame_size=0, end_frame, match_offset, window_posn; unsigned int R0, R1, R2; /* easy answers */ if (!lzx || (out_bytes < 0)) return MSPACK_ERR_ARGS; if (lzx->error) return lzx->error; /* flush out any stored-up bytes before we begin */ i = lzx->o_end - lzx->o_ptr; if ((off_t) i > out_bytes) i = (int) out_bytes; if (i) { if (lzx->sys->write(lzx->output, lzx->o_ptr, i) != i) { return lzx->error = MSPACK_ERR_WRITE; } lzx->o_ptr += i; lzx->offset += i; out_bytes -= i; } if (out_bytes == 0) return MSPACK_ERR_OK; /* restore local state */ RESTORE_BITS; window = lzx->window; window_posn = lzx->window_posn; R0 = lzx->R0; R1 = lzx->R1; R2 = lzx->R2; end_frame = (unsigned int)((lzx->offset + out_bytes) / LZX_FRAME_SIZE) + 1; while (lzx->frame < end_frame) { /* have we reached the reset interval? (if there is one?) */ if (lzx->reset_interval && ((lzx->frame % lzx->reset_interval) == 0)) { if (lzx->block_remaining) { D(("%d bytes remaining at reset interval", lzx->block_remaining)) return lzx->error = MSPACK_ERR_DECRUNCH; } /* re-read the intel header and reset the huffman lengths */ lzxd_reset_state(lzx); R0 = lzx->R0; R1 = lzx->R1; R2 = lzx->R2; } /* LZX DELTA format has chunk_size, not present in LZX format */ if (lzx->is_delta) { ENSURE_BITS(16); REMOVE_BITS(16); } /* read header if necessary */ if (!lzx->header_read) { /* read 1 bit. if bit=0, intel filesize = 0. * if bit=1, read intel filesize (32 bits) */ j = 0; READ_BITS(i, 1); if (i) { READ_BITS(i, 16); READ_BITS(j, 16); } lzx->intel_filesize = (i << 16) | j; lzx->header_read = 1; } /* calculate size of frame: all frames are 32k except the final frame * which is 32kb or less. this can only be calculated when lzx->length * has been filled in. */ frame_size = LZX_FRAME_SIZE; if (lzx->length && (lzx->length - lzx->offset) < (off_t)frame_size) { frame_size = lzx->length - lzx->offset; } /* decode until one more frame is available */ bytes_todo = lzx->frame_posn + frame_size - window_posn; while (bytes_todo > 0) { /* initialise new block, if one is needed */ if (lzx->block_remaining == 0) { /* realign if previous block was an odd-sized UNCOMPRESSED block */ if ((lzx->block_type == LZX_BLOCKTYPE_UNCOMPRESSED) && (lzx->block_length & 1)) { READ_IF_NEEDED; i_ptr++; } /* read block type (3 bits) and block length (24 bits) */ READ_BITS(lzx->block_type, 3); READ_BITS(i, 16); READ_BITS(j, 8); lzx->block_remaining = lzx->block_length = (i << 8) | j; /*D(("new block t%d len %u", lzx->block_type, lzx->block_length))*/ /* read individual block headers */ switch (lzx->block_type) { case LZX_BLOCKTYPE_ALIGNED: /* read lengths of and build aligned huffman decoding tree */ for (i = 0; i < 8; i++) { READ_BITS(j, 3); lzx->ALIGNED_len[i] = j; } BUILD_TABLE(ALIGNED); /* no break -- rest of aligned header is same as verbatim */ case LZX_BLOCKTYPE_VERBATIM: /* read lengths of and build main huffman decoding tree */ READ_LENGTHS(MAINTREE, 0, 256); READ_LENGTHS(MAINTREE, 256, LZX_NUM_CHARS + lzx->num_offsets); BUILD_TABLE(MAINTREE); /* if the literal 0xE8 is anywhere in the block... */ if (lzx->MAINTREE_len[0xE8] != 0) lzx->intel_started = 1; /* read lengths of and build lengths huffman decoding tree */ READ_LENGTHS(LENGTH, 0, LZX_NUM_SECONDARY_LENGTHS); BUILD_TABLE_MAYBE_EMPTY(LENGTH); break; case LZX_BLOCKTYPE_UNCOMPRESSED: /* because we can't assume otherwise */ lzx->intel_started = 1; /* read 1-16 (not 0-15) bits to align to bytes */ ENSURE_BITS(16); if (bits_left > 16) i_ptr -= 2; bits_left = 0; bit_buffer = 0; /* read 12 bytes of stored R0 / R1 / R2 values */ for (rundest = &buf[0], i = 0; i < 12; i++) { READ_IF_NEEDED; *rundest++ = *i_ptr++; } R0 = buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24); R1 = buf[4] | (buf[5] << 8) | (buf[6] << 16) | (buf[7] << 24); R2 = buf[8] | (buf[9] << 8) | (buf[10] << 16) | (buf[11] << 24); break; default: D(("bad block type")) return lzx->error = MSPACK_ERR_DECRUNCH; } } /* decode more of the block: * run = min(what's available, what's needed) */ this_run = lzx->block_remaining; if (this_run > bytes_todo) this_run = bytes_todo; /* assume we decode exactly this_run bytes, for now */ bytes_todo -= this_run; lzx->block_remaining -= this_run; /* decode at least this_run bytes */ switch (lzx->block_type) { case LZX_BLOCKTYPE_VERBATIM: while (this_run > 0) { READ_HUFFSYM(MAINTREE, main_element); if (main_element < LZX_NUM_CHARS) { /* literal: 0 to LZX_NUM_CHARS-1 */ window[window_posn++] = main_element; this_run--; } else { /* match: LZX_NUM_CHARS + ((slot<<3) | length_header (3 bits)) */ main_element -= LZX_NUM_CHARS; /* get match length */ match_length = main_element & LZX_NUM_PRIMARY_LENGTHS; if (match_length == LZX_NUM_PRIMARY_LENGTHS) { if (lzx->LENGTH_empty) { D(("LENGTH symbol needed but tree is empty")) return lzx->error = MSPACK_ERR_DECRUNCH; } READ_HUFFSYM(LENGTH, length_footer); match_length += length_footer; } match_length += LZX_MIN_MATCH; /* get match offset */ switch ((match_offset = (main_element >> 3))) { case 0: match_offset = R0; break; case 1: match_offset = R1; R1=R0; R0 = match_offset; break; case 2: match_offset = R2; R2=R0; R0 = match_offset; break; case 3: match_offset = 1; R2=R1; R1=R0; R0 = match_offset; break; default: extra = (match_offset >= 36) ? 17 : extra_bits[match_offset]; READ_BITS(verbatim_bits, extra); match_offset = position_base[match_offset] - 2 + verbatim_bits; R2 = R1; R1 = R0; R0 = match_offset; } /* LZX DELTA uses max match length to signal even longer match */ if (match_length == LZX_MAX_MATCH && lzx->is_delta) { int extra_len = 0; ENSURE_BITS(3); /* 4 entry huffman tree */ if (PEEK_BITS(1) == 0) { REMOVE_BITS(1); /* '0' -> 8 extra length bits */ READ_BITS(extra_len, 8); } else if (PEEK_BITS(2) == 2) { REMOVE_BITS(2); /* '10' -> 10 extra length bits + 0x100 */ READ_BITS(extra_len, 10); extra_len += 0x100; } else if (PEEK_BITS(3) == 6) { REMOVE_BITS(3); /* '110' -> 12 extra length bits + 0x500 */ READ_BITS(extra_len, 12); extra_len += 0x500; } else { REMOVE_BITS(3); /* '111' -> 15 extra length bits */ READ_BITS(extra_len, 15); } match_length += extra_len; } if ((window_posn + match_length) > lzx->window_size) { D(("match ran over window wrap")) return lzx->error = MSPACK_ERR_DECRUNCH; } /* copy match */ rundest = &window[window_posn]; i = match_length; /* does match offset wrap the window? */ if (match_offset > window_posn) { if (match_offset > lzx->offset && (match_offset - window_posn) > lzx->ref_data_size) { D(("match offset beyond LZX stream")) return lzx->error = MSPACK_ERR_DECRUNCH; } /* j = length from match offset to end of window */ j = match_offset - window_posn; if (j > (int) lzx->window_size) { D(("match offset beyond window boundaries")) return lzx->error = MSPACK_ERR_DECRUNCH; } runsrc = &window[lzx->window_size - j]; if (j < i) { /* if match goes over the window edge, do two copy runs */ i -= j; while (j-- > 0) *rundest++ = *runsrc++; runsrc = window; } while (i-- > 0) *rundest++ = *runsrc++; } else { runsrc = rundest - match_offset; while (i-- > 0) *rundest++ = *runsrc++; } this_run -= match_length; window_posn += match_length; } } /* while (this_run > 0) */ break; case LZX_BLOCKTYPE_ALIGNED: while (this_run > 0) { READ_HUFFSYM(MAINTREE, main_element); if (main_element < LZX_NUM_CHARS) { /* literal: 0 to LZX_NUM_CHARS-1 */ window[window_posn++] = main_element; this_run--; } else { /* match: LZX_NUM_CHARS + ((slot<<3) | length_header (3 bits)) */ main_element -= LZX_NUM_CHARS; /* get match length */ match_length = main_element & LZX_NUM_PRIMARY_LENGTHS; if (match_length == LZX_NUM_PRIMARY_LENGTHS) { if (lzx->LENGTH_empty) { D(("LENGTH symbol needed but tree is empty")) return lzx->error = MSPACK_ERR_DECRUNCH; } READ_HUFFSYM(LENGTH, length_footer); match_length += length_footer; } match_length += LZX_MIN_MATCH; /* get match offset */ switch ((match_offset = (main_element >> 3))) { case 0: match_offset = R0; break; case 1: match_offset = R1; R1 = R0; R0 = match_offset; break; case 2: match_offset = R2; R2 = R0; R0 = match_offset; break; default: extra = (match_offset >= 36) ? 17 : extra_bits[match_offset]; match_offset = position_base[match_offset] - 2; if (extra > 3) { /* verbatim and aligned bits */ extra -= 3; READ_BITS(verbatim_bits, extra); match_offset += (verbatim_bits << 3); READ_HUFFSYM(ALIGNED, aligned_bits); match_offset += aligned_bits; } else if (extra == 3) { /* aligned bits only */ READ_HUFFSYM(ALIGNED, aligned_bits); match_offset += aligned_bits; } else if (extra > 0) { /* extra==1, extra==2 */ /* verbatim bits only */ READ_BITS(verbatim_bits, extra); match_offset += verbatim_bits; } else /* extra == 0 */ { /* ??? not defined in LZX specification! */ match_offset = 1; } /* update repeated offset LRU queue */ R2 = R1; R1 = R0; R0 = match_offset; } /* LZX DELTA uses max match length to signal even longer match */ if (match_length == LZX_MAX_MATCH && lzx->is_delta) { int extra_len = 0; ENSURE_BITS(3); /* 4 entry huffman tree */ if (PEEK_BITS(1) == 0) { REMOVE_BITS(1); /* '0' -> 8 extra length bits */ READ_BITS(extra_len, 8); } else if (PEEK_BITS(2) == 2) { REMOVE_BITS(2); /* '10' -> 10 extra length bits + 0x100 */ READ_BITS(extra_len, 10); extra_len += 0x100; } else if (PEEK_BITS(3) == 6) { REMOVE_BITS(3); /* '110' -> 12 extra length bits + 0x500 */ READ_BITS(extra_len, 12); extra_len += 0x500; } else { REMOVE_BITS(3); /* '111' -> 15 extra length bits */ READ_BITS(extra_len, 15); } match_length += extra_len; } if ((window_posn + match_length) > lzx->window_size) { D(("match ran over window wrap")) return lzx->error = MSPACK_ERR_DECRUNCH; } /* copy match */ rundest = &window[window_posn]; i = match_length; /* does match offset wrap the window? */ if (match_offset > window_posn) { if (match_offset > lzx->offset && (match_offset - window_posn) > lzx->ref_data_size) { D(("match offset beyond LZX stream")) return lzx->error = MSPACK_ERR_DECRUNCH; } /* j = length from match offset to end of window */ j = match_offset - window_posn; if (j > (int) lzx->window_size) { D(("match offset beyond window boundaries")) return lzx->error = MSPACK_ERR_DECRUNCH; } runsrc = &window[lzx->window_size - j]; if (j < i) { /* if match goes over the window edge, do two copy runs */ i -= j; while (j-- > 0) *rundest++ = *runsrc++; runsrc = window; } while (i-- > 0) *rundest++ = *runsrc++; } else { runsrc = rundest - match_offset; while (i-- > 0) *rundest++ = *runsrc++; } this_run -= match_length; window_posn += match_length; } } /* while (this_run > 0) */ break; case LZX_BLOCKTYPE_UNCOMPRESSED: /* as this_run is limited not to wrap a frame, this also means it * won't wrap the window (as the window is a multiple of 32k) */ rundest = &window[window_posn]; window_posn += this_run; while (this_run > 0) { if ((i = i_end - i_ptr) == 0) { READ_IF_NEEDED; } else { if (i > this_run) i = this_run; lzx->sys->copy(i_ptr, rundest, (size_t) i); rundest += i; i_ptr += i; this_run -= i; } } break; default: return lzx->error = MSPACK_ERR_DECRUNCH; /* might as well */ } /* did the final match overrun our desired this_run length? */ if (this_run < 0) { if ((unsigned int)(-this_run) > lzx->block_remaining) { D(("overrun went past end of block by %d (%d remaining)", -this_run, lzx->block_remaining )) return lzx->error = MSPACK_ERR_DECRUNCH; } lzx->block_remaining -= -this_run; } } /* while (bytes_todo > 0) */ /* streams don't extend over frame boundaries */ if ((window_posn - lzx->frame_posn) != frame_size) { D(("decode beyond output frame limits! %d != %d", window_posn - lzx->frame_posn, frame_size)) return lzx->error = MSPACK_ERR_DECRUNCH; } /* re-align input bitstream */ if (bits_left > 0) ENSURE_BITS(16); if (bits_left & 15) REMOVE_BITS(bits_left & 15); /* check that we've used all of the previous frame first */ if (lzx->o_ptr != lzx->o_end) { D(("%ld avail bytes, new %d frame", (long)(lzx->o_end - lzx->o_ptr), frame_size)) return lzx->error = MSPACK_ERR_DECRUNCH; } /* does this intel block _really_ need decoding? */ if (lzx->intel_started && lzx->intel_filesize && (lzx->frame <= 32768) && (frame_size > 10)) { unsigned char *data = &lzx->e8_buf[0]; unsigned char *dataend = &lzx->e8_buf[frame_size - 10]; signed int curpos = lzx->intel_curpos; signed int filesize = lzx->intel_filesize; signed int abs_off, rel_off; /* copy e8 block to the e8 buffer and tweak if needed */ lzx->o_ptr = data; lzx->sys->copy(&lzx->window[lzx->frame_posn], data, frame_size); while (data < dataend) { if (*data++ != 0xE8) { curpos++; continue; } abs_off = data[0] | (data[1]<<8) | (data[2]<<16) | (data[3]<<24); if ((abs_off >= -curpos) && (abs_off < filesize)) { rel_off = (abs_off >= 0) ? abs_off - curpos : abs_off + filesize; data[0] = (unsigned char) rel_off; data[1] = (unsigned char) (rel_off >> 8); data[2] = (unsigned char) (rel_off >> 16); data[3] = (unsigned char) (rel_off >> 24); } data += 4; curpos += 5; } lzx->intel_curpos += frame_size; } else { lzx->o_ptr = &lzx->window[lzx->frame_posn]; if (lzx->intel_filesize) lzx->intel_curpos += frame_size; } lzx->o_end = &lzx->o_ptr[frame_size]; /* write a frame */ i = (out_bytes < (off_t)frame_size) ? (unsigned int)out_bytes : frame_size; if (lzx->sys->write(lzx->output, lzx->o_ptr, i) != i) { return lzx->error = MSPACK_ERR_WRITE; } lzx->o_ptr += i; lzx->offset += i; out_bytes -= i; /* advance frame start position */ lzx->frame_posn += frame_size; lzx->frame++; /* wrap window / frame position pointers */ if (window_posn == lzx->window_size) window_posn = 0; if (lzx->frame_posn == lzx->window_size) lzx->frame_posn = 0; } /* while (lzx->frame < end_frame) */ if (out_bytes) { D(("bytes left to output")) return lzx->error = MSPACK_ERR_DECRUNCH; } /* store local state */ STORE_BITS; lzx->window_posn = window_posn; lzx->R0 = R0; lzx->R1 = R1; lzx->R2 = R2; return MSPACK_ERR_OK; } Vulnerability Type: DoS CWE ID: CWE-189 Summary: Off-by-one error in the lzxd_decompress function in lzxd.c in libmspack before 0.5 allows remote attackers to cause a denial of service (buffer under-read and application crash) via a crafted CAB archive. Commit Message: Prevent a 1-byte underread of the input buffer if an odd-sized data block comes just before an uncompressed block header
Medium
12,386
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: PredictorEncodeRow(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s) { TIFFPredictorState *sp = PredictorState(tif); assert(sp != NULL); assert(sp->encodepfunc != NULL); assert(sp->encoderow != NULL); /* XXX horizontal differencing alters user's data XXX */ (*sp->encodepfunc)(tif, bp, cc); return (*sp->encoderow)(tif, bp, cc, s); } Vulnerability Type: Overflow CWE ID: CWE-119 Summary: tif_predict.h and tif_predict.c in libtiff 4.0.6 have assertions that can lead to assertion failures in debug mode, or buffer overflows in release mode, when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105, aka *Predictor heap-buffer-overflow.* Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team.
High
10,351
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: find_referral_tgs(kdc_realm_t *kdc_active_realm, krb5_kdc_req *request, krb5_principal *krbtgt_princ) { krb5_error_code retval = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; char **realms = NULL, *hostname = NULL; krb5_data srealm = request->server->realm; if (!is_referral_req(kdc_active_realm, request)) goto cleanup; hostname = data2string(krb5_princ_component(kdc_context, request->server, 1)); if (hostname == NULL) { retval = ENOMEM; goto cleanup; } /* If the hostname doesn't contain a '.', it's not a FQDN. */ if (strchr(hostname, '.') == NULL) goto cleanup; retval = krb5_get_host_realm(kdc_context, hostname, &realms); if (retval) { /* no match found */ kdc_err(kdc_context, retval, "unable to find realm of host"); goto cleanup; } /* Don't return a referral to the empty realm or the service realm. */ if (realms == NULL || realms[0] == '\0' || data_eq_string(srealm, realms[0])) { retval = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; goto cleanup; } retval = krb5_build_principal(kdc_context, krbtgt_princ, srealm.length, srealm.data, "krbtgt", realms[0], (char *)0); cleanup: krb5_free_host_realm(kdc_context, realms); free(hostname); return retval; } Vulnerability Type: DoS CWE ID: CWE-20 Summary: do_tgs_req.c in the Key Distribution Center (KDC) in MIT Kerberos 5 (aka krb5) 1.11 before 1.11.4, when a single-component realm name is used, allows remote authenticated users to cause a denial of service (daemon crash) via a TGS-REQ request that triggers an attempted cross-realm referral for a host-based service principal. Commit Message: KDC null deref due to referrals [CVE-2013-1417] An authenticated remote client can cause a KDC to crash by making a valid TGS-REQ to a KDC serving a realm with a single-component name. The process_tgs_req() function dereferences a null pointer because an unusual failure condition causes a helper function to return success. While attempting to provide cross-realm referrals for host-based service principals, the find_referral_tgs() function could return a TGS principal for a zero-length realm name (indicating that the hostname in the service principal has no known realm associated with it). Subsequently, the find_alternate_tgs() function would attempt to construct a path to this empty-string realm, and return success along with a null pointer in its output parameter. This happens because krb5_walk_realm_tree() returns a list of length one when it attempts to construct a transit path between a single-component realm and the empty-string realm. This list causes a loop in find_alternate_tgs() to iterate over zero elements, resulting in the unexpected output of a null pointer, which process_tgs_req() proceeds to dereference because there is no error condition. Add an error condition to find_referral_tgs() when krb5_get_host_realm() returns an empty realm name. Also add an error condition to find_alternate_tgs() to handle the length-one output from krb5_walk_realm_tree(). The vulnerable configuration is not likely to arise in practice. (Realm names that have a single component are likely to be test realms.) Releases prior to krb5-1.11 are not vulnerable. Thanks to Sol Jerome for reporting this problem. CVSSv2: AV:N/AC:M/Au:S/C:N/I:N/A:P/E:H/RL:O/RC:C (cherry picked from commit 3c7f1c21ffaaf6c90f1045f0f5440303c766acc0) ticket: 7668 version_fixed: 1.11.4 status: resolved
Low
2,360
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver, png_size_t png_struct_size) { #ifdef PNG_SETJMP_SUPPORTED jmp_buf tmp_jmp; /* to save current jump buffer */ #endif int i = 0; png_structp png_ptr=*ptr_ptr; if (png_ptr == NULL) return; do { if (user_png_ver[i] != png_libpng_ver[i]) { #ifdef PNG_LEGACY_SUPPORTED png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH; #else png_ptr->warning_fn = NULL; png_warning(png_ptr, "Application uses deprecated png_read_init() and should be" " recompiled."); break; #endif } } while (png_libpng_ver[i++]); png_debug(1, "in png_read_init_3"); #ifdef PNG_SETJMP_SUPPORTED /* Save jump buffer and error functions */ png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf)); #endif if (png_sizeof(png_struct) > png_struct_size) { png_destroy_struct(png_ptr); *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG); png_ptr = *ptr_ptr; } /* Reset all variables to 0 */ png_memset(png_ptr, 0, png_sizeof(png_struct)); #ifdef PNG_SETJMP_SUPPORTED /* Restore jump buffer */ png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf)); #endif /* Added at libpng-1.2.6 */ #ifdef PNG_SET_USER_LIMITS_SUPPORTED png_ptr->user_width_max = PNG_USER_WIDTH_MAX; png_ptr->user_height_max = PNG_USER_HEIGHT_MAX; #endif /* Initialize zbuf - compression buffer */ png_ptr->zbuf_size = PNG_ZBUF_SIZE; png_ptr->zstream.zalloc = png_zalloc; png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size); png_ptr->zstream.zalloc = png_zalloc; png_ptr->zstream.zfree = png_zfree; png_ptr->zstream.opaque = (voidpf)png_ptr; switch (inflateInit(&png_ptr->zstream)) { case Z_OK: /* Do nothing */ break; case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break; case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break; default: png_error(png_ptr, "Unknown zlib error"); } png_ptr->zstream.next_out = png_ptr->zbuf; png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL); } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: Multiple buffer overflows in the (1) png_set_PLTE and (2) png_get_PLTE functions in libpng before 1.0.64, 1.1.x and 1.2.x before 1.2.54, 1.3.x and 1.4.x before 1.4.17, 1.5.x before 1.5.24, and 1.6.x before 1.6.19 allow remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via a small bit-depth value in an IHDR (aka image header) chunk in a PNG image. 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}
High
17,635
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: PageGroupLoadDeferrer::PageGroupLoadDeferrer(Page* page, bool deferSelf) { const HashSet<Page*>& pages = page->group().pages(); HashSet<Page*>::const_iterator end = pages.end(); for (HashSet<Page*>::const_iterator it = pages.begin(); it != end; ++it) { Page* otherPage = *it; if ((deferSelf || otherPage != page)) { if (!otherPage->defersLoading()) { m_deferredFrames.append(otherPage->mainFrame()); for (Frame* frame = otherPage->mainFrame(); frame; frame = frame->tree()->traverseNext()) frame->document()->suspendScheduledTasks(ActiveDOMObject::WillDeferLoading); } } } size_t count = m_deferredFrames.size(); for (size_t i = 0; i < count; ++i) if (Page* page = m_deferredFrames[i]->page()) page->setDefersLoading(true); } Vulnerability Type: CWE ID: Summary: Blink, as used in Google Chrome before 30.0.1599.66, allows remote attackers to spoof the address bar via vectors involving a response with a 204 (aka No Content) status code, in conjunction with a delay in notifying the user of an attempted spoof. Commit Message: Don't wait to notify client of spoof attempt if a modal dialog is created. BUG=281256 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/23620020 git-svn-id: svn://svn.chromium.org/blink/trunk@157196 bbb929c8-8fbe-4397-9dbb-9b2b20218538
Medium
22,951
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: int main(int argc, char *argv[]) { struct mg_context *ctx; base::AtExitManager exit; base::WaitableEvent shutdown_event(false, false); CommandLine::Init(argc, argv); CommandLine* cmd_line = CommandLine::ForCurrentProcess(); #if defined(OS_POSIX) signal(SIGPIPE, SIG_IGN); #endif srand((unsigned int)time(NULL)); chrome::RegisterPathProvider(); TestTimeouts::Initialize(); InitChromeDriverLogging(*cmd_line); std::string port = "9515"; std::string root; std::string url_base; if (cmd_line->HasSwitch("port")) port = cmd_line->GetSwitchValueASCII("port"); if (cmd_line->HasSwitch("root")) root = cmd_line->GetSwitchValueASCII("root"); if (cmd_line->HasSwitch("url-base")) url_base = cmd_line->GetSwitchValueASCII("url-base"); webdriver::SessionManager* manager = webdriver::SessionManager::GetInstance(); manager->set_port(port); manager->set_url_base(url_base); ctx = mg_start(); if (!SetMongooseOptions(ctx, port, root)) { mg_stop(ctx); #if defined(OS_WIN) return WSAEADDRINUSE; #else return EADDRINUSE; #endif } webdriver::Dispatcher dispatcher(ctx, url_base); webdriver::InitCallbacks(ctx, &dispatcher, &shutdown_event, root.empty()); std::cout << "Started ChromeDriver" << std::endl << "port=" << port << std::endl; if (root.length()) { VLOG(1) << "Serving files from the current working directory"; } shutdown_event.Wait(); mg_stop(ctx); return (EXIT_SUCCESS); } Vulnerability Type: DoS CWE ID: CWE-399 Summary: Google V8, as used in Google Chrome before 13.0.782.107, does not properly perform const lookups, which allows remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via a crafted web site. Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
Medium
18,695
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void SplashOutputDev::drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, Stream *maskStr, int maskWidth, int maskHeight, GfxImageColorMap *maskColorMap) { double *ctm; SplashCoord mat[6]; SplashOutImageData imgData; SplashOutImageData imgMaskData; SplashColorMode srcMode; SplashBitmap *maskBitmap; Splash *maskSplash; SplashColor maskColor; GfxGray gray; GfxRGB rgb; #if SPLASH_CMYK GfxCMYK cmyk; #endif Guchar pix; int n, i; ctm = state->getCTM(); mat[0] = ctm[0]; mat[1] = ctm[1]; mat[2] = -ctm[2]; mat[3] = -ctm[3]; mat[4] = ctm[2] + ctm[4]; mat[5] = ctm[3] + ctm[5]; imgMaskData.imgStr = new ImageStream(maskStr, maskWidth, maskColorMap->getNumPixelComps(), maskColorMap->getBits()); imgMaskData.imgStr->reset(); imgMaskData.colorMap = maskColorMap; imgMaskData.maskColors = NULL; imgMaskData.colorMode = splashModeMono8; imgMaskData.width = maskWidth; imgMaskData.height = maskHeight; imgMaskData.y = 0; n = 1 << maskColorMap->getBits(); imgMaskData.lookup = (SplashColorPtr)gmalloc(n); for (i = 0; i < n; ++i) { pix = (Guchar)i; maskColorMap->getGray(&pix, &gray); imgMaskData.lookup[i] = colToByte(gray); } maskBitmap = new SplashBitmap(bitmap->getWidth(), bitmap->getHeight(), 1, splashModeMono8, gFalse); maskSplash = new Splash(maskBitmap, vectorAntialias); maskColor[0] = 0; maskSplash->clear(maskColor); maskSplash->drawImage(&imageSrc, &imgMaskData, splashModeMono8, gFalse, maskWidth, maskHeight, mat); delete imgMaskData.imgStr; maskStr->close(); gfree(imgMaskData.lookup); delete maskSplash; splash->setSoftMask(maskBitmap); imgData.imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); imgData.imgStr->reset(); imgData.colorMap = colorMap; imgData.maskColors = NULL; imgData.colorMode = colorMode; imgData.width = width; imgData.height = height; imgData.y = 0; imgData.lookup = NULL; if (colorMap->getNumPixelComps() == 1) { n = 1 << colorMap->getBits(); switch (colorMode) { case splashModeMono1: case splashModeMono8: imgData.lookup = (SplashColorPtr)gmalloc(n); for (i = 0; i < n; ++i) { pix = (Guchar)i; colorMap->getGray(&pix, &gray); imgData.lookup[i] = colToByte(gray); } break; case splashModeRGB8: case splashModeBGR8: imgData.lookup = (SplashColorPtr)gmalloc(3 * n); for (i = 0; i < n; ++i) { pix = (Guchar)i; colorMap->getRGB(&pix, &rgb); imgData.lookup[3*i] = colToByte(rgb.r); imgData.lookup[3*i+1] = colToByte(rgb.g); imgData.lookup[3*i+2] = colToByte(rgb.b); } break; case splashModeXBGR8: imgData.lookup = (SplashColorPtr)gmalloc(4 * n); for (i = 0; i < n; ++i) { pix = (Guchar)i; colorMap->getRGB(&pix, &rgb); imgData.lookup[4*i] = colToByte(rgb.r); imgData.lookup[4*i+1] = colToByte(rgb.g); imgData.lookup[4*i+2] = colToByte(rgb.b); imgData.lookup[4*i+3] = 255; } break; #if SPLASH_CMYK case splashModeCMYK8: imgData.lookup = (SplashColorPtr)gmalloc(4 * n); for (i = 0; i < n; ++i) { pix = (Guchar)i; colorMap->getCMYK(&pix, &cmyk); imgData.lookup[4*i] = colToByte(cmyk.c); imgData.lookup[4*i+1] = colToByte(cmyk.m); imgData.lookup[4*i+2] = colToByte(cmyk.y); imgData.lookup[4*i+3] = colToByte(cmyk.k); } break; #endif } } if (colorMode == splashModeMono1) { srcMode = splashModeMono8; } else { srcMode = colorMode; } splash->drawImage(&imageSrc, &imgData, srcMode, gFalse, width, height, mat); splash->setSoftMask(NULL); gfree(imgData.lookup); delete imgData.imgStr; str->close(); } Vulnerability Type: DoS Exec Code Overflow CWE ID: CWE-189 Summary: Multiple integer overflows in Poppler 0.10.5 and earlier allow remote attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a crafted PDF file, related to (1) glib/poppler-page.cc; (2) ArthurOutputDev.cc, (3) CairoOutputDev.cc, (4) GfxState.cc, (5) JBIG2Stream.cc, (6) PSOutputDev.cc, and (7) SplashOutputDev.cc in poppler/; and (8) SplashBitmap.cc, (9) Splash.cc, and (10) SplashFTFont.cc in splash/. NOTE: this may overlap CVE-2009-0791. Commit Message:
Medium
3,986
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void HttpBridge::MakeAsynchronousPost() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); base::AutoLock lock(fetch_state_lock_); DCHECK(!fetch_state_.request_completed); if (fetch_state_.aborted) return; fetch_state_.url_poster = new URLFetcher(url_for_request_, URLFetcher::POST, this); fetch_state_.url_poster->set_request_context(context_getter_for_request_); fetch_state_.url_poster->set_upload_data(content_type_, request_content_); fetch_state_.url_poster->set_extra_request_headers(extra_headers_); fetch_state_.url_poster->set_load_flags(net::LOAD_DO_NOT_SEND_COOKIES); fetch_state_.url_poster->Start(); } Vulnerability Type: DoS CWE ID: CWE-399 Summary: Use-after-free vulnerability in Google Chrome before 13.0.782.107 allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors related to media selectors. Commit Message: Use URLFetcher::Create instead of new in http_bridge.cc. This change modified http_bridge so that it uses a factory to construct the URLFetcher. Moreover, it modified sync_backend_host_unittest.cc to use an URLFetcher factory which will prevent access to www.example.com during the test. BUG=none TEST=sync_backend_host_unittest.cc Review URL: http://codereview.chromium.org/7053011 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87227 0039d316-1c4b-4281-b951-d872f2087c98
High
6,298
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs) { FILE *fp = fopen(dest_filename, "w"); if (!fp) return false; unsigned fd = 0; while (fd <= 99999) /* paranoia check */ { sprintf(source_filename + source_base_ofs, "fd/%u", fd); char *name = malloc_readlink(source_filename); if (!name) break; fprintf(fp, "%u:%s\n", fd, name); free(name); sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd); fd++; FILE *in = fopen(source_filename, "r"); if (!in) continue; char buf[128]; while (fgets(buf, sizeof(buf)-1, in)) { /* in case the line is not terminated, terminate it */ char *eol = strchrnul(buf, '\n'); eol[0] = '\n'; eol[1] = '\0'; fputs(buf, fp); } fclose(in); } fclose(fp); return true; } Vulnerability Type: CWE ID: CWE-59 Summary: Automatic Bug Reporting Tool (ABRT) allows local users to read, change the ownership of, or have other unspecified impact on arbitrary files via a symlink attack on (1) /var/tmp/abrt/*/maps, (2) /tmp/jvm-*/hs_error.log, (3) /proc/*/exe, (4) /etc/os-release in a chroot, or (5) an unspecified root directory related to librpm. Commit Message: ccpp: fix symlink race conditions Fix copy & chown race conditions Related: #1211835 Signed-off-by: Jakub Filak <[email protected]>
High
1,483
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int trusted_update(struct key *key, struct key_preparsed_payload *prep) { struct trusted_key_payload *p; struct trusted_key_payload *new_p; struct trusted_key_options *new_o; size_t datalen = prep->datalen; char *datablob; int ret = 0; if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) return -ENOKEY; p = key->payload.data[0]; if (!p->migratable) return -EPERM; if (datalen <= 0 || datalen > 32767 || !prep->data) return -EINVAL; datablob = kmalloc(datalen + 1, GFP_KERNEL); if (!datablob) return -ENOMEM; new_o = trusted_options_alloc(); if (!new_o) { ret = -ENOMEM; goto out; } new_p = trusted_payload_alloc(key); if (!new_p) { ret = -ENOMEM; goto out; } memcpy(datablob, prep->data, datalen); datablob[datalen] = '\0'; ret = datablob_parse(datablob, new_p, new_o); if (ret != Opt_update) { ret = -EINVAL; kzfree(new_p); goto out; } if (!new_o->keyhandle) { ret = -EINVAL; kzfree(new_p); goto out; } /* copy old key values, and reseal with new pcrs */ new_p->migratable = p->migratable; new_p->key_len = p->key_len; memcpy(new_p->key, p->key, p->key_len); dump_payload(p); dump_payload(new_p); ret = key_seal(new_p, new_o); if (ret < 0) { pr_info("trusted_key: key_seal failed (%d)\n", ret); kzfree(new_p); goto out; } if (new_o->pcrlock) { ret = pcrlock(new_o->pcrlock); if (ret < 0) { pr_info("trusted_key: pcrlock failed (%d)\n", ret); kzfree(new_p); goto out; } } rcu_assign_keypointer(key, new_p); call_rcu(&p->rcu, trusted_rcu_free); out: kzfree(datablob); kzfree(new_o); return ret; } Vulnerability Type: DoS CWE ID: CWE-20 Summary: The KEYS subsystem in the Linux kernel before 4.13.10 does not correctly synchronize the actions of updating versus finding a key in the *negative* state to avoid a race condition, which allows local users to cause a denial of service or possibly have unspecified other impact via crafted system calls. Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]>
High
16,616
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void SystemClipboard::WriteImage(Image* image, const KURL& url, const String& title) { DCHECK(image); PaintImage paint_image = image->PaintImageForCurrentFrame(); SkBitmap bitmap; if (sk_sp<SkImage> sk_image = paint_image.GetSkImage()) sk_image->asLegacyBitmap(&bitmap); if (bitmap.isNull()) return; if (!bitmap.getPixels()) return; clipboard_->WriteImage(mojom::ClipboardBuffer::kStandard, bitmap); if (url.IsValid() && !url.IsEmpty()) { #if !defined(OS_MACOSX) clipboard_->WriteBookmark(mojom::ClipboardBuffer::kStandard, url.GetString(), NonNullString(title)); #endif clipboard_->WriteHtml(mojom::ClipboardBuffer::kStandard, URLToImageMarkup(url, title), KURL()); } clipboard_->CommitWrite(mojom::ClipboardBuffer::kStandard); } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: Buffer overflow in the clipboard implementation in Google Chrome before 35.0.1916.153 allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors that trigger unexpected bitmap data, related to content/renderer/renderer_clipboard_client.cc and content/renderer/webclipboard_impl.cc. Commit Message: System Clipboard: Remove extraneous check for bitmap.getPixels() Bug 369621 originally led to this check being introduced via https://codereview.chromium.org/289573002/patch/40001/50002, but after https://crrev.com/c/1345809, I'm not sure that it's still necessary. This change succeeds when tested against the "minimized test case" provided in crbug.com/369621 's description, but I'm unsure how to make the minimized test case fail, so this doesn't prove that the change would succeed against the fuzzer's test case (which originally filed the bug). As I'm unable to view the relevant fuzzer test case, (see crbug.com/918705), I don't know exactly what may have caused the fuzzer to fail. Therefore, I've added a CHECK for the time being, so that we will be notified in canary if my assumption was incorrect. Bug: 369621 Change-Id: Ie9b47a4b38ba1ed47624de776015728e541d27f7 Reviewed-on: https://chromium-review.googlesource.com/c/1393436 Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Kai Ninomiya <[email protected]> Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Victor Costan <[email protected]> Cr-Commit-Position: refs/heads/master@{#619591}
High
13,308
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 2) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); ExceptionCode ec = 0; const String& strArg(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); TestObj* objArg(toTestObj(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(impl->methodThatRequiresAllArgsAndThrows(strArg, objArg, ec))); setDOMException(exec, ec); return JSValue::encode(result); } Vulnerability Type: DoS CWE ID: CWE-20 Summary: The HTML parser in Google Chrome before 12.0.742.112 does not properly address *lifetime and re-entrancy issues,* which allows remote attackers to cause a denial of service or possibly have unspecified other impact via unknown vectors. Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
High
17,214
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void PrintWebViewHelper::OnPrintForPrintPreview( const base::DictionaryValue& job_settings) { if (prep_frame_view_) return; if (!render_view()->GetWebView()) return; blink::WebFrame* main_frame = render_view()->GetWebView()->mainFrame(); if (!main_frame) return; blink::WebDocument document = main_frame->document(); blink::WebElement pdf_element = document.getElementById("pdf-viewer"); if (pdf_element.isNull()) { NOTREACHED(); return; } blink::WebLocalFrame* plugin_frame = pdf_element.document().frame(); blink::WebElement plugin_element = pdf_element; if (pdf_element.hasHTMLTagName("iframe")) { plugin_frame = blink::WebLocalFrame::fromFrameOwnerElement(pdf_element); plugin_element = delegate_->GetPdfElement(plugin_frame); if (plugin_element.isNull()) { NOTREACHED(); return; } } base::AutoReset<bool> set_printing_flag(&print_for_preview_, true); if (!UpdatePrintSettings(plugin_frame, plugin_element, job_settings)) { LOG(ERROR) << "UpdatePrintSettings failed"; DidFinishPrinting(FAIL_PRINT); return; } PrintMsg_Print_Params& print_params = print_pages_params_->params; print_params.printable_area = gfx::Rect(print_params.page_size); if (!RenderPagesForPrint(plugin_frame, plugin_element)) { LOG(ERROR) << "RenderPagesForPrint failed"; DidFinishPrinting(FAIL_PRINT); } } Vulnerability Type: DoS CWE ID: Summary: Multiple use-after-free vulnerabilities in the PrintWebViewHelper class in components/printing/renderer/print_web_view_helper.cc in Google Chrome before 45.0.2454.85 allow user-assisted remote attackers to cause a denial of service or possibly have unspecified other impact by triggering nested IPC messages during preparation for printing, as demonstrated by messages associated with PDF documents in conjunction with messages about printer capabilities. Commit Message: Crash on nested IPC handlers in PrintWebViewHelper Class is not designed to handle nested IPC. Regular flows also does not expect them. Still during printing of plugging them may show message boxes and start nested message loops. For now we are going just crash. If stats show us that this case is frequent we will have to do something more complicated. BUG=502562 Review URL: https://codereview.chromium.org/1228693002 Cr-Commit-Position: refs/heads/master@{#338100}
High
23,533
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: base::WaitableEvent* ProxyChannelDelegate::GetShutdownEvent() { return &shutdown_event_; } Vulnerability Type: DoS CWE ID: CWE-399 Summary: Use-after-free vulnerability in Google Chrome before 22.0.1229.79 allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors involving SVG text references. Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
High
22,996
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int fixup_bpf_calls(struct bpf_verifier_env *env) { struct bpf_prog *prog = env->prog; struct bpf_insn *insn = prog->insnsi; const struct bpf_func_proto *fn; const int insn_cnt = prog->len; const struct bpf_map_ops *ops; struct bpf_insn_aux_data *aux; struct bpf_insn insn_buf[16]; struct bpf_prog *new_prog; struct bpf_map *map_ptr; int i, cnt, delta = 0; for (i = 0; i < insn_cnt; i++, insn++) { if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || insn->code == (BPF_ALU | BPF_MOD | BPF_X) || insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; struct bpf_insn mask_and_div[] = { BPF_MOV32_REG(insn->src_reg, insn->src_reg), /* Rx div 0 -> 0 */ BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2), BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), BPF_JMP_IMM(BPF_JA, 0, 0, 1), *insn, }; struct bpf_insn mask_and_mod[] = { BPF_MOV32_REG(insn->src_reg, insn->src_reg), /* Rx mod 0 -> Rx */ BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1), *insn, }; struct bpf_insn *patchlet; if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { patchlet = mask_and_div + (is64 ? 1 : 0); cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0); } else { patchlet = mask_and_mod + (is64 ? 1 : 0); cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0); } new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } if (BPF_CLASS(insn->code) == BPF_LD && (BPF_MODE(insn->code) == BPF_ABS || BPF_MODE(insn->code) == BPF_IND)) { cnt = env->ops->gen_ld_abs(insn, insn_buf); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } if (insn->code != (BPF_JMP | BPF_CALL)) continue; if (insn->src_reg == BPF_PSEUDO_CALL) continue; if (insn->imm == BPF_FUNC_get_route_realm) prog->dst_needed = 1; if (insn->imm == BPF_FUNC_get_prandom_u32) bpf_user_rnd_init_once(); if (insn->imm == BPF_FUNC_override_return) prog->kprobe_override = 1; if (insn->imm == BPF_FUNC_tail_call) { /* If we tail call into other programs, we * cannot make any assumptions since they can * be replaced dynamically during runtime in * the program array. */ prog->cb_access = 1; env->prog->aux->stack_depth = MAX_BPF_STACK; env->prog->aux->max_pkt_offset = MAX_PACKET_OFF; /* mark bpf_tail_call as different opcode to avoid * conditional branch in the interpeter for every normal * call and to prevent accidental JITing by JIT compiler * that doesn't support bpf_tail_call yet */ insn->imm = 0; insn->code = BPF_JMP | BPF_TAIL_CALL; aux = &env->insn_aux_data[i + delta]; if (!bpf_map_ptr_unpriv(aux)) continue; /* instead of changing every JIT dealing with tail_call * emit two extra insns: * if (index >= max_entries) goto out; * index &= array->index_mask; * to avoid out-of-bounds cpu speculation */ if (bpf_map_ptr_poisoned(aux)) { verbose(env, "tail_call abusing map_ptr\n"); return -EINVAL; } map_ptr = BPF_MAP_PTR(aux->map_state); insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, map_ptr->max_entries, 2); insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, container_of(map_ptr, struct bpf_array, map)->index_mask); insn_buf[2] = *insn; cnt = 3; new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup * and other inlining handlers are currently limited to 64 bit * only. */ if (prog->jit_requested && BITS_PER_LONG == 64 && (insn->imm == BPF_FUNC_map_lookup_elem || insn->imm == BPF_FUNC_map_update_elem || insn->imm == BPF_FUNC_map_delete_elem || insn->imm == BPF_FUNC_map_push_elem || insn->imm == BPF_FUNC_map_pop_elem || insn->imm == BPF_FUNC_map_peek_elem)) { aux = &env->insn_aux_data[i + delta]; if (bpf_map_ptr_poisoned(aux)) goto patch_call_imm; map_ptr = BPF_MAP_PTR(aux->map_state); ops = map_ptr->ops; if (insn->imm == BPF_FUNC_map_lookup_elem && ops->map_gen_lookup) { cnt = ops->map_gen_lookup(map_ptr, insn_buf); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { verbose(env, "bpf verifier is misconfigured\n"); return -EINVAL; } new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, (void *(*)(struct bpf_map *map, void *key))NULL)); BUILD_BUG_ON(!__same_type(ops->map_delete_elem, (int (*)(struct bpf_map *map, void *key))NULL)); BUILD_BUG_ON(!__same_type(ops->map_update_elem, (int (*)(struct bpf_map *map, void *key, void *value, u64 flags))NULL)); BUILD_BUG_ON(!__same_type(ops->map_push_elem, (int (*)(struct bpf_map *map, void *value, u64 flags))NULL)); BUILD_BUG_ON(!__same_type(ops->map_pop_elem, (int (*)(struct bpf_map *map, void *value))NULL)); BUILD_BUG_ON(!__same_type(ops->map_peek_elem, (int (*)(struct bpf_map *map, void *value))NULL)); switch (insn->imm) { case BPF_FUNC_map_lookup_elem: insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) - __bpf_call_base; continue; case BPF_FUNC_map_update_elem: insn->imm = BPF_CAST_CALL(ops->map_update_elem) - __bpf_call_base; continue; case BPF_FUNC_map_delete_elem: insn->imm = BPF_CAST_CALL(ops->map_delete_elem) - __bpf_call_base; continue; case BPF_FUNC_map_push_elem: insn->imm = BPF_CAST_CALL(ops->map_push_elem) - __bpf_call_base; continue; case BPF_FUNC_map_pop_elem: insn->imm = BPF_CAST_CALL(ops->map_pop_elem) - __bpf_call_base; continue; case BPF_FUNC_map_peek_elem: insn->imm = BPF_CAST_CALL(ops->map_peek_elem) - __bpf_call_base; continue; } goto patch_call_imm; } patch_call_imm: fn = env->ops->get_func_proto(insn->imm, env->prog); /* all functions that have prototype and verifier allowed * programs to call them, must be real in-kernel functions */ if (!fn->func) { verbose(env, "kernel subsystem misconfigured func %s#%d\n", func_id_name(insn->imm), insn->imm); return -EFAULT; } insn->imm = fn->func - __bpf_call_base; } return 0; } Vulnerability Type: CWE ID: CWE-189 Summary: kernel/bpf/verifier.c in the Linux kernel before 4.20.6 performs undesirable out-of-bounds speculation on pointer arithmetic in various cases, including cases of different branches with different state or limits to sanitize, leading to side-channel attacks. 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]>
Medium
1,905
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: v8::Local<v8::Value> PrivateScriptRunner::runDOMAttributeGetter(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* attributeName, v8::Local<v8::Value> holder) { v8::Isolate* isolate = scriptState->isolate(); v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Local<v8::Value> descriptor; if (!classObject->GetOwnPropertyDescriptor(scriptState->context(), v8String(isolate, attributeName)).ToLocal(&descriptor) || !descriptor->IsObject()) { fprintf(stderr, "Private script error: Target DOM attribute getter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName); RELEASE_NOTREACHED(); } v8::Local<v8::Value> getter; if (!v8::Local<v8::Object>::Cast(descriptor)->Get(scriptState->context(), v8String(isolate, "get")).ToLocal(&getter) || !getter->IsFunction()) { fprintf(stderr, "Private script error: Target DOM attribute getter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName); RELEASE_NOTREACHED(); } initializeHolderIfNeeded(scriptState, classObject, holder); v8::TryCatch block(isolate); v8::Local<v8::Value> result; if (!V8ScriptRunner::callFunction(v8::Local<v8::Function>::Cast(getter), scriptState->getExecutionContext(), holder, 0, 0, isolate).ToLocal(&result)) { rethrowExceptionInPrivateScript(isolate, block, scriptStateInUserScript, ExceptionState::GetterContext, attributeName, className); block.ReThrow(); return v8::Local<v8::Value>(); } return result; } Vulnerability Type: XSS CWE ID: CWE-79 Summary: Blink in Google Chrome prior to 54.0.2840.59 for Windows, Mac, and Linux; 54.0.2840.85 for Android permitted execution of v8 microtasks while the DOM was in an inconsistent state, which allowed a remote attacker to inject arbitrary scripts or HTML (UXSS) via crafted HTML pages. Commit Message: Blink-in-JS should not run micro tasks If Blink-in-JS runs micro tasks, there's a risk of causing a UXSS bug (see 645211 for concrete steps). This CL makes Blink-in-JS use callInternalFunction (instead of callFunction) to avoid running micro tasks after Blink-in-JS' callbacks. BUG=645211 Review-Url: https://codereview.chromium.org/2330843002 Cr-Commit-Position: refs/heads/master@{#417874}
Medium
24,405
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void ThreadableBlobRegistry::registerStreamURL(const KURL& url, const String& type) { if (isMainThread()) { blobRegistry().registerStreamURL(url, type); } else { OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, type)); callOnMainThread(&registerStreamURLTask, context.leakPtr()); } } Vulnerability Type: DoS CWE ID: Summary: Google Chrome before 23.0.1271.91 on Mac OS X does not properly mitigate improper rendering behavior in the Intel GPU driver, which allows remote attackers to cause a denial of service or possibly have unspecified other impact via unknown vectors. Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
High
18,862
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void UpdateContentLengthPrefs(int received_content_length, int original_content_length, bool via_data_reduction_proxy) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK_GE(received_content_length, 0); DCHECK_GE(original_content_length, 0); if (!g_browser_process) return; PrefService* prefs = g_browser_process->local_state(); if (!prefs) return; #if defined(OS_ANDROID) bool with_data_reduction_proxy_enabled = g_browser_process->profile_manager()->GetDefaultProfile()-> GetPrefs()->GetBoolean(prefs::kSpdyProxyAuthEnabled); #else bool with_data_reduction_proxy_enabled = false; #endif chrome_browser_net::UpdateContentLengthPrefs( received_content_length, original_content_length, with_data_reduction_proxy_enabled, via_data_reduction_proxy, prefs); } Vulnerability Type: DoS CWE ID: CWE-416 Summary: Use-after-free vulnerability in the HTML5 Audio implementation in Google Chrome before 27.0.1453.110 allows remote attackers to cause a denial of service or possibly have unspecified other impact via unknown vectors. Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98
High
3,297
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static base::Callback<void(const gfx::Image&)> Wrap( const base::Callback<void(const SkBitmap&)>& image_decoded_callback) { auto* handler = new ImageDecodedHandlerWithTimeout(image_decoded_callback); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::Bind(&ImageDecodedHandlerWithTimeout::OnImageDecoded, handler->weak_ptr_factory_.GetWeakPtr(), gfx::Image()), base::TimeDelta::FromSeconds(kDecodeLogoTimeoutSeconds)); return base::Bind(&ImageDecodedHandlerWithTimeout::OnImageDecoded, handler->weak_ptr_factory_.GetWeakPtr()); } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: The Google V8 engine, as used in Google Chrome before 44.0.2403.89 and QtWebEngineCore in Qt before 5.5.1, allows remote attackers to cause a denial of service (memory corruption) or execute arbitrary code via a crafted web site. Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <[email protected]> Reviewed-by: Marc Treib <[email protected]> Commit-Queue: Chris Pickel <[email protected]> Cr-Commit-Position: refs/heads/master@{#505374}
High
24,243
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static struct o2nm_cluster *to_o2nm_cluster_from_node(struct o2nm_node *node) { /* through the first node_set .parent * mycluster/nodes/mynode == o2nm_cluster->o2nm_node_group->o2nm_node */ return to_o2nm_cluster(node->nd_item.ci_parent->ci_parent); } Vulnerability Type: DoS CWE ID: CWE-476 Summary: In fs/ocfs2/cluster/nodemanager.c in the Linux kernel before 4.15, local users can cause a denial of service (NULL pointer dereference and BUG) because a required mutex is not used. Commit Message: ocfs2: subsystem.su_mutex is required while accessing the item->ci_parent The subsystem.su_mutex is required while accessing the item->ci_parent, otherwise, NULL pointer dereference to the item->ci_parent will be triggered in the following situation: add node delete node sys_write vfs_write configfs_write_file o2nm_node_store o2nm_node_local_write do_rmdir vfs_rmdir configfs_rmdir mutex_lock(&subsys->su_mutex); unlink_obj item->ci_group = NULL; item->ci_parent = NULL; to_o2nm_cluster_from_node node->nd_item.ci_parent->ci_parent BUG since of NULL pointer dereference to nd_item.ci_parent Moreover, the o2nm_cluster also should be protected by the subsystem.su_mutex. [[email protected]: v2] Link: http://lkml.kernel.org/r/[email protected] Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Alex Chen <[email protected]> Reviewed-by: Jun Piao <[email protected]> Reviewed-by: Joseph Qi <[email protected]> Cc: Mark Fasheh <[email protected]> Cc: Joel Becker <[email protected]> Cc: Junxiao Bi <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>
Low
12,523
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: int tls1_setup_key_block(SSL *s) { unsigned char *p; const EVP_CIPHER *c; const EVP_MD *hash; int num; SSL_COMP *comp; int mac_type = NID_undef, mac_secret_size = 0; int ret = 0; if (s->s3->tmp.key_block_length != 0) return (1); if (!ssl_cipher_get_evp (s->session, &c, &hash, &mac_type, &mac_secret_size, &comp, SSL_USE_ETM(s))) { SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, SSL_R_CIPHER_OR_HASH_UNAVAILABLE); return (0); } s->s3->tmp.new_sym_enc = c; s->s3->tmp.new_hash = hash; s->s3->tmp.new_mac_pkey_type = mac_type; s->s3->tmp.new_mac_secret_size = mac_secret_size; num = EVP_CIPHER_key_length(c) + mac_secret_size + EVP_CIPHER_iv_length(c); num *= 2; ssl3_cleanup_key_block(s); if ((p = OPENSSL_malloc(num)) == NULL) { SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE); goto err; } s->s3->tmp.key_block_length = num; s->s3->tmp.key_block = p; #ifdef SSL_DEBUG printf("client random\n"); { int z; for (z = 0; z < SSL3_RANDOM_SIZE; z++) printf("%02X%c", s->s3->client_random[z], ((z + 1) % 16) ? ' ' : '\n'); } printf("server random\n"); { int z; for (z = 0; z < SSL3_RANDOM_SIZE; z++) printf("%02X%c", s->s3->server_random[z], ((z + 1) % 16) ? ' ' : '\n'); } printf("master key\n"); { int z; for (z = 0; z < s->session->master_key_length; z++) printf("%02X%c", s->session->master_key[z], ((z + 1) % 16) ? ' ' : '\n'); } #endif if (!tls1_generate_key_block(s, p, num)) goto err; #ifdef SSL_DEBUG printf("\nkey block\n"); { int z; for (z = 0; z < num; z++) printf("%02X%c", p[z], ((z + 1) % 16) ? ' ' : '\n'); } #endif if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) && s->method->version <= TLS1_VERSION) { /* * enable vulnerability countermeasure for CBC ciphers with known-IV * problem (http://www.openssl.org/~bodo/tls-cbc.txt) */ s->s3->need_empty_fragments = 1; if (s->session->cipher != NULL) { if (s->session->cipher->algorithm_enc == SSL_eNULL) s->s3->need_empty_fragments = 0; #ifndef OPENSSL_NO_RC4 if (s->session->cipher->algorithm_enc == SSL_RC4) s->s3->need_empty_fragments = 0; #endif } } ret = 1; err: return (ret); } Vulnerability Type: CWE ID: CWE-20 Summary: During a renegotiation handshake if the Encrypt-Then-Mac extension is negotiated where it was not in the original handshake (or vice-versa) then this can cause OpenSSL 1.1.0 before 1.1.0e to crash (dependent on ciphersuite). Both clients and servers are affected. Commit Message: Don't change the state of the ETM flags until CCS processing Changing the ciphersuite during a renegotiation can result in a crash leading to a DoS attack. ETM has not been implemented in 1.1.0 for DTLS so this is TLS only. The problem is caused by changing the flag indicating whether to use ETM or not immediately on negotiation of ETM, rather than at CCS. Therefore, during a renegotiation, if the ETM state is changing (usually due to a change of ciphersuite), then an error/crash will occur. Due to the fact that there are separate CCS messages for read and write we actually now need two flags to determine whether to use ETM or not. CVE-2017-3733 Reviewed-by: Richard Levitte <[email protected]>
Medium
19,974
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: reverseSamplesBytes (uint16 spp, uint16 bps, uint32 width, uint8 *src, uint8 *dst) { int i; uint32 col, bytes_per_pixel, col_offset; uint8 bytebuff1; unsigned char swapbuff[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("reverseSamplesBytes","Invalid input or output buffer"); return (1); } bytes_per_pixel = ((bps * spp) + 7) / 8; switch (bps / 8) { case 8: /* Use memcpy for multiple bytes per sample data */ case 4: case 3: case 2: for (col = 0; col < (width / 2); col++) { col_offset = col * bytes_per_pixel; _TIFFmemcpy (swapbuff, src + col_offset, bytes_per_pixel); _TIFFmemcpy (src + col_offset, dst - col_offset - bytes_per_pixel, bytes_per_pixel); _TIFFmemcpy (dst - col_offset - bytes_per_pixel, swapbuff, bytes_per_pixel); } break; case 1: /* Use byte copy only for single byte per sample data */ for (col = 0; col < (width / 2); col++) { for (i = 0; i < spp; i++) { bytebuff1 = *src; *src++ = *(dst - spp + i); *(dst - spp + i) = bytebuff1; } dst -= spp; } break; default: TIFFError("reverseSamplesBytes","Unsupported bit depth %d", bps); return (1); } return (0); } /* end reverseSamplesBytes */ Vulnerability Type: CWE ID: CWE-787 Summary: tools/tiffcrop.c in libtiff 4.0.6 has out-of-bounds write vulnerabilities in buffers. Reported as MSVR 35093, MSVR 35096, and MSVR 35097. Commit Message: * tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities in heap or stack allocated buffers. Reported as MSVR 35093, MSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in heap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR 35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities in heap allocated buffers. Reported as MSVR 35094. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1() that didn't reset the tif_rawcc and tif_rawcp members. I'm not completely sure if that could happen in practice outside of the odd behaviour of t2p_seekproc() of tiff2pdf). The report points that a better fix could be to check the return value of TIFFFlushData1() in places where it isn't done currently, but it seems this patch is enough. Reported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan & Suha Can from the MSRC Vulnerabilities & Mitigations team.
High
16,428
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: X11SurfaceFactory::GetAllowedGLImplementations() { std::vector<gl::GLImplementation> impls; impls.push_back(gl::kGLImplementationEGLGLES2); impls.push_back(gl::kGLImplementationDesktopGL); impls.push_back(gl::kGLImplementationOSMesaGL); return impls; } Vulnerability Type: Bypass CWE ID: CWE-284 Summary: Google Chrome before 39.0.2171.65 on Android does not prevent navigation to a URL in cases where an intent for the URL lacks CATEGORY_BROWSABLE, which allows remote attackers to bypass intended access restrictions via a crafted web site. Commit Message: Add ThreadChecker for Ozone X11 GPU. Ensure Ozone X11 tests the same thread constraints we have in Ozone GBM. BUG=none Review-Url: https://codereview.chromium.org/2366643002 Cr-Commit-Position: refs/heads/master@{#421817}
Medium
23,971
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: my_object_error_get_type (void) { static GType etype = 0; if (etype == 0) { static const GEnumValue values[] = { ENUM_ENTRY (MY_OBJECT_ERROR_FOO, "Foo"), ENUM_ENTRY (MY_OBJECT_ERROR_BAR, "Bar"), { 0, 0, 0 } }; etype = g_enum_register_static ("MyObjectError", values); } return etype; } Vulnerability Type: DoS Bypass CWE ID: CWE-264 Summary: DBus-GLib 0.73 disregards the access flag of exported GObject properties, which allows local users to bypass intended access restrictions and possibly cause a denial of service by modifying properties, as demonstrated by properties of the (1) DeviceKit-Power, (2) NetworkManager, and (3) ModemManager services. Commit Message:
Low
18,056
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: R_API void r_anal_bb_free(RAnalBlock *bb) { if (!bb) { return; } r_anal_cond_free (bb->cond); R_FREE (bb->fingerprint); r_anal_diff_free (bb->diff); bb->diff = NULL; R_FREE (bb->op_bytes); r_anal_switch_op_free (bb->switch_op); bb->switch_op = NULL; bb->fingerprint = NULL; bb->cond = NULL; R_FREE (bb->label); R_FREE (bb->op_pos); R_FREE (bb->parent_reg_arena); if (bb->prev) { if (bb->prev->jumpbb == bb) { bb->prev->jumpbb = NULL; } if (bb->prev->failbb == bb) { bb->prev->failbb = NULL; } bb->prev = NULL; } if (bb->jumpbb) { bb->jumpbb->prev = NULL; bb->jumpbb = NULL; } if (bb->failbb) { bb->failbb->prev = NULL; bb->failbb = NULL; } R_FREE (bb); } Vulnerability Type: CWE ID: CWE-416 Summary: There is a use after free in radare2 2.6.0 in r_anal_bb_free() in libr/anal/bb.c via a crafted Java binary file. Commit Message: Fix #10293 - Use-after-free in r_anal_bb_free()
Medium
6,749
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType logging, status; MngInfo *mng_info; char magic_number[MaxTextExtent]; ssize_t count; /* 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); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadPNGImage()"); image=AcquireImage(image_info); mng_info=(MngInfo *) NULL; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) ThrowReaderException(FileOpenError,"UnableToOpenFile"); /* Verify PNG signature. */ count=ReadBlob(image,8,(unsigned char *) magic_number); if (count < 8 || memcmp(magic_number,"\211PNG\r\n\032\n",8) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Allocate a MngInfo structure. */ mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); if (mng_info == (MngInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize members of the MngInfo structure. */ (void) ResetMagickMemory(mng_info,0,sizeof(MngInfo)); mng_info->image=image; image=ReadOnePNGImage(mng_info,image_info,exception); mng_info=MngInfoFreeStruct(mng_info); if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error"); return((Image *) NULL); } (void) CloseBlob(image); if ((image->columns == 0) || (image->rows == 0)) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadPNGImage() with error."); ThrowReaderException(CorruptImageError,"CorruptImage"); } if ((IssRGBColorspace(image->colorspace) != MagickFalse) && ((image->gamma < .45) || (image->gamma > .46)) && !(image->chromaticity.red_primary.x>0.6399f && image->chromaticity.red_primary.x<0.6401f && image->chromaticity.red_primary.y>0.3299f && image->chromaticity.red_primary.y<0.3301f && image->chromaticity.green_primary.x>0.2999f && image->chromaticity.green_primary.x<0.3001f && image->chromaticity.green_primary.y>0.5999f && image->chromaticity.green_primary.y<0.6001f && image->chromaticity.blue_primary.x>0.1499f && image->chromaticity.blue_primary.x<0.1501f && image->chromaticity.blue_primary.y>0.0599f && image->chromaticity.blue_primary.y<0.0601f && image->chromaticity.white_point.x>0.3126f && image->chromaticity.white_point.x<0.3128f && image->chromaticity.white_point.y>0.3289f && image->chromaticity.white_point.y<0.3291f)) SetImageColorspace(image,RGBColorspace); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " page.w: %.20g, page.h: %.20g,page.x: %.20g, page.y: %.20g.", (double) image->page.width,(double) image->page.height, (double) image->page.x,(double) image->page.y); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadPNGImage()"); return(image); } Vulnerability Type: CWE ID: CWE-754 Summary: In ImageMagick before 6.9.9-0 and 7.x before 7.0.6-1, a crafted PNG file could trigger a crash because there was an insufficient check for short files. Commit Message: ...
Medium
9,974
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: create_spnego_ctx(void) { spnego_gss_ctx_id_t spnego_ctx = NULL; spnego_ctx = (spnego_gss_ctx_id_t) malloc(sizeof (spnego_gss_ctx_id_rec)); if (spnego_ctx == NULL) { return (NULL); } spnego_ctx->magic_num = SPNEGO_MAGIC_ID; spnego_ctx->ctx_handle = GSS_C_NO_CONTEXT; spnego_ctx->mech_set = NULL; spnego_ctx->internal_mech = NULL; spnego_ctx->optionStr = NULL; spnego_ctx->DER_mechTypes.length = 0; spnego_ctx->DER_mechTypes.value = NULL; spnego_ctx->default_cred = GSS_C_NO_CREDENTIAL; spnego_ctx->mic_reqd = 0; spnego_ctx->mic_sent = 0; spnego_ctx->mic_rcvd = 0; spnego_ctx->mech_complete = 0; spnego_ctx->nego_done = 0; spnego_ctx->internal_name = GSS_C_NO_NAME; spnego_ctx->actual_mech = GSS_C_NO_OID; check_spnego_options(spnego_ctx); return (spnego_ctx); } Vulnerability Type: DoS CWE ID: CWE-18 Summary: lib/gssapi/spnego/spnego_mech.c in MIT Kerberos 5 (aka krb5) before 1.14 relies on an inappropriate context handle, which allows remote attackers to cause a denial of service (incorrect pointer read and process crash) via a crafted SPNEGO packet that is mishandled during a gss_inquire_context call. Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup
High
25,083
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void impeg2d_dec_pic_data_thread(dec_state_t *ps_dec) { WORD32 i4_continue_decode; WORD32 i4_cur_row, temp; UWORD32 u4_bits_read; WORD32 i4_dequeue_job; IMPEG2D_ERROR_CODES_T e_error; i4_cur_row = ps_dec->u2_mb_y + 1; i4_continue_decode = 1; i4_dequeue_job = 1; do { if(i4_cur_row > ps_dec->u2_num_vert_mb) { i4_continue_decode = 0; break; } { if((ps_dec->i4_num_cores> 1) && (i4_dequeue_job)) { job_t s_job; IV_API_CALL_STATUS_T e_ret; UWORD8 *pu1_buf; e_ret = impeg2_jobq_dequeue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 1); if(e_ret != IV_SUCCESS) break; if(CMD_PROCESS == s_job.i4_cmd) { pu1_buf = ps_dec->pu1_inp_bits_buf + s_job.i4_bistream_ofst; impeg2d_bit_stream_init(&(ps_dec->s_bit_stream), pu1_buf, (ps_dec->u4_num_inp_bytes - s_job.i4_bistream_ofst) + 8); i4_cur_row = s_job.i2_start_mb_y; ps_dec->i4_start_mb_y = s_job.i2_start_mb_y; ps_dec->i4_end_mb_y = s_job.i2_end_mb_y; ps_dec->u2_mb_x = 0; ps_dec->u2_mb_y = ps_dec->i4_start_mb_y; ps_dec->u2_num_mbs_left = (ps_dec->i4_end_mb_y - ps_dec->i4_start_mb_y) * ps_dec->u2_num_horiz_mb; } else { WORD32 start_row; WORD32 num_rows; start_row = s_job.i2_start_mb_y << 4; num_rows = MIN((s_job.i2_end_mb_y << 4), ps_dec->u2_vertical_size); num_rows -= start_row; impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic, ps_dec->ps_disp_frm_buf, start_row, num_rows); break; } } e_error = impeg2d_dec_slice(ps_dec); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { impeg2d_next_start_code(ps_dec); } } /* Detecting next slice start code */ while(1) { u4_bits_read = impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,START_CODE_LEN); temp = u4_bits_read & 0xFF; i4_continue_decode = (((u4_bits_read >> 8) == 0x01) && (temp) && (temp <= 0xAF)); if(i4_continue_decode) { /* If the slice is from the same row, then continue decoding without dequeue */ if((temp - 1) == i4_cur_row) { i4_dequeue_job = 0; break; } if(temp < ps_dec->i4_end_mb_y) { i4_cur_row = ps_dec->u2_mb_y; } else { i4_dequeue_job = 1; } break; } else break; } }while(i4_continue_decode); if(ps_dec->i4_num_cores > 1) { while(1) { job_t s_job; IV_API_CALL_STATUS_T e_ret; e_ret = impeg2_jobq_dequeue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 1); if(e_ret != IV_SUCCESS) break; if(CMD_FMTCONV == s_job.i4_cmd) { WORD32 start_row; WORD32 num_rows; start_row = s_job.i2_start_mb_y << 4; num_rows = MIN((s_job.i2_end_mb_y << 4), ps_dec->u2_vertical_size); num_rows -= start_row; impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic, ps_dec->ps_disp_frm_buf, start_row, num_rows); } } } else { if((NULL != ps_dec->ps_disp_pic) && ((0 == ps_dec->u4_share_disp_buf) || (IV_YUV_420P != ps_dec->i4_chromaFormat))) impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic, ps_dec->ps_disp_frm_buf, 0, ps_dec->u2_vertical_size); } } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: decoder/impeg2d_dec_hdr.c in mediaserver in Android 6.x before 2016-04-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file that triggers a certain negative value, aka internal bug 26070014. Commit Message: Fix for handling streams which resulted in negative num_mbs_left Bug: 26070014 Change-Id: Id9f063a2c72a802d991b92abaf00ec687db5bb0f
High
3,246
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void FaviconWebUIHandler::OnFaviconDataAvailable( FaviconService::Handle request_handle, history::FaviconData favicon) { FaviconService* favicon_service = web_ui_->GetProfile()->GetFaviconService(Profile::EXPLICIT_ACCESS); int id = consumer_.GetClientData(favicon_service, request_handle); if (favicon.is_valid()) { FundamentalValue id_value(id); color_utils::GridSampler sampler; SkColor color = color_utils::CalculateKMeanColorOfPNG(favicon.image_data, 100, 665, sampler); std::string css_color = base::StringPrintf("rgb(%d, %d, %d)", SkColorGetR(color), SkColorGetG(color), SkColorGetB(color)); StringValue color_value(css_color); web_ui_->CallJavascriptFunction("ntp4.setFaviconDominantColor", id_value, color_value); } } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: Google V8, as used in Google Chrome before 13.0.782.215, allows remote attackers to cause a denial of service or possibly have unspecified other impact via unknown vectors that trigger an out-of-bounds write. Commit Message: ntp4: show larger favicons in most visited page extend favicon source to provide larger icons. For now, larger means at most 32x32. Also, the only icon we actually support at this resolution is the default (globe). BUG=none TEST=manual Review URL: http://codereview.chromium.org/7300017 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91517 0039d316-1c4b-4281-b951-d872f2087c98
High
20,729
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void BaseAudioContext::Initialize() { if (IsDestinationInitialized()) return; FFTFrame::Initialize(); audio_worklet_ = AudioWorklet::Create(this); if (destination_node_) { destination_node_->Handler().Initialize(); listener_ = AudioListener::Create(*this); } } Vulnerability Type: CWE ID: CWE-416 Summary: A use after free in WebAudio in Google Chrome prior to 69.0.3497.81 allowed a remote attacker to potentially exploit heap corruption via a crafted HTML page. Commit Message: Audio thread should not access destination node The AudioDestinationNode is an object managed by Oilpan so the audio thread should not access it. However, the audio thread needs information (currentTime, etc) from the destination node. So instead of accessing the audio destination handler (a scoped_refptr) via the destination node, add a new member to the base audio context that holds onto the destination handler. The destination handler is not an oilpan object and lives at least as long as the base audio context. Bug: 860626, 860522, 863951 Test: Test case from 860522 doesn't crash on asan build Change-Id: I3add844d4eb8fdc7e05b89292938b843a0abbb99 Reviewed-on: https://chromium-review.googlesource.com/1138974 Commit-Queue: Raymond Toy <[email protected]> Reviewed-by: Hongchan Choi <[email protected]> Cr-Commit-Position: refs/heads/master@{#575509}
Medium
14,953
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int ext4_dax_fault(struct vm_area_struct *vma, struct vm_fault *vmf) { int result; handle_t *handle = NULL; struct super_block *sb = file_inode(vma->vm_file)->i_sb; bool write = vmf->flags & FAULT_FLAG_WRITE; if (write) { sb_start_pagefault(sb); file_update_time(vma->vm_file); handle = ext4_journal_start_sb(sb, EXT4_HT_WRITE_PAGE, EXT4_DATA_TRANS_BLOCKS(sb)); } if (IS_ERR(handle)) result = VM_FAULT_SIGBUS; else result = __dax_fault(vma, vmf, ext4_get_block_dax, ext4_end_io_unwritten); if (write) { if (!IS_ERR(handle)) ext4_journal_stop(handle); sb_end_pagefault(sb); } return result; } Vulnerability Type: DoS CWE ID: CWE-362 Summary: Multiple race conditions in the ext4 filesystem implementation in the Linux kernel before 4.5 allow local users to cause a denial of service (disk corruption) by writing to a page that is associated with a different user's file after unsynchronized hole punching and page-fault handling. Commit Message: ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]>
Low
17,679
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: uint32_t *GetPayload(size_t handle, uint32_t *lastpayload, uint32_t index) { mp4object *mp4 = (mp4object *)handle; if (mp4 == NULL) return NULL; uint32_t *MP4buffer = NULL; if (index < mp4->indexcount && mp4->mediafp) { MP4buffer = (uint32_t *)realloc((void *)lastpayload, mp4->metasizes[index]); if (MP4buffer) { LONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET); fread(MP4buffer, 1, mp4->metasizes[index], mp4->mediafp); return MP4buffer; } } return NULL; } Vulnerability Type: CWE ID: CWE-787 Summary: GoPro GPMF-parser 1.2.2 has an out-of-bounds write in OpenMP4Source in demo/GPMF_mp4reader.c. Commit Message: fixed many security issues with the too crude mp4 reader
Medium
21,156
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static char* cJSON_strdup( const char* str ) { size_t len; char* copy; len = strlen( str ) + 1; if ( ! ( copy = (char*) cJSON_malloc( len ) ) ) return 0; memcpy( copy, str, len ); return copy; } Vulnerability Type: DoS Exec Code Overflow CWE ID: CWE-119 Summary: The parse_string function in cjson.c in the cJSON library mishandles UTF8/16 strings, which allows remote attackers to cause a denial of service (crash) or execute arbitrary code via a non-hex character in a JSON string, which triggers a heap-based buffer overflow. Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]>
High
27,082
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: dwarf_elf_object_access_load_section(void* obj_in, Dwarf_Half section_index, Dwarf_Small** section_data, int* error) { dwarf_elf_object_access_internals_t*obj = (dwarf_elf_object_access_internals_t*)obj_in; if (section_index == 0) { return DW_DLV_NO_ENTRY; } { Elf_Scn *scn = 0; Elf_Data *data = 0; scn = elf_getscn(obj->elf, section_index); if (scn == NULL) { *error = DW_DLE_MDE; return DW_DLV_ERROR; } /* When using libelf as a producer, section data may be stored in multiple buffers. In libdwarf however, we only use libelf as a consumer (there is a dwarf producer API, but it doesn't use libelf). Because of this, this single call to elf_getdata will retrieve the entire section in a single contiguous buffer. */ data = elf_getdata(scn, NULL); if (data == NULL) { *error = DW_DLE_MDE; return DW_DLV_ERROR; } *section_data = data->d_buf; } return DW_DLV_OK; } Vulnerability Type: DoS CWE ID: CWE-476 Summary: libdwarf 20151114 and earlier allows remote attackers to cause a denial of service (NULL pointer dereference and crash) via a debug_abbrev section marked NOBITS in an ELF file. Commit Message: A DWARF related section marked SHT_NOBITS (elf section type) is an error in the elf object. Now detected. dwarf_elf_access.c
Medium
20,668
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void ScreenOrientationDispatcherHost::OnLockRequest( RenderFrameHost* render_frame_host, blink::WebScreenOrientationLockType orientation, int request_id) { if (current_lock_) { NotifyLockError(current_lock_->request_id, blink::WebLockOrientationErrorCanceled); } current_lock_ = new LockInformation(request_id, render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID()); if (!provider_) { NotifyLockError(request_id, blink::WebLockOrientationErrorNotAvailable); return; } provider_->LockOrientation(request_id, orientation); } Vulnerability Type: DoS CWE ID: CWE-362 Summary: Multiple race conditions in the Web Audio implementation in Blink, as used in Google Chrome before 30.0.1599.66, allow remote attackers to cause a denial of service or possibly have unspecified other impact via vectors related to threading in core/html/HTMLMediaElement.cpp, core/platform/audio/AudioDSPKernelProcessor.cpp, core/platform/audio/HRTFElevation.cpp, and modules/webaudio/ConvolverNode.cpp. Commit Message: Cleanups in ScreenOrientationDispatcherHost. BUG=None Review URL: https://codereview.chromium.org/408213003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@284786 0039d316-1c4b-4281-b951-d872f2087c98
Medium
23,398
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int sd_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long arg) { struct gendisk *disk = bdev->bd_disk; struct scsi_disk *sdkp = scsi_disk(disk); struct scsi_device *sdp = sdkp->device; void __user *p = (void __user *)arg; int error; SCSI_LOG_IOCTL(1, sd_printk(KERN_INFO, sdkp, "sd_ioctl: disk=%s, " "cmd=0x%x\n", disk->disk_name, cmd)); /* * If we are in the middle of error recovery, don't let anyone * else try and use this device. Also, if error recovery fails, it * may try and take the device offline, in which case all further * access to the device is prohibited. */ error = scsi_nonblockable_ioctl(sdp, cmd, p, (mode & FMODE_NDELAY) != 0); if (!scsi_block_when_processing_errors(sdp) || !error) goto out; /* * Send SCSI addressing ioctls directly to mid level, send other * ioctls to block level and then onto mid level if they can't be * resolved. */ switch (cmd) { case SCSI_IOCTL_GET_IDLUN: case SCSI_IOCTL_GET_BUS_NUMBER: error = scsi_ioctl(sdp, cmd, p); break; default: error = scsi_cmd_blk_ioctl(bdev, mode, cmd, p); if (error != -ENOTTY) break; error = scsi_ioctl(sdp, cmd, p); break; } out: return error; } Vulnerability Type: Bypass CWE ID: CWE-264 Summary: The Linux kernel before 3.2.2 does not properly restrict SG_IO ioctl calls, which allows local users to bypass intended restrictions on disk read and write operations by sending a SCSI command to (1) a partition block device or (2) an LVM volume. Commit Message: block: fail SCSI passthrough ioctls on partition devices Linux allows executing the SG_IO ioctl on a partition or LVM volume, and will pass the command to the underlying block device. This is well-known, but it is also a large security problem when (via Unix permissions, ACLs, SELinux or a combination thereof) a program or user needs to be granted access only to part of the disk. This patch lets partitions forward a small set of harmless ioctls; others are logged with printk so that we can see which ioctls are actually sent. In my tests only CDROM_GET_CAPABILITY actually occurred. Of course it was being sent to a (partition on a) hard disk, so it would have failed with ENOTTY and the patch isn't changing anything in practice. Still, I'm treating it specially to avoid spamming the logs. In principle, this restriction should include programs running with CAP_SYS_RAWIO. If for example I let a program access /dev/sda2 and /dev/sdb, it still should not be able to read/write outside the boundaries of /dev/sda2 independent of the capabilities. However, for now programs with CAP_SYS_RAWIO will still be allowed to send the ioctls. Their actions will still be logged. This patch does not affect the non-libata IDE driver. That driver however already tests for bd != bd->bd_contains before issuing some ioctl; it could be restricted further to forbid these ioctls even for programs running with CAP_SYS_ADMIN/CAP_SYS_RAWIO. Cc: [email protected] Cc: Jens Axboe <[email protected]> Cc: James Bottomley <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> [ Make it also print the command name when warning - Linus ] Signed-off-by: Linus Torvalds <[email protected]>
Medium
13,815
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: X11SurfaceFactory::GetAllowedGLImplementations() { std::vector<gl::GLImplementation> impls; impls.push_back(gl::kGLImplementationEGLGLES2); impls.push_back(gl::kGLImplementationDesktopGL); impls.push_back(gl::kGLImplementationOSMesaGL); return impls; } Vulnerability Type: Bypass CWE ID: CWE-284 Summary: Google Chrome before 39.0.2171.65 on Android does not prevent navigation to a URL in cases where an intent for the URL lacks CATEGORY_BROWSABLE, which allows remote attackers to bypass intended access restrictions via a crafted web site. Commit Message: Add ThreadChecker for Ozone X11 GPU. Ensure Ozone X11 tests the same thread constraints we have in Ozone GBM. BUG=none Review-Url: https://codereview.chromium.org/2366643002 Cr-Commit-Position: refs/heads/master@{#421817}
Medium
14,880
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: jp2_box_t *jp2_box_get(jas_stream_t *in) { jp2_box_t *box; jp2_boxinfo_t *boxinfo; jas_stream_t *tmpstream; uint_fast32_t len; uint_fast64_t extlen; bool dataflag; box = 0; tmpstream = 0; if (!(box = jas_malloc(sizeof(jp2_box_t)))) { goto error; } box->ops = &jp2_boxinfo_unk.ops; if (jp2_getuint32(in, &len) || jp2_getuint32(in, &box->type)) { goto error; } boxinfo = jp2_boxinfolookup(box->type); box->info = boxinfo; box->ops = &boxinfo->ops; box->len = len; if (box->len == 1) { if (jp2_getuint64(in, &extlen)) { goto error; } if (extlen > 0xffffffffUL) { jas_eprintf("warning: cannot handle large 64-bit box length\n"); extlen = 0xffffffffUL; } box->len = extlen; box->datalen = extlen - JP2_BOX_HDRLEN(true); } else { box->datalen = box->len - JP2_BOX_HDRLEN(false); } if (box->len != 0 && box->len < 8) { goto error; } dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA)); if (dataflag) { if (!(tmpstream = jas_stream_memopen(0, 0))) { goto error; } if (jas_stream_copy(tmpstream, in, box->datalen)) { jas_eprintf("cannot copy box data\n"); goto error; } jas_stream_rewind(tmpstream); if (box->ops->getdata) { if ((*box->ops->getdata)(box, tmpstream)) { jas_eprintf("cannot parse box data\n"); goto error; } } jas_stream_close(tmpstream); } if (jas_getdbglevel() >= 1) { jp2_box_dump(box, stderr); } return box; error: if (box) { jp2_box_destroy(box); } if (tmpstream) { jas_stream_close(tmpstream); } return 0; } Vulnerability Type: DoS CWE ID: CWE-476 Summary: The jp2_colr_destroy function in libjasper/jp2/jp2_cod.c in JasPer before 1.900.10 allows remote attackers to cause a denial of service (NULL pointer dereference). Commit Message: Fixed a bug that resulted in the destruction of JP2 box data that had never been constructed in the first place.
Medium
26,235
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: log2vis_utf8 (PyObject * string, int unicode_length, FriBidiParType base_direction, int clean, int reordernsm) { FriBidiChar *logical = NULL; /* input fribidi unicode buffer */ FriBidiChar *visual = NULL; /* output fribidi unicode buffer */ char *visual_utf8 = NULL; /* output fribidi UTF-8 buffer */ FriBidiStrIndex new_len = 0; /* length of the UTF-8 buffer */ PyObject *result = NULL; /* failure */ /* Allocate fribidi unicode buffers */ logical = PyMem_New (FriBidiChar, unicode_length + 1); if (logical == NULL) { PyErr_SetString (PyExc_MemoryError, "failed to allocate unicode buffer"); goto cleanup; } visual = PyMem_New (FriBidiChar, unicode_length + 1); if (visual == NULL) { PyErr_SetString (PyExc_MemoryError, "failed to allocate unicode buffer"); goto cleanup; } /* Convert to unicode and order visually */ fribidi_set_reorder_nsm(reordernsm); fribidi_utf8_to_unicode (PyString_AS_STRING (string), PyString_GET_SIZE (string), logical); if (!fribidi_log2vis (logical, unicode_length, &base_direction, visual, NULL, NULL, NULL)) { PyErr_SetString (PyExc_RuntimeError, "fribidi failed to order string"); goto cleanup; } /* Cleanup the string if requested */ if (clean) fribidi_remove_bidi_marks (visual, unicode_length, NULL, NULL, NULL); /* Allocate fribidi UTF-8 buffer */ visual_utf8 = PyMem_New(char, (unicode_length * 4)+1); if (visual_utf8 == NULL) { PyErr_SetString (PyExc_MemoryError, "failed to allocate UTF-8 buffer"); goto cleanup; } /* Encode the reordered string and create result string */ new_len = fribidi_unicode_to_utf8 (visual, unicode_length, visual_utf8); result = PyString_FromStringAndSize (visual_utf8, new_len); if (result == NULL) /* XXX does it raise any error? */ goto cleanup; cleanup: /* Delete unicode buffers */ PyMem_Del (logical); PyMem_Del (visual); PyMem_Del (visual_utf8); return result; } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: Buffer overflow in the fribidi_utf8_to_unicode function in PyFriBidi before 0.11.0 allows remote attackers to cause a denial of service (application crash) via a 4-byte utf-8 sequence. Commit Message: refactor pyfribidi.c module pyfribidi.c is now compiled as _pyfribidi. This module only handles unicode internally and doesn't use the fribidi_utf8_to_unicode function (which can't handle 4 byte utf-8 sequences). This fixes the buffer overflow in issue #2. The code is now also much simpler: pyfribidi.c is down from 280 to 130 lines of code. We now ship a pure python pyfribidi that handles the case when non-unicode strings are passed in. We now also adapt the size of the output string if clean=True is passed.
Medium
14,659
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: device_has_capability (NMDevice *self, NMDeviceCapabilities caps) { { static guint32 devcount = 0; NMDevicePrivate *priv; g_return_if_fail (NM_IS_DEVICE (self)); priv = NM_DEVICE_GET_PRIVATE (self); g_return_if_fail (priv->path == NULL); priv->path = g_strdup_printf ("/org/freedesktop/NetworkManager/Devices/%d", devcount++); _LOGI (LOGD_DEVICE, "exported as %s", priv->path); nm_dbus_manager_register_object (nm_dbus_manager_get (), priv->path, self); } const char * nm_device_get_path (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->path; } const char * nm_device_get_udi (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->udi; } const char * nm_device_get_iface (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), 0); return NM_DEVICE_GET_PRIVATE (self)->iface; } int nm_device_get_ifindex (NMDevice *self) { g_return_val_if_fail (self != NULL, 0); return NM_DEVICE_GET_PRIVATE (self)->ifindex; } gboolean nm_device_is_software (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); return priv->is_software; } const char * nm_device_get_ip_iface (NMDevice *self) { NMDevicePrivate *priv; g_return_val_if_fail (self != NULL, NULL); priv = NM_DEVICE_GET_PRIVATE (self); /* If it's not set, default to iface */ return priv->ip_iface ? priv->ip_iface : priv->iface; } int nm_device_get_ip_ifindex (NMDevice *self) { NMDevicePrivate *priv; g_return_val_if_fail (self != NULL, 0); priv = NM_DEVICE_GET_PRIVATE (self); /* If it's not set, default to iface */ return priv->ip_iface ? priv->ip_ifindex : priv->ifindex; } void nm_device_set_ip_iface (NMDevice *self, const char *iface) { NMDevicePrivate *priv; char *old_ip_iface; g_return_if_fail (NM_IS_DEVICE (self)); priv = NM_DEVICE_GET_PRIVATE (self); if (!g_strcmp0 (iface, priv->ip_iface)) return; old_ip_iface = priv->ip_iface; priv->ip_ifindex = 0; priv->ip_iface = g_strdup (iface); if (priv->ip_iface) { priv->ip_ifindex = nm_platform_link_get_ifindex (priv->ip_iface); if (priv->ip_ifindex > 0) { if (nm_platform_check_support_user_ipv6ll ()) nm_platform_link_set_user_ipv6ll_enabled (priv->ip_ifindex, TRUE); if (!nm_platform_link_is_up (priv->ip_ifindex)) nm_platform_link_set_up (priv->ip_ifindex); } else { /* Device IP interface must always be a kernel network interface */ _LOGW (LOGD_HW, "failed to look up interface index"); } } /* We don't care about any saved values from the old iface */ g_hash_table_remove_all (priv->ip6_saved_properties); /* Emit change notification */ if (g_strcmp0 (old_ip_iface, priv->ip_iface)) g_object_notify (G_OBJECT (self), NM_DEVICE_IP_IFACE); g_free (old_ip_iface); } static gboolean get_ip_iface_identifier (NMDevice *self, NMUtilsIPv6IfaceId *out_iid) { NMLinkType link_type; const guint8 *hwaddr = NULL; size_t hwaddr_len = 0; int ifindex; gboolean success; /* If we get here, we *must* have a kernel netdev, which implies an ifindex */ ifindex = nm_device_get_ip_ifindex (self); g_assert (ifindex); link_type = nm_platform_link_get_type (ifindex); g_return_val_if_fail (link_type > NM_LINK_TYPE_UNKNOWN, 0); hwaddr = nm_platform_link_get_address (ifindex, &hwaddr_len); if (!hwaddr_len) return FALSE; success = nm_utils_get_ipv6_interface_identifier (link_type, hwaddr, hwaddr_len, out_iid); if (!success) { _LOGW (LOGD_HW, "failed to generate interface identifier " "for link type %u hwaddr_len %zu", link_type, hwaddr_len); } return success; } static gboolean nm_device_get_ip_iface_identifier (NMDevice *self, NMUtilsIPv6IfaceId *iid) { return NM_DEVICE_GET_CLASS (self)->get_ip_iface_identifier (self, iid); } const char * nm_device_get_driver (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->driver; } const char * nm_device_get_driver_version (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->driver_version; } NMDeviceType nm_device_get_device_type (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), NM_DEVICE_TYPE_UNKNOWN); return NM_DEVICE_GET_PRIVATE (self)->type; } /** * nm_device_get_priority(): * @self: the #NMDevice * * Returns: the device's routing priority. Lower numbers means a "better" * device, eg higher priority. */ int nm_device_get_priority (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), 1000); /* Device 'priority' is used for the default route-metric and is based on * the device type. The settings ipv4.route-metric and ipv6.route-metric * can overwrite this default. * * Currently for both IPv4 and IPv6 we use the same default values. * * The route-metric is used for the metric of the routes of device. * This also applies to the default route. Therefore it affects also * which device is the "best". * * For comparison, note that iproute2 by default adds IPv4 routes with * metric 0, and IPv6 routes with metric 1024. The latter is the IPv6 * "user default" in the kernel (NM_PLATFORM_ROUTE_METRIC_DEFAULT_IP6). * In kernel, the full uint32_t range is available for route * metrics (except for IPv6, where 0 means 1024). */ switch (nm_device_get_device_type (self)) { /* 50 is reserved for VPN (NM_VPN_ROUTE_METRIC_DEFAULT) */ case NM_DEVICE_TYPE_ETHERNET: return 100; case NM_DEVICE_TYPE_INFINIBAND: return 150; case NM_DEVICE_TYPE_ADSL: return 200; case NM_DEVICE_TYPE_WIMAX: return 250; case NM_DEVICE_TYPE_BOND: return 300; case NM_DEVICE_TYPE_TEAM: return 350; case NM_DEVICE_TYPE_VLAN: return 400; case NM_DEVICE_TYPE_BRIDGE: return 425; case NM_DEVICE_TYPE_MODEM: return 450; case NM_DEVICE_TYPE_BT: return 550; case NM_DEVICE_TYPE_WIFI: return 600; case NM_DEVICE_TYPE_OLPC_MESH: return 650; case NM_DEVICE_TYPE_GENERIC: return 950; case NM_DEVICE_TYPE_UNKNOWN: return 10000; case NM_DEVICE_TYPE_UNUSED1: case NM_DEVICE_TYPE_UNUSED2: /* omit default: to get compiler warning about missing switch cases */ break; } return 11000; } guint32 nm_device_get_ip4_route_metric (NMDevice *self) { NMConnection *connection; gint64 route_metric = -1; g_return_val_if_fail (NM_IS_DEVICE (self), G_MAXUINT32); connection = nm_device_get_connection (self); if (connection) route_metric = nm_setting_ip_config_get_route_metric (nm_connection_get_setting_ip4_config (connection)); return route_metric >= 0 ? route_metric : nm_device_get_priority (self); } guint32 nm_device_get_ip6_route_metric (NMDevice *self) { NMConnection *connection; gint64 route_metric = -1; g_return_val_if_fail (NM_IS_DEVICE (self), G_MAXUINT32); connection = nm_device_get_connection (self); if (connection) route_metric = nm_setting_ip_config_get_route_metric (nm_connection_get_setting_ip6_config (connection)); return route_metric >= 0 ? route_metric : nm_device_get_priority (self); } const NMPlatformIP4Route * nm_device_get_ip4_default_route (NMDevice *self, gboolean *out_is_assumed) { NMDevicePrivate *priv; g_return_val_if_fail (NM_IS_DEVICE (self), NULL); priv = NM_DEVICE_GET_PRIVATE (self); if (out_is_assumed) *out_is_assumed = priv->default_route.v4_is_assumed; return priv->default_route.v4_has ? &priv->default_route.v4 : NULL; } const NMPlatformIP6Route * nm_device_get_ip6_default_route (NMDevice *self, gboolean *out_is_assumed) { NMDevicePrivate *priv; g_return_val_if_fail (NM_IS_DEVICE (self), NULL); priv = NM_DEVICE_GET_PRIVATE (self); if (out_is_assumed) *out_is_assumed = priv->default_route.v6_is_assumed; return priv->default_route.v6_has ? &priv->default_route.v6 : NULL; } const char * nm_device_get_type_desc (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->type_desc; } gboolean nm_device_has_carrier (NMDevice *self) { return NM_DEVICE_GET_PRIVATE (self)->carrier; } NMActRequest * nm_device_get_act_request (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->act_request; } NMConnection * nm_device_get_connection (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); return priv->act_request ? nm_act_request_get_connection (priv->act_request) : NULL; } RfKillType nm_device_get_rfkill_type (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); return NM_DEVICE_GET_PRIVATE (self)->rfkill_type; } static const char * nm_device_get_physical_port_id (NMDevice *self) { return NM_DEVICE_GET_PRIVATE (self)->physical_port_id; } /***********************************************************/ static gboolean nm_device_uses_generated_assumed_connection (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; if ( priv->act_request && nm_active_connection_get_assumed (NM_ACTIVE_CONNECTION (priv->act_request))) { connection = nm_act_request_get_connection (priv->act_request); if ( connection && nm_settings_connection_get_nm_generated_assumed (NM_SETTINGS_CONNECTION (connection))) return TRUE; } return FALSE; } gboolean nm_device_uses_assumed_connection (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if ( priv->act_request && nm_active_connection_get_assumed (NM_ACTIVE_CONNECTION (priv->act_request))) return TRUE; return FALSE; } static SlaveInfo * find_slave_info (NMDevice *self, NMDevice *slave) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); SlaveInfo *info; GSList *iter; for (iter = priv->slaves; iter; iter = g_slist_next (iter)) { info = iter->data; if (info->slave == slave) return info; } return NULL; } static void free_slave_info (SlaveInfo *info) { g_signal_handler_disconnect (info->slave, info->watch_id); g_clear_object (&info->slave); memset (info, 0, sizeof (*info)); g_free (info); } /** * nm_device_enslave_slave: * @self: the master device * @slave: the slave device to enslave * @connection: (allow-none): the slave device's connection * * If @self is capable of enslaving other devices (ie it's a bridge, bond, team, * etc) then this function enslaves @slave. * * Returns: %TRUE on success, %FALSE on failure or if this device cannot enslave * other devices. */ static gboolean nm_device_enslave_slave (NMDevice *self, NMDevice *slave, NMConnection *connection) { SlaveInfo *info; gboolean success = FALSE; gboolean configure; g_return_val_if_fail (self != NULL, FALSE); g_return_val_if_fail (slave != NULL, FALSE); g_return_val_if_fail (NM_DEVICE_GET_CLASS (self)->enslave_slave != NULL, FALSE); info = find_slave_info (self, slave); if (!info) return FALSE; if (info->enslaved) success = TRUE; else { configure = (info->configure && connection != NULL); if (configure) g_return_val_if_fail (nm_device_get_state (slave) >= NM_DEVICE_STATE_DISCONNECTED, FALSE); success = NM_DEVICE_GET_CLASS (self)->enslave_slave (self, slave, connection, configure); info->enslaved = success; } nm_device_slave_notify_enslave (info->slave, success); /* Ensure the device's hardware address is up-to-date; it often changes * when slaves change. */ nm_device_update_hw_address (self); /* Restart IP configuration if we're waiting for slaves. Do this * after updating the hardware address as IP config may need the * new address. */ if (success) { if (NM_DEVICE_GET_PRIVATE (self)->ip4_state == IP_WAIT) nm_device_activate_stage3_ip4_start (self); if (NM_DEVICE_GET_PRIVATE (self)->ip6_state == IP_WAIT) nm_device_activate_stage3_ip6_start (self); } return success; } /** * nm_device_release_one_slave: * @self: the master device * @slave: the slave device to release * @configure: whether @self needs to actually release @slave * @reason: the state change reason for the @slave * * If @self is capable of enslaving other devices (ie it's a bridge, bond, team, * etc) then this function releases the previously enslaved @slave and/or * updates the state of @self and @slave to reflect its release. * * Returns: %TRUE on success, %FALSE on failure, if this device cannot enslave * other devices, or if @slave was never enslaved. */ static gboolean nm_device_release_one_slave (NMDevice *self, NMDevice *slave, gboolean configure, NMDeviceStateReason reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); SlaveInfo *info; gboolean success = FALSE; g_return_val_if_fail (slave != NULL, FALSE); g_return_val_if_fail (NM_DEVICE_GET_CLASS (self)->release_slave != NULL, FALSE); info = find_slave_info (self, slave); if (!info) return FALSE; priv->slaves = g_slist_remove (priv->slaves, info); if (info->enslaved) { success = NM_DEVICE_GET_CLASS (self)->release_slave (self, slave, configure); /* The release_slave() implementation logs success/failure (in the * correct device-specific log domain), so we don't have to do anything. */ } if (!configure) { g_warn_if_fail (reason == NM_DEVICE_STATE_REASON_NONE || reason == NM_DEVICE_STATE_REASON_REMOVED); reason = NM_DEVICE_STATE_REASON_NONE; } else if (reason == NM_DEVICE_STATE_REASON_NONE) { g_warn_if_reached (); reason = NM_DEVICE_STATE_REASON_UNKNOWN; } nm_device_slave_notify_release (info->slave, reason); free_slave_info (info); /* Ensure the device's hardware address is up-to-date; it often changes * when slaves change. */ nm_device_update_hw_address (self); return success; } static gboolean is_software_external (NMDevice *self) { return nm_device_is_software (self) && !nm_device_get_is_nm_owned (self); } /** * nm_device_finish_init: * @self: the master device * * Whatever needs to be done post-initialization, when the device has a DBus * object name. */ void nm_device_finish_init (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); g_assert (priv->initialized == FALSE); /* Do not manage externally created software devices until they are IFF_UP */ if ( is_software_external (self) && !nm_platform_link_is_up (priv->ifindex) && priv->ifindex > 0) nm_device_set_initial_unmanaged_flag (self, NM_UNMANAGED_EXTERNAL_DOWN, TRUE); if (priv->master) nm_device_enslave_slave (priv->master, self, NULL); priv->initialized = TRUE; } static void carrier_changed (NMDevice *self, gboolean carrier) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (!nm_device_get_managed (self)) return; nm_device_recheck_available_connections (self); /* ignore-carrier devices ignore all carrier-down events */ if (priv->ignore_carrier && !carrier) return; if (priv->is_master) { /* Bridge/bond/team carrier does not affect its own activation, * but when carrier comes on, if there are slaves waiting, * it will restart them. */ if (!carrier) return; if (nm_device_activate_ip4_state_in_wait (self)) nm_device_activate_stage3_ip4_start (self); if (nm_device_activate_ip6_state_in_wait (self)) nm_device_activate_stage3_ip6_start (self); return; } else if (nm_device_get_enslaved (self) && !carrier) { /* Slaves don't deactivate when they lose carrier; for * bonds/teams in particular that would be actively * counterproductive. */ return; } if (carrier) { g_warn_if_fail (priv->state >= NM_DEVICE_STATE_UNAVAILABLE); if (priv->state == NM_DEVICE_STATE_UNAVAILABLE) { nm_device_queue_state (self, NM_DEVICE_STATE_DISCONNECTED, NM_DEVICE_STATE_REASON_CARRIER); } else if (priv->state == NM_DEVICE_STATE_DISCONNECTED) { /* If the device is already in DISCONNECTED state without a carrier * (probably because it is tagged for carrier ignore) ensure that * when the carrier appears, auto connections are rechecked for * the device. */ nm_device_emit_recheck_auto_activate (self); } } else { g_return_if_fail (priv->state >= NM_DEVICE_STATE_UNAVAILABLE); if (priv->state == NM_DEVICE_STATE_UNAVAILABLE) { if (nm_device_queued_state_peek (self) >= NM_DEVICE_STATE_DISCONNECTED) nm_device_queued_state_clear (self); } else { nm_device_queue_state (self, NM_DEVICE_STATE_UNAVAILABLE, NM_DEVICE_STATE_REASON_CARRIER); } } } #define LINK_DISCONNECT_DELAY 4 static gboolean link_disconnect_action_cb (gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); _LOGD (LOGD_DEVICE, "link disconnected (calling deferred action) (id=%u)", priv->carrier_defer_id); priv->carrier_defer_id = 0; _LOGI (LOGD_DEVICE, "link disconnected (calling deferred action)"); NM_DEVICE_GET_CLASS (self)->carrier_changed (self, FALSE); return FALSE; } static void link_disconnect_action_cancel (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->carrier_defer_id) { g_source_remove (priv->carrier_defer_id); _LOGD (LOGD_DEVICE, "link disconnected (canceling deferred action) (id=%u)", priv->carrier_defer_id); priv->carrier_defer_id = 0; } } void nm_device_set_carrier (NMDevice *self, gboolean carrier) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self); NMDeviceState state = nm_device_get_state (self); if (priv->carrier == carrier) return; priv->carrier = carrier; g_object_notify (G_OBJECT (self), NM_DEVICE_CARRIER); if (priv->carrier) { _LOGI (LOGD_DEVICE, "link connected"); link_disconnect_action_cancel (self); klass->carrier_changed (self, TRUE); if (priv->carrier_wait_id) { g_source_remove (priv->carrier_wait_id); priv->carrier_wait_id = 0; nm_device_remove_pending_action (self, "carrier wait", TRUE); _carrier_wait_check_queued_act_request (self); } } else if (state <= NM_DEVICE_STATE_DISCONNECTED) { _LOGI (LOGD_DEVICE, "link disconnected"); klass->carrier_changed (self, FALSE); } else { _LOGI (LOGD_DEVICE, "link disconnected (deferring action for %d seconds)", LINK_DISCONNECT_DELAY); priv->carrier_defer_id = g_timeout_add_seconds (LINK_DISCONNECT_DELAY, link_disconnect_action_cb, self); _LOGD (LOGD_DEVICE, "link disconnected (deferring action for %d seconds) (id=%u)", LINK_DISCONNECT_DELAY, priv->carrier_defer_id); } } static void update_for_ip_ifname_change (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); g_hash_table_remove_all (priv->ip6_saved_properties); if (priv->dhcp4_client) { if (!nm_device_dhcp4_renew (self, FALSE)) { nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_DHCP_FAILED); return; } } if (priv->dhcp6_client) { if (!nm_device_dhcp6_renew (self, FALSE)) { nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_DHCP_FAILED); return; } } if (priv->rdisc) { /* FIXME: todo */ } if (priv->dnsmasq_manager) { /* FIXME: todo */ } } static void device_set_master (NMDevice *self, int ifindex) { NMDevice *master; NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); master = nm_manager_get_device_by_ifindex (nm_manager_get (), ifindex); if (master && NM_DEVICE_GET_CLASS (master)->enslave_slave) { g_clear_object (&priv->master); priv->master = g_object_ref (master); nm_device_master_add_slave (master, self, FALSE); } else if (master) { _LOGI (LOGD_DEVICE, "enslaved to non-master-type device %s; ignoring", nm_device_get_iface (master)); } else { _LOGW (LOGD_DEVICE, "enslaved to unknown device %d %s", ifindex, nm_platform_link_get_name (ifindex)); } } static void device_link_changed (NMDevice *self, NMPlatformLink *info) { NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMUtilsIPv6IfaceId token_iid; gboolean ip_ifname_changed = FALSE; if (info->udi && g_strcmp0 (info->udi, priv->udi)) { /* Update UDI to what udev gives us */ g_free (priv->udi); priv->udi = g_strdup (info->udi); g_object_notify (G_OBJECT (self), NM_DEVICE_UDI); } /* Update MTU if it has changed. */ if (priv->mtu != info->mtu) { priv->mtu = info->mtu; g_object_notify (G_OBJECT (self), NM_DEVICE_MTU); } if (info->name[0] && strcmp (priv->iface, info->name) != 0) { _LOGI (LOGD_DEVICE, "interface index %d renamed iface from '%s' to '%s'", priv->ifindex, priv->iface, info->name); g_free (priv->iface); priv->iface = g_strdup (info->name); /* If the device has no explicit ip_iface, then changing iface changes ip_iface too. */ ip_ifname_changed = !priv->ip_iface; g_object_notify (G_OBJECT (self), NM_DEVICE_IFACE); if (ip_ifname_changed) g_object_notify (G_OBJECT (self), NM_DEVICE_IP_IFACE); /* Re-match available connections against the new interface name */ nm_device_recheck_available_connections (self); /* Let any connections that use the new interface name have a chance * to auto-activate on the device. */ nm_device_emit_recheck_auto_activate (self); } /* Update slave status for external changes */ if (priv->enslaved && info->master != nm_device_get_ifindex (priv->master)) nm_device_release_one_slave (priv->master, self, FALSE, NM_DEVICE_STATE_REASON_NONE); if (info->master && !priv->enslaved) { device_set_master (self, info->master); if (priv->master) nm_device_enslave_slave (priv->master, self, NULL); } if (priv->rdisc && nm_platform_link_get_ipv6_token (priv->ifindex, &token_iid)) { _LOGD (LOGD_DEVICE, "IPv6 tokenized identifier present on device %s", priv->iface); if (nm_rdisc_set_iid (priv->rdisc, token_iid)) nm_rdisc_start (priv->rdisc); } if (klass->link_changed) klass->link_changed (self, info); /* Update DHCP, etc, if needed */ if (ip_ifname_changed) update_for_ip_ifname_change (self); if (priv->up != info->up) { priv->up = info->up; /* Manage externally-created software interfaces only when they are IFF_UP */ g_assert (priv->ifindex > 0); if (is_software_external (self)) { gboolean external_down = nm_device_get_unmanaged_flag (self, NM_UNMANAGED_EXTERNAL_DOWN); if (external_down && info->up) { if (nm_device_get_state (self) < NM_DEVICE_STATE_DISCONNECTED) { /* Ensure the assume check is queued before any queued state changes * from the transition to UNAVAILABLE. */ nm_device_queue_recheck_assume (self); /* Resetting the EXTERNAL_DOWN flag may change the device's state * to UNAVAILABLE. To ensure that the state change doesn't touch * the device before assumption occurs, pass * NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED as the reason. */ nm_device_set_unmanaged (self, NM_UNMANAGED_EXTERNAL_DOWN, FALSE, NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED); } else { /* Don't trigger a state change; if the device is in a * state higher than UNAVAILABLE, it is already IFF_UP * or an explicit activation request was received. */ priv->unmanaged_flags &= ~NM_UNMANAGED_EXTERNAL_DOWN; } } else if (!external_down && !info->up && nm_device_get_state (self) <= NM_DEVICE_STATE_DISCONNECTED) { /* If the device is already disconnected and is set !IFF_UP, * unmanage it. */ nm_device_set_unmanaged (self, NM_UNMANAGED_EXTERNAL_DOWN, TRUE, NM_DEVICE_STATE_REASON_USER_REQUESTED); } } } } static void device_ip_link_changed (NMDevice *self, NMPlatformLink *info) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (info->name[0] && g_strcmp0 (priv->ip_iface, info->name)) { _LOGI (LOGD_DEVICE, "interface index %d renamed ip_iface (%d) from '%s' to '%s'", priv->ifindex, nm_device_get_ip_ifindex (self), priv->ip_iface, info->name); g_free (priv->ip_iface); priv->ip_iface = g_strdup (info->name); g_object_notify (G_OBJECT (self), NM_DEVICE_IP_IFACE); update_for_ip_ifname_change (self); } } static void link_changed_cb (NMPlatform *platform, int ifindex, NMPlatformLink *info, NMPlatformSignalChangeType change_type, NMPlatformReason reason, NMDevice *self) { if (change_type != NM_PLATFORM_SIGNAL_CHANGED) return; /* We don't filter by 'reason' because we are interested in *all* link * changes. For example a call to nm_platform_link_set_up() may result * in an internal carrier change (i.e. we ask the kernel to set IFF_UP * and it results in also setting IFF_LOWER_UP. */ if (ifindex == nm_device_get_ifindex (self)) device_link_changed (self, info); else if (ifindex == nm_device_get_ip_ifindex (self)) device_ip_link_changed (self, info); } static void link_changed (NMDevice *self, NMPlatformLink *info) { /* Update carrier from link event if applicable. */ if ( device_has_capability (self, NM_DEVICE_CAP_CARRIER_DETECT) && !device_has_capability (self, NM_DEVICE_CAP_NONSTANDARD_CARRIER)) nm_device_set_carrier (self, info->connected); } /** * nm_device_notify_component_added(): * @self: the #NMDevice * @component: the component being added by a plugin * * Called by the manager to notify the device that a new component has * been found. The device implementation should return %TRUE if it * wishes to claim the component, or %FALSE if it cannot. * * Returns: %TRUE to claim the component, %FALSE if the component cannot be * claimed. */ gboolean nm_device_notify_component_added (NMDevice *self, GObject *component) { if (NM_DEVICE_GET_CLASS (self)->component_added) return NM_DEVICE_GET_CLASS (self)->component_added (self, component); return FALSE; } /** * nm_device_owns_iface(): * @self: the #NMDevice * @iface: an interface name * * Called by the manager to ask if the device or any of its components owns * @iface. For example, a WWAN implementation would return %TRUE for an * ethernet interface name that was owned by the WWAN device's modem component, * because that ethernet interface is controlled by the WWAN device and cannot * be used independently of the WWAN device. * * Returns: %TRUE if @self or it's components owns the interface name, * %FALSE if not */ gboolean nm_device_owns_iface (NMDevice *self, const char *iface) { if (NM_DEVICE_GET_CLASS (self)->owns_iface) return NM_DEVICE_GET_CLASS (self)->owns_iface (self, iface); return FALSE; } NMConnection * nm_device_new_default_connection (NMDevice *self) { if (NM_DEVICE_GET_CLASS (self)->new_default_connection) return NM_DEVICE_GET_CLASS (self)->new_default_connection (self); return NULL; } static void slave_state_changed (NMDevice *slave, NMDeviceState slave_new_state, NMDeviceState slave_old_state, NMDeviceStateReason reason, NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); gboolean release = FALSE; _LOGD (LOGD_DEVICE, "slave %s state change %d (%s) -> %d (%s)", nm_device_get_iface (slave), slave_old_state, state_to_string (slave_old_state), slave_new_state, state_to_string (slave_new_state)); /* Don't try to enslave slaves until the master is ready */ if (priv->state < NM_DEVICE_STATE_CONFIG) return; if (slave_new_state == NM_DEVICE_STATE_IP_CONFIG) nm_device_enslave_slave (self, slave, nm_device_get_connection (slave)); else if (slave_new_state > NM_DEVICE_STATE_ACTIVATED) release = TRUE; else if ( slave_new_state <= NM_DEVICE_STATE_DISCONNECTED && slave_old_state > NM_DEVICE_STATE_DISCONNECTED) { /* Catch failures due to unavailable or unmanaged */ release = TRUE; } if (release) { nm_device_release_one_slave (self, slave, TRUE, reason); /* Bridge/bond/team interfaces are left up until manually deactivated */ if (priv->slaves == NULL && priv->state == NM_DEVICE_STATE_ACTIVATED) _LOGD (LOGD_DEVICE, "last slave removed; remaining activated"); } } /** * nm_device_master_add_slave: * @self: the master device * @slave: the slave device to enslave * @configure: pass %TRUE if the slave should be configured by the master, or * %FALSE if it is already configured outside NetworkManager * * If @self is capable of enslaving other devices (ie it's a bridge, bond, team, * etc) then this function adds @slave to the slave list for later enslavement. * * Returns: %TRUE on success, %FALSE on failure */ static gboolean nm_device_master_add_slave (NMDevice *self, NMDevice *slave, gboolean configure) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); SlaveInfo *info; g_return_val_if_fail (self != NULL, FALSE); g_return_val_if_fail (slave != NULL, FALSE); g_return_val_if_fail (NM_DEVICE_GET_CLASS (self)->enslave_slave != NULL, FALSE); if (configure) g_return_val_if_fail (nm_device_get_state (slave) >= NM_DEVICE_STATE_DISCONNECTED, FALSE); if (!find_slave_info (self, slave)) { info = g_malloc0 (sizeof (SlaveInfo)); info->slave = g_object_ref (slave); info->configure = configure; info->watch_id = g_signal_connect (slave, "state-changed", G_CALLBACK (slave_state_changed), self); priv->slaves = g_slist_append (priv->slaves, info); } nm_device_queue_recheck_assume (self); return TRUE; } /** * nm_device_master_get_slaves: * @self: the master device * * Returns: any slaves of which @self is the master. Caller owns returned list. */ GSList * nm_device_master_get_slaves (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); GSList *slaves = NULL, *iter; for (iter = priv->slaves; iter; iter = g_slist_next (iter)) slaves = g_slist_prepend (slaves, ((SlaveInfo *) iter->data)->slave); return slaves; } /** * nm_device_master_get_slave_by_ifindex: * @self: the master device * @ifindex: the slave's interface index * * Returns: the slave with the given @ifindex of which @self is the master, * or %NULL if no device with @ifindex is a slave of @self. */ NMDevice * nm_device_master_get_slave_by_ifindex (NMDevice *self, int ifindex) { GSList *iter; for (iter = NM_DEVICE_GET_PRIVATE (self)->slaves; iter; iter = g_slist_next (iter)) { SlaveInfo *info = iter->data; if (nm_device_get_ip_ifindex (info->slave) == ifindex) return info->slave; } return NULL; } /** * nm_device_master_check_slave_physical_port: * @self: the master device * @slave: a slave device * @log_domain: domain to log a warning in * * Checks if @self already has a slave with the same #NMDevice:physical-port-id * as @slave, and logs a warning if so. */ void nm_device_master_check_slave_physical_port (NMDevice *self, NMDevice *slave, guint64 log_domain) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); const char *slave_physical_port_id, *existing_physical_port_id; SlaveInfo *info; GSList *iter; slave_physical_port_id = nm_device_get_physical_port_id (slave); if (!slave_physical_port_id) return; for (iter = priv->slaves; iter; iter = iter->next) { info = iter->data; if (info->slave == slave) continue; existing_physical_port_id = nm_device_get_physical_port_id (info->slave); if (!g_strcmp0 (slave_physical_port_id, existing_physical_port_id)) { _LOGW (log_domain, "slave %s shares a physical port with existing slave %s", nm_device_get_ip_iface (slave), nm_device_get_ip_iface (info->slave)); /* Since this function will get called for every slave, we only have * to warn about the first match we find; if there are other matches * later in the list, we will have already warned about them matching * @existing earlier. */ return; } } } /* release all slaves */ static void nm_device_master_release_slaves (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMDeviceStateReason reason; /* Don't release the slaves if this connection doesn't belong to NM. */ if (nm_device_uses_generated_assumed_connection (self)) return; reason = priv->state_reason; if (priv->state == NM_DEVICE_STATE_FAILED) reason = NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED; while (priv->slaves) { SlaveInfo *info = priv->slaves->data; nm_device_release_one_slave (self, info->slave, TRUE, reason); } } /** * nm_device_get_master: * @self: the device * * If @self has been enslaved by another device, this returns that * device. Otherwise it returns %NULL. (In particular, note that if * @self is in the process of activating as a slave, but has not yet * been enslaved by its master, this will return %NULL.) * * Returns: (transfer none): @self's master, or %NULL */ NMDevice * nm_device_get_master (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->enslaved) return priv->master; else return NULL; } /** * nm_device_slave_notify_enslave: * @self: the slave device * @success: whether the enslaving operation succeeded * * Notifies a slave that either it has been enslaved, or else its master tried * to enslave it and failed. */ static void nm_device_slave_notify_enslave (NMDevice *self, gboolean success) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection = nm_device_get_connection (self); gboolean activating = (priv->state == NM_DEVICE_STATE_IP_CONFIG); g_assert (priv->master); if (!priv->enslaved) { if (success) { if (activating) { _LOGI (LOGD_DEVICE, "Activation: connection '%s' enslaved, continuing activation", nm_connection_get_id (connection)); } else _LOGI (LOGD_DEVICE, "enslaved to %s", nm_device_get_iface (priv->master)); priv->enslaved = TRUE; g_object_notify (G_OBJECT (self), NM_DEVICE_MASTER); } else if (activating) { _LOGW (LOGD_DEVICE, "Activation: connection '%s' could not be enslaved", nm_connection_get_id (connection)); } } if (activating) { priv->ip4_state = IP_DONE; priv->ip6_state = IP_DONE; nm_device_queue_state (self, success ? NM_DEVICE_STATE_SECONDARIES : NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_NONE); } else nm_device_queue_recheck_assume (self); } /** * nm_device_slave_notify_release: * @self: the slave device * @reason: the reason associated with the state change * * Notifies a slave that it has been released, and why. */ static void nm_device_slave_notify_release (NMDevice *self, NMDeviceStateReason reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection = nm_device_get_connection (self); NMDeviceState new_state; const char *master_status; if ( reason != NM_DEVICE_STATE_REASON_NONE && priv->state > NM_DEVICE_STATE_DISCONNECTED && priv->state <= NM_DEVICE_STATE_ACTIVATED) { if (reason == NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED) { new_state = NM_DEVICE_STATE_FAILED; master_status = "failed"; } else if (reason == NM_DEVICE_STATE_REASON_USER_REQUESTED) { new_state = NM_DEVICE_STATE_DEACTIVATING; master_status = "deactivated by user request"; } else { new_state = NM_DEVICE_STATE_DISCONNECTED; master_status = "deactivated"; } _LOGD (LOGD_DEVICE, "Activation: connection '%s' master %s", nm_connection_get_id (connection), master_status); nm_device_queue_state (self, new_state, reason); } else if (priv->master) _LOGI (LOGD_DEVICE, "released from master %s", nm_device_get_iface (priv->master)); else _LOGD (LOGD_DEVICE, "released from master%s", priv->enslaved ? "" : " (was not enslaved)"); if (priv->enslaved) { priv->enslaved = FALSE; g_object_notify (G_OBJECT (self), NM_DEVICE_MASTER); } } /** * nm_device_get_enslaved: * @self: the #NMDevice * * Returns: %TRUE if the device is enslaved to a master device (eg bridge or * bond or team), %FALSE if not */ gboolean nm_device_get_enslaved (NMDevice *self) { return NM_DEVICE_GET_PRIVATE (self)->enslaved; } /** * nm_device_removed: * @self: the #NMDevice * * Called by the manager when the device was removed. Releases the device from * the master in case it's enslaved. */ void nm_device_removed (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->enslaved) nm_device_release_one_slave (priv->master, self, FALSE, NM_DEVICE_STATE_REASON_REMOVED); } static gboolean is_available (NMDevice *self, NMDeviceCheckDevAvailableFlags flags) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->carrier || priv->ignore_carrier) return TRUE; if (NM_FLAGS_HAS (flags, NM_DEVICE_CHECK_DEV_AVAILABLE_IGNORE_CARRIER)) return TRUE; return FALSE; } /** * nm_device_is_available: * @self: the #NMDevice * @flags: additional flags to influence the check. Flags have the * meaning to increase the availability of a device. * * Checks if @self would currently be capable of activating a * connection. In particular, it checks that the device is ready (eg, * is not missing firmware), that it has carrier (if necessary), and * that any necessary external software (eg, ModemManager, * wpa_supplicant) is available. * * @self can only be in a state higher than * %NM_DEVICE_STATE_UNAVAILABLE when nm_device_is_available() returns * %TRUE. (But note that it can still be %NM_DEVICE_STATE_UNMANAGED * when it is available.) * * Returns: %TRUE or %FALSE */ gboolean nm_device_is_available (NMDevice *self, NMDeviceCheckDevAvailableFlags flags) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->firmware_missing) return FALSE; return NM_DEVICE_GET_CLASS (self)->is_available (self, flags); } gboolean nm_device_get_enabled (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); if (NM_DEVICE_GET_CLASS (self)->get_enabled) return NM_DEVICE_GET_CLASS (self)->get_enabled (self); return TRUE; } void nm_device_set_enabled (NMDevice *self, gboolean enabled) { g_return_if_fail (NM_IS_DEVICE (self)); if (NM_DEVICE_GET_CLASS (self)->set_enabled) NM_DEVICE_GET_CLASS (self)->set_enabled (self, enabled); } /** * nm_device_get_autoconnect: * @self: the #NMDevice * * Returns: %TRUE if the device allows autoconnect connections, or %FALSE if the * device is explicitly blocking all autoconnect connections. Does not take * into account transient conditions like companion devices that may wish to * block the device. */ gboolean nm_device_get_autoconnect (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); return NM_DEVICE_GET_PRIVATE (self)->autoconnect; } static void nm_device_set_autoconnect (NMDevice *self, gboolean autoconnect) { NMDevicePrivate *priv; g_return_if_fail (NM_IS_DEVICE (self)); priv = NM_DEVICE_GET_PRIVATE (self); if (priv->autoconnect == autoconnect) return; if (autoconnect) { /* Default-unmanaged devices never autoconnect */ if (!nm_device_get_default_unmanaged (self)) { priv->autoconnect = TRUE; g_object_notify (G_OBJECT (self), NM_DEVICE_AUTOCONNECT); } } else { priv->autoconnect = FALSE; g_object_notify (G_OBJECT (self), NM_DEVICE_AUTOCONNECT); } } static gboolean autoconnect_allowed_accumulator (GSignalInvocationHint *ihint, GValue *return_accu, const GValue *handler_return, gpointer data) { if (!g_value_get_boolean (handler_return)) g_value_set_boolean (return_accu, FALSE); return TRUE; } /** * nm_device_autoconnect_allowed: * @self: the #NMDevice * * Returns: %TRUE if the device can be auto-connected immediately, taking * transient conditions into account (like companion devices that may wish to * block autoconnect for a time). */ gboolean nm_device_autoconnect_allowed (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); GValue instance = G_VALUE_INIT; GValue retval = G_VALUE_INIT; if (priv->state < NM_DEVICE_STATE_DISCONNECTED || !priv->autoconnect) return FALSE; /* The 'autoconnect-allowed' signal is emitted on a device to allow * other listeners to block autoconnect on the device if they wish. * This is mainly used by the OLPC Mesh devices to block autoconnect * on their companion WiFi device as they share radio resources and * cannot be connected at the same time. */ g_value_init (&instance, G_TYPE_OBJECT); g_value_set_object (&instance, self); g_value_init (&retval, G_TYPE_BOOLEAN); if (priv->autoconnect) g_value_set_boolean (&retval, TRUE); else g_value_set_boolean (&retval, FALSE); /* Use g_signal_emitv() rather than g_signal_emit() to avoid the return * value being changed if no handlers are connected */ g_signal_emitv (&instance, signals[AUTOCONNECT_ALLOWED], 0, &retval); g_value_unset (&instance); return g_value_get_boolean (&retval); } static gboolean can_auto_connect (NMDevice *self, NMConnection *connection, char **specific_object) { NMSettingConnection *s_con; s_con = nm_connection_get_setting_connection (connection); if (!nm_setting_connection_get_autoconnect (s_con)) return FALSE; return nm_device_check_connection_available (self, connection, NM_DEVICE_CHECK_CON_AVAILABLE_NONE, NULL); } /** * nm_device_can_auto_connect: * @self: an #NMDevice * @connection: a #NMConnection * @specific_object: (out) (transfer full): on output, the path of an * object associated with the returned connection, to be passed to * nm_manager_activate_connection(), or %NULL. * * Checks if @connection can be auto-activated on @self right now. * This requires, at a minimum, that the connection be compatible with * @self, and that it have the #NMSettingConnection:autoconnect property * set, and that the device allow auto connections. Some devices impose * additional requirements. (Eg, a Wi-Fi connection can only be activated * if its SSID was seen in the last scan.) * * Returns: %TRUE, if the @connection can be auto-activated. **/ gboolean nm_device_can_auto_connect (NMDevice *self, NMConnection *connection, char **specific_object) { g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); g_return_val_if_fail (NM_IS_CONNECTION (connection), FALSE); g_return_val_if_fail (specific_object && !*specific_object, FALSE); if (nm_device_autoconnect_allowed (self)) return NM_DEVICE_GET_CLASS (self)->can_auto_connect (self, connection, specific_object); return FALSE; } static gboolean device_has_config (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); /* Check for IP configuration. */ if (priv->ip4_config && nm_ip4_config_get_num_addresses (priv->ip4_config)) return TRUE; if (priv->ip6_config && nm_ip6_config_get_num_addresses (priv->ip6_config)) return TRUE; /* The existence of a software device is good enough. */ if (nm_device_is_software (self)) return TRUE; /* Slaves are also configured by definition */ if (nm_platform_link_get_master (priv->ifindex) > 0) return TRUE; return FALSE; } /** * nm_device_master_update_slave_connection: * @self: the master #NMDevice * @slave: the slave #NMDevice * @connection: the #NMConnection to update with the slave settings * @GError: (out): error description * * Reads the slave configuration for @slave and updates @connection with those * properties. This invokes a virtual function on the master device @self. * * Returns: %TRUE if the configuration was read and @connection updated, * %FALSE on failure. */ gboolean nm_device_master_update_slave_connection (NMDevice *self, NMDevice *slave, NMConnection *connection, GError **error) { NMDeviceClass *klass; gboolean success; g_return_val_if_fail (self, FALSE); g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); g_return_val_if_fail (slave, FALSE); g_return_val_if_fail (connection, FALSE); g_return_val_if_fail (!error || !*error, FALSE); g_return_val_if_fail (nm_connection_get_setting_connection (connection), FALSE); g_return_val_if_fail (nm_device_get_iface (self), FALSE); klass = NM_DEVICE_GET_CLASS (self); if (klass->master_update_slave_connection) { success = klass->master_update_slave_connection (self, slave, connection, error); g_return_val_if_fail (!error || (success && !*error) || *error, success); return success; } g_set_error (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_FAILED, "master device '%s' cannot update a slave connection for slave device '%s' (master type not supported?)", nm_device_get_iface (self), nm_device_get_iface (slave)); return FALSE; } NMConnection * nm_device_generate_connection (NMDevice *self, NMDevice *master) { NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); const char *ifname = nm_device_get_iface (self); NMConnection *connection; NMSetting *s_con; NMSetting *s_ip4; NMSetting *s_ip6; gs_free char *uuid = NULL; const char *ip4_method, *ip6_method; GError *error = NULL; /* If update_connection() is not implemented, just fail. */ if (!klass->update_connection) return NULL; /* Return NULL if device is unconfigured. */ if (!device_has_config (self)) { _LOGD (LOGD_DEVICE, "device has no existing configuration"); return NULL; } connection = nm_simple_connection_new (); s_con = nm_setting_connection_new (); uuid = nm_utils_uuid_generate (); g_object_set (s_con, NM_SETTING_CONNECTION_UUID, uuid, NM_SETTING_CONNECTION_ID, ifname, NM_SETTING_CONNECTION_AUTOCONNECT, FALSE, NM_SETTING_CONNECTION_INTERFACE_NAME, ifname, NM_SETTING_CONNECTION_TIMESTAMP, (guint64) time (NULL), NULL); if (klass->connection_type) g_object_set (s_con, NM_SETTING_CONNECTION_TYPE, klass->connection_type, NULL); nm_connection_add_setting (connection, s_con); /* If the device is a slave, update various slave settings */ if (master) { if (!nm_device_master_update_slave_connection (master, self, connection, &error)) { _LOGE (LOGD_DEVICE, "master device '%s' failed to update slave connection: %s", nm_device_get_iface (master), error ? error->message : "(unknown error)"); g_error_free (error); g_object_unref (connection); return NULL; } } else { /* Only regular and master devices get IP configuration; slaves do not */ s_ip4 = nm_ip4_config_create_setting (priv->ip4_config); nm_connection_add_setting (connection, s_ip4); s_ip6 = nm_ip6_config_create_setting (priv->ip6_config); nm_connection_add_setting (connection, s_ip6); } klass->update_connection (self, connection); /* Check the connection in case of update_connection() bug. */ if (!nm_connection_verify (connection, &error)) { _LOGE (LOGD_DEVICE, "Generated connection does not verify: %s", error->message); g_clear_error (&error); g_object_unref (connection); return NULL; } /* Ignore the connection if it has no IP configuration, * no slave configuration, and is not a master interface. */ ip4_method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); ip6_method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG); if ( g_strcmp0 (ip4_method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED) == 0 && g_strcmp0 (ip6_method, NM_SETTING_IP6_CONFIG_METHOD_IGNORE) == 0 && !nm_setting_connection_get_master (NM_SETTING_CONNECTION (s_con)) && !priv->slaves) { _LOGD (LOGD_DEVICE, "ignoring generated connection (no IP and not in master-slave relationship)"); g_object_unref (connection); connection = NULL; } return connection; } gboolean nm_device_complete_connection (NMDevice *self, NMConnection *connection, const char *specific_object, const GSList *existing_connections, GError **error) { gboolean success = FALSE; g_return_val_if_fail (self != NULL, FALSE); g_return_val_if_fail (connection != NULL, FALSE); if (!NM_DEVICE_GET_CLASS (self)->complete_connection) { g_set_error (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_INVALID_CONNECTION, "Device class %s had no complete_connection method", G_OBJECT_TYPE_NAME (self)); return FALSE; } success = NM_DEVICE_GET_CLASS (self)->complete_connection (self, connection, specific_object, existing_connections, error); if (success) success = nm_connection_verify (connection, error); return success; } static gboolean check_connection_compatible (NMDevice *self, NMConnection *connection) { NMSettingConnection *s_con; const char *config_iface, *device_iface; s_con = nm_connection_get_setting_connection (connection); g_assert (s_con); config_iface = nm_setting_connection_get_interface_name (s_con); device_iface = nm_device_get_iface (self); if (config_iface && strcmp (config_iface, device_iface) != 0) return FALSE; return TRUE; } /** * nm_device_check_connection_compatible: * @self: an #NMDevice * @connection: an #NMConnection * * Checks if @connection could potentially be activated on @self. * This means only that @self has the proper capabilities, and that * @connection is not locked to some other device. It does not * necessarily mean that @connection could be activated on @self * right now. (Eg, it might refer to a Wi-Fi network that is not * currently available.) * * Returns: #TRUE if @connection could potentially be activated on * @self. */ gboolean nm_device_check_connection_compatible (NMDevice *self, NMConnection *connection) { g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); g_return_val_if_fail (NM_IS_CONNECTION (connection), FALSE); return NM_DEVICE_GET_CLASS (self)->check_connection_compatible (self, connection); } /** * nm_device_can_assume_connections: * @self: #NMDevice instance * * This is a convenience function to determine whether connection assumption * is available for this device. * * Returns: %TRUE if the device is capable of assuming connections, %FALSE if not */ static gboolean nm_device_can_assume_connections (NMDevice *self) { return !!NM_DEVICE_GET_CLASS (self)->update_connection; } /** * nm_device_can_assume_active_connection: * @self: #NMDevice instance * * This is a convenience function to determine whether the device's active * connection can be assumed if NetworkManager restarts. This method returns * %TRUE if and only if the device can assume connections, and the device has * an active connection, and that active connection can be assumed. * * Returns: %TRUE if the device's active connection can be assumed, or %FALSE * if there is no active connection or the active connection cannot be * assumed. */ gboolean nm_device_can_assume_active_connection (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; const char *method; const char *assumable_ip6_methods[] = { NM_SETTING_IP6_CONFIG_METHOD_IGNORE, NM_SETTING_IP6_CONFIG_METHOD_AUTO, NM_SETTING_IP6_CONFIG_METHOD_DHCP, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL, NM_SETTING_IP6_CONFIG_METHOD_MANUAL, NULL }; const char *assumable_ip4_methods[] = { NM_SETTING_IP4_CONFIG_METHOD_DISABLED, NM_SETTING_IP6_CONFIG_METHOD_AUTO, NM_SETTING_IP6_CONFIG_METHOD_MANUAL, NULL }; if (!nm_device_can_assume_connections (self)) return FALSE; connection = nm_device_get_connection (self); if (!connection) return FALSE; /* Can't assume connections that aren't yet configured * FIXME: what about bridges/bonds waiting for slaves? */ if (priv->state < NM_DEVICE_STATE_IP_CONFIG) return FALSE; if (priv->ip4_state != IP_DONE && priv->ip6_state != IP_DONE) return FALSE; method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG); if (!_nm_utils_string_in_list (method, assumable_ip6_methods)) return FALSE; method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); if (!_nm_utils_string_in_list (method, assumable_ip4_methods)) return FALSE; return TRUE; } static gboolean nm_device_emit_recheck_assume (gpointer self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); priv->recheck_assume_id = 0; if (!nm_device_get_act_request (self)) { _LOGD (LOGD_DEVICE, "emit RECHECK_ASSUME signal"); g_signal_emit (self, signals[RECHECK_ASSUME], 0); } return G_SOURCE_REMOVE; } void nm_device_queue_recheck_assume (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (nm_device_can_assume_connections (self) && !priv->recheck_assume_id) priv->recheck_assume_id = g_idle_add (nm_device_emit_recheck_assume, self); } void nm_device_emit_recheck_auto_activate (NMDevice *self) { g_signal_emit (self, signals[RECHECK_AUTO_ACTIVATE], 0); } static void dnsmasq_state_changed_cb (NMDnsMasqManager *manager, guint32 status, gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); switch (status) { case NM_DNSMASQ_STATUS_DEAD: nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_SHARED_START_FAILED); break; default: break; } } static void activation_source_clear (NMDevice *self, gboolean remove_source, int family) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); guint *act_source_id; gpointer *act_source_func; if (family == AF_INET6) { act_source_id = &priv->act_source6_id; act_source_func = &priv->act_source6_func; } else { act_source_id = &priv->act_source_id; act_source_func = &priv->act_source_func; } if (*act_source_id) { if (remove_source) g_source_remove (*act_source_id); *act_source_id = 0; *act_source_func = NULL; } } static void activation_source_schedule (NMDevice *self, GSourceFunc func, int family) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); guint *act_source_id; gpointer *act_source_func; if (family == AF_INET6) { act_source_id = &priv->act_source6_id; act_source_func = &priv->act_source6_func; } else { act_source_id = &priv->act_source_id; act_source_func = &priv->act_source_func; } if (*act_source_id) _LOGE (LOGD_DEVICE, "activation stage already scheduled"); /* Don't bother rescheduling the same function that's about to * run anyway. Fixes issues with crappy wireless drivers sending * streams of associate events before NM has had a chance to process * the first one. */ if (!*act_source_id || (*act_source_func != func)) { activation_source_clear (self, TRUE, family); *act_source_id = g_idle_add (func, self); *act_source_func = func; } } static gboolean get_ip_config_may_fail (NMDevice *self, int family) { NMConnection *connection; NMSettingIPConfig *s_ip = NULL; g_return_val_if_fail (self != NULL, TRUE); connection = nm_device_get_connection (self); g_assert (connection); /* Fail the connection if the failed IP method is required to complete */ switch (family) { case AF_INET: s_ip = nm_connection_get_setting_ip4_config (connection); break; case AF_INET6: s_ip = nm_connection_get_setting_ip6_config (connection); break; default: g_assert_not_reached (); } return nm_setting_ip_config_get_may_fail (s_ip); } static void master_ready_cb (NMActiveConnection *active, GParamSpec *pspec, NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMActiveConnection *master; g_assert (priv->state == NM_DEVICE_STATE_PREPARE); /* Notify a master device that it has a new slave */ g_assert (nm_active_connection_get_master_ready (active)); master = nm_active_connection_get_master (active); priv->master = g_object_ref (nm_active_connection_get_device (master)); nm_device_master_add_slave (priv->master, self, nm_active_connection_get_assumed (active) ? FALSE : TRUE); _LOGD (LOGD_DEVICE, "master connection ready; master device %s", nm_device_get_iface (priv->master)); if (priv->master_ready_id) { g_signal_handler_disconnect (active, priv->master_ready_id); priv->master_ready_id = 0; } nm_device_activate_schedule_stage2_device_config (self); } static NMActStageReturn act_stage1_prepare (NMDevice *self, NMDeviceStateReason *reason) { return NM_ACT_STAGE_RETURN_SUCCESS; } /* * nm_device_activate_stage1_device_prepare * * Prepare for device activation * */ static gboolean nm_device_activate_stage1_device_prepare (gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMActStageReturn ret = NM_ACT_STAGE_RETURN_SUCCESS; NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE; NMActiveConnection *active = NM_ACTIVE_CONNECTION (priv->act_request); /* Clear the activation source ID now that this stage has run */ activation_source_clear (self, FALSE, 0); priv->ip4_state = priv->ip6_state = IP_NONE; /* Notify the new ActiveConnection along with the state change */ g_object_notify (G_OBJECT (self), NM_DEVICE_ACTIVE_CONNECTION); _LOGI (LOGD_DEVICE, "Activation: Stage 1 of 5 (Device Prepare) started..."); nm_device_state_changed (self, NM_DEVICE_STATE_PREPARE, NM_DEVICE_STATE_REASON_NONE); /* Assumed connections were already set up outside NetworkManager */ if (!nm_active_connection_get_assumed (active)) { ret = NM_DEVICE_GET_CLASS (self)->act_stage1_prepare (self, &reason); if (ret == NM_ACT_STAGE_RETURN_POSTPONE) { goto out; } else if (ret == NM_ACT_STAGE_RETURN_FAILURE) { nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason); goto out; } g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS); } if (nm_active_connection_get_master (active)) { /* If the master connection is ready for slaves, attach ourselves */ if (nm_active_connection_get_master_ready (active)) master_ready_cb (active, NULL, self); else { _LOGD (LOGD_DEVICE, "waiting for master connection to become ready"); /* Attach a signal handler and wait for the master connection to begin activating */ g_assert (priv->master_ready_id == 0); priv->master_ready_id = g_signal_connect (active, "notify::" NM_ACTIVE_CONNECTION_INT_MASTER_READY, (GCallback) master_ready_cb, self); /* Postpone */ } } else nm_device_activate_schedule_stage2_device_config (self); out: _LOGI (LOGD_DEVICE, "Activation: Stage 1 of 5 (Device Prepare) complete."); return FALSE; } /* * nm_device_activate_schedule_stage1_device_prepare * * Prepare a device for activation * */ void nm_device_activate_schedule_stage1_device_prepare (NMDevice *self) { NMDevicePrivate *priv; g_return_if_fail (NM_IS_DEVICE (self)); priv = NM_DEVICE_GET_PRIVATE (self); g_return_if_fail (priv->act_request); activation_source_schedule (self, nm_device_activate_stage1_device_prepare, 0); _LOGI (LOGD_DEVICE, "Activation: Stage 1 of 5 (Device Prepare) scheduled..."); } static NMActStageReturn act_stage2_config (NMDevice *self, NMDeviceStateReason *reason) { /* Nothing to do */ return NM_ACT_STAGE_RETURN_SUCCESS; } /* * nm_device_activate_stage2_device_config * * Determine device parameters and set those on the device, ie * for wireless devices, set SSID, keys, etc. * */ static gboolean nm_device_activate_stage2_device_config (gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMActStageReturn ret; NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE; gboolean no_firmware = FALSE; NMActiveConnection *active = NM_ACTIVE_CONNECTION (priv->act_request); GSList *iter; /* Clear the activation source ID now that this stage has run */ activation_source_clear (self, FALSE, 0); _LOGI (LOGD_DEVICE, "Activation: Stage 2 of 5 (Device Configure) starting..."); nm_device_state_changed (self, NM_DEVICE_STATE_CONFIG, NM_DEVICE_STATE_REASON_NONE); /* Assumed connections were already set up outside NetworkManager */ if (!nm_active_connection_get_assumed (active)) { if (!nm_device_bring_up (self, FALSE, &no_firmware)) { if (no_firmware) nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_FIRMWARE_MISSING); else nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_CONFIG_FAILED); goto out; } ret = NM_DEVICE_GET_CLASS (self)->act_stage2_config (self, &reason); if (ret == NM_ACT_STAGE_RETURN_POSTPONE) goto out; else if (ret == NM_ACT_STAGE_RETURN_FAILURE) { nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason); goto out; } g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS); } /* If we have slaves that aren't yet enslaved, do that now */ for (iter = priv->slaves; iter; iter = g_slist_next (iter)) { SlaveInfo *info = iter->data; NMDeviceState slave_state = nm_device_get_state (info->slave); if (slave_state == NM_DEVICE_STATE_IP_CONFIG) nm_device_enslave_slave (self, info->slave, nm_device_get_connection (info->slave)); else if ( nm_device_uses_generated_assumed_connection (self) && slave_state <= NM_DEVICE_STATE_DISCONNECTED) nm_device_queue_recheck_assume (info->slave); } _LOGI (LOGD_DEVICE, "Activation: Stage 2 of 5 (Device Configure) successful."); nm_device_activate_schedule_stage3_ip_config_start (self); out: _LOGI (LOGD_DEVICE, "Activation: Stage 2 of 5 (Device Configure) complete."); return FALSE; } /* * nm_device_activate_schedule_stage2_device_config * * Schedule setup of the hardware device * */ void nm_device_activate_schedule_stage2_device_config (NMDevice *self) { NMDevicePrivate *priv; g_return_if_fail (NM_IS_DEVICE (self)); priv = NM_DEVICE_GET_PRIVATE (self); g_return_if_fail (priv->act_request); activation_source_schedule (self, nm_device_activate_stage2_device_config, 0); _LOGI (LOGD_DEVICE, "Activation: Stage 2 of 5 (Device Configure) scheduled..."); } /*********************************************/ /* avahi-autoipd stuff */ static void aipd_timeout_remove (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->aipd_timeout) { g_source_remove (priv->aipd_timeout); priv->aipd_timeout = 0; } } static void aipd_cleanup (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->aipd_watch) { g_source_remove (priv->aipd_watch); priv->aipd_watch = 0; } if (priv->aipd_pid > 0) { nm_utils_kill_child_sync (priv->aipd_pid, SIGKILL, LOGD_AUTOIP4, "avahi-autoipd", NULL, 0, 0); priv->aipd_pid = -1; } aipd_timeout_remove (self); } static NMIP4Config * aipd_get_ip4_config (NMDevice *self, guint32 lla) { NMIP4Config *config = NULL; NMPlatformIP4Address address; NMPlatformIP4Route route; config = nm_ip4_config_new (nm_device_get_ip_ifindex (self)); g_assert (config); memset (&address, 0, sizeof (address)); address.address = lla; address.plen = 16; address.source = NM_IP_CONFIG_SOURCE_IP4LL; nm_ip4_config_add_address (config, &address); /* Add a multicast route for link-local connections: destination= 224.0.0.0, netmask=240.0.0.0 */ memset (&route, 0, sizeof (route)); route.network = htonl (0xE0000000L); route.plen = 4; route.source = NM_IP_CONFIG_SOURCE_IP4LL; route.metric = nm_device_get_ip4_route_metric (self); nm_ip4_config_add_route (config, &route); return config; } #define IPV4LL_NETWORK (htonl (0xA9FE0000L)) #define IPV4LL_NETMASK (htonl (0xFFFF0000L)) void nm_device_handle_autoip4_event (NMDevice *self, const char *event, const char *address) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection = NULL; const char *method; NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE; g_return_if_fail (event != NULL); if (priv->act_request == NULL) return; connection = nm_act_request_get_connection (priv->act_request); g_assert (connection); /* Ignore if the connection isn't an AutoIP connection */ method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); if (g_strcmp0 (method, NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL) != 0) return; if (strcmp (event, "BIND") == 0) { guint32 lla; NMIP4Config *config; if (inet_pton (AF_INET, address, &lla) <= 0) { _LOGE (LOGD_AUTOIP4, "invalid address %s received from avahi-autoipd.", address); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_AUTOIP_ERROR); return; } if ((lla & IPV4LL_NETMASK) != IPV4LL_NETWORK) { _LOGE (LOGD_AUTOIP4, "invalid address %s received from avahi-autoipd (not link-local).", address); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_AUTOIP_ERROR); return; } config = aipd_get_ip4_config (self, lla); if (config == NULL) { _LOGE (LOGD_AUTOIP4, "failed to get autoip config"); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE); return; } if (priv->ip4_state == IP_CONF) { aipd_timeout_remove (self); nm_device_activate_schedule_ip4_config_result (self, config); } else if (priv->ip4_state == IP_DONE) { if (!ip4_config_merge_and_apply (self, config, TRUE, &reason)) { _LOGE (LOGD_AUTOIP4, "failed to update IP4 config for autoip change."); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason); } } else g_assert_not_reached (); g_object_unref (config); } else { _LOGW (LOGD_AUTOIP4, "autoip address %s no longer valid because '%s'.", address, event); /* The address is gone; terminate the connection or fail activation */ nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED); } } static void aipd_watch_cb (GPid pid, gint status, gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMDeviceState state; if (!priv->aipd_watch) return; priv->aipd_watch = 0; if (WIFEXITED (status)) _LOGD (LOGD_AUTOIP4, "avahi-autoipd exited with error code %d", WEXITSTATUS (status)); else if (WIFSTOPPED (status)) _LOGW (LOGD_AUTOIP4, "avahi-autoipd stopped unexpectedly with signal %d", WSTOPSIG (status)); else if (WIFSIGNALED (status)) _LOGW (LOGD_AUTOIP4, "avahi-autoipd died with signal %d", WTERMSIG (status)); else _LOGW (LOGD_AUTOIP4, "avahi-autoipd died from an unknown cause"); aipd_cleanup (self); state = nm_device_get_state (self); if (nm_device_is_activating (self) || (state == NM_DEVICE_STATE_ACTIVATED)) nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_AUTOIP_FAILED); } static gboolean aipd_timeout_cb (gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->aipd_timeout) { _LOGI (LOGD_AUTOIP4, "avahi-autoipd timed out."); priv->aipd_timeout = 0; aipd_cleanup (self); if (priv->ip4_state == IP_CONF) nm_device_activate_schedule_ip4_config_timeout (self); } return FALSE; } /* default to installed helper, but can be modified for testing */ const char *nm_device_autoipd_helper_path = LIBEXECDIR "/nm-avahi-autoipd.action"; static NMActStageReturn aipd_start (NMDevice *self, NMDeviceStateReason *reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); const char *argv[6]; char *cmdline; const char *aipd_binary; int i = 0; GError *error = NULL; aipd_cleanup (self); /* Find avahi-autoipd */ aipd_binary = nm_utils_find_helper ("avahi-autoipd", NULL, NULL); if (!aipd_binary) { _LOGW (LOGD_DEVICE | LOGD_AUTOIP4, "Activation: Stage 3 of 5 (IP Configure Start) failed" " to start avahi-autoipd: not found"); *reason = NM_DEVICE_STATE_REASON_AUTOIP_START_FAILED; return NM_ACT_STAGE_RETURN_FAILURE; } argv[i++] = aipd_binary; argv[i++] = "--script"; argv[i++] = nm_device_autoipd_helper_path; if (nm_logging_enabled (LOGL_DEBUG, LOGD_AUTOIP4)) argv[i++] = "--debug"; argv[i++] = nm_device_get_ip_iface (self); argv[i++] = NULL; cmdline = g_strjoinv (" ", (char **) argv); _LOGD (LOGD_AUTOIP4, "running: %s", cmdline); g_free (cmdline); if (!g_spawn_async ("/", (char **) argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD, nm_utils_setpgid, NULL, &(priv->aipd_pid), &error)) { _LOGW (LOGD_DEVICE | LOGD_AUTOIP4, "Activation: Stage 3 of 5 (IP Configure Start) failed" " to start avahi-autoipd: %s", error && error->message ? error->message : "(unknown)"); g_clear_error (&error); aipd_cleanup (self); return NM_ACT_STAGE_RETURN_FAILURE; } _LOGI (LOGD_DEVICE | LOGD_AUTOIP4, "Activation: Stage 3 of 5 (IP Configure Start) started" " avahi-autoipd..."); /* Monitor the child process so we know when it dies */ priv->aipd_watch = g_child_watch_add (priv->aipd_pid, aipd_watch_cb, self); /* Start a timeout to bound the address attempt */ priv->aipd_timeout = g_timeout_add_seconds (20, aipd_timeout_cb, self); return NM_ACT_STAGE_RETURN_POSTPONE; } /*********************************************/ static gboolean _device_get_default_route_from_platform (NMDevice *self, int addr_family, NMPlatformIPRoute *out_route) { gboolean success = FALSE; int ifindex = nm_device_get_ip_ifindex (self); GArray *routes; if (addr_family == AF_INET) routes = nm_platform_ip4_route_get_all (ifindex, NM_PLATFORM_GET_ROUTE_MODE_ONLY_DEFAULT); else routes = nm_platform_ip6_route_get_all (ifindex, NM_PLATFORM_GET_ROUTE_MODE_ONLY_DEFAULT); if (routes) { guint route_metric = G_MAXUINT32, m; const NMPlatformIPRoute *route = NULL, *r; guint i; /* if there are several default routes, find the one with the best metric */ for (i = 0; i < routes->len; i++) { if (addr_family == AF_INET) { r = (const NMPlatformIPRoute *) &g_array_index (routes, NMPlatformIP4Route, i); m = r->metric; } else { r = (const NMPlatformIPRoute *) &g_array_index (routes, NMPlatformIP6Route, i); m = nm_utils_ip6_route_metric_normalize (r->metric); } if (!route || m < route_metric) { route = r; route_metric = m; } } if (route) { if (addr_family == AF_INET) *((NMPlatformIP4Route *) out_route) = *((NMPlatformIP4Route *) route); else *((NMPlatformIP6Route *) out_route) = *((NMPlatformIP6Route *) route); success = TRUE; } g_array_free (routes, TRUE); } return success; } /*********************************************/ static void ensure_con_ipx_config (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); int ip_ifindex = nm_device_get_ip_ifindex (self); NMConnection *connection; g_assert (!!priv->con_ip4_config == !!priv->con_ip6_config); if (priv->con_ip4_config) return; connection = nm_device_get_connection (self); if (!connection) return; priv->con_ip4_config = nm_ip4_config_new (ip_ifindex); priv->con_ip6_config = nm_ip6_config_new (ip_ifindex); nm_ip4_config_merge_setting (priv->con_ip4_config, nm_connection_get_setting_ip4_config (connection), nm_device_get_ip4_route_metric (self)); nm_ip6_config_merge_setting (priv->con_ip6_config, nm_connection_get_setting_ip6_config (connection), nm_device_get_ip6_route_metric (self)); if (nm_device_uses_assumed_connection (self)) { /* For assumed connections ignore all addresses and routes. */ nm_ip4_config_reset_addresses (priv->con_ip4_config); nm_ip4_config_reset_routes (priv->con_ip4_config); nm_ip6_config_reset_addresses (priv->con_ip6_config); nm_ip6_config_reset_routes (priv->con_ip6_config); } } /*********************************************/ /* DHCPv4 stuff */ static void dhcp4_cleanup (NMDevice *self, gboolean stop, gboolean release) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->dhcp4_client) { /* Stop any ongoing DHCP transaction on this device */ if (priv->dhcp4_state_sigid) { g_signal_handler_disconnect (priv->dhcp4_client, priv->dhcp4_state_sigid); priv->dhcp4_state_sigid = 0; } nm_device_remove_pending_action (self, PENDING_ACTION_DHCP4, FALSE); if (stop) nm_dhcp_client_stop (priv->dhcp4_client, release); g_clear_object (&priv->dhcp4_client); } if (priv->dhcp4_config) { g_clear_object (&priv->dhcp4_config); g_object_notify (G_OBJECT (self), NM_DEVICE_DHCP4_CONFIG); } } static gboolean ip4_config_merge_and_apply (NMDevice *self, NMIP4Config *config, gboolean commit, NMDeviceStateReason *out_reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; gboolean success; NMIP4Config *composite; gboolean has_direct_route; const guint32 default_route_metric = nm_device_get_ip4_route_metric (self); guint32 gateway; /* Merge all the configs into the composite config */ if (config) { g_clear_object (&priv->dev_ip4_config); priv->dev_ip4_config = g_object_ref (config); } composite = nm_ip4_config_new (nm_device_get_ip_ifindex (self)); ensure_con_ipx_config (self); if (priv->dev_ip4_config) nm_ip4_config_merge (composite, priv->dev_ip4_config); if (priv->vpn4_config) nm_ip4_config_merge (composite, priv->vpn4_config); if (priv->ext_ip4_config) nm_ip4_config_merge (composite, priv->ext_ip4_config); /* Merge WWAN config *last* to ensure modem-given settings overwrite * any external stuff set by pppd or other scripts. */ if (priv->wwan_ip4_config) nm_ip4_config_merge (composite, priv->wwan_ip4_config); /* Merge user overrides into the composite config. For assumed connection, * con_ip4_config is empty. */ if (priv->con_ip4_config) nm_ip4_config_merge (composite, priv->con_ip4_config); connection = nm_device_get_connection (self); /* Add the default route. * * We keep track of the default route of a device in a private field. * NMDevice needs to know the default route at this point, because the gateway * might require a direct route (see below). * * But also, we don't want to add the default route to priv->ip4_config, * because the default route from the setting might not be the same that * NMDefaultRouteManager eventually configures (because the it might * tweak the effective metric). */ /* unless we come to a different conclusion below, we have no default route and * the route is assumed. */ priv->default_route.v4_has = FALSE; priv->default_route.v4_is_assumed = TRUE; if (!commit) { /* during a non-commit event, we always pickup whatever is configured. */ goto END_ADD_DEFAULT_ROUTE; } if (nm_device_uses_assumed_connection (self)) goto END_ADD_DEFAULT_ROUTE; /* we are about to commit (for a non-assumed connection). Enforce whatever we have * configured. */ priv->default_route.v4_is_assumed = FALSE; if ( !connection || !nm_default_route_manager_ip4_connection_has_default_route (nm_default_route_manager_get (), connection)) goto END_ADD_DEFAULT_ROUTE; if (!nm_ip4_config_get_num_addresses (composite)) { /* without addresses we can have no default route. */ goto END_ADD_DEFAULT_ROUTE; } gateway = nm_ip4_config_get_gateway (composite); if ( !gateway && nm_device_get_device_type (self) != NM_DEVICE_TYPE_MODEM) goto END_ADD_DEFAULT_ROUTE; has_direct_route = ( gateway == 0 || nm_ip4_config_get_subnet_for_host (composite, gateway) || nm_ip4_config_get_direct_route_for_host (composite, gateway)); priv->default_route.v4_has = TRUE; memset (&priv->default_route.v4, 0, sizeof (priv->default_route.v4)); priv->default_route.v4.source = NM_IP_CONFIG_SOURCE_USER; priv->default_route.v4.gateway = gateway; priv->default_route.v4.metric = default_route_metric; priv->default_route.v4.mss = nm_ip4_config_get_mss (composite); if (!has_direct_route) { NMPlatformIP4Route r = priv->default_route.v4; /* add a direct route to the gateway */ r.network = gateway; r.plen = 32; r.gateway = 0; nm_ip4_config_add_route (composite, &r); } END_ADD_DEFAULT_ROUTE: if (priv->default_route.v4_is_assumed) { /* If above does not explicitly assign a default route, we always pick up the * default route based on what is currently configured. * That means that even managed connections with never-default, can * get a default route (if configured externally). */ priv->default_route.v4_has = _device_get_default_route_from_platform (self, AF_INET, (NMPlatformIPRoute *) &priv->default_route.v4); } /* Allow setting MTU etc */ if (commit) { if (NM_DEVICE_GET_CLASS (self)->ip4_config_pre_commit) NM_DEVICE_GET_CLASS (self)->ip4_config_pre_commit (self, composite); } success = nm_device_set_ip4_config (self, composite, default_route_metric, commit, out_reason); g_object_unref (composite); return success; } static void dhcp4_lease_change (NMDevice *self, NMIP4Config *config) { NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE; g_return_if_fail (config != NULL); if (!ip4_config_merge_and_apply (self, config, TRUE, &reason)) { _LOGW (LOGD_DHCP4, "failed to update IPv4 config for DHCP change."); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason); } else { /* Notify dispatcher scripts of new DHCP4 config */ nm_dispatcher_call (DISPATCHER_ACTION_DHCP4_CHANGE, nm_device_get_connection (self), self, NULL, NULL, NULL); } } static void dhcp4_fail (NMDevice *self, gboolean timeout) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); dhcp4_cleanup (self, TRUE, FALSE); if (timeout || (priv->ip4_state == IP_CONF)) nm_device_activate_schedule_ip4_config_timeout (self); else if (priv->ip4_state == IP_DONE) nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED); else g_warn_if_reached (); } static void dhcp4_update_config (NMDevice *self, NMDhcp4Config *config, GHashTable *options) { GHashTableIter iter; const char *key, *value; /* Update the DHCP4 config object with new DHCP options */ nm_dhcp4_config_reset (config); g_hash_table_iter_init (&iter, options); while (g_hash_table_iter_next (&iter, (gpointer) &key, (gpointer) &value)) nm_dhcp4_config_add_option (config, key, value); g_object_notify (G_OBJECT (self), NM_DEVICE_DHCP4_CONFIG); } static void dhcp4_state_changed (NMDhcpClient *client, NMDhcpState state, NMIP4Config *ip4_config, GHashTable *options, gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); g_return_if_fail (nm_dhcp_client_get_ipv6 (client) == FALSE); g_return_if_fail (!ip4_config || NM_IS_IP4_CONFIG (ip4_config)); _LOGD (LOGD_DHCP4, "new DHCPv4 client state %d", state); switch (state) { case NM_DHCP_STATE_BOUND: if (!ip4_config) { _LOGW (LOGD_DHCP4, "failed to get IPv4 config in response to DHCP event."); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE); break; } dhcp4_update_config (self, priv->dhcp4_config, options); if (priv->ip4_state == IP_CONF) nm_device_activate_schedule_ip4_config_result (self, ip4_config); else if (priv->ip4_state == IP_DONE) dhcp4_lease_change (self, ip4_config); break; case NM_DHCP_STATE_TIMEOUT: dhcp4_fail (self, TRUE); break; case NM_DHCP_STATE_EXPIRE: /* Ignore expiry before we even have a lease (NAK, old lease, etc) */ if (priv->ip4_state == IP_CONF) break; /* Fall through */ case NM_DHCP_STATE_DONE: case NM_DHCP_STATE_FAIL: dhcp4_fail (self, FALSE); break; default: break; } } static NMActStageReturn dhcp4_start (NMDevice *self, NMConnection *connection, NMDeviceStateReason *reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMSettingIPConfig *s_ip4; const guint8 *hw_addr; size_t hw_addr_len = 0; GByteArray *tmp = NULL; s_ip4 = nm_connection_get_setting_ip4_config (connection); /* Clear old exported DHCP options */ if (priv->dhcp4_config) g_object_unref (priv->dhcp4_config); priv->dhcp4_config = nm_dhcp4_config_new (); hw_addr = nm_platform_link_get_address (nm_device_get_ip_ifindex (self), &hw_addr_len); if (hw_addr_len) { tmp = g_byte_array_sized_new (hw_addr_len); g_byte_array_append (tmp, hw_addr, hw_addr_len); } /* Begin DHCP on the interface */ g_warn_if_fail (priv->dhcp4_client == NULL); priv->dhcp4_client = nm_dhcp_manager_start_ip4 (nm_dhcp_manager_get (), nm_device_get_ip_iface (self), nm_device_get_ip_ifindex (self), tmp, nm_connection_get_uuid (connection), nm_device_get_ip4_route_metric (self), nm_setting_ip_config_get_dhcp_send_hostname (s_ip4), nm_setting_ip_config_get_dhcp_hostname (s_ip4), nm_setting_ip4_config_get_dhcp_client_id (NM_SETTING_IP4_CONFIG (s_ip4)), priv->dhcp_timeout, priv->dhcp_anycast_address, NULL); if (tmp) g_byte_array_free (tmp, TRUE); if (!priv->dhcp4_client) { *reason = NM_DEVICE_STATE_REASON_DHCP_START_FAILED; return NM_ACT_STAGE_RETURN_FAILURE; } priv->dhcp4_state_sigid = g_signal_connect (priv->dhcp4_client, NM_DHCP_CLIENT_SIGNAL_STATE_CHANGED, G_CALLBACK (dhcp4_state_changed), self); nm_device_add_pending_action (self, PENDING_ACTION_DHCP4, TRUE); /* DHCP devices will be notified by the DHCP manager when stuff happens */ return NM_ACT_STAGE_RETURN_POSTPONE; } gboolean nm_device_dhcp4_renew (NMDevice *self, gboolean release) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMActStageReturn ret; NMDeviceStateReason reason; NMConnection *connection; g_return_val_if_fail (priv->dhcp4_client != NULL, FALSE); _LOGI (LOGD_DHCP4, "DHCPv4 lease renewal requested"); /* Terminate old DHCP instance and release the old lease */ dhcp4_cleanup (self, TRUE, release); connection = nm_device_get_connection (self); g_assert (connection); /* Start DHCP again on the interface */ ret = dhcp4_start (self, connection, &reason); return (ret != NM_ACT_STAGE_RETURN_FAILURE); } /*********************************************/ static GHashTable *shared_ips = NULL; static void release_shared_ip (gpointer data) { g_hash_table_remove (shared_ips, data); } static gboolean reserve_shared_ip (NMDevice *self, NMSettingIPConfig *s_ip4, NMPlatformIP4Address *address) { if (G_UNLIKELY (shared_ips == NULL)) shared_ips = g_hash_table_new (g_direct_hash, g_direct_equal); memset (address, 0, sizeof (*address)); if (s_ip4 && nm_setting_ip_config_get_num_addresses (s_ip4)) { /* Use the first user-supplied address */ NMIPAddress *user = nm_setting_ip_config_get_address (s_ip4, 0); g_assert (user); nm_ip_address_get_address_binary (user, &address->address); address->plen = nm_ip_address_get_prefix (user); } else { /* Find an unused address in the 10.42.x.x range */ guint32 start = (guint32) ntohl (0x0a2a0001); /* 10.42.0.1 */ guint32 count = 0; while (g_hash_table_lookup (shared_ips, GUINT_TO_POINTER (start + count))) { count += ntohl (0x100); if (count > ntohl (0xFE00)) { _LOGE (LOGD_SHARING, "ran out of shared IP addresses!"); return FALSE; } } address->address = start + count; address->plen = 24; g_hash_table_insert (shared_ips, GUINT_TO_POINTER (address->address), GUINT_TO_POINTER (TRUE)); } return TRUE; } static NMIP4Config * shared4_new_config (NMDevice *self, NMConnection *connection, NMDeviceStateReason *reason) { NMIP4Config *config = NULL; NMPlatformIP4Address address; g_return_val_if_fail (self != NULL, NULL); if (!reserve_shared_ip (self, nm_connection_get_setting_ip4_config (connection), &address)) { *reason = NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE; return NULL; } config = nm_ip4_config_new (nm_device_get_ip_ifindex (self)); address.source = NM_IP_CONFIG_SOURCE_SHARED; nm_ip4_config_add_address (config, &address); /* Remove the address lock when the object gets disposed */ g_object_set_data_full (G_OBJECT (config), "shared-ip", GUINT_TO_POINTER (address.address), release_shared_ip); return config; } /*********************************************/ static gboolean connection_ip4_method_requires_carrier (NMConnection *connection, gboolean *out_ip4_enabled) { const char *method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); static const char *ip4_carrier_methods[] = { NM_SETTING_IP4_CONFIG_METHOD_AUTO, NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL, NULL }; if (out_ip4_enabled) *out_ip4_enabled = !!strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED); return _nm_utils_string_in_list (method, ip4_carrier_methods); } static gboolean connection_ip6_method_requires_carrier (NMConnection *connection, gboolean *out_ip6_enabled) { const char *method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG); static const char *ip6_carrier_methods[] = { NM_SETTING_IP6_CONFIG_METHOD_AUTO, NM_SETTING_IP6_CONFIG_METHOD_DHCP, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL, NULL }; if (out_ip6_enabled) *out_ip6_enabled = !!strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_IGNORE); return _nm_utils_string_in_list (method, ip6_carrier_methods); } static gboolean connection_requires_carrier (NMConnection *connection) { NMSettingIPConfig *s_ip4, *s_ip6; gboolean ip4_carrier_wanted, ip6_carrier_wanted; gboolean ip4_used = FALSE, ip6_used = FALSE; ip4_carrier_wanted = connection_ip4_method_requires_carrier (connection, &ip4_used); if (ip4_carrier_wanted) { /* If IPv4 wants a carrier and cannot fail, the whole connection * requires a carrier regardless of the IPv6 method. */ s_ip4 = nm_connection_get_setting_ip4_config (connection); if (s_ip4 && !nm_setting_ip_config_get_may_fail (s_ip4)) return TRUE; } ip6_carrier_wanted = connection_ip6_method_requires_carrier (connection, &ip6_used); if (ip6_carrier_wanted) { /* If IPv6 wants a carrier and cannot fail, the whole connection * requires a carrier regardless of the IPv4 method. */ s_ip6 = nm_connection_get_setting_ip6_config (connection); if (s_ip6 && !nm_setting_ip_config_get_may_fail (s_ip6)) return TRUE; } /* If an IP version wants a carrier and and the other IP version isn't * used, the connection requires carrier since it will just fail without one. */ if (ip4_carrier_wanted && !ip6_used) return TRUE; if (ip6_carrier_wanted && !ip4_used) return TRUE; /* If both want a carrier, the whole connection wants a carrier */ return ip4_carrier_wanted && ip6_carrier_wanted; } static gboolean have_any_ready_slaves (NMDevice *self, const GSList *slaves) { const GSList *iter; /* Any enslaved slave is "ready" in the generic case as it's * at least >= NM_DEVCIE_STATE_IP_CONFIG and has had Layer 2 * properties set up. */ for (iter = slaves; iter; iter = g_slist_next (iter)) { if (nm_device_get_enslaved (iter->data)) return TRUE; } return FALSE; } static gboolean ip4_requires_slaves (NMConnection *connection) { const char *method; method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); return strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO) == 0; } static NMActStageReturn act_stage3_ip4_config_start (NMDevice *self, NMIP4Config **out_config, NMDeviceStateReason *reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; NMActStageReturn ret = NM_ACT_STAGE_RETURN_FAILURE; const char *method; GSList *slaves; gboolean ready_slaves; g_return_val_if_fail (reason != NULL, NM_ACT_STAGE_RETURN_FAILURE); connection = nm_device_get_connection (self); g_assert (connection); if ( connection_ip4_method_requires_carrier (connection, NULL) && priv->is_master && !priv->carrier) { _LOGI (LOGD_IP4 | LOGD_DEVICE, "IPv4 config waiting until carrier is on"); return NM_ACT_STAGE_RETURN_WAIT; } if (priv->is_master && ip4_requires_slaves (connection)) { /* If the master has no ready slaves, and depends on slaves for * a successful IPv4 attempt, then postpone IPv4 addressing. */ slaves = nm_device_master_get_slaves (self); ready_slaves = NM_DEVICE_GET_CLASS (self)->have_any_ready_slaves (self, slaves); g_slist_free (slaves); if (ready_slaves == FALSE) { _LOGI (LOGD_DEVICE | LOGD_IP4, "IPv4 config waiting until slaves are ready"); return NM_ACT_STAGE_RETURN_WAIT; } } method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); /* Start IPv4 addressing based on the method requested */ if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO) == 0) ret = dhcp4_start (self, connection, reason); else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL) == 0) ret = aipd_start (self, reason); else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_MANUAL) == 0) { /* Use only IPv4 config from the connection data */ *out_config = nm_ip4_config_new (nm_device_get_ip_ifindex (self)); g_assert (*out_config); ret = NM_ACT_STAGE_RETURN_SUCCESS; } else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_SHARED) == 0) { *out_config = shared4_new_config (self, connection, reason); if (*out_config) { priv->dnsmasq_manager = nm_dnsmasq_manager_new (nm_device_get_ip_iface (self)); ret = NM_ACT_STAGE_RETURN_SUCCESS; } else ret = NM_ACT_STAGE_RETURN_FAILURE; } else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED) == 0) { /* Nothing to do... */ ret = NM_ACT_STAGE_RETURN_STOP; } else _LOGW (LOGD_IP4, "unhandled IPv4 config method '%s'; will fail", method); return ret; } /*********************************************/ /* DHCPv6 stuff */ static void dhcp6_cleanup (NMDevice *self, gboolean stop, gboolean release) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); priv->dhcp6_mode = NM_RDISC_DHCP_LEVEL_NONE; g_clear_object (&priv->dhcp6_ip6_config); if (priv->dhcp6_client) { if (priv->dhcp6_state_sigid) { g_signal_handler_disconnect (priv->dhcp6_client, priv->dhcp6_state_sigid); priv->dhcp6_state_sigid = 0; } if (stop) nm_dhcp_client_stop (priv->dhcp6_client, release); g_clear_object (&priv->dhcp6_client); } nm_device_remove_pending_action (self, PENDING_ACTION_DHCP6, FALSE); if (priv->dhcp6_config) { g_clear_object (&priv->dhcp6_config); g_object_notify (G_OBJECT (self), NM_DEVICE_DHCP6_CONFIG); } } static gboolean ip6_config_merge_and_apply (NMDevice *self, gboolean commit, NMDeviceStateReason *out_reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; gboolean success; NMIP6Config *composite; gboolean has_direct_route; const struct in6_addr *gateway; /* If no config was passed in, create a new one */ composite = nm_ip6_config_new (nm_device_get_ip_ifindex (self)); ensure_con_ipx_config (self); g_assert (composite); /* Merge all the IP configs into the composite config */ if (priv->ac_ip6_config) nm_ip6_config_merge (composite, priv->ac_ip6_config); if (priv->dhcp6_ip6_config) nm_ip6_config_merge (composite, priv->dhcp6_ip6_config); if (priv->vpn6_config) nm_ip6_config_merge (composite, priv->vpn6_config); if (priv->ext_ip6_config) nm_ip6_config_merge (composite, priv->ext_ip6_config); /* Merge WWAN config *last* to ensure modem-given settings overwrite * any external stuff set by pppd or other scripts. */ if (priv->wwan_ip6_config) nm_ip6_config_merge (composite, priv->wwan_ip6_config); /* Merge user overrides into the composite config. For assumed connections, * con_ip6_config is empty. */ if (priv->con_ip6_config) nm_ip6_config_merge (composite, priv->con_ip6_config); connection = nm_device_get_connection (self); /* Add the default route. * * We keep track of the default route of a device in a private field. * NMDevice needs to know the default route at this point, because the gateway * might require a direct route (see below). * * But also, we don't want to add the default route to priv->ip6_config, * because the default route from the setting might not be the same that * NMDefaultRouteManager eventually configures (because the it might * tweak the effective metric). */ /* unless we come to a different conclusion below, we have no default route and * the route is assumed. */ priv->default_route.v6_has = FALSE; priv->default_route.v6_is_assumed = TRUE; if (!commit) { /* during a non-commit event, we always pickup whatever is configured. */ goto END_ADD_DEFAULT_ROUTE; } if (nm_device_uses_assumed_connection (self)) goto END_ADD_DEFAULT_ROUTE; /* we are about to commit (for a non-assumed connection). Enforce whatever we have * configured. */ priv->default_route.v6_is_assumed = FALSE; if ( !connection || !nm_default_route_manager_ip6_connection_has_default_route (nm_default_route_manager_get (), connection)) goto END_ADD_DEFAULT_ROUTE; if (!nm_ip6_config_get_num_addresses (composite)) { /* without addresses we can have no default route. */ goto END_ADD_DEFAULT_ROUTE; } gateway = nm_ip6_config_get_gateway (composite); if (!gateway) goto END_ADD_DEFAULT_ROUTE; has_direct_route = nm_ip6_config_get_direct_route_for_host (composite, gateway) != NULL; priv->default_route.v6_has = TRUE; memset (&priv->default_route.v6, 0, sizeof (priv->default_route.v6)); priv->default_route.v6.source = NM_IP_CONFIG_SOURCE_USER; priv->default_route.v6.gateway = *gateway; priv->default_route.v6.metric = nm_device_get_ip6_route_metric (self); priv->default_route.v6.mss = nm_ip6_config_get_mss (composite); if (!has_direct_route) { NMPlatformIP6Route r = priv->default_route.v6; /* add a direct route to the gateway */ r.network = *gateway; r.plen = 128; r.gateway = in6addr_any; nm_ip6_config_add_route (composite, &r); } END_ADD_DEFAULT_ROUTE: if (priv->default_route.v6_is_assumed) { /* If above does not explicitly assign a default route, we always pick up the * default route based on what is currently configured. * That means that even managed connections with never-default, can * get a default route (if configured externally). */ priv->default_route.v6_has = _device_get_default_route_from_platform (self, AF_INET6, (NMPlatformIPRoute *) &priv->default_route.v6); } nm_ip6_config_addresses_sort (composite, priv->rdisc ? priv->rdisc_use_tempaddr : NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN); /* Allow setting MTU etc */ if (commit) { if (NM_DEVICE_GET_CLASS (self)->ip6_config_pre_commit) NM_DEVICE_GET_CLASS (self)->ip6_config_pre_commit (self, composite); } success = nm_device_set_ip6_config (self, composite, commit, out_reason); g_object_unref (composite); return success; } static void dhcp6_lease_change (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE; if (priv->dhcp6_ip6_config == NULL) { _LOGW (LOGD_DHCP6, "failed to get DHCPv6 config for rebind"); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED); return; } g_assert (priv->dhcp6_client); /* sanity check */ connection = nm_device_get_connection (self); g_assert (connection); /* Apply the updated config */ if (ip6_config_merge_and_apply (self, TRUE, &reason) == FALSE) { _LOGW (LOGD_DHCP6, "failed to update IPv6 config in response to DHCP event."); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason); } else { /* Notify dispatcher scripts of new DHCPv6 config */ nm_dispatcher_call (DISPATCHER_ACTION_DHCP6_CHANGE, connection, self, NULL, NULL, NULL); } } static void dhcp6_fail (NMDevice *self, gboolean timeout) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); dhcp6_cleanup (self, TRUE, FALSE); if (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_MANAGED) { if (timeout || (priv->ip6_state == IP_CONF)) nm_device_activate_schedule_ip6_config_timeout (self); else if (priv->ip6_state == IP_DONE) nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED); else g_warn_if_reached (); } else { /* not a hard failure; just live with the RA info */ if (priv->ip6_state == IP_CONF) nm_device_activate_schedule_ip6_config_result (self); } } static void dhcp6_timeout (NMDevice *self, NMDhcpClient *client) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_MANAGED) dhcp6_fail (self, TRUE); else { /* not a hard failure; just live with the RA info */ dhcp6_cleanup (self, TRUE, FALSE); if (priv->ip6_state == IP_CONF) nm_device_activate_schedule_ip6_config_result (self); } } static void dhcp6_update_config (NMDevice *self, NMDhcp6Config *config, GHashTable *options) { GHashTableIter iter; const char *key, *value; /* Update the DHCP6 config object with new DHCP options */ nm_dhcp6_config_reset (config); g_hash_table_iter_init (&iter, options); while (g_hash_table_iter_next (&iter, (gpointer) &key, (gpointer) &value)) nm_dhcp6_config_add_option (config, key, value); g_object_notify (G_OBJECT (self), NM_DEVICE_DHCP6_CONFIG); } static void dhcp6_state_changed (NMDhcpClient *client, NMDhcpState state, NMIP6Config *ip6_config, GHashTable *options, gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); g_return_if_fail (nm_dhcp_client_get_ipv6 (client) == TRUE); g_return_if_fail (!ip6_config || NM_IS_IP6_CONFIG (ip6_config)); _LOGD (LOGD_DHCP6, "new DHCPv6 client state %d", state); switch (state) { case NM_DHCP_STATE_BOUND: g_clear_object (&priv->dhcp6_ip6_config); if (ip6_config) { priv->dhcp6_ip6_config = g_object_ref (ip6_config); dhcp6_update_config (self, priv->dhcp6_config, options); } if (priv->ip6_state == IP_CONF) { if (priv->dhcp6_ip6_config == NULL) { /* FIXME: Initial DHCP failed; should we fail IPv6 entirely then? */ nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_DHCP_FAILED); break; } nm_device_activate_schedule_ip6_config_result (self); } else if (priv->ip6_state == IP_DONE) dhcp6_lease_change (self); break; case NM_DHCP_STATE_TIMEOUT: dhcp6_timeout (self, client); break; case NM_DHCP_STATE_EXPIRE: /* Ignore expiry before we even have a lease (NAK, old lease, etc) */ if (priv->ip6_state != IP_CONF) dhcp6_fail (self, FALSE); break; case NM_DHCP_STATE_DONE: /* In IPv6 info-only mode, the client doesn't handle leases so it * may exit right after getting a response from the server. That's * normal. In that case we just ignore the exit. */ if (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_OTHERCONF) break; /* Otherwise, fall through */ case NM_DHCP_STATE_FAIL: dhcp6_fail (self, FALSE); break; default: break; } } static gboolean dhcp6_start_with_link_ready (NMDevice *self, NMConnection *connection) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMSettingIPConfig *s_ip6; GByteArray *tmp = NULL; const guint8 *hw_addr; size_t hw_addr_len = 0; g_assert (connection); s_ip6 = nm_connection_get_setting_ip6_config (connection); g_assert (s_ip6); hw_addr = nm_platform_link_get_address (nm_device_get_ip_ifindex (self), &hw_addr_len); if (hw_addr_len) { tmp = g_byte_array_sized_new (hw_addr_len); g_byte_array_append (tmp, hw_addr, hw_addr_len); } priv->dhcp6_client = nm_dhcp_manager_start_ip6 (nm_dhcp_manager_get (), nm_device_get_ip_iface (self), nm_device_get_ip_ifindex (self), tmp, nm_connection_get_uuid (connection), nm_device_get_ip6_route_metric (self), nm_setting_ip_config_get_dhcp_send_hostname (s_ip6), nm_setting_ip_config_get_dhcp_hostname (s_ip6), priv->dhcp_timeout, priv->dhcp_anycast_address, (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_OTHERCONF) ? TRUE : FALSE, nm_setting_ip6_config_get_ip6_privacy (NM_SETTING_IP6_CONFIG (s_ip6))); if (tmp) g_byte_array_free (tmp, TRUE); if (priv->dhcp6_client) { priv->dhcp6_state_sigid = g_signal_connect (priv->dhcp6_client, NM_DHCP_CLIENT_SIGNAL_STATE_CHANGED, G_CALLBACK (dhcp6_state_changed), self); } return !!priv->dhcp6_client; } static gboolean dhcp6_start (NMDevice *self, gboolean wait_for_ll, NMDeviceStateReason *reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; NMSettingIPConfig *s_ip6; g_clear_object (&priv->dhcp6_config); priv->dhcp6_config = nm_dhcp6_config_new (); g_warn_if_fail (priv->dhcp6_ip6_config == NULL); g_clear_object (&priv->dhcp6_ip6_config); connection = nm_device_get_connection (self); g_assert (connection); s_ip6 = nm_connection_get_setting_ip6_config (connection); if (!nm_setting_ip_config_get_may_fail (s_ip6) || !strcmp (nm_setting_ip_config_get_method (s_ip6), NM_SETTING_IP6_CONFIG_METHOD_DHCP)) nm_device_add_pending_action (self, PENDING_ACTION_DHCP6, TRUE); if (wait_for_ll) { NMActStageReturn ret; /* ensure link local is ready... */ ret = linklocal6_start (self); if (ret == NM_ACT_STAGE_RETURN_POSTPONE) { /* success; wait for the LL address to show up */ return TRUE; } /* success; already have the LL address; kick off DHCP */ g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS); } if (!dhcp6_start_with_link_ready (self, connection)) { *reason = NM_DEVICE_STATE_REASON_DHCP_START_FAILED; return FALSE; } return TRUE; } gboolean nm_device_dhcp6_renew (NMDevice *self, gboolean release) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); g_return_val_if_fail (priv->dhcp6_client != NULL, FALSE); _LOGI (LOGD_DHCP6, "DHCPv6 lease renewal requested"); /* Terminate old DHCP instance and release the old lease */ dhcp6_cleanup (self, TRUE, release); /* Start DHCP again on the interface */ return dhcp6_start (self, FALSE, NULL); } /******************************************/ static gboolean have_ip6_address (const NMIP6Config *ip6_config, gboolean linklocal) { guint i; if (!ip6_config) return FALSE; linklocal = !!linklocal; for (i = 0; i < nm_ip6_config_get_num_addresses (ip6_config); i++) { const NMPlatformIP6Address *addr = nm_ip6_config_get_address (ip6_config, i); if ((IN6_IS_ADDR_LINKLOCAL (&addr->address) == linklocal) && !(addr->flags & IFA_F_TENTATIVE)) return TRUE; } return FALSE; } static void linklocal6_cleanup (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->linklocal6_timeout_id) { g_source_remove (priv->linklocal6_timeout_id); priv->linklocal6_timeout_id = 0; } } static gboolean linklocal6_timeout_cb (gpointer user_data) { NMDevice *self = user_data; linklocal6_cleanup (self); _LOGD (LOGD_DEVICE, "linklocal6: waiting for link-local addresses failed due to timeout"); nm_device_activate_schedule_ip6_config_timeout (self); return G_SOURCE_REMOVE; } static void linklocal6_complete (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; const char *method; g_assert (priv->linklocal6_timeout_id); g_assert (have_ip6_address (priv->ip6_config, TRUE)); linklocal6_cleanup (self); connection = nm_device_get_connection (self); g_assert (connection); method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG); _LOGD (LOGD_DEVICE, "linklocal6: waiting for link-local addresses successful, continue with method %s", method); if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_AUTO) == 0) { if (!addrconf6_start_with_link_ready (self)) { /* Time out IPv6 instead of failing the entire activation */ nm_device_activate_schedule_ip6_config_timeout (self); } } else if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_DHCP) == 0) { if (!dhcp6_start_with_link_ready (self, connection)) { /* Time out IPv6 instead of failing the entire activation */ nm_device_activate_schedule_ip6_config_timeout (self); } } else if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL) == 0) nm_device_activate_schedule_ip6_config_result (self); else g_return_if_fail (FALSE); } static void check_and_add_ipv6ll_addr (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); int ip_ifindex = nm_device_get_ip_ifindex (self); NMUtilsIPv6IfaceId iid; struct in6_addr lladdr; guint i, n; if (priv->nm_ipv6ll == FALSE) return; if (priv->ip6_config) { n = nm_ip6_config_get_num_addresses (priv->ip6_config); for (i = 0; i < n; i++) { const NMPlatformIP6Address *addr; addr = nm_ip6_config_get_address (priv->ip6_config, i); if (IN6_IS_ADDR_LINKLOCAL (&addr->address)) { /* Already have an LL address, nothing to do */ return; } } } if (!nm_device_get_ip_iface_identifier (self, &iid)) { _LOGW (LOGD_IP6, "failed to get interface identifier; IPv6 may be broken"); return; } memset (&lladdr, 0, sizeof (lladdr)); lladdr.s6_addr16[0] = htons (0xfe80); nm_utils_ipv6_addr_set_interface_identfier (&lladdr, iid); _LOGD (LOGD_IP6, "adding IPv6LL address %s", nm_utils_inet6_ntop (&lladdr, NULL)); if (!nm_platform_ip6_address_add (ip_ifindex, lladdr, in6addr_any, 64, NM_PLATFORM_LIFETIME_PERMANENT, NM_PLATFORM_LIFETIME_PERMANENT, 0)) { _LOGW (LOGD_IP6, "failed to add IPv6 link-local address %s", nm_utils_inet6_ntop (&lladdr, NULL)); } } static NMActStageReturn linklocal6_start (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; const char *method; linklocal6_cleanup (self); if (have_ip6_address (priv->ip6_config, TRUE)) return NM_ACT_STAGE_RETURN_SUCCESS; connection = nm_device_get_connection (self); g_assert (connection); method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG); _LOGD (LOGD_DEVICE, "linklocal6: starting IPv6 with method '%s', but the device has no link-local addresses configured. Wait.", method); check_and_add_ipv6ll_addr (self); priv->linklocal6_timeout_id = g_timeout_add_seconds (5, linklocal6_timeout_cb, self); return NM_ACT_STAGE_RETURN_POSTPONE; } /******************************************/ static void print_support_extended_ifa_flags (NMSettingIP6ConfigPrivacy use_tempaddr) { static gint8 warn = 0; static gint8 s_libnl = -1, s_kernel; if (warn >= 2) return; if (s_libnl == -1) { s_libnl = !!nm_platform_check_support_libnl_extended_ifa_flags (); s_kernel = !!nm_platform_check_support_kernel_extended_ifa_flags (); if (s_libnl && s_kernel) { nm_log_dbg (LOGD_IP6, "kernel and libnl support extended IFA_FLAGS (needed by NM for IPv6 private addresses)"); warn = 2; return; } } if ( use_tempaddr != NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_TEMP_ADDR && use_tempaddr != NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_PUBLIC_ADDR) { if (warn == 0) { nm_log_dbg (LOGD_IP6, "%s%s%s %s not support extended IFA_FLAGS (needed by NM for IPv6 private addresses)", !s_kernel ? "kernel" : "", !s_kernel && !s_libnl ? " and " : "", !s_libnl ? "libnl" : "", !s_kernel && !s_libnl ? "do" : "does"); warn = 1; } return; } if (!s_libnl && !s_kernel) { nm_log_warn (LOGD_IP6, "libnl and the kernel do not support extended IFA_FLAGS needed by NM for " "IPv6 private addresses. This feature is not available"); } else if (!s_libnl) { nm_log_warn (LOGD_IP6, "libnl does not support extended IFA_FLAGS needed by NM for " "IPv6 private addresses. This feature is not available"); } else if (!s_kernel) { nm_log_warn (LOGD_IP6, "The kernel does not support extended IFA_FLAGS needed by NM for " "IPv6 private addresses. This feature is not available"); } warn = 2; } static void rdisc_config_changed (NMRDisc *rdisc, NMRDiscConfigMap changed, NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); warn = 2; } static void rdisc_config_changed (NMRDisc *rdisc, NMRDiscConfigMap changed, NMDevice *self) { address.preferred = discovered_address->preferred; if (address.preferred > address.lifetime) address.preferred = address.lifetime; address.source = NM_IP_CONFIG_SOURCE_RDISC; address.flags = ifa_flags; nm_ip6_config_add_address (priv->ac_ip6_config, &address); } } Vulnerability Type: DoS CWE ID: CWE-20 Summary: GNOME NetworkManager allows remote attackers to cause a denial of service (IPv6 traffic disruption) via a crafted MTU value in an IPv6 Router Advertisement (RA) message, a different vulnerability than CVE-2015-8215. Commit Message:
Medium
26,722
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: ResolveStateAndPredicate(ExprDef *expr, enum xkb_match_operation *pred_rtrn, xkb_mod_mask_t *mods_rtrn, CompatInfo *info) { if (expr == NULL) { *pred_rtrn = MATCH_ANY_OR_NONE; *mods_rtrn = MOD_REAL_MASK_ALL; return true; } *pred_rtrn = MATCH_EXACTLY; if (expr->expr.op == EXPR_ACTION_DECL) { const char *pred_txt = xkb_atom_text(info->ctx, expr->action.name); if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn)) { log_err(info->ctx, "Illegal modifier predicate \"%s\"; Ignored\n", pred_txt); return false; } expr = expr->action.args; } else if (expr->expr.op == EXPR_IDENT) { const char *pred_txt = xkb_atom_text(info->ctx, expr->ident.ident); if (pred_txt && istreq(pred_txt, "any")) { *pred_rtrn = MATCH_ANY; *mods_rtrn = MOD_REAL_MASK_ALL; return true; } } return ExprResolveModMask(info->ctx, expr, MOD_REAL, &info->mods, mods_rtrn); } Vulnerability Type: CWE ID: CWE-476 Summary: Unchecked NULL pointer usage in ResolveStateAndPredicate in xkbcomp/compat.c in xkbcommon before 0.8.2 could be used by local attackers to crash (NULL pointer dereference) the xkbcommon parser by supplying a crafted keymap file with a no-op modmask expression. Commit Message: xkbcomp: Don't crash on no-op modmask expressions If we have an expression of the form 'l1' in an interp section, we unconditionally try to dereference its args, even if it has none. Signed-off-by: Daniel Stone <[email protected]>
Low
7,277
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: my_object_class_init (MyObjectClass *mobject_class) { GObjectClass *gobject_class = G_OBJECT_CLASS (mobject_class); gobject_class->finalize = my_object_finalize; gobject_class->set_property = my_object_set_property; gobject_class->get_property = my_object_get_property; g_object_class_install_property (gobject_class, PROP_THIS_IS_A_STRING, g_param_spec_string ("this_is_a_string", _("Sample string"), _("Example of a string property"), "default value", G_PARAM_READWRITE)); signals[FROBNICATE] = g_signal_new ("frobnicate", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); signals[SIG0] = g_signal_new ("sig0", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, my_object_marshal_VOID__STRING_INT_STRING, G_TYPE_NONE, 3, G_TYPE_STRING, G_TYPE_INT, G_TYPE_STRING); signals[SIG1] = g_signal_new ("sig1", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, my_object_marshal_VOID__STRING_BOXED, G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_VALUE); signals[SIG2] = g_signal_new ("sig2", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, g_cclosure_marshal_VOID__BOXED, G_TYPE_NONE, 1, DBUS_TYPE_G_STRING_STRING_HASHTABLE); } Vulnerability Type: DoS Bypass CWE ID: CWE-264 Summary: DBus-GLib 0.73 disregards the access flag of exported GObject properties, which allows local users to bypass intended access restrictions and possibly cause a denial of service by modifying properties, as demonstrated by properties of the (1) DeviceKit-Power, (2) NetworkManager, and (3) ModemManager services. Commit Message:
Low
24,450
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int sctp_init_sock(struct sock *sk) { struct net *net = sock_net(sk); struct sctp_sock *sp; pr_debug("%s: sk:%p\n", __func__, sk); sp = sctp_sk(sk); /* Initialize the SCTP per socket area. */ switch (sk->sk_type) { case SOCK_SEQPACKET: sp->type = SCTP_SOCKET_UDP; break; case SOCK_STREAM: sp->type = SCTP_SOCKET_TCP; break; default: return -ESOCKTNOSUPPORT; } /* Initialize default send parameters. These parameters can be * modified with the SCTP_DEFAULT_SEND_PARAM socket option. */ sp->default_stream = 0; sp->default_ppid = 0; sp->default_flags = 0; sp->default_context = 0; sp->default_timetolive = 0; sp->default_rcv_context = 0; sp->max_burst = net->sctp.max_burst; sp->sctp_hmac_alg = net->sctp.sctp_hmac_alg; /* Initialize default setup parameters. These parameters * can be modified with the SCTP_INITMSG socket option or * overridden by the SCTP_INIT CMSG. */ sp->initmsg.sinit_num_ostreams = sctp_max_outstreams; sp->initmsg.sinit_max_instreams = sctp_max_instreams; sp->initmsg.sinit_max_attempts = net->sctp.max_retrans_init; sp->initmsg.sinit_max_init_timeo = net->sctp.rto_max; /* Initialize default RTO related parameters. These parameters can * be modified for with the SCTP_RTOINFO socket option. */ sp->rtoinfo.srto_initial = net->sctp.rto_initial; sp->rtoinfo.srto_max = net->sctp.rto_max; sp->rtoinfo.srto_min = net->sctp.rto_min; /* Initialize default association related parameters. These parameters * can be modified with the SCTP_ASSOCINFO socket option. */ sp->assocparams.sasoc_asocmaxrxt = net->sctp.max_retrans_association; sp->assocparams.sasoc_number_peer_destinations = 0; sp->assocparams.sasoc_peer_rwnd = 0; sp->assocparams.sasoc_local_rwnd = 0; sp->assocparams.sasoc_cookie_life = net->sctp.valid_cookie_life; /* Initialize default event subscriptions. By default, all the * options are off. */ memset(&sp->subscribe, 0, sizeof(struct sctp_event_subscribe)); /* Default Peer Address Parameters. These defaults can * be modified via SCTP_PEER_ADDR_PARAMS */ sp->hbinterval = net->sctp.hb_interval; sp->pathmaxrxt = net->sctp.max_retrans_path; sp->pathmtu = 0; /* allow default discovery */ sp->sackdelay = net->sctp.sack_timeout; sp->sackfreq = 2; sp->param_flags = SPP_HB_ENABLE | SPP_PMTUD_ENABLE | SPP_SACKDELAY_ENABLE; /* If enabled no SCTP message fragmentation will be performed. * Configure through SCTP_DISABLE_FRAGMENTS socket option. */ sp->disable_fragments = 0; /* Enable Nagle algorithm by default. */ sp->nodelay = 0; sp->recvrcvinfo = 0; sp->recvnxtinfo = 0; /* Enable by default. */ sp->v4mapped = 1; /* Auto-close idle associations after the configured * number of seconds. A value of 0 disables this * feature. Configure through the SCTP_AUTOCLOSE socket option, * for UDP-style sockets only. */ sp->autoclose = 0; /* User specified fragmentation limit. */ sp->user_frag = 0; sp->adaptation_ind = 0; sp->pf = sctp_get_pf_specific(sk->sk_family); /* Control variables for partial data delivery. */ atomic_set(&sp->pd_mode, 0); skb_queue_head_init(&sp->pd_lobby); sp->frag_interleave = 0; /* Create a per socket endpoint structure. Even if we * change the data structure relationships, this may still * be useful for storing pre-connect address information. */ sp->ep = sctp_endpoint_new(sk, GFP_KERNEL); if (!sp->ep) return -ENOMEM; sp->hmac = NULL; sk->sk_destruct = sctp_destruct_sock; SCTP_DBG_OBJCNT_INC(sock); local_bh_disable(); percpu_counter_inc(&sctp_sockets_allocated); sock_prot_inuse_add(net, sk->sk_prot, 1); if (net->sctp.default_auto_asconf) { list_add_tail(&sp->auto_asconf_list, &net->sctp.auto_asconf_splist); sp->do_auto_asconf = 1; } else sp->do_auto_asconf = 0; local_bh_enable(); return 0; } Vulnerability Type: DoS CWE ID: CWE-362 Summary: Race condition in net/sctp/socket.c in the Linux kernel before 4.1.2 allows local users to cause a denial of service (list corruption and panic) via a rapid series of system calls related to sockets, as demonstrated by setsockopt calls. Commit Message: sctp: fix ASCONF list handling ->auto_asconf_splist is per namespace and mangled by functions like sctp_setsockopt_auto_asconf() which doesn't guarantee any serialization. Also, the call to inet_sk_copy_descendant() was backuping ->auto_asconf_list through the copy but was not honoring ->do_auto_asconf, which could lead to list corruption if it was different between both sockets. This commit thus fixes the list handling by using ->addr_wq_lock spinlock to protect the list. A special handling is done upon socket creation and destruction for that. Error handlig on sctp_init_sock() will never return an error after having initialized asconf, so sctp_destroy_sock() can be called without addrq_wq_lock. The lock now will be take on sctp_close_sock(), before locking the socket, so we don't do it in inverse order compared to sctp_addr_wq_timeout_handler(). Instead of taking the lock on sctp_sock_migrate() for copying and restoring the list values, it's preferred to avoid rewritting it by implementing sctp_copy_descendant(). Issue was found with a test application that kept flipping sysctl default_auto_asconf on and off, but one could trigger it by issuing simultaneous setsockopt() calls on multiple sockets or by creating/destroying sockets fast enough. This is only triggerable locally. Fixes: 9f7d653b67ae ("sctp: Add Auto-ASCONF support (core).") Reported-by: Ji Jianwen <[email protected]> Suggested-by: Neil Horman <[email protected]> Suggested-by: Hannes Frederic Sowa <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: Marcelo Ricardo Leitner <[email protected]> Signed-off-by: David S. Miller <[email protected]>
Medium
24,099
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *buf, unsigned char *limit) { int extdatalen=0; unsigned char *orig = buf; unsigned char *ret = buf; /* don't add extensions for SSLv3 unless doing secure renegotiation */ if (s->client_version == SSL3_VERSION && !s->s3->send_connection_binding) return orig; ret+=2; if (ret>=limit) return NULL; /* this really never occurs, but ... */ if (s->tlsext_hostname != NULL) { /* Add TLS extension servername to the Client Hello message */ unsigned long size_str; long lenmax; /* check for enough space. 4 for the servername type and entension length 2 for servernamelist length 1 for the hostname type 2 for hostname length + hostname length */ if ((lenmax = limit - ret - 9) < 0 || (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax) return NULL; /* extension type and length */ s2n(TLSEXT_TYPE_server_name,ret); s2n(size_str+5,ret); /* length of servername list */ s2n(size_str+3,ret); /* hostname type, length and hostname */ *(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name; s2n(size_str,ret); memcpy(ret, s->tlsext_hostname, size_str); ret+=size_str; } /* Add RI if renegotiating */ if (s->renegotiate) { int el; if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0)) { SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } if((limit - ret - 4 - el) < 0) return NULL; s2n(TLSEXT_TYPE_renegotiate,ret); s2n(el,ret); if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el)) { SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } ret += el; } #ifndef OPENSSL_NO_SRP /* Add SRP username if there is one */ if (s->srp_ctx.login != NULL) { /* Add TLS extension SRP username to the Client Hello message */ int login_len = strlen(s->srp_ctx.login); if (login_len > 255 || login_len == 0) { SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } /* check for enough space. 4 for the srp type type and entension length 1 for the srp user identity + srp user identity length */ if ((limit - ret - 5 - login_len) < 0) return NULL; /* fill in the extension */ s2n(TLSEXT_TYPE_srp,ret); s2n(login_len+1,ret); (*ret++) = (unsigned char) login_len; memcpy(ret, s->srp_ctx.login, login_len); ret+=login_len; } #endif #ifndef OPENSSL_NO_EC if (s->tlsext_ecpointformatlist != NULL) { /* Add TLS extension ECPointFormats to the ClientHello message */ long lenmax; if ((lenmax = limit - ret - 5) < 0) return NULL; if (s->tlsext_ecpointformatlist_length > (unsigned long)lenmax) return NULL; if (s->tlsext_ecpointformatlist_length > 255) { SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } s2n(TLSEXT_TYPE_ec_point_formats,ret); s2n(s->tlsext_ecpointformatlist_length + 1,ret); *(ret++) = (unsigned char) s->tlsext_ecpointformatlist_length; memcpy(ret, s->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist_length); ret+=s->tlsext_ecpointformatlist_length; } if (s->tlsext_ellipticcurvelist != NULL) { /* Add TLS extension EllipticCurves to the ClientHello message */ long lenmax; if ((lenmax = limit - ret - 6) < 0) return NULL; if (s->tlsext_ellipticcurvelist_length > (unsigned long)lenmax) return NULL; if (s->tlsext_ellipticcurvelist_length > 65532) { SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } s2n(TLSEXT_TYPE_elliptic_curves,ret); s2n(s->tlsext_ellipticcurvelist_length + 2, ret); /* NB: draft-ietf-tls-ecc-12.txt uses a one-byte prefix for * elliptic_curve_list, but the examples use two bytes. * http://www1.ietf.org/mail-archive/web/tls/current/msg00538.html * resolves this to two bytes. */ s2n(s->tlsext_ellipticcurvelist_length, ret); memcpy(ret, s->tlsext_ellipticcurvelist, s->tlsext_ellipticcurvelist_length); ret+=s->tlsext_ellipticcurvelist_length; } #endif /* OPENSSL_NO_EC */ if (!(SSL_get_options(s) & SSL_OP_NO_TICKET)) { int ticklen; if (!s->new_session && s->session && s->session->tlsext_tick) ticklen = s->session->tlsext_ticklen; else if (s->session && s->tlsext_session_ticket && s->tlsext_session_ticket->data) { ticklen = s->tlsext_session_ticket->length; s->session->tlsext_tick = OPENSSL_malloc(ticklen); if (!s->session->tlsext_tick) return NULL; memcpy(s->session->tlsext_tick, s->tlsext_session_ticket->data, ticklen); s->session->tlsext_ticklen = ticklen; } else ticklen = 0; if (ticklen == 0 && s->tlsext_session_ticket && s->tlsext_session_ticket->data == NULL) goto skip_ext; /* Check for enough room 2 for extension type, 2 for len * rest for ticket */ if ((long)(limit - ret - 4 - ticklen) < 0) return NULL; s2n(TLSEXT_TYPE_session_ticket,ret); s2n(ticklen,ret); if (ticklen) { memcpy(ret, s->session->tlsext_tick, ticklen); ret += ticklen; } } skip_ext: if (TLS1_get_client_version(s) >= TLS1_2_VERSION) { if ((size_t)(limit - ret) < sizeof(tls12_sigalgs) + 6) return NULL; s2n(TLSEXT_TYPE_signature_algorithms,ret); s2n(sizeof(tls12_sigalgs) + 2, ret); s2n(sizeof(tls12_sigalgs), ret); memcpy(ret, tls12_sigalgs, sizeof(tls12_sigalgs)); ret += sizeof(tls12_sigalgs); } #ifdef TLSEXT_TYPE_opaque_prf_input if (s->s3->client_opaque_prf_input != NULL && s->version != DTLS1_VERSION) { size_t col = s->s3->client_opaque_prf_input_len; if ((long)(limit - ret - 6 - col < 0)) return NULL; if (col > 0xFFFD) /* can't happen */ return NULL; s2n(TLSEXT_TYPE_opaque_prf_input, ret); s2n(col + 2, ret); s2n(col, ret); memcpy(ret, s->s3->client_opaque_prf_input, col); ret += col; } #endif if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp && s->version != DTLS1_VERSION) { int i; long extlen, idlen, itmp; OCSP_RESPID *id; idlen = 0; for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) { id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i); itmp = i2d_OCSP_RESPID(id, NULL); if (itmp <= 0) return NULL; idlen += itmp + 2; } if (s->tlsext_ocsp_exts) { extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL); if (extlen < 0) return NULL; } else extlen = 0; if ((long)(limit - ret - 7 - extlen - idlen) < 0) return NULL; s2n(TLSEXT_TYPE_status_request, ret); if (extlen + idlen > 0xFFF0) return NULL; s2n(extlen + idlen + 5, ret); *(ret++) = TLSEXT_STATUSTYPE_ocsp; s2n(idlen, ret); for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) { /* save position of id len */ unsigned char *q = ret; id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i); /* skip over id len */ ret += 2; itmp = i2d_OCSP_RESPID(id, &ret); /* write id len */ s2n(itmp, q); } s2n(extlen, ret); if (extlen > 0) i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret); } #ifndef OPENSSL_NO_HEARTBEATS /* Add Heartbeat extension */ if ((limit - ret - 4 - 1) < 0) return NULL; s2n(TLSEXT_TYPE_heartbeat,ret); s2n(1,ret); /* Set mode: * 1: peer may send requests * 2: peer not allowed to send requests */ if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS) *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS; else *(ret++) = SSL_TLSEXT_HB_ENABLED; #endif #ifndef OPENSSL_NO_NEXTPROTONEG if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len) { /* The client advertises an emtpy extension to indicate its * support for Next Protocol Negotiation */ if (limit - ret - 4 < 0) return NULL; s2n(TLSEXT_TYPE_next_proto_neg,ret); s2n(0,ret); } #endif #ifndef OPENSSL_NO_SRTP if(SSL_get_srtp_profiles(s)) { int el; ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0); if((limit - ret - 4 - el) < 0) return NULL; s2n(TLSEXT_TYPE_use_srtp,ret); s2n(el,ret); if(ssl_add_clienthello_use_srtp_ext(s, ret, &el, el)) { SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } ret += el; } #endif /* Add padding to workaround bugs in F5 terminators. * See https://tools.ietf.org/html/draft-agl-tls-padding-03 * * NB: because this code works out the length of all existing * extensions it MUST always appear last. */ if (s->options & SSL_OP_TLSEXT_PADDING) { int hlen = ret - (unsigned char *)s->init_buf->data; /* The code in s23_clnt.c to build ClientHello messages * includes the 5-byte record header in the buffer, while * the code in s3_clnt.c does not. */ if (s->state == SSL23_ST_CW_CLNT_HELLO_A) hlen -= 5; if (hlen > 0xff && hlen < 0x200) { hlen = 0x200 - hlen; if (hlen >= 4) hlen -= 4; else hlen = 0; s2n(TLSEXT_TYPE_padding, ret); s2n(hlen, ret); memset(ret, 0, hlen); ret += hlen; } } if ((extdatalen = ret-orig-2)== 0) return orig; s2n(extdatalen, orig); return ret; } Vulnerability Type: DoS CWE ID: CWE-20 Summary: Memory leak in d1_srtp.c in the DTLS SRTP extension in OpenSSL 1.0.1 before 1.0.1j allows remote attackers to cause a denial of service (memory consumption) via a crafted handshake message. Commit Message:
High
17,258
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void BaseRenderingContext2D::Reset() { ValidateStateStack(); UnwindStateStack(); state_stack_.resize(1); state_stack_.front() = CanvasRenderingContext2DState::Create(); path_.Clear(); if (PaintCanvas* c = ExistingDrawingCanvas()) { DCHECK_EQ(c->getSaveCount(), 2); c->restore(); c->save(); DCHECK(c->getTotalMatrix().isIdentity()); #if DCHECK_IS_ON() SkIRect clip_bounds; DCHECK(c->getDeviceClipBounds(&clip_bounds)); DCHECK(clip_bounds == c->imageInfo().bounds()); #endif } ValidateStateStack(); } Vulnerability Type: +Info CWE ID: CWE-200 Summary: Displacement map filters being applied to cross-origin images in Blink SVG rendering in Google Chrome prior to 65.0.3325.146 allowed a remote attacker to leak cross-origin data via a crafted HTML page. Commit Message: [PE] Distinguish between tainting due to canvas content and filter. A filter on a canvas can itself lead to origin tainting, for reasons other than that the canvas contents are tainted. This CL changes to distinguish these two causes, so that we recompute filters on content-tainting change. Bug: 778506 Change-Id: I3cec8ef3b2772f2af78cdd4b290520113092cca6 Reviewed-on: https://chromium-review.googlesource.com/811767 Reviewed-by: Fredrik Söderquist <[email protected]> Commit-Queue: Chris Harrelson <[email protected]> Cr-Commit-Position: refs/heads/master@{#522274}
Medium
12,602
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return((image->columns+7)/8); else return(image->columns*GetPSDPacketSize(image)); } Vulnerability Type: DoS Overflow CWE ID: CWE-125 Summary: Heap-based buffer overflow in coders/psd.c in ImageMagick allows remote attackers to cause a denial of service (out-of-bounds read) via a crafted PSD file. Commit Message: Fixed head buffer overflow reported in: https://github.com/ImageMagick/ImageMagick/issues/98
Medium
27,254
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: int main(int argc, char *argv[]) { char buff[1024]; int fd, nr, nw; if (argc < 2) { fprintf(stderr, "usage: %s output-filename\n" " %s |output-command\n" " %s :host:port\n", argv[0], argv[0], argv[0]); return 1; } fd = open_gen_fd(argv[1]); if (fd < 0) { perror("open_gen_fd"); exit(EXIT_FAILURE); } while ((nr = read(0, buff, sizeof (buff))) != 0) { if (nr < 0) { if (errno == EINTR) continue; perror("read"); exit(EXIT_FAILURE); } nw = write(fd, buff, nr); if (nw < 0) { perror("write"); exit(EXIT_FAILURE); } } return 0; } Vulnerability Type: CWE ID: Summary: Boa through 0.94.14rc21 allows remote attackers to trigger a memory leak because of missing calls to the free function. Commit Message: misc oom and possible memory leak fix
Low
17,116
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static enum entity_charset determine_charset(char *charset_hint TSRMLS_DC) { int i; enum entity_charset charset = cs_utf_8; int len = 0; const zend_encoding *zenc; /* Default is now UTF-8 */ if (charset_hint == NULL) return cs_utf_8; if ((len = strlen(charset_hint)) != 0) { goto det_charset; } zenc = zend_multibyte_get_internal_encoding(TSRMLS_C); if (zenc != NULL) { charset_hint = (char *)zend_multibyte_get_encoding_name(zenc); if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) { if ((len == 4) /* sizeof (none|auto|pass) */ && (!memcmp("pass", charset_hint, 4) || !memcmp("auto", charset_hint, 4) || !memcmp("auto", charset_hint, 4))) { charset_hint = NULL; len = 0; } else { goto det_charset; } } } charset_hint = SG(default_charset); if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) { goto det_charset; } /* try to detect the charset for the locale */ #if HAVE_NL_LANGINFO && HAVE_LOCALE_H && defined(CODESET) charset_hint = nl_langinfo(CODESET); if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) { goto det_charset; } #endif #if HAVE_LOCALE_H /* try to figure out the charset from the locale */ { char *localename; char *dot, *at; /* lang[_territory][.codeset][@modifier] */ localename = setlocale(LC_CTYPE, NULL); dot = strchr(localename, '.'); if (dot) { dot++; /* locale specifies a codeset */ at = strchr(dot, '@'); if (at) len = at - dot; else len = strlen(dot); charset_hint = dot; } else { /* no explicit name; see if the name itself * is the charset */ charset_hint = localename; len = strlen(charset_hint); } } #endif det_charset: if (charset_hint) { int found = 0; /* now walk the charset map and look for the codeset */ for (i = 0; charset_map[i].codeset; i++) { if (len == strlen(charset_map[i].codeset) && strncasecmp(charset_hint, charset_map[i].codeset, len) == 0) { charset = charset_map[i].charset; found = 1; break; } } if (!found) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "charset `%s' not supported, assuming utf-8", charset_hint); } } return charset; } Vulnerability Type: DoS Overflow CWE ID: CWE-190 Summary: Integer overflow in the php_html_entities function in ext/standard/html.c in PHP before 5.5.36 and 5.6.x before 5.6.22 allows remote attackers to cause a denial of service or possibly have unspecified other impact by triggering a large output string from the htmlspecialchars function. Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
High
8,616
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri) { CMS_KeyTransRecipientInfo *ktri = ri->d.ktri; EVP_PKEY *pkey = ktri->pkey; unsigned char *ek = NULL; size_t eklen; int ret = 0; CMS_EncryptedContentInfo *ec; ec = cms->d.envelopedData->encryptedContentInfo; CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_NO_PRIVATE_KEY); return 0; return 0; } Vulnerability Type: CWE ID: CWE-311 Summary: In situations where an attacker receives automated notification of the success or failure of a decryption attempt an attacker, after sending a very large number of messages to be decrypted, can recover a CMS/PKCS7 transported encryption key or decrypt any RSA encrypted message that was encrypted with the public RSA key, using a Bleichenbacher padding oracle attack. Applications are not affected if they use a certificate together with the private RSA key to the CMS_decrypt or PKCS7_decrypt functions to select the correct recipient info to decrypt. Fixed in OpenSSL 1.1.1d (Affected 1.1.1-1.1.1c). Fixed in OpenSSL 1.1.0l (Affected 1.1.0-1.1.0k). Fixed in OpenSSL 1.0.2t (Affected 1.0.2-1.0.2s). Commit Message:
Medium
17,909
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int br_parse_ip_options(struct sk_buff *skb) { struct ip_options *opt; struct iphdr *iph; struct net_device *dev = skb->dev; u32 len; iph = ip_hdr(skb); opt = &(IPCB(skb)->opt); /* Basic sanity checks */ if (iph->ihl < 5 || iph->version != 4) goto inhdr_error; if (!pskb_may_pull(skb, iph->ihl*4)) goto inhdr_error; iph = ip_hdr(skb); if (unlikely(ip_fast_csum((u8 *)iph, iph->ihl))) goto inhdr_error; len = ntohs(iph->tot_len); if (skb->len < len) { IP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INTRUNCATEDPKTS); goto drop; } else if (len < (iph->ihl*4)) goto inhdr_error; if (pskb_trim_rcsum(skb, len)) { IP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INDISCARDS); goto drop; } /* Zero out the CB buffer if no options present */ if (iph->ihl == 5) { memset(IPCB(skb), 0, sizeof(struct inet_skb_parm)); return 0; } opt->optlen = iph->ihl*4 - sizeof(struct iphdr); if (ip_options_compile(dev_net(dev), opt, skb)) goto inhdr_error; /* Check correct handling of SRR option */ if (unlikely(opt->srr)) { struct in_device *in_dev = __in_dev_get_rcu(dev); if (in_dev && !IN_DEV_SOURCE_ROUTE(in_dev)) goto drop; if (ip_options_rcv_srr(skb)) goto drop; } return 0; inhdr_error: IP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INHDRERRORS); drop: return -1; } Vulnerability Type: DoS CWE ID: CWE-399 Summary: The br_parse_ip_options function in net/bridge/br_netfilter.c in the Linux kernel before 2.6.39 does not properly initialize a certain data structure, which allows remote attackers to cause a denial of service by leveraging connectivity to a network interface that uses an Ethernet bridge device. Commit Message: bridge: reset IPCB in br_parse_ip_options Commit 462fb2af9788a82 (bridge : Sanitize skb before it enters the IP stack), missed one IPCB init before calling ip_options_compile() Thanks to Scot Doyle for his tests and bug reports. Reported-by: Scot Doyle <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Cc: Hiroaki SHIMODA <[email protected]> Acked-by: Bandan Das <[email protected]> Acked-by: Stephen Hemminger <[email protected]> Cc: Jan Lübbe <[email protected]> Signed-off-by: David S. Miller <[email protected]>
Medium
17,232
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: int dev_forward_skb(struct net_device *dev, struct sk_buff *skb) { skb_orphan(skb); if (!(dev->flags & IFF_UP)) return NET_RX_DROP; if (skb->len > (dev->mtu + dev->hard_header_len)) return NET_RX_DROP; skb_set_dev(skb, dev); skb->tstamp.tv64 = 0; skb->pkt_type = PACKET_HOST; skb->protocol = eth_type_trans(skb, dev); return netif_rx(skb); } Vulnerability Type: DoS CWE ID: CWE-399 Summary: The veth (aka virtual Ethernet) driver in the Linux kernel before 2.6.34 does not properly manage skbs during congestion, which allows remote attackers to cause a denial of service (system crash) by leveraging lack of skb consumption in conjunction with a double-free error. Commit Message: veth: Dont kfree_skb() after dev_forward_skb() In case of congestion, netif_rx() frees the skb, so we must assume dev_forward_skb() also consume skb. Bug introduced by commit 445409602c092 (veth: move loopback logic to common location) We must change dev_forward_skb() to always consume skb, and veth to not double free it. Bug report : http://marc.info/?l=linux-netdev&m=127310770900442&w=3 Reported-by: Martín Ferrari <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]>
High
11,212
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: int fpm_stdio_init_child(struct fpm_worker_pool_s *wp) /* {{{ */ { #ifdef HAVE_SYSLOG_H if (fpm_globals.error_log_fd == ZLOG_SYSLOG) { closelog(); /* ensure to close syslog not to interrupt with PHP syslog code */ } else #endif /* Notice: child cannot use master error_log * because not aware when being reopen * else, should use if (!fpm_use_error_log()) */ if (fpm_globals.error_log_fd > 0) { close(fpm_globals.error_log_fd); } fpm_globals.error_log_fd = -1; zlog_set_fd(-1); if (wp->listening_socket != STDIN_FILENO) { if (0 > dup2(wp->listening_socket, STDIN_FILENO)) { zlog(ZLOG_SYSERROR, "failed to init child stdio: dup2()"); return -1; } } return 0; } /* }}} */ Vulnerability Type: CWE ID: CWE-400 Summary: An issue was discovered in PHP 7.3.x before 7.3.0alpha3, 7.2.x before 7.2.8, and before 7.1.20. The php-fpm master process restarts a child process in an endless loop when using program execution functions (e.g., passthru, exec, shell_exec, or system) with a non-blocking STDIN stream, causing this master process to consume 100% of the CPU, and consume disk space with a large volume of error logs, as demonstrated by an attack by a customer of a shared-hosting facility. Commit Message: Fixed bug #73342 Directly listen on socket, instead of duping it to STDIN and listening on that.
Medium
23,399
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label, bool is_tld_ascii) { UErrorCode status = U_ZERO_ERROR; int32_t result = uspoof_check(checker_, label.data(), base::checked_cast<int32_t>(label.size()), nullptr, &status); if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS)) return false; icu::UnicodeString label_string(FALSE, label.data(), base::checked_cast<int32_t>(label.size())); if (deviation_characters_.containsSome(label_string)) return false; result &= USPOOF_RESTRICTION_LEVEL_MASK; if (result == USPOOF_ASCII) return true; if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE && kana_letters_exceptions_.containsNone(label_string) && combining_diacritics_exceptions_.containsNone(label_string)) { return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string); } if (non_ascii_latin_letters_.containsSome(label_string) && !lgc_letters_n_ascii_.containsAll(label_string)) return false; if (!tls_index.initialized()) tls_index.Initialize(&OnThreadTermination); icu::RegexMatcher* dangerous_pattern = reinterpret_cast<icu::RegexMatcher*>(tls_index.Get()); if (!dangerous_pattern) { dangerous_pattern = new icu::RegexMatcher( icu::UnicodeString( R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])" R"([\u30ce\u30f3\u30bd\u30be])" R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)" R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)" R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)" R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)" R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)" R"([a-z]\u30fb|\u30fb[a-z]|)" R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)" R"([ijl\u0131]\u0307)", -1, US_INV), 0, status); tls_index.Set(dangerous_pattern); } dangerous_pattern->reset(label_string); return !dangerous_pattern->find(); } Vulnerability Type: CWE ID: CWE-20 Summary: Incorrect security UI in Omnibox in Google Chrome prior to 64.0.3282.119 allowed a remote attacker to spoof the contents of the Omnibox (URL bar) via a crafted HTML page. Commit Message: Block dotless-i / j + a combining mark U+0131 (doltess i) and U+0237 (dotless j) are blocked from being followed by a combining mark in U+0300 block. Bug: 774842 Test: See the bug Change-Id: I92aac0e97233184864d060fd0f137a90b042c679 Reviewed-on: https://chromium-review.googlesource.com/767888 Commit-Queue: Jungshik Shin <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#517605}
Medium
29,275
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int ovl_copy_up_locked(struct dentry *workdir, struct dentry *upperdir, struct dentry *dentry, struct path *lowerpath, struct kstat *stat, struct iattr *attr, const char *link) { struct inode *wdir = workdir->d_inode; struct inode *udir = upperdir->d_inode; struct dentry *newdentry = NULL; struct dentry *upper = NULL; umode_t mode = stat->mode; int err; newdentry = ovl_lookup_temp(workdir, dentry); err = PTR_ERR(newdentry); if (IS_ERR(newdentry)) goto out; upper = lookup_one_len(dentry->d_name.name, upperdir, dentry->d_name.len); err = PTR_ERR(upper); if (IS_ERR(upper)) goto out1; /* Can't properly set mode on creation because of the umask */ stat->mode &= S_IFMT; err = ovl_create_real(wdir, newdentry, stat, link, NULL, true); stat->mode = mode; if (err) goto out2; if (S_ISREG(stat->mode)) { struct path upperpath; ovl_path_upper(dentry, &upperpath); BUG_ON(upperpath.dentry != NULL); upperpath.dentry = newdentry; err = ovl_copy_up_data(lowerpath, &upperpath, stat->size); if (err) goto out_cleanup; } err = ovl_copy_xattr(lowerpath->dentry, newdentry); if (err) goto out_cleanup; mutex_lock(&newdentry->d_inode->i_mutex); err = ovl_set_attr(newdentry, stat); if (!err && attr) err = notify_change(newdentry, attr, NULL); mutex_unlock(&newdentry->d_inode->i_mutex); if (err) goto out_cleanup; err = ovl_do_rename(wdir, newdentry, udir, upper, 0); if (err) goto out_cleanup; ovl_dentry_update(dentry, newdentry); newdentry = NULL; /* * Non-directores become opaque when copied up. */ if (!S_ISDIR(stat->mode)) ovl_dentry_set_opaque(dentry, true); out2: dput(upper); out1: dput(newdentry); out: return err; out_cleanup: ovl_cleanup(wdir, newdentry); goto out; } Vulnerability Type: DoS CWE ID: CWE-399 Summary: fs/overlayfs/copy_up.c in the Linux kernel before 4.2.6 uses an incorrect cleanup code path, which allows local users to cause a denial of service (dentry reference leak) via filesystem operations on a large file in a lower overlayfs layer. Commit Message: ovl: fix dentry reference leak In ovl_copy_up_locked(), newdentry is leaked if the function exits through out_cleanup as this just to out after calling ovl_cleanup() - which doesn't actually release the ref on newdentry. The out_cleanup segment should instead exit through out2 as certainly newdentry leaks - and possibly upper does also, though this isn't caught given the catch of newdentry. Without this fix, something like the following is seen: BUG: Dentry ffff880023e9eb20{i=f861,n=#ffff880023e82d90} still in use (1) [unmount of tmpfs tmpfs] BUG: Dentry ffff880023ece640{i=0,n=bigfile} still in use (1) [unmount of tmpfs tmpfs] when unmounting the upper layer after an error occurred in copyup. An error can be induced by creating a big file in a lower layer with something like: dd if=/dev/zero of=/lower/a/bigfile bs=65536 count=1 seek=$((0xf000)) to create a large file (4.1G). Overlay an upper layer that is too small (on tmpfs might do) and then induce a copy up by opening it writably. Reported-by: Ulrich Obergfell <[email protected]> Signed-off-by: David Howells <[email protected]> Signed-off-by: Miklos Szeredi <[email protected]> Cc: <[email protected]> # v3.18+
Medium
25,035
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: PHP_METHOD(Phar, addFromString) { char *localname, *cont_str; size_t localname_len, cont_len; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &localname, &localname_len, &cont_str, &cont_len) == FAILURE) { return; } phar_add_file(&(phar_obj->archive), localname, localname_len, cont_str, cont_len, NULL); } Vulnerability Type: Exec Code CWE ID: CWE-20 Summary: The Phar extension in PHP before 5.5.34, 5.6.x before 5.6.20, and 7.x before 7.0.5 allows remote attackers to execute arbitrary code via a crafted filename, as demonstrated by mishandling of \0 characters by the phar_analyze_path function in ext/phar/phar.c. Commit Message:
High
8,867
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void RunInvTxfm(const int16_t *out, uint8_t *dst, int stride) { inv_txfm_(out, dst, stride); } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: libvpx in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49H, and 6.0 before 2016-03-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to libwebm/mkvparser.cpp and other files, aka internal bug 23452792. 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
High
11,349
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { if (size > 512) return 0; net::ProxyBypassRules rules; std::string input(data, data + size); rules.ParseFromString(input); rules.ParseFromStringUsingSuffixMatching(input); return 0; } Vulnerability Type: CWE ID: CWE-20 Summary: Lack of special casing of localhost in WPAD files in Google Chrome prior to 71.0.3578.80 allowed an attacker on the local network segment to proxy resources on localhost via a crafted WPAD file. Commit Message: Implicitly bypass localhost when proxying requests. This aligns Chrome's behavior with the Windows and macOS proxy resolvers (but not Firefox). Concretely: * localhost names (as determined by net::IsLocalhost) now implicitly bypass the proxy * link-local IP addresses implicitly bypass the proxy The implicit rules are handled by ProxyBypassRules, and it is possible to override them when manually configuring proxy settings (but not when using PAC or auto-detect). This change also adds support for the "<-loopback>" proxy bypass rule, with similar semantics as it has on Windows (removes the implicit bypass rules for localhost and link-local). The compatibility risk of this change should be low as proxying through localhost was not universally supported. It is however an idiom used in testing (a number of our own tests had such a dependency). Impacted users can use the "<-loopback>" bypass rule as a workaround. Bug: 413511, 899126, 901896 Change-Id: I263ca21ef9f12d4759a20cb4751dc3261bda6ac0 Reviewed-on: https://chromium-review.googlesource.com/c/1303626 Commit-Queue: Eric Roman <[email protected]> Reviewed-by: Dominick Ng <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Reviewed-by: Matt Menke <[email protected]> Reviewed-by: Sami Kyöstilä <[email protected]> Cr-Commit-Position: refs/heads/master@{#606112}
Low
19,018
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: cJSON *cJSON_DetachItemFromObject( cJSON *object, const char *string ) { int i = 0; cJSON *c = object->child; while ( c && cJSON_strcasecmp( c->string, string ) ) { ++i; c = c->next; } if ( c ) return cJSON_DetachItemFromArray( object, i ); return 0; } Vulnerability Type: DoS Exec Code Overflow CWE ID: CWE-119 Summary: The parse_string function in cjson.c in the cJSON library mishandles UTF8/16 strings, which allows remote attackers to cause a denial of service (crash) or execute arbitrary code via a non-hex character in a JSON string, which triggers a heap-based buffer overflow. Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]>
High
1,245
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: int udf_get_filename(struct super_block *sb, uint8_t *sname, uint8_t *dname, int flen) { struct ustr *filename, *unifilename; int len = 0; filename = kmalloc(sizeof(struct ustr), GFP_NOFS); if (!filename) return 0; unifilename = kmalloc(sizeof(struct ustr), GFP_NOFS); if (!unifilename) goto out1; if (udf_build_ustr_exact(unifilename, sname, flen)) goto out2; if (UDF_QUERY_FLAG(sb, UDF_FLAG_UTF8)) { if (!udf_CS0toUTF8(filename, unifilename)) { udf_debug("Failed in udf_get_filename: sname = %s\n", sname); goto out2; } } else if (UDF_QUERY_FLAG(sb, UDF_FLAG_NLS_MAP)) { if (!udf_CS0toNLS(UDF_SB(sb)->s_nls_map, filename, unifilename)) { udf_debug("Failed in udf_get_filename: sname = %s\n", sname); goto out2; } } else goto out2; len = udf_translate_to_linux(dname, filename->u_name, filename->u_len, unifilename->u_name, unifilename->u_len); out2: kfree(unifilename); out1: kfree(filename); return len; } Vulnerability Type: +Info CWE ID: CWE-17 Summary: The UDF filesystem implementation in the Linux kernel before 3.18.2 does not ensure that space is available for storing a symlink target's name along with a trailing 0 character, which allows local users to obtain sensitive information via a crafted filesystem image, related to fs/udf/symlink.c and fs/udf/unicode.c. Commit Message: udf: Check path length when reading symlink Symlink reading code does not check whether the resulting path fits into the page provided by the generic code. This isn't as easy as just checking the symlink size because of various encoding conversions we perform on path. So we have to check whether there is still enough space in the buffer on the fly. CC: [email protected] Reported-by: Carl Henrik Lunde <[email protected]> Signed-off-by: Jan Kara <[email protected]>
Low
8,799
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: vips_foreign_load_gif_scan_image( VipsForeignLoadGif *gif ) { VipsObjectClass *class = VIPS_OBJECT_GET_CLASS( gif ); GifFileType *file = gif->file; ColorMapObject *map = file->Image.ColorMap ? file->Image.ColorMap : file->SColorMap; GifByteType *extension; if( DGifGetImageDesc( gif->file ) == GIF_ERROR ) { vips_foreign_load_gif_error( gif ); return( -1 ); } /* Check that the frame looks sane. Perhaps giflib checks * this for us. */ if( file->Image.Left < 0 || file->Image.Width < 1 || file->Image.Width > 10000 || file->Image.Left + file->Image.Width > file->SWidth || file->Image.Top < 0 || file->Image.Height < 1 || file->Image.Height > 10000 || file->Image.Top + file->Image.Height > file->SHeight ) { vips_error( class->nickname, "%s", _( "bad frame size" ) ); return( -1 ); } /* Test for a non-greyscale colourmap for this frame. */ if( !gif->has_colour && map ) { int i; for( i = 0; i < map->ColorCount; i++ ) if( map->Colors[i].Red != map->Colors[i].Green || map->Colors[i].Green != map->Colors[i].Blue ) { gif->has_colour = TRUE; break; } } /* Step over compressed image data. */ do { if( vips_foreign_load_gif_code_next( gif, &extension ) ) return( -1 ); } while( extension != NULL ); return( 0 ); } Vulnerability Type: CWE ID: Summary: vips_foreign_load_gif_scan_image in foreign/gifload.c in libvips before 8.8.2 tries to access a color map before a DGifGetImageDesc call, leading to a use-after-free. Commit Message: fetch map after DGifGetImageDesc() Earlier refactoring broke GIF map fetch.
Low
20,945
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void PrintPreviewDataService::GetDataEntry( const std::string& preview_ui_addr_str, int index, scoped_refptr<base::RefCountedBytes>* data_bytes) { *data_bytes = NULL; PreviewDataStoreMap::iterator it = data_store_map_.find(preview_ui_addr_str); if (it != data_store_map_.end()) it->second->GetPreviewDataForIndex(index, data_bytes); } Vulnerability Type: +Info CWE ID: CWE-200 Summary: The IPC implementation in Google Chrome before 22.0.1229.79 allows attackers to obtain potentially sensitive information about memory addresses via unspecified vectors. 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
Medium
24,468
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static Image *ReadDPSImage(const ImageInfo *image_info,ExceptionInfo *exception) { const char *client_name; Display *display; float pixels_per_point; Image *image; int sans, status; Pixmap pixmap; register IndexPacket *indexes; register ssize_t i; register PixelPacket *q; register size_t pixel; Screen *screen; ssize_t x, y; XColor *colors; XImage *dps_image; XRectangle page, bits_per_pixel; XResourceInfo resource_info; XrmDatabase resource_database; XStandardColormap *map_info; XVisualInfo *visual_info; /* Open X server connection. */ 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); display=XOpenDisplay(image_info->server_name); if (display == (Display *) NULL) return((Image *) NULL); /* Set our forgiving exception handler. */ (void) XSetErrorHandler(XError); /* Open image file. */ image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); /* Get user defaults from X resource database. */ client_name=GetClientName(); resource_database=XGetResourceDatabase(display,client_name); XGetResourceInfo(image_info,resource_database,client_name,&resource_info); /* Allocate standard colormap. */ map_info=XAllocStandardColormap(); visual_info=(XVisualInfo *) NULL; if (map_info == (XStandardColormap *) NULL) ThrowReaderException(ResourceLimitError,"UnableToCreateStandardColormap") else { /* Initialize visual info. */ (void) CloneString(&resource_info.visual_type,"default"); visual_info=XBestVisualInfo(display,map_info,&resource_info); map_info->colormap=(Colormap) NULL; } if ((map_info == (XStandardColormap *) NULL) || (visual_info == (XVisualInfo *) NULL)) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Create a pixmap the appropriate size for the image. */ screen=ScreenOfDisplay(display,visual_info->screen); pixels_per_point=XDPSPixelsPerPoint(screen); if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0)) pixels_per_point=MagickMin(image->x_resolution,image->y_resolution)/ DefaultResolution; status=XDPSCreatePixmapForEPSF((DPSContext) NULL,screen, GetBlobFileHandle(image),visual_info->depth,pixels_per_point,&pixmap, &bits_per_pixel,&page); if ((status == dps_status_failure) || (status == dps_status_no_extension)) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Rasterize the file into the pixmap. */ status=XDPSImageFileIntoDrawable((DPSContext) NULL,screen,pixmap, GetBlobFileHandle(image),(int) bits_per_pixel.height,visual_info->depth, &page,-page.x,-page.y,pixels_per_point,MagickTrue,MagickFalse,MagickTrue, &sans); if (status != dps_status_success) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Initialize DPS X image. */ dps_image=XGetImage(display,pixmap,0,0,bits_per_pixel.width, bits_per_pixel.height,AllPlanes,ZPixmap); (void) XFreePixmap(display,pixmap); if (dps_image == (XImage *) NULL) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Get the colormap colors. */ colors=(XColor *) AcquireQuantumMemory(visual_info->colormap_size, sizeof(*colors)); if (colors == (XColor *) NULL) { image=DestroyImage(image); XDestroyImage(dps_image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } if ((visual_info->klass != DirectColor) && (visual_info->klass != TrueColor)) for (i=0; i < visual_info->colormap_size; i++) { colors[i].pixel=(size_t) i; colors[i].pad=0; } else { size_t blue, blue_bit, green, green_bit, red, red_bit; /* DirectColor or TrueColor visual. */ red=0; green=0; blue=0; red_bit=visual_info->red_mask & (~(visual_info->red_mask)+1); green_bit=visual_info->green_mask & (~(visual_info->green_mask)+1); blue_bit=visual_info->blue_mask & (~(visual_info->blue_mask)+1); for (i=0; i < visual_info->colormap_size; i++) { colors[i].pixel=red | green | blue; colors[i].pad=0; red+=red_bit; if (red > visual_info->red_mask) red=0; green+=green_bit; if (green > visual_info->green_mask) green=0; blue+=blue_bit; if (blue > visual_info->blue_mask) blue=0; } } (void) XQueryColors(display,XDefaultColormap(display,visual_info->screen), colors,visual_info->colormap_size); /* Convert X image to MIFF format. */ if ((visual_info->klass != TrueColor) && (visual_info->klass != DirectColor)) image->storage_class=PseudoClass; image->columns=(size_t) dps_image->width; image->rows=(size_t) dps_image->height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } switch (image->storage_class) { case DirectClass: default: { register size_t color, index; size_t blue_mask, blue_shift, green_mask, green_shift, red_mask, red_shift; /* Determine shift and mask for red, green, and blue. */ red_mask=visual_info->red_mask; red_shift=0; while ((red_mask != 0) && ((red_mask & 0x01) == 0)) { red_mask>>=1; red_shift++; } green_mask=visual_info->green_mask; green_shift=0; while ((green_mask != 0) && ((green_mask & 0x01) == 0)) { green_mask>>=1; green_shift++; } blue_mask=visual_info->blue_mask; blue_shift=0; while ((blue_mask != 0) && ((blue_mask & 0x01) == 0)) { blue_mask>>=1; blue_shift++; } /* Convert X image to DirectClass packets. */ if ((visual_info->colormap_size > 0) && (visual_info->klass == DirectColor)) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(dps_image,x,y); index=(pixel >> red_shift) & red_mask; SetPixelRed(q,ScaleShortToQuantum(colors[index].red)); index=(pixel >> green_shift) & green_mask; SetPixelGreen(q,ScaleShortToQuantum(colors[index].green)); index=(pixel >> blue_shift) & blue_mask; SetPixelBlue(q,ScaleShortToQuantum(colors[index].blue)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } else for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(dps_image,x,y); color=(pixel >> red_shift) & red_mask; color=(color*65535L)/red_mask; SetPixelRed(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> green_shift) & green_mask; color=(color*65535L)/green_mask; SetPixelGreen(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> blue_shift) & blue_mask; color=(color*65535L)/blue_mask; SetPixelBlue(q,ScaleShortToQuantum((unsigned short) color)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } break; } case PseudoClass: { /* Create colormap. */ if (AcquireImageColormap(image,(size_t) visual_info->colormap_size) == MagickFalse) { image=DestroyImage(image); colors=(XColor *) RelinquishMagickMemory(colors); XDestroyImage(dps_image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[colors[i].pixel].red=ScaleShortToQuantum(colors[i].red); image->colormap[colors[i].pixel].green= ScaleShortToQuantum(colors[i].green); image->colormap[colors[i].pixel].blue= ScaleShortToQuantum(colors[i].blue); } /* Convert X image to PseudoClass packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,(unsigned short) XGetPixel(dps_image,x,y)); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } break; } } colors=(XColor *) RelinquishMagickMemory(colors); XDestroyImage(dps_image); if (image->storage_class == PseudoClass) (void) SyncImage(image); /* Rasterize matte image. */ status=XDPSCreatePixmapForEPSF((DPSContext) NULL,screen, GetBlobFileHandle(image),1,pixels_per_point,&pixmap,&bits_per_pixel,&page); if ((status != dps_status_failure) && (status != dps_status_no_extension)) { status=XDPSImageFileIntoDrawable((DPSContext) NULL,screen,pixmap, GetBlobFileHandle(image),(int) bits_per_pixel.height,1,&page,-page.x, -page.y,pixels_per_point,MagickTrue,MagickTrue,MagickTrue,&sans); if (status == dps_status_success) { XImage *matte_image; /* Initialize image matte. */ matte_image=XGetImage(display,pixmap,0,0,bits_per_pixel.width, bits_per_pixel.height,AllPlanes,ZPixmap); (void) XFreePixmap(display,pixmap); if (matte_image != (XImage *) NULL) { image->storage_class=DirectClass; image->matte=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,OpaqueOpacity); if (XGetPixel(matte_image,x,y) == 0) SetPixelOpacity(q,TransparentOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } XDestroyImage(matte_image); } } } /* Relinquish resources. */ XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: Buffer overflow in the ReadVIFFImage function in coders/viff.c in ImageMagick before 6.9.4-5 allows remote attackers to cause a denial of service (application crash) via a crafted file. Commit Message:
Medium
2,121
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void *Sys_LoadDll(const char *name, qboolean useSystemLib) { void *dllhandle; if(useSystemLib) Com_Printf("Trying to load \"%s\"...\n", name); if(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name))) { const char *topDir; char libPath[MAX_OSPATH]; topDir = Sys_BinaryPath(); if(!*topDir) topDir = "."; Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, topDir); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", topDir, PATH_SEP, name); if(!(dllhandle = Sys_LoadLibrary(libPath))) { const char *basePath = Cvar_VariableString("fs_basepath"); if(!basePath || !*basePath) basePath = "."; if(FS_FilenameCompare(topDir, basePath)) { Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, basePath); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", basePath, PATH_SEP, name); dllhandle = Sys_LoadLibrary(libPath); } if(!dllhandle) Com_Printf("Loading \"%s\" failed\n", name); } } return dllhandle; } Vulnerability Type: CWE ID: CWE-269 Summary: In ioquake3 before 2017-03-14, the auto-downloading feature has insufficient content restrictions. This also affects Quake III Arena, OpenArena, OpenJK, iortcw, and other id Tech 3 (aka Quake 3 engine) forks. A malicious auto-downloaded file can trigger loading of crafted auto-downloaded files as native code DLLs. A malicious auto-downloaded file can contain configuration defaults that override the user's. Executable bytecode in a malicious auto-downloaded file can set configuration variables to values that will result in unwanted native code DLLs being loaded, resulting in sandbox escape. Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s
High
20,195
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static v8::Handle<v8::Value> overloadedMethod6Callback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.overloadedMethod6"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(RefPtr<DOMStringList>, listArg, v8ValueToWebCoreDOMStringList(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); imp->overloadedMethod(listArg); return v8::Handle<v8::Value>(); } Vulnerability Type: CWE ID: Summary: The browser native UI in Google Chrome before 17.0.963.83 does not require user confirmation before an unpacked extension installation, which allows user-assisted remote attackers to have an unspecified impact via a crafted extension. Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
Medium
2,097
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int crypto_nivaead_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_aead raead; struct aead_alg *aead = &alg->cra_aead; snprintf(raead.type, CRYPTO_MAX_ALG_NAME, "%s", "nivaead"); snprintf(raead.geniv, CRYPTO_MAX_ALG_NAME, "%s", aead->geniv); raead.blocksize = alg->cra_blocksize; raead.maxauthsize = aead->maxauthsize; raead.ivsize = aead->ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_AEAD, sizeof(struct crypto_report_aead), &raead)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } Vulnerability Type: +Info CWE ID: CWE-310 Summary: The crypto_report_one function in crypto/crypto_user.c in the report API in the crypto user configuration API in the Linux kernel through 3.8.2 uses an incorrect length value during a copy operation, which allows local users to obtain sensitive information from kernel memory by leveraging the CAP_NET_ADMIN capability. Commit Message: crypto: user - fix info leaks in report API Three errors resulting in kernel memory disclosure: 1/ The structures used for the netlink based crypto algorithm report API are located on the stack. As snprintf() does not fill the remainder of the buffer with null bytes, those stack bytes will be disclosed to users of the API. Switch to strncpy() to fix this. 2/ crypto_report_one() does not initialize all field of struct crypto_user_alg. Fix this to fix the heap info leak. 3/ For the module name we should copy only as many bytes as module_name() returns -- not as much as the destination buffer could hold. But the current code does not and therefore copies random data from behind the end of the module name, as the module name is always shorter than CRYPTO_MAX_ALG_NAME. Also switch to use strncpy() to copy the algorithm's name and driver_name. They are strings, after all. Signed-off-by: Mathias Krause <[email protected]> Cc: Steffen Klassert <[email protected]> Signed-off-by: Herbert Xu <[email protected]>
Low
26,709
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: int Equalizer_getParameter(EffectContext *pContext, void *pParam, uint32_t *pValueSize, void *pValue){ int status = 0; int bMute = 0; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++; int32_t param2; char *name; switch (param) { case EQ_PARAM_NUM_BANDS: case EQ_PARAM_CUR_PRESET: case EQ_PARAM_GET_NUM_OF_PRESETS: case EQ_PARAM_BAND_LEVEL: case EQ_PARAM_GET_BAND: if (*pValueSize < sizeof(int16_t)) { ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 1 %d", *pValueSize); return -EINVAL; } *pValueSize = sizeof(int16_t); break; case EQ_PARAM_LEVEL_RANGE: if (*pValueSize < 2 * sizeof(int16_t)) { ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 2 %d", *pValueSize); return -EINVAL; } *pValueSize = 2 * sizeof(int16_t); break; case EQ_PARAM_BAND_FREQ_RANGE: if (*pValueSize < 2 * sizeof(int32_t)) { ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 3 %d", *pValueSize); return -EINVAL; } *pValueSize = 2 * sizeof(int32_t); break; case EQ_PARAM_CENTER_FREQ: if (*pValueSize < sizeof(int32_t)) { ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 5 %d", *pValueSize); return -EINVAL; } *pValueSize = sizeof(int32_t); break; case EQ_PARAM_GET_PRESET_NAME: break; case EQ_PARAM_PROPERTIES: if (*pValueSize < (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t)) { ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 1 %d", *pValueSize); return -EINVAL; } *pValueSize = (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t); break; default: ALOGV("\tLVM_ERROR : Equalizer_getParameter unknown param %d", param); return -EINVAL; } switch (param) { case EQ_PARAM_NUM_BANDS: *(uint16_t *)pValue = (uint16_t)FIVEBAND_NUMBANDS; break; case EQ_PARAM_LEVEL_RANGE: *(int16_t *)pValue = -1500; *((int16_t *)pValue + 1) = 1500; break; case EQ_PARAM_BAND_LEVEL: param2 = *pParamTemp; if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) { status = -EINVAL; if (param2 < 0) { android_errorWriteLog(0x534e4554, "32438598"); ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_BAND_LEVEL band %d", param2); } break; } *(int16_t *)pValue = (int16_t)EqualizerGetBandLevel(pContext, param2); break; case EQ_PARAM_CENTER_FREQ: param2 = *pParamTemp; if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) { status = -EINVAL; if (param2 < 0) { android_errorWriteLog(0x534e4554, "32436341"); ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_CENTER_FREQ band %d", param2); } break; } *(int32_t *)pValue = EqualizerGetCentreFrequency(pContext, param2); break; case EQ_PARAM_BAND_FREQ_RANGE: param2 = *pParamTemp; if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) { status = -EINVAL; if (param2 < 0) { android_errorWriteLog(0x534e4554, "32247948"); ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_BAND_FREQ_RANGE band %d", param2); } break; } EqualizerGetBandFreqRange(pContext, param2, (uint32_t *)pValue, ((uint32_t *)pValue + 1)); break; case EQ_PARAM_GET_BAND: param2 = *pParamTemp; *(uint16_t *)pValue = (uint16_t)EqualizerGetBand(pContext, param2); break; case EQ_PARAM_CUR_PRESET: *(uint16_t *)pValue = (uint16_t)EqualizerGetPreset(pContext); break; case EQ_PARAM_GET_NUM_OF_PRESETS: *(uint16_t *)pValue = (uint16_t)EqualizerGetNumPresets(); break; case EQ_PARAM_GET_PRESET_NAME: param2 = *pParamTemp; if (param2 >= EqualizerGetNumPresets()) { status = -EINVAL; break; } name = (char *)pValue; strncpy(name, EqualizerGetPresetName(param2), *pValueSize - 1); name[*pValueSize - 1] = 0; *pValueSize = strlen(name) + 1; break; case EQ_PARAM_PROPERTIES: { int16_t *p = (int16_t *)pValue; ALOGV("\tEqualizer_getParameter() EQ_PARAM_PROPERTIES"); p[0] = (int16_t)EqualizerGetPreset(pContext); p[1] = (int16_t)FIVEBAND_NUMBANDS; for (int i = 0; i < FIVEBAND_NUMBANDS; i++) { p[2 + i] = (int16_t)EqualizerGetBandLevel(pContext, i); } } break; default: ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid param %d", param); status = -EINVAL; break; } return status; } /* end Equalizer_getParameter */ int Equalizer_setParameter (EffectContext *pContext, void *pParam, void *pValue){ int status = 0; int32_t preset; int32_t band; int32_t level; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++; switch (param) { case EQ_PARAM_CUR_PRESET: preset = (int32_t)(*(uint16_t *)pValue); if ((preset >= EqualizerGetNumPresets())||(preset < 0)) { status = -EINVAL; break; } EqualizerSetPreset(pContext, preset); break; case EQ_PARAM_BAND_LEVEL: band = *pParamTemp; level = (int32_t)(*(int16_t *)pValue); if (band >= FIVEBAND_NUMBANDS) { status = -EINVAL; break; } EqualizerSetBandLevel(pContext, band, level); break; case EQ_PARAM_PROPERTIES: { int16_t *p = (int16_t *)pValue; if ((int)p[0] >= EqualizerGetNumPresets()) { status = -EINVAL; break; } if (p[0] >= 0) { EqualizerSetPreset(pContext, (int)p[0]); } else { if ((int)p[1] != FIVEBAND_NUMBANDS) { status = -EINVAL; break; } for (int i = 0; i < FIVEBAND_NUMBANDS; i++) { EqualizerSetBandLevel(pContext, i, (int)p[2 + i]); } } } break; default: ALOGV("\tLVM_ERROR : Equalizer_setParameter() invalid param %d", param); status = -EINVAL; break; } return status; } /* end Equalizer_setParameter */ int Volume_getParameter(EffectContext *pContext, void *pParam, uint32_t *pValueSize, void *pValue){ int status = 0; int bMute = 0; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++;; char *name; switch (param){ case VOLUME_PARAM_LEVEL: case VOLUME_PARAM_MAXLEVEL: case VOLUME_PARAM_STEREOPOSITION: if (*pValueSize != sizeof(int16_t)){ ALOGV("\tLVM_ERROR : Volume_getParameter() invalid pValueSize 1 %d", *pValueSize); return -EINVAL; } *pValueSize = sizeof(int16_t); break; case VOLUME_PARAM_MUTE: case VOLUME_PARAM_ENABLESTEREOPOSITION: if (*pValueSize < sizeof(int32_t)){ ALOGV("\tLVM_ERROR : Volume_getParameter() invalid pValueSize 2 %d", *pValueSize); return -EINVAL; } *pValueSize = sizeof(int32_t); break; default: ALOGV("\tLVM_ERROR : Volume_getParameter unknown param %d", param); return -EINVAL; } switch (param){ case VOLUME_PARAM_LEVEL: status = VolumeGetVolumeLevel(pContext, (int16_t *)(pValue)); break; case VOLUME_PARAM_MAXLEVEL: *(int16_t *)pValue = 0; break; case VOLUME_PARAM_STEREOPOSITION: VolumeGetStereoPosition(pContext, (int16_t *)pValue); break; case VOLUME_PARAM_MUTE: status = VolumeGetMute(pContext, (uint32_t *)pValue); ALOGV("\tVolume_getParameter() VOLUME_PARAM_MUTE Value is %d", *(uint32_t *)pValue); break; case VOLUME_PARAM_ENABLESTEREOPOSITION: *(int32_t *)pValue = pContext->pBundledContext->bStereoPositionEnabled; break; default: ALOGV("\tLVM_ERROR : Volume_getParameter() invalid param %d", param); status = -EINVAL; break; } return status; } /* end Volume_getParameter */ int Volume_setParameter (EffectContext *pContext, void *pParam, void *pValue){ int status = 0; int16_t level; int16_t position; uint32_t mute; uint32_t positionEnabled; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++; switch (param){ case VOLUME_PARAM_LEVEL: level = *(int16_t *)pValue; status = VolumeSetVolumeLevel(pContext, (int16_t)level); break; case VOLUME_PARAM_MUTE: mute = *(uint32_t *)pValue; status = VolumeSetMute(pContext, mute); break; case VOLUME_PARAM_ENABLESTEREOPOSITION: positionEnabled = *(uint32_t *)pValue; status = VolumeEnableStereoPosition(pContext, positionEnabled); status = VolumeSetStereoPosition(pContext, pContext->pBundledContext->positionSaved); break; case VOLUME_PARAM_STEREOPOSITION: position = *(int16_t *)pValue; status = VolumeSetStereoPosition(pContext, (int16_t)position); break; default: ALOGV("\tLVM_ERROR : Volume_setParameter() invalid param %d", param); break; } return status; } /* end Volume_setParameter */ /**************************************************************************************** * Name : LVC_ToDB_s32Tos16() * Input : Signed 32-bit integer * Output : Signed 16-bit integer * MSB (16) = sign bit * (15->05) = integer part * (04->01) = decimal part * Returns : Db value with respect to full scale * Description : * Remarks : ****************************************************************************************/ LVM_INT16 LVC_ToDB_s32Tos16(LVM_INT32 Lin_fix) { LVM_INT16 db_fix; LVM_INT16 Shift; LVM_INT16 SmallRemainder; LVM_UINT32 Remainder = (LVM_UINT32)Lin_fix; /* Count leading bits, 1 cycle in assembly*/ for (Shift = 0; Shift<32; Shift++) { if ((Remainder & 0x80000000U)!=0) { break; } Remainder = Remainder << 1; } /* * Based on the approximation equation (for Q11.4 format): * * dB = -96 * Shift + 16 * (8 * Remainder - 2 * Remainder^2) */ db_fix = (LVM_INT16)(-96 * Shift); /* Six dB steps in Q11.4 format*/ SmallRemainder = (LVM_INT16)((Remainder & 0x7fffffff) >> 24); db_fix = (LVM_INT16)(db_fix + SmallRemainder ); SmallRemainder = (LVM_INT16)(SmallRemainder * SmallRemainder); db_fix = (LVM_INT16)(db_fix - (LVM_INT16)((LVM_UINT16)SmallRemainder >> 9)); /* Correct for small offset */ db_fix = (LVM_INT16)(db_fix - 5); return db_fix; } int Effect_setEnabled(EffectContext *pContext, bool enabled) { ALOGV("\tEffect_setEnabled() type %d, enabled %d", pContext->EffectType, enabled); if (enabled) { bool tempDisabled = false; switch (pContext->EffectType) { case LVM_BASS_BOOST: if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) { ALOGV("\tEffect_setEnabled() LVM_BASS_BOOST is already enabled"); return -EINVAL; } if(pContext->pBundledContext->SamplesToExitCountBb <= 0){ pContext->pBundledContext->NumberEffectsEnabled++; } pContext->pBundledContext->SamplesToExitCountBb = (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1); pContext->pBundledContext->bBassEnabled = LVM_TRUE; tempDisabled = pContext->pBundledContext->bBassTempDisabled; break; case LVM_EQUALIZER: if (pContext->pBundledContext->bEqualizerEnabled == LVM_TRUE) { ALOGV("\tEffect_setEnabled() LVM_EQUALIZER is already enabled"); return -EINVAL; } if(pContext->pBundledContext->SamplesToExitCountEq <= 0){ pContext->pBundledContext->NumberEffectsEnabled++; } pContext->pBundledContext->SamplesToExitCountEq = (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1); pContext->pBundledContext->bEqualizerEnabled = LVM_TRUE; break; case LVM_VIRTUALIZER: if (pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE) { ALOGV("\tEffect_setEnabled() LVM_VIRTUALIZER is already enabled"); return -EINVAL; } if(pContext->pBundledContext->SamplesToExitCountVirt <= 0){ pContext->pBundledContext->NumberEffectsEnabled++; } pContext->pBundledContext->SamplesToExitCountVirt = (LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1); pContext->pBundledContext->bVirtualizerEnabled = LVM_TRUE; tempDisabled = pContext->pBundledContext->bVirtualizerTempDisabled; break; case LVM_VOLUME: if (pContext->pBundledContext->bVolumeEnabled == LVM_TRUE) { ALOGV("\tEffect_setEnabled() LVM_VOLUME is already enabled"); return -EINVAL; } pContext->pBundledContext->NumberEffectsEnabled++; pContext->pBundledContext->bVolumeEnabled = LVM_TRUE; break; default: ALOGV("\tEffect_setEnabled() invalid effect type"); return -EINVAL; } if (!tempDisabled) { LvmEffect_enable(pContext); } } else { switch (pContext->EffectType) { case LVM_BASS_BOOST: if (pContext->pBundledContext->bBassEnabled == LVM_FALSE) { ALOGV("\tEffect_setEnabled() LVM_BASS_BOOST is already disabled"); return -EINVAL; } pContext->pBundledContext->bBassEnabled = LVM_FALSE; break; case LVM_EQUALIZER: if (pContext->pBundledContext->bEqualizerEnabled == LVM_FALSE) { ALOGV("\tEffect_setEnabled() LVM_EQUALIZER is already disabled"); return -EINVAL; } pContext->pBundledContext->bEqualizerEnabled = LVM_FALSE; break; case LVM_VIRTUALIZER: if (pContext->pBundledContext->bVirtualizerEnabled == LVM_FALSE) { ALOGV("\tEffect_setEnabled() LVM_VIRTUALIZER is already disabled"); return -EINVAL; } pContext->pBundledContext->bVirtualizerEnabled = LVM_FALSE; break; case LVM_VOLUME: if (pContext->pBundledContext->bVolumeEnabled == LVM_FALSE) { ALOGV("\tEffect_setEnabled() LVM_VOLUME is already disabled"); return -EINVAL; } pContext->pBundledContext->bVolumeEnabled = LVM_FALSE; break; default: ALOGV("\tEffect_setEnabled() invalid effect type"); return -EINVAL; } LvmEffect_disable(pContext); } return 0; } int16_t LVC_Convert_VolToDb(uint32_t vol){ int16_t dB; dB = LVC_ToDB_s32Tos16(vol <<7); dB = (dB +8)>>4; dB = (dB <-96) ? -96 : dB ; return dB; } } // namespace Vulnerability Type: +Info CWE ID: CWE-200 Summary: An information disclosure vulnerability in lvm/wrapper/Bundle/EffectBundle.cpp in libeffects in the Qualcomm audio post processor could enable a local malicious application to access data outside of its permission levels. This issue is rated as Moderate because it could be used to access sensitive data without permission. Product: Android. Versions: 5.0.2, 5.1.1, 6.0, 6.0.1, 7.0, 7.1. Android ID: A-32588016. Commit Message: Fix security vulnerability: Effect command might allow negative indexes Bug: 32448258 Bug: 32095626 Test: Use POC bug or cts security test Change-Id: I69f24eac5866f8d9090fc4c0ebe58c2c297b63df (cherry picked from commit 01183402d757f0c28bfd5e3b127b3809dfd67459)
Medium
3,819
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static Image *ReadARTImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; QuantumInfo *quantum_info; QuantumType quantum_type; MagickBooleanType status; size_t length; ssize_t count, y; unsigned char *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); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->depth=1; image->endian=MSBEndian; (void) ReadBlobLSBShort(image); image->columns=(size_t) ReadBlobLSBShort(image); (void) ReadBlobLSBShort(image); image->rows=(size_t) ReadBlobLSBShort(image); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image colormap. */ if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Convert bi-level image to pixel packets. */ SetImageColorspace(image,GRAYColorspace); quantum_type=IndexQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); length=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); count=ReadBlob(image,(size_t) (-(ssize_t) length) & 0x01,pixels); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } SetQuantumImageType(image,quantum_type); quantum_info=DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: Buffer overflow in the ReadVIFFImage function in coders/viff.c in ImageMagick before 6.9.4-5 allows remote attackers to cause a denial of service (application crash) via a crafted file. Commit Message:
Medium
12,937
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: ssh_session(void) { int type; int interactive = 0; int have_tty = 0; struct winsize ws; char *cp; const char *display; /* Enable compression if requested. */ if (options.compression) { options.compression_level); if (options.compression_level < 1 || options.compression_level > 9) fatal("Compression level must be from 1 (fast) to " "9 (slow, best)."); /* Send the request. */ packet_start(SSH_CMSG_REQUEST_COMPRESSION); packet_put_int(options.compression_level); packet_send(); packet_write_wait(); type = packet_read(); if (type == SSH_SMSG_SUCCESS) packet_start_compression(options.compression_level); else if (type == SSH_SMSG_FAILURE) logit("Warning: Remote host refused compression."); else packet_disconnect("Protocol error waiting for " "compression response."); } /* Allocate a pseudo tty if appropriate. */ if (tty_flag) { debug("Requesting pty."); /* Start the packet. */ packet_start(SSH_CMSG_REQUEST_PTY); /* Store TERM in the packet. There is no limit on the length of the string. */ cp = getenv("TERM"); if (!cp) cp = ""; packet_put_cstring(cp); /* Store window size in the packet. */ if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0) memset(&ws, 0, sizeof(ws)); packet_put_int((u_int)ws.ws_row); packet_put_int((u_int)ws.ws_col); packet_put_int((u_int)ws.ws_xpixel); packet_put_int((u_int)ws.ws_ypixel); /* Store tty modes in the packet. */ tty_make_modes(fileno(stdin), NULL); /* Send the packet, and wait for it to leave. */ packet_send(); packet_write_wait(); /* Read response from the server. */ type = packet_read(); if (type == SSH_SMSG_SUCCESS) { interactive = 1; have_tty = 1; } else if (type == SSH_SMSG_FAILURE) logit("Warning: Remote host failed or refused to " "allocate a pseudo tty."); else packet_disconnect("Protocol error waiting for pty " "request response."); } /* Request X11 forwarding if enabled and DISPLAY is set. */ display = getenv("DISPLAY"); display = getenv("DISPLAY"); if (display == NULL && options.forward_x11) debug("X11 forwarding requested but DISPLAY not set"); if (options.forward_x11 && display != NULL) { char *proto, *data; /* Get reasonable local authentication information. */ client_x11_get_proto(display, options.xauth_location, options.forward_x11_trusted, options.forward_x11_timeout, &proto, &data); /* Request forwarding with authentication spoofing. */ debug("Requesting X11 forwarding with authentication " "spoofing."); /* Request forwarding with authentication spoofing. */ debug("Requesting X11 forwarding with authentication " "spoofing."); x11_request_forwarding_with_spoofing(0, display, proto, data, 0); /* Read response from the server. */ type = packet_read(); if (type == SSH_SMSG_SUCCESS) { interactive = 1; } else if (type == SSH_SMSG_FAILURE) { logit("Warning: Remote host denied X11 forwarding."); } else { packet_disconnect("Protocol error waiting for X11 " "forwarding"); } } /* Tell the packet module whether this is an interactive session. */ packet_set_interactive(interactive, options.ip_qos_interactive, options.ip_qos_bulk); /* Request authentication agent forwarding if appropriate. */ check_agent_present(); if (options.forward_agent) { debug("Requesting authentication agent forwarding."); auth_request_forwarding(); /* Read response from the server. */ type = packet_read(); packet_check_eom(); if (type != SSH_SMSG_SUCCESS) logit("Warning: Remote host denied authentication agent forwarding."); } /* Initiate port forwardings. */ ssh_init_stdio_forwarding(); ssh_init_forwarding(); /* Execute a local command */ if (options.local_command != NULL && options.permit_local_command) ssh_local_cmd(options.local_command); /* * If requested and we are not interested in replies to remote * forwarding requests, then let ssh continue in the background. */ if (fork_after_authentication_flag) { if (options.exit_on_forward_failure && options.num_remote_forwards > 0) { debug("deferring postauth fork until remote forward " "confirmation received"); } else fork_postauth(); } /* * If a command was specified on the command line, execute the * command now. Otherwise request the server to start a shell. */ if (buffer_len(&command) > 0) { int len = buffer_len(&command); if (len > 900) len = 900; debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command)); packet_start(SSH_CMSG_EXEC_CMD); packet_put_string(buffer_ptr(&command), buffer_len(&command)); packet_send(); packet_write_wait(); } else { debug("Requesting shell."); packet_start(SSH_CMSG_EXEC_SHELL); packet_send(); packet_write_wait(); } /* Enter the interactive session. */ return client_loop(have_tty, tty_flag ? options.escape_char : SSH_ESCAPECHAR_NONE, 0); } Vulnerability Type: CWE ID: CWE-254 Summary: The client in OpenSSH before 7.2 mishandles failed cookie generation for untrusted X11 forwarding and relies on the local X11 server for access-control decisions, which allows remote X11 clients to trigger a fallback and obtain trusted X11 forwarding privileges by leveraging configuration issues on this X11 server, as demonstrated by lack of the SECURITY extension on this X11 server. Commit Message:
High
1,622
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void SoftMPEG4::onQueueFilled(OMX_U32 /* portIndex */) { if (mSignalledError || mOutputPortSettingsChange != NONE) { return; } List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); while (!inQueue.empty() && outQueue.size() == kNumOutputBuffers) { BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; if (inHeader == NULL) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; continue; } PortInfo *port = editPortInfo(1); OMX_BUFFERHEADERTYPE *outHeader = port->mBuffers.editItemAt(mNumSamplesOutput & 1).mHeader; if (inHeader->nFilledLen == 0) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); ++mInputBufferCount; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; List<BufferInfo *>::iterator it = outQueue.begin(); while ((*it)->mHeader != outHeader) { ++it; } BufferInfo *outInfo = *it; outInfo->mOwnedByUs = false; outQueue.erase(it); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; } return; } uint8_t *bitstream = inHeader->pBuffer + inHeader->nOffset; uint32_t *start_code = (uint32_t *)bitstream; bool volHeader = *start_code == 0xB0010000; if (volHeader) { PVCleanUpVideoDecoder(mHandle); mInitialized = false; } if (!mInitialized) { uint8_t *vol_data[1]; int32_t vol_size = 0; vol_data[0] = NULL; if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) || volHeader) { vol_data[0] = bitstream; vol_size = inHeader->nFilledLen; } MP4DecodingMode mode = (mMode == MODE_MPEG4) ? MPEG4_MODE : H263_MODE; Bool success = PVInitVideoDecoder( mHandle, vol_data, &vol_size, 1, outputBufferWidth(), outputBufferHeight(), mode); if (!success) { ALOGW("PVInitVideoDecoder failed. Unsupported content?"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } MP4DecodingMode actualMode = PVGetDecBitstreamMode(mHandle); if (mode != actualMode) { notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } PVSetPostProcType((VideoDecControls *) mHandle, 0); bool hasFrameData = false; if (inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } else if (volHeader) { hasFrameData = true; } mInitialized = true; if (mode == MPEG4_MODE && handlePortSettingsChange()) { return; } if (!hasFrameData) { continue; } } if (!mFramesConfigured) { PortInfo *port = editPortInfo(1); OMX_BUFFERHEADERTYPE *outHeader = port->mBuffers.editItemAt(1).mHeader; PVSetReferenceYUV(mHandle, outHeader->pBuffer); mFramesConfigured = true; } uint32_t useExtTimestamp = (inHeader->nOffset == 0); uint32_t timestamp = 0xFFFFFFFF; if (useExtTimestamp) { mPvToOmxTimeMap.add(mPvTime, inHeader->nTimeStamp); timestamp = mPvTime; mPvTime++; } int32_t bufferSize = inHeader->nFilledLen; int32_t tmp = bufferSize; OMX_U32 frameSize = (mWidth * mHeight * 3) / 2; if (outHeader->nAllocLen < frameSize) { android_errorWriteLog(0x534e4554, "27833616"); ALOGE("Insufficient output buffer size"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } if (PVDecodeVideoFrame( mHandle, &bitstream, &timestamp, &tmp, &useExtTimestamp, outHeader->pBuffer) != PV_TRUE) { ALOGE("failed to decode video frame."); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } if (handlePortSettingsChange()) { return; } outHeader->nTimeStamp = mPvToOmxTimeMap.valueFor(timestamp); mPvToOmxTimeMap.removeItem(timestamp); inHeader->nOffset += bufferSize; inHeader->nFilledLen = 0; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { outHeader->nFlags = OMX_BUFFERFLAG_EOS; } else { outHeader->nFlags = 0; } if (inHeader->nFilledLen == 0) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } ++mInputBufferCount; outHeader->nOffset = 0; outHeader->nFilledLen = frameSize; List<BufferInfo *>::iterator it = outQueue.begin(); while ((*it)->mHeader != outHeader) { ++it; } BufferInfo *outInfo = *it; outInfo->mOwnedByUs = false; outQueue.erase(it); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; ++mNumSamplesOutput; } } Vulnerability Type: +Priv CWE ID: CWE-264 Summary: The SoftMPEG4 component in libstagefright in mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, 6.x before 2016-10-01, and 7.0 before 2016-10-01 allows attackers to gain privileges via a crafted application, aka internal bug 30033990. Commit Message: SoftMPEG4: Check the buffer size before writing the reference frame. Also prevent overflow in SoftMPEG4 and division by zero in SoftMPEG4Encoder. Bug: 30033990 Change-Id: I7701f5fc54c2670587d122330e5dc851f64ed3c2 (cherry picked from commit 695123195034402ca76169b195069c28c30342d3)
High
6,970
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static sent_status_t send_data_to_app(int fd, BT_HDR *p_buf) { if (p_buf->len == 0) return SENT_ALL; ssize_t sent = send(fd, p_buf->data + p_buf->offset, p_buf->len, MSG_DONTWAIT); if (sent == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return SENT_NONE; LOG_ERROR("%s error writing RFCOMM data back to app: %s", __func__, strerror(errno)); return SENT_FAILED; } if (sent == 0) return SENT_FAILED; if (sent == p_buf->len) return SENT_ALL; p_buf->offset += sent; p_buf->len -= sent; return SENT_PARTIAL; } Vulnerability Type: DoS CWE ID: CWE-284 Summary: Bluetooth in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-08-01 allows attackers to cause a denial of service (loss of Bluetooth 911 functionality) via a crafted application that sends a signal to a Bluetooth process, aka internal bug 28885210. 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
Medium
7,142
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; unsigned char* buffer=NULL; unsigned char* samplebuffer=NULL; tsize_t bufferoffset=0; tsize_t samplebufferoffset=0; tsize_t read=0; tstrip_t i=0; tstrip_t j=0; tstrip_t stripcount=0; tsize_t stripsize=0; tsize_t sepstripcount=0; tsize_t sepstripsize=0; #ifdef OJPEG_SUPPORT toff_t inputoffset=0; uint16 h_samp=1; uint16 v_samp=1; uint16 ri=1; uint32 rows=0; #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT unsigned char* jpt; float* xfloatp; uint64* sbc; unsigned char* stripbuffer; tsize_t striplength=0; uint32 max_striplength=0; #endif /* ifdef JPEG_SUPPORT */ /* Fail if prior error (in particular, can't trust tiff_datasize) */ if (t2p->t2p_error != T2P_ERR_OK) return(0); if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if (buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for " "t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ /* * make sure is lsb-to-msb * bit-endianness fill order */ TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef CCITT_SUPPORT */ #ifdef ZIP_SUPPORT if (t2p->pdf_compression == T2P_COMPRESS_ZIP) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB) { TIFFReverseBits(buffer, t2p->tiff_datasize); } t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif /* ifdef ZIP_SUPPORT */ #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG) { if(t2p->tiff_dataoffset != 0) { buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer == NULL) { TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if(t2p->pdf_ojpegiflength==0){ inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); t2pReadFile(input, (tdata_t) buffer, t2p->tiff_datasize); t2pSeekFile(input, inputoffset, SEEK_SET); t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } else { inputoffset=t2pSeekFile(input, 0, SEEK_CUR); t2pSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); bufferoffset = t2pReadFile(input, (tdata_t) buffer, t2p->pdf_ojpegiflength); t2p->pdf_ojpegiflength = 0; t2pSeekFile(input, inputoffset, SEEK_SET); TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp); buffer[bufferoffset++]= 0xff; buffer[bufferoffset++]= 0xdd; buffer[bufferoffset++]= 0x00; buffer[bufferoffset++]= 0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; buffer[bufferoffset++]= (ri>>8) & 0xff; buffer[bufferoffset++]= ri & 0xff; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0 ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } } else { if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); bufferoffset=t2p->pdf_ojpegdatalength; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } if( ! ( (buffer[bufferoffset-1]==0xd9) && (buffer[bufferoffset-2]==0xff) ) ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; } t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); #if 0 /* This hunk of code removed code is clearly mis-placed and we are not sure where it should be (if anywhere) */ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with no JPEG File Interchange offset", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); #endif } } #endif /* ifdef OJPEG_SUPPORT */ #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG) { uint32 count = 0; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); if (TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) { if(count > 4) { _TIFFmemcpy(buffer, jpt, count); bufferoffset += count - 2; } } stripcount=TIFFNumberOfStrips(input); TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); for(i=0;i<stripcount;i++){ if(sbc[i]>max_striplength) max_striplength=sbc[i]; } stripbuffer = (unsigned char*) _TIFFmalloc(max_striplength); if(stripbuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", max_striplength, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } for(i=0;i<stripcount;i++){ striplength=TIFFReadRawStrip(input, i, (tdata_t) stripbuffer, -1); if(!t2p_process_jpeg_strip( stripbuffer, &striplength, buffer, &bufferoffset, i, t2p->tiff_length)){ TIFFError(TIFF2PDF_MODULE, "Can't process JPEG data in input file %s", TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; t2pWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(stripbuffer); _TIFFfree(buffer); return(bufferoffset); } #endif /* ifdef JPEG_SUPPORT */ (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } } else { if(t2p->pdf_sample & T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ sepstripsize=TIFFStripSize(input); sepstripcount=TIFFNumberOfStrips(input); stripsize=sepstripsize*t2p->tiff_samplesperpixel; stripcount=sepstripcount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); samplebuffer = (unsigned char*) _TIFFmalloc(stripsize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } for(i=0;i<stripcount;i++){ samplebufferoffset=0; for(j=0;j<t2p->tiff_samplesperpixel;j++){ read = TIFFReadEncodedStrip(input, i + j*stripcount, (tdata_t) &(samplebuffer[samplebufferoffset]), TIFFmin(sepstripsize, stripsize - samplebufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i + j*stripcount, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; } _TIFFfree(samplebuffer); goto dataready; } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } memset(buffer, 0, t2p->tiff_datasize); stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], TIFFmin(stripsize, t2p->tiff_datasize - bufferoffset)); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t) buffer, t2p->tiff_datasize * t2p->tiff_samplesperpixel); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; t2p->tiff_datasize *= t2p->tiff_samplesperpixel; } t2p_sample_realize_palette(t2p, buffer); } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length*4); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_readwrite_pdf_image, %s", (unsigned long) t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; } if(!TIFFReadRGBAImageOriented( input, t2p->tiff_width, t2p->tiff_length, (uint32*)buffer, ORIENTATION_TOPLEFT, 0)){ TIFFError(TIFF2PDF_MODULE, "Can't use TIFFReadRGBAImageOriented to extract RGB image from %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } t2p->tiff_datasize=t2p_sample_abgr_to_rgb( (tdata_t) buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } } dataready: t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); TIFFSetField(output, TIFFTAG_IMAGEWIDTH, t2p->tiff_width); TIFFSetField(output, TIFFTAG_IMAGELENGTH, t2p->tiff_length); TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_length); TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif /* ifdef CCITT_SUPPORT */ #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR) { uint16 hor = 0, ver = 0; if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver) !=0 ) { if(hor != 0 && ver != 0){ TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } if(TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG)==0){ TIFFError(TIFF2PDF_MODULE, "Unable to use JPEG compression for input %s and output %s", TIFFFileName(input), TIFFFileName(output)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif /* ifdef JPEG_SUPPORT */ #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif /* ifdef ZIP_SUPPORT */ default: break; } t2p_enable(output); t2p->outputwritten = 0; #ifdef JPEG_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_JPEG && t2p->tiff_photometric == PHOTOMETRIC_YCBCR){ bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, stripsize * stripcount); } else #endif /* ifdef JPEG_SUPPORT */ { bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, t2p->tiff_datasize); } if (buffer != NULL) { _TIFFfree(buffer); buffer=NULL; } if (bufferoffset == (tsize_t)-1) { TIFFError(TIFF2PDF_MODULE, "Error writing encoded strip to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written = t2p->outputwritten; return(written); } Vulnerability Type: CWE ID: CWE-787 Summary: tools/tiffcrop.c in libtiff 4.0.6 has out-of-bounds write vulnerabilities in buffers. Reported as MSVR 35093, MSVR 35096, and MSVR 35097. Commit Message: * tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities in heap or stack allocated buffers. Reported as MSVR 35093, MSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in heap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR 35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities in heap allocated buffers. Reported as MSVR 35094. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1() that didn't reset the tif_rawcc and tif_rawcp members. I'm not completely sure if that could happen in practice outside of the odd behaviour of t2p_seekproc() of tiff2pdf). The report points that a better fix could be to check the return value of TIFFFlushData1() in places where it isn't done currently, but it seems this patch is enough. Reported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan & Suha Can from the MSRC Vulnerabilities & Mitigations team.
High
26,051
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: PHP_FUNCTION(mcrypt_cfb) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_long_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "cfb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC); } Vulnerability Type: DoS Overflow CWE ID: CWE-190 Summary: Multiple integer overflows in mcrypt.c in the mcrypt extension in PHP before 5.5.37, 5.6.x before 5.6.23, and 7.x before 7.0.8 allow remote attackers to cause a denial of service (heap-based buffer overflow and application crash) or possibly have unspecified other impact via a crafted length value, related to the (1) mcrypt_generic and (2) mdecrypt_generic functions. Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
High
5,754
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: virtual const ImePropertyList& current_ime_properties() const { return current_ime_properties_; } Vulnerability Type: DoS CWE ID: CWE-399 Summary: Google Chrome before 13.0.782.107 does not properly handle nested functions in PDF documents, which allows remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via a crafted document. 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
High
15,855
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static void testInspectorManualAttachDetach(CustomInspectorTest* test, gconstpointer) { test->showInWindowAndWaitUntilMapped(GTK_WINDOW_TOPLEVEL); test->resizeView(200, 200); test->loadHtml("<html><body><p>WebKitGTK+ Inspector test</p></body></html>", 0); test->waitUntilLoadFinished(); test->showAndWaitUntilFinished(false); test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(webkit_web_inspector_get_web_view(test->m_inspector))); g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); Vector<InspectorTest::InspectorEvents>& events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::BringToFront); g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); test->m_events.clear(); test->resizeViewAndAttach(); g_assert(webkit_web_inspector_is_attached(test->m_inspector)); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::Attach); test->m_events.clear(); test->detachAndWaitUntilWindowOpened(); g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::Detach); g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); test->m_events.clear(); test->resizeViewAndAttach(); g_assert(webkit_web_inspector_is_attached(test->m_inspector)); test->m_events.clear(); test->closeAndWaitUntilClosed(); events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::Detach); g_assert_cmpint(events[1], ==, InspectorTest::Closed); test->m_events.clear(); } Vulnerability Type: DoS CWE ID: CWE-399 Summary: Use-after-free vulnerability in the PDF functionality in Google Chrome before 19.0.1084.46 allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors involving a malformed name for the font encoding. Commit Message: [GTK] Inspector should set a default attached height before being attached https://bugs.webkit.org/show_bug.cgi?id=90767 Reviewed by Xan Lopez. We are currently using the minimum attached height in WebKitWebViewBase as the default height for the inspector when attached. It would be easier for WebKitWebViewBase and embedders implementing attach() if the inspector already had an attached height set when it's being attached. * UIProcess/API/gtk/WebKitWebViewBase.cpp: (webkitWebViewBaseContainerAdd): Don't initialize inspectorViewHeight. (webkitWebViewBaseSetInspectorViewHeight): Allow to set the inspector view height before having an inpector view, but only queue a resize when the view already has an inspector view. * UIProcess/API/gtk/tests/TestInspector.cpp: (testInspectorDefault): (testInspectorManualAttachDetach): * UIProcess/gtk/WebInspectorProxyGtk.cpp: (WebKit::WebInspectorProxy::platformAttach): Set the default attached height before attach the inspector view. git-svn-id: svn://svn.chromium.org/blink/trunk@124479 bbb929c8-8fbe-4397-9dbb-9b2b20218538
High
24,678
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: int cdc_parse_cdc_header(struct usb_cdc_parsed_header *hdr, struct usb_interface *intf, u8 *buffer, int buflen) { /* duplicates are ignored */ struct usb_cdc_union_desc *union_header = NULL; /* duplicates are not tolerated */ struct usb_cdc_header_desc *header = NULL; struct usb_cdc_ether_desc *ether = NULL; struct usb_cdc_mdlm_detail_desc *detail = NULL; struct usb_cdc_mdlm_desc *desc = NULL; unsigned int elength; int cnt = 0; memset(hdr, 0x00, sizeof(struct usb_cdc_parsed_header)); hdr->phonet_magic_present = false; while (buflen > 0) { elength = buffer[0]; if (!elength) { dev_err(&intf->dev, "skipping garbage byte\n"); elength = 1; goto next_desc; } if (buffer[1] != USB_DT_CS_INTERFACE) { dev_err(&intf->dev, "skipping garbage\n"); goto next_desc; } switch (buffer[2]) { case USB_CDC_UNION_TYPE: /* we've found it */ if (elength < sizeof(struct usb_cdc_union_desc)) goto next_desc; if (union_header) { dev_err(&intf->dev, "More than one union descriptor, skipping ...\n"); goto next_desc; } union_header = (struct usb_cdc_union_desc *)buffer; break; case USB_CDC_COUNTRY_TYPE: if (elength < sizeof(struct usb_cdc_country_functional_desc)) goto next_desc; hdr->usb_cdc_country_functional_desc = (struct usb_cdc_country_functional_desc *)buffer; break; case USB_CDC_HEADER_TYPE: if (elength != sizeof(struct usb_cdc_header_desc)) goto next_desc; if (header) return -EINVAL; header = (struct usb_cdc_header_desc *)buffer; break; case USB_CDC_ACM_TYPE: if (elength < sizeof(struct usb_cdc_acm_descriptor)) goto next_desc; hdr->usb_cdc_acm_descriptor = (struct usb_cdc_acm_descriptor *)buffer; break; case USB_CDC_ETHERNET_TYPE: if (elength != sizeof(struct usb_cdc_ether_desc)) goto next_desc; if (ether) return -EINVAL; ether = (struct usb_cdc_ether_desc *)buffer; break; case USB_CDC_CALL_MANAGEMENT_TYPE: if (elength < sizeof(struct usb_cdc_call_mgmt_descriptor)) goto next_desc; hdr->usb_cdc_call_mgmt_descriptor = (struct usb_cdc_call_mgmt_descriptor *)buffer; break; case USB_CDC_DMM_TYPE: if (elength < sizeof(struct usb_cdc_dmm_desc)) goto next_desc; hdr->usb_cdc_dmm_desc = (struct usb_cdc_dmm_desc *)buffer; break; case USB_CDC_MDLM_TYPE: if (elength < sizeof(struct usb_cdc_mdlm_desc *)) goto next_desc; if (desc) return -EINVAL; desc = (struct usb_cdc_mdlm_desc *)buffer; break; case USB_CDC_MDLM_DETAIL_TYPE: if (elength < sizeof(struct usb_cdc_mdlm_detail_desc *)) goto next_desc; if (detail) return -EINVAL; detail = (struct usb_cdc_mdlm_detail_desc *)buffer; break; case USB_CDC_NCM_TYPE: if (elength < sizeof(struct usb_cdc_ncm_desc)) goto next_desc; hdr->usb_cdc_ncm_desc = (struct usb_cdc_ncm_desc *)buffer; break; case USB_CDC_MBIM_TYPE: if (elength < sizeof(struct usb_cdc_mbim_desc)) goto next_desc; hdr->usb_cdc_mbim_desc = (struct usb_cdc_mbim_desc *)buffer; break; case USB_CDC_MBIM_EXTENDED_TYPE: if (elength < sizeof(struct usb_cdc_mbim_extended_desc)) break; hdr->usb_cdc_mbim_extended_desc = (struct usb_cdc_mbim_extended_desc *)buffer; break; case CDC_PHONET_MAGIC_NUMBER: hdr->phonet_magic_present = true; break; default: /* * there are LOTS more CDC descriptors that * could legitimately be found here. */ dev_dbg(&intf->dev, "Ignoring descriptor: type %02x, length %ud\n", buffer[2], elength); goto next_desc; } cnt++; next_desc: buflen -= elength; buffer += elength; } hdr->usb_cdc_union_desc = union_header; hdr->usb_cdc_header_desc = header; hdr->usb_cdc_mdlm_detail_desc = detail; hdr->usb_cdc_mdlm_desc = desc; hdr->usb_cdc_ether_desc = ether; return cnt; } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: The cdc_parse_cdc_header function in drivers/usb/core/message.c in the Linux kernel before 4.13.6 allows local users to cause a denial of service (out-of-bounds read and system crash) or possibly have unspecified other impact via a crafted USB device. Commit Message: USB: core: harden cdc_parse_cdc_header Andrey Konovalov reported a possible out-of-bounds problem for the cdc_parse_cdc_header function. He writes: It looks like cdc_parse_cdc_header() doesn't validate buflen before accessing buffer[1], buffer[2] and so on. The only check present is while (buflen > 0). So fix this issue up by properly validating the buffer length matches what the descriptor says it is. Reported-by: Andrey Konovalov <[email protected]> Tested-by: Andrey Konovalov <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]>
High
19,615
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void ChromeMockRenderThread::OnMsgOpenChannelToExtension( int routing_id, const std::string& source_extension_id, const std::string& target_extension_id, const std::string& channel_name, int* port_id) { *port_id = 0; } Vulnerability Type: +Info CWE ID: CWE-200 Summary: The IPC implementation in Google Chrome before 22.0.1229.79 allows attackers to obtain potentially sensitive information about memory addresses via unspecified vectors. 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
Medium
23,461
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: error::Error GLES2DecoderPassthroughImpl::DoBeginQueryEXT( GLenum target, GLuint id, int32_t sync_shm_id, uint32_t sync_shm_offset) { GLuint service_id = GetQueryServiceID(id, &query_id_map_); QueryInfo* query_info = &query_info_map_[service_id]; scoped_refptr<gpu::Buffer> buffer = GetSharedMemoryBuffer(sync_shm_id); if (!buffer) return error::kInvalidArguments; QuerySync* sync = static_cast<QuerySync*>( buffer->GetDataAddress(sync_shm_offset, sizeof(QuerySync))); if (!sync) return error::kOutOfBounds; if (IsEmulatedQueryTarget(target)) { if (active_queries_.find(target) != active_queries_.end()) { InsertError(GL_INVALID_OPERATION, "Query already active on target."); return error::kNoError; } if (id == 0) { InsertError(GL_INVALID_OPERATION, "Query id is 0."); return error::kNoError; } if (query_info->type != GL_NONE && query_info->type != target) { InsertError(GL_INVALID_OPERATION, "Query type does not match the target."); return error::kNoError; } } else { CheckErrorCallbackState(); api()->glBeginQueryFn(target, service_id); if (CheckErrorCallbackState()) { return error::kNoError; } } query_info->type = target; RemovePendingQuery(service_id); ActiveQuery query; query.service_id = service_id; query.shm = std::move(buffer); query.sync = sync; active_queries_[target] = std::move(query); return error::kNoError; } Vulnerability Type: CWE ID: CWE-416 Summary: A heap use after free in V8 in Google Chrome prior to 55.0.2883.75 for Mac, Windows and Linux, and 55.0.2883.84 for Android allowed a remote attacker to potentially exploit heap corruption via a crafted HTML page. Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568}
Medium
13,399
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) { int ret; if (input == NULL) return(-1); if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Pushing input %d : %.30s\n", ctxt->inputNr+1, input->cur); } ret = inputPush(ctxt, input); GROW; return(ret); } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: parser.c in libxml2 before 2.9.0, as used in Google Chrome before 28.0.1500.71 and other products, allows remote attackers to cause a denial of service (out-of-bounds read) via a document that ends abruptly, related to the lack of certain checks for the XML_PARSER_EOF state. Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
Medium
17,541
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: compare_two_images(Image *a, Image *b, int via_linear, png_const_colorp background) { ptrdiff_t stridea = a->stride; ptrdiff_t strideb = b->stride; png_const_bytep rowa = a->buffer+16; png_const_bytep rowb = b->buffer+16; const png_uint_32 width = a->image.width; const png_uint_32 height = a->image.height; const png_uint_32 formata = a->image.format; const png_uint_32 formatb = b->image.format; const unsigned int a_sample = PNG_IMAGE_SAMPLE_SIZE(formata); const unsigned int b_sample = PNG_IMAGE_SAMPLE_SIZE(formatb); int alpha_added, alpha_removed; int bchannels; int btoa[4]; png_uint_32 y; Transform tr; /* This should never happen: */ if (width != b->image.width || height != b->image.height) return logerror(a, a->file_name, ": width x height changed: ", b->file_name); /* Set up the background and the transform */ transform_from_formats(&tr, a, b, background, via_linear); /* Find the first row and inter-row space. */ if (!(formata & PNG_FORMAT_FLAG_COLORMAP) && (formata & PNG_FORMAT_FLAG_LINEAR)) stridea *= 2; if (!(formatb & PNG_FORMAT_FLAG_COLORMAP) && (formatb & PNG_FORMAT_FLAG_LINEAR)) strideb *= 2; if (stridea < 0) rowa += (height-1) * (-stridea); if (strideb < 0) rowb += (height-1) * (-strideb); /* First shortcut the two colormap case by comparing the image data; if it * matches then we expect the colormaps to match, although this is not * absolutely necessary for an image match. If the colormaps fail to match * then there is a problem in libpng. */ if (formata & formatb & PNG_FORMAT_FLAG_COLORMAP) { /* Only check colormap entries that actually exist; */ png_const_bytep ppa, ppb; int match; png_byte in_use[256], amax = 0, bmax = 0; memset(in_use, 0, sizeof in_use); ppa = rowa; ppb = rowb; /* Do this the slow way to accumulate the 'in_use' flags, don't break out * of the loop until the end; this validates the color-mapped data to * ensure all pixels are valid color-map indexes. */ for (y=0, match=1; y<height && match; ++y, ppa += stridea, ppb += strideb) { png_uint_32 x; for (x=0; x<width; ++x) { png_byte bval = ppb[x]; png_byte aval = ppa[x]; if (bval > bmax) bmax = bval; if (bval != aval) match = 0; in_use[aval] = 1; if (aval > amax) amax = aval; } } /* If the buffers match then the colormaps must too. */ if (match) { /* Do the color-maps match, entry by entry? Only check the 'in_use' * entries. An error here should be logged as a color-map error. */ png_const_bytep a_cmap = (png_const_bytep)a->colormap; png_const_bytep b_cmap = (png_const_bytep)b->colormap; int result = 1; /* match by default */ /* This is used in logpixel to get the error message correct. */ tr.is_palette = 1; for (y=0; y<256; ++y, a_cmap += a_sample, b_cmap += b_sample) if (in_use[y]) { /* The colormap entries should be valid, but because libpng doesn't * do any checking at present the original image may contain invalid * pixel values. These cause an error here (at present) unless * accumulating errors in which case the program just ignores them. */ if (y >= a->image.colormap_entries) { if ((a->opts & ACCUMULATE) == 0) { char pindex[9]; sprintf(pindex, "%lu[%lu]", (unsigned long)y, (unsigned long)a->image.colormap_entries); logerror(a, a->file_name, ": bad pixel index: ", pindex); } result = 0; } else if (y >= b->image.colormap_entries) { if ((a->opts & ACCUMULATE) == 0) { char pindex[9]; sprintf(pindex, "%lu[%lu]", (unsigned long)y, (unsigned long)b->image.colormap_entries); logerror(b, b->file_name, ": bad pixel index: ", pindex); } result = 0; } /* All the mismatches are logged here; there can only be 256! */ else if (!cmppixel(&tr, a_cmap, b_cmap, 0, y)) result = 0; } /* If reqested copy the error values back from the Transform. */ if (a->opts & ACCUMULATE) { tr.error_ptr[0] = tr.error[0]; tr.error_ptr[1] = tr.error[1]; tr.error_ptr[2] = tr.error[2]; tr.error_ptr[3] = tr.error[3]; result = 1; /* force a continue */ } return result; } /* else the image buffers don't match pixel-wise so compare sample values * instead, but first validate that the pixel indexes are in range (but * only if not accumulating, when the error is ignored.) */ else if ((a->opts & ACCUMULATE) == 0) { /* Check the original image first, * TODO: deal with input images with bad pixel values? */ if (amax >= a->image.colormap_entries) { char pindex[9]; sprintf(pindex, "%d[%lu]", amax, (unsigned long)a->image.colormap_entries); return logerror(a, a->file_name, ": bad pixel index: ", pindex); } else if (bmax >= b->image.colormap_entries) { char pindex[9]; sprintf(pindex, "%d[%lu]", bmax, (unsigned long)b->image.colormap_entries); return logerror(b, b->file_name, ": bad pixel index: ", pindex); } } } /* We can directly compare pixel values without the need to use the read * or transform support (i.e. a memory compare) if: * * 1) The bit depth has not changed. * 2) RGB to grayscale has not been done (the reverse is ok; we just compare * the three RGB values to the original grayscale.) * 3) An alpha channel has not been removed from an 8-bit format, or the * 8-bit alpha value of the pixel was 255 (opaque). * * If an alpha channel has been *added* then it must have the relevant opaque * value (255 or 65535). * * The fist two the tests (in the order given above) (using the boolean * equivalence !a && !b == !(a || b)) */ if (!(((formata ^ formatb) & PNG_FORMAT_FLAG_LINEAR) | (formata & (formatb ^ PNG_FORMAT_FLAG_COLOR) & PNG_FORMAT_FLAG_COLOR))) { /* Was an alpha channel changed? */ const png_uint_32 alpha_changed = (formata ^ formatb) & PNG_FORMAT_FLAG_ALPHA; /* Was an alpha channel removed? (The third test.) If so the direct * comparison is only possible if the input alpha is opaque. */ alpha_removed = (formata & alpha_changed) != 0; /* Was an alpha channel added? */ alpha_added = (formatb & alpha_changed) != 0; /* The channels may have been moved between input and output, this finds * out how, recording the result in the btoa array, which says where in * 'a' to find each channel of 'b'. If alpha was added then btoa[alpha] * ends up as 4 (and is not used.) */ { int i; png_byte aloc[4]; png_byte bloc[4]; /* The following are used only if the formats match, except that * 'bchannels' is a flag for matching formats. btoa[x] says, for each * channel in b, where to find the corresponding value in a, for the * bchannels. achannels may be different for a gray to rgb transform * (a will be 1 or 2, b will be 3 or 4 channels.) */ (void)component_loc(aloc, formata); bchannels = component_loc(bloc, formatb); /* Hence the btoa array. */ for (i=0; i<4; ++i) if (bloc[i] < 4) btoa[bloc[i]] = aloc[i]; /* may be '4' for alpha */ if (alpha_added) alpha_added = bloc[0]; /* location of alpha channel in image b */ else alpha_added = 4; /* Won't match an image b channel */ if (alpha_removed) alpha_removed = aloc[0]; /* location of alpha channel in image a */ else alpha_removed = 4; } } else { /* Direct compare is not possible, cancel out all the corresponding local * variables. */ bchannels = 0; alpha_removed = alpha_added = 4; btoa[3] = btoa[2] = btoa[1] = btoa[0] = 4; /* 4 == not present */ } for (y=0; y<height; ++y, rowa += stridea, rowb += strideb) { png_const_bytep ppa, ppb; png_uint_32 x; for (x=0, ppa=rowa, ppb=rowb; x<width; ++x) { png_const_bytep psa, psb; if (formata & PNG_FORMAT_FLAG_COLORMAP) psa = (png_const_bytep)a->colormap + a_sample * *ppa++; else psa = ppa, ppa += a_sample; if (formatb & PNG_FORMAT_FLAG_COLORMAP) psb = (png_const_bytep)b->colormap + b_sample * *ppb++; else psb = ppb, ppb += b_sample; /* Do the fast test if possible. */ if (bchannels) { /* Check each 'b' channel against either the corresponding 'a' * channel or the opaque alpha value, as appropriate. If * alpha_removed value is set (not 4) then also do this only if the * 'a' alpha channel (alpha_removed) is opaque; only relevant for * the 8-bit case. */ if (formatb & PNG_FORMAT_FLAG_LINEAR) /* 16-bit checks */ { png_const_uint_16p pua = aligncastconst(png_const_uint_16p, psa); png_const_uint_16p pub = aligncastconst(png_const_uint_16p, psb); switch (bchannels) { case 4: if (pua[btoa[3]] != pub[3]) break; case 3: if (pua[btoa[2]] != pub[2]) break; case 2: if (pua[btoa[1]] != pub[1]) break; case 1: if (pua[btoa[0]] != pub[0]) break; if (alpha_added != 4 && pub[alpha_added] != 65535) break; continue; /* x loop */ default: break; /* impossible */ } } else if (alpha_removed == 4 || psa[alpha_removed] == 255) { switch (bchannels) { case 4: if (psa[btoa[3]] != psb[3]) break; case 3: if (psa[btoa[2]] != psb[2]) break; case 2: if (psa[btoa[1]] != psb[1]) break; case 1: if (psa[btoa[0]] != psb[0]) break; if (alpha_added != 4 && psb[alpha_added] != 255) break; continue; /* x loop */ default: break; /* impossible */ } } } /* If we get to here the fast match failed; do the slow match for this * pixel. */ if (!cmppixel(&tr, psa, psb, x, y) && (a->opts & KEEP_GOING) == 0) return 0; /* error case */ } } /* If reqested copy the error values back from the Transform. */ if (a->opts & ACCUMULATE) { tr.error_ptr[0] = tr.error[0]; tr.error_ptr[1] = tr.error[1]; tr.error_ptr[2] = tr.error[2]; tr.error_ptr[3] = tr.error[3]; } return 1; } Vulnerability Type: +Priv CWE ID: Summary: Unspecified vulnerability in libpng before 1.6.20, as used in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-07-01, allows attackers to gain privileges via a crafted application, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 23265085. Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
High
11,768
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: xsltFreeTemplateHashes(xsltStylesheetPtr style) { if (style->templatesHash != NULL) xmlHashFree((xmlHashTablePtr) style->templatesHash, (xmlHashDeallocator) xsltFreeCompMatchList); if (style->rootMatch != NULL) xsltFreeCompMatchList(style->rootMatch); if (style->keyMatch != NULL) xsltFreeCompMatchList(style->keyMatch); if (style->elemMatch != NULL) xsltFreeCompMatchList(style->elemMatch); if (style->attrMatch != NULL) xsltFreeCompMatchList(style->attrMatch); if (style->parentMatch != NULL) xsltFreeCompMatchList(style->parentMatch); if (style->textMatch != NULL) xsltFreeCompMatchList(style->textMatch); if (style->piMatch != NULL) xsltFreeCompMatchList(style->piMatch); if (style->commentMatch != NULL) xsltFreeCompMatchList(style->commentMatch); } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: numbers.c in libxslt before 1.1.29, as used in Google Chrome before 51.0.2704.63, mishandles namespace nodes, which allows remote attackers to cause a denial of service (out-of-bounds heap memory access) or possibly have unspecified other impact via a crafted document. Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338}
Medium
10,905
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: ExtensionFunction* ExtensionFunctionDispatcher::CreateExtensionFunction( const ExtensionHostMsg_Request_Params& params, const Extension* extension, int requesting_process_id, const extensions::ProcessMap& process_map, extensions::ExtensionAPI* api, void* profile, IPC::Sender* ipc_sender, RenderViewHost* render_view_host, int routing_id) { if (!extension) { LOG(ERROR) << "Specified extension does not exist."; SendAccessDenied(ipc_sender, routing_id, params.request_id); return NULL; } if (api->IsPrivileged(params.name) && !process_map.Contains(extension->id(), requesting_process_id)) { LOG(ERROR) << "Extension API called from incorrect process " << requesting_process_id << " from URL " << params.source_url.spec(); SendAccessDenied(ipc_sender, routing_id, params.request_id); return NULL; } ExtensionFunction* function = ExtensionFunctionRegistry::GetInstance()->NewFunction(params.name); function->SetArgs(&params.arguments); function->set_source_url(params.source_url); function->set_request_id(params.request_id); function->set_has_callback(params.has_callback); function->set_user_gesture(params.user_gesture); function->set_extension(extension); function->set_profile_id(profile); UIThreadExtensionFunction* function_ui = function->AsUIThreadExtensionFunction(); if (function_ui) { function_ui->SetRenderViewHost(render_view_host); } return function; } Vulnerability Type: CWE ID: CWE-264 Summary: Google Chrome before 25.0.1364.97 on Windows and Linux, and before 25.0.1364.99 on Mac OS X, does not properly restrict API privileges during interaction with the Chrome Web Store, which has unspecified impact and attack vectors. Commit Message: Tighten restrictions on hosted apps calling extension APIs Only allow component apps to make any API calls, and for them only allow the namespaces they explicitly have permission for (plus chrome.test - I need to see if I can rework some WebStore tests to remove even this). BUG=172369 Review URL: https://chromiumcodereview.appspot.com/12095095 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180426 0039d316-1c4b-4281-b951-d872f2087c98
High
27,365
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: DevToolsUI::DevToolsUI(content::WebUI* web_ui) : WebUIController(web_ui), bindings_(web_ui->GetWebContents()) { web_ui->SetBindings(0); Profile* profile = Profile::FromWebUI(web_ui); content::URLDataSource::Add( profile, new DevToolsDataSource(profile->GetRequestContext())); } Vulnerability Type: +Info CWE ID: CWE-200 Summary: Google Chrome prior to 55.0.2883.75 for Mac, Windows and Linux, and 55.0.2883.84 for Android insufficiently sanitized DevTools URLs, which allowed a remote attacker to read local files via a crafted HTML page. Commit Message: [DevTools] Move sanitize url to devtools_ui.cc. Compatibility script is not reliable enough. BUG=653134 Review-Url: https://codereview.chromium.org/2403633002 Cr-Commit-Position: refs/heads/master@{#425814}
Medium
9,915
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static void SetUpTestCase() { source_data_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, kDataBlockSize)); reference_data_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, kDataBufferSize)); } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: libvpx in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49H, and 6.0 before 2016-03-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to libwebm/mkvparser.cpp and other files, aka internal bug 23452792. 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
High
14,754
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static void kvm_unpin_pages(struct kvm *kvm, pfn_t pfn, unsigned long npages) { unsigned long i; for (i = 0; i < npages; ++i) kvm_release_pfn_clean(pfn + i); } Vulnerability Type: DoS Mem. Corr. CWE ID: CWE-189 Summary: The kvm_iommu_map_pages function in virt/kvm/iommu.c in the Linux kernel through 3.16.1 miscalculates the number of pages during the handling of a mapping failure, which allows guest OS users to (1) cause a denial of service (host OS memory corruption) or possibly have unspecified other impact by triggering a large gfn value or (2) cause a denial of service (host OS memory consumption) by triggering a small gfn value that leads to permanently pinned pages. Commit Message: kvm: iommu: fix the third parameter of kvm_iommu_put_pages (CVE-2014-3601) The third parameter of kvm_iommu_put_pages is wrong, It should be 'gfn - slot->base_gfn'. By making gfn very large, malicious guest or userspace can cause kvm to go to this error path, and subsequently to pass a huge value as size. Alternatively if gfn is small, then pages would be pinned but never unpinned, causing host memory leak and local DOS. Passing a reasonable but large value could be the most dangerous case, because it would unpin a page that should have stayed pinned, and thus allow the device to DMA into arbitrary memory. However, this cannot happen because of the condition that can trigger the error: - out of memory (where you can't allocate even a single page) should not be possible for the attacker to trigger - when exceeding the iommu's address space, guest pages after gfn will also exceed the iommu's address space, and inside kvm_iommu_put_pages() the iommu_iova_to_phys() will fail. The page thus would not be unpinned at all. Reported-by: Jack Morgenstein <[email protected]> Cc: [email protected] Signed-off-by: Michael S. Tsirkin <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>
Medium
16,646
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static void worker_process(int fd, debugger_request_t& request) { std::string tombstone_path; int tombstone_fd = -1; switch (request.action) { case DEBUGGER_ACTION_DUMP_TOMBSTONE: case DEBUGGER_ACTION_CRASH: tombstone_fd = open_tombstone(&tombstone_path); if (tombstone_fd == -1) { ALOGE("debuggerd: failed to open tombstone file: %s\n", strerror(errno)); exit(1); } break; case DEBUGGER_ACTION_DUMP_BACKTRACE: break; default: ALOGE("debuggerd: unexpected request action: %d", request.action); exit(1); } if (ptrace(PTRACE_ATTACH, request.tid, 0, 0) != 0) { ALOGE("debuggerd: ptrace attach failed: %s", strerror(errno)); exit(1); } bool attach_gdb = should_attach_gdb(request); if (attach_gdb) { if (init_getevent() != 0) { ALOGE("debuggerd: failed to initialize input device, not waiting for gdb"); attach_gdb = false; } } std::set<pid_t> siblings; if (!attach_gdb) { ptrace_siblings(request.pid, request.tid, siblings); } std::unique_ptr<BacktraceMap> backtrace_map(BacktraceMap::Create(request.pid)); int amfd = -1; std::unique_ptr<std::string> amfd_data; if (request.action == DEBUGGER_ACTION_CRASH) { amfd = activity_manager_connect(); amfd_data.reset(new std::string); } bool succeeded = false; if (!drop_privileges()) { ALOGE("debuggerd: failed to drop privileges, exiting"); _exit(1); } int crash_signal = SIGKILL; succeeded = perform_dump(request, fd, tombstone_fd, backtrace_map.get(), siblings, &crash_signal, amfd_data.get()); if (succeeded) { if (request.action == DEBUGGER_ACTION_DUMP_TOMBSTONE) { if (!tombstone_path.empty()) { android::base::WriteFully(fd, tombstone_path.c_str(), tombstone_path.length()); } } } if (attach_gdb) { if (!send_signal(request.pid, 0, SIGSTOP)) { ALOGE("debuggerd: failed to stop process for gdb attach: %s", strerror(errno)); attach_gdb = false; } } if (!attach_gdb) { activity_manager_write(request.pid, crash_signal, amfd, *amfd_data.get()); } if (ptrace(PTRACE_DETACH, request.tid, 0, 0) != 0) { ALOGE("debuggerd: ptrace detach from %d failed: %s", request.tid, strerror(errno)); } for (pid_t sibling : siblings) { ptrace(PTRACE_DETACH, sibling, 0, 0); } if (!attach_gdb && request.action == DEBUGGER_ACTION_CRASH) { if (!send_signal(request.pid, request.tid, crash_signal)) { ALOGE("debuggerd: failed to kill process %d: %s", request.pid, strerror(errno)); } } if (attach_gdb) { wait_for_user_action(request); activity_manager_write(request.pid, crash_signal, amfd, *amfd_data.get()); if (!send_signal(request.pid, 0, SIGCONT)) { ALOGE("debuggerd: failed to resume process %d: %s", request.pid, strerror(errno)); } uninit_getevent(); } close(amfd); exit(!succeeded); } Vulnerability Type: +Priv CWE ID: CWE-264 Summary: debuggerd/debuggerd.cpp in Debuggerd in Android 5.0.x before 5.0.2, 5.1.x before 5.1.1, 6.x before 2016-09-01, and 7.0 before 2016-09-01 mishandles the interaction between PTRACE_ATTACH operations and thread exits, which allows attackers to gain privileges via a crafted application, aka internal bug 29555636. Commit Message: debuggerd: verify that traced threads belong to the right process. Fix two races in debuggerd's PTRACE_ATTACH logic: 1. The target thread in a crash dump request could exit between the /proc/<pid>/task/<tid> check and the PTRACE_ATTACH. 2. Sibling threads could exit between listing /proc/<pid>/task and the PTRACE_ATTACH. Bug: http://b/29555636 Change-Id: I4dfe1ea30e2c211d2389321bd66e3684dd757591
High
9,154
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if ((id == 0x000003ed) && (PSDQuantum(count) < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- (PSDQuantum(count)+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } Vulnerability Type: DoS CWE ID: CWE-125 Summary: coders/psd.c in ImageMagick allows remote attackers to cause a denial of service (out-of-bounds read) via a crafted PSD file. Commit Message: Added check for out of bounds read (https://github.com/ImageMagick/ImageMagick/issues/108).
Medium
1,889
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: mainloop_destroy_trigger(crm_trigger_t * source) { source->trigger = FALSE; if (source->id > 0) { g_source_remove(source->id); } return TRUE; } Vulnerability Type: DoS CWE ID: CWE-399 Summary: Pacemaker 1.1.10, when remote Cluster Information Base (CIB) configuration or resource management is enabled, does not limit the duration of connections to the blocking sockets, which allows remote attackers to cause a denial of service (connection blocking). Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
Medium
462
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: FileStream::FileStream(const scoped_refptr<base::TaskRunner>& task_runner) : context_(base::MakeUnique<Context>(task_runner)) {} Vulnerability Type: CWE ID: CWE-311 Summary: Inappropriate implementation in ChromeVox in Google Chrome OS prior to 62.0.3202.74 allowed a remote attacker in a privileged network position to observe or tamper with certain cleartext HTTP requests by leveraging that position. Commit Message: Replace base::MakeUnique with std::make_unique in net/. base/memory/ptr_util.h includes will be cleaned up later. Bug: 755727 Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434 Reviewed-on: https://chromium-review.googlesource.com/627300 Commit-Queue: Jeremy Roman <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Bence Béky <[email protected]> Cr-Commit-Position: refs/heads/master@{#498123}
Medium
4,949
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static void br_multicast_del_pg(struct net_bridge *br, struct net_bridge_port_group *pg) { struct net_bridge_mdb_htable *mdb; struct net_bridge_mdb_entry *mp; struct net_bridge_port_group *p; struct net_bridge_port_group __rcu **pp; mdb = mlock_dereference(br->mdb, br); mp = br_mdb_ip_get(mdb, &pg->addr); if (WARN_ON(!mp)) return; for (pp = &mp->ports; (p = mlock_dereference(*pp, br)) != NULL; pp = &p->next) { if (p != pg) continue; rcu_assign_pointer(*pp, p->next); hlist_del_init(&p->mglist); del_timer(&p->timer); call_rcu_bh(&p->rcu, br_multicast_free_pg); if (!mp->ports && !mp->mglist && netif_running(br->dev)) mod_timer(&mp->timer, jiffies); return; } WARN_ON(1); } Vulnerability Type: DoS CWE ID: CWE-20 Summary: The bridge multicast implementation in the Linux kernel through 3.10.3 does not check whether a certain timer is armed before modifying the timeout value of that timer, which allows local users to cause a denial of service (BUG and system crash) via vectors involving the shutdown of a KVM virtual machine, related to net/bridge/br_mdb.c and net/bridge/br_multicast.c. Commit Message: bridge: fix some kernel warning in multicast timer Several people reported the warning: "kernel BUG at kernel/timer.c:729!" and the stack trace is: #7 [ffff880214d25c10] mod_timer+501 at ffffffff8106d905 #8 [ffff880214d25c50] br_multicast_del_pg.isra.20+261 at ffffffffa0731d25 [bridge] #9 [ffff880214d25c80] br_multicast_disable_port+88 at ffffffffa0732948 [bridge] #10 [ffff880214d25cb0] br_stp_disable_port+154 at ffffffffa072bcca [bridge] #11 [ffff880214d25ce8] br_device_event+520 at ffffffffa072a4e8 [bridge] #12 [ffff880214d25d18] notifier_call_chain+76 at ffffffff8164aafc #13 [ffff880214d25d50] raw_notifier_call_chain+22 at ffffffff810858f6 #14 [ffff880214d25d60] call_netdevice_notifiers+45 at ffffffff81536aad #15 [ffff880214d25d80] dev_close_many+183 at ffffffff81536d17 #16 [ffff880214d25dc0] rollback_registered_many+168 at ffffffff81537f68 #17 [ffff880214d25de8] rollback_registered+49 at ffffffff81538101 #18 [ffff880214d25e10] unregister_netdevice_queue+72 at ffffffff815390d8 #19 [ffff880214d25e30] __tun_detach+272 at ffffffffa074c2f0 [tun] #20 [ffff880214d25e88] tun_chr_close+45 at ffffffffa074c4bd [tun] #21 [ffff880214d25ea8] __fput+225 at ffffffff8119b1f1 #22 [ffff880214d25ef0] ____fput+14 at ffffffff8119b3fe #23 [ffff880214d25f00] task_work_run+159 at ffffffff8107cf7f #24 [ffff880214d25f30] do_notify_resume+97 at ffffffff810139e1 #25 [ffff880214d25f50] int_signal+18 at ffffffff8164f292 this is due to I forgot to check if mp->timer is armed in br_multicast_del_pg(). This bug is introduced by commit 9f00b2e7cf241fa389733d41b6 (bridge: only expire the mdb entry when query is received). Same for __br_mdb_del(). Tested-by: poma <[email protected]> Reported-by: LiYonghua <[email protected]> Reported-by: Robert Hancock <[email protected]> Cc: Herbert Xu <[email protected]> Cc: Stephen Hemminger <[email protected]> Cc: "David S. Miller" <[email protected]> Signed-off-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]>
Medium
16,065
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: header_put_be_8byte (SF_PRIVATE *psf, sf_count_t x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8) { psf->header [psf->headindex++] = (x >> 56) ; psf->header [psf->headindex++] = (x >> 48) ; psf->header [psf->headindex++] = (x >> 40) ; psf->header [psf->headindex++] = (x >> 32) ; psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_be_8byte */ Vulnerability Type: Overflow CWE ID: CWE-119 Summary: In libsndfile before 1.0.28, an error in the *header_read()* function (common.c) when handling ID3 tags can be exploited to cause a stack-based buffer overflow via a specially crafted FLAC file. Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k.
Medium
25,078
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int pptp_connect(struct socket *sock, struct sockaddr *uservaddr, int sockaddr_len, int flags) { struct sock *sk = sock->sk; struct sockaddr_pppox *sp = (struct sockaddr_pppox *) uservaddr; struct pppox_sock *po = pppox_sk(sk); struct pptp_opt *opt = &po->proto.pptp; struct rtable *rt; struct flowi4 fl4; int error = 0; if (sp->sa_protocol != PX_PROTO_PPTP) return -EINVAL; if (lookup_chan_dst(sp->sa_addr.pptp.call_id, sp->sa_addr.pptp.sin_addr.s_addr)) return -EALREADY; lock_sock(sk); /* Check for already bound sockets */ if (sk->sk_state & PPPOX_CONNECTED) { error = -EBUSY; goto end; } /* Check for already disconnected sockets, on attempts to disconnect */ if (sk->sk_state & PPPOX_DEAD) { error = -EALREADY; goto end; } if (!opt->src_addr.sin_addr.s_addr || !sp->sa_addr.pptp.sin_addr.s_addr) { error = -EINVAL; goto end; } po->chan.private = sk; po->chan.ops = &pptp_chan_ops; rt = ip_route_output_ports(sock_net(sk), &fl4, sk, opt->dst_addr.sin_addr.s_addr, opt->src_addr.sin_addr.s_addr, 0, 0, IPPROTO_GRE, RT_CONN_FLAGS(sk), 0); if (IS_ERR(rt)) { error = -EHOSTUNREACH; goto end; } sk_setup_caps(sk, &rt->dst); po->chan.mtu = dst_mtu(&rt->dst); if (!po->chan.mtu) po->chan.mtu = PPP_MRU; ip_rt_put(rt); po->chan.mtu -= PPTP_HEADER_OVERHEAD; po->chan.hdrlen = 2 + sizeof(struct pptp_gre_header); error = ppp_register_channel(&po->chan); if (error) { pr_err("PPTP: failed to register PPP channel (%d)\n", error); goto end; } opt->dst_addr = sp->sa_addr.pptp; sk->sk_state = PPPOX_CONNECTED; end: release_sock(sk); return error; } Vulnerability Type: Bypass +Info CWE ID: CWE-200 Summary: The (1) pptp_bind and (2) pptp_connect functions in drivers/net/ppp/pptp.c in the Linux kernel through 4.3.3 do not verify an address length, which allows local users to obtain sensitive information from kernel memory and bypass the KASLR protection mechanism via a crafted application. Commit Message: pptp: verify sockaddr_len in pptp_bind() and pptp_connect() Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]>
Low
19,140
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) { /* ! */ dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle); WORD32 i4_err_status = 0; UWORD8 *pu1_buf = NULL; WORD32 buflen; UWORD32 u4_max_ofst, u4_length_of_start_code = 0; UWORD32 bytes_consumed = 0; UWORD32 cur_slice_is_nonref = 0; UWORD32 u4_next_is_aud; UWORD32 u4_first_start_code_found = 0; WORD32 ret = 0,api_ret_value = IV_SUCCESS; WORD32 header_data_left = 0,frame_data_left = 0; UWORD8 *pu1_bitstrm_buf; ivd_video_decode_ip_t *ps_dec_ip; ivd_video_decode_op_t *ps_dec_op; ithread_set_name((void*)"Parse_thread"); ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; { UWORD32 u4_size; u4_size = ps_dec_op->u4_size; memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); ps_dec_op->u4_size = u4_size; } ps_dec->pv_dec_out = ps_dec_op; ps_dec->process_called = 1; if(ps_dec->init_done != 1) { return IV_FAIL; } /*Data memory barries instruction,so that bitstream write by the application is complete*/ DATA_SYNC(); if(0 == ps_dec->u1_flushfrm) { if(ps_dec_ip->pv_stream_buffer == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->u4_num_Bytes <= 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; return IV_FAIL; } } ps_dec->u1_pic_decode_done = 0; ps_dec_op->u4_num_bytes_consumed = 0; ps_dec->ps_out_buffer = NULL; if(ps_dec_ip->u4_size >= offsetof(ivd_video_decode_ip_t, s_out_buffer)) ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer; ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 0; ps_dec->s_disp_op.u4_error_code = 1; ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS; ps_dec->u4_stop_threads = 0; if(0 == ps_dec->u4_share_disp_buf && ps_dec->i4_decode_header == 0) { UWORD32 i; if(ps_dec->ps_out_buffer->u4_num_bufs == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; return IV_FAIL; } for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++) { if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; return IV_FAIL; } if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return IV_FAIL; } } } if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT) { ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER; return IV_FAIL; } /* ! */ ps_dec->u4_ts = ps_dec_ip->u4_ts; ps_dec_op->u4_error_code = 0; ps_dec_op->e_pic_type = -1; ps_dec_op->u4_output_present = 0; ps_dec_op->u4_frame_decoded_flag = 0; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; ps_dec->u4_slice_start_code_found = 0; /* In case the deocder is not in flush mode(in shared mode), then decoder has to pick up a buffer to write current frame. Check if a frame is available in such cases */ if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1 && ps_dec->u1_flushfrm == 0) { UWORD32 i; WORD32 disp_avail = 0, free_id; /* Check if at least one buffer is available with the codec */ /* If not then return to application with error */ for(i = 0; i < ps_dec->u1_pic_bufs; i++) { if(0 == ps_dec->u4_disp_buf_mapping[i] || 1 == ps_dec->u4_disp_buf_to_be_freed[i]) { disp_avail = 1; break; } } if(0 == disp_avail) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } while(1) { pic_buffer_t *ps_pic_buf; ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id); if(ps_pic_buf == NULL) { UWORD32 i, display_queued = 0; /* check if any buffer was given for display which is not returned yet */ for(i = 0; i < (MAX_DISP_BUFS_NEW); i++) { if(0 != ps_dec->u4_disp_buf_mapping[i]) { display_queued = 1; break; } } /* If some buffer is queued for display, then codec has to singal an error and wait for that buffer to be returned. If nothing is queued for display then codec has ownership of all display buffers and it can reuse any of the existing buffers and continue decoding */ if(1 == display_queued) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } } else { /* If the buffer is with display, then mark it as in use and then look for a buffer again */ if(1 == ps_dec->u4_disp_buf_mapping[free_id]) { ih264_buf_mgr_set_status( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); } else { /** * Found a free buffer for present call. Release it now. * Will be again obtained later. */ ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); break; } } } } if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; ps_dec->u4_output_present = 1; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; ps_dec_op->u4_new_seq = 0; ps_dec_op->u4_output_present = ps_dec->u4_output_present; ps_dec_op->u4_progressive_frame_flag = ps_dec->s_disp_op.u4_progressive_frame_flag; ps_dec_op->e_output_format = ps_dec->s_disp_op.e_output_format; ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf; ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type; ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts; ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id; /*In the case of flush ,since no frame is decoded set pic type as invalid*/ ps_dec_op->u4_is_ref_flag = -1; ps_dec_op->e_pic_type = IV_NA_FRAME; ps_dec_op->u4_frame_decoded_flag = 0; if(0 == ps_dec->s_disp_op.u4_error_code) { return (IV_SUCCESS); } else return (IV_FAIL); } if(ps_dec->u1_res_changed == 1) { /*if resolution has changed and all buffers have been flushed, reset decoder*/ ih264d_init_decoder(ps_dec); } ps_dec->u4_prev_nal_skipped = 0; ps_dec->u2_cur_mb_addr = 0; ps_dec->u2_total_mbs_coded = 0; ps_dec->u2_cur_slice_num = 0; ps_dec->cur_dec_mb_num = 0; ps_dec->cur_recon_mb_num = 0; ps_dec->u4_first_slice_in_pic = 2; ps_dec->u1_first_pb_nal_in_pic = 1; ps_dec->u1_slice_header_done = 0; ps_dec->u1_dangling_field = 0; ps_dec->u4_dec_thread_created = 0; ps_dec->u4_bs_deblk_thread_created = 0; ps_dec->u4_cur_bs_mb_num = 0; ps_dec->u4_start_recon_deblk = 0; DEBUG_THREADS_PRINTF(" Starting process call\n"); ps_dec->u4_pic_buf_got = 0; do { pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer + ps_dec_op->u4_num_bytes_consumed; u4_max_ofst = ps_dec_ip->u4_num_Bytes - ps_dec_op->u4_num_bytes_consumed; pu1_bitstrm_buf = ps_dec->ps_mem_tab[MEM_REC_BITSBUF].pv_base; u4_next_is_aud = 0; buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst, &u4_length_of_start_code, &u4_next_is_aud); if(buflen == -1) buflen = 0; /* Ignore bytes beyond the allocated size of intermediate buffer */ /* Since 8 bytes are read ahead, ensure 8 bytes are free at the end of the buffer, which will be memset to 0 after emulation prevention */ buflen = MIN(buflen, (WORD32)(ps_dec->ps_mem_tab[MEM_REC_BITSBUF].u4_mem_size - 8)); bytes_consumed = buflen + u4_length_of_start_code; ps_dec_op->u4_num_bytes_consumed += bytes_consumed; if(buflen >= MAX_NAL_UNIT_SIZE) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); H264_DEC_DEBUG_PRINT( "\nNal Size exceeded %d, Processing Stopped..\n", MAX_NAL_UNIT_SIZE); ps_dec->i4_error_code = 1 << IVD_CORRUPTEDDATA; ps_dec_op->e_pic_type = -1; /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /*signal end of frame decode for curren frame*/ if(ps_dec->u4_pic_buf_got == 0) { if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return IV_FAIL; } else { ps_dec->u1_pic_decode_done = 1; continue; } } { UWORD8 u1_firstbyte, u1_nal_ref_idc; if(ps_dec->i4_app_skip_mode == IVD_SKIP_B) { u1_firstbyte = *(pu1_buf + u4_length_of_start_code); u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte)); if(u1_nal_ref_idc == 0) { /*skip non reference frames*/ cur_slice_is_nonref = 1; continue; } else { if(1 == cur_slice_is_nonref) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->e_pic_type = IV_B_FRAME; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } } } } if(buflen) { memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code, buflen); u4_first_start_code_found = 1; } else { /*start code not found*/ if(u4_first_start_code_found == 0) { /*no start codes found in current process call*/ ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND; ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA; if(ps_dec->u4_pic_buf_got == 0) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); ps_dec_op->u4_error_code = ps_dec->i4_error_code; ps_dec_op->u4_frame_decoded_flag = 0; return (IV_FAIL); } else { ps_dec->u1_pic_decode_done = 1; continue; } } else { /* a start code has already been found earlier in the same process call*/ frame_data_left = 0; header_data_left = 0; continue; } } ps_dec->u4_return_to_app = 0; ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op, pu1_bitstrm_buf, buflen); if(ret != OK) { UWORD32 error = ih264d_map_error(ret); ps_dec_op->u4_error_code = error | ret; api_ret_value = IV_FAIL; if((ret == IVD_RES_CHANGED) || (ret == IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { ps_dec->u4_slice_start_code_found = 0; break; } if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC)) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; api_ret_value = IV_FAIL; break; } if(ret == ERROR_IN_LAST_SLICE_OF_PIC) { api_ret_value = IV_FAIL; break; } } if(ps_dec->u4_return_to_app) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } header_data_left = ((ps_dec->i4_decode_header == 1) && (ps_dec->i4_header_decoded != 3) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); frame_data_left = (((ps_dec->i4_decode_header == 0) && ((ps_dec->u1_pic_decode_done == 0) || (u4_next_is_aud == 1))) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); } while(( header_data_left == 1)||(frame_data_left == 1)); if((ps_dec->u4_slice_start_code_found == 1) && ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { WORD32 num_mb_skipped; WORD32 prev_slice_err; pocstruct_t temp_poc; WORD32 ret1; WORD32 ht_in_mbs; ht_in_mbs = ps_dec->u2_pic_ht >> (4 + ps_dec->ps_cur_slice->u1_field_pic_flag); num_mb_skipped = (ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0)) prev_slice_err = 1; else prev_slice_err = 2; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u2_total_mbs_coded == 0)) prev_slice_err = 1; ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num, &temp_poc, prev_slice_err); if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T) || (ret1 == ERROR_INV_SPS_PPS_T)) { ret = ret1; } } if((ret == IVD_RES_CHANGED) || (ret == IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { /* signal the decode thread */ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet */ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } /* dont consume bitstream for change in resolution case */ if(ret == IVD_RES_CHANGED) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; } return IV_FAIL; } if(ps_dec->u1_separate_parse) { /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_num_cores == 2) { /*do deblocking of all mbs*/ if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0)) { UWORD32 u4_num_mbs,u4_max_addr; tfr_ctxt_t s_tfr_ctxt; tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt; pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr; /*BS is done for all mbs while parsing*/ u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1; ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1; ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt, ps_dec->u2_frm_wd_in_mbs, 0); u4_num_mbs = u4_max_addr - ps_dec->u4_cur_deblk_mb_num + 1; DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs); if(u4_num_mbs != 0) ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs, ps_tfr_cxt,1); ps_dec->u4_start_recon_deblk = 0; } } /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } } DATA_SYNC(); if((ps_dec_op->u4_error_code & 0xff) != ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED) { ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; } if(ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->u4_prev_nal_skipped) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } if((ps_dec->u4_slice_start_code_found == 1) && (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status)) { /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ if(ps_dec->ps_cur_slice->u1_field_pic_flag) { if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag) { ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY; } else { ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY; } } /* if new frame in not found (if we are still getting slices from previous frame) * ih264d_deblock_display is not called. Such frames will not be added to reference /display */ if (((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0) && (ps_dec->u4_pic_buf_got == 1)) { /* Calling Function to deblock Picture and Display */ ret = ih264d_deblock_display(ps_dec); } /*set to complete ,as we dont support partial frame decode*/ if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /*Update the i4_frametype at the end of picture*/ if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) { ps_dec->i4_frametype = IV_IDR_FRAME; } else if(ps_dec->i4_pic_type == B_SLICE) { ps_dec->i4_frametype = IV_B_FRAME; } else if(ps_dec->i4_pic_type == P_SLICE) { ps_dec->i4_frametype = IV_P_FRAME; } else if(ps_dec->i4_pic_type == I_SLICE) { ps_dec->i4_frametype = IV_I_FRAME; } else { H264_DEC_DEBUG_PRINT("Shouldn't come here\n"); } ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded - ps_dec->ps_cur_slice->u1_field_pic_flag; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } { /* In case the decoder is configured to run in low delay mode, * then get display buffer and then format convert. * Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles */ if((0 == ps_dec->u4_num_reorder_frames_at_init) && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 1; } } ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_output_present && (ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht)) { ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht - ps_dec->u4_fmt_conv_cur_row; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); } if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1) { ps_dec_op->u4_progressive_frame_flag = 1; if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) { if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag) && (0 == ps_dec->ps_sps->u1_mb_aff_flag)) ps_dec_op->u4_progressive_frame_flag = 0; } } if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded) { ps_dec->u1_top_bottom_decoded = 0; } /*--------------------------------------------------------------------*/ /* Do End of Pic processing. */ /* Should be called only if frame was decoded in previous process call*/ /*--------------------------------------------------------------------*/ if(ps_dec->u4_pic_buf_got == 1) { if(1 == ps_dec->u1_last_pic_not_decoded) { ret = ih264d_end_of_pic_dispbuf_mgr(ps_dec); if(ret != OK) return ret; ret = ih264d_end_of_pic(ps_dec); if(ret != OK) return ret; } else { ret = ih264d_end_of_pic(ps_dec); if(ret != OK) return ret; } } /*Data memory barrier instruction,so that yuv write by the library is complete*/ DATA_SYNC(); H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n", ps_dec_op->u4_num_bytes_consumed); return api_ret_value; } Vulnerability Type: +Info CWE ID: CWE-200 Summary: An information disclosure vulnerability in libavc in Mediaserver could enable a local malicious application to access data outside of its permission levels. This issue is rated as Moderate because it could be used to access data without permission. Product: Android. Versions: 6.0, 6.0.1, 7.0, 7.1.1. Android ID: A-33551775. Commit Message: Decoder: Fixed initialization of first_slice_in_pic To handle some errors, first_slice_in_pic was being set to 2. This is now cleaned up and first_slice_in_pic is set to 1 only once per pic. This will ensure picture level initializations are done only once even in case of error clips Bug: 33717589 Bug: 33551775 Bug: 33716442 Bug: 33677995 Change-Id: If341436b3cbaa724017eedddd88c2e6fac36d8ba
Medium
17,468
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the severity score category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void RegisterProperties(IBusPropList* ibus_prop_list) { DLOG(INFO) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)"); ImePropertyList prop_list; // our representation. if (ibus_prop_list) { if (!FlattenPropertyList(ibus_prop_list, &prop_list)) { RegisterProperties(NULL); return; } } register_ime_properties_(language_library_, prop_list); } Vulnerability Type: DoS CWE ID: CWE-399 Summary: Google Chrome before 13.0.782.107 does not properly handle nested functions in PDF documents, which allows remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via a crafted document. 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
High
15,918