instruction
stringclasses
1 value
input
stringlengths
306
235k
output
stringclasses
3 values
__index_level_0__
int64
165k
175k
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: struct inode *isofs_iget(struct super_block *sb, unsigned long block, unsigned long offset) { unsigned long hashval; struct inode *inode; struct isofs_iget5_callback_data data; long ret; if (offset >= 1ul << sb->s_blocksize_bits) return ERR_PTR(-EINVAL); data.block = block; data.offset = offset; hashval = (block << sb->s_blocksize_bits) | offset; inode = iget5_locked(sb, hashval, &isofs_iget5_test, &isofs_iget5_set, &data); if (!inode) return ERR_PTR(-ENOMEM); if (inode->i_state & I_NEW) { ret = isofs_read_inode(inode); if (ret < 0) { iget_failed(inode); inode = ERR_PTR(ret); } else { unlock_new_inode(inode); } } return inode; } Vulnerability Type: DoS CWE ID: CWE-20 Summary: The parse_rock_ridge_inode_internal function in fs/isofs/rock.c in the Linux kernel through 3.16.1 allows local users to cause a denial of service (unkillable mount process) via a crafted iso9660 image with a self-referential CL entry. Commit Message: isofs: Fix unbounded recursion when processing relocated directories We did not check relocated directory in any way when processing Rock Ridge 'CL' tag. Thus a corrupted isofs image can possibly have a CL entry pointing to another CL entry leading to possibly unbounded recursion in kernel code and thus stack overflow or deadlocks (if there is a loop created from CL entries). Fix the problem by not allowing CL entry to point to a directory entry with CL entry (such use makes no good sense anyway) and by checking whether CL entry doesn't point to itself. CC: [email protected] Reported-by: Chris Evans <[email protected]> Signed-off-by: Jan Kara <[email protected]>
Medium
166,268
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: xmlParseExtParsedEnt(xmlParserCtxtPtr ctxt) { xmlChar start[4]; xmlCharEncoding enc; if ((ctxt == NULL) || (ctxt->input == NULL)) return(-1); xmlDefaultSAXHandlerInit(); xmlDetectSAX2(ctxt); GROW; /* * SAX: beginning of the document processing. */ if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines. */ if ((ctxt->input->end - ctxt->input->cur) >= 4) { start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } } if (CUR == 0) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); } /* * Check for the XMLDecl in the Prolog. */ GROW; if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { /* * Note that we will switch encoding on the fly. */ xmlParseXMLDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing right here */ return(-1); } SKIP_BLANKS; } else { ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); } if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); /* * Doing validity checking on chunk doesn't make sense */ ctxt->instate = XML_PARSER_CONTENT; ctxt->validate = 0; ctxt->loadsubset = 0; ctxt->depth = 0; xmlParseContent(ctxt); if ((RAW == '<') && (NXT(1) == '/')) { xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL); } else if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL); } /* * SAX: end of the document processing. */ if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); if (! ctxt->wellFormed) return(-1); return(0); } 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
171,291
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: l2tp_proto_ver_print(netdissect_options *ndo, const uint16_t *dat) { ND_PRINT((ndo, "%u.%u", (EXTRACT_16BITS(dat) >> 8), (EXTRACT_16BITS(dat) & 0xff))); } Vulnerability Type: CWE ID: CWE-125 Summary: The L2TP parser in tcpdump before 4.9.2 has a buffer over-read in print-l2tp.c, several functions. Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length. It's not good enough to check whether all the data specified by the AVP length was captured - you also have to check whether that length is large enough for all the required data in the AVP. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file supplied by the reporter(s).
High
167,898
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static PixelChannels **AcquirePixelThreadSet(const Image *images) { const Image *next; PixelChannels **pixels; register ssize_t i; size_t columns, number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(PixelChannels **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (PixelChannels **) NULL) return((PixelChannels **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); columns=images->columns; for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) number_threads; i++) { register ssize_t j; pixels[i]=(PixelChannels *) AcquireQuantumMemory(columns,sizeof(**pixels)); if (pixels[i] == (PixelChannels *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) columns; j++) { register ssize_t k; for (k=0; k < MaxPixelChannels; k++) pixels[i][j].channel[k]=0.0; } } return(pixels); } Vulnerability Type: Overflow CWE ID: CWE-119 Summary: ImageMagick 7.0.8-50 Q16 has a heap-based buffer overflow at MagickCore/statistic.c in EvaluateImages because of mishandling rows. Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1615
Medium
170,201
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: NetworkHandler::NetworkHandler(const std::string& host_id) : DevToolsDomainHandler(Network::Metainfo::domainName), process_(nullptr), host_(nullptr), enabled_(false), host_id_(host_id), bypass_service_worker_(false), cache_disabled_(false), weak_factory_(this) { static bool have_configured_service_worker_context = false; if (have_configured_service_worker_context) return; have_configured_service_worker_context = true; BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::BindOnce(&ConfigureServiceWorkerContextOnIO)); } Vulnerability Type: Exec Code CWE ID: CWE-20 Summary: An object lifetime issue in the developer tools network handler in Google Chrome prior to 66.0.3359.117 allowed a local attacker to execute arbitrary code via a crafted HTML page. Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157}
Medium
172,759
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static int crypto_report_acomp(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_acomp racomp; strlcpy(racomp.type, "acomp", sizeof(racomp.type)); if (nla_put(skb, CRYPTOCFGA_REPORT_ACOMP, sizeof(struct crypto_report_acomp), &racomp)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } Vulnerability Type: CWE ID: Summary: An issue was discovered in the Linux kernel before 4.19.3. crypto_report_one() and related functions in crypto/crypto_user.c (the crypto user configuration API) do not fully initialize structures that are copied to userspace, potentially leaking sensitive memory to user programs. NOTE: this is a CVE-2013-2547 regression but with easier exploitability because the attacker does not need a capability (however, the system must have the CONFIG_CRYPTO_USER kconfig option). Commit Message: crypto: user - fix leaking uninitialized memory to userspace All bytes of the NETLINK_CRYPTO report structures must be initialized, since they are copied to userspace. The change from strncpy() to strlcpy() broke this. As a minimal fix, change it back. Fixes: 4473710df1f8 ("crypto: user - Prepare for CRYPTO_MAX_ALG_NAME expansion") Cc: <[email protected]> # v4.12+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: Herbert Xu <[email protected]>
Low
168,963
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: int32 CommandBufferProxyImpl::CreateTransferBuffer( size_t size, int32 id_request) { if (last_state_.error != gpu::error::kNoError) return -1; scoped_ptr<base::SharedMemory> shm( channel_->factory()->AllocateSharedMemory(size)); if (!shm.get()) return -1; base::SharedMemoryHandle handle = shm->handle(); #if defined(OS_POSIX) DCHECK(!handle.auto_close); #endif int32 id; if (!Send(new GpuCommandBufferMsg_RegisterTransferBuffer(route_id_, handle, size, id_request, &id))) { return -1; } return id; } Vulnerability Type: DoS CWE ID: Summary: Google Chrome before 20.0.1132.43 on Windows does not properly isolate sandboxed processes, which might allow remote attackers to cause a denial of service (process interference) via unspecified vectors. Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
High
170,926
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx) { struct xenvif *vif; struct pending_tx_info *pending_tx_info; pending_ring_idx_t index; /* Already complete? */ if (netbk->mmap_pages[pending_idx] == NULL) return; pending_tx_info = &netbk->pending_tx_info[pending_idx]; vif = pending_tx_info->vif; make_tx_response(vif, &pending_tx_info->req, XEN_NETIF_RSP_OKAY); index = pending_index(netbk->pending_prod++); netbk->pending_ring[index] = pending_idx; xenvif_put(vif); netbk->mmap_pages[pending_idx]->mapping = 0; put_page(netbk->mmap_pages[pending_idx]); netbk->mmap_pages[pending_idx] = NULL; } Vulnerability Type: DoS CWE ID: CWE-399 Summary: Memory leak in drivers/net/xen-netback/netback.c in the Xen netback functionality in the Linux kernel before 3.7.8 allows guest OS users to cause a denial of service (memory consumption) by triggering certain error conditions. Commit Message: xen/netback: don't leak pages on failure in xen_netbk_tx_check_gop. Signed-off-by: Matthew Daley <[email protected]> Reviewed-by: Konrad Rzeszutek Wilk <[email protected]> Acked-by: Ian Campbell <[email protected]> Acked-by: Jan Beulich <[email protected]> Signed-off-by: David S. Miller <[email protected]>
Medium
166,168
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain) { int r; size_t len = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); r = sc_check_sw(card, sm->sw1, sm->sw2); if (r == SC_SUCCESS) { if (exdata->sm) { if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len)) return SC_ERROR_CARD_CMD_FAILED; } else { memcpy(plain->resp, sm->resp, sm->resplen); len = sm->resplen; } } plain->resplen = len; plain->sw1 = sm->sw1; plain->sw2 = sm->sw2; sc_log(card->ctx, "unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X", plain->resplen, plain->sw1, plain->sw2); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } Vulnerability Type: DoS CWE ID: CWE-415 Summary: A double free when handling responses from an HSM Card in sc_pkcs15emu_sc_hsm_init in libopensc/pkcs15-sc-hsm.c in OpenSC before 0.19.0-rc1 could be used by attackers able to supply crafted smartcards to cause a denial of service (application crash) or possibly have unspecified other impact. Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems.
Medium
169,073
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void CL_Init( void ) { Com_Printf( "----- Client Initialization -----\n" ); Con_Init(); if(!com_fullyInitialized) { CL_ClearState(); clc.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED cl_oldGameSet = qfalse; } cls.realtime = 0; CL_InitInput(); cl_noprint = Cvar_Get( "cl_noprint", "0", 0 ); #ifdef UPDATE_SERVER_NAME cl_motd = Cvar_Get( "cl_motd", "1", 0 ); #endif cl_autoupdate = Cvar_Get( "cl_autoupdate", "0", CVAR_ARCHIVE ); cl_timeout = Cvar_Get( "cl_timeout", "200", 0 ); cl_wavefilerecord = Cvar_Get( "cl_wavefilerecord", "0", CVAR_TEMP ); cl_timeNudge = Cvar_Get( "cl_timeNudge", "0", CVAR_TEMP ); cl_shownet = Cvar_Get( "cl_shownet", "0", CVAR_TEMP ); cl_shownuments = Cvar_Get( "cl_shownuments", "0", CVAR_TEMP ); cl_visibleClients = Cvar_Get( "cl_visibleClients", "0", CVAR_TEMP ); cl_showServerCommands = Cvar_Get( "cl_showServerCommands", "0", 0 ); cl_showSend = Cvar_Get( "cl_showSend", "0", CVAR_TEMP ); cl_showTimeDelta = Cvar_Get( "cl_showTimeDelta", "0", CVAR_TEMP ); cl_freezeDemo = Cvar_Get( "cl_freezeDemo", "0", CVAR_TEMP ); rcon_client_password = Cvar_Get( "rconPassword", "", CVAR_TEMP ); cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP ); cl_timedemo = Cvar_Get( "timedemo", "0", 0 ); cl_timedemoLog = Cvar_Get ("cl_timedemoLog", "", CVAR_ARCHIVE); cl_autoRecordDemo = Cvar_Get ("cl_autoRecordDemo", "0", CVAR_ARCHIVE); cl_aviFrameRate = Cvar_Get ("cl_aviFrameRate", "25", CVAR_ARCHIVE); cl_aviMotionJpeg = Cvar_Get ("cl_aviMotionJpeg", "1", CVAR_ARCHIVE); cl_avidemo = Cvar_Get( "cl_avidemo", "0", 0 ); cl_forceavidemo = Cvar_Get( "cl_forceavidemo", "0", 0 ); rconAddress = Cvar_Get( "rconAddress", "", 0 ); cl_yawspeed = Cvar_Get( "cl_yawspeed", "140", CVAR_ARCHIVE ); cl_pitchspeed = Cvar_Get( "cl_pitchspeed", "140", CVAR_ARCHIVE ); cl_anglespeedkey = Cvar_Get( "cl_anglespeedkey", "1.5", 0 ); cl_maxpackets = Cvar_Get( "cl_maxpackets", "38", CVAR_ARCHIVE ); cl_packetdup = Cvar_Get( "cl_packetdup", "1", CVAR_ARCHIVE ); cl_showPing = Cvar_Get( "cl_showPing", "0", CVAR_ARCHIVE ); cl_run = Cvar_Get( "cl_run", "1", CVAR_ARCHIVE ); cl_sensitivity = Cvar_Get( "sensitivity", "5", CVAR_ARCHIVE ); cl_mouseAccel = Cvar_Get( "cl_mouseAccel", "0", CVAR_ARCHIVE ); cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE ); cl_mouseAccelStyle = Cvar_Get( "cl_mouseAccelStyle", "0", CVAR_ARCHIVE ); cl_mouseAccelOffset = Cvar_Get( "cl_mouseAccelOffset", "5", CVAR_ARCHIVE ); Cvar_CheckRange(cl_mouseAccelOffset, 0.001f, 50000.0f, qfalse); cl_showMouseRate = Cvar_Get( "cl_showmouserate", "0", 0 ); cl_allowDownload = Cvar_Get( "cl_allowDownload", "1", CVAR_ARCHIVE ); #ifdef USE_CURL_DLOPEN cl_cURLLib = Cvar_Get("cl_cURLLib", DEFAULT_CURL_LIB, CVAR_ARCHIVE); #endif Cvar_Get( "cg_autoswitch", "0", CVAR_ARCHIVE ); Cvar_Get( "cg_wolfparticles", "1", CVAR_ARCHIVE ); cl_conXOffset = Cvar_Get( "cl_conXOffset", "0", 0 ); cl_inGameVideo = Cvar_Get( "r_inGameVideo", "1", CVAR_ARCHIVE ); cl_serverStatusResendTime = Cvar_Get( "cl_serverStatusResendTime", "750", 0 ); cl_recoilPitch = Cvar_Get( "cg_recoilPitch", "0", CVAR_ROM ); cl_bypassMouseInput = Cvar_Get( "cl_bypassMouseInput", "0", 0 ); //CVAR_ROM ); // NERVE - SMF m_pitch = Cvar_Get( "m_pitch", "0.022", CVAR_ARCHIVE ); m_yaw = Cvar_Get( "m_yaw", "0.022", CVAR_ARCHIVE ); m_forward = Cvar_Get( "m_forward", "0.25", CVAR_ARCHIVE ); m_side = Cvar_Get( "m_side", "0.25", CVAR_ARCHIVE ); m_filter = Cvar_Get( "m_filter", "0", CVAR_ARCHIVE ); j_pitch = Cvar_Get ("j_pitch", "0.022", CVAR_ARCHIVE); j_yaw = Cvar_Get ("j_yaw", "-0.022", CVAR_ARCHIVE); j_forward = Cvar_Get ("j_forward", "-0.25", CVAR_ARCHIVE); j_side = Cvar_Get ("j_side", "0.25", CVAR_ARCHIVE); j_up = Cvar_Get ("j_up", "0", CVAR_ARCHIVE); j_pitch_axis = Cvar_Get ("j_pitch_axis", "3", CVAR_ARCHIVE); j_yaw_axis = Cvar_Get ("j_yaw_axis", "2", CVAR_ARCHIVE); j_forward_axis = Cvar_Get ("j_forward_axis", "1", CVAR_ARCHIVE); j_side_axis = Cvar_Get ("j_side_axis", "0", CVAR_ARCHIVE); j_up_axis = Cvar_Get ("j_up_axis", "4", CVAR_ARCHIVE); Cvar_CheckRange(j_pitch_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_yaw_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_forward_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_side_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_up_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM ); Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE ); cl_lanForcePackets = Cvar_Get ("cl_lanForcePackets", "1", CVAR_ARCHIVE); cl_guid = Cvar_Get( "cl_guid", "unknown", CVAR_USERINFO | CVAR_ROM ); cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE); cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60", CVAR_ARCHIVE); Cvar_Get( "cg_drawCompass", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_drawNotifyText", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_quickMessageAlt", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_popupLimboMenu", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_descriptiveText", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_drawTeamOverlay", "2", CVAR_ARCHIVE ); Cvar_Get( "cg_uselessNostalgia", "0", CVAR_ARCHIVE ); // JPW NERVE Cvar_Get( "cg_drawGun", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_cursorHints", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_voiceSpriteTime", "6000", CVAR_ARCHIVE ); Cvar_Get( "cg_teamChatsOnly", "0", CVAR_ARCHIVE ); Cvar_Get( "cg_noVoiceChats", "0", CVAR_ARCHIVE ); Cvar_Get( "cg_noVoiceText", "0", CVAR_ARCHIVE ); Cvar_Get( "cg_crosshairSize", "48", CVAR_ARCHIVE ); Cvar_Get( "cg_drawCrosshair", "1", CVAR_ARCHIVE ); Cvar_Get( "cg_zoomDefaultSniper", "20", CVAR_ARCHIVE ); Cvar_Get( "cg_zoomstepsniper", "2", CVAR_ARCHIVE ); Cvar_Get( "mp_playerType", "0", 0 ); Cvar_Get( "mp_currentPlayerType", "0", 0 ); Cvar_Get( "mp_weapon", "0", 0 ); Cvar_Get( "mp_team", "0", 0 ); Cvar_Get( "mp_currentTeam", "0", 0 ); Cvar_Get( "name", "WolfPlayer", CVAR_USERINFO | CVAR_ARCHIVE ); cl_rate = Cvar_Get( "rate", "25000", CVAR_USERINFO | CVAR_ARCHIVE ); // NERVE - SMF - changed from 3000 Cvar_Get( "snaps", "20", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get( "model", "multi", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get( "head", "default", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get( "color", "4", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get( "handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get( "sex", "male", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get( "cl_anonymous", "0", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get( "password", "", CVAR_USERINFO ); Cvar_Get( "cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE ); #ifdef USE_MUMBLE cl_useMumble = Cvar_Get ("cl_useMumble", "0", CVAR_ARCHIVE | CVAR_LATCH); cl_mumbleScale = Cvar_Get ("cl_mumbleScale", "0.0254", CVAR_ARCHIVE); #endif #ifdef USE_VOIP cl_voipSend = Cvar_Get ("cl_voipSend", "0", 0); cl_voipSendTarget = Cvar_Get ("cl_voipSendTarget", "spatial", 0); cl_voipGainDuringCapture = Cvar_Get ("cl_voipGainDuringCapture", "0.2", CVAR_ARCHIVE); cl_voipCaptureMult = Cvar_Get ("cl_voipCaptureMult", "2.0", CVAR_ARCHIVE); cl_voipUseVAD = Cvar_Get ("cl_voipUseVAD", "0", CVAR_ARCHIVE); cl_voipVADThreshold = Cvar_Get ("cl_voipVADThreshold", "0.25", CVAR_ARCHIVE); cl_voipShowMeter = Cvar_Get ("cl_voipShowMeter", "1", CVAR_ARCHIVE); cl_voip = Cvar_Get ("cl_voip", "1", CVAR_ARCHIVE); Cvar_CheckRange( cl_voip, 0, 1, qtrue ); cl_voipProtocol = Cvar_Get ("cl_voipProtocol", cl_voip->integer ? "opus" : "", CVAR_USERINFO | CVAR_ROM); #endif Cvar_Get( "cg_autoactivate", "1", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get( "cg_viewsize", "100", CVAR_ARCHIVE ); Cvar_Get ("cg_stereoSeparation", "0", CVAR_ROM); Cvar_Get( "cg_autoReload", "1", CVAR_ARCHIVE | CVAR_USERINFO ); cl_missionStats = Cvar_Get( "g_missionStats", "0", CVAR_ROM ); cl_waitForFire = Cvar_Get( "cl_waitForFire", "0", CVAR_ROM ); cl_language = Cvar_Get( "cl_language", "0", CVAR_ARCHIVE ); cl_debugTranslation = Cvar_Get( "cl_debugTranslation", "0", 0 ); cl_updateavailable = Cvar_Get( "cl_updateavailable", "0", CVAR_ROM ); cl_updatefiles = Cvar_Get( "cl_updatefiles", "", CVAR_ROM ); Q_strncpyz( cls.autoupdateServerNames[0], AUTOUPDATE_SERVER1_NAME, MAX_QPATH ); Q_strncpyz( cls.autoupdateServerNames[1], AUTOUPDATE_SERVER2_NAME, MAX_QPATH ); Q_strncpyz( cls.autoupdateServerNames[2], AUTOUPDATE_SERVER3_NAME, MAX_QPATH ); Q_strncpyz( cls.autoupdateServerNames[3], AUTOUPDATE_SERVER4_NAME, MAX_QPATH ); Q_strncpyz( cls.autoupdateServerNames[4], AUTOUPDATE_SERVER5_NAME, MAX_QPATH ); Cmd_AddCommand( "cmd", CL_ForwardToServer_f ); Cmd_AddCommand( "configstrings", CL_Configstrings_f ); Cmd_AddCommand( "clientinfo", CL_Clientinfo_f ); Cmd_AddCommand( "snd_restart", CL_Snd_Restart_f ); Cmd_AddCommand( "vid_restart", CL_Vid_Restart_f ); Cmd_AddCommand( "ui_restart", CL_UI_Restart_f ); // NERVE - SMF Cmd_AddCommand( "disconnect", CL_Disconnect_f ); Cmd_AddCommand( "record", CL_Record_f ); Cmd_AddCommand( "demo", CL_PlayDemo_f ); Cmd_SetCommandCompletionFunc( "demo", CL_CompleteDemoName ); Cmd_AddCommand( "cinematic", CL_PlayCinematic_f ); Cmd_AddCommand( "stoprecord", CL_StopRecord_f ); Cmd_AddCommand( "connect", CL_Connect_f ); Cmd_AddCommand( "reconnect", CL_Reconnect_f ); Cmd_AddCommand( "localservers", CL_LocalServers_f ); Cmd_AddCommand( "globalservers", CL_GlobalServers_f ); Cmd_AddCommand( "rcon", CL_Rcon_f ); Cmd_SetCommandCompletionFunc( "rcon", CL_CompleteRcon ); Cmd_AddCommand( "ping", CL_Ping_f ); Cmd_AddCommand( "serverstatus", CL_ServerStatus_f ); Cmd_AddCommand( "showip", CL_ShowIP_f ); Cmd_AddCommand( "fs_openedList", CL_OpenedPK3List_f ); Cmd_AddCommand( "fs_referencedList", CL_ReferencedPK3List_f ); Cmd_AddCommand ("video", CL_Video_f ); Cmd_AddCommand ("stopvideo", CL_StopVideo_f ); Cmd_AddCommand( "cache_startgather", CL_Cache_StartGather_f ); Cmd_AddCommand( "cache_usedfile", CL_Cache_UsedFile_f ); Cmd_AddCommand( "cache_setindex", CL_Cache_SetIndex_f ); Cmd_AddCommand( "cache_mapchange", CL_Cache_MapChange_f ); Cmd_AddCommand( "cache_endgather", CL_Cache_EndGather_f ); Cmd_AddCommand( "updatehunkusage", CL_UpdateLevelHunkUsage ); Cmd_AddCommand( "updatescreen", SCR_UpdateScreen ); Cmd_AddCommand( "SaveTranslations", CL_SaveTranslations_f ); // NERVE - SMF - localization Cmd_AddCommand( "SaveNewTranslations", CL_SaveNewTranslations_f ); // NERVE - SMF - localization Cmd_AddCommand( "LoadTranslations", CL_LoadTranslations_f ); // NERVE - SMF - localization Cmd_AddCommand( "startSingleplayer", CL_startSingleplayer_f ); // NERVE - SMF Cmd_AddCommand( "setRecommended", CL_SetRecommended_f ); CL_InitRef(); SCR_Init(); Cvar_Set( "cl_running", "1" ); autoupdateChecked = qfalse; autoupdateStarted = qfalse; CL_InitTranslation(); // NERVE - SMF - localization CL_GenerateQKey(); CL_UpdateGUID( NULL, 0 ); Com_Printf( "----- Client Initialization Complete -----\n" ); } 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
170,081
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void InspectorPageAgent::clearDeviceOrientationOverride(ErrorString* error) { setDeviceOrientationOverride(error, 0, 0, 0); } Vulnerability Type: DoS CWE ID: Summary: Multiple unspecified vulnerabilities in the IPC layer in Google Chrome before 25.0.1364.97 on Windows and Linux, and before 25.0.1364.99 on Mac OS X, allow remote attackers to cause a denial of service or possibly have other impact via unknown vectors. Commit Message: DevTools: remove references to modules/device_orientation from core BUG=340221 Review URL: https://codereview.chromium.org/150913003 git-svn-id: svn://svn.chromium.org/blink/trunk@166493 bbb929c8-8fbe-4397-9dbb-9b2b20218538
High
171,402
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: evutil_parse_sockaddr_port(const char *ip_as_string, struct sockaddr *out, int *outlen) { int port; char buf[128]; const char *cp, *addr_part, *port_part; int is_ipv6; /* recognized formats are: * [ipv6]:port * ipv6 * [ipv6] * ipv4:port * ipv4 */ cp = strchr(ip_as_string, ':'); if (*ip_as_string == '[') { int len; if (!(cp = strchr(ip_as_string, ']'))) { return -1; } len = (int) ( cp-(ip_as_string + 1) ); if (len > (int)sizeof(buf)-1) { return -1; } memcpy(buf, ip_as_string+1, len); buf[len] = '\0'; addr_part = buf; if (cp[1] == ':') port_part = cp+2; else port_part = NULL; is_ipv6 = 1; } else if (cp && strchr(cp+1, ':')) { is_ipv6 = 1; addr_part = ip_as_string; port_part = NULL; } else if (cp) { is_ipv6 = 0; if (cp - ip_as_string > (int)sizeof(buf)-1) { return -1; } memcpy(buf, ip_as_string, cp-ip_as_string); buf[cp-ip_as_string] = '\0'; addr_part = buf; port_part = cp+1; } else { addr_part = ip_as_string; port_part = NULL; is_ipv6 = 0; } if (port_part == NULL) { port = 0; } else { port = atoi(port_part); if (port <= 0 || port > 65535) { return -1; } } if (!addr_part) return -1; /* Should be impossible. */ #ifdef AF_INET6 if (is_ipv6) { struct sockaddr_in6 sin6; memset(&sin6, 0, sizeof(sin6)); #ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN sin6.sin6_len = sizeof(sin6); #endif sin6.sin6_family = AF_INET6; sin6.sin6_port = htons(port); if (1 != evutil_inet_pton(AF_INET6, addr_part, &sin6.sin6_addr)) return -1; if ((int)sizeof(sin6) > *outlen) return -1; memset(out, 0, *outlen); memcpy(out, &sin6, sizeof(sin6)); *outlen = sizeof(sin6); return 0; } else #endif { struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); #ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN sin.sin_len = sizeof(sin); #endif sin.sin_family = AF_INET; sin.sin_port = htons(port); if (1 != evutil_inet_pton(AF_INET, addr_part, &sin.sin_addr)) return -1; if ((int)sizeof(sin) > *outlen) return -1; memset(out, 0, *outlen); memcpy(out, &sin, sizeof(sin)); *outlen = sizeof(sin); return 0; } } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: Stack-based buffer overflow in the evutil_parse_sockaddr_port function in evutil.c in libevent before 2.1.6-beta allows attackers to cause a denial of service (segmentation fault) via vectors involving a long string in brackets in the ip_as_string argument. Commit Message: evutil_parse_sockaddr_port(): fix buffer overflow @asn-the-goblin-slayer: "Length between '[' and ']' is cast to signed 32 bit integer on line 1815. Is the length is more than 2<<31 (INT_MAX), len will hold a negative value. Consequently, it will pass the check at line 1816. Segfault happens at line 1819. Generate a resolv.conf with generate-resolv.conf, then compile and run poc.c. See entry-functions.txt for functions in tor that might be vulnerable. Please credit 'Guido Vranken' for this discovery through the Tor bug bounty program." Reproducer for gdb (https://gist.github.com/azat/be2b0d5e9417ba0dfe2c): start p (1ULL<<31)+1ULL # $1 = 2147483649 p malloc(sizeof(struct sockaddr)) # $2 = (void *) 0x646010 p malloc(sizeof(int)) # $3 = (void *) 0x646030 p malloc($1) # $4 = (void *) 0x7fff76a2a010 p memset($4, 1, $1) # $5 = 1990369296 p (char *)$4 # $6 = 0x7fff76a2a010 '\001' <repeats 200 times>... set $6[0]='[' set $6[$1]=']' p evutil_parse_sockaddr_port($4, $2, $3) # $7 = -1 Before: $ gdb bin/http-connect < gdb (gdb) $1 = 2147483649 (gdb) (gdb) $2 = (void *) 0x646010 (gdb) (gdb) $3 = (void *) 0x646030 (gdb) (gdb) $4 = (void *) 0x7fff76a2a010 (gdb) (gdb) $5 = 1990369296 (gdb) (gdb) $6 = 0x7fff76a2a010 '\001' <repeats 200 times>... (gdb) (gdb) (gdb) (gdb) Program received signal SIGSEGV, Segmentation fault. __memcpy_sse2_unaligned () at memcpy-sse2-unaligned.S:36 After: $ gdb bin/http-connect < gdb (gdb) $1 = 2147483649 (gdb) (gdb) $2 = (void *) 0x646010 (gdb) (gdb) $3 = (void *) 0x646030 (gdb) (gdb) $4 = (void *) 0x7fff76a2a010 (gdb) (gdb) $5 = 1990369296 (gdb) (gdb) $6 = 0x7fff76a2a010 '\001' <repeats 200 times>... (gdb) (gdb) (gdb) (gdb) $7 = -1 (gdb) (gdb) quit Fixes: #318
Medium
168,492
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define SkipLinesOp 0x01 #define SetColorOp 0x02 #define SkipPixelsOp 0x03 #define ByteDataOp 0x05 #define RunDataOp 0x06 #define EOFOp 0x07 char magick[12]; Image *image; IndexPacket index; int opcode, operand, status; MagickStatusType flags; MagickSizeType number_pixels; MemoryInfo *pixel_info; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bits_per_pixel, map_length, number_colormaps, number_planes, number_planes_filled, one, pixel_info_length; ssize_t count, offset, y; unsigned char background_color[256], *colormap, pixel, plane, *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) return(DestroyImageList(image)); /* Determine if this a RLE file. */ count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 2) || (memcmp(magick,"\122\314",2) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Read image header. */ image->page.x=ReadBlobLSBShort(image); image->page.y=ReadBlobLSBShort(image); image->columns=ReadBlobLSBShort(image); image->rows=ReadBlobLSBShort(image); flags=(MagickStatusType) ReadBlobByte(image); image->matte=flags & 0x04 ? MagickTrue : MagickFalse; number_planes=(size_t) ReadBlobByte(image); bits_per_pixel=(size_t) ReadBlobByte(image); number_colormaps=(size_t) ReadBlobByte(image); map_length=(unsigned char) ReadBlobByte(image); if (map_length >= 22) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); one=1; map_length=one << map_length; if ((number_planes == 0) || (number_planes == 2) || ((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) || (image->columns == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (flags & 0x02) { /* No background color-- initialize to black. */ for (i=0; i < (ssize_t) number_planes; i++) background_color[i]=0; (void) ReadBlobByte(image); } else { /* Initialize background color. */ p=background_color; for (i=0; i < (ssize_t) number_planes; i++) *p++=(unsigned char) ReadBlobByte(image); } if ((number_planes & 0x01) == 0) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } colormap=(unsigned char *) NULL; if (number_colormaps != 0) { /* Read image colormaps. */ colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps, 3*map_length*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; for (i=0; i < (ssize_t) number_colormaps; i++) for (x=0; x < (ssize_t) map_length; x++) *p++=(unsigned char) ScaleQuantumToChar(ScaleShortToQuantum( ReadBlobLSBShort(image))); } if ((flags & 0x08) != 0) { char *comment; size_t length; /* Read image comment. */ length=ReadBlobLSBShort(image); if (length != 0) { comment=(char *) AcquireQuantumMemory(length,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,length-1,(unsigned char *) comment); comment[length-1]='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); if ((length & 0x01) == 0) (void) ReadBlobByte(image); } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate RLE pixels. */ if (image->matte != MagickFalse) number_planes++; number_pixels=(MagickSizeType) image->columns*image->rows; number_planes_filled=(number_planes % 2 == 0) ? number_planes : number_planes+1; if ((number_pixels*number_planes_filled) != (size_t) (number_pixels* number_planes_filled)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info=AcquireVirtualMemory(image->columns,image->rows* MagickMax(number_planes_filled,4)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info_length=image->columns*image->rows* MagickMax(number_planes_filled,4); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) ResetMagickMemory(pixels,0,pixel_info_length); if ((flags & 0x01) && !(flags & 0x02)) { ssize_t j; /* Set background color. */ p=pixels; for (i=0; i < (ssize_t) number_pixels; i++) { if (image->matte == MagickFalse) for (j=0; j < (ssize_t) number_planes; j++) *p++=background_color[j]; else { for (j=0; j < (ssize_t) (number_planes-1); j++) *p++=background_color[j]; *p++=0; /* initialize matte channel */ } } } /* Read runlength-encoded image. */ plane=0; x=0; y=0; opcode=ReadBlobByte(image); do { switch (opcode & 0x3f) { case SkipLinesOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); x=0; y+=operand; break; } case SetColorOp: { operand=ReadBlobByte(image); plane=(unsigned char) operand; if (plane == 255) plane=(unsigned char) (number_planes-1); x=0; break; } case SkipPixelsOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); x+=operand; break; } case ByteDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; operand++; if ((offset < 0) || (offset+((size_t) operand*number_planes) > pixel_info_length)) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { pixel=(unsigned char) ReadBlobByte(image); if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } if (operand & 0x01) (void) ReadBlobByte(image); x+=operand; break; } case RunDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); pixel=(unsigned char) ReadBlobByte(image); (void) ReadBlobByte(image); operand++; offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; if ((offset < 0) || (offset+((size_t) operand*number_planes) > pixel_info_length)) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } x+=operand; break; } default: break; } opcode=ReadBlobByte(image); } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF)); if (number_colormaps != 0) { MagickStatusType mask; /* Apply colormap affineation to image. */ mask=(MagickStatusType) (map_length-1); p=pixels; x=(ssize_t) number_planes; if (number_colormaps == 1) for (i=0; i < (ssize_t) number_pixels; i++) { if (IsValidColormapIndex(image,*p & mask,&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } else if ((number_planes >= 3) && (number_colormaps >= 3)) for (i=0; i < (ssize_t) number_pixels; i++) for (x=0; x < (ssize_t) number_planes; x++) { if (IsValidColormapIndex(image,(size_t) (x*map_length+ (*p & mask)),&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } } /* Initialize image structure. */ if (number_planes >= 3) { /* Convert raster image to DirectClass pixel packets. */ p=pixels; 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++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum(*p++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create colormap. */ if (number_colormaps == 0) map_length=256; if (AcquireImageColormap(image,map_length) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; if (number_colormaps == 1) for (i=0; i < (ssize_t) image->colors; i++) { /* Pseudocolor. */ image->colormap[i].red=ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i); } else if (number_colormaps > 1) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(*p); image->colormap[i].green=ScaleCharToQuantum(*(p+map_length)); image->colormap[i].blue=ScaleCharToQuantum(*(p+map_length*2)); p++; } p=pixels; if (image->matte == MagickFalse) { /* Convert raster image to PseudoClass pixel 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,*p++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); } else { /* Image has a matte channel-- promote to DirectClass. */ 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++) { if (IsValidColormapIndex(image,*p++,&index,exception) == MagickFalse) break; SetPixelRed(q,image->colormap[(ssize_t) index].red); if (IsValidColormapIndex(image,*p++,&index,exception) == MagickFalse) break; SetPixelGreen(q,image->colormap[(ssize_t) index].green); if (IsValidColormapIndex(image,*p++,&index,exception) == MagickFalse) break; SetPixelBlue(q,image->colormap[(ssize_t) index].blue); SetPixelAlpha(q,ScaleCharToQuantum(*p++)); q++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } image->colormap=(PixelPacket *) RelinquishMagickMemory( image->colormap); image->storage_class=DirectClass; image->colors=0; } } if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; (void) ReadBlobByte(image); count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 0) && (memcmp(magick,"\122\314",2) == 0)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (memcmp(magick,"\122\314",2) == 0)); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Vulnerability Type: CWE ID: CWE-20 Summary: In ImageMagick 7.0.5-5, a crafted RLE image can trigger a crash because of incorrect EOF handling in coders/rle.c. Commit Message: Check for EOF conditions for RLE image format
Medium
168,122
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: bool AppCacheDatabase::FindCache(int64_t cache_id, CacheRecord* record) { DCHECK(record); if (!LazyOpen(kDontCreate)) return false; static const char kSql[] = "SELECT cache_id, group_id, online_wildcard, update_time, cache_size" " FROM Caches WHERE cache_id = ?"; sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt64(0, cache_id); if (!statement.Step()) return false; ReadCacheRecord(statement, record); return true; } Vulnerability Type: +Info CWE ID: CWE-200 Summary: Resource size information leakage in Blink in Google Chrome prior to 75.0.3770.80 allowed a remote attacker to leak cross-origin data via a crafted HTML page. Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <[email protected]> > Reviewed-by: Victor Costan <[email protected]> > Reviewed-by: Marijn Kruisselbrink <[email protected]> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Staphany Park <[email protected]> Cr-Commit-Position: refs/heads/master@{#644719}
Medium
172,973
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: AcpiDsCreateOperands ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *FirstArg) { ACPI_STATUS Status = AE_OK; ACPI_PARSE_OBJECT *Arg; ACPI_PARSE_OBJECT *Arguments[ACPI_OBJ_NUM_OPERANDS]; UINT32 ArgCount = 0; UINT32 Index = WalkState->NumOperands; UINT32 i; ACPI_FUNCTION_TRACE_PTR (DsCreateOperands, FirstArg); /* Get all arguments in the list */ Arg = FirstArg; while (Arg) { if (Index >= ACPI_OBJ_NUM_OPERANDS) { return_ACPI_STATUS (AE_BAD_DATA); } Arguments[Index] = Arg; WalkState->Operands [Index] = NULL; /* Move on to next argument, if any */ Arg = Arg->Common.Next; ArgCount++; Index++; } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "NumOperands %d, ArgCount %d, Index %d\n", WalkState->NumOperands, ArgCount, Index)); /* Create the interpreter arguments, in reverse order */ Index--; for (i = 0; i < ArgCount; i++) { Arg = Arguments[Index]; WalkState->OperandIndex = (UINT8) Index; Status = AcpiDsCreateOperand (WalkState, Arg, Index); if (ACPI_FAILURE (Status)) { goto Cleanup; } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Created Arg #%u (%p) %u args total\n", Index, Arg, ArgCount)); Index--; } return_ACPI_STATUS (Status); Cleanup: /* * We must undo everything done above; meaning that we must * pop everything off of the operand stack and delete those * objects */ AcpiDsObjStackPopAndDelete (ArgCount, WalkState); ACPI_EXCEPTION ((AE_INFO, Status, "While creating Arg %u", Index)); return_ACPI_STATUS (Status); } Vulnerability Type: Bypass +Info CWE ID: CWE-200 Summary: The acpi_ds_create_operands() function in drivers/acpi/acpica/dsutils.c in the Linux kernel through 4.12.9 does not flush the operand cache and causes a kernel stack dump, which allows local users to obtain sensitive information from kernel memory and bypass the KASLR protection mechanism (in the kernel through 4.9) via a crafted ACPI table. Commit Message: acpi: acpica: fix acpi operand cache leak in dswstate.c I found an ACPI cache leak in ACPI early termination and boot continuing case. When early termination occurs due to malicious ACPI table, Linux kernel terminates ACPI function and continues to boot process. While kernel terminates ACPI function, kmem_cache_destroy() reports Acpi-Operand cache leak. Boot log of ACPI operand cache leak is as follows: >[ 0.585957] ACPI: Added _OSI(Module Device) >[ 0.587218] ACPI: Added _OSI(Processor Device) >[ 0.588530] ACPI: Added _OSI(3.0 _SCP Extensions) >[ 0.589790] ACPI: Added _OSI(Processor Aggregator Device) >[ 0.591534] ACPI Error: Illegal I/O port address/length above 64K: C806E00000004002/0x2 (20170303/hwvalid-155) >[ 0.594351] ACPI Exception: AE_LIMIT, Unable to initialize fixed events (20170303/evevent-88) >[ 0.597858] ACPI: Unable to start the ACPI Interpreter >[ 0.599162] ACPI Error: Could not remove SCI handler (20170303/evmisc-281) >[ 0.601836] kmem_cache_destroy Acpi-Operand: Slab cache still has objects >[ 0.603556] CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.12.0-rc5 #26 >[ 0.605159] Hardware name: innotek GmbH VirtualBox/VirtualBox, BIOS VirtualBox 12/01/2006 >[ 0.609177] Call Trace: >[ 0.610063] ? dump_stack+0x5c/0x81 >[ 0.611118] ? kmem_cache_destroy+0x1aa/0x1c0 >[ 0.612632] ? acpi_sleep_proc_init+0x27/0x27 >[ 0.613906] ? acpi_os_delete_cache+0xa/0x10 >[ 0.617986] ? acpi_ut_delete_caches+0x3f/0x7b >[ 0.619293] ? acpi_terminate+0xa/0x14 >[ 0.620394] ? acpi_init+0x2af/0x34f >[ 0.621616] ? __class_create+0x4c/0x80 >[ 0.623412] ? video_setup+0x7f/0x7f >[ 0.624585] ? acpi_sleep_proc_init+0x27/0x27 >[ 0.625861] ? do_one_initcall+0x4e/0x1a0 >[ 0.627513] ? kernel_init_freeable+0x19e/0x21f >[ 0.628972] ? rest_init+0x80/0x80 >[ 0.630043] ? kernel_init+0xa/0x100 >[ 0.631084] ? ret_from_fork+0x25/0x30 >[ 0.633343] vgaarb: loaded >[ 0.635036] EDAC MC: Ver: 3.0.0 >[ 0.638601] PCI: Probing PCI hardware >[ 0.639833] PCI host bridge to bus 0000:00 >[ 0.641031] pci_bus 0000:00: root bus resource [io 0x0000-0xffff] > ... Continue to boot and log is omitted ... I analyzed this memory leak in detail and found acpi_ds_obj_stack_pop_and_ delete() function miscalculated the top of the stack. acpi_ds_obj_stack_push() function uses walk_state->operand_index for start position of the top, but acpi_ds_obj_stack_pop_and_delete() function considers index 0 for it. Therefore, this causes acpi operand memory leak. This cache leak causes a security threat because an old kernel (<= 4.9) shows memory locations of kernel functions in stack dump. Some malicious users could use this information to neutralize kernel ASLR. I made a patch to fix ACPI operand cache leak. Signed-off-by: Seunghun Han <[email protected]>
Medium
167,788
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate, ExceptionInfo *exception) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t i; size_t count, length; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } Vulnerability Type: CWE ID: CWE-787 Summary: coders/psd.c in ImageMagick allows remote attackers to have unspecified impact via a crafted PSD file, which triggers an out-of-bounds write. Commit Message: https://github.com/ImageMagick/ImageMagick/issues/348
Medium
168,402
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static struct dst_entry *inet6_csk_route_socket(struct sock *sk, struct flowi6 *fl6) { struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *final_p, final; struct dst_entry *dst; memset(fl6, 0, sizeof(*fl6)); fl6->flowi6_proto = sk->sk_protocol; fl6->daddr = sk->sk_v6_daddr; fl6->saddr = np->saddr; fl6->flowlabel = np->flow_label; IP6_ECN_flow_xmit(sk, fl6->flowlabel); fl6->flowi6_oif = sk->sk_bound_dev_if; fl6->flowi6_mark = sk->sk_mark; fl6->fl6_sport = inet->inet_sport; fl6->fl6_dport = inet->inet_dport; security_sk_classify_flow(sk, flowi6_to_flowi(fl6)); final_p = fl6_update_dst(fl6, np->opt, &final); dst = __inet6_csk_dst_check(sk, np->dst_cookie); if (!dst) { dst = ip6_dst_lookup_flow(sk, fl6, final_p); if (!IS_ERR(dst)) __inet6_csk_dst_store(sk, dst, NULL, NULL); } return dst; } Vulnerability Type: DoS +Priv CWE ID: CWE-416 Summary: The IPv6 stack in the Linux kernel before 4.3.3 mishandles options data, which allows local users to gain privileges or cause a denial of service (use-after-free and system crash) via a crafted sendmsg system call. Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]>
High
167,333
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static int snd_compr_allocate_buffer(struct snd_compr_stream *stream, struct snd_compr_params *params) { unsigned int buffer_size; void *buffer; buffer_size = params->buffer.fragment_size * params->buffer.fragments; if (stream->ops->copy) { buffer = NULL; /* if copy is defined the driver will be required to copy * the data from core */ } else { buffer = kmalloc(buffer_size, GFP_KERNEL); if (!buffer) return -ENOMEM; } stream->runtime->fragment_size = params->buffer.fragment_size; stream->runtime->fragments = params->buffer.fragments; stream->runtime->buffer = buffer; stream->runtime->buffer_size = buffer_size; return 0; } Vulnerability Type: DoS Overflow CWE ID: Summary: Integer overflow in the snd_compr_allocate_buffer function in sound/core/compress_offload.c in the ALSA subsystem in the Linux kernel before 3.6-rc6-next-20120917 allows local users to cause a denial of service (insufficient memory allocation) or possibly have unspecified other impact via a crafted SNDRV_COMPRESS_SET_PARAMS ioctl call. Commit Message: ALSA: compress_core: integer overflow in snd_compr_allocate_buffer() These are 32 bit values that come from the user, we need to check for integer overflows or we could end up allocating a smaller buffer than expected. Signed-off-by: Dan Carpenter <[email protected]> Signed-off-by: Takashi Iwai <[email protected]>
High
167,610
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void ResourceDispatcherHostImpl::OnReadCompleted(net::URLRequest* request, int bytes_read) { DCHECK(request); VLOG(1) << "OnReadCompleted: \"" << request->url().spec() << "\"" << " bytes_read = " << bytes_read; ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request); if (bytes_read == -1) { DCHECK(!request->status().is_success()); ResponseCompleted(request); return; } info->set_has_started_reading(true); if (PauseRequestIfNeeded(info)) { info->set_paused_read_bytes(bytes_read); VLOG(1) << "OnReadCompleted pausing: \"" << request->url().spec() << "\"" << " bytes_read = " << bytes_read; return; } if (request->status().is_success() && CompleteRead(request, &bytes_read)) { if (info->pause_count() == 0 && Read(request, &bytes_read) && request->status().is_success()) { if (bytes_read == 0) { CompleteRead(request, &bytes_read); } else { VLOG(1) << "OnReadCompleted postponing: \"" << request->url().spec() << "\"" << " bytes_read = " << bytes_read; info->set_paused_read_bytes(bytes_read); info->set_is_paused(true); GlobalRequestID id(info->GetChildID(), info->GetRequestID()); MessageLoop::current()->PostTask( FROM_HERE, base::Bind( &ResourceDispatcherHostImpl::ResumeRequest, weak_factory_.GetWeakPtr(), id)); return; } } } if (PauseRequestIfNeeded(info)) { info->set_paused_read_bytes(bytes_read); VLOG(1) << "OnReadCompleted (CompleteRead) pausing: \"" << request->url().spec() << "\"" << " bytes_read = " << bytes_read; return; } if (!request->status().is_io_pending()) ResponseCompleted(request); } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: The WebSockets implementation in Google Chrome before 19.0.1084.52 does not properly handle use of SSL, which allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via unspecified vectors. Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T> This change refines r137676. BUG=122654 TEST=browser_test Review URL: https://chromiumcodereview.appspot.com/10332233 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98
High
170,988
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: PluginModule::PluginModule(const std::string& name, const FilePath& path, PluginDelegate::ModuleLifetime* lifetime_delegate) : lifetime_delegate_(lifetime_delegate), callback_tracker_(new ::ppapi::CallbackTracker), is_in_destructor_(false), is_crashed_(false), broker_(NULL), library_(NULL), name_(name), path_(path), reserve_instance_id_(NULL), nacl_ipc_proxy_(false) { if (!host_globals) host_globals = new HostGlobals; memset(&entry_points_, 0, sizeof(entry_points_)); pp_module_ = HostGlobals::Get()->AddModule(this); GetMainThreadMessageLoop(); // Initialize the main thread message loop. GetLivePluginSet()->insert(this); } 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
170,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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void ChunkedUploadDataStream::AppendData( const char* data, int data_len, bool is_done) { DCHECK(!all_data_appended_); DCHECK(data_len > 0 || is_done); if (data_len > 0) { DCHECK(data); upload_data_.push_back( base::MakeUnique<std::vector<char>>(data, data + data_len)); } all_data_appended_ = is_done; if (!read_buffer_.get()) return; int result = ReadChunk(read_buffer_.get(), read_buffer_len_); DCHECK_GE(result, 0); read_buffer_ = NULL; read_buffer_len_ = 0; OnReadCompleted(result); } 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
173,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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void PostScript_MetaHandler::ParsePSFile() { bool found = false; IOBuffer ioBuf; XMP_IO* fileRef = this->parent->ioRef; XMP_AbortProc abortProc = this->parent->abortProc; void * abortArg = this->parent->abortArg; const bool checkAbort = (abortProc != 0); if ( ! PostScript_Support::IsValidPSFile(fileRef,this->fileformat) ) return ; fileRef->Rewind(); if ( ! CheckFileSpace ( fileRef, &ioBuf, 4 ) ) return ; XMP_Uns32 fileheader = GetUns32BE ( ioBuf.ptr ); if ( fileheader == 0xC5D0D3C6 ) { if ( ! CheckFileSpace ( fileRef, &ioBuf, 30 ) ) return ; XMP_Uns32 psOffset = GetUns32LE ( ioBuf.ptr+4 ); // PostScript offset. XMP_Uns32 psLength = GetUns32LE ( ioBuf.ptr+8 ); // PostScript length. setTokenInfo(kPS_EndPostScript,psOffset+psLength,0); MoveToOffset ( fileRef, psOffset, &ioBuf ); } while ( true ) { if ( checkAbort && abortProc(abortArg) ) { XMP_Throw ( "PostScript_MetaHandler::FindPostScriptHint - User abort", kXMPErr_UserAbort ); } if ( ! CheckFileSpace ( fileRef, &ioBuf, kPSContainsForString.length() ) ) return ; if ( (CheckFileSpace ( fileRef, &ioBuf, kPSEndCommentString.length() )&& CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSEndCommentString.c_str()), kPSEndCommentString.length() ) )|| *ioBuf.ptr!='%' || !(*(ioBuf.ptr+1)>32 && *(ioBuf.ptr+1)<=126 )) // implicit endcomment check { if (CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSEndCommentString.c_str()), kPSEndCommentString.length() )) { setTokenInfo(kPS_EndComments,ioBuf.filePos+ioBuf.ptr-ioBuf.data,kPSEndCommentString.length()); ioBuf.ptr+=kPSEndCommentString.length(); } else { setTokenInfo(kPS_EndComments,ioBuf.filePos+ioBuf.ptr-ioBuf.data,0); } while(true) { if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return ; if (! IsWhitespace (*ioBuf.ptr)) break; ++ioBuf.ptr; } while(true) { if ( ! CheckFileSpace ( fileRef, &ioBuf, 5 ) ) return ; if (CheckBytes ( ioBuf.ptr, Uns8Ptr("/DOCI"), 5 ) && CheckFileSpace ( fileRef, &ioBuf, kPSContainsDocInfoString.length() ) &&CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsDocInfoString.c_str()), kPSContainsDocInfoString.length() )) { ioBuf.ptr+=kPSContainsDocInfoString.length(); ExtractDocInfoDict(ioBuf); }// DOCINFO Not found in document else if(CheckBytes ( ioBuf.ptr, Uns8Ptr("%%Beg"), 5 )) {//possibly one of %%BeginProlog %%BeginSetup %%BeginBinary %%BeginData XMP_Int64 begStartpos=ioBuf.filePos+ioBuf.ptr-ioBuf.data; ioBuf.ptr+=5; if (!CheckFileSpace ( fileRef, &ioBuf, 6 )) return; if(CheckBytes ( ioBuf.ptr, Uns8Ptr("inProl"), 6 )) {//%%BeginProlog ioBuf.ptr+=6; if (!CheckFileSpace ( fileRef, &ioBuf, 2 ))return; if(CheckBytes ( ioBuf.ptr, Uns8Ptr("og"), 2 )) { ioBuf.ptr+=2; setTokenInfo(kPS_BeginProlog,begStartpos,13); } } else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("inSetu"), 6 )) {//%%BeginSetup ioBuf.ptr+=6; if (!CheckFileSpace ( fileRef, &ioBuf, 1 ))return; if(CheckBytes ( ioBuf.ptr, Uns8Ptr("p"), 1 )) { ioBuf.ptr+=1; setTokenInfo(kPS_BeginSetup,begStartpos,12); } } else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("inBina"), 6 )) {//%%BeginBinary ioBuf.ptr+=6; if (!CheckFileSpace ( fileRef, &ioBuf, 3 ))return; if(CheckBytes ( ioBuf.ptr, Uns8Ptr("ry"), 3 )) { ioBuf.ptr+=3; while(true) { if (!CheckFileSpace ( fileRef, &ioBuf, 12 ))return; if (CheckBytes ( ioBuf.ptr, Uns8Ptr("%%EndBinary"), 11 )) { ioBuf.ptr+=11; if (IsWhitespace(*ioBuf.ptr)) { ioBuf.ptr++; break; } } ++ioBuf.ptr; } } } else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("inData"), 6 )) {//%%BeginData ioBuf.ptr+=6; if (!CheckFileSpace ( fileRef, &ioBuf, 1 ))return; if(CheckBytes ( ioBuf.ptr, Uns8Ptr(":"), 1 )) { while(true) { if (!CheckFileSpace ( fileRef, &ioBuf, 10 ))return; if (CheckBytes ( ioBuf.ptr, Uns8Ptr("%%EndData"), 9 )) { ioBuf.ptr+=9; if (IsWhitespace(*ioBuf.ptr)) { ioBuf.ptr++; break; } } ++ioBuf.ptr; } } } else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("inDocu"), 6 )) {// %%BeginDocument ioBuf.ptr+=6; if (!CheckFileSpace ( fileRef, &ioBuf, 5 ))return; if(CheckBytes ( ioBuf.ptr, Uns8Ptr("ment:"), 5 )) { ioBuf.ptr+=5; while(true) { if (!CheckFileSpace ( fileRef, &ioBuf, 14 ))return; if (CheckBytes ( ioBuf.ptr, Uns8Ptr("%%EndDocument"), 13 )) { ioBuf.ptr+=13; if (IsWhitespace(*ioBuf.ptr)) { ioBuf.ptr++; break; } } ++ioBuf.ptr; } } } else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("inPage"), 6 )) {// %%BeginPageSetup ioBuf.ptr+=6; if (!CheckFileSpace ( fileRef, &ioBuf, 5 ))return; if(CheckBytes ( ioBuf.ptr, Uns8Ptr("Setup"), 5 )) { ioBuf.ptr+=5; setTokenInfo(kPS_BeginPageSetup,begStartpos,16); } } } else if(CheckBytes ( ioBuf.ptr, Uns8Ptr("%%End"), 5 )) {//possibly %%EndProlog %%EndSetup %%EndPageSetup %%EndPageComments XMP_Int64 begStartpos=ioBuf.filePos+ioBuf.ptr-ioBuf.data; ioBuf.ptr+=5; if ( ! CheckFileSpace ( fileRef, &ioBuf, 5 ) ) return ; if (CheckBytes ( ioBuf.ptr, Uns8Ptr("Prolo"), 5 )) {// %%EndProlog ioBuf.ptr+=5; if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return ; if (CheckBytes ( ioBuf.ptr, Uns8Ptr("g"), 1 )) { ioBuf.ptr+=1; setTokenInfo(kPS_EndProlog,begStartpos,11); } } else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("Setup"), 5 )) {//%%EndSetup ioBuf.ptr+=5; setTokenInfo(kPS_EndSetup,begStartpos,10); } else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("PageS"), 5 )) {//%%EndPageSetup ioBuf.ptr+=5; if ( ! CheckFileSpace ( fileRef, &ioBuf, 4 ) ) return ; if (CheckBytes ( ioBuf.ptr, Uns8Ptr("etup"), 4 )) { ioBuf.ptr+=4; setTokenInfo(kPS_EndPageSetup,begStartpos,14); } } else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("PageC"), 5 )) {//%%EndPageComments ioBuf.ptr+=5; if ( ! CheckFileSpace ( fileRef, &ioBuf, 7 ) ) return ; if (CheckBytes ( ioBuf.ptr, Uns8Ptr("omments"), 7 )) { ioBuf.ptr+=7; setTokenInfo(kPS_EndPageComments,begStartpos,17); } } } else if(CheckBytes ( ioBuf.ptr, Uns8Ptr("%%Pag"), 5 )) { XMP_Int64 begStartpos=ioBuf.filePos+ioBuf.ptr-ioBuf.data; ioBuf.ptr+=5; if ( ! CheckFileSpace ( fileRef, &ioBuf, 2 ) ) return ; if (CheckBytes ( ioBuf.ptr, Uns8Ptr(":"), 2 )) { ioBuf.ptr+=2; while(!IsNewline(*ioBuf.ptr)) { if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return ; ++ioBuf.ptr; } setTokenInfo(kPS_Page,begStartpos,ioBuf.filePos+ioBuf.ptr-ioBuf.data-begStartpos); } } else if(CheckBytes ( ioBuf.ptr, Uns8Ptr("%%Tra"), 5 )) { XMP_Int64 begStartpos=ioBuf.filePos+ioBuf.ptr-ioBuf.data; ioBuf.ptr+=5; if ( ! CheckFileSpace ( fileRef, &ioBuf, 4 ) ) return ; if (CheckBytes ( ioBuf.ptr, Uns8Ptr("iler"), 4 )) { ioBuf.ptr+=4; while(!IsNewline(*ioBuf.ptr)) ++ioBuf.ptr; setTokenInfo(kPS_Trailer,begStartpos,ioBuf.filePos+ioBuf.ptr-ioBuf.data-begStartpos); } } ioBuf.ptr+=5; setTokenInfo(kPS_EOF,ioBuf.filePos+ioBuf.ptr-ioBuf.data,5); } if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return ; ++ioBuf.ptr; } return; }else if (!(kPS_Creator & dscFlags) && CheckFileSpace ( fileRef, &ioBuf, kPSContainsForString.length() )&& CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsForString.c_str()), kPSContainsForString.length() )) { ioBuf.ptr+=kPSContainsForString.length(); if ( ! ExtractDSCCommentValue(ioBuf,kPS_dscFor) ) return ; } else if (!(kPS_CreatorTool & dscFlags) && CheckFileSpace ( fileRef, &ioBuf, kPSContainsCreatorString.length() )&& CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsCreatorString.c_str()), kPSContainsCreatorString.length() )) { ioBuf.ptr+=kPSContainsCreatorString.length(); if ( ! ExtractDSCCommentValue(ioBuf,kPS_dscCreator) ) return ; } else if (!(kPS_CreateDate & dscFlags) && CheckFileSpace ( fileRef, &ioBuf, kPSContainsCreateDateString.length() )&& CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsCreateDateString.c_str()), kPSContainsCreateDateString.length() )) { ioBuf.ptr+=kPSContainsCreateDateString.length(); if ( ! ExtractDSCCommentValue(ioBuf,kPS_dscCreateDate) ) return ; } else if (!(kPS_Title & dscFlags) && CheckFileSpace ( fileRef, &ioBuf, kPSContainsTitleString.length() )&& CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsTitleString.c_str()), kPSContainsTitleString.length() )) { ioBuf.ptr+=kPSContainsTitleString.length(); if ( ! ExtractDSCCommentValue(ioBuf,kPS_dscTitle) ) return ; } else if( CheckFileSpace ( fileRef, &ioBuf, kPSContainsXMPString.length() )&& ( CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsXMPString.c_str()), kPSContainsXMPString.length() ) )) { XMP_Int64 containsXMPStartpos=ioBuf.filePos+ioBuf.ptr-ioBuf.data; ioBuf.ptr += kPSContainsXMPString.length(); ExtractContainsXMPHint(ioBuf,containsXMPStartpos); } // Found "%ADO_ContainsXMP:". if ( ! PostScript_Support::SkipUntilNewline(fileRef,ioBuf) ) return ; } // Outer marker loop. Vulnerability Type: CWE ID: CWE-125 Summary: An issue was discovered in Exempi through 2.4.4. There is a stack-based buffer over-read in the PostScript_MetaHandler::ParsePSFile() function in XMPFiles/source/FileHandlers/PostScript_Handler.cpp. Commit Message:
Medium
164,995
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: bool PlatformFontSkia::InitDefaultFont() { if (g_default_font.Get()) return true; bool success = false; std::string family = kFallbackFontFamilyName; int size_pixels = 12; int style = Font::NORMAL; Font::Weight weight = Font::Weight::NORMAL; FontRenderParams params; const SkiaFontDelegate* delegate = SkiaFontDelegate::instance(); if (delegate) { delegate->GetDefaultFontDescription(&family, &size_pixels, &style, &weight, &params); } else if (default_font_description_) { #if defined(OS_CHROMEOS) FontRenderParamsQuery query; CHECK(FontList::ParseDescription(*default_font_description_, &query.families, &query.style, &query.pixel_size, &query.weight)) << "Failed to parse font description " << *default_font_description_; params = gfx::GetFontRenderParams(query, &family); size_pixels = query.pixel_size; style = query.style; weight = query.weight; #else NOTREACHED(); #endif } sk_sp<SkTypeface> typeface = CreateSkTypeface(style & Font::ITALIC, weight, &family, &success); if (!success) return false; g_default_font.Get() = new PlatformFontSkia( std::move(typeface), family, size_pixels, style, weight, params); return true; } Vulnerability Type: CWE ID: CWE-862 Summary: Allowing the chrome.debugger API to run on file:// URLs in DevTools in Google Chrome prior to 69.0.3497.81 allowed an attacker who convinced a user to install a malicious extension to access files on the local file system without file access permission via a crafted Chrome Extension. Commit Message: Take default system font size from PlatformFont The default font returned by Skia should take the initial size from the default value kDefaultBaseFontSize specified in PlatformFont. [email protected], [email protected] [email protected] Bug: 944227 Change-Id: I6b230b80c349abbe5968edb3cebdd6e89db4c4a6 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1642738 Reviewed-by: Robert Liao <[email protected]> Reviewed-by: Alexei Svitkine <[email protected]> Commit-Queue: Etienne Bergeron <[email protected]> Cr-Commit-Position: refs/heads/master@{#666299}
Medium
173,209
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void Huff_offsetReceive (node_t *node, int *ch, byte *fin, int *offset) { bloc = *offset; while (node && node->symbol == INTERNAL_NODE) { if (get_bit(fin)) { node = node->right; } else { node = node->left; } } if (!node) { *ch = 0; return; } *ch = node->symbol; *offset = bloc; } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: Buffer overflow in ioquake3 before 2017-08-02 allows remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via a crafted packet. Commit Message: Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits Prevent reading past end of message in MSG_ReadBits. If read past end of msg->data buffer (16348 bytes) the engine could SEGFAULT. Make MSG_WriteBits use an exact buffer overflow check instead of possibly failing with a few bytes left.
High
167,994
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: dissect_usb_video_control_interface_descriptor(proto_tree *parent_tree, tvbuff_t *tvb, guint8 descriptor_len, packet_info *pinfo, usb_conv_info_t *usb_conv_info) { video_conv_info_t *video_conv_info = NULL; video_entity_t *entity = NULL; proto_item *item = NULL; proto_item *subtype_item = NULL; proto_tree *tree = NULL; guint8 entity_id = 0; guint16 terminal_type = 0; int offset = 0; guint8 subtype; subtype = tvb_get_guint8(tvb, offset+2); if (parent_tree) { const gchar *subtype_str; subtype_str = val_to_str_ext(subtype, &vc_if_descriptor_subtypes_ext, "Unknown (0x%x)"); tree = proto_tree_add_subtree_format(parent_tree, tvb, offset, descriptor_len, ett_descriptor_video_control, &item, "VIDEO CONTROL INTERFACE DESCRIPTOR [%s]", subtype_str); } /* Common fields */ dissect_usb_descriptor_header(tree, tvb, offset, &vid_descriptor_type_vals_ext); subtype_item = proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_subtype, tvb, offset+2, 1, ENC_LITTLE_ENDIAN); offset += 3; if (subtype == VC_HEADER) { guint8 num_vs_interfaces; proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_bcdUVC, tvb, offset, 2, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_ifdesc_wTotalLength, tvb, offset+2, 2, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_dwClockFrequency, tvb, offset+4, 4, ENC_LITTLE_ENDIAN); num_vs_interfaces = tvb_get_guint8(tvb, offset+8); proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_bInCollection, tvb, offset+8, 1, ENC_LITTLE_ENDIAN); if (num_vs_interfaces > 0) { proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_baInterfaceNr, tvb, offset+9, num_vs_interfaces, ENC_NA); } offset += 9 + num_vs_interfaces; } else if ((subtype == VC_INPUT_TERMINAL) || (subtype == VC_OUTPUT_TERMINAL)) { /* Fields common to input and output terminals */ entity_id = tvb_get_guint8(tvb, offset); terminal_type = tvb_get_letohs(tvb, offset+1); proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_terminal_id, tvb, offset, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_terminal_type, tvb, offset+1, 2, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_assoc_terminal, tvb, offset+3, 1, ENC_LITTLE_ENDIAN); offset += 4; if (subtype == VC_OUTPUT_TERMINAL) { proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_src_id, tvb, offset, 1, ENC_LITTLE_ENDIAN); ++offset; } proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_iTerminal, tvb, offset, 1, ENC_LITTLE_ENDIAN); ++offset; if (subtype == VC_INPUT_TERMINAL) { if (terminal_type == ITT_CAMERA) { offset = dissect_usb_video_camera_terminal(tree, tvb, offset); } else if (terminal_type == ITT_MEDIA_TRANSPORT_INPUT) { /* @todo */ } } if (subtype == VC_OUTPUT_TERMINAL) { if (terminal_type == OTT_MEDIA_TRANSPORT_OUTPUT) { /* @todo */ } } } else { /* Field common to extension / processing / selector / encoding units */ entity_id = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_usb_vid_control_ifdesc_unit_id, tvb, offset, 1, ENC_LITTLE_ENDIAN); ++offset; if (subtype == VC_PROCESSING_UNIT) { offset = dissect_usb_video_processing_unit(tree, tvb, offset); } else if (subtype == VC_SELECTOR_UNIT) { offset = dissect_usb_video_selector_unit(tree, tvb, offset); } else if (subtype == VC_EXTENSION_UNIT) { offset = dissect_usb_video_extension_unit(tree, tvb, offset); } else if (subtype == VC_ENCODING_UNIT) { /* @todo UVC 1.5 */ } else { expert_add_info_format(pinfo, subtype_item, &ei_usb_vid_subtype_unknown, "Unknown VC subtype %u", subtype); } } /* Soak up descriptor bytes beyond those we know how to dissect */ if (offset < descriptor_len) { proto_tree_add_item(tree, hf_usb_vid_descriptor_data, tvb, offset, descriptor_len-offset, ENC_NA); /* offset = descriptor_len; */ } if (entity_id != 0) proto_item_append_text(item, " (Entity %d)", entity_id); if (subtype != VC_HEADER && usb_conv_info) { /* Switch to the usb_conv_info of the Video Control interface */ usb_conv_info = get_usb_iface_conv_info(pinfo, usb_conv_info->interfaceNum); video_conv_info = (video_conv_info_t *)usb_conv_info->class_data; if (!video_conv_info) { video_conv_info = wmem_new(wmem_file_scope(), video_conv_info_t); video_conv_info->entities = wmem_tree_new(wmem_file_scope()); usb_conv_info->class_data = video_conv_info; } entity = (video_entity_t*) wmem_tree_lookup32(video_conv_info->entities, entity_id); if (!entity) { entity = wmem_new(wmem_file_scope(), video_entity_t); entity->entityID = entity_id; entity->subtype = subtype; entity->terminalType = terminal_type; wmem_tree_insert32(video_conv_info->entities, entity_id, entity); } } return descriptor_len; } Vulnerability Type: DoS CWE ID: CWE-476 Summary: The USB subsystem in Wireshark 1.12.x before 1.12.12 and 2.x before 2.0.4 mishandles class types, which allows remote attackers to cause a denial of service (application crash) via a crafted packet. Commit Message: Make class "type" for USB conversations. USB dissectors can't assume that only their class type has been passed around in the conversation. Make explicit check that class type expected matches the dissector and stop/prevent dissection if there isn't a match. Bug: 12356 Change-Id: Ib23973a4ebd0fbb51952ffc118daf95e3389a209 Reviewed-on: https://code.wireshark.org/review/15212 Petri-Dish: Michael Mann <[email protected]> Reviewed-by: Martin Kaiser <[email protected]> Petri-Dish: Martin Kaiser <[email protected]> Tested-by: Petri Dish Buildbot <[email protected]> Reviewed-by: Michael Mann <[email protected]>
Medium
167,155
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: ServiceManagerContext::ServiceManagerContext() { service_manager::mojom::ServiceRequest packaged_services_request; if (service_manager::ServiceManagerIsRemote()) { auto invitation = mojo::edk::IncomingBrokerClientInvitation::AcceptFromCommandLine( mojo::edk::TransportProtocol::kLegacy); packaged_services_request = service_manager::GetServiceRequestFromCommandLine(invitation.get()); } else { std::unique_ptr<BuiltinManifestProvider> manifest_provider = base::MakeUnique<BuiltinManifestProvider>(); static const struct ManifestInfo { const char* name; int resource_id; } kManifests[] = { {mojom::kBrowserServiceName, IDR_MOJO_CONTENT_BROWSER_MANIFEST}, {mojom::kGpuServiceName, IDR_MOJO_CONTENT_GPU_MANIFEST}, {mojom::kPackagedServicesServiceName, IDR_MOJO_CONTENT_PACKAGED_SERVICES_MANIFEST}, {mojom::kPluginServiceName, IDR_MOJO_CONTENT_PLUGIN_MANIFEST}, {mojom::kRendererServiceName, IDR_MOJO_CONTENT_RENDERER_MANIFEST}, {mojom::kUtilityServiceName, IDR_MOJO_CONTENT_UTILITY_MANIFEST}, {catalog::mojom::kServiceName, IDR_MOJO_CATALOG_MANIFEST}, }; for (size_t i = 0; i < arraysize(kManifests); ++i) { manifest_provider->AddServiceManifest(kManifests[i].name, kManifests[i].resource_id); } for (const auto& manifest : GetContentClient()->browser()->GetExtraServiceManifests()) { manifest_provider->AddServiceManifest(manifest.name, manifest.resource_id); } in_process_context_ = new InProcessServiceManagerContext; service_manager::mojom::ServicePtr packaged_services_service; packaged_services_request = mojo::MakeRequest(&packaged_services_service); in_process_context_->Start(packaged_services_service.PassInterface(), std::move(manifest_provider)); } packaged_services_connection_ = ServiceManagerConnection::Create( std::move(packaged_services_request), BrowserThread::GetTaskRunnerForThread(BrowserThread::IO)); service_manager::mojom::ServicePtr root_browser_service; ServiceManagerConnection::SetForProcess(ServiceManagerConnection::Create( mojo::MakeRequest(&root_browser_service), BrowserThread::GetTaskRunnerForThread(BrowserThread::IO))); auto* browser_connection = ServiceManagerConnection::GetForProcess(); service_manager::mojom::PIDReceiverPtr pid_receiver; packaged_services_connection_->GetConnector()->StartService( service_manager::Identity(mojom::kBrowserServiceName, service_manager::mojom::kRootUserID), std::move(root_browser_service), mojo::MakeRequest(&pid_receiver)); pid_receiver->SetPID(base::GetCurrentProcId()); service_manager::EmbeddedServiceInfo device_info; #if defined(OS_ANDROID) JNIEnv* env = base::android::AttachCurrentThread(); base::android::ScopedJavaGlobalRef<jobject> java_nfc_delegate; java_nfc_delegate.Reset(Java_ContentNfcDelegate_create(env)); DCHECK(!java_nfc_delegate.is_null()); device_info.factory = base::Bind(&device::CreateDeviceService, BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE), BrowserThread::GetTaskRunnerForThread(BrowserThread::IO), base::Bind(&WakeLockContextHost::GetNativeViewForContext), std::move(java_nfc_delegate)); #else device_info.factory = base::Bind(&device::CreateDeviceService, BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE), BrowserThread::GetTaskRunnerForThread(BrowserThread::IO)); #endif device_info.task_runner = base::ThreadTaskRunnerHandle::Get(); packaged_services_connection_->AddEmbeddedService(device::mojom::kServiceName, device_info); if (base::FeatureList::IsEnabled(features::kGlobalResourceCoordinator)) { service_manager::EmbeddedServiceInfo resource_coordinator_info; resource_coordinator_info.factory = base::Bind(&resource_coordinator::ResourceCoordinatorService::Create); packaged_services_connection_->AddEmbeddedService( resource_coordinator::mojom::kServiceName, resource_coordinator_info); } ContentBrowserClient::StaticServiceMap services; GetContentClient()->browser()->RegisterInProcessServices(&services); for (const auto& entry : services) { packaged_services_connection_->AddEmbeddedService(entry.first, entry.second); } g_io_thread_connector.Get() = browser_connection->GetConnector()->Clone(); ContentBrowserClient::OutOfProcessServiceMap out_of_process_services; GetContentClient()->browser()->RegisterOutOfProcessServices( &out_of_process_services); out_of_process_services[data_decoder::mojom::kServiceName] = { base::ASCIIToUTF16("Data Decoder Service"), SANDBOX_TYPE_UTILITY}; bool network_service_enabled = base::FeatureList::IsEnabled(features::kNetworkService); if (network_service_enabled) { out_of_process_services[content::mojom::kNetworkServiceName] = { base::ASCIIToUTF16("Network Service"), SANDBOX_TYPE_NETWORK}; } if (base::FeatureList::IsEnabled(video_capture::kMojoVideoCapture)) { out_of_process_services[video_capture::mojom::kServiceName] = { base::ASCIIToUTF16("Video Capture Service"), SANDBOX_TYPE_NO_SANDBOX}; } #if BUILDFLAG(ENABLE_MOJO_MEDIA_IN_UTILITY_PROCESS) out_of_process_services[media::mojom::kMediaServiceName] = { base::ASCIIToUTF16("Media Service"), SANDBOX_TYPE_NO_SANDBOX}; #endif for (const auto& service : out_of_process_services) { packaged_services_connection_->AddServiceRequestHandler( service.first, base::Bind(&StartServiceInUtilityProcess, service.first, service.second.first, service.second.second)); } #if BUILDFLAG(ENABLE_MOJO_MEDIA_IN_GPU_PROCESS) packaged_services_connection_->AddServiceRequestHandler( media::mojom::kMediaServiceName, base::Bind(&StartServiceInGpuProcess, media::mojom::kMediaServiceName)); #endif packaged_services_connection_->AddServiceRequestHandler( shape_detection::mojom::kServiceName, base::Bind(&StartServiceInGpuProcess, shape_detection::mojom::kServiceName)); packaged_services_connection_->Start(); RegisterCommonBrowserInterfaces(browser_connection); browser_connection->Start(); if (network_service_enabled) { browser_connection->GetConnector()->StartService( mojom::kNetworkServiceName); } } Vulnerability Type: DoS Overflow Mem. Corr. CWE ID: CWE-119 Summary: SkPictureShader.cpp in Skia, as used in Google Chrome before 44.0.2403.89, allows remote attackers to cause a denial of service (memory corruption) or possibly have unspecified other impact by leveraging access to a renderer process and providing crafted serialized data. Commit Message: media: Support hosting mojo CDM in a standalone service Currently when mojo CDM is enabled it is hosted in the MediaService running in the process specified by "mojo_media_host". However, on some platforms we need to run mojo CDM and other mojo media services in different processes. For example, on desktop platforms, we want to run mojo video decoder in the GPU process, but run the mojo CDM in the utility process. This CL adds a new build flag "enable_standalone_cdm_service". When enabled, the mojo CDM service will be hosted in a standalone "cdm" service running in the utility process. All other mojo media services will sill be hosted in the "media" servie running in the process specified by "mojo_media_host". BUG=664364 TEST=Encrypted media browser tests using mojo CDM is still working. Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487 Reviewed-on: https://chromium-review.googlesource.com/567172 Commit-Queue: Xiaohan Wang <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Dan Sanders <[email protected]> Cr-Commit-Position: refs/heads/master@{#486947}
High
171,939
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: int snd_ctl_replace(struct snd_card *card, struct snd_kcontrol *kcontrol, bool add_on_replace) { struct snd_ctl_elem_id id; unsigned int idx; struct snd_kcontrol *old; int ret; if (!kcontrol) return -EINVAL; if (snd_BUG_ON(!card || !kcontrol->info)) { ret = -EINVAL; goto error; } id = kcontrol->id; down_write(&card->controls_rwsem); old = snd_ctl_find_id(card, &id); if (!old) { if (add_on_replace) goto add; up_write(&card->controls_rwsem); ret = -EINVAL; goto error; } ret = snd_ctl_remove(card, old); if (ret < 0) { up_write(&card->controls_rwsem); goto error; } add: if (snd_ctl_find_hole(card, kcontrol->count) < 0) { up_write(&card->controls_rwsem); ret = -ENOMEM; goto error; } list_add_tail(&kcontrol->list, &card->controls); card->controls_count += kcontrol->count; kcontrol->id.numid = card->last_numid + 1; card->last_numid += kcontrol->count; up_write(&card->controls_rwsem); for (idx = 0; idx < kcontrol->count; idx++, id.index++, id.numid++) snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_ADD, &id); return 0; error: snd_ctl_free_one(kcontrol); return ret; } Vulnerability Type: DoS +Info CWE ID: Summary: sound/core/control.c in the ALSA control implementation in the Linux kernel before 3.15.2 does not ensure possession of a read/write lock, which allows local users to cause a denial of service (use-after-free) and obtain sensitive information from kernel memory by leveraging /dev/snd/controlCX access. Commit Message: ALSA: control: Don't access controls outside of protected regions A control that is visible on the card->controls list can be freed at any time. This means we must not access any of its memory while not holding the controls_rw_lock. Otherwise we risk a use after free access. Signed-off-by: Lars-Peter Clausen <[email protected]> Acked-by: Jaroslav Kysela <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]>
Medium
166,294
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: image_pixel_setf(image_pixel *this, unsigned int max) { this->redf = this->red / (double)max; this->greenf = this->green / (double)max; this->bluef = this->blue / (double)max; this->alphaf = this->alpha / (double)max; if (this->red < max) this->rede = this->redf * DBL_EPSILON; else this->rede = 0; if (this->green < max) this->greene = this->greenf * DBL_EPSILON; else this->greene = 0; if (this->blue < max) this->bluee = this->bluef * DBL_EPSILON; else this->bluee = 0; if (this->alpha < max) this->alphae = this->alphaf * DBL_EPSILON; else this->alphae = 0; } 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
173,618
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static int intel_pmu_drain_bts_buffer(void) { struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events); struct debug_store *ds = cpuc->ds; struct bts_record { u64 from; u64 to; u64 flags; }; struct perf_event *event = cpuc->events[X86_PMC_IDX_FIXED_BTS]; struct bts_record *at, *top; struct perf_output_handle handle; struct perf_event_header header; struct perf_sample_data data; struct pt_regs regs; if (!event) return 0; if (!x86_pmu.bts_active) return 0; at = (struct bts_record *)(unsigned long)ds->bts_buffer_base; top = (struct bts_record *)(unsigned long)ds->bts_index; if (top <= at) return 0; ds->bts_index = ds->bts_buffer_base; perf_sample_data_init(&data, 0); data.period = event->hw.last_period; regs.ip = 0; /* * Prepare a generic sample, i.e. fill in the invariant fields. * We will overwrite the from and to address before we output * the sample. */ perf_prepare_sample(&header, &data, event, &regs); if (perf_output_begin(&handle, event, header.size * (top - at), 1, 1)) return 1; for (; at < top; at++) { data.ip = at->from; data.addr = at->to; perf_output_sample(&handle, &header, &data, event); } perf_output_end(&handle); /* There's new data available. */ event->hw.interrupts++; event->pending_kill = POLL_IN; return 1; } Vulnerability Type: DoS Overflow CWE ID: CWE-399 Summary: The Performance Events subsystem in the Linux kernel before 3.1 does not properly handle event overflows associated with PERF_COUNT_SW_CPU_CLOCK events, which allows local users to cause a denial of service (system hang) via a crafted application. Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]>
Medium
165,821
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: status_t MyOpusExtractor::readNextPacket(MediaBuffer **out) { if (mOffset <= mFirstDataOffset && mStartGranulePosition < 0) { MediaBuffer *mBuf; uint32_t numSamples = 0; uint64_t curGranulePosition = 0; while (true) { status_t err = _readNextPacket(&mBuf, /* calcVorbisTimestamp = */false); if (err != OK && err != ERROR_END_OF_STREAM) { return err; } if (err == ERROR_END_OF_STREAM || mCurrentPage.mPageNo > 2) { break; } curGranulePosition = mCurrentPage.mGranulePosition; numSamples += getNumSamplesInPacket(mBuf); mBuf->release(); mBuf = NULL; } if (curGranulePosition > numSamples) { mStartGranulePosition = curGranulePosition - numSamples; } else { mStartGranulePosition = 0; } seekToOffset(0); } status_t err = _readNextPacket(out, /* calcVorbisTimestamp = */false); if (err != OK) { return err; } int32_t currentPageSamples; if ((*out)->meta_data()->findInt32(kKeyValidSamples, &currentPageSamples)) { if (mOffset == mFirstDataOffset) { currentPageSamples -= mStartGranulePosition; (*out)->meta_data()->setInt32(kKeyValidSamples, currentPageSamples); } mCurGranulePosition = mCurrentPage.mGranulePosition - currentPageSamples; } int64_t timeUs = getTimeUsOfGranule(mCurGranulePosition); (*out)->meta_data()->setInt64(kKeyTime, timeUs); uint32_t frames = getNumSamplesInPacket(*out); mCurGranulePosition += frames; return OK; } Vulnerability Type: CWE ID: CWE-772 Summary: A vulnerability in the Android media framework (n/a). Product: Android. Versions: 7.0, 7.1.1, 7.1.2, 8.0. Android ID: A-63581671. Commit Message: Fix memory leak in OggExtractor Test: added a temporal log and run poc Bug: 63581671 Change-Id: I436a08e54d5e831f9fbdb33c26d15397ce1fbeba (cherry picked from commit 63079e7c8e12cda4eb124fbe565213d30b9ea34c)
High
173,976
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: int x86_decode_insn(struct x86_emulate_ctxt *ctxt, void *insn, int insn_len) { int rc = X86EMUL_CONTINUE; int mode = ctxt->mode; int def_op_bytes, def_ad_bytes, goffset, simd_prefix; bool op_prefix = false; bool has_seg_override = false; struct opcode opcode; ctxt->memop.type = OP_NONE; ctxt->memopp = NULL; ctxt->_eip = ctxt->eip; ctxt->fetch.ptr = ctxt->fetch.data; ctxt->fetch.end = ctxt->fetch.data + insn_len; ctxt->opcode_len = 1; if (insn_len > 0) memcpy(ctxt->fetch.data, insn, insn_len); else { rc = __do_insn_fetch_bytes(ctxt, 1); if (rc != X86EMUL_CONTINUE) return rc; } switch (mode) { case X86EMUL_MODE_REAL: case X86EMUL_MODE_VM86: case X86EMUL_MODE_PROT16: def_op_bytes = def_ad_bytes = 2; break; case X86EMUL_MODE_PROT32: def_op_bytes = def_ad_bytes = 4; break; #ifdef CONFIG_X86_64 case X86EMUL_MODE_PROT64: def_op_bytes = 4; def_ad_bytes = 8; break; #endif default: return EMULATION_FAILED; } ctxt->op_bytes = def_op_bytes; ctxt->ad_bytes = def_ad_bytes; /* Legacy prefixes. */ for (;;) { switch (ctxt->b = insn_fetch(u8, ctxt)) { case 0x66: /* operand-size override */ op_prefix = true; /* switch between 2/4 bytes */ ctxt->op_bytes = def_op_bytes ^ 6; break; case 0x67: /* address-size override */ if (mode == X86EMUL_MODE_PROT64) /* switch between 4/8 bytes */ ctxt->ad_bytes = def_ad_bytes ^ 12; else /* switch between 2/4 bytes */ ctxt->ad_bytes = def_ad_bytes ^ 6; break; case 0x26: /* ES override */ case 0x2e: /* CS override */ case 0x36: /* SS override */ case 0x3e: /* DS override */ has_seg_override = true; ctxt->seg_override = (ctxt->b >> 3) & 3; break; case 0x64: /* FS override */ case 0x65: /* GS override */ has_seg_override = true; ctxt->seg_override = ctxt->b & 7; break; case 0x40 ... 0x4f: /* REX */ if (mode != X86EMUL_MODE_PROT64) goto done_prefixes; ctxt->rex_prefix = ctxt->b; continue; case 0xf0: /* LOCK */ ctxt->lock_prefix = 1; break; case 0xf2: /* REPNE/REPNZ */ case 0xf3: /* REP/REPE/REPZ */ ctxt->rep_prefix = ctxt->b; break; default: goto done_prefixes; } /* Any legacy prefix after a REX prefix nullifies its effect. */ ctxt->rex_prefix = 0; } done_prefixes: /* REX prefix. */ if (ctxt->rex_prefix & 8) ctxt->op_bytes = 8; /* REX.W */ /* Opcode byte(s). */ opcode = opcode_table[ctxt->b]; /* Two-byte opcode? */ if (ctxt->b == 0x0f) { ctxt->opcode_len = 2; ctxt->b = insn_fetch(u8, ctxt); opcode = twobyte_table[ctxt->b]; /* 0F_38 opcode map */ if (ctxt->b == 0x38) { ctxt->opcode_len = 3; ctxt->b = insn_fetch(u8, ctxt); opcode = opcode_map_0f_38[ctxt->b]; } } ctxt->d = opcode.flags; if (ctxt->d & ModRM) ctxt->modrm = insn_fetch(u8, ctxt); /* vex-prefix instructions are not implemented */ if (ctxt->opcode_len == 1 && (ctxt->b == 0xc5 || ctxt->b == 0xc4) && (mode == X86EMUL_MODE_PROT64 || (mode >= X86EMUL_MODE_PROT16 && (ctxt->modrm & 0x80)))) { ctxt->d = NotImpl; } while (ctxt->d & GroupMask) { switch (ctxt->d & GroupMask) { case Group: goffset = (ctxt->modrm >> 3) & 7; opcode = opcode.u.group[goffset]; break; case GroupDual: goffset = (ctxt->modrm >> 3) & 7; if ((ctxt->modrm >> 6) == 3) opcode = opcode.u.gdual->mod3[goffset]; else opcode = opcode.u.gdual->mod012[goffset]; break; case RMExt: goffset = ctxt->modrm & 7; opcode = opcode.u.group[goffset]; break; case Prefix: if (ctxt->rep_prefix && op_prefix) return EMULATION_FAILED; simd_prefix = op_prefix ? 0x66 : ctxt->rep_prefix; switch (simd_prefix) { case 0x00: opcode = opcode.u.gprefix->pfx_no; break; case 0x66: opcode = opcode.u.gprefix->pfx_66; break; case 0xf2: opcode = opcode.u.gprefix->pfx_f2; break; case 0xf3: opcode = opcode.u.gprefix->pfx_f3; break; } break; case Escape: if (ctxt->modrm > 0xbf) opcode = opcode.u.esc->high[ctxt->modrm - 0xc0]; else opcode = opcode.u.esc->op[(ctxt->modrm >> 3) & 7]; break; default: return EMULATION_FAILED; } ctxt->d &= ~(u64)GroupMask; ctxt->d |= opcode.flags; } /* Unrecognised? */ if (ctxt->d == 0) return EMULATION_FAILED; ctxt->execute = opcode.u.execute; if (unlikely(ctxt->ud) && likely(!(ctxt->d & EmulateOnUD))) return EMULATION_FAILED; if (unlikely(ctxt->d & (NotImpl|Stack|Op3264|Sse|Mmx|Intercept|CheckPerm))) { /* * These are copied unconditionally here, and checked unconditionally * in x86_emulate_insn. */ ctxt->check_perm = opcode.check_perm; ctxt->intercept = opcode.intercept; if (ctxt->d & NotImpl) return EMULATION_FAILED; if (mode == X86EMUL_MODE_PROT64 && (ctxt->d & Stack)) ctxt->op_bytes = 8; if (ctxt->d & Op3264) { if (mode == X86EMUL_MODE_PROT64) ctxt->op_bytes = 8; else ctxt->op_bytes = 4; } if (ctxt->d & Sse) ctxt->op_bytes = 16; else if (ctxt->d & Mmx) ctxt->op_bytes = 8; } /* ModRM and SIB bytes. */ if (ctxt->d & ModRM) { rc = decode_modrm(ctxt, &ctxt->memop); if (!has_seg_override) { has_seg_override = true; ctxt->seg_override = ctxt->modrm_seg; } } else if (ctxt->d & MemAbs) rc = decode_abs(ctxt, &ctxt->memop); if (rc != X86EMUL_CONTINUE) goto done; if (!has_seg_override) ctxt->seg_override = VCPU_SREG_DS; ctxt->memop.addr.mem.seg = ctxt->seg_override; /* * Decode and fetch the source operand: register, memory * or immediate. */ rc = decode_operand(ctxt, &ctxt->src, (ctxt->d >> SrcShift) & OpMask); if (rc != X86EMUL_CONTINUE) goto done; /* * Decode and fetch the second source operand: register, memory * or immediate. */ rc = decode_operand(ctxt, &ctxt->src2, (ctxt->d >> Src2Shift) & OpMask); if (rc != X86EMUL_CONTINUE) goto done; /* Decode and fetch the destination operand: register or memory. */ rc = decode_operand(ctxt, &ctxt->dst, (ctxt->d >> DstShift) & OpMask); done: if (ctxt->rip_relative) ctxt->memopp->addr.mem.ea += ctxt->_eip; return (rc != X86EMUL_CONTINUE) ? EMULATION_FAILED : EMULATION_OK; } Vulnerability Type: DoS CWE ID: CWE-399 Summary: The instruction decoder in arch/x86/kvm/emulate.c in the KVM subsystem in the Linux kernel before 3.18-rc2 does not properly handle invalid instructions, which allows guest OS users to cause a denial of service (NULL pointer dereference and host OS crash) via a crafted application that triggers (1) an improperly fetched instruction or (2) an instruction that occupies too many bytes. NOTE: this vulnerability exists because of an incomplete fix for CVE-2014-8480. Commit Message: KVM: emulate: avoid accessing NULL ctxt->memopp A failure to decode the instruction can cause a NULL pointer access. This is fixed simply by moving the "done" label as close as possible to the return. This fixes CVE-2014-8481. Reported-by: Andy Lutomirski <[email protected]> Cc: [email protected] Fixes: 41061cdb98a0bec464278b4db8e894a3121671f5 Signed-off-by: Paolo Bonzini <[email protected]>
Medium
166,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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: bool SyncManager::Init( const FilePath& database_location, const WeakHandle<JsEventHandler>& event_handler, const std::string& sync_server_and_path, int sync_server_port, bool use_ssl, const scoped_refptr<base::TaskRunner>& blocking_task_runner, HttpPostProviderFactory* post_factory, ModelSafeWorkerRegistrar* registrar, browser_sync::ExtensionsActivityMonitor* extensions_activity_monitor, ChangeDelegate* change_delegate, const std::string& user_agent, const SyncCredentials& credentials, bool enable_sync_tabs_for_other_clients, sync_notifier::SyncNotifier* sync_notifier, const std::string& restored_key_for_bootstrapping, TestingMode testing_mode, Encryptor* encryptor, UnrecoverableErrorHandler* unrecoverable_error_handler, ReportUnrecoverableErrorFunction report_unrecoverable_error_function) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(post_factory); DVLOG(1) << "SyncManager starting Init..."; std::string server_string(sync_server_and_path); return data_->Init(database_location, event_handler, server_string, sync_server_port, use_ssl, blocking_task_runner, post_factory, registrar, extensions_activity_monitor, change_delegate, user_agent, credentials, enable_sync_tabs_for_other_clients, sync_notifier, restored_key_for_bootstrapping, testing_mode, encryptor, unrecoverable_error_handler, report_unrecoverable_error_function); } Vulnerability Type: DoS CWE ID: CWE-362 Summary: Race condition 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 related to the plug-in paint buffer. Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
High
170,792
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void buffer_slow_realign(struct buffer *buf) { /* two possible cases : * - the buffer is in one contiguous block, we move it in-place * - the buffer is in two blocks, we move it via the swap_buffer */ if (buf->i) { int block1 = buf->i; int block2 = 0; if (buf->p + buf->i > buf->data + buf->size) { /* non-contiguous block */ block1 = buf->data + buf->size - buf->p; block2 = buf->p + buf->i - (buf->data + buf->size); } if (block2) memcpy(swap_buffer, buf->data, block2); memmove(buf->data, buf->p, block1); if (block2) memcpy(buf->data + block1, swap_buffer, block2); } buf->p = buf->data; } Vulnerability Type: Overflow +Info CWE ID: CWE-119 Summary: The buffer_slow_realign function in HAProxy 1.5.x before 1.5.14 and 1.6-dev does not properly realign a buffer that is used for pending outgoing data, which allows remote attackers to obtain sensitive information (uninitialized memory contents of previous requests) via a crafted request. Commit Message:
Medium
164,714
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: status_t MPEG4Extractor::parseChunk(off64_t *offset, int depth) { ALOGV("entering parseChunk %lld/%d", (long long)*offset, depth); if (*offset < 0) { ALOGE("b/23540914"); return ERROR_MALFORMED; } if (depth > 100) { ALOGE("b/27456299"); return ERROR_MALFORMED; } uint32_t hdr[2]; if (mDataSource->readAt(*offset, hdr, 8) < 8) { return ERROR_IO; } uint64_t chunk_size = ntohl(hdr[0]); int32_t chunk_type = ntohl(hdr[1]); off64_t data_offset = *offset + 8; if (chunk_size == 1) { if (mDataSource->readAt(*offset + 8, &chunk_size, 8) < 8) { return ERROR_IO; } chunk_size = ntoh64(chunk_size); data_offset += 8; if (chunk_size < 16) { return ERROR_MALFORMED; } } else if (chunk_size == 0) { if (depth == 0) { off64_t sourceSize; if (mDataSource->getSize(&sourceSize) == OK) { chunk_size = (sourceSize - *offset); } else { ALOGE("atom size is 0, and data source has no size"); return ERROR_MALFORMED; } } else { *offset += 4; return OK; } } else if (chunk_size < 8) { ALOGE("invalid chunk size: %" PRIu64, chunk_size); return ERROR_MALFORMED; } char chunk[5]; MakeFourCCString(chunk_type, chunk); ALOGV("chunk: %s @ %lld, %d", chunk, (long long)*offset, depth); if (kUseHexDump) { static const char kWhitespace[] = " "; const char *indent = &kWhitespace[sizeof(kWhitespace) - 1 - 2 * depth]; printf("%sfound chunk '%s' of size %" PRIu64 "\n", indent, chunk, chunk_size); char buffer[256]; size_t n = chunk_size; if (n > sizeof(buffer)) { n = sizeof(buffer); } if (mDataSource->readAt(*offset, buffer, n) < (ssize_t)n) { return ERROR_IO; } hexdump(buffer, n); } PathAdder autoAdder(&mPath, chunk_type); off64_t chunk_data_size = chunk_size - (data_offset - *offset); if (chunk_data_size < 0) { ALOGE("b/23540914"); return ERROR_MALFORMED; } if (chunk_type != FOURCC('m', 'd', 'a', 't') && chunk_data_size > kMaxAtomSize) { char errMsg[100]; sprintf(errMsg, "%s atom has size %" PRId64, chunk, chunk_data_size); ALOGE("%s (b/28615448)", errMsg); android_errorWriteWithInfoLog(0x534e4554, "28615448", -1, errMsg, strlen(errMsg)); return ERROR_MALFORMED; } if (chunk_type != FOURCC('c', 'p', 'r', 't') && chunk_type != FOURCC('c', 'o', 'v', 'r') && mPath.size() == 5 && underMetaDataPath(mPath)) { off64_t stop_offset = *offset + chunk_size; *offset = data_offset; while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } return OK; } switch(chunk_type) { case FOURCC('m', 'o', 'o', 'v'): case FOURCC('t', 'r', 'a', 'k'): case FOURCC('m', 'd', 'i', 'a'): case FOURCC('m', 'i', 'n', 'f'): case FOURCC('d', 'i', 'n', 'f'): case FOURCC('s', 't', 'b', 'l'): case FOURCC('m', 'v', 'e', 'x'): case FOURCC('m', 'o', 'o', 'f'): case FOURCC('t', 'r', 'a', 'f'): case FOURCC('m', 'f', 'r', 'a'): case FOURCC('u', 'd', 't', 'a'): case FOURCC('i', 'l', 's', 't'): case FOURCC('s', 'i', 'n', 'f'): case FOURCC('s', 'c', 'h', 'i'): case FOURCC('e', 'd', 't', 's'): case FOURCC('w', 'a', 'v', 'e'): { if (chunk_type == FOURCC('m', 'o', 'o', 'v') && depth != 0) { ALOGE("moov: depth %d", depth); return ERROR_MALFORMED; } if (chunk_type == FOURCC('m', 'o', 'o', 'f') && !mMoofFound) { mMoofFound = true; mMoofOffset = *offset; } if (chunk_type == FOURCC('s', 't', 'b', 'l')) { ALOGV("sampleTable chunk is %" PRIu64 " bytes long.", chunk_size); if (mDataSource->flags() & (DataSource::kWantsPrefetching | DataSource::kIsCachingDataSource)) { sp<MPEG4DataSource> cachedSource = new MPEG4DataSource(mDataSource); if (cachedSource->setCachedRange(*offset, chunk_size) == OK) { mDataSource = cachedSource; } } if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->sampleTable = new SampleTable(mDataSource); } bool isTrack = false; if (chunk_type == FOURCC('t', 'r', 'a', 'k')) { if (depth != 1) { ALOGE("trak: depth %d", depth); return ERROR_MALFORMED; } isTrack = true; Track *track = new Track; track->next = NULL; if (mLastTrack) { mLastTrack->next = track; } else { mFirstTrack = track; } mLastTrack = track; track->meta = new MetaData; track->includes_expensive_metadata = false; track->skipTrack = false; track->timescale = 0; track->meta->setCString(kKeyMIMEType, "application/octet-stream"); } off64_t stop_offset = *offset + chunk_size; *offset = data_offset; while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { if (isTrack) { mLastTrack->skipTrack = true; break; } return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } if (isTrack) { int32_t trackId; if (!mLastTrack->meta->findInt32(kKeyTrackID, &trackId)) { mLastTrack->skipTrack = true; } if (mLastTrack->skipTrack) { Track *cur = mFirstTrack; if (cur == mLastTrack) { delete cur; mFirstTrack = mLastTrack = NULL; } else { while (cur && cur->next != mLastTrack) { cur = cur->next; } if (cur) { cur->next = NULL; } delete mLastTrack; mLastTrack = cur; } return OK; } status_t err = verifyTrack(mLastTrack); if (err != OK) { return err; } } else if (chunk_type == FOURCC('m', 'o', 'o', 'v')) { mInitCheck = OK; if (!mIsDrm) { return UNKNOWN_ERROR; // Return a dummy error. } else { return OK; } } break; } case FOURCC('e', 'l', 's', 't'): { *offset += chunk_size; uint8_t version; if (mDataSource->readAt(data_offset, &version, 1) < 1) { return ERROR_IO; } uint32_t entry_count; if (!mDataSource->getUInt32(data_offset + 4, &entry_count)) { return ERROR_IO; } if (entry_count != 1) { ALOGW("ignoring edit list with %d entries", entry_count); } else if (mHeaderTimescale == 0) { ALOGW("ignoring edit list because timescale is 0"); } else { off64_t entriesoffset = data_offset + 8; uint64_t segment_duration; int64_t media_time; if (version == 1) { if (!mDataSource->getUInt64(entriesoffset, &segment_duration) || !mDataSource->getUInt64(entriesoffset + 8, (uint64_t*)&media_time)) { return ERROR_IO; } } else if (version == 0) { uint32_t sd; int32_t mt; if (!mDataSource->getUInt32(entriesoffset, &sd) || !mDataSource->getUInt32(entriesoffset + 4, (uint32_t*)&mt)) { return ERROR_IO; } segment_duration = sd; media_time = mt; } else { return ERROR_IO; } uint64_t halfscale = mHeaderTimescale / 2; segment_duration = (segment_duration * 1000000 + halfscale)/ mHeaderTimescale; media_time = (media_time * 1000000 + halfscale) / mHeaderTimescale; int64_t duration; int32_t samplerate; if (!mLastTrack) { return ERROR_MALFORMED; } if (mLastTrack->meta->findInt64(kKeyDuration, &duration) && mLastTrack->meta->findInt32(kKeySampleRate, &samplerate)) { int64_t delay = (media_time * samplerate + 500000) / 1000000; mLastTrack->meta->setInt32(kKeyEncoderDelay, delay); int64_t paddingus = duration - (int64_t)(segment_duration + media_time); if (paddingus < 0) { paddingus = 0; } int64_t paddingsamples = (paddingus * samplerate + 500000) / 1000000; mLastTrack->meta->setInt32(kKeyEncoderPadding, paddingsamples); } } break; } case FOURCC('f', 'r', 'm', 'a'): { *offset += chunk_size; uint32_t original_fourcc; if (mDataSource->readAt(data_offset, &original_fourcc, 4) < 4) { return ERROR_IO; } original_fourcc = ntohl(original_fourcc); ALOGV("read original format: %d", original_fourcc); if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(original_fourcc)); uint32_t num_channels = 0; uint32_t sample_rate = 0; if (AdjustChannelsAndRate(original_fourcc, &num_channels, &sample_rate)) { mLastTrack->meta->setInt32(kKeyChannelCount, num_channels); mLastTrack->meta->setInt32(kKeySampleRate, sample_rate); } break; } case FOURCC('t', 'e', 'n', 'c'): { *offset += chunk_size; if (chunk_size < 32) { return ERROR_MALFORMED; } char buf[4]; memset(buf, 0, 4); if (mDataSource->readAt(data_offset + 4, buf + 1, 3) < 3) { return ERROR_IO; } uint32_t defaultAlgorithmId = ntohl(*((int32_t*)buf)); if (defaultAlgorithmId > 1) { return ERROR_MALFORMED; } memset(buf, 0, 4); if (mDataSource->readAt(data_offset + 7, buf + 3, 1) < 1) { return ERROR_IO; } uint32_t defaultIVSize = ntohl(*((int32_t*)buf)); if ((defaultAlgorithmId == 0 && defaultIVSize != 0) || (defaultAlgorithmId != 0 && defaultIVSize == 0)) { return ERROR_MALFORMED; } else if (defaultIVSize != 0 && defaultIVSize != 8 && defaultIVSize != 16) { return ERROR_MALFORMED; } uint8_t defaultKeyId[16]; if (mDataSource->readAt(data_offset + 8, &defaultKeyId, 16) < 16) { return ERROR_IO; } if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->meta->setInt32(kKeyCryptoMode, defaultAlgorithmId); mLastTrack->meta->setInt32(kKeyCryptoDefaultIVSize, defaultIVSize); mLastTrack->meta->setData(kKeyCryptoKey, 'tenc', defaultKeyId, 16); break; } case FOURCC('t', 'k', 'h', 'd'): { *offset += chunk_size; status_t err; if ((err = parseTrackHeader(data_offset, chunk_data_size)) != OK) { return err; } break; } case FOURCC('p', 's', 's', 'h'): { *offset += chunk_size; PsshInfo pssh; if (mDataSource->readAt(data_offset + 4, &pssh.uuid, 16) < 16) { return ERROR_IO; } uint32_t psshdatalen = 0; if (mDataSource->readAt(data_offset + 20, &psshdatalen, 4) < 4) { return ERROR_IO; } pssh.datalen = ntohl(psshdatalen); ALOGV("pssh data size: %d", pssh.datalen); if (chunk_size < 20 || pssh.datalen > chunk_size - 20) { return ERROR_MALFORMED; } pssh.data = new (std::nothrow) uint8_t[pssh.datalen]; if (pssh.data == NULL) { return ERROR_MALFORMED; } ALOGV("allocated pssh @ %p", pssh.data); ssize_t requested = (ssize_t) pssh.datalen; if (mDataSource->readAt(data_offset + 24, pssh.data, requested) < requested) { delete[] pssh.data; return ERROR_IO; } mPssh.push_back(pssh); break; } case FOURCC('m', 'd', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 4 || mLastTrack == NULL) { return ERROR_MALFORMED; } uint8_t version; if (mDataSource->readAt( data_offset, &version, sizeof(version)) < (ssize_t)sizeof(version)) { return ERROR_IO; } off64_t timescale_offset; if (version == 1) { timescale_offset = data_offset + 4 + 16; } else if (version == 0) { timescale_offset = data_offset + 4 + 8; } else { return ERROR_IO; } uint32_t timescale; if (mDataSource->readAt( timescale_offset, &timescale, sizeof(timescale)) < (ssize_t)sizeof(timescale)) { return ERROR_IO; } if (!timescale) { ALOGE("timescale should not be ZERO."); return ERROR_MALFORMED; } mLastTrack->timescale = ntohl(timescale); int64_t duration = 0; if (version == 1) { if (mDataSource->readAt( timescale_offset + 4, &duration, sizeof(duration)) < (ssize_t)sizeof(duration)) { return ERROR_IO; } if (duration != -1) { duration = ntoh64(duration); } } else { uint32_t duration32; if (mDataSource->readAt( timescale_offset + 4, &duration32, sizeof(duration32)) < (ssize_t)sizeof(duration32)) { return ERROR_IO; } if (duration32 != 0xffffffff) { duration = ntohl(duration32); } } if (duration != 0 && mLastTrack->timescale != 0) { mLastTrack->meta->setInt64( kKeyDuration, (duration * 1000000) / mLastTrack->timescale); } uint8_t lang[2]; off64_t lang_offset; if (version == 1) { lang_offset = timescale_offset + 4 + 8; } else if (version == 0) { lang_offset = timescale_offset + 4 + 4; } else { return ERROR_IO; } if (mDataSource->readAt(lang_offset, &lang, sizeof(lang)) < (ssize_t)sizeof(lang)) { return ERROR_IO; } char lang_code[4]; lang_code[0] = ((lang[0] >> 2) & 0x1f) + 0x60; lang_code[1] = ((lang[0] & 0x3) << 3 | (lang[1] >> 5)) + 0x60; lang_code[2] = (lang[1] & 0x1f) + 0x60; lang_code[3] = '\0'; mLastTrack->meta->setCString( kKeyMediaLanguage, lang_code); break; } case FOURCC('s', 't', 's', 'd'): { uint8_t buffer[8]; if (chunk_data_size < (off64_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, 8) < 8) { return ERROR_IO; } if (U32_AT(buffer) != 0) { return ERROR_MALFORMED; } uint32_t entry_count = U32_AT(&buffer[4]); if (entry_count > 1) { const char *mime; if (mLastTrack == NULL) return ERROR_MALFORMED; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) && strcasecmp(mime, "application/octet-stream")) { mLastTrack->skipTrack = true; *offset += chunk_size; break; } } off64_t stop_offset = *offset + chunk_size; *offset = data_offset + 8; for (uint32_t i = 0; i < entry_count; ++i) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'e', 't', 't'): { *offset += chunk_size; if (mLastTrack == NULL) return ERROR_MALFORMED; sp<ABuffer> buffer = new ABuffer(chunk_data_size); if (buffer->data() == NULL) { return NO_MEMORY; } if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { return ERROR_IO; } String8 mimeFormat((const char *)(buffer->data()), chunk_data_size); mLastTrack->meta->setCString(kKeyMIMEType, mimeFormat.string()); break; } case FOURCC('m', 'p', '4', 'a'): case FOURCC('e', 'n', 'c', 'a'): case FOURCC('s', 'a', 'm', 'r'): case FOURCC('s', 'a', 'w', 'b'): { if (mIsQT && chunk_type == FOURCC('m', 'p', '4', 'a') && depth >= 1 && mPath[depth - 1] == FOURCC('w', 'a', 'v', 'e')) { *offset += chunk_size; break; } uint8_t buffer[8 + 20]; if (chunk_data_size < (ssize_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) { return ERROR_IO; } uint16_t data_ref_index __unused = U16_AT(&buffer[6]); uint16_t version = U16_AT(&buffer[8]); uint32_t num_channels = U16_AT(&buffer[16]); uint16_t sample_size = U16_AT(&buffer[18]); uint32_t sample_rate = U32_AT(&buffer[24]) >> 16; if (mLastTrack == NULL) return ERROR_MALFORMED; off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); if (mIsQT && chunk_type == FOURCC('m', 'p', '4', 'a')) { if (version == 1) { if (mDataSource->readAt(*offset, buffer, 16) < 16) { return ERROR_IO; } #if 0 U32_AT(buffer); // samples per packet U32_AT(&buffer[4]); // bytes per packet U32_AT(&buffer[8]); // bytes per frame U32_AT(&buffer[12]); // bytes per sample #endif *offset += 16; } else if (version == 2) { uint8_t v2buffer[36]; if (mDataSource->readAt(*offset, v2buffer, 36) < 36) { return ERROR_IO; } #if 0 U32_AT(v2buffer); // size of struct only sample_rate = (uint32_t)U64_AT(&v2buffer[4]); // audio sample rate num_channels = U32_AT(&v2buffer[12]); // num audio channels U32_AT(&v2buffer[16]); // always 0x7f000000 sample_size = (uint16_t)U32_AT(&v2buffer[20]); // const bits per channel U32_AT(&v2buffer[24]); // format specifc flags U32_AT(&v2buffer[28]); // const bytes per audio packet U32_AT(&v2buffer[32]); // const LPCM frames per audio packet #endif *offset += 36; } } if (chunk_type != FOURCC('e', 'n', 'c', 'a')) { mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type)); AdjustChannelsAndRate(chunk_type, &num_channels, &sample_rate); } ALOGV("*** coding='%s' %d channels, size %d, rate %d\n", chunk, num_channels, sample_size, sample_rate); mLastTrack->meta->setInt32(kKeyChannelCount, num_channels); mLastTrack->meta->setInt32(kKeySampleRate, sample_rate); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'p', '4', 'v'): case FOURCC('e', 'n', 'c', 'v'): case FOURCC('s', '2', '6', '3'): case FOURCC('H', '2', '6', '3'): case FOURCC('h', '2', '6', '3'): case FOURCC('a', 'v', 'c', '1'): case FOURCC('h', 'v', 'c', '1'): case FOURCC('h', 'e', 'v', '1'): { uint8_t buffer[78]; if (chunk_data_size < (ssize_t)sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) { return ERROR_IO; } uint16_t data_ref_index __unused = U16_AT(&buffer[6]); uint16_t width = U16_AT(&buffer[6 + 18]); uint16_t height = U16_AT(&buffer[6 + 20]); if (width == 0) width = 352; if (height == 0) height = 288; if (mLastTrack == NULL) return ERROR_MALFORMED; if (chunk_type != FOURCC('e', 'n', 'c', 'v')) { mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type)); } mLastTrack->meta->setInt32(kKeyWidth, width); mLastTrack->meta->setInt32(kKeyHeight, height); off64_t stop_offset = *offset + chunk_size; *offset = data_offset + sizeof(buffer); while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('s', 't', 'c', 'o'): case FOURCC('c', 'o', '6', '4'): { if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL)) return ERROR_MALFORMED; status_t err = mLastTrack->sampleTable->setChunkOffsetParams( chunk_type, data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 'c'): { if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL)) return ERROR_MALFORMED; status_t err = mLastTrack->sampleTable->setSampleToChunkParams( data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 'z'): case FOURCC('s', 't', 'z', '2'): { if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL)) return ERROR_MALFORMED; status_t err = mLastTrack->sampleTable->setSampleSizeParams( chunk_type, data_offset, chunk_data_size); *offset += chunk_size; if (err != OK) { return err; } size_t max_size; err = mLastTrack->sampleTable->getMaxSampleSize(&max_size); if (err != OK) { return err; } if (max_size != 0) { if (max_size > SIZE_MAX - 10 * 2) { ALOGE("max sample size too big: %zu", max_size); return ERROR_MALFORMED; } mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size + 10 * 2); } else { uint32_t width, height; if (!mLastTrack->meta->findInt32(kKeyWidth, (int32_t*)&width) || !mLastTrack->meta->findInt32(kKeyHeight,(int32_t*) &height)) { ALOGE("No width or height, assuming worst case 1080p"); width = 1920; height = 1080; } else { if (width > 32768 || height > 32768) { ALOGE("can't support %u x %u video", width, height); return ERROR_MALFORMED; } } const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (!strcmp(mime, MEDIA_MIMETYPE_VIDEO_AVC) || !strcmp(mime, MEDIA_MIMETYPE_VIDEO_HEVC)) { max_size = ((width + 15) / 16) * ((height + 15) / 16) * 192; } else { max_size = width * height * 3 / 2; } mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size); } const char *mime; CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); if (!strncasecmp("video/", mime, 6)) { size_t nSamples = mLastTrack->sampleTable->countSamples(); if (nSamples == 0) { int32_t trackId; if (mLastTrack->meta->findInt32(kKeyTrackID, &trackId)) { for (size_t i = 0; i < mTrex.size(); i++) { Trex *t = &mTrex.editItemAt(i); if (t->track_ID == (uint32_t) trackId) { if (t->default_sample_duration > 0) { int32_t frameRate = mLastTrack->timescale / t->default_sample_duration; mLastTrack->meta->setInt32(kKeyFrameRate, frameRate); } break; } } } } else { int64_t durationUs; if (mLastTrack->meta->findInt64(kKeyDuration, &durationUs)) { if (durationUs > 0) { int32_t frameRate = (nSamples * 1000000LL + (durationUs >> 1)) / durationUs; mLastTrack->meta->setInt32(kKeyFrameRate, frameRate); } } } } break; } case FOURCC('s', 't', 't', 's'): { if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL)) return ERROR_MALFORMED; *offset += chunk_size; status_t err = mLastTrack->sampleTable->setTimeToSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('c', 't', 't', 's'): { if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL)) return ERROR_MALFORMED; *offset += chunk_size; status_t err = mLastTrack->sampleTable->setCompositionTimeToSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC('s', 't', 's', 's'): { if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL)) return ERROR_MALFORMED; *offset += chunk_size; status_t err = mLastTrack->sampleTable->setSyncSampleParams( data_offset, chunk_data_size); if (err != OK) { return err; } break; } case FOURCC(0xA9, 'x', 'y', 'z'): { *offset += chunk_size; if (chunk_data_size < 8) { return ERROR_MALFORMED; } char buffer[18 + 8]; off64_t location_length = chunk_data_size - 5; if (location_length >= (off64_t) sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset + 4, buffer, location_length) < location_length) { return ERROR_IO; } buffer[location_length] = '\0'; mFileMetaData->setCString(kKeyLocation, buffer); break; } case FOURCC('e', 's', 'd', 's'): { *offset += chunk_size; if (chunk_data_size < 4) { return ERROR_MALFORMED; } uint8_t buffer[256]; if (chunk_data_size > (off64_t)sizeof(buffer)) { return ERROR_BUFFER_TOO_SMALL; } if (mDataSource->readAt( data_offset, buffer, chunk_data_size) < chunk_data_size) { return ERROR_IO; } if (U32_AT(buffer) != 0) { return ERROR_MALFORMED; } if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->meta->setData( kKeyESDS, kTypeESDS, &buffer[4], chunk_data_size - 4); if (mPath.size() >= 2 && mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'a')) { status_t err = updateAudioTrackInfoFromESDS_MPEG4Audio( &buffer[4], chunk_data_size - 4); if (err != OK) { return err; } } if (mPath.size() >= 2 && mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'v')) { ESDS esds(&buffer[4], chunk_data_size - 4); uint8_t objectTypeIndication; if (esds.getObjectTypeIndication(&objectTypeIndication) == OK) { if (objectTypeIndication >= 0x60 && objectTypeIndication <= 0x65) { mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG2); } } } break; } case FOURCC('b', 't', 'r', 't'): { *offset += chunk_size; if (mLastTrack == NULL) { return ERROR_MALFORMED; } uint8_t buffer[12]; if (chunk_data_size != sizeof(buffer)) { return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, chunk_data_size) < chunk_data_size) { return ERROR_IO; } uint32_t maxBitrate = U32_AT(&buffer[4]); uint32_t avgBitrate = U32_AT(&buffer[8]); if (maxBitrate > 0 && maxBitrate < INT32_MAX) { mLastTrack->meta->setInt32(kKeyMaxBitRate, (int32_t)maxBitrate); } if (avgBitrate > 0 && avgBitrate < INT32_MAX) { mLastTrack->meta->setInt32(kKeyBitRate, (int32_t)avgBitrate); } break; } case FOURCC('a', 'v', 'c', 'C'): { *offset += chunk_size; sp<ABuffer> buffer = new ABuffer(chunk_data_size); if (buffer->data() == NULL) { ALOGE("b/28471206"); return NO_MEMORY; } if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { return ERROR_IO; } if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->meta->setData( kKeyAVCC, kTypeAVCC, buffer->data(), chunk_data_size); break; } case FOURCC('h', 'v', 'c', 'C'): { sp<ABuffer> buffer = new ABuffer(chunk_data_size); if (buffer->data() == NULL) { ALOGE("b/28471206"); return NO_MEMORY; } if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { return ERROR_IO; } if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->meta->setData( kKeyHVCC, kTypeHVCC, buffer->data(), chunk_data_size); *offset += chunk_size; break; } case FOURCC('d', '2', '6', '3'): { *offset += chunk_size; /* * d263 contains a fixed 7 bytes part: * vendor - 4 bytes * version - 1 byte * level - 1 byte * profile - 1 byte * optionally, "d263" box itself may contain a 16-byte * bit rate box (bitr) * average bit rate - 4 bytes * max bit rate - 4 bytes */ char buffer[23]; if (chunk_data_size != 7 && chunk_data_size != 23) { ALOGE("Incorrect D263 box size %lld", (long long)chunk_data_size); return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, chunk_data_size) < chunk_data_size) { return ERROR_IO; } if (mLastTrack == NULL) return ERROR_MALFORMED; mLastTrack->meta->setData(kKeyD263, kTypeD263, buffer, chunk_data_size); break; } case FOURCC('m', 'e', 't', 'a'): { off64_t stop_offset = *offset + chunk_size; *offset = data_offset; bool isParsingMetaKeys = underQTMetaPath(mPath, 2); if (!isParsingMetaKeys) { uint8_t buffer[4]; if (chunk_data_size < (off64_t)sizeof(buffer)) { *offset = stop_offset; return ERROR_MALFORMED; } if (mDataSource->readAt( data_offset, buffer, 4) < 4) { *offset = stop_offset; return ERROR_IO; } if (U32_AT(buffer) != 0) { *offset = stop_offset; return OK; } *offset += sizeof(buffer); } while (*offset < stop_offset) { status_t err = parseChunk(offset, depth + 1); if (err != OK) { return err; } } if (*offset != stop_offset) { return ERROR_MALFORMED; } break; } case FOURCC('m', 'e', 'a', 'n'): case FOURCC('n', 'a', 'm', 'e'): case FOURCC('d', 'a', 't', 'a'): { *offset += chunk_size; if (mPath.size() == 6 && underMetaDataPath(mPath)) { status_t err = parseITunesMetaData(data_offset, chunk_data_size); if (err != OK) { return err; } } break; } case FOURCC('m', 'v', 'h', 'd'): { *offset += chunk_size; if (depth != 1) { ALOGE("mvhd: depth %d", depth); return ERROR_MALFORMED; } if (chunk_data_size < 32) { return ERROR_MALFORMED; } uint8_t header[32]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } uint64_t creationTime; uint64_t duration = 0; if (header[0] == 1) { creationTime = U64_AT(&header[4]); mHeaderTimescale = U32_AT(&header[20]); duration = U64_AT(&header[24]); if (duration == 0xffffffffffffffff) { duration = 0; } } else if (header[0] != 0) { return ERROR_MALFORMED; } else { creationTime = U32_AT(&header[4]); mHeaderTimescale = U32_AT(&header[12]); uint32_t d32 = U32_AT(&header[16]); if (d32 == 0xffffffff) { d32 = 0; } duration = d32; } if (duration != 0 && mHeaderTimescale != 0 && duration < UINT64_MAX / 1000000) { mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale); } String8 s; if (convertTimeToDate(creationTime, &s)) { mFileMetaData->setCString(kKeyDate, s.string()); } break; } case FOURCC('m', 'e', 'h', 'd'): { *offset += chunk_size; if (chunk_data_size < 8) { return ERROR_MALFORMED; } uint8_t flags[4]; if (mDataSource->readAt( data_offset, flags, sizeof(flags)) < (ssize_t)sizeof(flags)) { return ERROR_IO; } uint64_t duration = 0; if (flags[0] == 1) { if (chunk_data_size < 12) { return ERROR_MALFORMED; } mDataSource->getUInt64(data_offset + 4, &duration); if (duration == 0xffffffffffffffff) { duration = 0; } } else if (flags[0] == 0) { uint32_t d32; mDataSource->getUInt32(data_offset + 4, &d32); if (d32 == 0xffffffff) { d32 = 0; } duration = d32; } else { return ERROR_MALFORMED; } if (duration != 0 && mHeaderTimescale != 0) { mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale); } break; } case FOURCC('m', 'd', 'a', 't'): { ALOGV("mdat chunk, drm: %d", mIsDrm); mMdatFound = true; if (!mIsDrm) { *offset += chunk_size; break; } if (chunk_size < 8) { return ERROR_MALFORMED; } return parseDrmSINF(offset, data_offset); } case FOURCC('h', 'd', 'l', 'r'): { *offset += chunk_size; if (underQTMetaPath(mPath, 3)) { break; } uint32_t buffer; if (mDataSource->readAt( data_offset + 8, &buffer, 4) < 4) { return ERROR_IO; } uint32_t type = ntohl(buffer); if (type == FOURCC('t', 'e', 'x', 't') || type == FOURCC('s', 'b', 't', 'l')) { if (mLastTrack != NULL) { mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_TEXT_3GPP); } } break; } case FOURCC('k', 'e', 'y', 's'): { *offset += chunk_size; if (underQTMetaPath(mPath, 3)) { status_t err = parseQTMetaKey(data_offset, chunk_data_size); if (err != OK) { return err; } } break; } case FOURCC('t', 'r', 'e', 'x'): { *offset += chunk_size; if (chunk_data_size < 24) { return ERROR_IO; } Trex trex; if (!mDataSource->getUInt32(data_offset + 4, &trex.track_ID) || !mDataSource->getUInt32(data_offset + 8, &trex.default_sample_description_index) || !mDataSource->getUInt32(data_offset + 12, &trex.default_sample_duration) || !mDataSource->getUInt32(data_offset + 16, &trex.default_sample_size) || !mDataSource->getUInt32(data_offset + 20, &trex.default_sample_flags)) { return ERROR_IO; } mTrex.add(trex); break; } case FOURCC('t', 'x', '3', 'g'): { if (mLastTrack == NULL) return ERROR_MALFORMED; uint32_t type; const void *data; size_t size = 0; if (!mLastTrack->meta->findData( kKeyTextFormatData, &type, &data, &size)) { size = 0; } if ((chunk_size > SIZE_MAX) || (SIZE_MAX - chunk_size <= size)) { return ERROR_MALFORMED; } uint8_t *buffer = new (std::nothrow) uint8_t[size + chunk_size]; if (buffer == NULL) { return ERROR_MALFORMED; } if (size > 0) { memcpy(buffer, data, size); } if ((size_t)(mDataSource->readAt(*offset, buffer + size, chunk_size)) < chunk_size) { delete[] buffer; buffer = NULL; *offset += chunk_size; return ERROR_IO; } mLastTrack->meta->setData( kKeyTextFormatData, 0, buffer, size + chunk_size); delete[] buffer; *offset += chunk_size; break; } case FOURCC('c', 'o', 'v', 'r'): { *offset += chunk_size; if (mFileMetaData != NULL) { ALOGV("chunk_data_size = %" PRId64 " and data_offset = %" PRId64, chunk_data_size, data_offset); if (chunk_data_size < 0 || static_cast<uint64_t>(chunk_data_size) >= SIZE_MAX - 1) { return ERROR_MALFORMED; } sp<ABuffer> buffer = new ABuffer(chunk_data_size + 1); if (buffer->data() == NULL) { ALOGE("b/28471206"); return NO_MEMORY; } if (mDataSource->readAt( data_offset, buffer->data(), chunk_data_size) != (ssize_t)chunk_data_size) { return ERROR_IO; } const int kSkipBytesOfDataBox = 16; if (chunk_data_size <= kSkipBytesOfDataBox) { return ERROR_MALFORMED; } mFileMetaData->setData( kKeyAlbumArt, MetaData::TYPE_NONE, buffer->data() + kSkipBytesOfDataBox, chunk_data_size - kSkipBytesOfDataBox); } break; } case FOURCC('c', 'o', 'l', 'r'): { *offset += chunk_size; if (depth >= 2 && mPath[depth - 2] == FOURCC('s', 't', 's', 'd')) { status_t err = parseColorInfo(data_offset, chunk_data_size); if (err != OK) { return err; } } break; } case FOURCC('t', 'i', 't', 'l'): case FOURCC('p', 'e', 'r', 'f'): case FOURCC('a', 'u', 't', 'h'): case FOURCC('g', 'n', 'r', 'e'): case FOURCC('a', 'l', 'b', 'm'): case FOURCC('y', 'r', 'r', 'c'): { *offset += chunk_size; status_t err = parse3GPPMetaData(data_offset, chunk_data_size, depth); if (err != OK) { return err; } break; } case FOURCC('I', 'D', '3', '2'): { *offset += chunk_size; if (chunk_data_size < 6) { return ERROR_MALFORMED; } parseID3v2MetaData(data_offset + 6); break; } case FOURCC('-', '-', '-', '-'): { mLastCommentMean.clear(); mLastCommentName.clear(); mLastCommentData.clear(); *offset += chunk_size; break; } case FOURCC('s', 'i', 'd', 'x'): { status_t err = parseSegmentIndex(data_offset, chunk_data_size); if (err != OK) { return err; } *offset += chunk_size; return UNKNOWN_ERROR; // stop parsing after sidx } case FOURCC('a', 'c', '-', '3'): { *offset += chunk_size; return parseAC3SampleEntry(data_offset); } case FOURCC('f', 't', 'y', 'p'): { if (chunk_data_size < 8 || depth != 0) { return ERROR_MALFORMED; } off64_t stop_offset = *offset + chunk_size; uint32_t numCompatibleBrands = (chunk_data_size - 8) / 4; for (size_t i = 0; i < numCompatibleBrands + 2; ++i) { if (i == 1) { continue; } uint32_t brand; if (mDataSource->readAt(data_offset + 4 * i, &brand, 4) < 4) { return ERROR_MALFORMED; } brand = ntohl(brand); if (brand == FOURCC('q', 't', ' ', ' ')) { mIsQT = true; break; } } *offset = stop_offset; break; } default: { if (underQTMetaPath(mPath, 3)) { status_t err = parseQTMetaVal(chunk_type, data_offset, chunk_data_size); if (err != OK) { return err; } } *offset += chunk_size; break; } } return OK; } Vulnerability Type: CWE ID: Summary: A vulnerability in the Android media framework (n/a). Product: Android. Versions: 7.0, 7.1.1, 7.1.2, 8.0. Android ID: A-62187433. Commit Message: Skip track if verification fails Bug: 62187433 Test: ran poc, CTS Change-Id: Ib9b0b6de88d046d8149e9ea5073d6c40ffec7b0c (cherry picked from commit ef8c7830d838d877e6b37b75b47294b064c79397)
High
173,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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: OmniboxPopupViewGtk::OmniboxPopupViewGtk(const gfx::Font& font, OmniboxView* omnibox_view, AutocompleteEditModel* edit_model, GtkWidget* location_bar) : model_(new AutocompletePopupModel(this, edit_model)), omnibox_view_(omnibox_view), location_bar_(location_bar), window_(gtk_window_new(GTK_WINDOW_POPUP)), layout_(NULL), theme_service_(ThemeServiceGtk::GetFrom(edit_model->profile())), font_(font.DeriveFont(kEditFontAdjust)), ignore_mouse_drag_(false), opened_(false) { gtk_widget_set_can_focus(window_, FALSE); gtk_window_set_resizable(GTK_WINDOW(window_), FALSE); gtk_widget_set_app_paintable(window_, TRUE); gtk_widget_set_double_buffered(window_, TRUE); layout_ = gtk_widget_create_pango_layout(window_, NULL); pango_layout_set_auto_dir(layout_, FALSE); pango_layout_set_ellipsize(layout_, PANGO_ELLIPSIZE_END); gtk_widget_add_events(window_, GDK_BUTTON_MOTION_MASK | GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK); g_signal_connect(window_, "motion-notify-event", G_CALLBACK(HandleMotionThunk), this); g_signal_connect(window_, "button-press-event", G_CALLBACK(HandleButtonPressThunk), this); g_signal_connect(window_, "button-release-event", G_CALLBACK(HandleButtonReleaseThunk), this); g_signal_connect(window_, "expose-event", G_CALLBACK(HandleExposeThunk), this); registrar_.Add(this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED, content::Source<ThemeService>(theme_service_)); theme_service_->InitThemesFor(this); } Vulnerability Type: DoS CWE ID: CWE-399 Summary: Use-after-free vulnerability in Google Chrome before 19.0.1084.46 on Linux allows remote attackers to cause a denial of service or possibly have unspecified other impact by leveraging an error in the GTK implementation of the omnibox. Commit Message: GTK: Stop listening to gtk signals in the omnibox before destroying the model. BUG=123530 TEST=none Review URL: http://codereview.chromium.org/10103012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132498 0039d316-1c4b-4281-b951-d872f2087c98
High
171,048
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void ClientControlledShellSurface::OnBoundsChangeEvent( ash::WindowStateType current_state, ash::WindowStateType requested_state, int64_t display_id, const gfx::Rect& window_bounds, int bounds_change) { if (!geometry().IsEmpty() && !window_bounds.IsEmpty() && (!widget_->IsMinimized() || requested_state != ash::WindowStateType::kMinimized) && bounds_changed_callback_) { ash::NonClientFrameViewAsh* frame_view = GetFrameView(); const bool becoming_snapped = requested_state == ash::WindowStateType::kLeftSnapped || requested_state == ash::WindowStateType::kRightSnapped; const bool is_tablet_mode = WMHelper::GetInstance()->IsTabletModeWindowManagerEnabled(); gfx::Rect client_bounds = becoming_snapped && is_tablet_mode ? window_bounds : frame_view->GetClientBoundsForWindowBounds(window_bounds); gfx::Size current_size = frame_view->GetBoundsForClientView().size(); bool is_resize = client_bounds.size() != current_size && !widget_->IsMaximized() && !widget_->IsFullscreen(); bounds_changed_callback_.Run(current_state, requested_state, display_id, client_bounds, is_resize, bounds_change); auto* window_state = GetWindowState(); if (server_reparent_window_ && window_state->GetDisplay().id() != display_id) { ScopedSetBoundsLocally scoped_set_bounds(this); int container_id = window_state->window()->parent()->id(); aura::Window* new_parent = ash::Shell::GetRootWindowControllerWithDisplayId(display_id) ->GetContainer(container_id); new_parent->AddChild(window_state->window()); } } } Vulnerability Type: CWE ID: CWE-787 Summary: PDFium in Google Chrome prior to 57.0.2987.98 for Windows could be made to increment off the end of a buffer, which allowed a remote attacker to potentially exploit heap corruption via a crafted PDF file. Commit Message: Ignore updatePipBounds before initial bounds is set When PIP enter/exit transition happens, window state change and initial bounds change are committed in the same commit. However, as state change is applied first in OnPreWidgetCommit and the bounds is update later, if updatePipBounds is called between the gap, it ends up returning a wrong bounds based on the previous bounds. Currently, there are two callstacks that end up triggering updatePipBounds between the gap: (i) The state change causes OnWindowAddedToLayout and updatePipBounds is called in OnWMEvent, (ii) updatePipBounds is called in UpdatePipState to prevent it from being placed under some system ui. As it doesn't make sense to call updatePipBounds before the first bounds is not set, this CL adds a boolean to defer updatePipBounds. position. Bug: b130782006 Test: Got VLC into PIP and confirmed it was placed at the correct Change-Id: I5b9f3644bfb2533fd3f905bc09d49708a5d08a90 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1578719 Commit-Queue: Kazuki Takise <[email protected]> Auto-Submit: Kazuki Takise <[email protected]> Reviewed-by: Mitsuru Oshima <[email protected]> Cr-Commit-Position: refs/heads/master@{#668724}
Medium
172,408
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void MediaInterfaceProxy::CreateCdm( media::mojom::ContentDecryptionModuleRequest request) { DCHECK(thread_checker_.CalledOnValidThread()); GetMediaInterfaceFactory()->CreateCdm(std::move(request)); } Vulnerability Type: DoS Overflow Mem. Corr. CWE ID: CWE-119 Summary: SkPictureShader.cpp in Skia, as used in Google Chrome before 44.0.2403.89, allows remote attackers to cause a denial of service (memory corruption) or possibly have unspecified other impact by leveraging access to a renderer process and providing crafted serialized data. Commit Message: media: Support hosting mojo CDM in a standalone service Currently when mojo CDM is enabled it is hosted in the MediaService running in the process specified by "mojo_media_host". However, on some platforms we need to run mojo CDM and other mojo media services in different processes. For example, on desktop platforms, we want to run mojo video decoder in the GPU process, but run the mojo CDM in the utility process. This CL adds a new build flag "enable_standalone_cdm_service". When enabled, the mojo CDM service will be hosted in a standalone "cdm" service running in the utility process. All other mojo media services will sill be hosted in the "media" servie running in the process specified by "mojo_media_host". BUG=664364 TEST=Encrypted media browser tests using mojo CDM is still working. Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487 Reviewed-on: https://chromium-review.googlesource.com/567172 Commit-Queue: Xiaohan Wang <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Dan Sanders <[email protected]> Cr-Commit-Position: refs/heads/master@{#486947}
High
171,936
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: HTMLFrameOwnerElement::HTMLFrameOwnerElement(const QualifiedName& tag_name, Document& document) : HTMLElement(tag_name, document), content_frame_(nullptr), embedded_content_view_(nullptr), sandbox_flags_(kSandboxNone) {} Vulnerability Type: CWE ID: CWE-601 Summary: Insufficient policy enforcement in Resource Timing API in Google Chrome prior to 63.0.3239.84 allowed a remote attacker to infer browsing history by triggering a leaked cross-origin URL via a crafted HTML page. Commit Message: Resource Timing: Do not report subsequent navigations within subframes We only want to record resource timing for the load that was initiated by parent document. We filter out subsequent navigations for <iframe>, but we should do it for other types of subframes too. Bug: 780312 Change-Id: I3a7b9e1a365c99e24bb8dac190e88c7099fc3da5 Reviewed-on: https://chromium-review.googlesource.com/750487 Reviewed-by: Nate Chapin <[email protected]> Commit-Queue: Kunihiko Sakamoto <[email protected]> Cr-Commit-Position: refs/heads/master@{#513665}
Medium
172,928
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static int dccp_error(struct net *net, struct nf_conn *tmpl, struct sk_buff *skb, unsigned int dataoff, enum ip_conntrack_info *ctinfo, u_int8_t pf, unsigned int hooknum) { struct dccp_hdr _dh, *dh; unsigned int dccp_len = skb->len - dataoff; unsigned int cscov; const char *msg; dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &dh); if (dh == NULL) { msg = "nf_ct_dccp: short packet "; goto out_invalid; } if (dh->dccph_doff * 4 < sizeof(struct dccp_hdr) || dh->dccph_doff * 4 > dccp_len) { msg = "nf_ct_dccp: truncated/malformed packet "; goto out_invalid; } cscov = dccp_len; if (dh->dccph_cscov) { cscov = (dh->dccph_cscov - 1) * 4; if (cscov > dccp_len) { msg = "nf_ct_dccp: bad checksum coverage "; goto out_invalid; } } if (net->ct.sysctl_checksum && hooknum == NF_INET_PRE_ROUTING && nf_checksum_partial(skb, hooknum, dataoff, cscov, IPPROTO_DCCP, pf)) { msg = "nf_ct_dccp: bad checksum "; goto out_invalid; } if (dh->dccph_type >= DCCP_PKT_INVALID) { msg = "nf_ct_dccp: reserved packet type "; goto out_invalid; } return NF_ACCEPT; out_invalid: if (LOG_INVALID(net, IPPROTO_DCCP)) nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL, "%s", msg); return -NF_ACCEPT; } Vulnerability Type: DoS Exec Code CWE ID: CWE-20 Summary: net/netfilter/nf_conntrack_proto_dccp.c in the Linux kernel through 3.13.6 uses a DCCP header pointer incorrectly, which allows remote attackers to cause a denial of service (system crash) or possibly execute arbitrary code via a DCCP packet that triggers a call to the (1) dccp_new, (2) dccp_packet, or (3) dccp_error function. Commit Message: netfilter: nf_conntrack_dccp: fix skb_header_pointer API usages Some occurences in the netfilter tree use skb_header_pointer() in the following way ... struct dccp_hdr _dh, *dh; ... skb_header_pointer(skb, dataoff, sizeof(_dh), &dh); ... where dh itself is a pointer that is being passed as the copy buffer. Instead, we need to use &_dh as the forth argument so that we're copying the data into an actual buffer that sits on the stack. Currently, we probably could overwrite memory on the stack (e.g. with a possibly mal-formed DCCP packet), but unintentionally, as we only want the buffer to be placed into _dh variable. Fixes: 2bc780499aa3 ("[NETFILTER]: nf_conntrack: add DCCP protocol support") Signed-off-by: Daniel Borkmann <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]>
High
166,420
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: pickCopyFunc(TIFF* in, TIFF* out, uint16 bitspersample, uint16 samplesperpixel) { uint16 shortv; uint32 w, l, tw, tl; int bychunk; (void) TIFFGetField(in, TIFFTAG_PLANARCONFIG, &shortv); if (shortv != config && bitspersample != 8 && samplesperpixel > 1) { fprintf(stderr, "%s: Cannot handle different planar configuration w/ bits/sample != 8\n", TIFFFileName(in)); return (NULL); } TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w); TIFFGetField(in, TIFFTAG_IMAGELENGTH, &l); if (!(TIFFIsTiled(out) || TIFFIsTiled(in))) { uint32 irps = (uint32) -1L; TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &irps); /* if biased, force decoded copying to allow image subtraction */ bychunk = !bias && (rowsperstrip == irps); }else{ /* either in or out is tiled */ if (bias) { fprintf(stderr, "%s: Cannot handle tiled configuration w/bias image\n", TIFFFileName(in)); return (NULL); } if (TIFFIsTiled(out)) { if (!TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw)) tw = w; if (!TIFFGetField(in, TIFFTAG_TILELENGTH, &tl)) tl = l; bychunk = (tw == tilewidth && tl == tilelength); } else { /* out's not, so in must be tiled */ TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); bychunk = (tw == w && tl == rowsperstrip); } } #define T 1 #define F 0 #define pack(a,b,c,d,e) ((long)(((a)<<11)|((b)<<3)|((c)<<2)|((d)<<1)|(e))) switch(pack(shortv,config,TIFFIsTiled(in),TIFFIsTiled(out),bychunk)) { /* Strips -> Tiles */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,T): return cpContigStrips2ContigTiles; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,T): return cpContigStrips2SeparateTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,T): return cpSeparateStrips2ContigTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,T): return cpSeparateStrips2SeparateTiles; /* Tiles -> Tiles */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,T): return cpContigTiles2ContigTiles; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,T): return cpContigTiles2SeparateTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,T): return cpSeparateTiles2ContigTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,T): return cpSeparateTiles2SeparateTiles; /* Tiles -> Strips */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,T): return cpContigTiles2ContigStrips; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,T): return cpContigTiles2SeparateStrips; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,T): return cpSeparateTiles2ContigStrips; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,T): return cpSeparateTiles2SeparateStrips; /* Strips -> Strips */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,F): return bias ? cpBiasedContig2Contig : cpContig2ContigByRow; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,T): return cpDecodedStrips; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,T): return cpContig2SeparateByRow; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,T): return cpSeparate2ContigByRow; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,T): return cpSeparate2SeparateByRow; } #undef pack #undef F #undef T fprintf(stderr, "tiffcp: %s: Don't know how to copy/convert image.\n", TIFFFileName(in)); return (NULL); } Vulnerability Type: Exec Code Overflow CWE ID: CWE-119 Summary: LibTIFF version 4.0.7 is vulnerable to a heap buffer overflow in the tools/tiffcp resulting in DoS or code execution via a crafted BitsPerSample value. Commit Message: * tools/tiffcp.c: error out cleanly in cpContig2SeparateByRow and cpSeparate2ContigByRow if BitsPerSample != 8 to avoid heap based overflow. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2656 and http://bugzilla.maptools.org/show_bug.cgi?id=2657
High
168,414
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void ssl_set_client_disabled(SSL *s) { CERT *c = s->cert; c->mask_a = 0; c->mask_k = 0; /* Don't allow TLS 1.2 only ciphers if we don't suppport them */ if (!SSL_CLIENT_USE_TLS1_2_CIPHERS(s)) c->mask_ssl = SSL_TLSV1_2; else c->mask_ssl = 0; ssl_set_sig_mask(&c->mask_a, s, SSL_SECOP_SIGALG_MASK); /* Disable static DH if we don't include any appropriate * signature algorithms. */ if (c->mask_a & SSL_aRSA) c->mask_k |= SSL_kDHr|SSL_kECDHr; if (c->mask_a & SSL_aDSS) c->mask_k |= SSL_kDHd; if (c->mask_a & SSL_aECDSA) c->mask_k |= SSL_kECDHe; #ifndef OPENSSL_NO_KRB5 if (!kssl_tgt_is_available(s->kssl_ctx)) { c->mask_a |= SSL_aKRB5; c->mask_k |= SSL_kKRB5; } #endif #ifndef OPENSSL_NO_PSK /* with PSK there must be client callback set */ if (!s->psk_client_callback) { c->mask_a |= SSL_aPSK; c->mask_k |= SSL_kPSK; } #endif /* OPENSSL_NO_PSK */ c->valid = 1; } Vulnerability Type: DoS CWE ID: Summary: The ssl_set_client_disabled function in t1_lib.c in OpenSSL 1.0.1 before 1.0.1i allows remote SSL servers to cause a denial of service (NULL pointer dereference and client application crash) via a ServerHello message that includes an SRP ciphersuite without the required negotiation of that ciphersuite with the client. Commit Message:
Medium
165,023
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: bool ID3::removeUnsynchronizationV2_4(bool iTunesHack) { size_t oldSize = mSize; size_t offset = 0; while (mSize >= 10 && offset <= mSize - 10) { if (!memcmp(&mData[offset], "\0\0\0\0", 4)) { break; } size_t dataSize; if (iTunesHack) { dataSize = U32_AT(&mData[offset + 4]); } else if (!ParseSyncsafeInteger(&mData[offset + 4], &dataSize)) { return false; } if (dataSize > mSize - 10 - offset) { return false; } uint16_t flags = U16_AT(&mData[offset + 8]); uint16_t prevFlags = flags; if (flags & 1) { if (mSize < 14 || mSize - 14 < offset || dataSize < 4) { return false; } memmove(&mData[offset + 10], &mData[offset + 14], mSize - offset - 14); mSize -= 4; dataSize -= 4; flags &= ~1; } if (flags & 2) { size_t readOffset = offset + 11; size_t writeOffset = offset + 11; for (size_t i = 0; i + 1 < dataSize; ++i) { if (mData[readOffset - 1] == 0xff && mData[readOffset] == 0x00) { ++readOffset; --mSize; --dataSize; } mData[writeOffset++] = mData[readOffset++]; } memmove(&mData[writeOffset], &mData[readOffset], oldSize - readOffset); flags &= ~2; } if (flags != prevFlags || iTunesHack) { WriteSyncsafeInteger(&mData[offset + 4], dataSize); mData[offset + 8] = flags >> 8; mData[offset + 9] = flags & 0xff; } offset += 10 + dataSize; } memset(&mData[mSize], 0, oldSize - mSize); return true; } Vulnerability Type: Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: A remote code execution vulnerability in id3/ID3.cpp in libstagefright in Mediaserver could enable an attacker using a specially crafted file to cause memory corruption during media file and data processing. This issue is rated as Critical due to the possibility of remote code execution within the context of the Mediaserver process. Product: Android. Versions: 4.4.4, 5.0.2, 5.1.1, 6.0, 6.0.1, 7.0, 7.1.1, 7.1.2. Android ID: A-34618607. Commit Message: Fix out of bounds access Bug: 34618607 Change-Id: I84f0ef948414d0b2d54e8948b6c30b8ae4da2b36 (cherry picked from commit d1c19c57f66d91ea8033c8fa6510a8760a6e663b)
High
174,031
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void RenderFrameHostImpl::OnDidAddMessageToConsole( int32_t level, const base::string16& message, int32_t line_no, const base::string16& source_id) { if (level < logging::LOG_VERBOSE || level > logging::LOG_FATAL) { bad_message::ReceivedBadMessage( GetProcess(), bad_message::RFH_DID_ADD_CONSOLE_MESSAGE_BAD_SEVERITY); return; } if (delegate_->DidAddMessageToConsole(level, message, line_no, source_id)) return; const bool is_builtin_component = HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL()) || GetContentClient()->browser()->IsBuiltinComponent( GetProcess()->GetBrowserContext(), GetLastCommittedOrigin()); const bool is_off_the_record = GetSiteInstance()->GetBrowserContext()->IsOffTheRecord(); LogConsoleMessage(level, message, line_no, is_builtin_component, is_off_the_record, source_id); } Vulnerability Type: CWE ID: CWE-416 Summary: A use after free in Google Chrome prior to 56.0.2924.76 for Linux, Windows and Mac, and 56.0.2924.87 for Android, allowed a remote attacker to potentially exploit heap corruption via a crafted HTML page. Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Cr-Commit-Position: refs/heads/master@{#653137}
Medium
172,485
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: eap_print(netdissect_options *ndo, register const u_char *cp, u_int length) { const struct eap_frame_t *eap; const u_char *tptr; u_int tlen, type, subtype; int count=0, len; tptr = cp; tlen = length; eap = (const struct eap_frame_t *)cp; ND_TCHECK(*eap); /* in non-verbose mode just lets print the basic info */ if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "%s (%u) v%u, len %u", tok2str(eap_frame_type_values, "unknown", eap->type), eap->type, eap->version, EXTRACT_16BITS(eap->length))); return; } ND_PRINT((ndo, "%s (%u) v%u, len %u", tok2str(eap_frame_type_values, "unknown", eap->type), eap->type, eap->version, EXTRACT_16BITS(eap->length))); tptr += sizeof(const struct eap_frame_t); tlen -= sizeof(const struct eap_frame_t); switch (eap->type) { case EAP_FRAME_TYPE_PACKET: type = *(tptr); len = EXTRACT_16BITS(tptr+2); ND_PRINT((ndo, ", %s (%u), id %u, len %u", tok2str(eap_code_values, "unknown", type), type, *(tptr+1), len)); ND_TCHECK2(*tptr, len); if (type <= 2) { /* For EAP_REQUEST and EAP_RESPONSE only */ subtype = *(tptr+4); ND_PRINT((ndo, "\n\t\t Type %s (%u)", tok2str(eap_type_values, "unknown", *(tptr+4)), *(tptr + 4))); switch (subtype) { case EAP_TYPE_IDENTITY: if (len - 5 > 0) { ND_PRINT((ndo, ", Identity: ")); safeputs(ndo, tptr + 5, len - 5); } break; case EAP_TYPE_NOTIFICATION: if (len - 5 > 0) { ND_PRINT((ndo, ", Notification: ")); safeputs(ndo, tptr + 5, len - 5); } break; case EAP_TYPE_NAK: count = 5; /* * one or more octets indicating * the desired authentication * type one octet per type */ while (count < len) { ND_PRINT((ndo, " %s (%u),", tok2str(eap_type_values, "unknown", *(tptr+count)), *(tptr + count))); count++; } break; case EAP_TYPE_TTLS: ND_PRINT((ndo, " TTLSv%u", EAP_TTLS_VERSION(*(tptr + 5)))); /* fall through */ case EAP_TYPE_TLS: ND_PRINT((ndo, " flags [%s] 0x%02x,", bittok2str(eap_tls_flags_values, "none", *(tptr+5)), *(tptr + 5))); if (EAP_TLS_EXTRACT_BIT_L(*(tptr+5))) { ND_PRINT((ndo, " len %u", EXTRACT_32BITS(tptr + 6))); } break; case EAP_TYPE_FAST: ND_PRINT((ndo, " FASTv%u", EAP_TTLS_VERSION(*(tptr + 5)))); ND_PRINT((ndo, " flags [%s] 0x%02x,", bittok2str(eap_tls_flags_values, "none", *(tptr+5)), *(tptr + 5))); if (EAP_TLS_EXTRACT_BIT_L(*(tptr+5))) { ND_PRINT((ndo, " len %u", EXTRACT_32BITS(tptr + 6))); } /* FIXME - TLV attributes follow */ break; case EAP_TYPE_AKA: case EAP_TYPE_SIM: ND_PRINT((ndo, " subtype [%s] 0x%02x,", tok2str(eap_aka_subtype_values, "unknown", *(tptr+5)), *(tptr + 5))); /* FIXME - TLV attributes follow */ break; case EAP_TYPE_MD5_CHALLENGE: case EAP_TYPE_OTP: case EAP_TYPE_GTC: case EAP_TYPE_EXPANDED_TYPES: case EAP_TYPE_EXPERIMENTAL: default: break; } } break; case EAP_FRAME_TYPE_LOGOFF: case EAP_FRAME_TYPE_ENCAP_ASF_ALERT: default: break; } return; trunc: ND_PRINT((ndo, "\n\t[|EAP]")); } Vulnerability Type: CWE ID: CWE-125 Summary: The EAP parser in tcpdump before 4.9.2 has a buffer over-read in print-eap.c:eap_print(). Commit Message: CVE-2017-13015/EAP: Add more bounds checks. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture.
High
167,877
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: char * exif_dump_data(int *dump_free, int format, int components, int length, int motorola_intel, char *value_ptr TSRMLS_DC) /* {{{ */ { char *dump; int len; *dump_free = 0; if (format == TAG_FMT_STRING) { return value_ptr ? value_ptr : "<no data>"; } if (format == TAG_FMT_UNDEFINED) { return "<undefined>\n"; } if (format == TAG_FMT_IFD) { return ""; } if (format == TAG_FMT_SINGLE || format == TAG_FMT_DOUBLE) { return "<not implemented>"; } *dump_free = 1; if (components > 1) { len = spprintf(&dump, 0, "(%d,%d) {", components, length); } else { len = spprintf(&dump, 0, "{"); } while(components > 0) { switch(format) { case TAG_FMT_BYTE: case TAG_FMT_UNDEFINED: case TAG_FMT_STRING: case TAG_FMT_SBYTE: dump = erealloc(dump, len + 4 + 1); snprintf(dump + len, 4 + 1, "0x%02X", *value_ptr); len += 4; value_ptr++; break; case TAG_FMT_USHORT: case TAG_FMT_SSHORT: dump = erealloc(dump, len + 6 + 1); snprintf(dump + len, 6 + 1, "0x%04X", php_ifd_get16s(value_ptr, motorola_intel)); len += 6; value_ptr += 2; break; case TAG_FMT_ULONG: case TAG_FMT_SLONG: dump = erealloc(dump, len + 6 + 1); snprintf(dump + len, 6 + 1, "0x%04X", php_ifd_get32s(value_ptr, motorola_intel)); len += 6; value_ptr += 4; break; case TAG_FMT_URATIONAL: case TAG_FMT_SRATIONAL: dump = erealloc(dump, len + 13 + 1); snprintf(dump + len, 13 + 1, "0x%04X/0x%04X", php_ifd_get32s(value_ptr, motorola_intel), php_ifd_get32s(value_ptr+4, motorola_intel)); len += 13; value_ptr += 8; break; } if (components > 0) { dump = erealloc(dump, len + 2 + 1); snprintf(dump + len, 2 + 1, ", "); len += 2; components--; } else{ break; } } dump = erealloc(dump, len + 1 + 1); snprintf(dump + len, 1 + 1, "}"); return dump; } /* }}} */ #endif /* {{{ exif_convert_any_format * Evaluate number, be it int, rational, or float from directory. */ static double exif_convert_any_format(void *value, int format, int motorola_intel TSRMLS_DC) { int s_den; unsigned u_den; switch(format) { case TAG_FMT_SBYTE: return *(signed char *)value; case TAG_FMT_BYTE: return *(uchar *)value; case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel); case TAG_FMT_URATIONAL: u_den = php_ifd_get32u(4+(char *)value, motorola_intel); if (u_den == 0) { return 0; } else { return (double)php_ifd_get32u(value, motorola_intel) / u_den; } case TAG_FMT_SRATIONAL: s_den = php_ifd_get32s(4+(char *)value, motorola_intel); if (s_den == 0) { return 0; } else { return (double)php_ifd_get32s(value, motorola_intel) / s_den; } case TAG_FMT_SSHORT: return (signed short)php_ifd_get16u(value, motorola_intel); case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel); /* Not sure if this is correct (never seen float used in Exif format) */ case TAG_FMT_SINGLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type single"); #endif return (double)*(float *)value; case TAG_FMT_DOUBLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type double"); #endif return *(double *)value; } return 0; } /* }}} */ /* {{{ exif_convert_any_to_int * Evaluate number, be it int, rational, or float from directory. */ static size_t exif_convert_any_to_int(void *value, int format, int motorola_intel TSRMLS_DC) { int s_den; unsigned u_den; switch(format) { case TAG_FMT_SBYTE: return *(signed char *)value; case TAG_FMT_BYTE: return *(uchar *)value; case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel); case TAG_FMT_URATIONAL: u_den = php_ifd_get32u(4+(char *)value, motorola_intel); if (u_den == 0) { return 0; } else { return php_ifd_get32u(value, motorola_intel) / u_den; } case TAG_FMT_SRATIONAL: s_den = php_ifd_get32s(4+(char *)value, motorola_intel); if (s_den == 0) { return 0; } else { return php_ifd_get32s(value, motorola_intel) / s_den; } case TAG_FMT_SSHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel); /* Not sure if this is correct (never seen float used in Exif format) */ case TAG_FMT_SINGLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type single"); #endif return (size_t)*(float *)value; case TAG_FMT_DOUBLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type double"); #endif return (size_t)*(double *)value; } return 0; } /* }}} */ /* {{{ struct image_info_value, image_info_list */ #ifndef WORD #define WORD unsigned short #endif #ifndef DWORD #define DWORD unsigned int #endif typedef struct { int num; int den; } signed_rational; typedef struct { unsigned int num; unsigned int den; } unsigned_rational; typedef union _image_info_value { char *s; unsigned u; int i; float f; double d; signed_rational sr; unsigned_rational ur; union _image_info_value *list; } image_info_value; typedef struct { WORD tag; WORD format; DWORD length; DWORD dummy; /* value ptr of tiff directory entry */ char *name; image_info_value value; } image_info_data; typedef struct { int count; image_info_data *list; } image_info_list; /* }}} */ /* {{{ exif_get_sectionname Returns the name of a section */ #define SECTION_FILE 0 #define SECTION_COMPUTED 1 #define SECTION_ANY_TAG 2 #define SECTION_IFD0 3 #define SECTION_THUMBNAIL 4 #define SECTION_COMMENT 5 #define SECTION_APP0 6 #define SECTION_EXIF 7 #define SECTION_FPIX 8 #define SECTION_GPS 9 #define SECTION_INTEROP 10 #define SECTION_APP12 11 #define SECTION_WINXP 12 #define SECTION_MAKERNOTE 13 #define SECTION_COUNT 14 #define FOUND_FILE (1<<SECTION_FILE) #define FOUND_COMPUTED (1<<SECTION_COMPUTED) #define FOUND_ANY_TAG (1<<SECTION_ANY_TAG) #define FOUND_IFD0 (1<<SECTION_IFD0) #define FOUND_THUMBNAIL (1<<SECTION_THUMBNAIL) #define FOUND_COMMENT (1<<SECTION_COMMENT) #define FOUND_APP0 (1<<SECTION_APP0) #define FOUND_EXIF (1<<SECTION_EXIF) #define FOUND_FPIX (1<<SECTION_FPIX) #define FOUND_GPS (1<<SECTION_GPS) #define FOUND_INTEROP (1<<SECTION_INTEROP) #define FOUND_APP12 (1<<SECTION_APP12) #define FOUND_WINXP (1<<SECTION_WINXP) #define FOUND_MAKERNOTE (1<<SECTION_MAKERNOTE) static char *exif_get_sectionname(int section) { switch(section) { case SECTION_FILE: return "FILE"; case SECTION_COMPUTED: return "COMPUTED"; case SECTION_ANY_TAG: return "ANY_TAG"; case SECTION_IFD0: return "IFD0"; case SECTION_THUMBNAIL: return "THUMBNAIL"; case SECTION_COMMENT: return "COMMENT"; case SECTION_APP0: return "APP0"; case SECTION_EXIF: return "EXIF"; case SECTION_FPIX: return "FPIX"; case SECTION_GPS: return "GPS"; case SECTION_INTEROP: return "INTEROP"; case SECTION_APP12: return "APP12"; case SECTION_WINXP: return "WINXP"; case SECTION_MAKERNOTE: return "MAKERNOTE"; } return ""; } static tag_table_type exif_get_tag_table(int section) { switch(section) { case SECTION_FILE: return &tag_table_IFD[0]; case SECTION_COMPUTED: return &tag_table_IFD[0]; case SECTION_ANY_TAG: return &tag_table_IFD[0]; case SECTION_IFD0: return &tag_table_IFD[0]; case SECTION_THUMBNAIL: return &tag_table_IFD[0]; case SECTION_COMMENT: return &tag_table_IFD[0]; case SECTION_APP0: return &tag_table_IFD[0]; case SECTION_EXIF: return &tag_table_IFD[0]; case SECTION_FPIX: return &tag_table_IFD[0]; case SECTION_GPS: return &tag_table_GPS[0]; case SECTION_INTEROP: return &tag_table_IOP[0]; case SECTION_APP12: return &tag_table_IFD[0]; case SECTION_WINXP: return &tag_table_IFD[0]; } return &tag_table_IFD[0]; } /* }}} */ /* {{{ exif_get_sectionlist Return list of sectionnames specified by sectionlist. Return value must be freed */ static char *exif_get_sectionlist(int sectionlist TSRMLS_DC) { int i, len, ml = 0; char *sections; for(i=0; i<SECTION_COUNT; i++) { ml += strlen(exif_get_sectionname(i))+2; } sections = safe_emalloc(ml, 1, 1); sections[0] = '\0'; len = 0; for(i=0; i<SECTION_COUNT; i++) { if (sectionlist&(1<<i)) { snprintf(sections+len, ml-len, "%s, ", exif_get_sectionname(i)); len = strlen(sections); } } if (len>2) sections[len-2] = '\0'; return sections; } /* }}} */ /* {{{ struct image_info_type This structure stores Exif header image elements in a simple manner Used to store camera data as extracted from the various ways that it can be stored in a nexif header */ typedef struct { int type; size_t size; uchar *data; } file_section; typedef struct { int count; file_section *list; } file_section_list; typedef struct { image_filetype filetype; size_t width, height; size_t size; size_t offset; char *data; } thumbnail_data; typedef struct { char *value; size_t size; int tag; } xp_field_type; typedef struct { int count; xp_field_type *list; } xp_field_list; /* This structure is used to store a section of a Jpeg file. */ typedef struct { php_stream *infile; char *FileName; time_t FileDateTime; size_t FileSize; image_filetype FileType; int Height, Width; int IsColor; char *make; char *model; float ApertureFNumber; float ExposureTime; double FocalplaneUnits; float CCDWidth; double FocalplaneXRes; size_t ExifImageWidth; float FocalLength; float Distance; int motorola_intel; /* 1 Motorola; 0 Intel */ char *UserComment; int UserCommentLength; char *UserCommentEncoding; char *encode_unicode; char *decode_unicode_be; char *decode_unicode_le; char *encode_jis; char *decode_jis_be; char *decode_jis_le; char *Copyright;/* EXIF standard defines Copyright as "<Photographer> [ '\0' <Editor> ] ['\0']" */ char *CopyrightPhotographer; char *CopyrightEditor; xp_field_list xp_fields; thumbnail_data Thumbnail; /* other */ int sections_found; /* FOUND_<marker> */ image_info_list info_list[SECTION_COUNT]; /* for parsing */ int read_thumbnail; int read_all; int ifd_nesting_level; /* internal */ file_section_list file; } image_info_type; /* }}} */ /* {{{ exif_error_docref */ static void exif_error_docref(const char *docref EXIFERR_DC, const image_info_type *ImageInfo, int type, const char *format, ...) { va_list args; va_start(args, format); #ifdef EXIF_DEBUG { char *buf; spprintf(&buf, 0, "%s(%d): %s", _file, _line, format); php_verror(docref, ImageInfo->FileName?ImageInfo->FileName:"", type, buf, args TSRMLS_CC); efree(buf); } #else php_verror(docref, ImageInfo->FileName?ImageInfo->FileName:"", type, format, args TSRMLS_CC); #endif va_end(args); } /* }}} */ /* {{{ jpeg_sof_info */ typedef struct { int bits_per_sample; size_t width; size_t height; int num_components; } jpeg_sof_info; /* }}} */ /* {{{ exif_file_sections_add Add a file_section to image_info returns the used block or -1. if size>0 and data == NULL buffer of size is allocated */ static int exif_file_sections_add(image_info_type *ImageInfo, int type, size_t size, uchar *data) { file_section *tmp; int count = ImageInfo->file.count; tmp = safe_erealloc(ImageInfo->file.list, (count+1), sizeof(file_section), 0); ImageInfo->file.list = tmp; ImageInfo->file.list[count].type = 0xFFFF; ImageInfo->file.list[count].data = NULL; ImageInfo->file.list[count].size = 0; ImageInfo->file.count = count+1; if (!size) { data = NULL; } else if (data == NULL) { data = safe_emalloc(size, 1, 0); } ImageInfo->file.list[count].type = type; ImageInfo->file.list[count].data = data; ImageInfo->file.list[count].size = size; return count; } /* }}} */ /* {{{ exif_file_sections_realloc Reallocate a file section returns 0 on success and -1 on failure */ static int exif_file_sections_realloc(image_info_type *ImageInfo, int section_index, size_t size TSRMLS_DC) { void *tmp; /* This is not a malloc/realloc check. It is a plausibility check for the * function parameters (requirements engineering). */ if (section_index >= ImageInfo->file.count) { EXIF_ERRLOG_FSREALLOC(ImageInfo) return -1; } tmp = safe_erealloc(ImageInfo->file.list[section_index].data, 1, size, 0); ImageInfo->file.list[section_index].data = tmp; ImageInfo->file.list[section_index].size = size; return 0; } /* }}} */ /* {{{ exif_file_section_free Discard all file_sections in ImageInfo */ static int exif_file_sections_free(image_info_type *ImageInfo) { int i; if (ImageInfo->file.count) { for (i=0; i<ImageInfo->file.count; i++) { EFREE_IF(ImageInfo->file.list[i].data); } } EFREE_IF(ImageInfo->file.list); ImageInfo->file.count = 0; return TRUE; } /* }}} */ /* {{{ exif_iif_add_value Add a value to image_info */ static void exif_iif_add_value(image_info_type *image_info, int section_index, char *name, int tag, int format, int length, void* value, int motorola_intel TSRMLS_DC) { size_t idex; void *vptr; image_info_value *info_value; image_info_data *info_data; image_info_data *list; if (length < 0) { return; } list = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index].list[image_info->info_list[section_index].count]; memset(info_data, 0, sizeof(image_info_data)); info_data->tag = tag; info_data->format = format; info_data->length = length; info_data->name = estrdup(name); info_value = &info_data->value; switch (format) { case TAG_FMT_STRING: if (value) { length = php_strnlen(value, length); info_value->s = estrndup(value, length); info_data->length = length; } else { info_data->length = 0; info_value->s = estrdup(""); } break; default: /* Standard says more types possible but skip them... * but allow users to handle data if they know how to * So not return but use type UNDEFINED * return; */ info_data->tag = TAG_FMT_UNDEFINED;/* otherwise not freed from memory */ case TAG_FMT_SBYTE: case TAG_FMT_BYTE: /* in contrast to strings bytes do not need to allocate buffer for NULL if length==0 */ if (!length) break; case TAG_FMT_UNDEFINED: if (value) { /* do not recompute length here */ info_value->s = estrndup(value, length); info_data->length = length; } else { info_data->length = 0; info_value->s = estrdup(""); } break; case TAG_FMT_USHORT: case TAG_FMT_ULONG: case TAG_FMT_URATIONAL: case TAG_FMT_SSHORT: case TAG_FMT_SLONG: case TAG_FMT_SRATIONAL: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: if (length==0) { break; } else if (length>1) { info_value->list = safe_emalloc(length, sizeof(image_info_value), 0); } else { info_value = &info_data->value; } for (idex=0,vptr=value; idex<(size_t)length; idex++,vptr=(char *) vptr + php_tiff_bytes_per_format[format]) { if (length>1) { info_value = &info_data->value.list[idex]; } switch (format) { case TAG_FMT_USHORT: info_value->u = php_ifd_get16u(vptr, motorola_intel); break; case TAG_FMT_ULONG: info_value->u = php_ifd_get32u(vptr, motorola_intel); break; case TAG_FMT_URATIONAL: info_value->ur.num = php_ifd_get32u(vptr, motorola_intel); info_value->ur.den = php_ifd_get32u(4+(char *)vptr, motorola_intel); break; case TAG_FMT_SSHORT: info_value->i = php_ifd_get16s(vptr, motorola_intel); break; case TAG_FMT_SLONG: info_value->i = php_ifd_get32s(vptr, motorola_intel); break; case TAG_FMT_SRATIONAL: info_value->sr.num = php_ifd_get32u(vptr, motorola_intel); info_value->sr.den = php_ifd_get32u(4+(char *)vptr, motorola_intel); break; case TAG_FMT_SINGLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_WARNING, "Found value of type single"); #endif info_value->f = *(float *)value; case TAG_FMT_DOUBLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_WARNING, "Found value of type double"); #endif info_value->d = *(double *)value; break; } } } image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } /* }}} */ /* {{{ exif_iif_add_tag Add a tag from IFD to image_info */ static void exif_iif_add_tag(image_info_type *image_info, int section_index, char *name, int tag, int format, size_t length, void* value TSRMLS_DC) { exif_iif_add_value(image_info, section_index, name, tag, format, (int)length, value, image_info->motorola_intel TSRMLS_CC); } /* }}} */ /* {{{ exif_iif_add_int Add an int value to image_info */ static void exif_iif_add_int(image_info_type *image_info, int section_index, char *name, int value TSRMLS_DC) { image_info_data *info_data; image_info_data *list; list = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index].list[image_info->info_list[section_index].count]; info_data->tag = TAG_NONE; info_data->format = TAG_FMT_SLONG; info_data->length = 1; info_data->name = estrdup(name); info_data->value.i = value; image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } /* }}} */ /* {{{ exif_iif_add_str Add a string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_str(image_info_type *image_info, int section_index, char *name, char *value TSRMLS_DC) { image_info_data *info_data; image_info_data *list; if (value) { list = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index].list[image_info->info_list[section_index].count]; info_data->tag = TAG_NONE; info_data->format = TAG_FMT_STRING; info_data->length = 1; info_data->name = estrdup(name); info_data->value.s = estrdup(value); image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } } /* }}} */ /* {{{ exif_iif_add_fmt Add a format string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_fmt(image_info_type *image_info, int section_index, char *name TSRMLS_DC, char *value, ...) { char *tmp; va_list arglist; va_start(arglist, value); if (value) { vspprintf(&tmp, 0, value, arglist); exif_iif_add_str(image_info, section_index, name, tmp TSRMLS_CC); efree(tmp); } va_end(arglist); } /* }}} */ /* {{{ exif_iif_add_str Add a string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_buffer(image_info_type *image_info, int section_index, char *name, int length, char *value TSRMLS_DC) { image_info_data *info_data; image_info_data *list; if (value) { list = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index].list[image_info->info_list[section_index].count]; info_data->tag = TAG_NONE; info_data->format = TAG_FMT_UNDEFINED; info_data->length = length; info_data->name = estrdup(name); info_data->value.s = safe_emalloc(length, 1, 1); memcpy(info_data->value.s, value, length); info_data->value.s[length] = 0; image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } } /* }}} */ /* {{{ exif_iif_free Free memory allocated for image_info */ static void exif_iif_free(image_info_type *image_info, int section_index) { int i; void *f; /* faster */ if (image_info->info_list[section_index].count) { for (i=0; i < image_info->info_list[section_index].count; i++) { if ((f=image_info->info_list[section_index].list[i].name) != NULL) { efree(f); } switch(image_info->info_list[section_index].list[i].format) { case TAG_FMT_SBYTE: case TAG_FMT_BYTE: /* in contrast to strings bytes do not need to allocate buffer for NULL if length==0 */ if (image_info->info_list[section_index].list[i].length<1) break; default: case TAG_FMT_UNDEFINED: case TAG_FMT_STRING: if ((f=image_info->info_list[section_index].list[i].value.s) != NULL) { efree(f); } break; case TAG_FMT_USHORT: case TAG_FMT_ULONG: case TAG_FMT_URATIONAL: case TAG_FMT_SSHORT: case TAG_FMT_SLONG: case TAG_FMT_SRATIONAL: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: /* nothing to do here */ if (image_info->info_list[section_index].list[i].length > 1) { if ((f=image_info->info_list[section_index].list[i].value.list) != NULL) { efree(f); } } break; } } } EFREE_IF(image_info->info_list[section_index].list); } /* }}} */ /* {{{ add_assoc_image_info * Add image_info to associative array value. */ static void add_assoc_image_info(zval *value, int sub_array, image_info_type *image_info, int section_index TSRMLS_DC) { char buffer[64], *val, *name, uname[64]; int i, ap, l, b, idx=0, unknown=0; #ifdef EXIF_DEBUG int info_tag; #endif image_info_value *info_value; image_info_data *info_data; zval *tmpi, *array = NULL; #ifdef EXIF_DEBUG /* php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Adding %d infos from section %s", image_info->info_list[section_index].count, exif_get_sectionname(section_index));*/ #endif if (image_info->info_list[section_index].count) { if (sub_array) { MAKE_STD_ZVAL(tmpi); array_init(tmpi); } else { tmpi = value; } for(i=0; i<image_info->info_list[section_index].count; i++) { info_data = &image_info->info_list[section_index].list[i]; #ifdef EXIF_DEBUG info_tag = info_data->tag; /* conversion */ #endif info_value = &info_data->value; if (!(name = info_data->name)) { snprintf(uname, sizeof(uname), "%d", unknown++); name = uname; } #ifdef EXIF_DEBUG /* php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Adding infos: tag(0x%04X,%12s,L=0x%04X): %s", info_tag, exif_get_tagname(info_tag, buffer, -12, exif_get_tag_table(section_index) TSRMLS_CC), info_data->length, info_data->format==TAG_FMT_STRING?(info_value&&info_value->s?info_value->s:"<no data>"):exif_get_tagformat(info_data->format));*/ #endif if (info_data->length==0) { add_assoc_null(tmpi, name); } else { switch (info_data->format) { default: /* Standard says more types possible but skip them... * but allow users to handle data if they know how to * So not return but use type UNDEFINED * return; */ case TAG_FMT_BYTE: case TAG_FMT_SBYTE: case TAG_FMT_UNDEFINED: if (!info_value->s) { add_assoc_stringl(tmpi, name, "", 0, 1); } else { add_assoc_stringl(tmpi, name, info_value->s, info_data->length, 1); } break; case TAG_FMT_STRING: if (!(val = info_value->s)) { val = ""; } if (section_index==SECTION_COMMENT) { add_index_string(tmpi, idx++, val, 1); } else { add_assoc_string(tmpi, name, val, 1); } break; case TAG_FMT_URATIONAL: case TAG_FMT_SRATIONAL: /*case TAG_FMT_BYTE: case TAG_FMT_SBYTE:*/ case TAG_FMT_USHORT: case TAG_FMT_SSHORT: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: case TAG_FMT_ULONG: case TAG_FMT_SLONG: /* now the rest, first see if it becomes an array */ if ((l = info_data->length) > 1) { array = NULL; MAKE_STD_ZVAL(array); array_init(array); } for(ap=0; ap<l; ap++) { if (l>1) { info_value = &info_data->value.list[ap]; } switch (info_data->format) { case TAG_FMT_BYTE: if (l>1) { info_value = &info_data->value; for (b=0;b<l;b++) { add_index_long(array, b, (int)(info_value->s[b])); } break; } case TAG_FMT_USHORT: case TAG_FMT_ULONG: if (l==1) { add_assoc_long(tmpi, name, (int)info_value->u); } else { add_index_long(array, ap, (int)info_value->u); } break; case TAG_FMT_URATIONAL: snprintf(buffer, sizeof(buffer), "%i/%i", info_value->ur.num, info_value->ur.den); if (l==1) { add_assoc_string(tmpi, name, buffer, 1); } else { add_index_string(array, ap, buffer, 1); } break; case TAG_FMT_SBYTE: if (l>1) { info_value = &info_data->value; for (b=0;b<l;b++) { add_index_long(array, ap, (int)info_value->s[b]); } break; } case TAG_FMT_SSHORT: case TAG_FMT_SLONG: if (l==1) { add_assoc_long(tmpi, name, info_value->i); } else { add_index_long(array, ap, info_value->i); } break; case TAG_FMT_SRATIONAL: snprintf(buffer, sizeof(buffer), "%i/%i", info_value->sr.num, info_value->sr.den); if (l==1) { add_assoc_string(tmpi, name, buffer, 1); } else { add_index_string(array, ap, buffer, 1); } break; case TAG_FMT_SINGLE: if (l==1) { add_assoc_double(tmpi, name, info_value->f); } else { add_index_double(array, ap, info_value->f); } break; case TAG_FMT_DOUBLE: if (l==1) { add_assoc_double(tmpi, name, info_value->d); } else { add_index_double(array, ap, info_value->d); } break; } info_value = &info_data->value.list[ap]; } if (l>1) { add_assoc_zval(tmpi, name, array); } break; } } } if (sub_array) { add_assoc_zval(value, exif_get_sectionname(section_index), tmpi); } } } /* }}} */ /* {{{ Markers JPEG markers consist of one or more 0xFF bytes, followed by a marker code byte (which is not an FF). Here are the marker codes of interest in this program. (See jdmarker.c for a more complete list.) */ #define M_TEM 0x01 /* temp for arithmetic coding */ #define M_RES 0x02 /* reserved */ #define M_SOF0 0xC0 /* Start Of Frame N */ #define M_SOF1 0xC1 /* N indicates which compression process */ #define M_SOF2 0xC2 /* Only SOF0-SOF2 are now in common use */ #define M_SOF3 0xC3 #define M_DHT 0xC4 #define M_SOF5 0xC5 /* NB: codes C4 and CC are NOT SOF markers */ #define M_SOF6 0xC6 #define M_SOF7 0xC7 #define M_JPEG 0x08 /* reserved for extensions */ #define M_SOF9 0xC9 #define M_SOF10 0xCA #define M_SOF11 0xCB #define M_DAC 0xCC /* arithmetic table */ #define M_SOF13 0xCD #define M_SOF14 0xCE #define M_SOF15 0xCF #define M_RST0 0xD0 /* restart segment */ #define M_RST1 0xD1 #define M_RST2 0xD2 #define M_RST3 0xD3 #define M_RST4 0xD4 #define M_RST5 0xD5 #define M_RST6 0xD6 #define M_RST7 0xD7 #define M_SOI 0xD8 /* Start Of Image (beginning of datastream) */ #define M_EOI 0xD9 /* End Of Image (end of datastream) */ #define M_SOS 0xDA /* Start Of Scan (begins compressed data) */ #define M_DQT 0xDB #define M_DNL 0xDC #define M_DRI 0xDD #define M_DHP 0xDE #define M_EXP 0xDF #define M_APP0 0xE0 /* JPEG: 'JFIFF' AND (additional 'JFXX') */ #define M_EXIF 0xE1 /* Exif Attribute Information */ #define M_APP2 0xE2 /* Flash Pix Extension Data? */ #define M_APP3 0xE3 #define M_APP4 0xE4 #define M_APP5 0xE5 #define M_APP6 0xE6 #define M_APP7 0xE7 #define M_APP8 0xE8 #define M_APP9 0xE9 #define M_APP10 0xEA #define M_APP11 0xEB #define M_APP12 0xEC #define M_APP13 0xED /* IPTC International Press Telecommunications Council */ #define M_APP14 0xEE /* Software, Copyright? */ #define M_APP15 0xEF #define M_JPG0 0xF0 #define M_JPG1 0xF1 #define M_JPG2 0xF2 #define M_JPG3 0xF3 #define M_JPG4 0xF4 #define M_JPG5 0xF5 #define M_JPG6 0xF6 #define M_JPG7 0xF7 #define M_JPG8 0xF8 #define M_JPG9 0xF9 #define M_JPG10 0xFA #define M_JPG11 0xFB #define M_JPG12 0xFC #define M_JPG13 0xFD #define M_COM 0xFE /* COMment */ #define M_PSEUDO 0x123 /* Extra value. */ /* }}} */ /* {{{ jpeg2000 markers */ /* Markers x30 - x3F do not have a segment */ /* Markers x00, x01, xFE, xC0 - xDF ISO/IEC 10918-1 -> M_<xx> */ /* Markers xF0 - xF7 ISO/IEC 10918-3 */ /* Markers xF7 - xF8 ISO/IEC 14495-1 */ /* XY=Main/Tile-header:(R:required, N:not_allowed, O:optional, L:last_marker) */ #define JC_SOC 0x4F /* NN, Start of codestream */ #define JC_SIZ 0x51 /* RN, Image and tile size */ #define JC_COD 0x52 /* RO, Codeing style defaulte */ #define JC_COC 0x53 /* OO, Coding style component */ #define JC_TLM 0x55 /* ON, Tile part length main header */ #define JC_PLM 0x57 /* ON, Packet length main header */ #define JC_PLT 0x58 /* NO, Packet length tile part header */ #define JC_QCD 0x5C /* RO, Quantization default */ #define JC_QCC 0x5D /* OO, Quantization component */ #define JC_RGN 0x5E /* OO, Region of interest */ #define JC_POD 0x5F /* OO, Progression order default */ #define JC_PPM 0x60 /* ON, Packed packet headers main header */ #define JC_PPT 0x61 /* NO, Packet packet headers tile part header */ #define JC_CME 0x64 /* OO, Comment: "LL E <text>" E=0:binary, E=1:ascii */ #define JC_SOT 0x90 /* NR, Start of tile */ #define JC_SOP 0x91 /* NO, Start of packeter default */ #define JC_EPH 0x92 /* NO, End of packet header */ #define JC_SOD 0x93 /* NL, Start of data */ #define JC_EOC 0xD9 /* NN, End of codestream */ /* }}} */ /* {{{ exif_process_COM Process a COM marker. We want to print out the marker contents as legible text; we must guard against random junk and varying newline representations. */ static void exif_process_COM (image_info_type *image_info, char *value, size_t length TSRMLS_DC) { exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_STRING, length-2, value+2 TSRMLS_CC); } /* }}} */ /* {{{ exif_process_CME Process a CME marker. We want to print out the marker contents as legible text; we must guard against random junk and varying newline representations. */ #ifdef EXIF_JPEG2000 static void exif_process_CME (image_info_type *image_info, char *value, size_t length TSRMLS_DC) { if (length>3) { switch(value[2]) { case 0: exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_UNDEFINED, length, value TSRMLS_CC); break; case 1: exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_STRING, length, value); break; default: php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Undefined JPEG2000 comment encoding"); break; } } else { exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_UNDEFINED, 0, NULL); php_error_docref(NULL TSRMLS_CC, E_NOTICE, "JPEG2000 comment section too small"); } } #endif /* }}} */ /* {{{ exif_process_SOFn * Process a SOFn marker. This is useful for the image dimensions */ static void exif_process_SOFn (uchar *Data, int marker, jpeg_sof_info *result) { /* 0xFF SOSn SectLen(2) Bits(1) Height(2) Width(2) Channels(1) 3*Channels (1) */ result->bits_per_sample = Data[2]; result->height = php_jpg_get16(Data+3); result->width = php_jpg_get16(Data+5); result->num_components = Data[7]; /* switch (marker) { case M_SOF0: process = "Baseline"; break; case M_SOF1: process = "Extended sequential"; break; case M_SOF2: process = "Progressive"; break; case M_SOF3: process = "Lossless"; break; case M_SOF5: process = "Differential sequential"; break; case M_SOF6: process = "Differential progressive"; break; case M_SOF7: process = "Differential lossless"; break; case M_SOF9: process = "Extended sequential, arithmetic coding"; break; case M_SOF10: process = "Progressive, arithmetic coding"; break; case M_SOF11: process = "Lossless, arithmetic coding"; break; case M_SOF13: process = "Differential sequential, arithmetic coding"; break; case M_SOF14: process = "Differential progressive, arithmetic coding"; break; case M_SOF15: process = "Differential lossless, arithmetic coding"; break; default: process = "Unknown"; break; }*/ } /* }}} */ /* forward declarations */ static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, char *offset_base, size_t IFDlength, size_t displacement, int section_index TSRMLS_DC); static int exif_process_IFD_TAG( image_info_type *ImageInfo, char *dir_entry, char *offset_base, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table TSRMLS_DC); /* {{{ exif_get_markername Get name of marker */ #ifdef EXIF_DEBUG static char * exif_get_markername(int marker) { switch(marker) { case 0xC0: return "SOF0"; case 0xC1: return "SOF1"; case 0xC2: return "SOF2"; case 0xC3: return "SOF3"; case 0xC4: return "DHT"; case 0xC5: return "SOF5"; case 0xC6: return "SOF6"; case 0xC7: return "SOF7"; case 0xC9: return "SOF9"; case 0xCA: return "SOF10"; case 0xCB: return "SOF11"; case 0xCD: return "SOF13"; case 0xCE: return "SOF14"; case 0xCF: return "SOF15"; case 0xD8: return "SOI"; case 0xD9: return "EOI"; case 0xDA: return "SOS"; case 0xDB: return "DQT"; case 0xDC: return "DNL"; case 0xDD: return "DRI"; case 0xDE: return "DHP"; case 0xDF: return "EXP"; case 0xE0: return "APP0"; case 0xE1: return "EXIF"; case 0xE2: return "FPIX"; case 0xE3: return "APP3"; case 0xE4: return "APP4"; case 0xE5: return "APP5"; case 0xE6: return "APP6"; case 0xE7: return "APP7"; case 0xE8: return "APP8"; case 0xE9: return "APP9"; case 0xEA: return "APP10"; case 0xEB: return "APP11"; case 0xEC: return "APP12"; case 0xED: return "APP13"; case 0xEE: return "APP14"; case 0xEF: return "APP15"; case 0xF0: return "JPG0"; case 0xFD: return "JPG13"; case 0xFE: return "COM"; case 0x01: return "TEM"; } return "Unknown"; } #endif /* }}} */ /* {{{ proto string exif_tagname(index) Get headername for index or false if not defined */ PHP_FUNCTION(exif_tagname) { long tag; char *szTemp; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &tag) == FAILURE) { return; } szTemp = exif_get_tagname(tag, NULL, 0, tag_table_IFD TSRMLS_CC); if (tag < 0 || !szTemp || !szTemp[0]) { RETURN_FALSE; } RETURN_STRING(szTemp, 1) } /* }}} */ /* {{{ exif_ifd_make_value * Create a value for an ifd from an info_data pointer */ static void* exif_ifd_make_value(image_info_data *info_data, int motorola_intel TSRMLS_DC) { size_t byte_count; char *value_ptr, *data_ptr; size_t i; image_info_value *info_value; byte_count = php_tiff_bytes_per_format[info_data->format] * info_data->length; value_ptr = safe_emalloc(max(byte_count, 4), 1, 0); memset(value_ptr, 0, 4); if (!info_data->length) { return value_ptr; } if (info_data->format == TAG_FMT_UNDEFINED || info_data->format == TAG_FMT_STRING || (byte_count>1 && (info_data->format == TAG_FMT_BYTE || info_data->format == TAG_FMT_SBYTE)) ) { memmove(value_ptr, info_data->value.s, byte_count); return value_ptr; } else if (info_data->format == TAG_FMT_BYTE) { *value_ptr = info_data->value.u; return value_ptr; } else if (info_data->format == TAG_FMT_SBYTE) { *value_ptr = info_data->value.i; return value_ptr; } else { data_ptr = value_ptr; for(i=0; i<info_data->length; i++) { if (info_data->length==1) { info_value = &info_data->value; } else { info_value = &info_data->value.list[i]; } switch(info_data->format) { case TAG_FMT_USHORT: php_ifd_set16u(data_ptr, info_value->u, motorola_intel); data_ptr += 2; break; case TAG_FMT_ULONG: php_ifd_set32u(data_ptr, info_value->u, motorola_intel); data_ptr += 4; break; case TAG_FMT_SSHORT: php_ifd_set16u(data_ptr, info_value->i, motorola_intel); data_ptr += 2; break; case TAG_FMT_SLONG: php_ifd_set32u(data_ptr, info_value->i, motorola_intel); data_ptr += 4; break; case TAG_FMT_URATIONAL: php_ifd_set32u(data_ptr, info_value->sr.num, motorola_intel); php_ifd_set32u(data_ptr+4, info_value->sr.den, motorola_intel); data_ptr += 8; break; case TAG_FMT_SRATIONAL: php_ifd_set32u(data_ptr, info_value->ur.num, motorola_intel); php_ifd_set32u(data_ptr+4, info_value->ur.den, motorola_intel); data_ptr += 8; break; case TAG_FMT_SINGLE: memmove(data_ptr, &info_value->f, 4); data_ptr += 4; break; case TAG_FMT_DOUBLE: memmove(data_ptr, &info_value->d, 8); data_ptr += 8; break; } } } return value_ptr; } /* }}} */ /* {{{ exif_thumbnail_build * Check and build thumbnail */ static void exif_thumbnail_build(image_info_type *ImageInfo TSRMLS_DC) { size_t new_size, new_move, new_value; char *new_data; void *value_ptr; int i, byte_count; image_info_list *info_list; image_info_data *info_data; #ifdef EXIF_DEBUG char tagname[64]; #endif if (!ImageInfo->read_thumbnail || !ImageInfo->Thumbnail.offset || !ImageInfo->Thumbnail.size) { return; /* ignore this call */ } #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: filetype = %d", ImageInfo->Thumbnail.filetype); #endif switch(ImageInfo->Thumbnail.filetype) { default: case IMAGE_FILETYPE_JPEG: /* done */ break; case IMAGE_FILETYPE_TIFF_II: case IMAGE_FILETYPE_TIFF_MM: info_list = &ImageInfo->info_list[SECTION_THUMBNAIL]; new_size = 8 + 2 + info_list->count * 12 + 4; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: size of signature + directory(%d): 0x%02X", info_list->count, new_size); #endif new_value= new_size; /* offset for ifd values outside ifd directory */ for (i=0; i<info_list->count; i++) { info_data = &info_list->list[i]; byte_count = php_tiff_bytes_per_format[info_data->format] * info_data->length; if (byte_count > 4) { new_size += byte_count; } } new_move = new_size; new_data = safe_erealloc(ImageInfo->Thumbnail.data, 1, ImageInfo->Thumbnail.size, new_size); ImageInfo->Thumbnail.data = new_data; memmove(ImageInfo->Thumbnail.data + new_move, ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size); ImageInfo->Thumbnail.size += new_size; /* fill in data */ if (ImageInfo->motorola_intel) { memmove(new_data, "MM\x00\x2a\x00\x00\x00\x08", 8); } else { memmove(new_data, "II\x2a\x00\x08\x00\x00\x00", 8); } new_data += 8; php_ifd_set16u(new_data, info_list->count, ImageInfo->motorola_intel); new_data += 2; for (i=0; i<info_list->count; i++) { info_data = &info_list->list[i]; byte_count = php_tiff_bytes_per_format[info_data->format] * info_data->length; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: process tag(x%04X=%s): %s%s (%d bytes)", info_data->tag, exif_get_tagname(info_data->tag, tagname, -12, tag_table_IFD TSRMLS_CC), (info_data->length>1)&&info_data->format!=TAG_FMT_UNDEFINED&&info_data->format!=TAG_FMT_STRING?"ARRAY OF ":"", exif_get_tagformat(info_data->format), byte_count); #endif if (info_data->tag==TAG_STRIP_OFFSETS || info_data->tag==TAG_JPEG_INTERCHANGE_FORMAT) { php_ifd_set16u(new_data + 0, info_data->tag, ImageInfo->motorola_intel); php_ifd_set16u(new_data + 2, TAG_FMT_ULONG, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 4, 1, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 8, new_move, ImageInfo->motorola_intel); } else { php_ifd_set16u(new_data + 0, info_data->tag, ImageInfo->motorola_intel); php_ifd_set16u(new_data + 2, info_data->format, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 4, info_data->length, ImageInfo->motorola_intel); value_ptr = exif_ifd_make_value(info_data, ImageInfo->motorola_intel TSRMLS_CC); if (byte_count <= 4) { memmove(new_data+8, value_ptr, 4); } else { php_ifd_set32u(new_data+8, new_value, ImageInfo->motorola_intel); #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: writing with value offset: 0x%04X + 0x%02X", new_value, byte_count); #endif memmove(ImageInfo->Thumbnail.data+new_value, value_ptr, byte_count); new_value += byte_count; } efree(value_ptr); } new_data += 12; } memset(new_data, 0, 4); /* next ifd pointer */ #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: created"); #endif break; } } /* }}} */ /* {{{ exif_thumbnail_extract * Grab the thumbnail, corrected */ static void exif_thumbnail_extract(image_info_type *ImageInfo, char *offset, size_t length TSRMLS_DC) { if (ImageInfo->Thumbnail.data) { exif_error_docref("exif_read_data#error_mult_thumb" EXIFERR_CC, ImageInfo, E_WARNING, "Multiple possible thumbnails"); return; /* Should not happen */ } if (!ImageInfo->read_thumbnail) { return; /* ignore this call */ } /* according to exif2.1, the thumbnail is not supposed to be greater than 64K */ if (ImageInfo->Thumbnail.size >= 65536 || ImageInfo->Thumbnail.size <= 0 || ImageInfo->Thumbnail.offset <= 0 ) { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Illegal thumbnail size/offset"); return; } /* Check to make sure we are not going to go past the ExifLength */ if ((ImageInfo->Thumbnail.offset + ImageInfo->Thumbnail.size) > length) { EXIF_ERRLOG_THUMBEOF(ImageInfo) return; } ImageInfo->Thumbnail.data = estrndup(offset + ImageInfo->Thumbnail.offset, ImageInfo->Thumbnail.size); exif_thumbnail_build(ImageInfo TSRMLS_CC); } /* }}} */ /* {{{ exif_process_undefined * Copy a string/buffer in Exif header to a character string and return length of allocated buffer if any. */ static int exif_process_undefined(char **result, char *value, size_t byte_count TSRMLS_DC) { /* we cannot use strlcpy - here the problem is that we have to copy NUL * chars up to byte_count, we also have to add a single NUL character to * force end of string. * estrndup does not return length */ if (byte_count) { (*result) = estrndup(value, byte_count); /* NULL @ byte_count!!! */ return byte_count+1; } return 0; } /* }}} */ /* {{{ exif_process_string_raw * Copy a string in Exif header to a character string returns length of allocated buffer if any. */ static int exif_process_string_raw(char **result, char *value, size_t byte_count) { /* we cannot use strlcpy - here the problem is that we have to copy NUL * chars up to byte_count, we also have to add a single NUL character to * force end of string. */ if (byte_count) { (*result) = safe_emalloc(byte_count, 1, 1); memcpy(*result, value, byte_count); (*result)[byte_count] = '\0'; return byte_count+1; } return 0; } /* }}} */ /* {{{ exif_process_string * Copy a string in Exif header to a character string and return length of allocated buffer if any. * In contrast to exif_process_string this function does always return a string buffer */ static int exif_process_string(char **result, char *value, size_t byte_count TSRMLS_DC) { /* we cannot use strlcpy - here the problem is that we cannot use strlen to * determin length of string and we cannot use strlcpy with len=byte_count+1 * because then we might get into an EXCEPTION if we exceed an allocated * memory page...so we use php_strnlen in conjunction with memcpy and add the NUL * char. * estrdup would sometimes allocate more memory and does not return length */ if ((byte_count=php_strnlen(value, byte_count)) > 0) { return exif_process_undefined(result, value, byte_count TSRMLS_CC); } (*result) = estrndup("", 1); /* force empty string */ return byte_count+1; } /* }}} */ /* {{{ exif_process_user_comment * Process UserComment in IFD. */ static int exif_process_user_comment(image_info_type *ImageInfo, char **pszInfoPtr, char **pszEncoding, char *szValuePtr, int ByteCount TSRMLS_DC) { int a; char *decode; size_t len;; *pszEncoding = NULL; /* Copy the comment */ if (ByteCount>=8) { if (!memcmp(szValuePtr, "UNICODE\0", 8)) { *pszEncoding = estrdup((const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; /* First try to detect BOM: ZERO WIDTH NOBREAK SPACE (FEFF 16) * since we have no encoding support for the BOM yet we skip that. */ if (!memcmp(szValuePtr, "\xFE\xFF", 2)) { decode = "UCS-2BE"; szValuePtr = szValuePtr+2; ByteCount -= 2; } else if (!memcmp(szValuePtr, "\xFF\xFE", 2)) { decode = "UCS-2LE"; szValuePtr = szValuePtr+2; ByteCount -= 2; } else if (ImageInfo->motorola_intel) { decode = ImageInfo->decode_unicode_be; } else { decode = ImageInfo->decode_unicode_le; } /* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX */ if (zend_multibyte_encoding_converter( (unsigned char**)pszInfoPtr, &len, (unsigned char*)szValuePtr, ByteCount, zend_multibyte_fetch_encoding(ImageInfo->encode_unicode TSRMLS_CC), zend_multibyte_fetch_encoding(decode TSRMLS_CC) TSRMLS_CC) == (size_t)-1) { len = exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); } return len; } else if (!memcmp(szValuePtr, "ASCII\0\0\0", 8)) { *pszEncoding = estrdup((const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; } else if (!memcmp(szValuePtr, "JIS\0\0\0\0\0", 8)) { /* JIS should be tanslated to MB or we leave it to the user - leave it to the user */ *pszEncoding = estrdup((const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; /* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX */ if (zend_multibyte_encoding_converter( (unsigned char**)pszInfoPtr, &len, (unsigned char*)szValuePtr, ByteCount, zend_multibyte_fetch_encoding(ImageInfo->encode_jis TSRMLS_CC), zend_multibyte_fetch_encoding(ImageInfo->motorola_intel ? ImageInfo->decode_jis_be : ImageInfo->decode_jis_le TSRMLS_CC) TSRMLS_CC) == (size_t)-1) { len = exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); } return len; } else if (!memcmp(szValuePtr, "\0\0\0\0\0\0\0\0", 8)) { /* 8 NULL means undefined and should be ASCII... */ *pszEncoding = estrdup("UNDEFINED"); szValuePtr = szValuePtr+8; ByteCount -= 8; } } /* Olympus has this padded with trailing spaces. Remove these first. */ if (ByteCount>0) { for (a=ByteCount-1;a && szValuePtr[a]==' ';a--) { (szValuePtr)[a] = '\0'; } } /* normal text without encoding */ exif_process_string(pszInfoPtr, szValuePtr, ByteCount TSRMLS_CC); return strlen(*pszInfoPtr); } /* }}} */ /* {{{ exif_process_unicode * Process unicode field in IFD. */ static int exif_process_unicode(image_info_type *ImageInfo, xp_field_type *xp_field, int tag, char *szValuePtr, int ByteCount TSRMLS_DC) { xp_field->tag = tag; xp_field->value = NULL; /* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX */ if (zend_multibyte_encoding_converter( (unsigned char**)&xp_field->value, &xp_field->size, (unsigned char*)szValuePtr, ByteCount, zend_multibyte_fetch_encoding(ImageInfo->encode_unicode TSRMLS_CC), zend_multibyte_fetch_encoding(ImageInfo->motorola_intel ? ImageInfo->decode_unicode_be : ImageInfo->decode_unicode_le TSRMLS_CC) TSRMLS_CC) == (size_t)-1) { xp_field->size = exif_process_string_raw(&xp_field->value, szValuePtr, ByteCount); } return xp_field->size; } /* }}} */ /* {{{ exif_process_IFD_in_MAKERNOTE * Process nested IFDs directories in Maker Note. */ static int exif_process_IFD_in_MAKERNOTE(image_info_type *ImageInfo, char * value_ptr, int value_len, char *offset_base, size_t IFDlength, size_t displacement TSRMLS_DC) { int de, i=0, section_index = SECTION_MAKERNOTE; int NumDirEntries, old_motorola_intel, offset_diff; const maker_note_type *maker_note; char *dir_start; for (i=0; i<=sizeof(maker_note_array)/sizeof(maker_note_type); i++) { if (i==sizeof(maker_note_array)/sizeof(maker_note_type)) return FALSE; maker_note = maker_note_array+i; /*exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "check (%s,%s)", maker_note->make?maker_note->make:"", maker_note->model?maker_note->model:"");*/ if (maker_note->make && (!ImageInfo->make || strcmp(maker_note->make, ImageInfo->make))) continue; if (maker_note->model && (!ImageInfo->model || strcmp(maker_note->model, ImageInfo->model))) continue; if (maker_note->id_string && strncmp(maker_note->id_string, value_ptr, maker_note->id_string_len)) continue; break; } dir_start = value_ptr + maker_note->offset; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process %s @x%04X + 0x%04X=%d: %s", exif_get_sectionname(section_index), (int)dir_start-(int)offset_base+maker_note->offset+displacement, value_len, value_len, exif_char_dump(value_ptr, value_len, (int)dir_start-(int)offset_base+maker_note->offset+displacement)); #endif ImageInfo->sections_found |= FOUND_MAKERNOTE; old_motorola_intel = ImageInfo->motorola_intel; switch (maker_note->byte_order) { case MN_ORDER_INTEL: ImageInfo->motorola_intel = 0; break; case MN_ORDER_MOTOROLA: ImageInfo->motorola_intel = 1; break; default: case MN_ORDER_NORMAL: break; } NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); switch (maker_note->offset_mode) { case MN_OFFSET_MAKER: offset_base = value_ptr; break; case MN_OFFSET_GUESS: offset_diff = 2 + NumDirEntries*12 + 4 - php_ifd_get32u(dir_start+10, ImageInfo->motorola_intel); #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Using automatic offset correction: 0x%04X", ((int)dir_start-(int)offset_base+maker_note->offset+displacement) + offset_diff); #endif offset_base = value_ptr + offset_diff; break; default: case MN_OFFSET_NORMAL: break; } if ((2+NumDirEntries*12) > value_len) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size: 2 + x%04X*12 = x%04X > x%04X", NumDirEntries, 2+NumDirEntries*12, value_len); return FALSE; } for (de=0;de<NumDirEntries;de++) { if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de, offset_base, IFDlength, displacement, section_index, 0, maker_note->tag_table TSRMLS_CC)) { return FALSE; } } ImageInfo->motorola_intel = old_motorola_intel; /* NextDirOffset (must be NULL) = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);*/ #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(SECTION_MAKERNOTE)); #endif return TRUE; } /* }}} */ /* {{{ exif_process_IFD_TAG * Process one of the nested IFDs directories. */ static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table TSRMLS_DC) { size_t length; int tag, format, components; char *value_ptr, tagname[64], cbuf[32], *outside=NULL; size_t byte_count, offset_val, fpos, fgot; int64_t byte_count_signed; xp_field_type *tmp_xp; #ifdef EXIF_DEBUG char *dump_data; int dump_free; #endif /* EXIF_DEBUG */ /* Protect against corrupt headers */ if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "corrupt EXIF header: maximum directory nesting level reached"); return FALSE; } ImageInfo->ifd_nesting_level++; tag = php_ifd_get16u(dir_entry, ImageInfo->motorola_intel); format = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel); components = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel); if (!format || format > NUM_FORMATS) { /* (-1) catches illegal zero case as unsigned underflows to positive large. */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal format code 0x%04X, suppose BYTE", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), format); format = TAG_FMT_BYTE; /*return TRUE;*/ } if (components < 0) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal components(%ld)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), components); return FALSE; } byte_count_signed = (int64_t)components * php_tiff_bytes_per_format[format]; if (byte_count_signed < 0 || (byte_count_signed > INT32_MAX)) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal byte_count", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC)); return FALSE; } byte_count = (size_t)byte_count_signed; if (byte_count > 4) { offset_val = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); /* If its bigger than 4 bytes, the dir entry contains an offset. */ value_ptr = offset_base+offset_val; /* dir_entry is ImageInfo->file.list[sn].data+2+i*12 offset_base is ImageInfo->file.list[sn].data-dir_offset dir_entry - offset_base is dir_offset+2+i*12 */ if (byte_count > IFDlength || offset_val > IFDlength-byte_count || value_ptr < dir_entry || offset_val < (size_t)(dir_entry-offset_base)) { /* It is important to check for IMAGE_FILETYPE_TIFF * JPEG does not use absolute pointers instead its pointers are * relative to the start of the TIFF header in APP1 section. */ if (byte_count > ImageInfo->FileSize || offset_val>ImageInfo->FileSize-byte_count || (ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_II && ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_MM && ImageInfo->FileType!=IMAGE_FILETYPE_JPEG)) { if (value_ptr < dir_entry) { /* we can read this if offset_val > 0 */ /* some files have their values in other parts of the file */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X < x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, dir_entry); } else { /* this is for sure not allowed */ /* exception are IFD pointers */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X + x%04X = x%04X > x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, byte_count, offset_val+byte_count, IFDlength); } return FALSE; } if (byte_count>sizeof(cbuf)) { /* mark as outside range and get buffer */ value_ptr = safe_emalloc(byte_count, 1, 0); outside = value_ptr; } else { /* In most cases we only access a small range so * it is faster to use a static buffer there * BUT it offers also the possibility to have * pointers read without the need to free them * explicitley before returning. */ memset(&cbuf, 0, sizeof(cbuf)); value_ptr = cbuf; } fpos = php_stream_tell(ImageInfo->infile); php_stream_seek(ImageInfo->infile, offset_val, SEEK_SET); fgot = php_stream_tell(ImageInfo->infile); if (fgot!=offset_val) { EFREE_IF(outside); exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Wrong file pointer: 0x%08X != 0x%08X", fgot, offset_val); return FALSE; } fgot = php_stream_read(ImageInfo->infile, value_ptr, byte_count); php_stream_seek(ImageInfo->infile, fpos, SEEK_SET); if (fgot<byte_count) { EFREE_IF(outside); EXIF_ERRLOG_FILEEOF(ImageInfo) return FALSE; } } } else { /* 4 bytes or less and value is in the dir entry itself */ value_ptr = dir_entry+8; offset_val= value_ptr-offset_base; } ImageInfo->sections_found |= FOUND_ANY_TAG; #ifdef EXIF_DEBUG dump_data = exif_dump_data(&dump_free, format, components, length, ImageInfo->motorola_intel, value_ptr TSRMLS_CC); exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process tag(x%04X=%s,@x%04X + x%04X(=%d)): %s%s %s", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val+displacement, byte_count, byte_count, (components>1)&&format!=TAG_FMT_UNDEFINED&&format!=TAG_FMT_STRING?"ARRAY OF ":"", exif_get_tagformat(format), dump_data); if (dump_free) { efree(dump_data); } #endif if (section_index==SECTION_THUMBNAIL) { if (!ImageInfo->Thumbnail.data) { switch(tag) { case TAG_IMAGEWIDTH: case TAG_COMP_IMAGE_WIDTH: ImageInfo->Thumbnail.width = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_IMAGEHEIGHT: case TAG_COMP_IMAGE_HEIGHT: ImageInfo->Thumbnail.height = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_STRIP_OFFSETS: case TAG_JPEG_INTERCHANGE_FORMAT: /* accept both formats */ ImageInfo->Thumbnail.offset = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_STRIP_BYTE_COUNTS: if (ImageInfo->FileType == IMAGE_FILETYPE_TIFF_II || ImageInfo->FileType == IMAGE_FILETYPE_TIFF_MM) { ImageInfo->Thumbnail.filetype = ImageInfo->FileType; } else { /* motorola is easier to read */ ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_TIFF_MM; } ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_JPEG_INTERCHANGE_FORMAT_LEN: if (ImageInfo->Thumbnail.filetype == IMAGE_FILETYPE_UNKNOWN) { ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_JPEG; ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); } break; } } } else { if (section_index==SECTION_IFD0 || section_index==SECTION_EXIF) switch(tag) { case TAG_COPYRIGHT: /* check for "<photographer> NUL <editor> NUL" */ if (byte_count>1 && (length=php_strnlen(value_ptr, byte_count)) > 0) { if (length<byte_count-1) { /* When there are any characters after the first NUL */ ImageInfo->CopyrightPhotographer = estrdup(value_ptr); ImageInfo->CopyrightEditor = estrndup(value_ptr+length+1, byte_count-length-1); spprintf(&ImageInfo->Copyright, 0, "%s, %s", value_ptr, value_ptr+length+1); /* format = TAG_FMT_UNDEFINED; this musn't be ASCII */ /* but we are not supposed to change this */ /* keep in mind that image_info does not store editor value */ } else { ImageInfo->Copyright = estrndup(value_ptr, byte_count); } } break; case TAG_USERCOMMENT: ImageInfo->UserCommentLength = exif_process_user_comment(ImageInfo, &(ImageInfo->UserComment), &(ImageInfo->UserCommentEncoding), value_ptr, byte_count TSRMLS_CC); break; case TAG_XP_TITLE: case TAG_XP_COMMENTS: case TAG_XP_AUTHOR: case TAG_XP_KEYWORDS: case TAG_XP_SUBJECT: tmp_xp = (xp_field_type*)safe_erealloc(ImageInfo->xp_fields.list, (ImageInfo->xp_fields.count+1), sizeof(xp_field_type), 0); ImageInfo->sections_found |= FOUND_WINXP; ImageInfo->xp_fields.list = tmp_xp; ImageInfo->xp_fields.count++; exif_process_unicode(ImageInfo, &(ImageInfo->xp_fields.list[ImageInfo->xp_fields.count-1]), tag, value_ptr, byte_count TSRMLS_CC); break; case TAG_FNUMBER: /* Simplest way of expressing aperture, so I trust it the most. (overwrite previously computed value if there is one) */ ImageInfo->ApertureFNumber = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_APERTURE: case TAG_MAX_APERTURE: /* More relevant info always comes earlier, so only use this field if we don't have appropriate aperture information yet. */ if (ImageInfo->ApertureFNumber == 0) { ImageInfo->ApertureFNumber = (float)exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2)*0.5); } break; case TAG_SHUTTERSPEED: /* More complicated way of expressing exposure time, so only use this value if we don't already have it from somewhere else. SHUTTERSPEED comes after EXPOSURE TIME */ if (ImageInfo->ExposureTime == 0) { ImageInfo->ExposureTime = (float)(1/exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2))); } break; case TAG_EXPOSURETIME: ImageInfo->ExposureTime = -1; break; case TAG_COMP_IMAGE_WIDTH: ImageInfo->ExifImageWidth = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_FOCALPLANE_X_RES: ImageInfo->FocalplaneXRes = exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_SUBJECT_DISTANCE: /* Inidcates the distacne the autofocus camera is focused to. Tends to be less accurate as distance increases. */ ImageInfo->Distance = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC); break; case TAG_FOCALPLANE_RESOLUTION_UNIT: switch((int)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)) { case 1: ImageInfo->FocalplaneUnits = 25.4; break; /* inch */ case 2: /* According to the information I was using, 2 measn meters. But looking at the Cannon powershot's files, inches is the only sensible value. */ ImageInfo->FocalplaneUnits = 25.4; break; case 3: ImageInfo->FocalplaneUnits = 10; break; /* centimeter */ case 4: ImageInfo->FocalplaneUnits = 1; break; /* milimeter */ case 5: ImageInfo->FocalplaneUnits = .001; break; /* micrometer */ } break; case TAG_SUB_IFD: if (format==TAG_FMT_IFD) { /* If this is called we are either in a TIFFs thumbnail or a JPEG where we cannot handle it */ /* TIFF thumbnail: our data structure cannot store a thumbnail of a thumbnail */ /* JPEG do we have the data area and what to do with it */ exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Skip SUB IFD"); } break; case TAG_MAKE: ImageInfo->make = estrndup(value_ptr, byte_count); break; case TAG_MODEL: ImageInfo->model = estrndup(value_ptr, byte_count); break; case TAG_MAKER_NOTE: exif_process_IFD_in_MAKERNOTE(ImageInfo, value_ptr, byte_count, offset_base, IFDlength, displacement TSRMLS_CC); break; case TAG_EXIF_IFD_POINTER: case TAG_GPS_IFD_POINTER: case TAG_INTEROP_IFD_POINTER: if (ReadNextIFD) { char *Subdir_start; int sub_section_index = 0; switch(tag) { case TAG_EXIF_IFD_POINTER: #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found EXIF"); #endif ImageInfo->sections_found |= FOUND_EXIF; sub_section_index = SECTION_EXIF; break; case TAG_GPS_IFD_POINTER: #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found GPS"); #endif ImageInfo->sections_found |= FOUND_GPS; sub_section_index = SECTION_GPS; break; case TAG_INTEROP_IFD_POINTER: #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found INTEROPERABILITY"); #endif ImageInfo->sections_found |= FOUND_INTEROP; sub_section_index = SECTION_INTEROP; break; } Subdir_start = offset_base + php_ifd_get32u(value_ptr, ImageInfo->motorola_intel); if (Subdir_start < offset_base || Subdir_start > offset_base+IFDlength) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD Pointer"); return FALSE; } if (!exif_process_IFD_in_JPEG(ImageInfo, Subdir_start, offset_base, IFDlength, displacement, sub_section_index TSRMLS_CC)) { return FALSE; } #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(sub_section_index)); #endif } } } exif_iif_add_tag(ImageInfo, section_index, exif_get_tagname(tag, tagname, sizeof(tagname), tag_table TSRMLS_CC), tag, format, components, value_ptr TSRMLS_CC); EFREE_IF(outside); return TRUE; } /* }}} */ /* {{{ exif_process_IFD_in_JPEG * Process one of the nested IFDs directories. */ static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, char *offset_base, size_t IFDlength, size_t displacement, int section_index TSRMLS_DC) { int de; int NumDirEntries; int NextDirOffset; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process %s (x%04X(=%d))", exif_get_sectionname(section_index), IFDlength, IFDlength); #endif ImageInfo->sections_found |= FOUND_IFD0; NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); if ((dir_start+2+NumDirEntries*12) > (offset_base+IFDlength)) { if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de, offset_base, IFDlength, displacement, section_index, 1, exif_get_tag_table(section_index) TSRMLS_CC)) { return FALSE; } } /* * Ignore IFD2 if it purportedly exists */ if (section_index == SECTION_THUMBNAIL) { return TRUE; } /* * Hack to make it process IDF1 I hope * There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) to the thumbnail */ NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel); if (NextDirOffset) { * Hack to make it process IDF1 I hope * There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) to the thumbnail */ NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel); if (NextDirOffset) { /* the next line seems false but here IFDlength means length of all IFDs */ #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail size: 0x%04X", ImageInfo->Thumbnail.size); #endif if (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN && ImageInfo->Thumbnail.size && ImageInfo->Thumbnail.offset && ImageInfo->read_thumbnail ) { exif_thumbnail_extract(ImageInfo, offset_base, IFDlength TSRMLS_CC); } return TRUE; } else { return FALSE; } } return TRUE; } /* }}} */ /* {{{ exif_process_TIFF_in_JPEG Process a TIFF header in a JPEG file */ static void exif_process_TIFF_in_JPEG(image_info_type *ImageInfo, char *CharBuf, size_t length, size_t displacement TSRMLS_DC) { unsigned exif_value_2a, offset_of_ifd; /* set the thumbnail stuff to nothing so we can test to see if they get set up */ if (memcmp(CharBuf, "II", 2) == 0) { ImageInfo->motorola_intel = 0; } else if (memcmp(CharBuf, "MM", 2) == 0) { ImageInfo->motorola_intel = 1; } else { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF alignment marker"); return; } /* Check the next two values for correctness. */ exif_value_2a = php_ifd_get16u(CharBuf+2, ImageInfo->motorola_intel); offset_of_ifd = php_ifd_get32u(CharBuf+4, ImageInfo->motorola_intel); if ( exif_value_2a != 0x2a || offset_of_ifd < 0x08) { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF start (1)"); return; } } /* Check the next two values for correctness. */ exif_value_2a = php_ifd_get16u(CharBuf+2, ImageInfo->motorola_intel); offset_of_ifd = php_ifd_get32u(CharBuf+4, ImageInfo->motorola_intel); if ( exif_value_2a != 0x2a || offset_of_ifd < 0x08) { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF start (1)"); return; } /* Compute the CCD width, in milimeters. */ if (ImageInfo->FocalplaneXRes != 0) { ImageInfo->CCDWidth = (float)(ImageInfo->ExifImageWidth * ImageInfo->FocalplaneUnits / ImageInfo->FocalplaneXRes); } } /* }}} */ Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: The exif_process_TIFF_in_JPEG function in ext/exif/exif.c in PHP before 5.5.35, 5.6.x before 5.6.21, and 7.x before 7.0.6 does not validate TIFF start data, which allows remote attackers to cause a denial of service (out-of-bounds read) or possibly have unspecified other impact via crafted header data. Commit Message:
High
165,031
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: header_put_be_short (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 2) { psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_be_short */ 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
170,052
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: bool Chapters::Edition::ExpandAtomsArray() { if (m_atoms_size > m_atoms_count) return true; // nothing else to do const int size = (m_atoms_size == 0) ? 1 : 2 * m_atoms_size; Atom* const atoms = new (std::nothrow) Atom[size]; if (atoms == NULL) return false; for (int idx = 0; idx < m_atoms_count; ++idx) { m_atoms[idx].ShallowCopy(atoms[idx]); } delete[] m_atoms; m_atoms = atoms; m_atoms_size = size; return true; } 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: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
High
174,274
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: MagickExport XMLTreeInfo *NewXMLTree(const char *xml,ExceptionInfo *exception) { char **attribute, **attributes, *tag, *utf8; int c, terminal; MagickBooleanType status; register char *p; register ssize_t i; size_t ignore_depth, length; ssize_t j, l; XMLTreeRoot *root; /* Convert xml-string to UTF8. */ if ((xml == (const char *) NULL) || (strlen(xml) == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "ParseError","root tag missing"); return((XMLTreeInfo *) NULL); } root=(XMLTreeRoot *) NewXMLTreeTag((char *) NULL); length=strlen(xml); utf8=ConvertUTF16ToUTF8(xml,&length); if (utf8 == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "ParseError","UTF16 to UTF8 failed"); return((XMLTreeInfo *) NULL); } terminal=utf8[length-1]; utf8[length-1]='\0'; p=utf8; while ((*p != '\0') && (*p != '<')) p++; if (*p == '\0') { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "ParseError","root tag missing"); utf8=DestroyString(utf8); return((XMLTreeInfo *) NULL); } attribute=(char **) NULL; l=0; ignore_depth=0; for (p++; ; p++) { attributes=(char **) sentinel; tag=p; c=(*p); if ((isalpha((int) ((unsigned char) *p)) !=0) || (*p == '_') || (*p == ':') || (c < '\0')) { /* Tag. */ if (root->node == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"ParseError","root tag missing"); utf8=DestroyString(utf8); return(&root->root); } p+=strcspn(p,XMLWhitespace "/>"); while (isspace((int) ((unsigned char) *p)) != 0) *p++='\0'; if (ignore_depth == 0) { if ((*p != '\0') && (*p != '/') && (*p != '>')) { /* Find tag in default attributes list. */ i=0; while ((root->attributes[i] != (char **) NULL) && (strcmp(root->attributes[i][0],tag) != 0)) i++; attribute=root->attributes[i]; } for (l=0; (*p != '\0') && (*p != '/') && (*p != '>'); l+=2) { /* Attribute. */ if (l == 0) attributes=(char **) AcquireQuantumMemory(4, sizeof(*attributes)); else attributes=(char **) ResizeQuantumMemory(attributes, (size_t) (l+4),sizeof(*attributes)); if (attributes == (char **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); utf8=DestroyString(utf8); return(&root->root); } attributes[l+2]=(char *) NULL; attributes[l+1]=(char *) NULL; attributes[l]=p; p+=strcspn(p,XMLWhitespace "=/>"); if ((*p != '=') && (isspace((int) ((unsigned char) *p)) == 0)) attributes[l]=ConstantString(""); else { *p++='\0'; p+=strspn(p,XMLWhitespace "="); c=(*p); if ((c == '"') || (c == '\'')) { /* Attributes value. */ p++; attributes[l+1]=p; while ((*p != '\0') && (*p != c)) p++; if (*p != '\0') *p++='\0'; else { attributes[l]=ConstantString(""); attributes[l+1]=ConstantString(""); (void) DestroyXMLTreeAttributes(attributes); (void) ThrowMagickException(exception, GetMagickModule(),OptionWarning,"ParseError", "missing %c",c); utf8=DestroyString(utf8); return(&root->root); } j=1; while ((attribute != (char **) NULL) && (attribute[j] != (char *) NULL) && (strcmp(attribute[j],attributes[l]) != 0)) j+=3; attributes[l+1]=ParseEntities(attributes[l+1], root->entities,(attribute != (char **) NULL) && (attribute[j] != (char *) NULL) ? *attribute[j+2] : ' '); } attributes[l]=ConstantString(attributes[l]); } while (isspace((int) ((unsigned char) *p)) != 0) p++; } } else { while((*p != '\0') && (*p != '/') && (*p != '>')) p++; } if (*p == '/') { /* Self closing tag. */ *p++='\0'; if (((*p != '\0') && (*p != '>')) || ((*p == '\0') && (terminal != '>'))) { if (l != 0) (void) DestroyXMLTreeAttributes(attributes); (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"ParseError","missing >"); utf8=DestroyString(utf8); return(&root->root); } if ((ignore_depth == 0) && (IsSkipTag(tag) == MagickFalse)) { ParseOpenTag(root,tag,attributes); (void) ParseCloseTag(root,tag,exception); } } else { c=(*p); if ((*p == '>') || ((*p == '\0') && (terminal == '>'))) { *p='\0'; if ((ignore_depth == 0) && (IsSkipTag(tag) == MagickFalse)) ParseOpenTag(root,tag,attributes); else ignore_depth++; *p=c; } else { if (l != 0) (void) DestroyXMLTreeAttributes(attributes); (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"ParseError","missing >"); utf8=DestroyString(utf8); return(&root->root); } } } else if (*p == '/') { /* Close tag. */ tag=p+1; p+=strcspn(tag,XMLWhitespace ">")+1; c=(*p); if ((c == '\0') && (terminal != '>')) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"ParseError","missing >"); utf8=DestroyString(utf8); return(&root->root); } *p='\0'; if (ignore_depth == 0 && ParseCloseTag(root,tag,exception) != (XMLTreeInfo *) NULL) { utf8=DestroyString(utf8); return(&root->root); } if (ignore_depth > 0) ignore_depth--; *p=c; if (isspace((int) ((unsigned char) *p)) != 0) p+=strspn(p,XMLWhitespace); } else if (strncmp(p,"!--",3) == 0) { /* Comment. */ p=strstr(p+3,"--"); if ((p == (char *) NULL) || ((*(p+=2) != '>') && (*p != '\0')) || ((*p == '\0') && (terminal != '>'))) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"ParseError","unclosed <!--"); utf8=DestroyString(utf8); return(&root->root); } } else if (strncmp(p,"![CDATA[",8) == 0) { /* Cdata. */ p=strstr(p,"]]>"); if (p != (char *) NULL) { p+=2; if (ignore_depth == 0) ParseCharacterContent(root,tag+8,(size_t) (p-tag-10),'c'); } else { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"ParseError","unclosed <![CDATA["); utf8=DestroyString(utf8); return(&root->root); } } else if (strncmp(p,"!DOCTYPE",8) == 0) { /* DTD. */ for (l=0; (*p != '\0') && (((l == 0) && (*p != '>')) || ((l != 0) && ((*p != ']') || (*(p+strspn(p+1,XMLWhitespace)+1) != '>')))); l=(ssize_t) ((*p == '[') ? 1 : l)) p+=strcspn(p+1,"[]>")+1; if ((*p == '\0') && (terminal != '>')) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"ParseError","unclosed <!DOCTYPE"); utf8=DestroyString(utf8); return(&root->root); } if (l != 0) tag=strchr(tag,'[')+1; if (l != 0) { status=ParseInternalDoctype(root,tag,(size_t) (p-tag), exception); if (status == MagickFalse) { utf8=DestroyString(utf8); return(&root->root); } p++; } } else if (*p == '?') { /* Processing instructions. */ do { p=strchr(p,'?'); if (p == (char *) NULL) break; p++; } while ((*p != '\0') && (*p != '>')); if ((p == (char *) NULL) || ((*p == '\0') && (terminal != '>'))) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"ParseError","unclosed <?"); utf8=DestroyString(utf8); return(&root->root); } ParseProcessingInstructions(root,tag+1,(size_t) (p-tag-2)); } else { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"ParseError","unexpected <"); utf8=DestroyString(utf8); return(&root->root); } if ((p == (char *) NULL) || (*p == '\0')) break; *p++='\0'; tag=p; if ((*p != '\0') && (*p != '<')) { /* Tag character content. */ while ((*p != '\0') && (*p != '<')) p++; if (*p == '\0') break; if (ignore_depth == 0) ParseCharacterContent(root,tag,(size_t) (p-tag),'&'); } else if (*p == '\0') break; } utf8=DestroyString(utf8); if (root->node == (XMLTreeInfo *) NULL) return(&root->root); if (root->node->tag == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "ParseError","root tag missing"); return(&root->root); } (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "ParseError","unclosed tag: `%s'",root->node->tag); return(&root->root); } Vulnerability Type: Dir. Trav. CWE ID: CWE-22 Summary: Directory traversal vulnerability in magick/module.c in ImageMagick 6.9.4-7 allows remote attackers to load arbitrary modules via unspecified vectors. Commit Message: Coder path traversal is not authorized, bug report provided by Masaaki Chida
Medium
168,643
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static int llc_ui_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sockaddr_llc *uaddr = (struct sockaddr_llc *)msg->msg_name; const int nonblock = flags & MSG_DONTWAIT; struct sk_buff *skb = NULL; struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); unsigned long cpu_flags; size_t copied = 0; u32 peek_seq = 0; u32 *seq; unsigned long used; int target; /* Read at least this many bytes */ long timeo; msg->msg_namelen = 0; lock_sock(sk); copied = -ENOTCONN; if (unlikely(sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_LISTEN)) goto out; timeo = sock_rcvtimeo(sk, nonblock); seq = &llc->copied_seq; if (flags & MSG_PEEK) { peek_seq = llc->copied_seq; seq = &peek_seq; } target = sock_rcvlowat(sk, flags & MSG_WAITALL, len); copied = 0; do { u32 offset; /* * We need to check signals first, to get correct SIGURG * handling. FIXME: Need to check this doesn't impact 1003.1g * and move it down to the bottom of the loop */ if (signal_pending(current)) { if (copied) break; copied = timeo ? sock_intr_errno(timeo) : -EAGAIN; break; } /* Next get a buffer. */ skb = skb_peek(&sk->sk_receive_queue); if (skb) { offset = *seq; goto found_ok_skb; } /* Well, if we have backlog, try to process it now yet. */ if (copied >= target && !sk->sk_backlog.tail) break; if (copied) { if (sk->sk_err || sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN) || !timeo || (flags & MSG_PEEK)) break; } else { if (sock_flag(sk, SOCK_DONE)) break; if (sk->sk_err) { copied = sock_error(sk); break; } if (sk->sk_shutdown & RCV_SHUTDOWN) break; if (sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_CLOSE) { if (!sock_flag(sk, SOCK_DONE)) { /* * This occurs when user tries to read * from never connected socket. */ copied = -ENOTCONN; break; } break; } if (!timeo) { copied = -EAGAIN; break; } } if (copied >= target) { /* Do not sleep, just process backlog. */ release_sock(sk); lock_sock(sk); } else sk_wait_data(sk, &timeo); if ((flags & MSG_PEEK) && peek_seq != llc->copied_seq) { net_dbg_ratelimited("LLC(%s:%d): Application bug, race in MSG_PEEK\n", current->comm, task_pid_nr(current)); peek_seq = llc->copied_seq; } continue; found_ok_skb: /* Ok so how much can we use? */ used = skb->len - offset; if (len < used) used = len; if (!(flags & MSG_TRUNC)) { int rc = skb_copy_datagram_iovec(skb, offset, msg->msg_iov, used); if (rc) { /* Exception. Bailout! */ if (!copied) copied = -EFAULT; break; } } *seq += used; copied += used; len -= used; /* For non stream protcols we get one packet per recvmsg call */ if (sk->sk_type != SOCK_STREAM) goto copy_uaddr; if (!(flags & MSG_PEEK)) { spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags); sk_eat_skb(sk, skb, false); spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags); *seq = 0; } /* Partial read */ if (used + offset < skb->len) continue; } while (len > 0); out: release_sock(sk); return copied; copy_uaddr: if (uaddr != NULL && skb != NULL) { memcpy(uaddr, llc_ui_skb_cb(skb), sizeof(*uaddr)); msg->msg_namelen = sizeof(*uaddr); } if (llc_sk(sk)->cmsg_flags) llc_cmsg_rcv(msg, skb); if (!(flags & MSG_PEEK)) { spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags); sk_eat_skb(sk, skb, false); spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags); *seq = 0; } goto out; } Vulnerability Type: +Info CWE ID: CWE-20 Summary: The x25_recvmsg function in net/x25/af_x25.c in the Linux kernel before 3.12.4 updates a certain length value without ensuring that an associated data structure has been initialized, which allows local users to obtain sensitive information from kernel memory via a (1) recvfrom, (2) recvmmsg, or (3) recvmsg system call. Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]>
Medium
166,506
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static PHP_GINIT_FUNCTION(libxml) { libxml_globals->stream_context = NULL; libxml_globals->error_buffer.c = NULL; libxml_globals->error_list = NULL; } Vulnerability Type: +Info CWE ID: CWE-200 Summary: The SOAP parser in PHP before 5.3.23 and 5.4.x before 5.4.13 allows remote attackers to read arbitrary files via a SOAP WSDL file containing an XML external entity declaration in conjunction with an entity reference, related to an XML External Entity (XXE) issue in the soap_xmlParseFile and soap_xmlParseMemory functions. NOTE: this vulnerability exists because of an incorrect fix for CVE-2013-1824. Commit Message:
Medium
164,744
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static char *create_output_name(unsigned char *fname, unsigned char *dir, int lower, int isunix, int utf8) { unsigned char *p, *name, c, *fe, sep, slash; unsigned int x; sep = (isunix) ? '/' : '\\'; /* the path-seperator */ slash = (isunix) ? '\\' : '/'; /* the other slash */ /* length of filename */ x = strlen((char *) fname); /* UTF8 worst case scenario: tolower() expands all chars from 1 to 3 bytes */ if (utf8) x *= 3; /* length of output directory */ if (dir) x += strlen((char *) dir); if (!(name = (unsigned char *) malloc(x + 2))) { fprintf(stderr, "out of memory!\n"); return NULL; } /* start with blank name */ *name = '\0'; /* add output directory if needed */ if (dir) { strcpy((char *) name, (char *) dir); strcat((char *) name, "/"); } /* remove leading slashes */ while (*fname == sep) fname++; /* copy from fi->filename to new name, converting MS-DOS slashes to UNIX * slashes as we go. Also lowercases characters if needed. */ p = &name[strlen((char *)name)]; fe = &fname[strlen((char *)fname)]; if (utf8) { /* UTF8 translates two-byte unicode characters into 1, 2 or 3 bytes. * %000000000xxxxxxx -> %0xxxxxxx * %00000xxxxxyyyyyy -> %110xxxxx %10yyyyyy * %xxxxyyyyyyzzzzzz -> %1110xxxx %10yyyyyy %10zzzzzz * * Therefore, the inverse is as follows: * First char: * 0x00 - 0x7F = one byte char * 0x80 - 0xBF = invalid * 0xC0 - 0xDF = 2 byte char (next char only 0x80-0xBF is valid) * 0xE0 - 0xEF = 3 byte char (next 2 chars only 0x80-0xBF is valid) * 0xF0 - 0xFF = invalid */ do { if (fname >= fe) { free(name); return NULL; } /* get next UTF8 char */ if ((c = *fname++) < 0x80) x = c; else { if ((c >= 0xC0) && (c < 0xE0)) { x = (c & 0x1F) << 6; x |= *fname++ & 0x3F; } else if ((c >= 0xE0) && (c < 0xF0)) { x = (c & 0xF) << 12; x |= (*fname++ & 0x3F) << 6; x |= *fname++ & 0x3F; } else x = '?'; } /* whatever is the path seperator -> '/' * whatever is the other slash -> '\\' * otherwise, if lower is set, the lowercase version */ if (x == sep) x = '/'; else if (x == slash) x = '\\'; else if (lower) x = (unsigned int) tolower((int) x); /* integer back to UTF8 */ if (x < 0x80) { *p++ = (unsigned char) x; } else if (x < 0x800) { *p++ = 0xC0 | (x >> 6); *p++ = 0x80 | (x & 0x3F); } else { *p++ = 0xE0 | (x >> 12); *p++ = 0x80 | ((x >> 6) & 0x3F); *p++ = 0x80 | (x & 0x3F); } } while (x); } else { /* regular non-utf8 version */ do { c = *fname++; if (c == sep) c = '/'; else if (c == slash) c = '\\'; else if (lower) c = (unsigned char) tolower((int) c); } while ((*p++ = c)); } return (char *) name; } Vulnerability Type: Dir. Trav. CWE ID: CWE-22 Summary: ** DISPUTED ** chmextract.c in the chmextract sample program, as distributed with libmspack before 0.8alpha, does not protect against absolute/relative pathnames in CHM files, leading to Directory Traversal. NOTE: the vendor disputes that this is a libmspack vulnerability, because chmextract.c was only intended as a source-code example, not a supported application. Commit Message: add anti "../" and leading slash protection to chmextract
Medium
169,001
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: cdf_read_short_sector_chain(const cdf_header_t *h, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SEC_SIZE(h), i, j; scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h)); scn->sst_dirlen = len; if (sst->sst_tab == NULL || scn->sst_len == (size_t)-1) return -1; scn->sst_tab = calloc(scn->sst_len, ss); if (scn->sst_tab == NULL) return -1; for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sector chain loop limit")); errno = EFTYPE; goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); errno = EFTYPE; goto out; } if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h, sid) != (ssize_t)ss) { DPRINTF(("Reading short sector chain %d", sid)); goto out; } sid = CDF_TOLE4((uint32_t)ssat->sat_tab[sid]); } return 0; out: free(scn->sst_tab); return -1; } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: file before 5.11 and libmagic allow remote attackers to cause a denial of service (crash) via a crafted Composite Document File (CDF) file that triggers (1) an out-of-bounds read or (2) an invalid pointer dereference. Commit Message: Fix bounds checks again.
Medium
165,625
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: std::unique_ptr<HistogramBase> PersistentHistogramAllocator::CreateHistogram( PersistentHistogramData* histogram_data_ptr) { if (!histogram_data_ptr) { RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_METADATA_POINTER); NOTREACHED(); return nullptr; } if (histogram_data_ptr->histogram_type == SPARSE_HISTOGRAM) { std::unique_ptr<HistogramBase> histogram = SparseHistogram::PersistentCreate(this, histogram_data_ptr->name, &histogram_data_ptr->samples_metadata, &histogram_data_ptr->logged_metadata); DCHECK(histogram); histogram->SetFlags(histogram_data_ptr->flags); RecordCreateHistogramResult(CREATE_HISTOGRAM_SUCCESS); return histogram; } int32_t histogram_type = histogram_data_ptr->histogram_type; int32_t histogram_flags = histogram_data_ptr->flags; int32_t histogram_minimum = histogram_data_ptr->minimum; int32_t histogram_maximum = histogram_data_ptr->maximum; uint32_t histogram_bucket_count = histogram_data_ptr->bucket_count; uint32_t histogram_ranges_ref = histogram_data_ptr->ranges_ref; uint32_t histogram_ranges_checksum = histogram_data_ptr->ranges_checksum; HistogramBase::Sample* ranges_data = memory_allocator_->GetAsArray<HistogramBase::Sample>( histogram_ranges_ref, kTypeIdRangesArray, PersistentMemoryAllocator::kSizeAny); const uint32_t max_buckets = std::numeric_limits<uint32_t>::max() / sizeof(HistogramBase::Sample); size_t required_bytes = (histogram_bucket_count + 1) * sizeof(HistogramBase::Sample); size_t allocated_bytes = memory_allocator_->GetAllocSize(histogram_ranges_ref); if (!ranges_data || histogram_bucket_count < 2 || histogram_bucket_count >= max_buckets || allocated_bytes < required_bytes) { RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_RANGES_ARRAY); NOTREACHED(); return nullptr; } std::unique_ptr<const BucketRanges> created_ranges = CreateRangesFromData( ranges_data, histogram_ranges_checksum, histogram_bucket_count + 1); if (!created_ranges) { RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_RANGES_ARRAY); NOTREACHED(); return nullptr; } const BucketRanges* ranges = StatisticsRecorder::RegisterOrDeleteDuplicateRanges( created_ranges.release()); size_t counts_bytes = CalculateRequiredCountsBytes(histogram_bucket_count); PersistentMemoryAllocator::Reference counts_ref = subtle::Acquire_Load(&histogram_data_ptr->counts_ref); if (counts_bytes == 0 || (counts_ref != 0 && memory_allocator_->GetAllocSize(counts_ref) < counts_bytes)) { RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_COUNTS_ARRAY); NOTREACHED(); return nullptr; } DelayedPersistentAllocation counts_data(memory_allocator_.get(), &histogram_data_ptr->counts_ref, kTypeIdCountsArray, counts_bytes, 0); DelayedPersistentAllocation logged_data( memory_allocator_.get(), &histogram_data_ptr->counts_ref, kTypeIdCountsArray, counts_bytes, counts_bytes / 2, /*make_iterable=*/false); const char* name = histogram_data_ptr->name; std::unique_ptr<HistogramBase> histogram; switch (histogram_type) { case HISTOGRAM: histogram = Histogram::PersistentCreate( name, histogram_minimum, histogram_maximum, ranges, counts_data, logged_data, &histogram_data_ptr->samples_metadata, &histogram_data_ptr->logged_metadata); DCHECK(histogram); break; case LINEAR_HISTOGRAM: histogram = LinearHistogram::PersistentCreate( name, histogram_minimum, histogram_maximum, ranges, counts_data, logged_data, &histogram_data_ptr->samples_metadata, &histogram_data_ptr->logged_metadata); DCHECK(histogram); break; case BOOLEAN_HISTOGRAM: histogram = BooleanHistogram::PersistentCreate( name, ranges, counts_data, logged_data, &histogram_data_ptr->samples_metadata, &histogram_data_ptr->logged_metadata); DCHECK(histogram); break; case CUSTOM_HISTOGRAM: histogram = CustomHistogram::PersistentCreate( name, ranges, counts_data, logged_data, &histogram_data_ptr->samples_metadata, &histogram_data_ptr->logged_metadata); DCHECK(histogram); break; default: NOTREACHED(); } if (histogram) { DCHECK_EQ(histogram_type, histogram->GetHistogramType()); histogram->SetFlags(histogram_flags); RecordCreateHistogramResult(CREATE_HISTOGRAM_SUCCESS); } else { RecordCreateHistogramResult(CREATE_HISTOGRAM_UNKNOWN_TYPE); } return histogram; } Vulnerability Type: Bypass CWE ID: CWE-264 Summary: The Extensions subsystem in Google Chrome before 49.0.2623.75 does not properly maintain own properties, which allows remote attackers to bypass intended access restrictions via crafted JavaScript code that triggers an incorrect cast, related to extensions/renderer/v8_helpers.h and gin/converter.h. Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <[email protected]> Reviewed-by: Alexei Svitkine <[email protected]> Cr-Commit-Position: refs/heads/master@{#549986}
Medium
172,132
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static int createFromTiffRgba(TIFF * tif, gdImagePtr im) { int a; int x, y; int alphaBlendingFlag = 0; int color; int width = im->sx; int height = im->sy; uint32 *buffer; uint32 rgba; /* switch off colour merging on target gd image just while we write out * content - we want to preserve the alpha data until the user chooses * what to do with the image */ alphaBlendingFlag = im->alphaBlendingFlag; gdImageAlphaBlending(im, 0); buffer = (uint32 *) gdCalloc(sizeof(uint32), width * height); if (!buffer) { return GD_FAILURE; } TIFFReadRGBAImage(tif, width, height, buffer, 0); for(y = 0; y < height; y++) { for(x = 0; x < width; x++) { /* if it doesn't already exist, allocate a new colour, * else use existing one */ rgba = buffer[(y * width + x)]; a = (0xff - TIFFGetA(rgba)) / 2; color = gdTrueColorAlpha(TIFFGetR(rgba), TIFFGetG(rgba), TIFFGetB(rgba), a); /* set pixel colour to this colour */ gdImageSetPixel(im, x, height - y - 1, color); } } gdFree(buffer); /* now reset colour merge for alpha blending routines */ gdImageAlphaBlending(im, alphaBlendingFlag); return GD_SUCCESS; } Vulnerability Type: DoS CWE ID: CWE-125 Summary: The dynamicGetbuf function in the GD Graphics Library (aka libgd) before 2.2.4 allows remote attackers to cause a denial of service (out-of-bounds read) via a crafted TIFF image. Commit Message: Fix invalid read in gdImageCreateFromTiffPtr() tiff_invalid_read.tiff is corrupt, and causes an invalid read in gdImageCreateFromTiffPtr(), but not in gdImageCreateFromTiff(). The culprit is dynamicGetbuf(), which doesn't check for out-of-bound reads. In this case, dynamicGetbuf() is called with a negative dp->pos, but also positive buffer overflows have to be handled, in which case 0 has to be returned (cf. commit 75e29a9). Fixing dynamicGetbuf() exhibits that the corrupt TIFF would still create the image, because the return value of TIFFReadRGBAImage() is not checked. We do that, and let createFromTiffRgba() fail if TIFFReadRGBAImage() fails. This issue had been reported by Ibrahim El-Sayed to [email protected]. CVE-2016-6911
Medium
168,822
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void WebGLRenderingContextBase::TexImageImpl( TexImageFunctionID function_id, GLenum target, GLint level, GLint internalformat, GLint xoffset, GLint yoffset, GLint zoffset, GLenum format, GLenum type, Image* image, WebGLImageConversion::ImageHtmlDomSource dom_source, bool flip_y, bool premultiply_alpha, const IntRect& source_image_rect, GLsizei depth, GLint unpack_image_height) { const char* func_name = GetTexImageFunctionName(function_id); if (type == GL_UNSIGNED_INT_10F_11F_11F_REV) { type = GL_FLOAT; } Vector<uint8_t> data; IntRect sub_rect = source_image_rect; if (sub_rect == SentinelEmptyRect()) { sub_rect = SafeGetImageSize(image); } bool selecting_sub_rectangle = false; if (!ValidateTexImageSubRectangle(func_name, function_id, image, sub_rect, depth, unpack_image_height, &selecting_sub_rectangle)) { return; } IntRect adjusted_source_image_rect = sub_rect; if (flip_y) { adjusted_source_image_rect.SetY(image->height() - adjusted_source_image_rect.MaxY()); } WebGLImageConversion::ImageExtractor image_extractor( image, dom_source, premultiply_alpha, unpack_colorspace_conversion_ == GL_NONE); if (!image_extractor.ImagePixelData()) { SynthesizeGLError(GL_INVALID_VALUE, func_name, "bad image data"); return; } WebGLImageConversion::DataFormat source_data_format = image_extractor.ImageSourceFormat(); WebGLImageConversion::AlphaOp alpha_op = image_extractor.ImageAlphaOp(); const void* image_pixel_data = image_extractor.ImagePixelData(); bool need_conversion = true; if (type == GL_UNSIGNED_BYTE && source_data_format == WebGLImageConversion::kDataFormatRGBA8 && format == GL_RGBA && alpha_op == WebGLImageConversion::kAlphaDoNothing && !flip_y && !selecting_sub_rectangle && depth == 1) { need_conversion = false; } else { if (!WebGLImageConversion::PackImageData( image, image_pixel_data, format, type, flip_y, alpha_op, source_data_format, image_extractor.ImageWidth(), image_extractor.ImageHeight(), adjusted_source_image_rect, depth, image_extractor.ImageSourceUnpackAlignment(), unpack_image_height, data)) { SynthesizeGLError(GL_INVALID_VALUE, func_name, "packImage error"); return; } } ScopedUnpackParametersResetRestore temporary_reset_unpack(this); if (function_id == kTexImage2D) { TexImage2DBase(target, level, internalformat, adjusted_source_image_rect.Width(), adjusted_source_image_rect.Height(), 0, format, type, need_conversion ? data.data() : image_pixel_data); } else if (function_id == kTexSubImage2D) { ContextGL()->TexSubImage2D( target, level, xoffset, yoffset, adjusted_source_image_rect.Width(), adjusted_source_image_rect.Height(), format, type, need_conversion ? data.data() : image_pixel_data); } else { if (function_id == kTexImage3D) { ContextGL()->TexImage3D( target, level, internalformat, adjusted_source_image_rect.Width(), adjusted_source_image_rect.Height(), depth, 0, format, type, need_conversion ? data.data() : image_pixel_data); } else { DCHECK_EQ(function_id, kTexSubImage3D); ContextGL()->TexSubImage3D( target, level, xoffset, yoffset, zoffset, adjusted_source_image_rect.Width(), adjusted_source_image_rect.Height(), depth, format, type, need_conversion ? data.data() : image_pixel_data); } } } Vulnerability Type: CWE ID: CWE-125 Summary: Insufficient data validation in WebGL in Google Chrome prior to 64.0.3282.119 allowed a remote attacker to perform an out of bounds memory read via a crafted HTML page. Commit Message: Tighten about IntRect use in WebGL with overflow detection BUG=784183 TEST=test case in the bug in ASAN build [email protected] Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: Ie25ca328af99de7828e28e6a6e3d775f1bebc43f Reviewed-on: https://chromium-review.googlesource.com/811826 Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#522213}
Medium
172,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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void FragmentPaintPropertyTreeBuilder::UpdateScrollAndScrollTranslation() { DCHECK(properties_); if (NeedsPaintPropertyUpdate()) { if (NeedsScrollNode(object_)) { const LayoutBox& box = ToLayoutBox(object_); auto* scrollable_area = box.GetScrollableArea(); ScrollPaintPropertyNode::State state; state.container_rect = PixelSnappedIntRect( box.OverflowClipRect(context_.current.paint_offset)); state.contents_rect = IntRect( -scrollable_area->ScrollOrigin() + state.container_rect.Location(), scrollable_area->ContentsSize()); if (box.HasFlippedBlocksWritingMode()) state.contents_rect.Move(box.VerticalScrollbarWidth(), 0); state.user_scrollable_horizontal = scrollable_area->UserInputScrollable(kHorizontalScrollbar); state.user_scrollable_vertical = scrollable_area->UserInputScrollable(kVerticalScrollbar); auto ancestor_reasons = context_.current.scroll->GetMainThreadScrollingReasons(); state.main_thread_scrolling_reasons = GetMainThreadScrollingReasons(object_, ancestor_reasons); if (auto* existing_scroll = properties_->Scroll()) { if (existing_scroll->GetMainThreadScrollingReasons() != state.main_thread_scrolling_reasons) full_context_.force_subtree_update = true; } if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() || RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) state.compositor_element_id = scrollable_area->GetCompositorElementId(); OnUpdate( properties_->UpdateScroll(context_.current.scroll, std::move(state))); } else { OnClear(properties_->ClearScroll()); } if (NeedsScrollOrScrollTranslation(object_)) { const LayoutBox& box = ToLayoutBox(object_); TransformPaintPropertyNode::State state; IntSize scroll_offset = box.ScrolledContentOffset(); state.matrix.Translate(-scroll_offset.Width(), -scroll_offset.Height()); state.flattens_inherited_transform = context_.current.should_flatten_inherited_transform; if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() || RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) { state.direct_compositing_reasons = CompositingReasonsForScroll(box); state.rendering_context_id = context_.current.rendering_context_id; } state.scroll = properties_->Scroll(); OnUpdate(properties_->UpdateScrollTranslation(context_.current.transform, std::move(state))); } else { OnClear(properties_->ClearScrollTranslation()); } } if (properties_->Scroll()) context_.current.scroll = properties_->Scroll(); if (properties_->ScrollTranslation()) { context_.current.transform = properties_->ScrollTranslation(); context_.current.should_flatten_inherited_transform = false; } } Vulnerability Type: DoS CWE ID: Summary: Multiple unspecified vulnerabilities in Google Chrome before 47.0.2526.73 allow attackers to cause a denial of service or possibly have other impact via unknown vectors. Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930}
High
171,804
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static void php_pgsql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent) { char *host=NULL,*port=NULL,*options=NULL,*tty=NULL,*dbname=NULL,*connstring=NULL; PGconn *pgsql; smart_str str = {0}; zval **args[5]; int i, connect_type = 0; PGresult *pg_result; if (ZEND_NUM_ARGS() < 1 || ZEND_NUM_ARGS() > 5 || zend_get_parameters_array_ex(ZEND_NUM_ARGS(), args) == FAILURE) { WRONG_PARAM_COUNT; } smart_str_appends(&str, "pgsql"); for (i = 0; i < ZEND_NUM_ARGS(); i++) { /* make sure that the PGSQL_CONNECT_FORCE_NEW bit is not part of the hash so that subsequent connections * can re-use this connection. Bug #39979 */ if (i == 1 && ZEND_NUM_ARGS() == 2 && Z_TYPE_PP(args[i]) == IS_LONG) { if (Z_LVAL_PP(args[1]) == PGSQL_CONNECT_FORCE_NEW) { continue; } else if (Z_LVAL_PP(args[1]) & PGSQL_CONNECT_FORCE_NEW) { smart_str_append_long(&str, Z_LVAL_PP(args[1]) ^ PGSQL_CONNECT_FORCE_NEW); } } convert_to_string_ex(args[i]); smart_str_appendc(&str, '_'); smart_str_appendl(&str, Z_STRVAL_PP(args[i]), Z_STRLEN_PP(args[i])); } smart_str_0(&str); if (ZEND_NUM_ARGS() == 1) { /* new style, using connection string */ connstring = Z_STRVAL_PP(args[0]); } else if (ZEND_NUM_ARGS() == 2 ) { /* Safe to add conntype_option, since 2 args was illegal */ connstring = Z_STRVAL_PP(args[0]); convert_to_long_ex(args[1]); connect_type = Z_LVAL_PP(args[1]); } else { host = Z_STRVAL_PP(args[0]); port = Z_STRVAL_PP(args[1]); dbname = Z_STRVAL_PP(args[ZEND_NUM_ARGS()-1]); switch (ZEND_NUM_ARGS()) { case 5: tty = Z_STRVAL_PP(args[3]); /* fall through */ case 4: options = Z_STRVAL_PP(args[2]); break; } } if (persistent && PGG(allow_persistent)) { zend_rsrc_list_entry *le; /* try to find if we already have this link in our persistent list */ if (zend_hash_find(&EG(persistent_list), str.c, str.len+1, (void **) &le)==FAILURE) { /* we don't */ zend_rsrc_list_entry new_le; if (PGG(max_links)!=-1 && PGG(num_links)>=PGG(max_links)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create new link. Too many open links (%ld)", PGG(num_links)); goto err; } if (PGG(max_persistent)!=-1 && PGG(num_persistent)>=PGG(max_persistent)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create new link. Too many open persistent links (%ld)", PGG(num_persistent)); goto err; } /* create the link */ if (connstring) { pgsql=PQconnectdb(connstring); } else { pgsql=PQsetdb(host,port,options,tty,dbname); } if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) { PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql) if (pgsql) { PQfinish(pgsql); } goto err; } /* hash it up */ Z_TYPE(new_le) = le_plink; new_le.ptr = pgsql; if (zend_hash_update(&EG(persistent_list), str.c, str.len+1, (void *) &new_le, sizeof(zend_rsrc_list_entry), NULL)==FAILURE) { goto err; } PGG(num_links)++; PGG(num_persistent)++; } else { /* we do */ if (Z_TYPE_P(le) != le_plink) { RETURN_FALSE; } /* ensure that the link did not die */ if (PGG(auto_reset_persistent) & 1) { /* need to send & get something from backend to make sure we catch CONNECTION_BAD everytime */ PGresult *pg_result; pg_result = PQexec(le->ptr, "select 1"); PQclear(pg_result); } if (PQstatus(le->ptr)==CONNECTION_BAD) { /* the link died */ if (le->ptr == NULL) { if (connstring) { le->ptr=PQconnectdb(connstring); } else { le->ptr=PQsetdb(host,port,options,tty,dbname); } } else { PQreset(le->ptr); } if (le->ptr==NULL || PQstatus(le->ptr)==CONNECTION_BAD) { php_error_docref(NULL TSRMLS_CC, E_WARNING,"PostgreSQL link lost, unable to reconnect"); zend_hash_del(&EG(persistent_list),str.c,str.len+1); goto err; } } pgsql = (PGconn *) le->ptr; #if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 7.2) { #else if (atof(PG_VERSION) >= 7.2) { #endif pg_result = PQexec(pgsql, "RESET ALL;"); PQclear(pg_result); } } ZEND_REGISTER_RESOURCE(return_value, pgsql, le_plink); } else { /* Non persistent connection */ zend_rsrc_list_entry *index_ptr,new_index_ptr; /* first we check the hash for the hashed_details key. if it exists, * it should point us to the right offset where the actual pgsql link sits. * if it doesn't, open a new pgsql link, add it to the resource list, * and add a pointer to it with hashed_details as the key. */ if (!(connect_type & PGSQL_CONNECT_FORCE_NEW) && zend_hash_find(&EG(regular_list),str.c,str.len+1,(void **) &index_ptr)==SUCCESS) { int type; ulong link; void *ptr; if (Z_TYPE_P(index_ptr) != le_index_ptr) { RETURN_FALSE; } link = (ulong) index_ptr->ptr; ptr = zend_list_find(link,&type); /* check if the link is still there */ if (ptr && (type==le_link || type==le_plink)) { Z_LVAL_P(return_value) = link; zend_list_addref(link); php_pgsql_set_default_link(link TSRMLS_CC); Z_TYPE_P(return_value) = IS_RESOURCE; goto cleanup; } else { zend_hash_del(&EG(regular_list),str.c,str.len+1); } } if (PGG(max_links)!=-1 && PGG(num_links)>=PGG(max_links)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create new link. Too many open links (%ld)", PGG(num_links)); goto err; } if (connstring) { pgsql = PQconnectdb(connstring); } else { pgsql = PQsetdb(host,port,options,tty,dbname); } if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) { PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql); if (pgsql) { PQfinish(pgsql); } goto err; } /* add it to the list */ ZEND_REGISTER_RESOURCE(return_value, pgsql, le_link); /* add it to the hash */ new_index_ptr.ptr = (void *) Z_LVAL_P(return_value); Z_TYPE(new_index_ptr) = le_index_ptr; if (zend_hash_update(&EG(regular_list),str.c,str.len+1,(void *) &new_index_ptr, sizeof(zend_rsrc_list_entry), NULL)==FAILURE) { goto err; } PGG(num_links)++; } /* set notice processer */ if (! PGG(ignore_notices) && Z_TYPE_P(return_value) == IS_RESOURCE) { PQsetNoticeProcessor(pgsql, _php_pgsql_notice_handler, (void*)Z_RESVAL_P(return_value)); } php_pgsql_set_default_link(Z_LVAL_P(return_value) TSRMLS_CC); cleanup: smart_str_free(&str); return; err: smart_str_free(&str); RETURN_FALSE; } /* }}} */ #if 0 /* {{{ php_pgsql_get_default_link */ static int php_pgsql_get_default_link(INTERNAL_FUNCTION_PARAMETERS) { if (PGG(default_link)==-1) { /* no link opened yet, implicitly open one */ ht = 0; php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,0); } return PGG(default_link); } /* }}} */ #endif /* {{{ proto resource pg_connect(string connection_string[, int connect_type] | [string host, string port [, string options [, string tty,]]] string database) Open a PostgreSQL connection */ PHP_FUNCTION(pg_connect) { php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,0); } /* }}} */ /* {{{ proto resource pg_pconnect(string connection_string | [string host, string port [, string options [, string tty,]]] string database) Open a persistent PostgreSQL connection */ PHP_FUNCTION(pg_pconnect) { php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,1); } /* }}} */ /* {{{ proto bool pg_close([resource connection]) Close a PostgreSQL connection */ PHP_FUNCTION(pg_close) { zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) { return; } if (argc == 0) { id = PGG(default_link); CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (id==-1) { /* explicit resource number */ zend_list_delete(Z_RESVAL_P(pgsql_link)); } if (id!=-1 || (pgsql_link && Z_RESVAL_P(pgsql_link)==PGG(default_link))) { zend_list_delete(PGG(default_link)); PGG(default_link) = -1; } RETURN_TRUE; } /* }}} */ #define PHP_PG_DBNAME 1 #define PHP_PG_ERROR_MESSAGE 2 #define PHP_PG_OPTIONS 3 #define PHP_PG_PORT 4 #define PHP_PG_TTY 5 #define PHP_PG_HOST 6 #define PHP_PG_VERSION 7 /* {{{ php_pgsql_get_link_info */ static void php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type) { zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; char *msgbuf; if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) { return; } if (argc == 0) { id = PGG(default_link); CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); switch(entry_type) { case PHP_PG_DBNAME: Z_STRVAL_P(return_value) = PQdb(pgsql); break; case PHP_PG_ERROR_MESSAGE: RETURN_STRING(PQErrorMessageTrim(pgsql, &msgbuf), 0); return; case PHP_PG_OPTIONS: Z_STRVAL_P(return_value) = PQoptions(pgsql); break; case PHP_PG_PORT: Z_STRVAL_P(return_value) = PQport(pgsql); break; case PHP_PG_TTY: Z_STRVAL_P(return_value) = PQtty(pgsql); break; case PHP_PG_HOST: Z_STRVAL_P(return_value) = PQhost(pgsql); break; case PHP_PG_VERSION: array_init(return_value); add_assoc_string(return_value, "client", PG_VERSION, 1); #if HAVE_PQPROTOCOLVERSION add_assoc_long(return_value, "protocol", PQprotocolVersion(pgsql)); #if HAVE_PQPARAMETERSTATUS if (PQprotocolVersion(pgsql) >= 3) { add_assoc_string(return_value, "server", (char*)PQparameterStatus(pgsql, "server_version"), 1); } #endif #endif return; default: RETURN_FALSE; } if (Z_STRVAL_P(return_value)) { Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value)); Z_STRVAL_P(return_value) = (char *) estrdup(Z_STRVAL_P(return_value)); } else { Z_STRLEN_P(return_value) = 0; Z_STRVAL_P(return_value) = (char *) estrdup(""); } Z_TYPE_P(return_value) = IS_STRING; } /* }}} */ /* {{{ proto string pg_dbname([resource connection]) Get the database name */ PHP_FUNCTION(pg_dbname) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_DBNAME); } /* }}} */ /* {{{ proto string pg_last_error([resource connection]) Get the error message string */ PHP_FUNCTION(pg_last_error) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_ERROR_MESSAGE); } /* }}} */ /* {{{ proto string pg_options([resource connection]) Get the options associated with the connection */ PHP_FUNCTION(pg_options) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_OPTIONS); } /* }}} */ /* {{{ proto int pg_port([resource connection]) Return the port number associated with the connection */ PHP_FUNCTION(pg_port) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_PORT); } /* }}} */ /* {{{ proto string pg_tty([resource connection]) Return the tty name associated with the connection */ PHP_FUNCTION(pg_tty) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_TTY); } /* }}} */ /* {{{ proto string pg_host([resource connection]) Returns the host name associated with the connection */ PHP_FUNCTION(pg_host) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_HOST); } /* }}} */ /* {{{ proto array pg_version([resource connection]) Returns an array with client, protocol and server version (when available) */ PHP_FUNCTION(pg_version) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_VERSION); } /* }}} */ #if HAVE_PQPARAMETERSTATUS /* {{{ proto string|false pg_parameter_status([resource connection,] string param_name) Returns the value of a server parameter */ PHP_FUNCTION(pg_parameter_status) { zval *pgsql_link; int id; PGconn *pgsql; char *param; int len; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &param, &len) == SUCCESS) { id = -1; } else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &param, &len) == SUCCESS) { pgsql_link = NULL; id = PGG(default_link); } else { RETURN_FALSE; } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); param = (char*)PQparameterStatus(pgsql, param); if (param) { RETURN_STRING(param, 1); } else { RETURN_FALSE; } } /* }}} */ #endif /* {{{ proto bool pg_ping([resource connection]) Ping database. If connection is bad, try to reconnect. */ PHP_FUNCTION(pg_ping) { zval *pgsql_link; int id; PGconn *pgsql; PGresult *res; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == SUCCESS) { id = -1; } else { pgsql_link = NULL; id = PGG(default_link); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); /* ping connection */ res = PQexec(pgsql, "SELECT 1;"); PQclear(res); /* check status. */ if (PQstatus(pgsql) == CONNECTION_OK) RETURN_TRUE; /* reset connection if it's broken */ PQreset(pgsql); if (PQstatus(pgsql) == CONNECTION_OK) { RETURN_TRUE; } RETURN_FALSE; } /* }}} */ /* {{{ proto resource pg_query([resource connection,] string query) Execute a query */ PHP_FUNCTION(pg_query) { zval *pgsql_link = NULL; char *query; int id = -1, query_len, argc = ZEND_NUM_ARGS(); int leftover = 0; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; pgsql_result_handle *pg_result; if (argc == 1) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &query, &query_len) == FAILURE) { return; } id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &query, &query_len) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (PQ_SETNONBLOCKING(pgsql, 0)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode"); RETURN_FALSE; } while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); leftover = 1; } if (leftover) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first"); } pgsql_result = PQexec(pgsql, query); if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQclear(pgsql_result); PQreset(pgsql); pgsql_result = PQexec(pgsql, query); } if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } switch (status) { case PGRES_EMPTY_QUERY: case PGRES_BAD_RESPONSE: case PGRES_NONFATAL_ERROR: case PGRES_FATAL_ERROR: PHP_PQ_ERROR("Query failed: %s", pgsql); PQclear(pgsql_result); RETURN_FALSE; break; case PGRES_COMMAND_OK: /* successful command that did not return rows */ default: if (pgsql_result) { pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle)); pg_result->conn = pgsql; pg_result->result = pgsql_result; pg_result->row = 0; ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result); } else { PQclear(pgsql_result); RETURN_FALSE; } break; } } /* }}} */ #if HAVE_PQEXECPARAMS || HAVE_PQEXECPREPARED || HAVE_PQSENDQUERYPARAMS || HAVE_PQSENDQUERYPREPARED /* {{{ _php_pgsql_free_params */ static void _php_pgsql_free_params(char **params, int num_params) { if (num_params > 0) { int i; for (i = 0; i < num_params; i++) { if (params[i]) { efree(params[i]); } } efree(params); } } /* }}} */ #endif #if HAVE_PQEXECPARAMS /* {{{ proto resource pg_query_params([resource connection,] string query, array params) Execute a query */ PHP_FUNCTION(pg_query_params) { zval *pgsql_link = NULL; zval *pv_param_arr, **tmp; char *query; int query_len, id = -1, argc = ZEND_NUM_ARGS(); int leftover = 0; int num_params = 0; char **params = NULL; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; pgsql_result_handle *pg_result; if (argc == 2) { if (zend_parse_parameters(argc TSRMLS_CC, "sa", &query, &query_len, &pv_param_arr) == FAILURE) { return; } id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(argc TSRMLS_CC, "rsa", &pgsql_link, &query, &query_len, &pv_param_arr) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (PQ_SETNONBLOCKING(pgsql, 0)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode"); RETURN_FALSE; } while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); leftover = 1; } if (leftover) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first"); } zend_hash_internal_pointer_reset(Z_ARRVAL_P(pv_param_arr)); num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr)); if (num_params > 0) { int i = 0; params = (char **)safe_emalloc(sizeof(char *), num_params, 0); for(i = 0; i < num_params; i++) { if (zend_hash_get_current_data(Z_ARRVAL_P(pv_param_arr), (void **) &tmp) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error getting parameter"); _php_pgsql_free_params(params, num_params); RETURN_FALSE; } if (Z_TYPE_PP(tmp) == IS_NULL) { params[i] = NULL; } else { zval tmp_val = **tmp; zval_copy_ctor(&tmp_val); convert_to_string(&tmp_val); if (Z_TYPE(tmp_val) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error converting parameter"); zval_dtor(&tmp_val); _php_pgsql_free_params(params, num_params); RETURN_FALSE; } params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val)); zval_dtor(&tmp_val); } zend_hash_move_forward(Z_ARRVAL_P(pv_param_arr)); } } pgsql_result = PQexecParams(pgsql, query, num_params, NULL, (const char * const *)params, NULL, NULL, 0); if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQclear(pgsql_result); PQreset(pgsql); pgsql_result = PQexecParams(pgsql, query, num_params, NULL, (const char * const *)params, NULL, NULL, 0); } if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } _php_pgsql_free_params(params, num_params); switch (status) { case PGRES_EMPTY_QUERY: case PGRES_BAD_RESPONSE: case PGRES_NONFATAL_ERROR: case PGRES_FATAL_ERROR: PHP_PQ_ERROR("Query failed: %s", pgsql); PQclear(pgsql_result); RETURN_FALSE; break; case PGRES_COMMAND_OK: /* successful command that did not return rows */ default: if (pgsql_result) { pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle)); pg_result->conn = pgsql; pg_result->result = pgsql_result; pg_result->row = 0; ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result); } else { PQclear(pgsql_result); RETURN_FALSE; } break; } } /* }}} */ #endif #if HAVE_PQPREPARE /* {{{ proto resource pg_prepare([resource connection,] string stmtname, string query) Prepare a query for future execution */ PHP_FUNCTION(pg_prepare) { zval *pgsql_link = NULL; char *query, *stmtname; int query_len, stmtname_len, id = -1, argc = ZEND_NUM_ARGS(); int leftover = 0; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; pgsql_result_handle *pg_result; if (argc == 2) { if (zend_parse_parameters(argc TSRMLS_CC, "ss", &stmtname, &stmtname_len, &query, &query_len) == FAILURE) { return; } id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(argc TSRMLS_CC, "rss", &pgsql_link, &stmtname, &stmtname_len, &query, &query_len) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (PQ_SETNONBLOCKING(pgsql, 0)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode"); RETURN_FALSE; } while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); leftover = 1; } if (leftover) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first"); } pgsql_result = PQprepare(pgsql, stmtname, query, 0, NULL); if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQclear(pgsql_result); PQreset(pgsql); pgsql_result = PQprepare(pgsql, stmtname, query, 0, NULL); } if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } switch (status) { case PGRES_EMPTY_QUERY: case PGRES_BAD_RESPONSE: case PGRES_NONFATAL_ERROR: case PGRES_FATAL_ERROR: PHP_PQ_ERROR("Query failed: %s", pgsql); PQclear(pgsql_result); RETURN_FALSE; break; case PGRES_COMMAND_OK: /* successful command that did not return rows */ default: if (pgsql_result) { pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle)); pg_result->conn = pgsql; pg_result->result = pgsql_result; pg_result->row = 0; ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result); } else { PQclear(pgsql_result); RETURN_FALSE; } break; } } /* }}} */ #endif #if HAVE_PQEXECPREPARED /* {{{ proto resource pg_execute([resource connection,] string stmtname, array params) Execute a prepared query */ PHP_FUNCTION(pg_execute) { zval *pgsql_link = NULL; zval *pv_param_arr, **tmp; char *stmtname; int stmtname_len, id = -1, argc = ZEND_NUM_ARGS(); int leftover = 0; int num_params = 0; char **params = NULL; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; pgsql_result_handle *pg_result; if (argc == 2) { if (zend_parse_parameters(argc TSRMLS_CC, "sa/", &stmtname, &stmtname_len, &pv_param_arr)==FAILURE) { return; } id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(argc TSRMLS_CC, "rsa/", &pgsql_link, &stmtname, &stmtname_len, &pv_param_arr) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (PQ_SETNONBLOCKING(pgsql, 0)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode"); RETURN_FALSE; } while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); leftover = 1; } if (leftover) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first"); } zend_hash_internal_pointer_reset(Z_ARRVAL_P(pv_param_arr)); num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr)); if (num_params > 0) { int i = 0; params = (char **)safe_emalloc(sizeof(char *), num_params, 0); for(i = 0; i < num_params; i++) { if (zend_hash_get_current_data(Z_ARRVAL_P(pv_param_arr), (void **) &tmp) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error getting parameter"); _php_pgsql_free_params(params, num_params); RETURN_FALSE; } if (Z_TYPE_PP(tmp) == IS_NULL) { params[i] = NULL; } else { zval tmp_val = **tmp; zval_copy_ctor(&tmp_val); convert_to_string(&tmp_val); if (Z_TYPE(tmp_val) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error converting parameter"); zval_dtor(&tmp_val); _php_pgsql_free_params(params, num_params); RETURN_FALSE; } params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val)); zval_dtor(&tmp_val); } zend_hash_move_forward(Z_ARRVAL_P(pv_param_arr)); } } pgsql_result = PQexecPrepared(pgsql, stmtname, num_params, (const char * const *)params, NULL, NULL, 0); if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQclear(pgsql_result); PQreset(pgsql); pgsql_result = PQexecPrepared(pgsql, stmtname, num_params, (const char * const *)params, NULL, NULL, 0); } if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } _php_pgsql_free_params(params, num_params); switch (status) { case PGRES_EMPTY_QUERY: case PGRES_BAD_RESPONSE: case PGRES_NONFATAL_ERROR: case PGRES_FATAL_ERROR: PHP_PQ_ERROR("Query failed: %s", pgsql); PQclear(pgsql_result); RETURN_FALSE; break; case PGRES_COMMAND_OK: /* successful command that did not return rows */ default: if (pgsql_result) { pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle)); pg_result->conn = pgsql; pg_result->result = pgsql_result; pg_result->row = 0; ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result); } else { PQclear(pgsql_result); RETURN_FALSE; } break; } } /* }}} */ #endif #define PHP_PG_NUM_ROWS 1 #define PHP_PG_NUM_FIELDS 2 #define PHP_PG_CMD_TUPLES 3 /* {{{ php_pgsql_get_result_info */ static void php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type) { zval *result; PGresult *pgsql_result; pgsql_result_handle *pg_result; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); pgsql_result = pg_result->result; switch (entry_type) { case PHP_PG_NUM_ROWS: Z_LVAL_P(return_value) = PQntuples(pgsql_result); break; case PHP_PG_NUM_FIELDS: Z_LVAL_P(return_value) = PQnfields(pgsql_result); break; case PHP_PG_CMD_TUPLES: #if HAVE_PQCMDTUPLES Z_LVAL_P(return_value) = atoi(PQcmdTuples(pgsql_result)); #else php_error_docref(NULL TSRMLS_CC, E_WARNING, "Not supported under this build"); Z_LVAL_P(return_value) = 0; #endif break; default: RETURN_FALSE; } Z_TYPE_P(return_value) = IS_LONG; } /* }}} */ /* {{{ proto int pg_num_rows(resource result) Return the number of rows in the result */ PHP_FUNCTION(pg_num_rows) { php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_ROWS); } /* }}} */ /* {{{ proto int pg_num_fields(resource result) Return the number of fields in the result */ PHP_FUNCTION(pg_num_fields) { php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_FIELDS); } /* }}} */ #if HAVE_PQCMDTUPLES /* {{{ proto int pg_affected_rows(resource result) Returns the number of affected tuples */ PHP_FUNCTION(pg_affected_rows) { php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_CMD_TUPLES); } /* }}} */ #endif /* {{{ proto string pg_last_notice(resource connection) Returns the last notice set by the backend */ PHP_FUNCTION(pg_last_notice) { zval *pgsql_link; PGconn *pg_link; int id = -1; php_pgsql_notice **notice; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == FAILURE) { return; } /* Just to check if user passed valid resoruce */ ZEND_FETCH_RESOURCE2(pg_link, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (zend_hash_index_find(&PGG(notices), Z_RESVAL_P(pgsql_link), (void **)&notice) == FAILURE) { RETURN_FALSE; } RETURN_STRINGL((*notice)->message, (*notice)->len, 1); } /* }}} */ /* {{{ get_field_name */ static char *get_field_name(PGconn *pgsql, Oid oid, HashTable *list TSRMLS_DC) { PGresult *result; smart_str str = {0}; zend_rsrc_list_entry *field_type; char *ret=NULL; /* try to lookup the type in the resource list */ smart_str_appends(&str, "pgsql_oid_"); smart_str_append_unsigned(&str, oid); smart_str_0(&str); if (zend_hash_find(list,str.c,str.len+1,(void **) &field_type)==SUCCESS) { ret = estrdup((char *)field_type->ptr); } else { /* hash all oid's */ int i,num_rows; int oid_offset,name_offset; char *tmp_oid, *end_ptr, *tmp_name; zend_rsrc_list_entry new_oid_entry; if ((result = PQexec(pgsql,"select oid,typname from pg_type")) == NULL || PQresultStatus(result) != PGRES_TUPLES_OK) { if (result) { PQclear(result); } smart_str_free(&str); return STR_EMPTY_ALLOC(); } num_rows = PQntuples(result); oid_offset = PQfnumber(result,"oid"); name_offset = PQfnumber(result,"typname"); for (i=0; i<num_rows; i++) { if ((tmp_oid = PQgetvalue(result,i,oid_offset))==NULL) { continue; } str.len = 0; smart_str_appends(&str, "pgsql_oid_"); smart_str_appends(&str, tmp_oid); smart_str_0(&str); if ((tmp_name = PQgetvalue(result,i,name_offset))==NULL) { continue; } Z_TYPE(new_oid_entry) = le_string; new_oid_entry.ptr = estrdup(tmp_name); zend_hash_update(list,str.c,str.len+1,(void *) &new_oid_entry, sizeof(zend_rsrc_list_entry), NULL); if (!ret && strtoul(tmp_oid, &end_ptr, 10)==oid) { ret = estrdup(tmp_name); } } PQclear(result); } smart_str_free(&str); return ret; } /* }}} */ #ifdef HAVE_PQFTABLE /* {{{ proto mixed pg_field_table(resource result, int field_number[, bool oid_only]) Returns the name of the table field belongs to, or table's oid if oid_only is true */ PHP_FUNCTION(pg_field_table) { zval *result; pgsql_result_handle *pg_result; long fnum = -1; zend_bool return_oid = 0; Oid oid; smart_str hash_key = {0}; char *table_name; zend_rsrc_list_entry *field_table; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl|b", &result, &fnum, &return_oid) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); if (fnum < 0 || fnum >= PQnfields(pg_result->result)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad field offset specified"); RETURN_FALSE; } oid = PQftable(pg_result->result, fnum); if (InvalidOid == oid) { RETURN_FALSE; } if (return_oid) { #if UINT_MAX > LONG_MAX /* Oid is unsigned int, we don't need this code, where LONG is wider */ if (oid > LONG_MAX) { smart_str oidstr = {0}; smart_str_append_unsigned(&oidstr, oid); smart_str_0(&oidstr); RETURN_STRINGL(oidstr.c, oidstr.len, 0); } else #endif RETURN_LONG((long)oid); } /* try to lookup the table name in the resource list */ smart_str_appends(&hash_key, "pgsql_table_oid_"); smart_str_append_unsigned(&hash_key, oid); smart_str_0(&hash_key); if (zend_hash_find(&EG(regular_list), hash_key.c, hash_key.len+1, (void **) &field_table) == SUCCESS) { smart_str_free(&hash_key); RETURN_STRING((char *)field_table->ptr, 1); } else { /* Not found, lookup by querying PostgreSQL system tables */ PGresult *tmp_res; smart_str querystr = {0}; zend_rsrc_list_entry new_field_table; smart_str_appends(&querystr, "select relname from pg_class where oid="); smart_str_append_unsigned(&querystr, oid); smart_str_0(&querystr); if ((tmp_res = PQexec(pg_result->conn, querystr.c)) == NULL || PQresultStatus(tmp_res) != PGRES_TUPLES_OK) { if (tmp_res) { PQclear(tmp_res); } smart_str_free(&querystr); smart_str_free(&hash_key); RETURN_FALSE; } smart_str_free(&querystr); if ((table_name = PQgetvalue(tmp_res, 0, 0)) == NULL) { PQclear(tmp_res); smart_str_free(&hash_key); RETURN_FALSE; } Z_TYPE(new_field_table) = le_string; new_field_table.ptr = estrdup(table_name); zend_hash_update(&EG(regular_list), hash_key.c, hash_key.len+1, (void *) &new_field_table, sizeof(zend_rsrc_list_entry), NULL); smart_str_free(&hash_key); PQclear(tmp_res); RETURN_STRING(table_name, 1); } } /* }}} */ #endif #define PHP_PG_FIELD_NAME 1 #define PHP_PG_FIELD_SIZE 2 #define PHP_PG_FIELD_TYPE 3 #define PHP_PG_FIELD_TYPE_OID 4 /* {{{ php_pgsql_get_field_info */ static void php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type) { zval *result; long field; PGresult *pgsql_result; pgsql_result_handle *pg_result; Oid oid; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &result, &field) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); pgsql_result = pg_result->result; if (field < 0 || field >= PQnfields(pgsql_result)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad field offset specified"); RETURN_FALSE; } switch (entry_type) { case PHP_PG_FIELD_NAME: Z_STRVAL_P(return_value) = PQfname(pgsql_result, field); Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value)); Z_STRVAL_P(return_value) = estrndup(Z_STRVAL_P(return_value),Z_STRLEN_P(return_value)); Z_TYPE_P(return_value) = IS_STRING; break; case PHP_PG_FIELD_SIZE: Z_LVAL_P(return_value) = PQfsize(pgsql_result, field); Z_TYPE_P(return_value) = IS_LONG; break; case PHP_PG_FIELD_TYPE: Z_STRVAL_P(return_value) = get_field_name(pg_result->conn, PQftype(pgsql_result, field), &EG(regular_list) TSRMLS_CC); Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value)); Z_TYPE_P(return_value) = IS_STRING; break; case PHP_PG_FIELD_TYPE_OID: oid = PQftype(pgsql_result, field); #if UINT_MAX > LONG_MAX if (oid > LONG_MAX) { smart_str s = {0}; smart_str_append_unsigned(&s, oid); smart_str_0(&s); Z_STRVAL_P(return_value) = s.c; Z_STRLEN_P(return_value) = s.len; Z_TYPE_P(return_value) = IS_STRING; } else #endif { Z_LVAL_P(return_value) = (long)oid; Z_TYPE_P(return_value) = IS_LONG; } break; default: RETURN_FALSE; } } /* }}} */ /* {{{ proto string pg_field_name(resource result, int field_number) Returns the name of the field */ PHP_FUNCTION(pg_field_name) { php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_NAME); } /* }}} */ /* {{{ proto int pg_field_size(resource result, int field_number) Returns the internal size of the field */ PHP_FUNCTION(pg_field_size) { php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_SIZE); } /* }}} */ /* {{{ proto string pg_field_type(resource result, int field_number) Returns the type name for the given field */ PHP_FUNCTION(pg_field_type) { php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_TYPE); } /* }}} */ /* {{{ proto string pg_field_type_oid(resource result, int field_number) Returns the type oid for the given field */ PHP_FUNCTION(pg_field_type_oid) { php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_TYPE_OID); } /* }}} */ /* {{{ proto int pg_field_num(resource result, string field_name) Returns the field number of the named field */ PHP_FUNCTION(pg_field_num) { zval *result; char *field; int field_len; PGresult *pgsql_result; pgsql_result_handle *pg_result; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &result, &field, &field_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); pgsql_result = pg_result->result; Z_LVAL_P(return_value) = PQfnumber(pgsql_result, field); Z_TYPE_P(return_value) = IS_LONG; } /* }}} */ /* {{{ proto mixed pg_fetch_result(resource result, [int row_number,] mixed field_name) Returns values from a result identifier */ PHP_FUNCTION(pg_fetch_result) { zval *result, **field=NULL; long row; PGresult *pgsql_result; pgsql_result_handle *pg_result; int field_offset, pgsql_row, argc = ZEND_NUM_ARGS(); if (argc == 2) { if (zend_parse_parameters(argc TSRMLS_CC, "rZ", &result, &field) == FAILURE) { return; } } else { if (zend_parse_parameters(argc TSRMLS_CC, "rlZ", &result, &row, &field) == FAILURE) { return; } } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); pgsql_result = pg_result->result; if (argc == 2) { if (pg_result->row < 0) { pg_result->row = 0; } pgsql_row = pg_result->row; if (pgsql_row >= PQntuples(pgsql_result)) { RETURN_FALSE; } } else { pgsql_row = row; if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld", row, Z_LVAL_P(result)); RETURN_FALSE; } } switch(Z_TYPE_PP(field)) { case IS_STRING: field_offset = PQfnumber(pgsql_result, Z_STRVAL_PP(field)); break; default: convert_to_long_ex(field); field_offset = Z_LVAL_PP(field); break; } if (field_offset<0 || field_offset>=PQnfields(pgsql_result)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad column offset specified"); RETURN_FALSE; } if (PQgetisnull(pgsql_result, pgsql_row, field_offset)) { Z_TYPE_P(return_value) = IS_NULL; } else { char *value = PQgetvalue(pgsql_result, pgsql_row, field_offset); int value_len = PQgetlength(pgsql_result, pgsql_row, field_offset); ZVAL_STRINGL(return_value, value, value_len, 1); } } /* }}} */ /* {{{ void php_pgsql_fetch_hash */ static void php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAMETERS, long result_type, int into_object) { zval *result, *zrow = NULL; PGresult *pgsql_result; pgsql_result_handle *pg_result; int i, num_fields, pgsql_row, use_row; long row = -1; char *field_name; zval *ctor_params = NULL; zend_class_entry *ce = NULL; if (into_object) { char *class_name = NULL; int class_name_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|z!sz", &result, &zrow, &class_name, &class_name_len, &ctor_params) == FAILURE) { return; } if (!class_name) { ce = zend_standard_class_def; } else { ce = zend_fetch_class(class_name, class_name_len, ZEND_FETCH_CLASS_AUTO TSRMLS_CC); } if (!ce) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not find class '%s'", class_name); return; } result_type = PGSQL_ASSOC; } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|z!l", &result, &zrow, &result_type) == FAILURE) { return; } } if (zrow == NULL) { row = -1; } else { convert_to_long(zrow); row = Z_LVAL_P(zrow); if (row < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The row parameter must be greater or equal to zero"); RETURN_FALSE; } } use_row = ZEND_NUM_ARGS() > 1 && row != -1; if (!(result_type & PGSQL_BOTH)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid result type"); RETURN_FALSE; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); pgsql_result = pg_result->result; if (use_row) { pgsql_row = row; pg_result->row = pgsql_row; if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld", row, Z_LVAL_P(result)); RETURN_FALSE; } } else { /* If 2nd param is NULL, use internal row counter to access next row */ pgsql_row = pg_result->row; if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) { RETURN_FALSE; } pg_result->row++; } array_init(return_value); for (i = 0, num_fields = PQnfields(pgsql_result); i < num_fields; i++) { if (PQgetisnull(pgsql_result, pgsql_row, i)) { if (result_type & PGSQL_NUM) { add_index_null(return_value, i); } if (result_type & PGSQL_ASSOC) { field_name = PQfname(pgsql_result, i); add_assoc_null(return_value, field_name); } } else { char *element = PQgetvalue(pgsql_result, pgsql_row, i); if (element) { char *data; int data_len; int should_copy=0; const uint element_len = strlen(element); data = safe_estrndup(element, element_len); data_len = element_len; if (result_type & PGSQL_NUM) { add_index_stringl(return_value, i, data, data_len, should_copy); should_copy=1; } if (result_type & PGSQL_ASSOC) { field_name = PQfname(pgsql_result, i); add_assoc_stringl(return_value, field_name, data, data_len, should_copy); } } } } if (into_object) { zval dataset = *return_value; zend_fcall_info fci; zend_fcall_info_cache fcc; zval *retval_ptr; object_and_properties_init(return_value, ce, NULL); zend_merge_properties(return_value, Z_ARRVAL(dataset), 1 TSRMLS_CC); if (ce->constructor) { fci.size = sizeof(fci); fci.function_table = &ce->function_table; fci.function_name = NULL; fci.symbol_table = NULL; fci.object_ptr = return_value; fci.retval_ptr_ptr = &retval_ptr; if (ctor_params && Z_TYPE_P(ctor_params) != IS_NULL) { if (Z_TYPE_P(ctor_params) == IS_ARRAY) { HashTable *ht = Z_ARRVAL_P(ctor_params); Bucket *p; fci.param_count = 0; fci.params = safe_emalloc(sizeof(zval***), ht->nNumOfElements, 0); p = ht->pListHead; while (p != NULL) { fci.params[fci.param_count++] = (zval**)p->pData; p = p->pListNext; } } else { /* Two problems why we throw exceptions here: PHP is typeless * and hence passing one argument that's not an array could be * by mistake and the other way round is possible, too. The * single value is an array. Also we'd have to make that one * argument passed by reference. */ zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Parameter ctor_params must be an array", 0 TSRMLS_CC); return; } } else { fci.param_count = 0; fci.params = NULL; } fci.no_separation = 1; fcc.initialized = 1; fcc.function_handler = ce->constructor; fcc.calling_scope = EG(scope); fcc.called_scope = Z_OBJCE_P(return_value); fcc.object_ptr = return_value; if (zend_call_function(&fci, &fcc TSRMLS_CC) == FAILURE) { zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Could not execute %s::%s()", ce->name, ce->constructor->common.function_name); } else { if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } } if (fci.params) { efree(fci.params); } } else if (ctor_params) { zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Class %s does not have a constructor hence you cannot use ctor_params", ce->name); } } } /* }}} */ /* {{{ proto array pg_fetch_row(resource result [, int row [, int result_type]]) Get a row as an enumerated array */ PHP_FUNCTION(pg_fetch_row) { php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_NUM, 0); } /* }}} */ /* {{{ proto array pg_fetch_assoc(resource result [, int row]) Fetch a row as an assoc array */ PHP_FUNCTION(pg_fetch_assoc) { /* pg_fetch_assoc() is added from PHP 4.3.0. It should raise error, when there is 3rd parameter */ if (ZEND_NUM_ARGS() > 2) WRONG_PARAM_COUNT; php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_ASSOC, 0); } /* }}} */ /* {{{ proto array pg_fetch_array(resource result [, int row [, int result_type]]) Fetch a row as an array */ PHP_FUNCTION(pg_fetch_array) { php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_BOTH, 0); } /* }}} */ /* {{{ proto object pg_fetch_object(resource result [, int row [, string class_name [, NULL|array ctor_params]]]) Fetch a row as an object */ PHP_FUNCTION(pg_fetch_object) { /* pg_fetch_object() allowed result_type used to be. 3rd parameter must be allowed for compatibility */ php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_ASSOC, 1); } /* }}} */ /* {{{ proto array pg_fetch_all(resource result) Fetch all rows into array */ PHP_FUNCTION(pg_fetch_all) { zval *result; PGresult *pgsql_result; pgsql_result_handle *pg_result; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); pgsql_result = pg_result->result; array_init(return_value); if (php_pgsql_result2array(pgsql_result, return_value TSRMLS_CC) == FAILURE) { zval_dtor(return_value); RETURN_FALSE; } } /* }}} */ /* {{{ proto array pg_fetch_all_columns(resource result [, int column_number]) Fetch all rows into array */ PHP_FUNCTION(pg_fetch_all_columns) { zval *result; PGresult *pgsql_result; pgsql_result_handle *pg_result; unsigned long colno=0; int pg_numrows, pg_row; size_t num_fields; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &result, &colno) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); pgsql_result = pg_result->result; num_fields = PQnfields(pgsql_result); if (colno >= num_fields || colno < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid column number '%ld'", colno); RETURN_FALSE; } array_init(return_value); if ((pg_numrows = PQntuples(pgsql_result)) <= 0) { return; } for (pg_row = 0; pg_row < pg_numrows; pg_row++) { if (PQgetisnull(pgsql_result, pg_row, colno)) { add_next_index_null(return_value); } else { add_next_index_string(return_value, PQgetvalue(pgsql_result, pg_row, colno), 1); } } } /* }}} */ /* {{{ proto bool pg_result_seek(resource result, int offset) Set internal row offset */ PHP_FUNCTION(pg_result_seek) { zval *result; long row; pgsql_result_handle *pg_result; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &result, &row) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); if (row < 0 || row >= PQntuples(pg_result->result)) { RETURN_FALSE; } /* seek to offset */ pg_result->row = row; RETURN_TRUE; } /* }}} */ #define PHP_PG_DATA_LENGTH 1 #define PHP_PG_DATA_ISNULL 2 /* {{{ php_pgsql_data_info */ static void php_pgsql_data_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type) { zval *result, **field; long row; PGresult *pgsql_result; pgsql_result_handle *pg_result; int field_offset, pgsql_row, argc = ZEND_NUM_ARGS(); if (argc == 2) { if (zend_parse_parameters(argc TSRMLS_CC, "rZ", &result, &field) == FAILURE) { return; } } else { if (zend_parse_parameters(argc TSRMLS_CC, "rlZ", &result, &row, &field) == FAILURE) { return; } } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); pgsql_result = pg_result->result; if (argc == 2) { if (pg_result->row < 0) { pg_result->row = 0; } pgsql_row = pg_result->row; if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) { RETURN_FALSE; } } else { pgsql_row = row; if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld", row, Z_LVAL_P(result)); RETURN_FALSE; } } switch(Z_TYPE_PP(field)) { case IS_STRING: convert_to_string_ex(field); field_offset = PQfnumber(pgsql_result, Z_STRVAL_PP(field)); break; default: convert_to_long_ex(field); field_offset = Z_LVAL_PP(field); break; } if (field_offset < 0 || field_offset >= PQnfields(pgsql_result)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad column offset specified"); RETURN_FALSE; } switch (entry_type) { case PHP_PG_DATA_LENGTH: Z_LVAL_P(return_value) = PQgetlength(pgsql_result, pgsql_row, field_offset); break; case PHP_PG_DATA_ISNULL: Z_LVAL_P(return_value) = PQgetisnull(pgsql_result, pgsql_row, field_offset); break; } Z_TYPE_P(return_value) = IS_LONG; } /* }}} */ /* {{{ proto int pg_field_prtlen(resource result, [int row,] mixed field_name_or_number) Returns the printed length */ PHP_FUNCTION(pg_field_prtlen) { php_pgsql_data_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_DATA_LENGTH); } /* }}} */ /* {{{ proto int pg_field_is_null(resource result, [int row,] mixed field_name_or_number) Test if a field is NULL */ PHP_FUNCTION(pg_field_is_null) { php_pgsql_data_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_DATA_ISNULL); } /* }}} */ /* {{{ proto bool pg_free_result(resource result) Free result memory */ PHP_FUNCTION(pg_free_result) { zval *result; pgsql_result_handle *pg_result; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); if (Z_LVAL_P(result) == 0) { RETURN_FALSE; } zend_list_delete(Z_RESVAL_P(result)); RETURN_TRUE; } /* }}} */ /* {{{ proto string pg_last_oid(resource result) Returns the last object identifier */ PHP_FUNCTION(pg_last_oid) { zval *result; PGresult *pgsql_result; pgsql_result_handle *pg_result; #ifdef HAVE_PQOIDVALUE Oid oid; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &result) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result); pgsql_result = pg_result->result; #ifdef HAVE_PQOIDVALUE oid = PQoidValue(pgsql_result); if (oid == InvalidOid) { RETURN_FALSE; } PGSQL_RETURN_OID(oid); #else Z_STRVAL_P(return_value) = (char *) PQoidStatus(pgsql_result); if (Z_STRVAL_P(return_value)) { RETURN_STRING(Z_STRVAL_P(return_value), 1); } RETURN_STRING("", 1); #endif } /* }}} */ /* {{{ proto bool pg_trace(string filename [, string mode [, resource connection]]) Enable tracing a PostgreSQL connection */ PHP_FUNCTION(pg_trace) { char *z_filename, *mode = "w"; int z_filename_len, mode_len; zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; FILE *fp = NULL; php_stream *stream; id = PGG(default_link); if (zend_parse_parameters(argc TSRMLS_CC, "s|sr", &z_filename, &z_filename_len, &mode, &mode_len, &pgsql_link) == FAILURE) { return; } if (argc < 3) { CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); stream = php_stream_open_wrapper(z_filename, mode, REPORT_ERRORS, NULL); if (!stream) { RETURN_FALSE; } if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) { php_stream_close(stream); RETURN_FALSE; } php_stream_auto_cleanup(stream); PQtrace(pgsql, fp); RETURN_TRUE; } /* }}} */ /* {{{ proto bool pg_untrace([resource connection]) Disable tracing of a PostgreSQL connection */ PHP_FUNCTION(pg_untrace) { zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) { return; } if (argc == 0) { id = PGG(default_link); CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); PQuntrace(pgsql); RETURN_TRUE; } /* }}} */ /* {{{ proto mixed pg_lo_create([resource connection],[mixed large_object_oid]) Create a large object */ PHP_FUNCTION(pg_lo_create) { zval *pgsql_link = NULL, *oid = NULL; PGconn *pgsql; Oid pgsql_oid, wanted_oid = InvalidOid; int id = -1, argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "|zz", &pgsql_link, &oid) == FAILURE) { return; } if ((argc == 1) && (Z_TYPE_P(pgsql_link) != IS_RESOURCE)) { oid = pgsql_link; pgsql_link = NULL; } if (pgsql_link == NULL) { id = PGG(default_link); CHECK_DEFAULT_LINK(id); if (id == -1) { RETURN_FALSE; } } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (oid) { #ifndef HAVE_PG_LO_CREATE php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Passing OID value is not supported. Upgrade your PostgreSQL"); #else switch (Z_TYPE_P(oid)) { case IS_STRING: { char *end_ptr; wanted_oid = (Oid)strtoul(Z_STRVAL_P(oid), &end_ptr, 10); if ((Z_STRVAL_P(oid)+Z_STRLEN_P(oid)) != end_ptr) { /* wrong integer format */ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed"); RETURN_FALSE; } } break; case IS_LONG: if (Z_LVAL_P(oid) < (long)InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed"); RETURN_FALSE; } wanted_oid = (Oid)Z_LVAL_P(oid); break; default: php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed"); RETURN_FALSE; } if ((pgsql_oid = lo_create(pgsql, wanted_oid)) == InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object"); RETURN_FALSE; } PGSQL_RETURN_OID(pgsql_oid); #endif } if ((pgsql_oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object"); RETURN_FALSE; } PGSQL_RETURN_OID(pgsql_oid); } /* }}} */ /* {{{ proto bool pg_lo_unlink([resource connection,] string large_object_oid) Delete a large object */ PHP_FUNCTION(pg_lo_unlink) { zval *pgsql_link = NULL; long oid_long; char *oid_string, *end_ptr; int oid_strlen; PGconn *pgsql; Oid oid; int id = -1; int argc = ZEND_NUM_ARGS(); /* accept string type since Oid type is unsigned int */ if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "rs", &pgsql_link, &oid_string, &oid_strlen) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { /* wrong integer format */ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed"); RETURN_FALSE; } } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "rl", &pgsql_link, &oid_long) == SUCCESS) { if (oid_long <= InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified"); RETURN_FALSE; } oid = (Oid)oid_long; } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "s", &oid_string, &oid_strlen) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { /* wrong integer format */ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed"); RETURN_FALSE; } id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "l", &oid_long) == SUCCESS) { if (oid_long <= InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID is specified"); RETURN_FALSE; } oid = (Oid)oid_long; id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 1 or 2 arguments"); RETURN_FALSE; } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (lo_unlink(pgsql, oid) == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to delete PostgreSQL large object %u", oid); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto resource pg_lo_open([resource connection,] int large_object_oid, string mode) Open a large object and return fd */ PHP_FUNCTION(pg_lo_open) { zval *pgsql_link = NULL; long oid_long; char *oid_string, *end_ptr, *mode_string; int oid_strlen, mode_strlen; PGconn *pgsql; Oid oid; int id = -1, pgsql_mode=0, pgsql_lofd; int create=0; pgLofp *pgsql_lofp; int argc = ZEND_NUM_ARGS(); /* accept string type since Oid is unsigned int */ if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "rss", &pgsql_link, &oid_string, &oid_strlen, &mode_string, &mode_strlen) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { /* wrong integer format */ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed"); RETURN_FALSE; } } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "rls", &pgsql_link, &oid_long, &mode_string, &mode_strlen) == SUCCESS) { if (oid_long <= InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified"); RETURN_FALSE; } oid = (Oid)oid_long; } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "ss", &oid_string, &oid_strlen, &mode_string, &mode_strlen) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { /* wrong integer format */ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed"); RETURN_FALSE; } id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "ls", &oid_long, &mode_string, &mode_strlen) == SUCCESS) { if (oid_long <= InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified"); RETURN_FALSE; } oid = (Oid)oid_long; id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 1 or 2 arguments"); RETURN_FALSE; } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); /* r/w/+ is little bit more PHP-like than INV_READ/INV_WRITE and a lot of faster to type. Unfortunately, doesn't behave the same way as fopen()... (Jouni) */ if (strchr(mode_string, 'r') == mode_string) { pgsql_mode |= INV_READ; if (strchr(mode_string, '+') == mode_string+1) { pgsql_mode |= INV_WRITE; } } if (strchr(mode_string, 'w') == mode_string) { pgsql_mode |= INV_WRITE; create = 1; if (strchr(mode_string, '+') == mode_string+1) { pgsql_mode |= INV_READ; } } pgsql_lofp = (pgLofp *) emalloc(sizeof(pgLofp)); if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) { if (create) { if ((oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == 0) { efree(pgsql_lofp); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object"); RETURN_FALSE; } else { if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) { if (lo_unlink(pgsql, oid) == -1) { efree(pgsql_lofp); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Something is really messed up! Your database is badly corrupted in a way NOT related to PHP"); RETURN_FALSE; } efree(pgsql_lofp); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open PostgreSQL large object"); RETURN_FALSE; } else { pgsql_lofp->conn = pgsql; pgsql_lofp->lofd = pgsql_lofd; Z_LVAL_P(return_value) = zend_list_insert(pgsql_lofp, le_lofp TSRMLS_CC); Z_TYPE_P(return_value) = IS_LONG; } } } else { efree(pgsql_lofp); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open PostgreSQL large object"); RETURN_FALSE; } } else { pgsql_lofp->conn = pgsql; pgsql_lofp->lofd = pgsql_lofd; ZEND_REGISTER_RESOURCE(return_value, pgsql_lofp, le_lofp); } } /* }}} */ /* {{{ proto bool pg_lo_close(resource large_object) Close a large object */ PHP_FUNCTION(pg_lo_close) { zval *pgsql_lofp; pgLofp *pgsql; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_lofp) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_lofp, -1, "PostgreSQL large object", le_lofp); if (lo_close((PGconn *)pgsql->conn, pgsql->lofd) < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to close PostgreSQL large object descriptor %d", pgsql->lofd); RETVAL_FALSE; } else { RETVAL_TRUE; } zend_list_delete(Z_RESVAL_P(pgsql_lofp)); return; } /* }}} */ #define PGSQL_LO_READ_BUF_SIZE 8192 /* {{{ proto string pg_lo_read(resource large_object [, int len]) Read a large object */ PHP_FUNCTION(pg_lo_read) { zval *pgsql_id; long len; int buf_len = PGSQL_LO_READ_BUF_SIZE, nbytes, argc = ZEND_NUM_ARGS(); char *buf; pgLofp *pgsql; if (zend_parse_parameters(argc TSRMLS_CC, "r|l", &pgsql_id, &len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp); if (argc > 1) { buf_len = len; } buf = (char *) safe_emalloc(sizeof(char), (buf_len+1), 0); if ((nbytes = lo_read((PGconn *)pgsql->conn, pgsql->lofd, buf, buf_len))<0) { efree(buf); RETURN_FALSE; } buf[nbytes] = '\0'; RETURN_STRINGL(buf, nbytes, 0); } /* }}} */ /* {{{ proto int pg_lo_write(resource large_object, string buf [, int len]) Write a large object */ PHP_FUNCTION(pg_lo_write) { zval *pgsql_id; char *str; long z_len; int str_len, nbytes; int len; pgLofp *pgsql; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "rs|l", &pgsql_id, &str, &str_len, &z_len) == FAILURE) { return; } if (argc > 2) { if (z_len > str_len) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot write more than buffer size %d. Tried to write %ld", str_len, z_len); RETURN_FALSE; } if (z_len < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Buffer size must be larger than 0, but %ld was specified", z_len); RETURN_FALSE; } len = z_len; } else { len = str_len; } ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp); if ((nbytes = lo_write((PGconn *)pgsql->conn, pgsql->lofd, str, len)) == -1) { RETURN_FALSE; } RETURN_LONG(nbytes); } /* }}} */ /* {{{ proto int pg_lo_read_all(resource large_object) Read a large object and send straight to browser */ PHP_FUNCTION(pg_lo_read_all) { zval *pgsql_id; int tbytes; volatile int nbytes; char buf[PGSQL_LO_READ_BUF_SIZE]; pgLofp *pgsql; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_id) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp); tbytes = 0; while ((nbytes = lo_read((PGconn *)pgsql->conn, pgsql->lofd, buf, PGSQL_LO_READ_BUF_SIZE))>0) { PHPWRITE(buf, nbytes); tbytes += nbytes; } RETURN_LONG(tbytes); } /* }}} */ /* {{{ proto int pg_lo_import([resource connection, ] string filename [, mixed oid]) Import large object direct from filesystem */ PHP_FUNCTION(pg_lo_import) { zval *pgsql_link = NULL, *oid = NULL; char *file_in; int id = -1, name_len; int argc = ZEND_NUM_ARGS(); PGconn *pgsql; Oid returned_oid; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "rp|z", &pgsql_link, &file_in, &name_len, &oid) == SUCCESS) { ; } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "p|z", &file_in, &name_len, &oid) == SUCCESS) { id = PGG(default_link); CHECK_DEFAULT_LINK(id); } /* old calling convention, deprecated since PHP 4.2 */ else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "pr", &file_in, &name_len, &pgsql_link ) == SUCCESS) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Old API is used"); } else { WRONG_PARAM_COUNT; } if (php_check_open_basedir(file_in TSRMLS_CC)) { RETURN_FALSE; } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (oid) { #ifndef HAVE_PG_LO_IMPORT_WITH_OID php_error_docref(NULL TSRMLS_CC, E_NOTICE, "OID value passing not supported"); #else Oid wanted_oid; switch (Z_TYPE_P(oid)) { case IS_STRING: { char *end_ptr; wanted_oid = (Oid)strtoul(Z_STRVAL_P(oid), &end_ptr, 10); if ((Z_STRVAL_P(oid)+Z_STRLEN_P(oid)) != end_ptr) { /* wrong integer format */ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed"); RETURN_FALSE; } } break; case IS_LONG: if (Z_LVAL_P(oid) < (long)InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed"); RETURN_FALSE; } wanted_oid = (Oid)Z_LVAL_P(oid); break; default: php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid OID value passed"); RETURN_FALSE; } returned_oid = lo_import_with_oid(pgsql, file_in, wanted_oid); if (returned_oid == InvalidOid) { RETURN_FALSE; } PGSQL_RETURN_OID(returned_oid); #endif } returned_oid = lo_import(pgsql, file_in); if (returned_oid == InvalidOid) { RETURN_FALSE; } PGSQL_RETURN_OID(returned_oid); } /* }}} */ /* {{{ proto bool pg_lo_export([resource connection, ] int objoid, string filename) Export large object direct to filesystem */ PHP_FUNCTION(pg_lo_export) { zval *pgsql_link = NULL; char *file_out, *oid_string, *end_ptr; int oid_strlen; int id = -1, name_len; long oid_long; Oid oid; PGconn *pgsql; int argc = ZEND_NUM_ARGS(); /* allow string to handle large OID value correctly */ if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "rlp", &pgsql_link, &oid_long, &file_out, &name_len) == SUCCESS) { if (oid_long <= InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified"); RETURN_FALSE; } oid = (Oid)oid_long; } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "rss", &pgsql_link, &oid_string, &oid_strlen, &file_out, &name_len) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { /* wrong integer format */ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed"); RETURN_FALSE; } } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "lp", &oid_long, &file_out, &name_len) == SUCCESS) { if (oid_long <= InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified"); RETURN_FALSE; } oid = (Oid)oid_long; id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "sp", &oid_string, &oid_strlen, &file_out, &name_len) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { /* wrong integer format */ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed"); RETURN_FALSE; } id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "spr", &oid_string, &oid_strlen, &file_out, &name_len, &pgsql_link) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { /* wrong integer format */ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed"); RETURN_FALSE; } } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "lpr", &oid_long, &file_out, &name_len, &pgsql_link) == SUCCESS) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Old API is used"); if (oid_long <= InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified"); RETURN_FALSE; } oid = (Oid)oid_long; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 2 or 3 arguments"); RETURN_FALSE; } if (php_check_open_basedir(file_out TSRMLS_CC)) { RETURN_FALSE; } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (lo_export(pgsql, oid, file_out)) { RETURN_TRUE; } RETURN_FALSE; } /* }}} */ /* {{{ proto bool pg_lo_seek(resource large_object, int offset [, int whence]) Seeks position of large object */ PHP_FUNCTION(pg_lo_seek) { zval *pgsql_id = NULL; long offset = 0, whence = SEEK_CUR; pgLofp *pgsql; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "rl|l", &pgsql_id, &offset, &whence) == FAILURE) { return; } if (whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid whence parameter"); return; } ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp); if (lo_lseek((PGconn *)pgsql->conn, pgsql->lofd, offset, whence) > -1) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto int pg_lo_tell(resource large_object) Returns current position of large object */ PHP_FUNCTION(pg_lo_tell) { zval *pgsql_id = NULL; int offset = 0; pgLofp *pgsql; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "r", &pgsql_id) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp); offset = lo_tell((PGconn *)pgsql->conn, pgsql->lofd); RETURN_LONG(offset); } /* }}} */ #if HAVE_PQSETERRORVERBOSITY /* {{{ proto int pg_set_error_verbosity([resource connection,] int verbosity) Set error verbosity */ PHP_FUNCTION(pg_set_error_verbosity) { zval *pgsql_link = NULL; long verbosity; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; if (argc == 1) { if (zend_parse_parameters(argc TSRMLS_CC, "l", &verbosity) == FAILURE) { return; } id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(argc TSRMLS_CC, "rl", &pgsql_link, &verbosity) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (verbosity & (PQERRORS_TERSE|PQERRORS_DEFAULT|PQERRORS_VERBOSE)) { Z_LVAL_P(return_value) = PQsetErrorVerbosity(pgsql, verbosity); Z_TYPE_P(return_value) = IS_LONG; } else { RETURN_FALSE; } } /* }}} */ #endif #ifdef HAVE_PQCLIENTENCODING /* {{{ proto int pg_set_client_encoding([resource connection,] string encoding) Set client encoding */ PHP_FUNCTION(pg_set_client_encoding) { char *encoding; int encoding_len; zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; if (argc == 1) { if (zend_parse_parameters(argc TSRMLS_CC, "s", &encoding, &encoding_len) == FAILURE) { return; } id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(argc TSRMLS_CC, "rs", &pgsql_link, &encoding, &encoding_len) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); Z_LVAL_P(return_value) = PQsetClientEncoding(pgsql, encoding); Z_TYPE_P(return_value) = IS_LONG; } /* }}} */ /* {{{ proto string pg_client_encoding([resource connection]) Get the current client encoding */ PHP_FUNCTION(pg_client_encoding) { zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) { return; } if (argc == 0) { id = PGG(default_link); CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); /* Just do the same as found in PostgreSQL sources... */ Z_STRVAL_P(return_value) = (char *) pg_encoding_to_char(PQclientEncoding(pgsql)); Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value)); Z_STRVAL_P(return_value) = (char *) estrdup(Z_STRVAL_P(return_value)); Z_TYPE_P(return_value) = IS_STRING; } /* }}} */ #endif #if !HAVE_PQGETCOPYDATA #define COPYBUFSIZ 8192 #endif /* {{{ proto bool pg_end_copy([resource connection]) Sync with backend. Completes the Copy command */ PHP_FUNCTION(pg_end_copy) { zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; int result = 0; if (zend_parse_parameters(argc TSRMLS_CC, "|r", &pgsql_link) == FAILURE) { return; } if (argc == 0) { id = PGG(default_link); CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); result = PQendcopy(pgsql); if (result!=0) { PHP_PQ_ERROR("Query failed: %s", pgsql); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool pg_put_line([resource connection,] string query) Send null-terminated string to backend server*/ PHP_FUNCTION(pg_put_line) { char *query; zval *pgsql_link = NULL; int query_len, id = -1; PGconn *pgsql; int result = 0, argc = ZEND_NUM_ARGS(); if (argc == 1) { if (zend_parse_parameters(argc TSRMLS_CC, "s", &query, &query_len) == FAILURE) { return; } id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else { if (zend_parse_parameters(argc TSRMLS_CC, "rs", &pgsql_link, &query, &query_len) == FAILURE) { return; } } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); result = PQputline(pgsql, query); if (result==EOF) { PHP_PQ_ERROR("Query failed: %s", pgsql); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto array pg_copy_to(resource connection, string table_name [, string delimiter [, string null_as]]) Copy table to array */ PHP_FUNCTION(pg_copy_to) { zval *pgsql_link; char *table_name, *pg_delim = NULL, *pg_null_as = NULL; int table_name_len, pg_delim_len, pg_null_as_len, free_pg_null = 0; char *query; int id = -1; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; int copydone = 0; #if !HAVE_PQGETCOPYDATA char copybuf[COPYBUFSIZ]; #endif char *csv = (char *)NULL; int ret; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "rs|ss", &pgsql_link, &table_name, &table_name_len, &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len) == FAILURE) { return; } if (!pg_delim) { pg_delim = "\t"; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (!pg_null_as) { pg_null_as = safe_estrdup("\\\\N"); free_pg_null = 1; } spprintf(&query, 0, "COPY %s TO STDOUT DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, *pg_delim, pg_null_as); while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); } pgsql_result = PQexec(pgsql, query); if (free_pg_null) { efree(pg_null_as); } efree(query); if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } switch (status) { case PGRES_COPY_OUT: if (pgsql_result) { PQclear(pgsql_result); array_init(return_value); #if HAVE_PQGETCOPYDATA while (!copydone) { ret = PQgetCopyData(pgsql, &csv, 0); switch (ret) { case -1: copydone = 1; break; case 0: case -2: PHP_PQ_ERROR("getline failed: %s", pgsql); RETURN_FALSE; break; default: add_next_index_string(return_value, csv, 1); PQfreemem(csv); break; } } #else while (!copydone) { if ((ret = PQgetline(pgsql, copybuf, COPYBUFSIZ))) { PHP_PQ_ERROR("getline failed: %s", pgsql); RETURN_FALSE; } if (copybuf[0] == '\\' && copybuf[1] == '.' && copybuf[2] == '\0') { copydone = 1; } else { if (csv == (char *)NULL) { csv = estrdup(copybuf); } else { csv = (char *)erealloc(csv, strlen(csv) + sizeof(char)*(COPYBUFSIZ+1)); strcat(csv, copybuf); } switch (ret) { case EOF: copydone = 1; case 0: add_next_index_string(return_value, csv, 1); efree(csv); csv = (char *)NULL; break; case 1: break; } } } if (PQendcopy(pgsql)) { PHP_PQ_ERROR("endcopy failed: %s", pgsql); RETURN_FALSE; } #endif while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); } } else { PQclear(pgsql_result); RETURN_FALSE; } break; default: PQclear(pgsql_result); PHP_PQ_ERROR("Copy command failed: %s", pgsql); RETURN_FALSE; break; } } /* }}} */ /* {{{ proto bool pg_copy_from(resource connection, string table_name , array rows [, string delimiter [, string null_as]]) Copy table from array */ PHP_FUNCTION(pg_copy_from) { zval *pgsql_link = NULL, *pg_rows; zval **tmp; char *table_name, *pg_delim = NULL, *pg_null_as = NULL; int table_name_len, pg_delim_len, pg_null_as_len; int pg_null_as_free = 0; char *query; HashPosition pos; int id = -1; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "rsa|ss", &pgsql_link, &table_name, &table_name_len, &pg_rows, &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len) == FAILURE) { return; } if (!pg_delim) { pg_delim = "\t"; } if (!pg_null_as) { pg_null_as = safe_estrdup("\\\\N"); pg_null_as_free = 1; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); spprintf(&query, 0, "COPY %s FROM STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, *pg_delim, pg_null_as); while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); } pgsql_result = PQexec(pgsql, query); if (pg_null_as_free) { efree(pg_null_as); } efree(query); if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } switch (status) { case PGRES_COPY_IN: if (pgsql_result) { int command_failed = 0; PQclear(pgsql_result); zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(pg_rows), &pos); #if HAVE_PQPUTCOPYDATA while (zend_hash_get_current_data_ex(Z_ARRVAL_P(pg_rows), (void **) &tmp, &pos) == SUCCESS) { convert_to_string_ex(tmp); query = (char *)emalloc(Z_STRLEN_PP(tmp) + 2); strlcpy(query, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp) + 2); if(Z_STRLEN_PP(tmp) > 0 && *(query + Z_STRLEN_PP(tmp) - 1) != '\n') { strlcat(query, "\n", Z_STRLEN_PP(tmp) + 2); } if (PQputCopyData(pgsql, query, strlen(query)) != 1) { efree(query); PHP_PQ_ERROR("copy failed: %s", pgsql); RETURN_FALSE; } efree(query); zend_hash_move_forward_ex(Z_ARRVAL_P(pg_rows), &pos); } if (PQputCopyEnd(pgsql, NULL) != 1) { PHP_PQ_ERROR("putcopyend failed: %s", pgsql); RETURN_FALSE; } #else while (zend_hash_get_current_data_ex(Z_ARRVAL_P(pg_rows), (void **) &tmp, &pos) == SUCCESS) { convert_to_string_ex(tmp); query = (char *)emalloc(Z_STRLEN_PP(tmp) + 2); strlcpy(query, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp) + 2); if(Z_STRLEN_PP(tmp) > 0 && *(query + Z_STRLEN_PP(tmp) - 1) != '\n') { strlcat(query, "\n", Z_STRLEN_PP(tmp) + 2); } if (PQputline(pgsql, query)==EOF) { efree(query); PHP_PQ_ERROR("copy failed: %s", pgsql); RETURN_FALSE; } efree(query); zend_hash_move_forward_ex(Z_ARRVAL_P(pg_rows), &pos); } if (PQputline(pgsql, "\\.\n") == EOF) { PHP_PQ_ERROR("putline failed: %s", pgsql); RETURN_FALSE; } if (PQendcopy(pgsql)) { PHP_PQ_ERROR("endcopy failed: %s", pgsql); RETURN_FALSE; } #endif while ((pgsql_result = PQgetResult(pgsql))) { if (PGRES_COMMAND_OK != PQresultStatus(pgsql_result)) { PHP_PQ_ERROR("Copy command failed: %s", pgsql); command_failed = 1; } PQclear(pgsql_result); } if (command_failed) { RETURN_FALSE; } } else { PQclear(pgsql_result); RETURN_FALSE; } RETURN_TRUE; break; default: PQclear(pgsql_result); PHP_PQ_ERROR("Copy command failed: %s", pgsql); RETURN_FALSE; break; } } /* }}} */ #ifdef HAVE_PQESCAPE /* {{{ proto string pg_escape_string([resource connection,] string data) Escape string for text/char type */ PHP_FUNCTION(pg_escape_string) { char *from = NULL, *to = NULL; zval *pgsql_link; #ifdef HAVE_PQESCAPE_CONN PGconn *pgsql; #endif int to_len; int from_len; int id = -1; switch (ZEND_NUM_ARGS()) { case 1: if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &from, &from_len) == FAILURE) { return; } pgsql_link = NULL; id = PGG(default_link); break; default: if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &from, &from_len) == FAILURE) { return; } break; } to = (char *) safe_emalloc(from_len, 2, 1); #ifdef HAVE_PQESCAPE_CONN if (pgsql_link != NULL || id != -1) { ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); to_len = (int) PQescapeStringConn(pgsql, to, from, (size_t)from_len, NULL); } else #endif to_len = (int) PQescapeString(to, from, (size_t)from_len); RETURN_STRINGL(to, to_len, 0); } /* }}} */ /* {{{ proto string pg_escape_bytea([resource connection,] string data) Escape binary for bytea type */ PHP_FUNCTION(pg_escape_bytea) { char *from = NULL, *to = NULL; size_t to_len; int from_len, id = -1; #ifdef HAVE_PQESCAPE_BYTEA_CONN PGconn *pgsql; #endif zval *pgsql_link; switch (ZEND_NUM_ARGS()) { case 1: if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &from, &from_len) == FAILURE) { return; } pgsql_link = NULL; id = PGG(default_link); break; default: if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &from, &from_len) == FAILURE) { return; } break; } #ifdef HAVE_PQESCAPE_BYTEA_CONN if (pgsql_link != NULL || id != -1) { ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); to = (char *)PQescapeByteaConn(pgsql, (unsigned char *)from, (size_t)from_len, &to_len); } else #endif to = (char *)PQescapeBytea((unsigned char*)from, from_len, &to_len); RETVAL_STRINGL(to, to_len-1, 1); /* to_len includes addtional '\0' */ PQfreemem(to); } /* }}} */ #if !HAVE_PQUNESCAPEBYTEA /* PQunescapeBytea() from PostgreSQL 7.3 to provide bytea unescape feature to 7.2 users. Renamed to php_pgsql_unescape_bytea() */ /* * PQunescapeBytea - converts the null terminated string representation * of a bytea, strtext, into binary, filling a buffer. It returns a * pointer to the buffer which is NULL on error, and the size of the * buffer in retbuflen. The pointer may subsequently be used as an * argument to the function free(3). It is the reverse of PQescapeBytea. * * The following transformations are reversed: * '\0' == ASCII 0 == \000 * '\'' == ASCII 39 == \' * '\\' == ASCII 92 == \\ * * States: * 0 normal 0->1->2->3->4 * 1 \ 1->5 * 2 \0 1->6 * 3 \00 * 4 \000 * 5 \' * 6 \\ */ static unsigned char * php_pgsql_unescape_bytea(unsigned char *strtext, size_t *retbuflen) { size_t buflen; unsigned char *buffer, *sp, *bp; unsigned int state = 0; if (strtext == NULL) return NULL; buflen = strlen(strtext); /* will shrink, also we discover if * strtext */ buffer = (unsigned char *) emalloc(buflen); /* isn't NULL terminated */ for (bp = buffer, sp = strtext; *sp != '\0'; bp++, sp++) { Vulnerability Type: Bypass CWE ID: CWE-254 Summary: PHP before 5.4.40, 5.5.x before 5.5.24, and 5.6.x before 5.6.8 does not ensure that pathnames lack %00 sequences, which might allow remote attackers to read arbitrary files via crafted input to an application that calls the stream_resolve_include_path function in ext/standard/streamsfuncs.c, as demonstrated by a filename\0.extension attack that bypasses an intended configuration in which client users may read files with only one specific extension. Commit Message:
Medium
165,315
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: ext2_xattr_put_super(struct super_block *sb) { mb_cache_shrink(sb->s_bdev); } Vulnerability Type: DoS CWE ID: CWE-19 Summary: The mbcache feature in the ext2 and ext4 filesystem implementations in the Linux kernel before 4.6 mishandles xattr block caching, which allows local users to cause a denial of service (soft lockup) via filesystem operations in environments that use many attributes, as demonstrated by Ceph and Samba. Commit Message: ext2: convert to mbcache2 The conversion is generally straightforward. We convert filesystem from a global cache to per-fs one. Similarly to ext4 the tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting the buffer lock. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]>
Low
169,982
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: nfsd4_encode_getdeviceinfo(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_getdeviceinfo *gdev) { struct xdr_stream *xdr = &resp->xdr; const struct nfsd4_layout_ops *ops = nfsd4_layout_ops[gdev->gd_layout_type]; u32 starting_len = xdr->buf->len, needed_len; __be32 *p; dprintk("%s: err %d\n", __func__, be32_to_cpu(nfserr)); if (nfserr) goto out; nfserr = nfserr_resource; p = xdr_reserve_space(xdr, 4); if (!p) goto out; *p++ = cpu_to_be32(gdev->gd_layout_type); /* If maxcount is 0 then just update notifications */ if (gdev->gd_maxcount != 0) { nfserr = ops->encode_getdeviceinfo(xdr, gdev); if (nfserr) { /* * We don't bother to burden the layout drivers with * enforcing gd_maxcount, just tell the client to * come back with a bigger buffer if it's not enough. */ if (xdr->buf->len + 4 > gdev->gd_maxcount) goto toosmall; goto out; } } nfserr = nfserr_resource; if (gdev->gd_notify_types) { p = xdr_reserve_space(xdr, 4 + 4); if (!p) goto out; *p++ = cpu_to_be32(1); /* bitmap length */ *p++ = cpu_to_be32(gdev->gd_notify_types); } else { p = xdr_reserve_space(xdr, 4); if (!p) goto out; *p++ = 0; } nfserr = 0; out: kfree(gdev->gd_device); dprintk("%s: done: %d\n", __func__, be32_to_cpu(nfserr)); return nfserr; toosmall: dprintk("%s: maxcount too small\n", __func__); needed_len = xdr->buf->len + 4 /* notifications */; xdr_truncate_encode(xdr, starting_len); p = xdr_reserve_space(xdr, 4); if (!p) { nfserr = nfserr_resource; } else { *p++ = cpu_to_be32(needed_len); nfserr = nfserr_toosmall; } goto out; } Vulnerability Type: DoS CWE ID: CWE-404 Summary: The NFSv4 implementation in the Linux kernel through 4.11.1 allows local users to cause a denial of service (resource consumption) by leveraging improper channel callback shutdown when unmounting an NFSv4 filesystem, aka a *module reference and kernel daemon* leak. Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ...
Medium
168,148
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: store_current_palette(png_store *ps, int *npalette) { /* This is an internal error (the call has been made outside a read * operation.) */ if (ps->current == NULL) store_log(ps, ps->pread, "no current stream for palette", 1); /* The result may be null if there is no palette. */ *npalette = ps->current->npalette; return ps->current->palette; } 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
173,703
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: Chapters::Atom::~Atom() { } 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: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
High
174,454
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: babel_print_v2(netdissect_options *ndo, const u_char *cp, u_int length) { u_int i; u_short bodylen; u_char v4_prefix[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0, 0, 0 }; u_char v6_prefix[16] = {0}; ND_TCHECK2(*cp, 4); if (length < 4) goto invalid; bodylen = EXTRACT_16BITS(cp + 2); ND_PRINT((ndo, " (%u)", bodylen)); /* Process the TLVs in the body */ i = 0; while(i < bodylen) { const u_char *message; u_int type, len; message = cp + 4 + i; ND_TCHECK2(*message, 1); if((type = message[0]) == MESSAGE_PAD1) { ND_PRINT((ndo, ndo->ndo_vflag ? "\n\tPad 1" : " pad1")); i += 1; continue; } ND_TCHECK2(*message, 2); ICHECK(i, 2); len = message[1]; ND_TCHECK2(*message, 2 + len); ICHECK(i, 2 + len); switch(type) { case MESSAGE_PADN: { if (!ndo->ndo_vflag) ND_PRINT((ndo, " padN")); else ND_PRINT((ndo, "\n\tPad %d", len + 2)); } break; case MESSAGE_ACK_REQ: { u_short nonce, interval; if (!ndo->ndo_vflag) ND_PRINT((ndo, " ack-req")); else { ND_PRINT((ndo, "\n\tAcknowledgment Request ")); if(len < 6) goto invalid; nonce = EXTRACT_16BITS(message + 4); interval = EXTRACT_16BITS(message + 6); ND_PRINT((ndo, "%04x %s", nonce, format_interval(interval))); } } break; case MESSAGE_ACK: { u_short nonce; if (!ndo->ndo_vflag) ND_PRINT((ndo, " ack")); else { ND_PRINT((ndo, "\n\tAcknowledgment ")); if(len < 2) goto invalid; nonce = EXTRACT_16BITS(message + 2); ND_PRINT((ndo, "%04x", nonce)); } } break; case MESSAGE_HELLO: { u_short seqno, interval; if (!ndo->ndo_vflag) ND_PRINT((ndo, " hello")); else { ND_PRINT((ndo, "\n\tHello ")); if(len < 6) goto invalid; seqno = EXTRACT_16BITS(message + 4); interval = EXTRACT_16BITS(message + 6); ND_PRINT((ndo, "seqno %u interval %s", seqno, format_interval(interval))); /* Extra data. */ if(len > 6) subtlvs_print(ndo, message + 8, message + 2 + len, type); } } break; case MESSAGE_IHU: { unsigned short txcost, interval; if (!ndo->ndo_vflag) ND_PRINT((ndo, " ihu")); else { u_char address[16]; int rc; ND_PRINT((ndo, "\n\tIHU ")); if(len < 6) goto invalid; txcost = EXTRACT_16BITS(message + 4); interval = EXTRACT_16BITS(message + 6); rc = network_address(message[2], message + 8, len - 6, address); if(rc < 0) { ND_PRINT((ndo, "%s", tstr)); break; } ND_PRINT((ndo, "%s txcost %u interval %s", format_address(ndo, address), txcost, format_interval(interval))); /* Extra data. */ if((u_int)rc < len - 6) subtlvs_print(ndo, message + 8 + rc, message + 2 + len, type); } } break; case MESSAGE_ROUTER_ID: { if (!ndo->ndo_vflag) ND_PRINT((ndo, " router-id")); else { ND_PRINT((ndo, "\n\tRouter Id")); if(len < 10) goto invalid; ND_PRINT((ndo, " %s", format_id(message + 4))); } } break; case MESSAGE_NH: { if (!ndo->ndo_vflag) ND_PRINT((ndo, " nh")); else { int rc; u_char nh[16]; ND_PRINT((ndo, "\n\tNext Hop")); if(len < 2) goto invalid; rc = network_address(message[2], message + 4, len - 2, nh); if(rc < 0) goto invalid; ND_PRINT((ndo, " %s", format_address(ndo, nh))); } } break; case MESSAGE_UPDATE: { if (!ndo->ndo_vflag) { ND_PRINT((ndo, " update")); if(len < 1) ND_PRINT((ndo, "/truncated")); else ND_PRINT((ndo, "%s%s%s", (message[3] & 0x80) ? "/prefix": "", (message[3] & 0x40) ? "/id" : "", (message[3] & 0x3f) ? "/unknown" : "")); } else { u_short interval, seqno, metric; u_char plen; int rc; u_char prefix[16]; ND_PRINT((ndo, "\n\tUpdate")); if(len < 10) goto invalid; plen = message[4] + (message[2] == 1 ? 96 : 0); rc = network_prefix(message[2], message[4], message[5], message + 12, message[2] == 1 ? v4_prefix : v6_prefix, len - 10, prefix); if(rc < 0) goto invalid; interval = EXTRACT_16BITS(message + 6); seqno = EXTRACT_16BITS(message + 8); metric = EXTRACT_16BITS(message + 10); ND_PRINT((ndo, "%s%s%s %s metric %u seqno %u interval %s", (message[3] & 0x80) ? "/prefix": "", (message[3] & 0x40) ? "/id" : "", (message[3] & 0x3f) ? "/unknown" : "", format_prefix(ndo, prefix, plen), metric, seqno, format_interval_update(interval))); if(message[3] & 0x80) { if(message[2] == 1) memcpy(v4_prefix, prefix, 16); else memcpy(v6_prefix, prefix, 16); } /* extra data? */ if((u_int)rc < len - 10) subtlvs_print(ndo, message + 12 + rc, message + 2 + len, type); } } break; case MESSAGE_REQUEST: { if (!ndo->ndo_vflag) ND_PRINT((ndo, " request")); else { int rc; u_char prefix[16], plen; ND_PRINT((ndo, "\n\tRequest ")); if(len < 2) goto invalid; plen = message[3] + (message[2] == 1 ? 96 : 0); rc = network_prefix(message[2], message[3], 0, message + 4, NULL, len - 2, prefix); if(rc < 0) goto invalid; ND_PRINT((ndo, "for %s", message[2] == 0 ? "any" : format_prefix(ndo, prefix, plen))); } } break; case MESSAGE_MH_REQUEST : { if (!ndo->ndo_vflag) ND_PRINT((ndo, " mh-request")); else { int rc; u_short seqno; u_char prefix[16], plen; ND_PRINT((ndo, "\n\tMH-Request ")); if(len < 14) goto invalid; seqno = EXTRACT_16BITS(message + 4); rc = network_prefix(message[2], message[3], 0, message + 16, NULL, len - 14, prefix); if(rc < 0) goto invalid; plen = message[3] + (message[2] == 1 ? 96 : 0); ND_PRINT((ndo, "(%u hops) for %s seqno %u id %s", message[6], format_prefix(ndo, prefix, plen), seqno, format_id(message + 8))); } } break; case MESSAGE_TSPC : if (!ndo->ndo_vflag) ND_PRINT((ndo, " tspc")); else { ND_PRINT((ndo, "\n\tTS/PC ")); if(len < 6) goto invalid; ND_PRINT((ndo, "timestamp %u packetcounter %u", EXTRACT_32BITS (message + 4), EXTRACT_16BITS(message + 2))); } break; case MESSAGE_HMAC : { if (!ndo->ndo_vflag) ND_PRINT((ndo, " hmac")); else { unsigned j; ND_PRINT((ndo, "\n\tHMAC ")); if(len < 18) goto invalid; ND_PRINT((ndo, "key-id %u digest-%u ", EXTRACT_16BITS(message + 2), len - 2)); for (j = 0; j < len - 2; j++) ND_PRINT((ndo, "%02X", message[4 + j])); } } break; case MESSAGE_UPDATE_SRC_SPECIFIC : { if(!ndo->ndo_vflag) { ND_PRINT((ndo, " ss-update")); } else { u_char prefix[16], src_prefix[16]; u_short interval, seqno, metric; u_char ae, plen, src_plen, omitted; int rc; int parsed_len = 10; ND_PRINT((ndo, "\n\tSS-Update")); if(len < 10) goto invalid; ae = message[2]; src_plen = message[3]; plen = message[4]; omitted = message[5]; interval = EXTRACT_16BITS(message + 6); seqno = EXTRACT_16BITS(message + 8); metric = EXTRACT_16BITS(message + 10); rc = network_prefix(ae, plen, omitted, message + 2 + parsed_len, ae == 1 ? v4_prefix : v6_prefix, len - parsed_len, prefix); if(rc < 0) goto invalid; if(ae == 1) plen += 96; parsed_len += rc; rc = network_prefix(ae, src_plen, 0, message + 2 + parsed_len, NULL, len - parsed_len, src_prefix); if(rc < 0) goto invalid; if(ae == 1) src_plen += 96; parsed_len += rc; ND_PRINT((ndo, " %s from", format_prefix(ndo, prefix, plen))); ND_PRINT((ndo, " %s metric %u seqno %u interval %s", format_prefix(ndo, src_prefix, src_plen), metric, seqno, format_interval_update(interval))); /* extra data? */ if((u_int)parsed_len < len) subtlvs_print(ndo, message + 2 + parsed_len, message + 2 + len, type); } } break; case MESSAGE_REQUEST_SRC_SPECIFIC : { if(!ndo->ndo_vflag) ND_PRINT((ndo, " ss-request")); else { int rc, parsed_len = 3; u_char ae, plen, src_plen, prefix[16], src_prefix[16]; ND_PRINT((ndo, "\n\tSS-Request ")); if(len < 3) goto invalid; ae = message[2]; plen = message[3]; src_plen = message[4]; rc = network_prefix(ae, plen, 0, message + 2 + parsed_len, NULL, len - parsed_len, prefix); if(rc < 0) goto invalid; if(ae == 1) plen += 96; parsed_len += rc; rc = network_prefix(ae, src_plen, 0, message + 2 + parsed_len, NULL, len - parsed_len, src_prefix); if(rc < 0) goto invalid; if(ae == 1) src_plen += 96; parsed_len += rc; if(ae == 0) { ND_PRINT((ndo, "for any")); } else { ND_PRINT((ndo, "for (%s, ", format_prefix(ndo, prefix, plen))); ND_PRINT((ndo, "%s)", format_prefix(ndo, src_prefix, src_plen))); } } } break; case MESSAGE_MH_REQUEST_SRC_SPECIFIC : { if(!ndo->ndo_vflag) ND_PRINT((ndo, " ss-mh-request")); else { int rc, parsed_len = 14; u_short seqno; u_char ae, plen, src_plen, prefix[16], src_prefix[16], hopc; const u_char *router_id = NULL; ND_PRINT((ndo, "\n\tSS-MH-Request ")); if(len < 14) goto invalid; ae = message[2]; plen = message[3]; seqno = EXTRACT_16BITS(message + 4); hopc = message[6]; src_plen = message[7]; router_id = message + 8; rc = network_prefix(ae, plen, 0, message + 2 + parsed_len, NULL, len - parsed_len, prefix); if(rc < 0) goto invalid; if(ae == 1) plen += 96; parsed_len += rc; rc = network_prefix(ae, src_plen, 0, message + 2 + parsed_len, NULL, len - parsed_len, src_prefix); if(rc < 0) goto invalid; if(ae == 1) src_plen += 96; ND_PRINT((ndo, "(%u hops) for (%s, ", hopc, format_prefix(ndo, prefix, plen))); ND_PRINT((ndo, "%s) seqno %u id %s", format_prefix(ndo, src_prefix, src_plen), seqno, format_id(router_id))); } } break; default: if (!ndo->ndo_vflag) ND_PRINT((ndo, " unknown")); else ND_PRINT((ndo, "\n\tUnknown message type %d", type)); } i += len + 2; } return; trunc: ND_PRINT((ndo, " %s", tstr)); return; invalid: ND_PRINT((ndo, "%s", istr)); return; } Vulnerability Type: CWE ID: CWE-125 Summary: The Babel parser in tcpdump before 4.9.3 has a buffer over-read in print-babel.c:babel_print_v2(). Commit Message: (for 4.9.3) CVE-2018-14470/Babel: fix an existing length check In babel_print_v2() the non-verbose branch for an Update TLV compared the TLV Length against 1 instead of 10 (probably a typo), put it right. This fixes a buffer over-read discovered by Henri Salo from Nixu Corporation. Add a test using the capture file supplied by the reporter(s).
High
169,841
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static int interface_get_command(QXLInstance *sin, struct QXLCommandExt *ext) { SimpleSpiceDisplay *ssd = container_of(sin, SimpleSpiceDisplay, qxl); info->num_memslots = NUM_MEMSLOTS; info->num_memslots_groups = NUM_MEMSLOTS_GROUPS; info->internal_groupslot_id = 0; info->qxl_ram_size = ssd->bufsize; info->n_surfaces = ssd->num_surfaces; } Vulnerability Type: +Info CWE ID: CWE-200 Summary: The VGA emulator in QEMU allows local guest users to read host memory by setting the display to a high resolution. Commit Message:
Low
165,150
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: int vis_emul(struct pt_regs *regs, unsigned int insn) { unsigned long pc = regs->tpc; unsigned int opf; BUG_ON(regs->tstate & TSTATE_PRIV); perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0); if (test_thread_flag(TIF_32BIT)) pc = (u32)pc; if (get_user(insn, (u32 __user *) pc)) return -EFAULT; save_and_clear_fpu(); opf = (insn & VIS_OPF_MASK) >> VIS_OPF_SHIFT; switch (opf) { default: return -EINVAL; /* Pixel Formatting Instructions. */ case FPACK16_OPF: case FPACK32_OPF: case FPACKFIX_OPF: case FEXPAND_OPF: case FPMERGE_OPF: pformat(regs, insn, opf); break; /* Partitioned Multiply Instructions */ case FMUL8x16_OPF: case FMUL8x16AU_OPF: case FMUL8x16AL_OPF: case FMUL8SUx16_OPF: case FMUL8ULx16_OPF: case FMULD8SUx16_OPF: case FMULD8ULx16_OPF: pmul(regs, insn, opf); break; /* Pixel Compare Instructions */ case FCMPGT16_OPF: case FCMPGT32_OPF: case FCMPLE16_OPF: case FCMPLE32_OPF: case FCMPNE16_OPF: case FCMPNE32_OPF: case FCMPEQ16_OPF: case FCMPEQ32_OPF: pcmp(regs, insn, opf); break; /* Edge Handling Instructions */ case EDGE8_OPF: case EDGE8N_OPF: case EDGE8L_OPF: case EDGE8LN_OPF: case EDGE16_OPF: case EDGE16N_OPF: case EDGE16L_OPF: case EDGE16LN_OPF: case EDGE32_OPF: case EDGE32N_OPF: case EDGE32L_OPF: case EDGE32LN_OPF: edge(regs, insn, opf); break; /* Pixel Component Distance */ case PDIST_OPF: pdist(regs, insn); break; /* Three-Dimensional Array Addressing Instructions */ case ARRAY8_OPF: case ARRAY16_OPF: case ARRAY32_OPF: array(regs, insn, opf); break; /* Byte Mask and Shuffle Instructions */ case BMASK_OPF: bmask(regs, insn); break; case BSHUFFLE_OPF: bshuffle(regs, insn); break; } regs->tpc = regs->tnpc; regs->tnpc += 4; return 0; } Vulnerability Type: DoS Overflow CWE ID: CWE-399 Summary: The Performance Events subsystem in the Linux kernel before 3.1 does not properly handle event overflows associated with PERF_COUNT_SW_CPU_CLOCK events, which allows local users to cause a denial of service (system hang) via a crafted application. Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]>
Medium
165,813
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static void timer_enter_running(Timer *t) { _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL; int r; assert(t); /* Don't start job if we are supposed to go down */ if (unit_stop_pending(UNIT(t))) return; r = manager_add_job(UNIT(t)->manager, JOB_START, UNIT_TRIGGER(UNIT(t)), JOB_REPLACE, true, &error, NULL); if (r < 0) goto fail; dual_timestamp_get(&t->last_trigger); if (t->stamp_path) touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, 0); timer_set_state(t, TIMER_RUNNING); return; fail: log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r)); timer_enter_dead(t, TIMER_FAILURE_RESOURCES); } Vulnerability Type: CWE ID: CWE-264 Summary: A flaw in systemd v228 in /src/basic/fs-util.c caused world writable suid files to be created when using the systemd timers features, allowing local attackers to escalate their privileges to root. This is fixed in v229. Commit Message: util-lib: use MODE_INVALID as invalid value for mode_t everywhere
High
170,106
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: spnego_gss_verify_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count) { return gss_verify_mic_iov(minor_status, context_handle, qop_state, iov, iov_count); } 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
166,670
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: AppCacheUpdateJob::~AppCacheUpdateJob() { if (service_) service_->RemoveObserver(this); if (internal_state_ != COMPLETED) Cancel(); DCHECK(!manifest_fetcher_); DCHECK(pending_url_fetches_.empty()); DCHECK(!inprogress_cache_.get()); DCHECK(pending_master_entries_.empty()); DCHECK(master_entry_fetches_.empty()); if (group_) group_->SetUpdateAppCacheStatus(AppCacheGroup::IDLE); } Vulnerability Type: DoS Exec Code CWE ID: Summary: Use-after-free vulnerability in content/browser/appcache/appcache_update_job.cc in Google Chrome before 47.0.2526.73 allows remote attackers to execute arbitrary code or cause a denial of service by leveraging the mishandling of AppCache update jobs. Commit Message: AppCache: fix a browser crashing bug that can happen during updates. BUG=558589 Review URL: https://codereview.chromium.org/1463463003 Cr-Commit-Position: refs/heads/master@{#360967}
High
171,734
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void WebsiteSettings::OnUIClosing() { if (show_info_bar_) WebsiteSettingsInfoBarDelegate::Create(infobar_service_); SSLCertificateDecisionsDidRevoke user_decision = did_revoke_user_ssl_decisions_ ? USER_CERT_DECISIONS_REVOKED : USER_CERT_DECISIONS_NOT_REVOKED; UMA_HISTOGRAM_ENUMERATION("interstitial.ssl.did_user_revoke_decisions", user_decision, END_OF_SSL_CERTIFICATE_DECISIONS_DID_REVOKE_ENUM); } Vulnerability Type: DoS CWE ID: Summary: Use-after-free vulnerability in the Infobars implementation in Google Chrome before 47.0.2526.73 allows remote attackers to cause a denial of service or possibly have unspecified other impact via a crafted web site, related to browser/ui/views/website_settings/website_settings_popup_view.cc. Commit Message: Fix UAF in Origin Info Bubble and permission settings UI. In addition to fixing the UAF, will this also fix the problem of the bubble showing over the previous tab (if the bubble is open when the tab it was opened for closes). BUG=490492 TBR=tedchoc Review URL: https://codereview.chromium.org/1317443002 Cr-Commit-Position: refs/heads/master@{#346023}
Medium
171,780
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *inet = inet_sk(sk); DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name); struct sk_buff *skb; unsigned int ulen, copied; int peeked, off = 0; int err; int is_udplite = IS_UDPLITE(sk); bool slow; if (flags & MSG_ERRQUEUE) return ip_recv_error(sk, msg, len, addr_len); try_again: skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0), &peeked, &off, &err); if (!skb) goto out; ulen = skb->len - sizeof(struct udphdr); copied = len; if (copied > ulen) copied = ulen; else if (copied < ulen) msg->msg_flags |= MSG_TRUNC; /* * If checksum is needed at all, try to do it while copying the * data. If the data is truncated, or if we only want a partial * coverage checksum (UDP-Lite), do it before the copy. */ if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) { if (udp_lib_checksum_complete(skb)) goto csum_copy_err; } if (skb_csum_unnecessary(skb)) err = skb_copy_datagram_msg(skb, sizeof(struct udphdr), msg, copied); else { err = skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr), msg); if (err == -EINVAL) goto csum_copy_err; } if (unlikely(err)) { trace_kfree_skb(skb, udp_recvmsg); if (!peeked) { atomic_inc(&sk->sk_drops); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } goto out_free; } if (!peeked) UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); sock_recv_ts_and_drops(msg, sk, skb); /* Copy the address. */ if (sin) { sin->sin_family = AF_INET; sin->sin_port = udp_hdr(skb)->source; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); *addr_len = sizeof(*sin); } if (inet->cmsg_flags) ip_cmsg_recv_offset(msg, skb, sizeof(struct udphdr)); err = copied; if (flags & MSG_TRUNC) err = ulen; out_free: skb_free_datagram_locked(sk, skb); out: return err; csum_copy_err: slow = lock_sock_fast(sk); if (!skb_kill_datagram(sk, skb, flags)) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } unlock_sock_fast(sk, slow); /* starting over for a new packet, but check if we need to yield */ cond_resched(); msg->msg_flags &= ~MSG_TRUNC; goto try_again; } Vulnerability Type: Exec Code CWE ID: CWE-358 Summary: udp.c in the Linux kernel before 4.5 allows remote attackers to execute arbitrary code via UDP traffic that triggers an unsafe second checksum calculation during execution of a recv system call with the MSG_PEEK flag. Commit Message: udp: properly support MSG_PEEK with truncated buffers Backport of this upstream commit into stable kernels : 89c22d8c3b27 ("net: Fix skb csum races when peeking") exposed a bug in udp stack vs MSG_PEEK support, when user provides a buffer smaller than skb payload. In this case, skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov); returns -EFAULT. This bug does not happen in upstream kernels since Al Viro did a great job to replace this into : skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr), msg); This variant is safe vs short buffers. For the time being, instead reverting Herbert Xu patch and add back skb->ip_summed invalid changes, simply store the result of udp_lib_checksum_complete() so that we avoid computing the checksum a second time, and avoid the problematic skb_copy_and_csum_datagram_iovec() call. This patch can be applied on recent kernels as it avoids a double checksumming, then backported to stable kernels as a bug fix. Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]>
High
168,479
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: destroy_one_secret (gpointer data) { char *secret = (char *) data; /* Don't leave the secret lying around in memory */ g_message ("%s: destroying %s", __func__, secret); memset (secret, 0, strlen (secret)); g_free (secret); } Vulnerability Type: +Info CWE ID: CWE-200 Summary: The destroy_one_secret function in nm-setting-vpn.c in libnm-util in the NetworkManager package 0.8.999-3.git20110526 in Fedora 15 creates a log entry containing a certificate password, which allows local users to obtain sensitive information by reading a log file. Commit Message:
Low
164,689
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: bool CustomButton::AcceleratorPressed(const ui::Accelerator& accelerator) { SetState(STATE_NORMAL); ui::MouseEvent synthetic_event( ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); NotifyClick(synthetic_event); return true; } Vulnerability Type: CWE ID: CWE-254 Summary: The CustomButton::AcceleratorPressed function in ui/views/controls/button/custom_button.cc in Google Chrome before 48.0.2564.82 allows remote attackers to spoof URLs via vectors involving an unfocused custom button. Commit Message: Custom buttons should only handle accelerators when focused. BUG=541415 Review URL: https://codereview.chromium.org/1437523005 Cr-Commit-Position: refs/heads/master@{#360130}
Medium
172,236
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static Image *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image,*palette; ImageInfo *clone_info; MagickBooleanType status; MagickOffsetType offset; size_t EncodedByte; unsigned char RunCount,RunValue,RunCountMasked; CUTHeader Header; CUTPalHeader PalHeader; ssize_t depth; ssize_t i,j; ssize_t ldblk; unsigned char *BImgBuff=NULL,*ptrB; PixelPacket *q; /* 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); } /* Read CUT image. */ palette=NULL; clone_info=NULL; Header.Width=ReadBlobLSBShort(image); Header.Height=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.Width==0 || Header.Height==0 || Header.Reserved!=0) CUT_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /*---This code checks first line of image---*/ EncodedByte=ReadBlobLSBShort(image); RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; ldblk=0; while((int) RunCountMasked!=0) /*end of line?*/ { i=1; if((int) RunCount<0x80) i=(ssize_t) RunCountMasked; offset=SeekBlob(image,TellBlob(image)+i,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data*/ EncodedByte-=i+1; ldblk+=(ssize_t) RunCountMasked; RunCount=(unsigned char) ReadBlobByte(image); if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data: unexpected eof in line*/ RunCountMasked=RunCount & 0x7F; } if(EncodedByte!=1) goto CUT_KO; /*wrong data: size incorrect*/ i=0; /*guess a number of bit planes*/ if(ldblk==(int) Header.Width) i=8; if(2*ldblk==(int) Header.Width) i=4; if(8*ldblk==(int) Header.Width) i=1; if(i==0) goto CUT_KO; /*wrong data: incorrect bit planes*/ depth=i; image->columns=Header.Width; image->rows=Header.Height; image->depth=8; image->colors=(size_t) (GetQuantumRange(1UL*i)+1); if (image_info->ping) goto Finish; /* ----- Do something with palette ----- */ if ((clone_info=CloneImageInfo(image_info)) == NULL) goto NoPalette; i=(ssize_t) strlen(clone_info->filename); j=i; while(--i>0) { if(clone_info->filename[i]=='.') { break; } if(clone_info->filename[i]=='/' || clone_info->filename[i]=='\\' || clone_info->filename[i]==':' ) { i=j; break; } } (void) CopyMagickString(clone_info->filename+i,".PAL",(size_t) (MaxTextExtent-i)); if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { (void) CopyMagickString(clone_info->filename+i,".pal",(size_t) (MaxTextExtent-i)); if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { clone_info->filename[i]='\0'; if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { clone_info=DestroyImageInfo(clone_info); clone_info=NULL; goto NoPalette; } } } if( (palette=AcquireImage(clone_info))==NULL ) goto NoPalette; status=OpenBlob(clone_info,palette,ReadBinaryBlobMode,exception); if (status == MagickFalse) { ErasePalette: palette=DestroyImage(palette); palette=NULL; goto NoPalette; } if(palette!=NULL) { (void) ReadBlob(palette,2,(unsigned char *) PalHeader.FileId); if(strncmp(PalHeader.FileId,"AH",2) != 0) goto ErasePalette; PalHeader.Version=ReadBlobLSBShort(palette); PalHeader.Size=ReadBlobLSBShort(palette); PalHeader.FileType=(char) ReadBlobByte(palette); PalHeader.SubType=(char) ReadBlobByte(palette); PalHeader.BoardID=ReadBlobLSBShort(palette); PalHeader.GraphicsMode=ReadBlobLSBShort(palette); PalHeader.MaxIndex=ReadBlobLSBShort(palette); PalHeader.MaxRed=ReadBlobLSBShort(palette); PalHeader.MaxGreen=ReadBlobLSBShort(palette); PalHeader.MaxBlue=ReadBlobLSBShort(palette); (void) ReadBlob(palette,20,(unsigned char *) PalHeader.PaletteId); if(PalHeader.MaxIndex<1) goto ErasePalette; image->colors=PalHeader.MaxIndex+1; if (AcquireImageColormap(image,image->colors) == MagickFalse) goto NoMemory; if(PalHeader.MaxRed==0) PalHeader.MaxRed=(unsigned int) QuantumRange; /*avoid division by 0*/ if(PalHeader.MaxGreen==0) PalHeader.MaxGreen=(unsigned int) QuantumRange; if(PalHeader.MaxBlue==0) PalHeader.MaxBlue=(unsigned int) QuantumRange; for(i=0;i<=(int) PalHeader.MaxIndex;i++) { /*this may be wrong- I don't know why is palette such strange*/ j=(ssize_t) TellBlob(palette); if((j % 512)>512-6) { j=((j / 512)+1)*512; offset=SeekBlob(palette,j,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image->colormap[i].red=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxRed) { image->colormap[i].red=ClampToQuantum(((double) image->colormap[i].red*QuantumRange+(PalHeader.MaxRed>>1))/ PalHeader.MaxRed); } image->colormap[i].green=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxGreen) { image->colormap[i].green=ClampToQuantum (((double) image->colormap[i].green*QuantumRange+(PalHeader.MaxGreen>>1))/PalHeader.MaxGreen); } image->colormap[i].blue=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxBlue) { image->colormap[i].blue=ClampToQuantum (((double)image->colormap[i].blue*QuantumRange+(PalHeader.MaxBlue>>1))/PalHeader.MaxBlue); } } } NoPalette: if(palette==NULL) { image->colors=256; if (AcquireImageColormap(image,image->colors) == MagickFalse) { NoMemory: ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t)image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i); } } /* ----- Load RLE compressed raster ----- */ BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk, sizeof(*BImgBuff)); /*Ldblk was set in the check phase*/ if(BImgBuff==NULL) goto NoMemory; offset=SeekBlob(image,6 /*sizeof(Header)*/,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); for (i=0; i < (int) Header.Height; i++) { EncodedByte=ReadBlobLSBShort(image); ptrB=BImgBuff; j=ldblk; RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; while ((int) RunCountMasked != 0) { if((ssize_t) RunCountMasked>j) { /*Wrong Data*/ RunCountMasked=(unsigned char) j; if(j==0) { break; } } if((int) RunCount>0x80) { RunValue=(unsigned char) ReadBlobByte(image); (void) ResetMagickMemory(ptrB,(int) RunValue,(size_t) RunCountMasked); } else { (void) ReadBlob(image,(size_t) RunCountMasked,ptrB); } ptrB+=(int) RunCountMasked; j-=(int) RunCountMasked; if (EOFBlob(image) != MagickFalse) goto Finish; /* wrong data: unexpected eof in line */ RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; } InsertRow(depth,BImgBuff,i,image); } (void) SyncImage(image); /*detect monochrome image*/ if(palette==NULL) { /*attempt to detect binary (black&white) images*/ if ((image->storage_class == PseudoClass) && (IsGrayImage(image,&image->exception) != MagickFalse)) { if(GetCutColors(image)==2) { for (i=0; i < (ssize_t)image->colors; i++) { register Quantum sample; sample=ScaleCharToQuantum((unsigned char) i); if(image->colormap[i].red!=sample) goto Finish; if(image->colormap[i].green!=sample) goto Finish; if(image->colormap[i].blue!=sample) goto Finish; } image->colormap[1].red=image->colormap[1].green= image->colormap[1].blue=QuantumRange; for (i=0; i < (ssize_t)image->rows; i++) { q=QueueAuthenticPixels(image,0,i,image->columns,1,exception); for (j=0; j < (ssize_t)image->columns; j++) { if (GetPixelRed(q) == ScaleCharToQuantum(1)) { SetPixelRed(q,QuantumRange); SetPixelGreen(q,QuantumRange); SetPixelBlue(q,QuantumRange); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) goto Finish; } } } } Finish: if (BImgBuff != NULL) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); if (palette != NULL) palette=DestroyImage(palette); if (clone_info != NULL) clone_info=DestroyImageInfo(clone_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
168,554
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: mprint(struct magic_set *ms, struct magic *m) { uint64_t v; float vf; double vd; int64_t t = 0; char buf[128], tbuf[26]; union VALUETYPE *p = &ms->ms_value; switch (m->type) { case FILE_BYTE: v = file_signextend(ms, m, (uint64_t)p->b); switch (check_fmt(ms, m)) { case -1: return -1; case 1: (void)snprintf(buf, sizeof(buf), "%d", (unsigned char)v); if (file_printf(ms, F(ms, m, "%s"), buf) == -1) return -1; break; default: if (file_printf(ms, F(ms, m, "%d"), (unsigned char) v) == -1) return -1; break; } t = ms->offset + sizeof(char); break; case FILE_SHORT: case FILE_BESHORT: case FILE_LESHORT: v = file_signextend(ms, m, (uint64_t)p->h); switch (check_fmt(ms, m)) { case -1: return -1; case 1: (void)snprintf(buf, sizeof(buf), "%u", (unsigned short)v); if (file_printf(ms, F(ms, m, "%s"), buf) == -1) return -1; break; default: if (file_printf(ms, F(ms, m, "%u"), (unsigned short) v) == -1) return -1; break; } t = ms->offset + sizeof(short); break; case FILE_LONG: case FILE_BELONG: case FILE_LELONG: case FILE_MELONG: v = file_signextend(ms, m, (uint64_t)p->l); switch (check_fmt(ms, m)) { case -1: return -1; case 1: (void)snprintf(buf, sizeof(buf), "%u", (uint32_t) v); if (file_printf(ms, F(ms, m, "%s"), buf) == -1) return -1; break; default: if (file_printf(ms, F(ms, m, "%u"), (uint32_t) v) == -1) return -1; break; } t = ms->offset + sizeof(int32_t); break; case FILE_QUAD: case FILE_BEQUAD: case FILE_LEQUAD: v = file_signextend(ms, m, p->q); switch (check_fmt(ms, m)) { case -1: return -1; case 1: (void)snprintf(buf, sizeof(buf), "%" INT64_T_FORMAT "u", (unsigned long long)v); if (file_printf(ms, F(ms, m, "%s"), buf) == -1) return -1; break; default: if (file_printf(ms, F(ms, m, "%" INT64_T_FORMAT "u"), (unsigned long long) v) == -1) return -1; break; } t = ms->offset + sizeof(int64_t); break; case FILE_STRING: case FILE_PSTRING: case FILE_BESTRING16: case FILE_LESTRING16: if (m->reln == '=' || m->reln == '!') { if (file_printf(ms, F(ms, m, "%s"), m->value.s) == -1) return -1; t = ms->offset + m->vallen; } else { char *str = p->s; /* compute t before we mangle the string? */ t = ms->offset + strlen(str); if (*m->value.s == '\0') str[strcspn(str, "\n")] = '\0'; if (m->str_flags & STRING_TRIM) { char *last; while (isspace((unsigned char)*str)) str++; last = str; while (*last) last++; --last; while (isspace((unsigned char)*last)) last--; *++last = '\0'; } if (file_printf(ms, F(ms, m, "%s"), str) == -1) return -1; if (m->type == FILE_PSTRING) t += file_pstring_length_size(m); } break; case FILE_DATE: case FILE_BEDATE: case FILE_LEDATE: case FILE_MEDATE: if (file_printf(ms, F(ms, m, "%s"), file_fmttime(p->l, FILE_T_LOCAL, tbuf)) == -1) return -1; t = ms->offset + sizeof(uint32_t); break; case FILE_LDATE: case FILE_BELDATE: case FILE_LELDATE: case FILE_MELDATE: if (file_printf(ms, F(ms, m, "%s"), file_fmttime(p->l, 0, tbuf)) == -1) return -1; t = ms->offset + sizeof(uint32_t); break; case FILE_QDATE: case FILE_BEQDATE: case FILE_LEQDATE: if (file_printf(ms, F(ms, m, "%s"), file_fmttime(p->q, FILE_T_LOCAL, tbuf)) == -1) return -1; t = ms->offset + sizeof(uint64_t); break; case FILE_QLDATE: case FILE_BEQLDATE: case FILE_LEQLDATE: if (file_printf(ms, F(ms, m, "%s"), file_fmttime(p->q, 0, tbuf)) == -1) return -1; t = ms->offset + sizeof(uint64_t); break; case FILE_QWDATE: case FILE_BEQWDATE: case FILE_LEQWDATE: if (file_printf(ms, F(ms, m, "%s"), file_fmttime(p->q, FILE_T_WINDOWS, tbuf)) == -1) return -1; t = ms->offset + sizeof(uint64_t); break; case FILE_FLOAT: case FILE_BEFLOAT: case FILE_LEFLOAT: vf = p->f; switch (check_fmt(ms, m)) { case -1: return -1; case 1: (void)snprintf(buf, sizeof(buf), "%g", vf); if (file_printf(ms, F(ms, m, "%s"), buf) == -1) return -1; break; default: if (file_printf(ms, F(ms, m, "%g"), vf) == -1) return -1; break; } t = ms->offset + sizeof(float); break; case FILE_DOUBLE: case FILE_BEDOUBLE: case FILE_LEDOUBLE: vd = p->d; switch (check_fmt(ms, m)) { case -1: return -1; case 1: (void)snprintf(buf, sizeof(buf), "%g", vd); if (file_printf(ms, F(ms, m, "%s"), buf) == -1) return -1; break; default: if (file_printf(ms, F(ms, m, "%g"), vd) == -1) return -1; break; } t = ms->offset + sizeof(double); break; case FILE_REGEX: { char *cp; int rval; cp = strndup((const char *)ms->search.s, ms->search.rm_len); if (cp == NULL) { file_oomem(ms, ms->search.rm_len); return -1; } rval = file_printf(ms, F(ms, m, "%s"), cp); free(cp); if (rval == -1) return -1; if ((m->str_flags & REGEX_OFFSET_START)) t = ms->search.offset; else t = ms->search.offset + ms->search.rm_len; break; } case FILE_SEARCH: if (file_printf(ms, F(ms, m, "%s"), m->value.s) == -1) return -1; if ((m->str_flags & REGEX_OFFSET_START)) t = ms->search.offset; else t = ms->search.offset + m->vallen; break; case FILE_DEFAULT: case FILE_CLEAR: if (file_printf(ms, "%s", m->desc) == -1) return -1; t = ms->offset; break; case FILE_INDIRECT: case FILE_USE: case FILE_NAME: t = ms->offset; break; default: file_magerror(ms, "invalid m->type (%d) in mprint()", m->type); return -1; } return (int32_t)t; } Vulnerability Type: DoS CWE ID: CWE-399 Summary: file before 5.19 does not properly restrict the amount of data read during a regex search, which allows remote attackers to cause a denial of service (CPU consumption) via a crafted file that triggers backtracking during processing of an awk rule. NOTE: this vulnerability exists because of an incomplete fix for CVE-2013-7345. Commit Message: * Enforce limit of 8K on regex searches that have no limits * Allow the l modifier for regex to mean line count. Default to byte count. If line count is specified, assume a max of 80 characters per line to limit the byte count. * Don't allow conversions to be used for dates, allowing the mask field to be used as an offset. * Bump the version of the magic format so that regex changes are visible.
Medium
166,361
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void AppCacheHost::SelectCacheForWorker(int parent_process_id, int parent_host_id) { DCHECK(pending_start_update_callback_.is_null() && pending_swap_cache_callback_.is_null() && pending_get_status_callback_.is_null() && !is_selection_pending() && !was_select_cache_called_); was_select_cache_called_ = true; parent_process_id_ = parent_process_id; parent_host_id_ = parent_host_id; FinishCacheSelection(NULL, NULL); } Vulnerability Type: DoS CWE ID: Summary: Use-after-free vulnerability in the AppCache implementation in Google Chrome before 47.0.2526.73 allows remote attackers with renderer access to cause a denial of service or possibly have unspecified other impact by leveraging incorrect AppCacheUpdateJob behavior associated with duplicate cache selection. Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer. BUG=551044 Review URL: https://codereview.chromium.org/1418783005 Cr-Commit-Position: refs/heads/master@{#358815}
High
171,742
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: int read_ndx_and_attrs(int f_in, int f_out, int *iflag_ptr, uchar *type_ptr, char *buf, int *len_ptr) { int len, iflags = 0; struct file_list *flist; uchar fnamecmp_type = FNAMECMP_FNAME; int ndx; read_loop: while (1) { ndx = read_ndx(f_in); if (ndx >= 0) break; if (ndx == NDX_DONE) return ndx; if (ndx == NDX_DEL_STATS) { read_del_stats(f_in); if (am_sender && am_server) write_del_stats(f_out); continue; } if (!inc_recurse || am_sender) { int last; if (first_flist) last = first_flist->prev->ndx_start + first_flist->prev->used - 1; else last = -1; rprintf(FERROR, "Invalid file index: %d (%d - %d) [%s]\n", ndx, NDX_DONE, last, who_am_i()); exit_cleanup(RERR_PROTOCOL); } if (ndx == NDX_FLIST_EOF) { flist_eof = 1; if (DEBUG_GTE(FLIST, 3)) rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i()); write_int(f_out, NDX_FLIST_EOF); continue; } ndx = NDX_FLIST_OFFSET - ndx; if (ndx < 0 || ndx >= dir_flist->used) { ndx = NDX_FLIST_OFFSET - ndx; rprintf(FERROR, "Invalid dir index: %d (%d - %d) [%s]\n", ndx, NDX_FLIST_OFFSET, NDX_FLIST_OFFSET - dir_flist->used + 1, who_am_i()); exit_cleanup(RERR_PROTOCOL); } if (DEBUG_GTE(FLIST, 2)) { rprintf(FINFO, "[%s] receiving flist for dir %d\n", who_am_i(), ndx); } /* Send all the data we read for this flist to the generator. */ start_flist_forward(ndx); flist = recv_file_list(f_in, ndx); flist->parent_ndx = ndx; stop_flist_forward(); } iflags = protocol_version >= 29 ? read_shortint(f_in) : ITEM_TRANSFER | ITEM_MISSING_DATA; /* Support the protocol-29 keep-alive style. */ if (protocol_version < 30 && ndx == cur_flist->used && iflags == ITEM_IS_NEW) { if (am_sender) maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH); goto read_loop; } flist = flist_for_ndx(ndx, "read_ndx_and_attrs"); if (flist != cur_flist) { cur_flist = flist; if (am_sender) { file_old_total = cur_flist->used; for (flist = first_flist; flist != cur_flist; flist = flist->next) file_old_total += flist->used; } } if (iflags & ITEM_BASIS_TYPE_FOLLOWS) fnamecmp_type = read_byte(f_in); *type_ptr = fnamecmp_type; if (iflags & ITEM_XNAME_FOLLOWS) { if (iflags & ITEM_XNAME_FOLLOWS) { if ((len = read_vstring(f_in, buf, MAXPATHLEN)) < 0) exit_cleanup(RERR_PROTOCOL); } else { *buf = '\0'; len = -1; rprintf(FERROR, "received request to transfer non-regular file: %d [%s]\n", ndx, who_am_i()); exit_cleanup(RERR_PROTOCOL); } } *iflag_ptr = iflags; return ndx; } Vulnerability Type: Bypass CWE ID: Summary: The daemon in rsync 3.1.2, and 3.1.3-development before 2017-12-03, does not check for fnamecmp filenames in the daemon_filter_list data structure (in the recv_files function in receiver.c) and also does not apply the sanitize_paths protection mechanism to pathnames found in "xname follows" strings (in the read_ndx_and_attrs function in rsync.c), which allows remote attackers to bypass intended access restrictions. Commit Message:
High
164,598
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: parse_wbxml_attribute_list (proto_tree *tree, tvbuff_t *tvb, guint32 offset, guint32 str_tbl, guint8 level, guint8 *codepage_attr) { guint32 tvb_len = tvb_reported_length (tvb); guint32 off = offset; guint32 len; guint str_len; guint32 ent; guint32 idx; guint8 peek; DebugLog(("parse_wbxml_attr (level = %u, offset = %u)\n", level, offset)); /* Parse attributes */ while (off < tvb_len) { peek = tvb_get_guint8 (tvb, off); DebugLog(("ATTR: (top of while) level = %3u, peek = 0x%02X, " "off = %u, tvb_len = %u\n", level, peek, off, tvb_len)); if ((peek & 0x3F) < 5) switch (peek) { /* Global tokens in state = ATTR */ case 0x00: /* SWITCH_PAGE */ *codepage_attr = tvb_get_guint8 (tvb, off+1); proto_tree_add_text (tree, tvb, off, 2, " | Attr | A -->%3d " "| SWITCH_PAGE (Attr code page) |", *codepage_attr); off += 2; break; case 0x01: /* END */ /* BEWARE * The Attribute END token means either ">" or "/>" * and as a consequence both must be treated separately. * This is done in the TAG state parser. */ off++; DebugLog(("ATTR: level = %u, Return: len = %u\n", level, off - offset)); return (off - offset); case 0x02: /* ENTITY */ ent = tvb_get_guintvar (tvb, off+1, &len); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| ENTITY " "| %s'&#%u;'", level, *codepage_attr, Indent (level), ent); off += 1+len; break; case 0x03: /* STR_I */ len = tvb_strsize (tvb, off+1); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| STR_I (Inline string) " "| %s\'%s\'", level, *codepage_attr, Indent (level), tvb_format_text (tvb, off+1, len-1)); off += 1+len; break; case 0x04: /* LITERAL */ idx = tvb_get_guintvar (tvb, off+1, &len); str_len = tvb_strsize (tvb, str_tbl+idx); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| LITERAL (Literal Attribute) " "| %s<%s />", level, *codepage_attr, Indent (level), tvb_format_text (tvb, str_tbl+idx, str_len-1)); off += 1+len; break; case 0x40: /* EXT_I_0 */ case 0x41: /* EXT_I_1 */ case 0x42: /* EXT_I_2 */ /* Extension tokens */ len = tvb_strsize (tvb, off+1); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| EXT_I_%1x (Extension Token) " "| %s(Inline string extension: \'%s\')", level, *codepage_attr, peek & 0x0f, Indent (level), tvb_format_text (tvb, off+1, len-1)); off += 1+len; break; /* 0x43 impossible in ATTR state */ /* 0x44 impossible in ATTR state */ case 0x80: /* EXT_T_0 */ case 0x81: /* EXT_T_1 */ case 0x82: /* EXT_T_2 */ /* Extension tokens */ idx = tvb_get_guintvar (tvb, off+1, &len); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| EXT_T_%1x (Extension Token) " "| %s(Extension Token, integer value: %u)", level, *codepage_attr, peek & 0x0f, Indent (level), idx); off += 1+len; break; case 0x83: /* STR_T */ idx = tvb_get_guintvar (tvb, off+1, &len); str_len = tvb_strsize (tvb, str_tbl+idx); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| STR_T (Tableref string) " "| %s\'%s\'", level, *codepage_attr, Indent (level), tvb_format_text (tvb, str_tbl+idx, str_len-1)); off += 1+len; break; /* 0x84 impossible in ATTR state */ case 0xC0: /* EXT_0 */ case 0xC1: /* EXT_1 */ case 0xC2: /* EXT_2 */ /* Extension tokens */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Attr | A %3d " "| EXT_%1x (Extension Token) " "| %s(Single-byte extension)", level, *codepage_attr, peek & 0x0f, Indent (level)); off++; break; case 0xC3: /* OPAQUE - WBXML 1.1 and newer */ if (tvb_get_guint8 (tvb, 0)) { /* WBXML 1.x (x > 0) */ idx = tvb_get_guintvar (tvb, off+1, &len); proto_tree_add_text (tree, tvb, off, 1 + len + idx, " %3d | Attr | A %3d " "| OPAQUE (Opaque data) " "| %s(%d bytes of opaque data)", level, *codepage_attr, Indent (level), idx); off += 1+len+idx; } else { /* WBXML 1.0 - RESERVED_2 token (invalid) */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Attr | A %3d " "| RESERVED_2 (Invalid Token!) " "| WBXML 1.0 parsing stops here.", level, *codepage_attr); /* Stop processing as it is impossible to parse now */ off = tvb_len; DebugLog(("ATTR: level = %u, Return: len = %u\n", level, off - offset)); return (off - offset); } break; /* 0xC4 impossible in ATTR state */ default: proto_tree_add_text (tree, tvb, off, 1, " %3d | Attr | A %3d " "| %-10s (Invalid Token!) " "| WBXML parsing stops here.", level, *codepage_attr, val_to_str_ext (peek, &vals_wbxml1x_global_tokens_ext, "(unknown 0x%x)")); /* Move to end of buffer */ off = tvb_len; break; } else { /* Known atribute token */ if (peek & 0x80) { /* attrValue */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Attr | A %3d " "| Known attrValue 0x%02X " "| %sattrValue_0x%02X", level, *codepage_attr, peek & 0x7f, Indent (level), peek); off++; } else { /* attrStart */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Attr | A %3d " "| Known attrStart 0x%02X " "| %sattrStart_0x%02X", level, *codepage_attr, peek & 0x7f, Indent (level), peek); off++; } } } /* End WHILE */ DebugLog(("ATTR: level = %u, Return: len = %u (end of function body)\n", level, off - offset)); return (off - offset); } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: epan/dissectors/packet-wbxml.c in the WBXML dissector in Wireshark 1.12.x before 1.12.12 mishandles offsets, which allows remote attackers to cause a denial of service (integer overflow and infinite loop) via a crafted packet. Commit Message: WBXML: add a basic sanity check for offset overflow This is a naive approach allowing to detact that something went wrong, without the need to replace all proto_tree_add_text() calls as what was done in master-2.0 branch. Bug: 12408 Change-Id: Ia14905005e17ae322c2fc639ad5e491fa08b0108 Reviewed-on: https://code.wireshark.org/review/15310 Reviewed-by: Michael Mann <[email protected]> Reviewed-by: Pascal Quantin <[email protected]>
Medium
167,139
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static int read_public_key(RSA *rsa) { int r; sc_path_t path; sc_file_t *file; u8 buf[2048], *p = buf; size_t bufsize, keysize; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } bufsize = file->size; sc_file_free(file); r = sc_read_binary(card, 0, buf, bufsize, 0); if (r < 0) { fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r)); return 2; } bufsize = r; do { if (bufsize < 4) return 3; keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; if (keysize < 3) return 3; if (p[2] == opt_key_num) break; p += keysize; bufsize -= keysize; } while (1); if (keysize == 0) { printf("Key number %d not found.\n", opt_key_num); return 2; } return parse_public_key(p, keysize, rsa); } Vulnerability Type: DoS CWE ID: CWE-415 Summary: A double free when handling responses from an HSM Card in sc_pkcs15emu_sc_hsm_init in libopensc/pkcs15-sc-hsm.c in OpenSC before 0.19.0-rc1 could be used by attackers able to supply crafted smartcards to cause a denial of service (application crash) or possibly have unspecified other impact. Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems.
Medium
169,081
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: int ipmi_si_mem_setup(struct si_sm_io *io) { unsigned long addr = io->addr_data; int mapsize, idx; if (!addr) return -ENODEV; io->io_cleanup = mem_cleanup; /* * Figure out the actual readb/readw/readl/etc routine to use based * upon the register size. */ switch (io->regsize) { case 1: io->inputb = intf_mem_inb; io->outputb = intf_mem_outb; break; case 2: io->inputb = intf_mem_inw; io->outputb = intf_mem_outw; break; case 4: io->inputb = intf_mem_inl; io->outputb = intf_mem_outl; break; #ifdef readq case 8: io->inputb = mem_inq; io->outputb = mem_outq; break; #endif default: dev_warn(io->dev, "Invalid register size: %d\n", io->regsize); return -EINVAL; } /* * Some BIOSes reserve disjoint memory regions in their ACPI * tables. This causes problems when trying to request the * entire region. Therefore we must request each register * separately. */ for (idx = 0; idx < io->io_size; idx++) { if (request_mem_region(addr + idx * io->regspacing, io->regsize, DEVICE_NAME) == NULL) { /* Undo allocations */ mem_region_cleanup(io, idx); return -EIO; } } /* * Calculate the total amount of memory to claim. This is an * unusual looking calculation, but it avoids claiming any * more memory than it has to. It will claim everything * between the first address to the end of the last full * register. */ mapsize = ((io->io_size * io->regspacing) - (io->regspacing - io->regsize)); io->addr = ioremap(addr, mapsize); if (io->addr == NULL) { mem_region_cleanup(io, io->io_size); return -EIO; } return 0; } Vulnerability Type: CWE ID: CWE-416 Summary: An issue was discovered in the Linux kernel before 5.0.4. There is a use-after-free upon attempted read access to /proc/ioports after the ipmi_si module is removed, related to drivers/char/ipmi/ipmi_si_intf.c, drivers/char/ipmi/ipmi_si_mem_io.c, and drivers/char/ipmi/ipmi_si_port_io.c. Commit Message: ipmi_si: fix use-after-free of resource->name When we excute the following commands, we got oops rmmod ipmi_si cat /proc/ioports [ 1623.482380] Unable to handle kernel paging request at virtual address ffff00000901d478 [ 1623.482382] Mem abort info: [ 1623.482383] ESR = 0x96000007 [ 1623.482385] Exception class = DABT (current EL), IL = 32 bits [ 1623.482386] SET = 0, FnV = 0 [ 1623.482387] EA = 0, S1PTW = 0 [ 1623.482388] Data abort info: [ 1623.482389] ISV = 0, ISS = 0x00000007 [ 1623.482390] CM = 0, WnR = 0 [ 1623.482393] swapper pgtable: 4k pages, 48-bit VAs, pgdp = 00000000d7d94a66 [ 1623.482395] [ffff00000901d478] pgd=000000dffbfff003, pud=000000dffbffe003, pmd=0000003f5d06e003, pte=0000000000000000 [ 1623.482399] Internal error: Oops: 96000007 [#1] SMP [ 1623.487407] Modules linked in: ipmi_si(E) nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm dm_mirror dm_region_hash dm_log iw_cm dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ses ghash_ce sha2_ce enclosure sha256_arm64 sg sha1_ce hisi_sas_v2_hw hibmc_drm sbsa_gwdt hisi_sas_main ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe mdio hns_dsaf ipmi_devintf hns_enet_drv ipmi_msghandler hns_mdio [last unloaded: ipmi_si] [ 1623.532410] CPU: 30 PID: 11438 Comm: cat Kdump: loaded Tainted: G E 5.0.0-rc3+ #168 [ 1623.541498] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017 [ 1623.548822] pstate: a0000005 (NzCv daif -PAN -UAO) [ 1623.553684] pc : string+0x28/0x98 [ 1623.557040] lr : vsnprintf+0x368/0x5e8 [ 1623.560837] sp : ffff000013213a80 [ 1623.564191] x29: ffff000013213a80 x28: ffff00001138abb5 [ 1623.569577] x27: ffff000013213c18 x26: ffff805f67d06049 [ 1623.574963] x25: 0000000000000000 x24: ffff00001138abb5 [ 1623.580349] x23: 0000000000000fb7 x22: ffff0000117ed000 [ 1623.585734] x21: ffff000011188fd8 x20: ffff805f67d07000 [ 1623.591119] x19: ffff805f67d06061 x18: ffffffffffffffff [ 1623.596505] x17: 0000000000000200 x16: 0000000000000000 [ 1623.601890] x15: ffff0000117ed748 x14: ffff805f67d07000 [ 1623.607276] x13: ffff805f67d0605e x12: 0000000000000000 [ 1623.612661] x11: 0000000000000000 x10: 0000000000000000 [ 1623.618046] x9 : 0000000000000000 x8 : 000000000000000f [ 1623.623432] x7 : ffff805f67d06061 x6 : fffffffffffffffe [ 1623.628817] x5 : 0000000000000012 x4 : ffff00000901d478 [ 1623.634203] x3 : ffff0a00ffffff04 x2 : ffff805f67d07000 [ 1623.639588] x1 : ffff805f67d07000 x0 : ffffffffffffffff [ 1623.644974] Process cat (pid: 11438, stack limit = 0x000000008d4cbc10) [ 1623.651592] Call trace: [ 1623.654068] string+0x28/0x98 [ 1623.657071] vsnprintf+0x368/0x5e8 [ 1623.660517] seq_vprintf+0x70/0x98 [ 1623.668009] seq_printf+0x7c/0xa0 [ 1623.675530] r_show+0xc8/0xf8 [ 1623.682558] seq_read+0x330/0x440 [ 1623.689877] proc_reg_read+0x78/0xd0 [ 1623.697346] __vfs_read+0x60/0x1a0 [ 1623.704564] vfs_read+0x94/0x150 [ 1623.711339] ksys_read+0x6c/0xd8 [ 1623.717939] __arm64_sys_read+0x24/0x30 [ 1623.725077] el0_svc_common+0x120/0x148 [ 1623.732035] el0_svc_handler+0x30/0x40 [ 1623.738757] el0_svc+0x8/0xc [ 1623.744520] Code: d1000406 aa0103e2 54000149 b4000080 (39400085) [ 1623.753441] ---[ end trace f91b6a4937de9835 ]--- [ 1623.760871] Kernel panic - not syncing: Fatal exception [ 1623.768935] SMP: stopping secondary CPUs [ 1623.775718] Kernel Offset: disabled [ 1623.781998] CPU features: 0x002,21006008 [ 1623.788777] Memory Limit: none [ 1623.798329] Starting crashdump kernel... [ 1623.805202] Bye! If io_setup is called successful in try_smi_init() but try_smi_init() goes out_err before calling ipmi_register_smi(), so ipmi_unregister_smi() will not be called while removing module. It leads to the resource that allocated in io_setup() can not be freed, but the name(DEVICE_NAME) of resource is freed while removing the module. It causes use-after-free when cat /proc/ioports. Fix this by calling io_cleanup() while try_smi_init() goes to out_err. and don't call io_cleanup() until io_setup() returns successful to avoid warning prints. Fixes: 93c303d2045b ("ipmi_si: Clean up shutdown a bit") Cc: [email protected] Reported-by: NuoHan Qiao <[email protected]> Suggested-by: Corey Minyard <[email protected]> Signed-off-by: Yang Yingliang <[email protected]> Signed-off-by: Corey Minyard <[email protected]>
High
169,681
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: image_transform_png_set_palette_to_rgb_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return colour_type == PNG_COLOR_TYPE_PALETTE; } 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
173,638
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: gray_render_span( int y, int count, const FT_Span* spans, PWorker worker ) { unsigned char* p; FT_Bitmap* map = &worker->target; /* first of all, compute the scanline offset */ p = (unsigned char*)map->buffer - y * map->pitch; if ( map->pitch >= 0 ) p += ( map->rows - 1 ) * map->pitch; for ( ; count > 0; count--, spans++ ) { unsigned char coverage = spans->coverage; if ( coverage ) { /* For small-spans it is faster to do it by ourselves than * calling `memset'. This is mainly due to the cost of the * function call. */ if ( spans->len >= 8 ) FT_MEM_SET( p + spans->x, (unsigned char)coverage, spans->len ); else { unsigned char* q = p + spans->x; switch ( spans->len ) { case 7: *q++ = (unsigned char)coverage; case 6: *q++ = (unsigned char)coverage; case 5: *q++ = (unsigned char)coverage; case 4: *q++ = (unsigned char)coverage; case 3: *q++ = (unsigned char)coverage; case 2: *q++ = (unsigned char)coverage; case 1: *q = (unsigned char)coverage; default: ; } } } } } Vulnerability Type: DoS Exec Code Overflow CWE ID: CWE-189 Summary: Integer overflow in the gray_render_span function in smooth/ftgrays.c in FreeType before 2.4.0 allows remote attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a crafted font file. Commit Message:
Medium
165,004
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void StopCastCallback( CastConfigDelegate* cast_config, const CastConfigDelegate::ReceiversAndActivites& receivers_activities) { for (auto& item : receivers_activities) { CastConfigDelegate::Activity activity = item.second.activity; if (activity.allow_stop && activity.id.empty() == false) cast_config->StopCasting(activity.id); } } Vulnerability Type: XSS CWE ID: CWE-79 Summary: Cross-site scripting (XSS) vulnerability in the DocumentLoader::maybeCreateArchive function in core/loader/DocumentLoader.cpp in Blink, as used in Google Chrome before 35.0.1916.114, allows remote attackers to inject arbitrary web script or HTML via crafted MHTML content, aka *Universal XSS (UXSS).* Commit Message: Allow the cast tray to function as expected when the installed extension is missing API methods. BUG=489445 Review URL: https://codereview.chromium.org/1145833003 Cr-Commit-Position: refs/heads/master@{#330663}
Medium
171,626
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void SSLManager::OnSSLCertificateError( base::WeakPtr<SSLErrorHandler::Delegate> delegate, const content::GlobalRequestID& id, const ResourceType::Type resource_type, const GURL& url, int render_process_id, int render_view_id, const net::SSLInfo& ssl_info, bool fatal) { DCHECK(delegate); DVLOG(1) << "OnSSLCertificateError() cert_error: " << net::MapCertStatusToNetError(ssl_info.cert_status) << " id: " << id.child_id << "," << id.request_id << " resource_type: " << resource_type << " url: " << url.spec() << " render_process_id: " << render_process_id << " render_view_id: " << render_view_id << " cert_status: " << std::hex << ssl_info.cert_status; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&SSLCertErrorHandler::Dispatch, new SSLCertErrorHandler(delegate, id, resource_type, url, render_process_id, render_view_id, ssl_info, fatal))); } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: The WebSockets implementation in Google Chrome before 19.0.1084.52 does not properly handle use of SSL, which allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via unspecified vectors. Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T> This change refines r137676. BUG=122654 TEST=browser_test Review URL: https://chromiumcodereview.appspot.com/10332233 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98
High
170,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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static PassRefPtr<StaticBitmapImage> cropImage( Image* image, const ParsedOptions& parsedOptions, AlphaDisposition imageFormat = PremultiplyAlpha, ImageDecoder::ColorSpaceOption colorSpaceOp = ImageDecoder::ColorSpaceApplied) { ASSERT(image); IntRect imgRect(IntPoint(), IntSize(image->width(), image->height())); const IntRect srcRect = intersection(imgRect, parsedOptions.cropRect); if (srcRect.isEmpty() && !parsedOptions.premultiplyAlpha) { SkImageInfo info = SkImageInfo::Make(parsedOptions.resizeWidth, parsedOptions.resizeHeight, kN32_SkColorType, kUnpremul_SkAlphaType); RefPtr<ArrayBuffer> dstBuffer = ArrayBuffer::createOrNull( static_cast<size_t>(info.width()) * info.height(), info.bytesPerPixel()); if (!dstBuffer) return nullptr; RefPtr<Uint8Array> dstPixels = Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength()); return StaticBitmapImage::create(newSkImageFromRaster( info, std::move(dstPixels), static_cast<size_t>(info.width()) * info.bytesPerPixel())); } sk_sp<SkImage> skiaImage = image->imageForCurrentFrame(); if ((((!parsedOptions.premultiplyAlpha && !skiaImage->isOpaque()) || !skiaImage) && image->data() && imageFormat == PremultiplyAlpha) || colorSpaceOp == ImageDecoder::ColorSpaceIgnored) { std::unique_ptr<ImageDecoder> decoder(ImageDecoder::create( image->data(), true, parsedOptions.premultiplyAlpha ? ImageDecoder::AlphaPremultiplied : ImageDecoder::AlphaNotPremultiplied, colorSpaceOp)); if (!decoder) return nullptr; skiaImage = ImageBitmap::getSkImageFromDecoder(std::move(decoder)); if (!skiaImage) return nullptr; } if (parsedOptions.cropRect == srcRect && !parsedOptions.shouldScaleInput) { sk_sp<SkImage> croppedSkImage = skiaImage->makeSubset(srcRect); if (parsedOptions.flipY) return StaticBitmapImage::create(flipSkImageVertically( croppedSkImage.get(), parsedOptions.premultiplyAlpha ? PremultiplyAlpha : DontPremultiplyAlpha)); if (parsedOptions.premultiplyAlpha && imageFormat == DontPremultiplyAlpha) return StaticBitmapImage::create( unPremulSkImageToPremul(croppedSkImage.get())); croppedSkImage->preroll(); return StaticBitmapImage::create(std::move(croppedSkImage)); } sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul( parsedOptions.resizeWidth, parsedOptions.resizeHeight); if (!surface) return nullptr; if (srcRect.isEmpty()) return StaticBitmapImage::create(surface->makeImageSnapshot()); SkScalar dstLeft = std::min(0, -parsedOptions.cropRect.x()); SkScalar dstTop = std::min(0, -parsedOptions.cropRect.y()); if (parsedOptions.cropRect.x() < 0) dstLeft = -parsedOptions.cropRect.x(); if (parsedOptions.cropRect.y() < 0) dstTop = -parsedOptions.cropRect.y(); if (parsedOptions.flipY) { surface->getCanvas()->translate(0, surface->height()); surface->getCanvas()->scale(1, -1); } if (parsedOptions.shouldScaleInput) { SkRect drawSrcRect = SkRect::MakeXYWH( parsedOptions.cropRect.x(), parsedOptions.cropRect.y(), parsedOptions.cropRect.width(), parsedOptions.cropRect.height()); SkRect drawDstRect = SkRect::MakeXYWH(0, 0, parsedOptions.resizeWidth, parsedOptions.resizeHeight); SkPaint paint; paint.setFilterQuality(parsedOptions.resizeQuality); surface->getCanvas()->drawImageRect(skiaImage, drawSrcRect, drawDstRect, &paint); } else { surface->getCanvas()->drawImage(skiaImage, dstLeft, dstTop); } skiaImage = surface->makeImageSnapshot(); if (parsedOptions.premultiplyAlpha) { if (imageFormat == DontPremultiplyAlpha) return StaticBitmapImage::create( unPremulSkImageToPremul(skiaImage.get())); return StaticBitmapImage::create(std::move(skiaImage)); } return StaticBitmapImage::create(premulSkImageToUnPremul(skiaImage.get())); } Vulnerability Type: CWE ID: CWE-787 Summary: Bad casting in bitmap manipulation in Blink 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: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull Currently when ImageBitmap's constructor is invoked, we check whether dstSize will overflow size_t or not. The problem comes when we call ArrayBuffer::createOrNull some times in the code. Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap when we call this method, the first parameter is usually width * height. This could overflow unsigned even if it has been checked safe with size_t, the reason is that unsigned is a 32-bit value on 64-bit systems, while size_t is a 64-bit value. This CL makes a change such that we check whether the dstSize will overflow unsigned or not. In this case, we can guarantee that createOrNull will not have any crash. BUG=664139 Review-Url: https://codereview.chromium.org/2500493002 Cr-Commit-Position: refs/heads/master@{#431936}
Medium
172,500
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: xsltInitCtxtKey(xsltTransformContextPtr ctxt, xsltDocumentPtr idoc, xsltKeyDefPtr keyDef) { int i, len, k; xmlNodeSetPtr matchList = NULL, keylist; xmlXPathObjectPtr matchRes = NULL, useRes = NULL; xmlChar *str = NULL; xsltKeyTablePtr table; xmlNodePtr oldInst, cur; xmlNodePtr oldContextNode; xsltDocumentPtr oldDocInfo; int oldXPPos, oldXPSize; xmlDocPtr oldXPDoc; int oldXPNsNr; xmlNsPtr *oldXPNamespaces; xmlXPathContextPtr xpctxt; #ifdef KEY_INIT_DEBUG fprintf(stderr, "xsltInitCtxtKey %s : %d\n", keyDef->name, ctxt->keyInitLevel); #endif if ((keyDef->comp == NULL) || (keyDef->usecomp == NULL)) return(-1); /* * Detect recursive keys */ if (ctxt->keyInitLevel > ctxt->nbKeys) { #ifdef WITH_XSLT_DEBUG_KEYS XSLT_TRACE(ctxt,XSLT_TRACE_KEYS, xsltGenericDebug(xsltGenericDebugContext, "xsltInitCtxtKey: key definition of %s is recursive\n", keyDef->name)); #endif xsltTransformError(ctxt, NULL, keyDef->inst, "Key definition for %s is recursive\n", keyDef->name); ctxt->state = XSLT_STATE_STOPPED; return(-1); } ctxt->keyInitLevel++; xpctxt = ctxt->xpathCtxt; idoc->nbKeysComputed++; /* * Save context state. */ oldInst = ctxt->inst; oldDocInfo = ctxt->document; oldContextNode = ctxt->node; oldXPDoc = xpctxt->doc; oldXPPos = xpctxt->proximityPosition; oldXPSize = xpctxt->contextSize; oldXPNsNr = xpctxt->nsNr; oldXPNamespaces = xpctxt->namespaces; /* * Set up contexts. */ ctxt->document = idoc; ctxt->node = (xmlNodePtr) idoc->doc; ctxt->inst = keyDef->inst; xpctxt->doc = idoc->doc; xpctxt->node = (xmlNodePtr) idoc->doc; /* TODO : clarify the use of namespaces in keys evaluation */ xpctxt->namespaces = keyDef->nsList; xpctxt->nsNr = keyDef->nsNr; /* * Evaluate the 'match' expression of the xsl:key. * TODO: The 'match' is a *pattern*. */ matchRes = xmlXPathCompiledEval(keyDef->comp, xpctxt); if (matchRes == NULL) { #ifdef WITH_XSLT_DEBUG_KEYS XSLT_TRACE(ctxt,XSLT_TRACE_KEYS,xsltGenericDebug(xsltGenericDebugContext, "xsltInitCtxtKey: %s evaluation failed\n", keyDef->match)); #endif xsltTransformError(ctxt, NULL, keyDef->inst, "Failed to evaluate the 'match' expression.\n"); ctxt->state = XSLT_STATE_STOPPED; goto error; } else { if (matchRes->type == XPATH_NODESET) { matchList = matchRes->nodesetval; #ifdef WITH_XSLT_DEBUG_KEYS if (matchList != NULL) XSLT_TRACE(ctxt,XSLT_TRACE_KEYS,xsltGenericDebug(xsltGenericDebugContext, "xsltInitCtxtKey: %s evaluates to %d nodes\n", keyDef->match, matchList->nodeNr)); #endif } else { /* * Is not a node set, but must be. */ #ifdef WITH_XSLT_DEBUG_KEYS XSLT_TRACE(ctxt,XSLT_TRACE_KEYS,xsltGenericDebug(xsltGenericDebugContext, "xsltInitCtxtKey: %s is not a node set\n", keyDef->match)); #endif xsltTransformError(ctxt, NULL, keyDef->inst, "The 'match' expression did not evaluate to a node set.\n"); ctxt->state = XSLT_STATE_STOPPED; goto error; } } if ((matchList == NULL) || (matchList->nodeNr <= 0)) goto exit; /** * Multiple key definitions for the same name are allowed, so * we must check if the key is already present for this doc */ table = (xsltKeyTablePtr) idoc->keys; while (table != NULL) { if (xmlStrEqual(table->name, keyDef->name) && (((keyDef->nameURI == NULL) && (table->nameURI == NULL)) || ((keyDef->nameURI != NULL) && (table->nameURI != NULL) && (xmlStrEqual(table->nameURI, keyDef->nameURI))))) break; table = table->next; } /** * If the key was not previously defined, create it now and * chain it to the list of keys for the doc */ if (table == NULL) { table = xsltNewKeyTable(keyDef->name, keyDef->nameURI); if (table == NULL) goto error; table->next = idoc->keys; idoc->keys = table; } /* * SPEC XSLT 1.0 (XSLT 2.0 does not clarify the context size!) * "...the use attribute of the xsl:key element is evaluated with x as " the current node and with a node list containing just x as the * current node list" */ xpctxt->contextSize = 1; xpctxt->proximityPosition = 1; for (i = 0; i < matchList->nodeNr; i++) { cur = matchList->nodeTab[i]; if (! IS_XSLT_REAL_NODE(cur)) continue; xpctxt->node = cur; /* * Process the 'use' of the xsl:key. * SPEC XSLT 1.0: * "The use attribute is an expression specifying the values of * the key; the expression is evaluated once for each node that * matches the pattern." */ if (useRes != NULL) xmlXPathFreeObject(useRes); useRes = xmlXPathCompiledEval(keyDef->usecomp, xpctxt); if (useRes == NULL) { xsltTransformError(ctxt, NULL, keyDef->inst, "Failed to evaluate the 'use' expression.\n"); ctxt->state = XSLT_STATE_STOPPED; break; } if (useRes->type == XPATH_NODESET) { if ((useRes->nodesetval != NULL) && (useRes->nodesetval->nodeNr != 0)) { len = useRes->nodesetval->nodeNr; str = xmlXPathCastNodeToString(useRes->nodesetval->nodeTab[0]); } else { continue; } } else { len = 1; if (useRes->type == XPATH_STRING) { /* * Consume the string value. */ str = useRes->stringval; useRes->stringval = NULL; } else { str = xmlXPathCastToString(useRes); } } /* * Process all strings. */ k = 0; while (1) { if (str == NULL) goto next_string; #ifdef WITH_XSLT_DEBUG_KEYS XSLT_TRACE(ctxt,XSLT_TRACE_KEYS,xsltGenericDebug(xsltGenericDebugContext, "xsl:key : node associated to ('%s', '%s')\n", keyDef->name, str)); #endif keylist = xmlHashLookup(table->keys, str); if (keylist == NULL) { keylist = xmlXPathNodeSetCreate(cur); if (keylist == NULL) goto error; xmlHashAddEntry(table->keys, str, keylist); } else { /* * TODO: How do we know if this function failed? */ xmlXPathNodeSetAdd(keylist, cur); } switch (cur->type) { case XML_ELEMENT_NODE: case XML_TEXT_NODE: case XML_CDATA_SECTION_NODE: case XML_PI_NODE: case XML_COMMENT_NODE: cur->psvi = keyDef; break; case XML_ATTRIBUTE_NODE: ((xmlAttrPtr) cur)->psvi = keyDef; break; case XML_DOCUMENT_NODE: case XML_HTML_DOCUMENT_NODE: ((xmlDocPtr) cur)->psvi = keyDef; break; default: break; } xmlFree(str); str = NULL; next_string: k++; if (k >= len) break; str = xmlXPathCastNodeToString(useRes->nodesetval->nodeTab[k]); } } exit: error: ctxt->keyInitLevel--; /* * Restore context state. */ xpctxt->doc = oldXPDoc; xpctxt->nsNr = oldXPNsNr; xpctxt->namespaces = oldXPNamespaces; xpctxt->proximityPosition = oldXPPos; xpctxt->contextSize = oldXPSize; ctxt->node = oldContextNode; ctxt->document = oldDocInfo; ctxt->inst = oldInst; if (str) xmlFree(str); if (useRes != NULL) xmlXPathFreeObject(useRes); if (matchRes != NULL) xmlXPathFreeObject(matchRes); return(0); } 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
173,304
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void ExtensionTtsPlatformImpl::set_error(const std::string& error) { error_ = error; } Vulnerability Type: DoS CWE ID: CWE-20 Summary: The PDF implementation in Google Chrome before 13.0.782.215 on Linux does not properly use the memset library function, which allows remote attackers to cause a denial of service or possibly have unspecified other impact via unknown vectors. Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
High
170,395
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h, const void *p, size_t tail, int line) { const char *b = (const char *)sst->sst_tab; const char *e = ((const char *)p) + tail; (void)&line; if (e >= b && (size_t)(e - b) <= CDF_SEC_SIZE(h) * sst->sst_len) return 0; DPRINTF(("%d: offset begin %p < end %p || %" SIZE_T_FORMAT "u" " > %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b), CDF_SEC_SIZE(h) * sst->sst_len, CDF_SEC_SIZE(h), sst->sst_len)); errno = EFTYPE; return -1; } Vulnerability Type: DoS CWE ID: CWE-189 Summary: The cdf_check_stream_offset function in cdf.c in file before 5.19, as used in the Fileinfo component in PHP before 5.4.30 and 5.5.x before 5.5.14, relies on incorrect sector-size data, which allows remote attackers to cause a denial of service (application crash) via a crafted stream offset in a CDF file. Commit Message: Use the proper sector size when checking stream offsets (Francisco Alonso and Jan Kaluza at RedHat)
Medium
166,366
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void CCLayerTreeHostTest::doBeginTest() { ASSERT(isMainThread()); ASSERT(!m_running); m_running = true; m_client = MockLayerTreeHostClient::create(this); RefPtr<LayerChromium> rootLayer = LayerChromium::create(0); m_layerTreeHost = MockLayerTreeHost::create(this, m_client.get(), rootLayer, m_settings); ASSERT(m_layerTreeHost); m_beginning = true; beginTest(); m_beginning = false; if (m_endWhenBeginReturns) onEndTest(static_cast<void*>(this)); } Vulnerability Type: DoS Overflow Mem. Corr. CWE ID: CWE-119 Summary: Google Chrome before 14.0.835.202 does not properly handle Google V8 hidden objects, which allows remote attackers to cause a denial of service (memory corruption) or possibly have unspecified other impact via crafted JavaScript code. Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests https://bugs.webkit.org/show_bug.cgi?id=70161 Reviewed by David Levin. Source/WebCore: Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was destroyed. This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the CCThreadProxy have been drained. Covered by the now-enabled CCLayerTreeHostTest* unit tests. * WebCore.gypi: * platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added. (WebCore::CCScopedMainThreadProxy::create): (WebCore::CCScopedMainThreadProxy::postTask): (WebCore::CCScopedMainThreadProxy::shutdown): (WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy): (WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown): * platform/graphics/chromium/cc/CCThreadProxy.cpp: (WebCore::CCThreadProxy::CCThreadProxy): (WebCore::CCThreadProxy::~CCThreadProxy): (WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread): * platform/graphics/chromium/cc/CCThreadProxy.h: Source/WebKit/chromium: Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor thread scheduling draws by itself. * tests/CCLayerTreeHostTest.cpp: (::CCLayerTreeHostTest::timeout): (::CCLayerTreeHostTest::clearTimeout): (::CCLayerTreeHostTest::CCLayerTreeHostTest): (::CCLayerTreeHostTest::onEndTest): (::CCLayerTreeHostTest::TimeoutTask::TimeoutTask): (::CCLayerTreeHostTest::TimeoutTask::clearTest): (::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask): (::CCLayerTreeHostTest::TimeoutTask::Run): (::CCLayerTreeHostTest::runTest): (::CCLayerTreeHostTest::doBeginTest): (::CCLayerTreeHostTestThreadOnly::runTest): (::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread): git-svn-id: svn://svn.chromium.org/blink/trunk@97784 bbb929c8-8fbe-4397-9dbb-9b2b20218538
Medium
170,292
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void ReportPreconnectAccuracy( const PreconnectStats& stats, const std::map<GURL, OriginRequestSummary>& requests) { if (stats.requests_stats.empty()) return; int preresolve_hits_count = 0; int preresolve_misses_count = 0; int preconnect_hits_count = 0; int preconnect_misses_count = 0; for (const auto& request_stats : stats.requests_stats) { bool hit = requests.find(request_stats.origin) != requests.end(); bool preconnect = request_stats.was_preconnected; preresolve_hits_count += hit; preresolve_misses_count += !hit; preconnect_hits_count += preconnect && hit; preconnect_misses_count += preconnect && !hit; } int total_preresolves = preresolve_hits_count + preresolve_misses_count; int total_preconnects = preconnect_hits_count + preconnect_misses_count; DCHECK_EQ(static_cast<int>(stats.requests_stats.size()), preresolve_hits_count + preresolve_misses_count); DCHECK_GT(total_preresolves, 0); size_t preresolve_hits_percentage = (100 * preresolve_hits_count) / total_preresolves; if (total_preconnects > 0) { size_t preconnect_hits_percentage = (100 * preconnect_hits_count) / total_preconnects; UMA_HISTOGRAM_PERCENTAGE( internal::kLoadingPredictorPreconnectHitsPercentage, preconnect_hits_percentage); } UMA_HISTOGRAM_PERCENTAGE(internal::kLoadingPredictorPreresolveHitsPercentage, preresolve_hits_percentage); UMA_HISTOGRAM_COUNTS_100(internal::kLoadingPredictorPreresolveCount, total_preresolves); UMA_HISTOGRAM_COUNTS_100(internal::kLoadingPredictorPreconnectCount, total_preconnects); } Vulnerability Type: CWE ID: CWE-125 Summary: Insufficient validation of untrusted input in Skia in Google Chrome prior to 59.0.3071.86 for Linux, Windows, and Mac, and 59.0.3071.92 for Android, allowed a remote attacker to perform an out of bounds memory read via a crafted HTML page. Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <[email protected]> Reviewed-by: Alex Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#716311}
Medium
172,372
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: SPL_METHOD(SplTempFileObject, __construct) { long max_memory = PHP_STREAM_MAX_MEM; char tmp_fname[48]; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &max_memory) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (max_memory < 0) { intern->file_name = "php://memory"; intern->file_name_len = 12; } else if (ZEND_NUM_ARGS()) { intern->file_name_len = slprintf(tmp_fname, sizeof(tmp_fname), "php://temp/maxmemory:%ld", max_memory); intern->file_name = tmp_fname; } else { intern->file_name = "php://temp"; intern->file_name_len = 10; } intern->u.file.open_mode = "wb"; intern->u.file.open_mode_len = 1; intern->u.file.zcontext = NULL; if (spl_filesystem_file_open(intern, 0, 0 TSRMLS_CC) == SUCCESS) { intern->_path_len = 0; intern->_path = estrndup("", 0); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileObject::rewind() Vulnerability Type: DoS Overflow CWE ID: CWE-190 Summary: Integer overflow in the SplFileObject::fread function in spl_directory.c in the SPL extension in PHP before 5.5.37 and 5.6.x before 5.6.23 allows remote attackers to cause a denial of service or possibly have unspecified other impact via a large integer argument, a related issue to CVE-2016-5096. Commit Message: Fix bug #72262 - do not overflow int
High
167,050
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: int mif_validate(jas_stream_t *in) { uchar buf[MIF_MAGICLEN]; uint_fast32_t magic; int i; int n; assert(JAS_STREAM_MAXPUTBACK >= MIF_MAGICLEN); /* Read the validation data (i.e., the data used for detecting the format). */ if ((n = jas_stream_read(in, buf, MIF_MAGICLEN)) < 0) { return -1; } /* Put the validation data back onto the stream, so that the stream position will not be changed. */ for (i = n - 1; i >= 0; --i) { if (jas_stream_ungetc(in, buf[i]) == EOF) { return -1; } } /* Was enough data read? */ if (n < MIF_MAGICLEN) { return -1; } /* Compute the signature value. */ magic = (JAS_CAST(uint_fast32_t, buf[0]) << 24) | (JAS_CAST(uint_fast32_t, buf[1]) << 16) | (JAS_CAST(uint_fast32_t, buf[2]) << 8) | buf[3]; /* Ensure that the signature is correct for this format. */ if (magic != MIF_MAGIC) { return -1; } return 0; } 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
168,725
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static int __net_init sctp_net_init(struct net *net) { int status; /* * 14. Suggested SCTP Protocol Parameter Values */ /* The following protocol parameters are RECOMMENDED: */ /* RTO.Initial - 3 seconds */ net->sctp.rto_initial = SCTP_RTO_INITIAL; /* RTO.Min - 1 second */ net->sctp.rto_min = SCTP_RTO_MIN; /* RTO.Max - 60 seconds */ net->sctp.rto_max = SCTP_RTO_MAX; /* RTO.Alpha - 1/8 */ net->sctp.rto_alpha = SCTP_RTO_ALPHA; /* RTO.Beta - 1/4 */ net->sctp.rto_beta = SCTP_RTO_BETA; /* Valid.Cookie.Life - 60 seconds */ net->sctp.valid_cookie_life = SCTP_DEFAULT_COOKIE_LIFE; /* Whether Cookie Preservative is enabled(1) or not(0) */ net->sctp.cookie_preserve_enable = 1; /* Default sctp sockets to use md5 as their hmac alg */ #if defined (CONFIG_SCTP_DEFAULT_COOKIE_HMAC_MD5) net->sctp.sctp_hmac_alg = "md5"; #elif defined (CONFIG_SCTP_DEFAULT_COOKIE_HMAC_SHA1) net->sctp.sctp_hmac_alg = "sha1"; #else net->sctp.sctp_hmac_alg = NULL; #endif /* Max.Burst - 4 */ net->sctp.max_burst = SCTP_DEFAULT_MAX_BURST; /* Association.Max.Retrans - 10 attempts * Path.Max.Retrans - 5 attempts (per destination address) * Max.Init.Retransmits - 8 attempts */ net->sctp.max_retrans_association = 10; net->sctp.max_retrans_path = 5; net->sctp.max_retrans_init = 8; /* Sendbuffer growth - do per-socket accounting */ net->sctp.sndbuf_policy = 0; /* Rcvbuffer growth - do per-socket accounting */ net->sctp.rcvbuf_policy = 0; /* HB.interval - 30 seconds */ net->sctp.hb_interval = SCTP_DEFAULT_TIMEOUT_HEARTBEAT; /* delayed SACK timeout */ net->sctp.sack_timeout = SCTP_DEFAULT_TIMEOUT_SACK; /* Disable ADDIP by default. */ net->sctp.addip_enable = 0; net->sctp.addip_noauth = 0; net->sctp.default_auto_asconf = 0; /* Enable PR-SCTP by default. */ net->sctp.prsctp_enable = 1; /* Disable AUTH by default. */ net->sctp.auth_enable = 0; /* Set SCOPE policy to enabled */ net->sctp.scope_policy = SCTP_SCOPE_POLICY_ENABLE; /* Set the default rwnd update threshold */ net->sctp.rwnd_upd_shift = SCTP_DEFAULT_RWND_SHIFT; /* Initialize maximum autoclose timeout. */ net->sctp.max_autoclose = INT_MAX / HZ; status = sctp_sysctl_net_register(net); if (status) goto err_sysctl_register; /* Allocate and initialise sctp mibs. */ status = init_sctp_mibs(net); if (status) goto err_init_mibs; /* Initialize proc fs directory. */ status = sctp_proc_init(net); if (status) goto err_init_proc; sctp_dbg_objcnt_init(net); /* Initialize the control inode/socket for handling OOTB packets. */ if ((status = sctp_ctl_sock_init(net))) { pr_err("Failed to initialize the SCTP control sock\n"); goto err_ctl_sock_init; } /* Initialize the local address list. */ INIT_LIST_HEAD(&net->sctp.local_addr_list); spin_lock_init(&net->sctp.local_addr_lock); sctp_get_local_addr_list(net); /* Initialize the address event list */ INIT_LIST_HEAD(&net->sctp.addr_waitq); INIT_LIST_HEAD(&net->sctp.auto_asconf_splist); spin_lock_init(&net->sctp.addr_wq_lock); net->sctp.addr_wq_timer.expires = 0; setup_timer(&net->sctp.addr_wq_timer, sctp_addr_wq_timeout_handler, (unsigned long)net); return 0; err_ctl_sock_init: sctp_dbg_objcnt_exit(net); sctp_proc_exit(net); err_init_proc: cleanup_sctp_mibs(net); err_init_mibs: sctp_sysctl_net_unregister(net); err_sysctl_register: return status; } Vulnerability Type: DoS Overflow Mem. Corr. CWE ID: CWE-119 Summary: The sctp_init function in net/sctp/protocol.c in the Linux kernel before 4.2.3 has an incorrect sequence of protocol-initialization steps, which allows local users to cause a denial of service (panic or memory corruption) by creating SCTP sockets before all of the steps have finished. Commit Message: sctp: fix race on protocol/netns initialization Consider sctp module is unloaded and is being requested because an user is creating a sctp socket. During initialization, sctp will add the new protocol type and then initialize pernet subsys: status = sctp_v4_protosw_init(); if (status) goto err_protosw_init; status = sctp_v6_protosw_init(); if (status) goto err_v6_protosw_init; status = register_pernet_subsys(&sctp_net_ops); The problem is that after those calls to sctp_v{4,6}_protosw_init(), it is possible for userspace to create SCTP sockets like if the module is already fully loaded. If that happens, one of the possible effects is that we will have readers for net->sctp.local_addr_list list earlier than expected and sctp_net_init() does not take precautions while dealing with that list, leading to a potential panic but not limited to that, as sctp_sock_init() will copy a bunch of blank/partially initialized values from net->sctp. The race happens like this: CPU 0 | CPU 1 socket() | __sock_create | socket() inet_create | __sock_create list_for_each_entry_rcu( | answer, &inetsw[sock->type], | list) { | inet_create /* no hits */ | if (unlikely(err)) { | ... | request_module() | /* socket creation is blocked | * the module is fully loaded | */ | sctp_init | sctp_v4_protosw_init | inet_register_protosw | list_add_rcu(&p->list, | last_perm); | | list_for_each_entry_rcu( | answer, &inetsw[sock->type], sctp_v6_protosw_init | list) { | /* hit, so assumes protocol | * is already loaded | */ | /* socket creation continues | * before netns is initialized | */ register_pernet_subsys | Simply inverting the initialization order between register_pernet_subsys() and sctp_v4_protosw_init() is not possible because register_pernet_subsys() will create a control sctp socket, so the protocol must be already visible by then. Deferring the socket creation to a work-queue is not good specially because we loose the ability to handle its errors. So, as suggested by Vlad, the fix is to split netns initialization in two moments: defaults and control socket, so that the defaults are already loaded by when we register the protocol, while control socket initialization is kept at the same moment it is today. Fixes: 4db67e808640 ("sctp: Make the address lists per network namespace") Signed-off-by: Vlad Yasevich <[email protected]> Signed-off-by: Marcelo Ricardo Leitner <[email protected]> Signed-off-by: David S. Miller <[email protected]>
Medium
166,608
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: int ssl23_get_client_hello(SSL *s) { char buf_space[11]; /* Request this many bytes in initial read. * We can detect SSL 3.0/TLS 1.0 Client Hellos * ('type == 3') correctly only when the following * is in a single record, which is not guaranteed by * the protocol specification: * Byte Content * 0 type \ * 1/2 version > record header * 3/4 length / * 5 msg_type \ * 6-8 length > Client Hello message * 9/10 client_version / */ char *buf= &(buf_space[0]); unsigned char *p,*d,*d_len,*dd; unsigned int i; unsigned int csl,sil,cl; int n=0,j; int type=0; int v[2]; if (s->state == SSL23_ST_SR_CLNT_HELLO_A) { /* read the initial header */ v[0]=v[1]=0; if (!ssl3_setup_buffers(s)) goto err; n=ssl23_read_bytes(s, sizeof buf_space); if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */ p=s->packet; memcpy(buf,p,n); if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) { /* * SSLv2 header */ if ((p[3] == 0x00) && (p[4] == 0x02)) { v[0]=p[3]; v[1]=p[4]; /* SSLv2 */ if (!(s->options & SSL_OP_NO_SSLv2)) type=1; } else if (p[3] == SSL3_VERSION_MAJOR) { v[0]=p[3]; v[1]=p[4]; /* SSLv3/TLSv1 */ if (p[4] >= TLS1_VERSION_MINOR) { if (p[4] >= TLS1_2_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_2)) { s->version=TLS1_2_VERSION; s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (p[4] >= TLS1_1_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_1)) { s->version=TLS1_1_VERSION; /* type=2; */ /* done later to survive restarts */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_TLSv1)) { s->version=TLS1_VERSION; /* type=2; */ /* done later to survive restarts */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; /* type=2; */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv2)) { type=1; } } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; /* type=2; */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv2)) type=1; } } else if ((p[0] == SSL3_RT_HANDSHAKE) && (p[1] == SSL3_VERSION_MAJOR) && (p[5] == SSL3_MT_CLIENT_HELLO) && ((p[3] == 0 && p[4] < 5 /* silly record length? */) || (p[9] >= p[1]))) { /* * SSLv3 or tls1 header */ v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */ /* We must look at client_version inside the Client Hello message * to get the correct minor version. * However if we have only a pathologically small fragment of the * Client Hello message, this would be difficult, and we'd have * to read more records to find out. * No known SSL 3.0 client fragments ClientHello like this, * so we simply reject such connections to avoid * protocol version downgrade attacks. */ if (p[3] == 0 && p[4] < 6) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL); goto err; } /* if major version number > 3 set minor to a value * which will use the highest version 3 we support. * If TLS 2.0 ever appears we will need to revise * this.... */ if (p[9] > SSL3_VERSION_MAJOR) v[1]=0xff; else v[1]=p[10]; /* minor version according to client_version */ if (v[1] >= TLS1_VERSION_MINOR) { if (v[1] >= TLS1_2_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_2)) { s->version=TLS1_2_VERSION; type=3; } else if (v[1] >= TLS1_1_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_1)) { s->version=TLS1_1_VERSION; type=3; } else if (!(s->options & SSL_OP_NO_TLSv1)) { s->version=TLS1_VERSION; type=3; } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; type=3; } } else { /* client requests SSL 3.0 */ if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; type=3; } else if (!(s->options & SSL_OP_NO_TLSv1)) { /* we won't be able to use TLS of course, * but this will send an appropriate alert */ s->version=TLS1_VERSION; type=3; } } } else if ((strncmp("GET ", (char *)p,4) == 0) || (strncmp("POST ",(char *)p,5) == 0) || (strncmp("HEAD ",(char *)p,5) == 0) || (strncmp("PUT ", (char *)p,4) == 0)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST); goto err; } else if (strncmp("CONNECT",(char *)p,7) == 0) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST); goto err; } } /* ensure that TLS_MAX_VERSION is up-to-date */ OPENSSL_assert(s->version <= TLS_MAX_VERSION); if (s->version < TLS1_2_VERSION && tls1_suiteb(s)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO, SSL_R_ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE); goto err; } #ifdef OPENSSL_FIPS if (FIPS_mode() && (s->version < TLS1_VERSION)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO, SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE); goto err; } #endif if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_VERSION_TOO_LOW); goto err; } if (s->state == SSL23_ST_SR_CLNT_HELLO_B) { /* we have SSLv3/TLSv1 in an SSLv2 header * (other cases skip this state) */ type=2; p=s->packet; v[0] = p[3]; /* == SSL3_VERSION_MAJOR */ v[1] = p[4]; /* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2 * header is sent directly on the wire, not wrapped as a TLS * record. It's format is: * Byte Content * 0-1 msg_length * 2 msg_type * 3-4 version * 5-6 cipher_spec_length * 7-8 session_id_length * 9-10 challenge_length * ... ... */ n=((p[0]&0x7f)<<8)|p[1]; if (n > (1024*4)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE); goto err; } if (n < 9) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH); goto err; } j=ssl23_read_bytes(s,n+2); /* We previously read 11 bytes, so if j > 0, we must have * j == n+2 == s->packet_length. We have at least 11 valid * packet bytes. */ if (j <= 0) return(j); ssl3_finish_mac(s, s->packet+2, s->packet_length-2); if (s->msg_callback) s->msg_callback(0, SSL2_VERSION, 0, s->packet+2, s->packet_length-2, s, s->msg_callback_arg); /* CLIENT-HELLO */ p=s->packet; p+=5; n2s(p,csl); n2s(p,sil); n2s(p,cl); d=(unsigned char *)s->init_buf->data; if ((csl+sil+cl+11) != s->packet_length) /* We can't have TLS extensions in SSL 2.0 format * Client Hello, can we? Error condition should be * '>' otherweise */ { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH); goto err; } /* record header: msg_type ... */ *(d++) = SSL3_MT_CLIENT_HELLO; /* ... and length (actual value will be written later) */ d_len = d; d += 3; /* client_version */ *(d++) = SSL3_VERSION_MAJOR; /* == v[0] */ *(d++) = v[1]; /* lets populate the random area */ /* get the challenge_length */ i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl; memset(d,0,SSL3_RANDOM_SIZE); memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i); d+=SSL3_RANDOM_SIZE; /* no session-id reuse */ *(d++)=0; /* ciphers */ j=0; dd=d; d+=2; for (i=0; i<csl; i+=3) { if (p[i] != 0) continue; *(d++)=p[i+1]; *(d++)=p[i+2]; j+=2; } s2n(j,dd); /* COMPRESSION */ *(d++)=1; *(d++)=0; #if 0 /* copy any remaining data with may be extensions */ p = p+csl+sil+cl; while (p < s->packet+s->packet_length) { *(d++)=*(p++); } #endif i = (d-(unsigned char *)s->init_buf->data) - 4; l2n3((long)i, d_len); /* get the data reused from the init_buf */ s->s3->tmp.reuse_message=1; s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO; s->s3->tmp.message_size=i; } /* imaginary new state (for program structure): */ /* s->state = SSL23_SR_CLNT_HELLO_C */ if (type == 1) { #ifdef OPENSSL_NO_SSL2 SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); goto err; #else /* we are talking sslv2 */ /* we need to clean up the SSLv3/TLSv1 setup and put in the * sslv2 stuff. */ if (s->s2 == NULL) { if (!ssl2_new(s)) goto err; } else ssl2_clear(s); if (s->s3 != NULL) ssl3_free(s); if (!BUF_MEM_grow_clean(s->init_buf, SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)) { goto err; } s->state=SSL2_ST_GET_CLIENT_HELLO_A; if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3) s->s2->ssl2_rollback=0; else /* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0 * (SSL 3.0 draft/RFC 2246, App. E.2) */ s->s2->ssl2_rollback=1; /* setup the n bytes we have read so we get them from * the sslv2 buffer */ s->rstate=SSL_ST_READ_HEADER; s->packet_length=n; s->packet= &(s->s2->rbuf[0]); memcpy(s->packet,buf,n); s->s2->rbuf_left=n; s->s2->rbuf_offs=0; s->method=SSLv2_server_method(); s->handshake_func=s->method->ssl_accept; #endif } if ((type == 2) || (type == 3)) { /* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */ s->method = ssl23_get_server_method(s->version); if (s->method == NULL) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); goto err; } if (!ssl_init_wbio_buffer(s,1)) goto err; if (type == 3) { /* put the 'n' bytes we have read into the input buffer * for SSLv3 */ s->rstate=SSL_ST_READ_HEADER; s->packet_length=n; if (s->s3->rbuf.buf == NULL) if (!ssl3_setup_read_buffer(s)) goto err; s->packet= &(s->s3->rbuf.buf[0]); memcpy(s->packet,buf,n); s->s3->rbuf.left=n; s->s3->rbuf.offset=0; } else { s->packet_length=0; s->s3->rbuf.left=0; s->s3->rbuf.offset=0; } #if 0 /* ssl3_get_client_hello does this */ s->client_version=(v[0]<<8)|v[1]; #endif s->handshake_func=s->method->ssl_accept; } if ((type < 1) || (type > 3)) { /* bad, very bad */ SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNKNOWN_PROTOCOL); goto err; } s->init_num=0; if (buf != buf_space) OPENSSL_free(buf); return(SSL_accept(s)); err: if (buf != buf_space) OPENSSL_free(buf); return(-1); } Vulnerability Type: DoS CWE ID: Summary: The ssl23_get_client_hello function in s23_srvr.c in OpenSSL 0.9.8zc, 1.0.0o, and 1.0.1j does not properly handle attempts to use unsupported protocols, which allows remote attackers to cause a denial of service (NULL pointer dereference and daemon crash) via an unexpected handshake, as demonstrated by an SSLv3 handshake to a no-ssl3 application with certain error handling. NOTE: this issue became relevant after the CVE-2014-3568 fix. Commit Message:
Medium
165,153
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: load(ImlibImage * im, ImlibProgressFunction progress, char progress_granularity, char immediate_load) { int rc; char p = ' ', numbers = 3, count = 0; int w = 0, h = 0, v = 255, c = 0; char buf[256]; FILE *f = NULL; if (im->data) return 0; f = fopen(im->real_file, "rb"); if (!f) return 0; /* can't use fgets(), because there might be * binary data after the header and there * needn't be a newline before the data, so * no chance to distinguish between end of buffer * and a binary 0. */ /* read the header info */ rc = 0; /* Error */ c = fgetc(f); if (c != 'P') goto quit; p = fgetc(f); if (p == '1' || p == '4') numbers = 2; /* bitimages don't have max value */ if ((p < '1') || (p > '8')) goto quit; count = 0; while (count < numbers) { c = fgetc(f); if (c == EOF) goto quit; /* eat whitespace */ while (isspace(c)) c = fgetc(f); /* if comment, eat that */ if (c == '#') { do c = fgetc(f); while (c != '\n' && c != EOF); } /* no comment -> proceed */ else { int i = 0; /* read numbers */ while (c != EOF && !isspace(c) && (i < 255)) { buf[i++] = c; c = fgetc(f); } if (i) { buf[i] = 0; count++; switch (count) { /* width */ case 1: w = atoi(buf); break; /* height */ case 2: h = atoi(buf); break; /* max value, only for color and greyscale */ case 3: v = atoi(buf); break; } } } } if ((v < 0) || (v > 255)) goto quit; im->w = w; im->h = h; if (!IMAGE_DIMENSIONS_OK(w, h)) goto quit; if (!im->format) { if (p == '8') SET_FLAG(im->flags, F_HAS_ALPHA); else UNSET_FLAG(im->flags, F_HAS_ALPHA); im->format = strdup("pnm"); } rc = 1; /* Ok */ if (((!im->data) && (im->loader)) || (immediate_load) || (progress)) { DATA8 *data = NULL; /* for the binary versions */ DATA8 *ptr = NULL; int *idata = NULL; /* for the ASCII versions */ int *iptr; char buf2[256]; DATA32 *ptr2; int i, j, x, y, pl = 0; char pper = 0; /* must set the im->data member before callign progress function */ ptr2 = im->data = malloc(w * h * sizeof(DATA32)); if (!im->data) goto quit_error; /* start reading the data */ switch (p) { case '1': /* ASCII monochrome */ buf[0] = 0; i = 0; for (y = 0; y < h; y++) { x = 0; while (x < w) { if (!buf[i]) /* fill buffer */ { if (!fgets(buf, 255, f)) goto quit_error; i = 0; } while (buf[i] && isspace(buf[i])) i++; if (buf[i]) { if (buf[i] == '1') *ptr2 = 0xff000000; else if (buf[i] == '0') *ptr2 = 0xffffffff; else goto quit_error; ptr2++; i++; } } if (progress && do_progress(im, progress, progress_granularity, &pper, &pl, y)) goto quit_progress; } break; case '2': /* ASCII greyscale */ idata = malloc(sizeof(int) * w); if (!idata) goto quit_error; buf[0] = 0; i = 0; j = 0; for (y = 0; y < h; y++) { iptr = idata; x = 0; while (x < w) { int k; /* check 4 chars ahead to see if we need to * fill the buffer */ for (k = 0; k < 4; k++) { if (!buf[i + k]) /* fill buffer */ { if (fseek(f, -k, SEEK_CUR) == -1 || !fgets(buf, 255, f)) goto quit_error; i = 0; break; } } while (buf[i] && isspace(buf[i])) i++; while (buf[i] && !isspace(buf[i])) buf2[j++] = buf[i++]; if (j) { buf2[j] = 0; *(iptr++) = atoi(buf2); j = 0; x++; } } iptr = idata; if (v == 255) { for (x = 0; x < w; x++) { *ptr2 = 0xff000000 | (iptr[0] << 16) | (iptr[0] << 8) | iptr[0]; ptr2++; iptr++; } } else { for (x = 0; x < w; x++) { *ptr2 = 0xff000000 | (((iptr[0] * 255) / v) << 16) | (((iptr[0] * 255) / v) << 8) | ((iptr[0] * 255) / v); ptr2++; iptr++; } } if (progress && do_progress(im, progress, progress_granularity, &pper, &pl, y)) goto quit_progress; } break; case '3': /* ASCII RGB */ idata = malloc(3 * sizeof(int) * w); if (!idata) goto quit_error; buf[0] = 0; i = 0; j = 0; for (y = 0; y < h; y++) { int w3 = 3 * w; iptr = idata; x = 0; while (x < w3) { int k; /* check 4 chars ahead to see if we need to * fill the buffer */ for (k = 0; k < 4; k++) { if (!buf[i + k]) /* fill buffer */ { if (fseek(f, -k, SEEK_CUR) == -1 || !fgets(buf, 255, f)) goto quit_error; i = 0; break; } } while (buf[i] && isspace(buf[i])) i++; while (buf[i] && !isspace(buf[i])) buf2[j++] = buf[i++]; if (j) { buf2[j] = 0; *(iptr++) = atoi(buf2); j = 0; x++; } } iptr = idata; if (v == 255) { for (x = 0; x < w; x++) { *ptr2 = 0xff000000 | (iptr[0] << 16) | (iptr[1] << 8) | iptr[2]; ptr2++; iptr += 3; } } else { for (x = 0; x < w; x++) { *ptr2 = 0xff000000 | (((iptr[0] * 255) / v) << 16) | (((iptr[1] * 255) / v) << 8) | ((iptr[2] * 255) / v); ptr2++; iptr += 3; } } if (progress && do_progress(im, progress, progress_granularity, &pper, &pl, y)) goto quit_progress; } break; case '4': /* binary 1bit monochrome */ data = malloc((w + 7) / 8 * sizeof(DATA8)); if (!data) goto quit_error; ptr2 = im->data; for (y = 0; y < h; y++) { if (!fread(data, (w + 7) / 8, 1, f)) goto quit_error; ptr = data; for (x = 0; x < w; x += 8) { j = (w - x >= 8) ? 8 : w - x; for (i = 0; i < j; i++) { if (ptr[0] & (0x80 >> i)) *ptr2 = 0xff000000; else *ptr2 = 0xffffffff; ptr2++; } ptr++; } if (progress && do_progress(im, progress, progress_granularity, &pper, &pl, y)) goto quit_progress; } break; case '5': /* binary 8bit grayscale GGGGGGGG */ data = malloc(1 * sizeof(DATA8) * w); if (!data) goto quit_error; ptr2 = im->data; for (y = 0; y < h; y++) { if (!fread(data, w * 1, 1, f)) break; ptr = data; if (v == 255) { for (x = 0; x < w; x++) { *ptr2 = 0xff000000 | (ptr[0] << 16) | (ptr[0] << 8) | ptr[0]; ptr2++; ptr++; } } else { for (x = 0; x < w; x++) { *ptr2 = 0xff000000 | (((ptr[0] * 255) / v) << 16) | (((ptr[0] * 255) / v) << 8) | ((ptr[0] * 255) / v); ptr2++; ptr++; } } if (progress && do_progress(im, progress, progress_granularity, &pper, &pl, y)) goto quit_progress; } break; case '6': /* 24bit binary RGBRGBRGB */ data = malloc(3 * sizeof(DATA8) * w); if (!data) goto quit_error; ptr2 = im->data; for (y = 0; y < h; y++) { if (!fread(data, w * 3, 1, f)) break; ptr = data; if (v == 255) { for (x = 0; x < w; x++) { *ptr2 = 0xff000000 | (ptr[0] << 16) | (ptr[1] << 8) | ptr[2]; ptr2++; ptr += 3; } } else { for (x = 0; x < w; x++) { *ptr2 = 0xff000000 | (((ptr[0] * 255) / v) << 16) | (((ptr[1] * 255) / v) << 8) | ((ptr[2] * 255) / v); ptr2++; ptr += 3; } } if (progress && do_progress(im, progress, progress_granularity, &pper, &pl, y)) goto quit_progress; } break; case '7': /* XV's 8bit 332 format */ data = malloc(1 * sizeof(DATA8) * w); if (!data) goto quit_error; ptr2 = im->data; for (y = 0; y < h; y++) { if (!fread(data, w * 1, 1, f)) break; ptr = data; for (x = 0; x < w; x++) { int r, g, b; r = (*ptr >> 5) & 0x7; g = (*ptr >> 2) & 0x7; b = (*ptr) & 0x3; *ptr2 = 0xff000000 | (((r << 21) | (r << 18) | (r << 15)) & 0xff0000) | (((g << 13) | (g << 10) | (g << 7)) & 0xff00) | ((b << 6) | (b << 4) | (b << 2) | (b << 0)); ptr2++; ptr++; } if (progress && do_progress(im, progress, progress_granularity, &pper, &pl, y)) goto quit_progress; } break; case '8': /* 24bit binary RGBARGBARGBA */ data = malloc(4 * sizeof(DATA8) * w); if (!data) goto quit_error; ptr2 = im->data; for (y = 0; y < h; y++) { if (!fread(data, w * 4, 1, f)) break; ptr = data; if (v == 255) { for (x = 0; x < w; x++) { *ptr2 = (ptr[3] << 24) | (ptr[0] << 16) | (ptr[1] << 8) | ptr[2]; ptr2++; ptr += 4; } } else { for (x = 0; x < w; x++) { *ptr2 = (((ptr[3] * 255) / v) << 24) | (((ptr[0] * 255) / v) << 16) | (((ptr[1] * 255) / v) << 8) | ((ptr[2] * 255) / v); ptr2++; ptr += 4; } } if (progress && do_progress(im, progress, progress_granularity, &pper, &pl, y)) goto quit_progress; } break; default: quit_error: rc = 0; break; quit_progress: rc = 2; break; } if (idata) free(idata); if (data) free(data); } quit: fclose(f); return rc; } Vulnerability Type: DoS CWE ID: CWE-189 Summary: imlib2 before 1.4.7 allows remote attackers to cause a denial of service (divide-by-zero error and application crash) via a crafted PNM file. Commit Message:
Medium
165,339
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void MojoAudioOutputStream::OnStreamCreated( int stream_id, const base::SharedMemory* shared_memory, std::unique_ptr<base::CancelableSyncSocket> foreign_socket) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(stream_created_callback_); DCHECK(shared_memory); DCHECK(foreign_socket); base::SharedMemoryHandle foreign_memory_handle = base::SharedMemory::DuplicateHandle(shared_memory->handle()); if (!base::SharedMemory::IsHandleValid(foreign_memory_handle)) { OnStreamError(/*not used*/ 0); return; } mojo::ScopedSharedBufferHandle buffer_handle = mojo::WrapSharedMemoryHandle( foreign_memory_handle, shared_memory->requested_size(), false); mojo::ScopedHandle socket_handle = mojo::WrapPlatformFile(foreign_socket->Release()); DCHECK(buffer_handle.is_valid()); DCHECK(socket_handle.is_valid()); base::ResetAndReturn(&stream_created_callback_) .Run(std::move(buffer_handle), std::move(socket_handle)); } Vulnerability Type: CWE ID: CWE-787 Summary: Incorrect use of mojo::WrapSharedMemoryHandle in Mojo in Google Chrome prior to 65.0.3325.146 allowed a remote attacker who had compromised the renderer process to perform an out of bounds memory write via a crafted HTML page. Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268}
Medium
172,879
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: m_authenticate(struct Client *client_p, struct Client *source_p, int parc, const char *parv[]) { struct Client *agent_p = NULL; struct Client *saslserv_p = NULL; /* They really should use CAP for their own sake. */ if(!IsCapable(source_p, CLICAP_SASL)) return 0; if (strlen(client_p->id) == 3) { exit_client(client_p, client_p, client_p, "Mixing client and server protocol"); return 0; } saslserv_p = find_named_client(ConfigFileEntry.sasl_service); if (saslserv_p == NULL || !IsService(saslserv_p)) { sendto_one(source_p, form_str(ERR_SASLABORTED), me.name, EmptyString(source_p->name) ? "*" : source_p->name); return 0; } if(source_p->localClient->sasl_complete) { *source_p->localClient->sasl_agent = '\0'; source_p->localClient->sasl_complete = 0; } if(strlen(parv[1]) > 400) { sendto_one(source_p, form_str(ERR_SASLTOOLONG), me.name, EmptyString(source_p->name) ? "*" : source_p->name); return 0; } if(!*source_p->id) { /* Allocate a UID. */ strcpy(source_p->id, generate_uid()); add_to_id_hash(source_p->id, source_p); } if(*source_p->localClient->sasl_agent) agent_p = find_id(source_p->localClient->sasl_agent); if(agent_p == NULL) { sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s H %s %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, source_p->host, source_p->sockhost); if (!strcmp(parv[1], "EXTERNAL") && source_p->certfp != NULL) sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s S %s %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, parv[1], source_p->certfp); else sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s S %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, parv[1]); rb_strlcpy(source_p->localClient->sasl_agent, saslserv_p->id, IDLEN); } else sendto_one(agent_p, ":%s ENCAP %s SASL %s %s C %s", me.id, agent_p->servptr->name, source_p->id, agent_p->id, parv[1]); source_p->localClient->sasl_out++; return 0; } Vulnerability Type: CWE ID: CWE-285 Summary: The m_authenticate function in modules/m_sasl.c in Charybdis before 3.5.3 allows remote attackers to spoof certificate fingerprints and consequently log in as another user via a crafted AUTHENTICATE parameter. Commit Message: SASL: Disallow beginning : and space anywhere in AUTHENTICATE parameter This is a FIX FOR A SECURITY VULNERABILITY. All Charybdis users must apply this fix if you support SASL on your servers, or unload m_sasl.so in the meantime.
Medium
166,944
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void cJSON_InitHooks(cJSON_Hooks* hooks) { if ( ! hooks ) { /* Reset hooks. */ cJSON_malloc = malloc; cJSON_free = free; return; } cJSON_malloc = (hooks->malloc_fn) ? hooks->malloc_fn : malloc; cJSON_free = (hooks->free_fn) ? hooks->free_fn : free; } 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
167,290
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void impeg2d_next_code(dec_state_t *ps_dec, UWORD32 u4_start_code_val) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; impeg2d_bit_stream_flush_to_byte_boundary(ps_stream); while ((impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != u4_start_code_val) && (ps_dec->s_bit_stream.u4_offset <= ps_dec->s_bit_stream.u4_max_offset)) { if (impeg2d_bit_stream_get(ps_stream,8) != 0) { /* Ignore stuffing bit errors. */ } } return; } Vulnerability Type: Bypass +Info CWE ID: CWE-254 Summary: libmpeg2 in libstagefright in Android 6.x before 2016-03-01 allows attackers to obtain sensitive information, and consequently bypass an unspecified protection mechanism, via crafted Bitstream data, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 25765591. Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6
Medium
173,950
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: void PrintPreviewMessageHandler::OnMetafileReadyForPrinting( const PrintHostMsg_DidPreviewDocument_Params& params) { StopWorker(params.document_cookie); if (params.expected_pages_count <= 0) { NOTREACHED(); return; } PrintPreviewUI* print_preview_ui = GetPrintPreviewUI(); if (!print_preview_ui) return; scoped_refptr<base::RefCountedBytes> data_bytes = GetDataFromHandle(params.metafile_data_handle, params.data_size); if (!data_bytes || !data_bytes->size()) return; print_preview_ui->SetPrintPreviewDataForIndex(COMPLETE_PREVIEW_DOCUMENT_INDEX, std::move(data_bytes)); print_preview_ui->OnPreviewDataIsAvailable( params.expected_pages_count, params.preview_request_id); } Vulnerability Type: +Info CWE ID: CWE-254 Summary: The FrameFetchContext::updateTimingInfoForIFrameNavigation function in core/loader/FrameFetchContext.cpp in Blink, as used in Google Chrome before 45.0.2454.85, does not properly restrict the availability of IFRAME Resource Timing API times, which allows remote attackers to obtain sensitive information via crafted JavaScript code that leverages a history.back call. Commit Message: Use pdf compositor service for printing when OOPIF is enabled When OOPIF is enabled (by site-per-process flag or top-document-isolation feature), use the pdf compositor service for converting PaintRecord to PDF on renderers. In the future, this will make compositing PDF from multiple renderers possible. [email protected] BUG=455764 Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f Reviewed-on: https://chromium-review.googlesource.com/699765 Commit-Queue: Wei Li <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Cr-Commit-Position: refs/heads/master@{#511616}
Medium
171,890
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: static int host_start(struct ci13xxx *ci) { struct usb_hcd *hcd; struct ehci_hcd *ehci; int ret; if (usb_disabled()) return -ENODEV; hcd = usb_create_hcd(&ci_ehci_hc_driver, ci->dev, dev_name(ci->dev)); if (!hcd) return -ENOMEM; dev_set_drvdata(ci->dev, ci); hcd->rsrc_start = ci->hw_bank.phys; hcd->rsrc_len = ci->hw_bank.size; hcd->regs = ci->hw_bank.abs; hcd->has_tt = 1; hcd->power_budget = ci->platdata->power_budget; hcd->phy = ci->transceiver; ehci = hcd_to_ehci(hcd); ehci->caps = ci->hw_bank.cap; ehci->has_hostpc = ci->hw_bank.lpm; ret = usb_add_hcd(hcd, 0, 0); if (ret) usb_put_hcd(hcd); else ci->hcd = hcd; return ret; } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: The host_start function in drivers/usb/chipidea/host.c in the Linux kernel before 3.7.4 does not properly support a certain non-streaming option, which allows local users to cause a denial of service (system crash) by sending a large amount of network traffic through a USB/Ethernet adapter. Commit Message: usb: chipidea: Allow disabling streaming not only in udc mode When running a scp transfer using a USB/Ethernet adapter the following crash happens: $ scp test.tar.gz [email protected]:/home/fabio [email protected]'s password: test.tar.gz 0% 0 0.0KB/s --:-- ETA ------------[ cut here ]------------ WARNING: at net/sched/sch_generic.c:255 dev_watchdog+0x2cc/0x2f0() NETDEV WATCHDOG: eth0 (asix): transmit queue 0 timed out Modules linked in: Backtrace: [<80011c94>] (dump_backtrace+0x0/0x10c) from [<804d3a5c>] (dump_stack+0x18/0x1c) r6:000000ff r5:80412388 r4:80685dc0 r3:80696cc0 [<804d3a44>] (dump_stack+0x0/0x1c) from [<80021868>] (warn_slowpath_common+0x54/0x6c) [<80021814>] (warn_slowpath_common+0x0/0x6c) from [<80021924>] (warn_slowpath_fmt+0x38/0x40) ... Setting SDIS (Stream Disable Mode- bit 4 of USBMODE register) fixes the problem. However, in current code CI13XXX_DISABLE_STREAMING flag is only set in udc mode, so allow disabling streaming also in host mode. Tested on a mx6qsabrelite board. Suggested-by: Peter Chen <[email protected]> Signed-off-by: Fabio Estevam <[email protected]> Reviewed-by: Peter Chen <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]>
Medium
166,087
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. Remember, I want response in 'High' or 'Medium' or 'Low', No explanation.
Code: write_message( RenderState state ) { ADisplay adisplay = (ADisplay)state->display.disp; if ( state->message == NULL ) { FontFace face = &state->faces[state->face_index]; int idx, total; idx = face->index; total = 1; while ( total + state->face_index < state->num_faces && face[total].filepath == face[0].filepath ) total++; total += idx; state->message = state->message0; if ( total > 1 ) sprintf( state->message0, "%s %d/%d @ %5.1fpt", state->filename, idx + 1, total, state->char_size ); else sprintf( state->message0, "%s @ %5.1fpt", state->filename, state->char_size ); } grWriteCellString( adisplay->bitmap, 0, DIM_Y - 10, state->message, adisplay->fore_color ); state->message = NULL; } Vulnerability Type: DoS Exec Code Overflow CWE ID: CWE-119 Summary: Multiple buffer overflows in demo programs in FreeType before 2.4.0 allow remote attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a crafted font file. Commit Message:
Medium
164,997