instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int copy_to_user_tmpl(struct xfrm_policy *xp, struct sk_buff *skb) { struct xfrm_user_tmpl vec[XFRM_MAX_DEPTH]; int i; if (xp->xfrm_nr == 0) return 0; for (i = 0; i < xp->xfrm_nr; i++) { struct xfrm_user_tmpl *up = &vec[i]; struct xfrm_tmpl *kp = &xp->xfrm_vec[i]; memcpy(&up->id, &kp->id, sizeof(up->id)); up->family = kp->encap_family; memcpy(&up->saddr, &kp->saddr, sizeof(up->saddr)); up->reqid = kp->reqid; up->mode = kp->mode; up->share = kp->share; up->optional = kp->optional; up->aalgos = kp->aalgos; up->ealgos = kp->ealgos; up->calgos = kp->calgos; } return nla_put(skb, XFRMA_TMPL, sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr, vec); } Commit Message: xfrm_user: fix info leak in copy_to_user_tmpl() The memory used for the template copy is a local stack variable. As struct xfrm_user_tmpl contains multiple holes added by the compiler for alignment, not initializing the memory will lead to leaking stack bytes to userland. Add an explicit memset(0) to avoid the info leak. Initial version of the patch by Brad Spengler. Cc: Brad Spengler <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Acked-by: Steffen Klassert <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int copy_to_user_tmpl(struct xfrm_policy *xp, struct sk_buff *skb) { struct xfrm_user_tmpl vec[XFRM_MAX_DEPTH]; int i; if (xp->xfrm_nr == 0) return 0; for (i = 0; i < xp->xfrm_nr; i++) { struct xfrm_user_tmpl *up = &vec[i]; struct xfrm_tmpl *kp = &xp->xfrm_vec[i]; memset(up, 0, sizeof(*up)); memcpy(&up->id, &kp->id, sizeof(up->id)); up->family = kp->encap_family; memcpy(&up->saddr, &kp->saddr, sizeof(up->saddr)); up->reqid = kp->reqid; up->mode = kp->mode; up->share = kp->share; up->optional = kp->optional; up->aalgos = kp->aalgos; up->ealgos = kp->ealgos; up->calgos = kp->calgos; } return nla_put(skb, XFRMA_TMPL, sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr, vec); }
169,901
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: v8::Handle<v8::Value> V8TestObj::constructorCallback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.Constructor"); if (!args.IsConstructCall()) return V8Proxy::throwTypeError("DOM object constructor cannot be called as a function."); if (ConstructorMode::current() == ConstructorMode::WrapExistingObject) return args.Holder(); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); if (args.Length() <= 0 || !args[0]->IsFunction()) return throwError(TYPE_MISMATCH_ERR, args.GetIsolate()); RefPtr<TestCallback> testCallback = V8TestCallback::create(args[0], getScriptExecutionContext()); RefPtr<TestObj> impl = TestObj::create(testCallback); v8::Handle<v8::Object> wrapper = args.Holder(); V8DOMWrapper::setDOMWrapper(wrapper, &info, impl.get()); V8DOMWrapper::setJSWrapperForDOMObject(impl.release(), v8::Persistent<v8::Object>::New(wrapper), args.GetIsolate()); return args.Holder(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
v8::Handle<v8::Value> V8TestObj::constructorCallback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.Constructor"); if (!args.IsConstructCall()) return V8Proxy::throwTypeError("DOM object constructor cannot be called as a function."); if (ConstructorMode::current() == ConstructorMode::WrapExistingObject) return args.Holder(); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); if (args.Length() <= 0 || !args[0]->IsFunction()) return throwError(TYPE_MISMATCH_ERR, args.GetIsolate()); RefPtr<TestCallback> testCallback = V8TestCallback::create(args[0], getScriptExecutionContext()); RefPtr<TestObj> impl = TestObj::create(testCallback); v8::Handle<v8::Object> wrapper = args.Holder(); V8DOMWrapper::setDOMWrapper(wrapper, &info, impl.get()); V8DOMWrapper::setJSWrapperForDOMObject(impl.release(), v8::Persistent<v8::Object>::New(wrapper), args.GetIsolate()); return args.Holder(); }
171,076
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ras_getdatastd(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap, jas_image_t *image) { int pad; int nz; int z; int c; int y; int x; int v; int i; jas_matrix_t *data[3]; /* Note: This function does not properly handle images with a colormap. */ /* Avoid compiler warnings about unused parameters. */ cmap = 0; for (i = 0; i < jas_image_numcmpts(image); ++i) { data[i] = jas_matrix_create(1, jas_image_width(image)); assert(data[i]); } pad = RAS_ROWSIZE(hdr) - (hdr->width * hdr->depth + 7) / 8; for (y = 0; y < hdr->height; y++) { nz = 0; z = 0; for (x = 0; x < hdr->width; x++) { while (nz < hdr->depth) { if ((c = jas_stream_getc(in)) == EOF) { return -1; } z = (z << 8) | c; nz += 8; } v = (z >> (nz - hdr->depth)) & RAS_ONES(hdr->depth); z &= RAS_ONES(nz - hdr->depth); nz -= hdr->depth; if (jas_image_numcmpts(image) == 3) { jas_matrix_setv(data[0], x, (RAS_GETRED(v))); jas_matrix_setv(data[1], x, (RAS_GETGREEN(v))); jas_matrix_setv(data[2], x, (RAS_GETBLUE(v))); } else { jas_matrix_setv(data[0], x, (v)); } } if (pad) { if ((c = jas_stream_getc(in)) == EOF) { return -1; } } for (i = 0; i < jas_image_numcmpts(image); ++i) { if (jas_image_writecmpt(image, i, 0, y, hdr->width, 1, data[i])) { return -1; } } } for (i = 0; i < jas_image_numcmpts(image); ++i) { jas_matrix_destroy(data[i]); } return 0; } Commit Message: Fixed a few bugs in the RAS encoder and decoder where errors were tested with assertions instead of being gracefully handled. CWE ID:
static int ras_getdatastd(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap, jas_image_t *image) { int pad; int nz; int z; int c; int y; int x; int v; int i; jas_matrix_t *data[3]; /* Note: This function does not properly handle images with a colormap. */ /* Avoid compiler warnings about unused parameters. */ cmap = 0; assert(jas_image_numcmpts(image) <= 3); for (i = 0; i < 3; ++i) { data[i] = 0; } for (i = 0; i < jas_image_numcmpts(image); ++i) { if (!(data[i] = jas_matrix_create(1, jas_image_width(image)))) { goto error; } } pad = RAS_ROWSIZE(hdr) - (hdr->width * hdr->depth + 7) / 8; for (y = 0; y < hdr->height; y++) { nz = 0; z = 0; for (x = 0; x < hdr->width; x++) { while (nz < hdr->depth) { if ((c = jas_stream_getc(in)) == EOF) { goto error; } z = (z << 8) | c; nz += 8; } v = (z >> (nz - hdr->depth)) & RAS_ONES(hdr->depth); z &= RAS_ONES(nz - hdr->depth); nz -= hdr->depth; if (jas_image_numcmpts(image) == 3) { jas_matrix_setv(data[0], x, (RAS_GETRED(v))); jas_matrix_setv(data[1], x, (RAS_GETGREEN(v))); jas_matrix_setv(data[2], x, (RAS_GETBLUE(v))); } else { jas_matrix_setv(data[0], x, (v)); } } if (pad) { if ((c = jas_stream_getc(in)) == EOF) { goto error; } } for (i = 0; i < jas_image_numcmpts(image); ++i) { if (jas_image_writecmpt(image, i, 0, y, hdr->width, 1, data[i])) { goto error; } } } for (i = 0; i < jas_image_numcmpts(image); ++i) { jas_matrix_destroy(data[i]); data[i] = 0; } return 0; error: for (i = 0; i < 3; ++i) { if (data[i]) { jas_matrix_destroy(data[i]); } } return -1; }
168,740
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: header_read (SF_PRIVATE *psf, void *ptr, int bytes) { int count = 0 ; if (psf->headindex >= SIGNED_SIZEOF (psf->header)) return psf_fread (ptr, 1, bytes, psf) ; if (psf->headindex + bytes > SIGNED_SIZEOF (psf->header)) { int most ; most = SIGNED_SIZEOF (psf->header) - psf->headend ; psf_fread (psf->header + psf->headend, 1, most, psf) ; memcpy (ptr, psf->header + psf->headend, most) ; psf->headend = psf->headindex += most ; psf_fread ((char *) ptr + most, bytes - most, 1, psf) ; return bytes ; } ; if (psf->headindex + bytes > psf->headend) { count = psf_fread (psf->header + psf->headend, 1, bytes - (psf->headend - psf->headindex), psf) ; if (count != bytes - (int) (psf->headend - psf->headindex)) { psf_log_printf (psf, "Error : psf_fread returned short count.\n") ; return count ; } ; psf->headend += count ; } ; memcpy (ptr, psf->header + psf->headindex, bytes) ; psf->headindex += bytes ; return bytes ; } /* header_read */ 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. CWE ID: CWE-119
header_read (SF_PRIVATE *psf, void *ptr, int bytes) { int count = 0 ; if (psf->header.indx + bytes >= psf->header.len && psf_bump_header_allocation (psf, bytes)) return count ; if (psf->header.indx + bytes > psf->header.end) { count = psf_fread (psf->header.ptr + psf->header.end, 1, bytes - (psf->header.end - psf->header.indx), psf) ; if (count != bytes - (int) (psf->header.end - psf->header.indx)) { psf_log_printf (psf, "Error : psf_fread returned short count.\n") ; return count ; } ; psf->header.end += count ; } ; memcpy (ptr, psf->header.ptr + psf->header.indx, bytes) ; psf->header.indx += bytes ; return bytes ; } /* header_read */
170,061
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kNGroupsOffset = 12; const size_t kFirstGroupOffset = 16; const size_t kGroupSize = 12; const size_t kStartCharCodeOffset = 0; const size_t kEndCharCodeOffset = 4; const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow if (kFirstGroupOffset > size) { return false; } uint32_t nGroups = readU32(data, kNGroupsOffset); if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) { return false; } for (uint32_t i = 0; i < nGroups; i++) { uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize; uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset); uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset); if (end < start) { return false; } addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive } return true; } Commit Message: Add error logging on invalid cmap - DO NOT MERGE This patch logs instances of fonts with invalid cmap tables. Bug: 25645298 Bug: 26413177 Change-Id: I183985e9784a97a2b4307a22e036382b1fc90e5e CWE ID: CWE-20
static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kNGroupsOffset = 12; const size_t kFirstGroupOffset = 16; const size_t kGroupSize = 12; const size_t kStartCharCodeOffset = 0; const size_t kEndCharCodeOffset = 4; const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow if (kFirstGroupOffset > size) { return false; } uint32_t nGroups = readU32(data, kNGroupsOffset); if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) { android_errorWriteLog(0x534e4554, "25645298"); return false; } for (uint32_t i = 0; i < nGroups; i++) { uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize; uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset); uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset); if (end < start) { android_errorWriteLog(0x534e4554, "26413177"); return false; } addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive } return true; }
173,895
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_siz_t *siz = &ms->parms.siz; int compno; int tileno; jpc_dec_tile_t *tile; jpc_dec_tcomp_t *tcomp; int htileno; int vtileno; jpc_dec_cmpt_t *cmpt; dec->xstart = siz->xoff; dec->ystart = siz->yoff; dec->xend = siz->width; dec->yend = siz->height; dec->tilewidth = siz->tilewidth; dec->tileheight = siz->tileheight; dec->tilexoff = siz->tilexoff; dec->tileyoff = siz->tileyoff; dec->numcomps = siz->numcomps; if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) { return -1; } if (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++cmpt) { cmpt->prec = siz->comps[compno].prec; cmpt->sgnd = siz->comps[compno].sgnd; cmpt->hstep = siz->comps[compno].hsamp; cmpt->vstep = siz->comps[compno].vsamp; cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) - JPC_CEILDIV(dec->xstart, cmpt->hstep); cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) - JPC_CEILDIV(dec->ystart, cmpt->vstep); cmpt->hsubstep = 0; cmpt->vsubstep = 0; } dec->image = 0; dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth); dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight); dec->numtiles = dec->numhtiles * dec->numvtiles; JAS_DBGLOG(10, ("numtiles = %d; numhtiles = %d; numvtiles = %d;\n", dec->numtiles, dec->numhtiles, dec->numvtiles)); if (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) { return -1; } for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno, ++tile) { htileno = tileno % dec->numhtiles; vtileno = tileno / dec->numhtiles; tile->realmode = 0; tile->state = JPC_TILE_INIT; tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth, dec->xstart); tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight, dec->ystart); tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) * dec->tilewidth, dec->xend); tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) * dec->tileheight, dec->yend); tile->numparts = 0; tile->partno = 0; tile->pkthdrstream = 0; tile->pkthdrstreampos = 0; tile->pptstab = 0; tile->cp = 0; tile->pi = 0; if (!(tile->tcomps = jas_alloc2(dec->numcomps, sizeof(jpc_dec_tcomp_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) { tcomp->rlvls = 0; tcomp->numrlvls = 0; tcomp->data = 0; tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep); tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep); tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep); tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep); tcomp->tsfb = 0; } } dec->pkthdrstreams = 0; /* We should expect to encounter other main header marker segments or an SOT marker segment next. */ dec->state = JPC_MH; return 0; } Commit Message: Fixed another integer overflow problem. CWE ID: CWE-190
static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_siz_t *siz = &ms->parms.siz; int compno; int tileno; jpc_dec_tile_t *tile; jpc_dec_tcomp_t *tcomp; int htileno; int vtileno; jpc_dec_cmpt_t *cmpt; size_t size; dec->xstart = siz->xoff; dec->ystart = siz->yoff; dec->xend = siz->width; dec->yend = siz->height; dec->tilewidth = siz->tilewidth; dec->tileheight = siz->tileheight; dec->tilexoff = siz->tilexoff; dec->tileyoff = siz->tileyoff; dec->numcomps = siz->numcomps; if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) { return -1; } if (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++cmpt) { cmpt->prec = siz->comps[compno].prec; cmpt->sgnd = siz->comps[compno].sgnd; cmpt->hstep = siz->comps[compno].hsamp; cmpt->vstep = siz->comps[compno].vsamp; cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) - JPC_CEILDIV(dec->xstart, cmpt->hstep); cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) - JPC_CEILDIV(dec->ystart, cmpt->vstep); cmpt->hsubstep = 0; cmpt->vsubstep = 0; } dec->image = 0; dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth); dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight); if (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size)) { return -1; } dec->numtiles = size; JAS_DBGLOG(10, ("numtiles = %d; numhtiles = %d; numvtiles = %d;\n", dec->numtiles, dec->numhtiles, dec->numvtiles)); if (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) { return -1; } for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno, ++tile) { htileno = tileno % dec->numhtiles; vtileno = tileno / dec->numhtiles; tile->realmode = 0; tile->state = JPC_TILE_INIT; tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth, dec->xstart); tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight, dec->ystart); tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) * dec->tilewidth, dec->xend); tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) * dec->tileheight, dec->yend); tile->numparts = 0; tile->partno = 0; tile->pkthdrstream = 0; tile->pkthdrstreampos = 0; tile->pptstab = 0; tile->cp = 0; tile->pi = 0; if (!(tile->tcomps = jas_alloc2(dec->numcomps, sizeof(jpc_dec_tcomp_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) { tcomp->rlvls = 0; tcomp->numrlvls = 0; tcomp->data = 0; tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep); tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep); tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep); tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep); tcomp->tsfb = 0; } } dec->pkthdrstreams = 0; /* We should expect to encounter other main header marker segments or an SOT marker segment next. */ dec->state = JPC_MH; return 0; }
168,742
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: parse_charstrings( T1_Face face, T1_Loader loader ) { T1_Parser parser = &loader->parser; PS_Table code_table = &loader->charstrings; PS_Table name_table = &loader->glyph_names; PS_Table swap_table = &loader->swap_table; FT_Memory memory = parser->root.memory; FT_Error error; PSAux_Service psaux = (PSAux_Service)face->psaux; FT_Byte* cur; FT_Byte* limit = parser->root.limit; FT_Int n, num_glyphs; FT_UInt notdef_index = 0; FT_Byte notdef_found = 0; num_glyphs = (FT_Int)T1_ToInt( parser ); if ( num_glyphs < 0 ) { error = FT_THROW( Invalid_File_Format ); goto Fail; } /* some fonts like Optima-Oblique not only define the /CharStrings */ /* array but access it also */ if ( num_glyphs == 0 || parser->root.error ) return; /* initialize tables, leaving space for addition of .notdef, */ /* if necessary, and a few other glyphs to handle buggy */ /* fonts which have more glyphs than specified. */ /* for some non-standard fonts like `Optima' which provides */ /* different outlines depending on the resolution it is */ /* possible to get here twice */ if ( !loader->num_glyphs ) { error = psaux->ps_table_funcs->init( code_table, num_glyphs + 1 + TABLE_EXTEND, memory ); if ( error ) goto Fail; error = psaux->ps_table_funcs->init( name_table, num_glyphs + 1 + TABLE_EXTEND, memory ); if ( error ) goto Fail; /* Initialize table for swapping index notdef_index and */ /* index 0 names and codes (if necessary). */ error = psaux->ps_table_funcs->init( swap_table, 4, memory ); if ( error ) goto Fail; } n = 0; for (;;) { FT_Long size; FT_Byte* base; /* the format is simple: */ /* `/glyphname' + binary data */ T1_Skip_Spaces( parser ); cur = parser->root.cursor; if ( cur >= limit ) break; /* we stop when we find a `def' or `end' keyword */ if ( cur + 3 < limit && IS_PS_DELIM( cur[3] ) ) { if ( cur[0] == 'd' && cur[1] == 'e' && cur[2] == 'f' ) { /* There are fonts which have this: */ /* */ /* /CharStrings 118 dict def */ /* Private begin */ /* CharStrings begin */ /* ... */ /* */ /* To catch this we ignore `def' if */ /* no charstring has actually been */ /* seen. */ if ( n ) break; } if ( cur[0] == 'e' && cur[1] == 'n' && cur[2] == 'd' ) break; } T1_Skip_PS_Token( parser ); if ( parser->root.error ) return; if ( *cur == '/' ) { FT_PtrDist len; if ( cur + 1 >= limit ) { error = FT_THROW( Invalid_File_Format ); goto Fail; } cur++; /* skip `/' */ len = parser->root.cursor - cur; if ( !read_binary_data( parser, &size, &base, IS_INCREMENTAL ) ) return; /* for some non-standard fonts like `Optima' which provides */ /* different outlines depending on the resolution it is */ /* possible to get here twice */ if ( loader->num_glyphs ) continue; error = T1_Add_Table( name_table, n, cur, len + 1 ); if ( error ) goto Fail; /* add a trailing zero to the name table */ name_table->elements[n][len] = '\0'; /* record index of /.notdef */ if ( *cur == '.' && ft_strcmp( ".notdef", (const char*)(name_table->elements[n]) ) == 0 ) { notdef_index = n; notdef_found = 1; } if ( face->type1.private_dict.lenIV >= 0 && n < num_glyphs + TABLE_EXTEND ) { FT_Byte* temp; if ( size <= face->type1.private_dict.lenIV ) { error = FT_THROW( Invalid_File_Format ); goto Fail; } /* t1_decrypt() shouldn't write to base -- make temporary copy */ if ( FT_ALLOC( temp, size ) ) goto Fail; FT_MEM_COPY( temp, base, size ); psaux->t1_decrypt( temp, size, 4330 ); size -= face->type1.private_dict.lenIV; error = T1_Add_Table( code_table, n, temp + face->type1.private_dict.lenIV, size ); FT_FREE( temp ); } else error = T1_Add_Table( code_table, n, base, size ); if ( error ) goto Fail; n++; } } loader->num_glyphs = n; /* if /.notdef is found but does not occupy index 0, do our magic. */ if ( notdef_found && ft_strcmp( ".notdef", (const char*)name_table->elements[0] ) ) { /* Swap glyph in index 0 with /.notdef glyph. First, add index 0 */ /* name and code entries to swap_table. Then place notdef_index */ /* name and code entries into swap_table. Then swap name and code */ /* entries at indices notdef_index and 0 using values stored in */ /* swap_table. */ /* Index 0 name */ error = T1_Add_Table( swap_table, 0, name_table->elements[0], name_table->lengths [0] ); if ( error ) goto Fail; /* Index 0 code */ error = T1_Add_Table( swap_table, 1, code_table->elements[0], code_table->lengths [0] ); if ( error ) goto Fail; /* Index notdef_index name */ error = T1_Add_Table( swap_table, 2, name_table->elements[notdef_index], name_table->lengths [notdef_index] ); if ( error ) goto Fail; /* Index notdef_index code */ error = T1_Add_Table( swap_table, 3, code_table->elements[notdef_index], code_table->lengths [notdef_index] ); if ( error ) goto Fail; error = T1_Add_Table( name_table, notdef_index, swap_table->elements[0], swap_table->lengths [0] ); if ( error ) goto Fail; error = T1_Add_Table( code_table, notdef_index, swap_table->elements[1], swap_table->lengths [1] ); if ( error ) goto Fail; error = T1_Add_Table( name_table, 0, swap_table->elements[2], swap_table->lengths [2] ); if ( error ) goto Fail; error = T1_Add_Table( code_table, 0, swap_table->elements[3], swap_table->lengths [3] ); if ( error ) goto Fail; } else if ( !notdef_found ) { /* notdef_index is already 0, or /.notdef is undefined in */ /* charstrings dictionary. Worry about /.notdef undefined. */ /* We take index 0 and add it to the end of the table(s) */ /* and add our own /.notdef glyph to index 0. */ /* 0 333 hsbw endchar */ FT_Byte notdef_glyph[] = { 0x8B, 0xF7, 0xE1, 0x0D, 0x0E }; char* notdef_name = (char *)".notdef"; error = T1_Add_Table( swap_table, 0, name_table->elements[0], name_table->lengths [0] ); if ( error ) goto Fail; error = T1_Add_Table( swap_table, 1, code_table->elements[0], code_table->lengths [0] ); if ( error ) goto Fail; error = T1_Add_Table( name_table, 0, notdef_name, 8 ); if ( error ) goto Fail; error = T1_Add_Table( code_table, 0, notdef_glyph, 5 ); if ( error ) goto Fail; error = T1_Add_Table( name_table, n, swap_table->elements[0], swap_table->lengths [0] ); if ( error ) goto Fail; error = T1_Add_Table( code_table, n, swap_table->elements[1], swap_table->lengths [1] ); if ( error ) goto Fail; /* we added a glyph. */ loader->num_glyphs += 1; } return; Fail: parser->root.error = error; } Commit Message: CWE ID: CWE-119
parse_charstrings( T1_Face face, T1_Loader loader ) { T1_Parser parser = &loader->parser; PS_Table code_table = &loader->charstrings; PS_Table name_table = &loader->glyph_names; PS_Table swap_table = &loader->swap_table; FT_Memory memory = parser->root.memory; FT_Error error; PSAux_Service psaux = (PSAux_Service)face->psaux; FT_Byte* cur; FT_Byte* limit = parser->root.limit; FT_Int n, num_glyphs; FT_UInt notdef_index = 0; FT_Byte notdef_found = 0; num_glyphs = (FT_Int)T1_ToInt( parser ); if ( num_glyphs < 0 ) { error = FT_THROW( Invalid_File_Format ); goto Fail; } /* some fonts like Optima-Oblique not only define the /CharStrings */ /* array but access it also */ if ( num_glyphs == 0 || parser->root.error ) return; /* initialize tables, leaving space for addition of .notdef, */ /* if necessary, and a few other glyphs to handle buggy */ /* fonts which have more glyphs than specified. */ /* for some non-standard fonts like `Optima' which provides */ /* different outlines depending on the resolution it is */ /* possible to get here twice */ if ( !loader->num_glyphs ) { error = psaux->ps_table_funcs->init( code_table, num_glyphs + 1 + TABLE_EXTEND, memory ); if ( error ) goto Fail; error = psaux->ps_table_funcs->init( name_table, num_glyphs + 1 + TABLE_EXTEND, memory ); if ( error ) goto Fail; /* Initialize table for swapping index notdef_index and */ /* index 0 names and codes (if necessary). */ error = psaux->ps_table_funcs->init( swap_table, 4, memory ); if ( error ) goto Fail; } n = 0; for (;;) { FT_Long size; FT_Byte* base; /* the format is simple: */ /* `/glyphname' + binary data */ T1_Skip_Spaces( parser ); cur = parser->root.cursor; if ( cur >= limit ) break; /* we stop when we find a `def' or `end' keyword */ if ( cur + 3 < limit && IS_PS_DELIM( cur[3] ) ) { if ( cur[0] == 'd' && cur[1] == 'e' && cur[2] == 'f' ) { /* There are fonts which have this: */ /* */ /* /CharStrings 118 dict def */ /* Private begin */ /* CharStrings begin */ /* ... */ /* */ /* To catch this we ignore `def' if */ /* no charstring has actually been */ /* seen. */ if ( n ) break; } if ( cur[0] == 'e' && cur[1] == 'n' && cur[2] == 'd' ) break; } T1_Skip_PS_Token( parser ); if ( parser->root.error ) return; if ( *cur == '/' ) { FT_PtrDist len; if ( cur + 2 >= limit ) { error = FT_THROW( Invalid_File_Format ); goto Fail; } cur++; /* skip `/' */ len = parser->root.cursor - cur; if ( !read_binary_data( parser, &size, &base, IS_INCREMENTAL ) ) return; /* for some non-standard fonts like `Optima' which provides */ /* different outlines depending on the resolution it is */ /* possible to get here twice */ if ( loader->num_glyphs ) continue; error = T1_Add_Table( name_table, n, cur, len + 1 ); if ( error ) goto Fail; /* add a trailing zero to the name table */ name_table->elements[n][len] = '\0'; /* record index of /.notdef */ if ( *cur == '.' && ft_strcmp( ".notdef", (const char*)(name_table->elements[n]) ) == 0 ) { notdef_index = n; notdef_found = 1; } if ( face->type1.private_dict.lenIV >= 0 && n < num_glyphs + TABLE_EXTEND ) { FT_Byte* temp; if ( size <= face->type1.private_dict.lenIV ) { error = FT_THROW( Invalid_File_Format ); goto Fail; } /* t1_decrypt() shouldn't write to base -- make temporary copy */ if ( FT_ALLOC( temp, size ) ) goto Fail; FT_MEM_COPY( temp, base, size ); psaux->t1_decrypt( temp, size, 4330 ); size -= face->type1.private_dict.lenIV; error = T1_Add_Table( code_table, n, temp + face->type1.private_dict.lenIV, size ); FT_FREE( temp ); } else error = T1_Add_Table( code_table, n, base, size ); if ( error ) goto Fail; n++; } } loader->num_glyphs = n; /* if /.notdef is found but does not occupy index 0, do our magic. */ if ( notdef_found && ft_strcmp( ".notdef", (const char*)name_table->elements[0] ) ) { /* Swap glyph in index 0 with /.notdef glyph. First, add index 0 */ /* name and code entries to swap_table. Then place notdef_index */ /* name and code entries into swap_table. Then swap name and code */ /* entries at indices notdef_index and 0 using values stored in */ /* swap_table. */ /* Index 0 name */ error = T1_Add_Table( swap_table, 0, name_table->elements[0], name_table->lengths [0] ); if ( error ) goto Fail; /* Index 0 code */ error = T1_Add_Table( swap_table, 1, code_table->elements[0], code_table->lengths [0] ); if ( error ) goto Fail; /* Index notdef_index name */ error = T1_Add_Table( swap_table, 2, name_table->elements[notdef_index], name_table->lengths [notdef_index] ); if ( error ) goto Fail; /* Index notdef_index code */ error = T1_Add_Table( swap_table, 3, code_table->elements[notdef_index], code_table->lengths [notdef_index] ); if ( error ) goto Fail; error = T1_Add_Table( name_table, notdef_index, swap_table->elements[0], swap_table->lengths [0] ); if ( error ) goto Fail; error = T1_Add_Table( code_table, notdef_index, swap_table->elements[1], swap_table->lengths [1] ); if ( error ) goto Fail; error = T1_Add_Table( name_table, 0, swap_table->elements[2], swap_table->lengths [2] ); if ( error ) goto Fail; error = T1_Add_Table( code_table, 0, swap_table->elements[3], swap_table->lengths [3] ); if ( error ) goto Fail; } else if ( !notdef_found ) { /* notdef_index is already 0, or /.notdef is undefined in */ /* charstrings dictionary. Worry about /.notdef undefined. */ /* We take index 0 and add it to the end of the table(s) */ /* and add our own /.notdef glyph to index 0. */ /* 0 333 hsbw endchar */ FT_Byte notdef_glyph[] = { 0x8B, 0xF7, 0xE1, 0x0D, 0x0E }; char* notdef_name = (char *)".notdef"; error = T1_Add_Table( swap_table, 0, name_table->elements[0], name_table->lengths [0] ); if ( error ) goto Fail; error = T1_Add_Table( swap_table, 1, code_table->elements[0], code_table->lengths [0] ); if ( error ) goto Fail; error = T1_Add_Table( name_table, 0, notdef_name, 8 ); if ( error ) goto Fail; error = T1_Add_Table( code_table, 0, notdef_glyph, 5 ); if ( error ) goto Fail; error = T1_Add_Table( name_table, n, swap_table->elements[0], swap_table->lengths [0] ); if ( error ) goto Fail; error = T1_Add_Table( code_table, n, swap_table->elements[1], swap_table->lengths [1] ); if ( error ) goto Fail; /* we added a glyph. */ loader->num_glyphs += 1; } return; Fail: parser->root.error = error; }
164,855
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void perf_log_throttle(struct perf_event *event, int enable) { struct perf_output_handle handle; struct perf_sample_data sample; int ret; struct { struct perf_event_header header; u64 time; u64 id; u64 stream_id; } throttle_event = { .header = { .type = PERF_RECORD_THROTTLE, .misc = 0, .size = sizeof(throttle_event), }, .time = perf_clock(), .id = primary_event_id(event), .stream_id = event->id, }; if (enable) throttle_event.header.type = PERF_RECORD_UNTHROTTLE; perf_event_header__init_id(&throttle_event.header, &sample, event); ret = perf_output_begin(&handle, event, throttle_event.header.size, 1, 0); if (ret) return; perf_output_put(&handle, throttle_event); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); } 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]> CWE ID: CWE-399
static void perf_log_throttle(struct perf_event *event, int enable) { struct perf_output_handle handle; struct perf_sample_data sample; int ret; struct { struct perf_event_header header; u64 time; u64 id; u64 stream_id; } throttle_event = { .header = { .type = PERF_RECORD_THROTTLE, .misc = 0, .size = sizeof(throttle_event), }, .time = perf_clock(), .id = primary_event_id(event), .stream_id = event->id, }; if (enable) throttle_event.header.type = PERF_RECORD_UNTHROTTLE; perf_event_header__init_id(&throttle_event.header, &sample, event); ret = perf_output_begin(&handle, event, throttle_event.header.size, 0); if (ret) return; perf_output_put(&handle, throttle_event); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); }
165,836
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ohci_bus_start(OHCIState *ohci) { ohci->eof_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, ohci_frame_boundary, ohci); if (ohci->eof_timer == NULL) { trace_usb_ohci_bus_eof_timer_failed(ohci->name); ohci_die(ohci); return 0; } trace_usb_ohci_start(ohci->name); /* Delay the first SOF event by one frame time as if (ohci->eof_timer == NULL) { trace_usb_ohci_bus_eof_timer_failed(ohci->name); ohci_die(ohci); return 0; } trace_usb_ohci_start(ohci->name); /* Delay the first SOF event by one frame time as static void ohci_bus_stop(OHCIState *ohci) { trace_usb_ohci_stop(ohci->name); if (ohci->eof_timer) { timer_del(ohci->eof_timer); timer_free(ohci->eof_timer); } ohci->eof_timer = NULL; } /* Sets a flag in a port status register but only set it if the port is } Commit Message: CWE ID:
static int ohci_bus_start(OHCIState *ohci) { trace_usb_ohci_start(ohci->name); /* Delay the first SOF event by one frame time as if (ohci->eof_timer == NULL) { trace_usb_ohci_bus_eof_timer_failed(ohci->name); ohci_die(ohci); return 0; } trace_usb_ohci_start(ohci->name); /* Delay the first SOF event by one frame time as static void ohci_bus_stop(OHCIState *ohci) { trace_usb_ohci_stop(ohci->name); timer_del(ohci->eof_timer); } /* Sets a flag in a port status register but only set it if the port is }
165,188
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static v8::Handle<v8::Value> voidMethodWithArgsCallback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.voidMethodWithArgs"); if (args.Length() < 3) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(int, intArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined))) : 0); imp->voidMethodWithArgs(intArg, strArg, objArg); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static v8::Handle<v8::Value> voidMethodWithArgsCallback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.voidMethodWithArgs"); if (args.Length() < 3) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(int, intArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined))) : 0); imp->voidMethodWithArgs(intArg, strArg, objArg); return v8::Handle<v8::Value>(); }
171,106
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BrowserGpuChannelHostFactory::GpuChannelEstablishedOnIO( EstablishRequest* request, const IPC::ChannelHandle& channel_handle, base::ProcessHandle gpu_process_handle, const GPUInfo& gpu_info) { request->channel_handle = channel_handle; request->gpu_process_handle = gpu_process_handle; request->gpu_info = gpu_info; request->event.Signal(); } 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 CWE ID:
void BrowserGpuChannelHostFactory::GpuChannelEstablishedOnIO( EstablishRequest* request, const IPC::ChannelHandle& channel_handle, const GPUInfo& gpu_info) { request->channel_handle = channel_handle; request->gpu_info = gpu_info; request->event.Signal(); }
170,919
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(Phar, offsetUnset) { char *fname, *error; size_t fname_len; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) { return; } if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) { if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ return; } if (phar_obj->archive->is_persistent) { if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); return; } /* re-populate entry after copy on write */ entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len); } entry->is_modified = 0; entry->is_deleted = 1; /* we need to "flush" the stream to save the newly deleted file on disk */ phar_flush(phar_obj->archive, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } RETURN_TRUE; } } else { RETURN_FALSE; } } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, offsetUnset) { char *fname, *error; size_t fname_len; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) { return; } if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) { if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ return; } if (phar_obj->archive->is_persistent) { if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); return; } /* re-populate entry after copy on write */ entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len); } entry->is_modified = 0; entry->is_deleted = 1; /* we need to "flush" the stream to save the newly deleted file on disk */ phar_flush(phar_obj->archive, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } RETURN_TRUE; } } else { RETURN_FALSE; } }
165,068
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void initializeHolderIfNeeded(ScriptState* scriptState, v8::Local<v8::Object> classObject, v8::Local<v8::Value> holder) { RELEASE_ASSERT(!holder.IsEmpty()); RELEASE_ASSERT(holder->IsObject()); v8::Local<v8::Object> holderObject = v8::Local<v8::Object>::Cast(holder); v8::Isolate* isolate = scriptState->isolate(); v8::Local<v8::Context> context = scriptState->context(); auto privateIsInitialized = V8PrivateProperty::getPrivateScriptRunnerIsInitialized(isolate); if (privateIsInitialized.hasValue(context, holderObject)) return; // Already initialized. v8::TryCatch block(isolate); v8::Local<v8::Value> initializeFunction; if (classObject->Get(scriptState->context(), v8String(isolate, "initialize")).ToLocal(&initializeFunction) && initializeFunction->IsFunction()) { v8::TryCatch block(isolate); v8::Local<v8::Value> result; if (!V8ScriptRunner::callFunction(v8::Local<v8::Function>::Cast(initializeFunction), scriptState->getExecutionContext(), holder, 0, 0, isolate).ToLocal(&result)) { fprintf(stderr, "Private script error: Object constructor threw an exception.\n"); dumpV8Message(context, block.Message()); RELEASE_NOTREACHED(); } } if (classObject->GetPrototype() != holderObject->GetPrototype()) { if (!v8CallBoolean(classObject->SetPrototype(context, holderObject->GetPrototype()))) { fprintf(stderr, "Private script error: SetPrototype failed.\n"); dumpV8Message(context, block.Message()); RELEASE_NOTREACHED(); } } if (!v8CallBoolean(holderObject->SetPrototype(context, classObject))) { fprintf(stderr, "Private script error: SetPrototype failed.\n"); dumpV8Message(context, block.Message()); RELEASE_NOTREACHED(); } privateIsInitialized.set(context, holderObject, v8Boolean(true, isolate)); } Commit Message: Blink-in-JS should not run micro tasks If Blink-in-JS runs micro tasks, there's a risk of causing a UXSS bug (see 645211 for concrete steps). This CL makes Blink-in-JS use callInternalFunction (instead of callFunction) to avoid running micro tasks after Blink-in-JS' callbacks. BUG=645211 Review-Url: https://codereview.chromium.org/2330843002 Cr-Commit-Position: refs/heads/master@{#417874} CWE ID: CWE-79
static void initializeHolderIfNeeded(ScriptState* scriptState, v8::Local<v8::Object> classObject, v8::Local<v8::Value> holder) { RELEASE_ASSERT(!holder.IsEmpty()); RELEASE_ASSERT(holder->IsObject()); v8::Local<v8::Object> holderObject = v8::Local<v8::Object>::Cast(holder); v8::Isolate* isolate = scriptState->isolate(); v8::Local<v8::Context> context = scriptState->context(); auto privateIsInitialized = V8PrivateProperty::getPrivateScriptRunnerIsInitialized(isolate); if (privateIsInitialized.hasValue(context, holderObject)) return; // Already initialized. v8::TryCatch block(isolate); v8::Local<v8::Value> initializeFunction; if (classObject->Get(scriptState->context(), v8String(isolate, "initialize")).ToLocal(&initializeFunction) && initializeFunction->IsFunction()) { v8::TryCatch block(isolate); v8::Local<v8::Value> result; if (!V8ScriptRunner::callInternalFunction(v8::Local<v8::Function>::Cast(initializeFunction), holder, 0, 0, isolate).ToLocal(&result)) { fprintf(stderr, "Private script error: Object constructor threw an exception.\n"); dumpV8Message(context, block.Message()); RELEASE_NOTREACHED(); } } if (classObject->GetPrototype() != holderObject->GetPrototype()) { if (!v8CallBoolean(classObject->SetPrototype(context, holderObject->GetPrototype()))) { fprintf(stderr, "Private script error: SetPrototype failed.\n"); dumpV8Message(context, block.Message()); RELEASE_NOTREACHED(); } } if (!v8CallBoolean(holderObject->SetPrototype(context, classObject))) { fprintf(stderr, "Private script error: SetPrototype failed.\n"); dumpV8Message(context, block.Message()); RELEASE_NOTREACHED(); } privateIsInitialized.set(context, holderObject, v8Boolean(true, isolate)); }
172,074
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderThreadImpl::Shutdown() { FOR_EACH_OBSERVER( RenderProcessObserver, observers_, OnRenderProcessShutdown()); ChildThread::Shutdown(); if (memory_observer_) { message_loop()->RemoveTaskObserver(memory_observer_.get()); memory_observer_.reset(); } if (webkit_platform_support_) { webkit_platform_support_->web_database_observer_impl()-> WaitForAllDatabasesToClose(); } if (devtools_agent_message_filter_.get()) { RemoveFilter(devtools_agent_message_filter_.get()); devtools_agent_message_filter_ = NULL; } RemoveFilter(audio_input_message_filter_.get()); audio_input_message_filter_ = NULL; RemoveFilter(audio_message_filter_.get()); audio_message_filter_ = NULL; #if defined(ENABLE_WEBRTC) RTCPeerConnectionHandler::DestructAllHandlers(); peer_connection_factory_.reset(); #endif RemoveFilter(vc_manager_->video_capture_message_filter()); vc_manager_.reset(); RemoveFilter(db_message_filter_.get()); db_message_filter_ = NULL; if (file_thread_) file_thread_->Stop(); if (compositor_output_surface_filter_.get()) { RemoveFilter(compositor_output_surface_filter_.get()); compositor_output_surface_filter_ = NULL; } media_thread_.reset(); compositor_thread_.reset(); input_handler_manager_.reset(); if (input_event_filter_.get()) { RemoveFilter(input_event_filter_.get()); input_event_filter_ = NULL; } embedded_worker_dispatcher_.reset(); main_thread_indexed_db_dispatcher_.reset(); if (webkit_platform_support_) blink::shutdown(); lazy_tls.Pointer()->Set(NULL); #if defined(OS_WIN) NPChannelBase::CleanupChannels(); #endif } Commit Message: Suspend shared timers while blockingly closing databases BUG=388771 [email protected] Review URL: https://codereview.chromium.org/409863002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@284785 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void RenderThreadImpl::Shutdown() { FOR_EACH_OBSERVER( RenderProcessObserver, observers_, OnRenderProcessShutdown()); ChildThread::Shutdown(); if (memory_observer_) { message_loop()->RemoveTaskObserver(memory_observer_.get()); memory_observer_.reset(); } if (webkit_platform_support_) { // WaitForAllDatabasesToClose might run a nested message loop. To avoid // processing timer events while we're already in the process of shutting // down blink, put a ScopePageLoadDeferrer on the stack. WebView::willEnterModalLoop(); webkit_platform_support_->web_database_observer_impl()-> WaitForAllDatabasesToClose(); WebView::didExitModalLoop(); } if (devtools_agent_message_filter_.get()) { RemoveFilter(devtools_agent_message_filter_.get()); devtools_agent_message_filter_ = NULL; } RemoveFilter(audio_input_message_filter_.get()); audio_input_message_filter_ = NULL; RemoveFilter(audio_message_filter_.get()); audio_message_filter_ = NULL; #if defined(ENABLE_WEBRTC) RTCPeerConnectionHandler::DestructAllHandlers(); peer_connection_factory_.reset(); #endif RemoveFilter(vc_manager_->video_capture_message_filter()); vc_manager_.reset(); RemoveFilter(db_message_filter_.get()); db_message_filter_ = NULL; if (file_thread_) file_thread_->Stop(); if (compositor_output_surface_filter_.get()) { RemoveFilter(compositor_output_surface_filter_.get()); compositor_output_surface_filter_ = NULL; } media_thread_.reset(); compositor_thread_.reset(); input_handler_manager_.reset(); if (input_event_filter_.get()) { RemoveFilter(input_event_filter_.get()); input_event_filter_ = NULL; } embedded_worker_dispatcher_.reset(); main_thread_indexed_db_dispatcher_.reset(); if (webkit_platform_support_) blink::shutdown(); lazy_tls.Pointer()->Set(NULL); #if defined(OS_WIN) NPChannelBase::CleanupChannels(); #endif }
171,176
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: jas_matrix_t *jas_seq2d_input(FILE *in) { jas_matrix_t *matrix; int i; int j; long x; int numrows; int numcols; int xoff; int yoff; if (fscanf(in, "%d %d", &xoff, &yoff) != 2) return 0; if (fscanf(in, "%d %d", &numcols, &numrows) != 2) return 0; if (!(matrix = jas_seq2d_create(xoff, yoff, xoff + numcols, yoff + numrows))) return 0; if (jas_matrix_numrows(matrix) != numrows || jas_matrix_numcols(matrix) != numcols) { abort(); } /* Get matrix data. */ for (i = 0; i < jas_matrix_numrows(matrix); i++) { for (j = 0; j < jas_matrix_numcols(matrix); j++) { if (fscanf(in, "%ld", &x) != 1) { jas_matrix_destroy(matrix); return 0; } jas_matrix_set(matrix, i, j, JAS_CAST(jas_seqent_t, x)); } } return matrix; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190
jas_matrix_t *jas_seq2d_input(FILE *in) { jas_matrix_t *matrix; jas_matind_t i; jas_matind_t j; long x; jas_matind_t numrows; jas_matind_t numcols; jas_matind_t xoff; jas_matind_t yoff; long tmp_xoff; long tmp_yoff; long tmp_numrows; long tmp_numcols; if (fscanf(in, "%ld %ld", &tmp_xoff, &tmp_yoff) != 2) { return 0; } xoff = tmp_xoff; yoff = tmp_yoff; if (fscanf(in, "%ld %ld", &tmp_numcols, &tmp_numrows) != 2) { return 0; } numrows = tmp_numrows; numcols = tmp_numcols; if (!(matrix = jas_seq2d_create(xoff, yoff, xoff + numcols, yoff + numrows))) { return 0; } if (jas_matrix_numrows(matrix) != numrows || jas_matrix_numcols(matrix) != numcols) { abort(); } /* Get matrix data. */ for (i = 0; i < jas_matrix_numrows(matrix); i++) { for (j = 0; j < jas_matrix_numcols(matrix); j++) { if (fscanf(in, "%ld", &x) != 1) { jas_matrix_destroy(matrix); return 0; } jas_matrix_set(matrix, i, j, JAS_CAST(jas_seqent_t, x)); } } return matrix; }
168,710
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: main(const int argc, const char * const * const argv) { /* For each file on the command line test it with a range of transforms */ int option_end, ilog = 0; struct display d; validate_T(); display_init(&d); for (option_end=1; option_end<argc; ++option_end) { const char *name = argv[option_end]; if (strcmp(name, "--verbose") == 0) d.options = (d.options & ~LEVEL_MASK) | VERBOSE; else if (strcmp(name, "--warnings") == 0) d.options = (d.options & ~LEVEL_MASK) | WARNINGS; else if (strcmp(name, "--errors") == 0) d.options = (d.options & ~LEVEL_MASK) | ERRORS; else if (strcmp(name, "--quiet") == 0) d.options = (d.options & ~LEVEL_MASK) | QUIET; else if (strcmp(name, "--exhaustive") == 0) d.options |= EXHAUSTIVE; else if (strcmp(name, "--fast") == 0) d.options &= ~EXHAUSTIVE; else if (strcmp(name, "--strict") == 0) d.options |= STRICT; else if (strcmp(name, "--relaxed") == 0) d.options &= ~STRICT; else if (strcmp(name, "--log") == 0) { ilog = option_end; /* prevent display */ d.options |= LOG; } else if (strcmp(name, "--nolog") == 0) d.options &= ~LOG; else if (strcmp(name, "--continue") == 0) d.options |= CONTINUE; else if (strcmp(name, "--stop") == 0) d.options &= ~CONTINUE; else if (strcmp(name, "--skip-bugs") == 0) d.options |= SKIP_BUGS; else if (strcmp(name, "--test-all") == 0) d.options &= ~SKIP_BUGS; else if (strcmp(name, "--log-skipped") == 0) d.options |= LOG_SKIPPED; else if (strcmp(name, "--nolog-skipped") == 0) d.options &= ~LOG_SKIPPED; else if (strcmp(name, "--find-bad-combos") == 0) d.options |= FIND_BAD_COMBOS; else if (strcmp(name, "--nofind-bad-combos") == 0) d.options &= ~FIND_BAD_COMBOS; else if (name[0] == '-' && name[1] == '-') { fprintf(stderr, "pngimage: %s: unknown option\n", name); return 99; } else break; /* Not an option */ } { int i; int errors = 0; for (i=option_end; i<argc; ++i) { { int ret = do_test(&d, argv[i]); if (ret > QUIET) /* abort on user or internal error */ return 99; } /* Here on any return, including failures, except user/internal issues */ { const int pass = (d.options & STRICT) ? RESULT_STRICT(d.results) : RESULT_RELAXED(d.results); if (!pass) ++errors; if (d.options & LOG) { int j; printf("%s: pngimage ", pass ? "PASS" : "FAIL"); for (j=1; j<option_end; ++j) if (j != ilog) printf("%s ", argv[j]); printf("%s\n", d.filename); } } display_clean(&d); } return errors != 0; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
main(const int argc, const char * const * const argv) { /* For each file on the command line test it with a range of transforms */ int option_end, ilog = 0; struct display d; validate_T(); display_init(&d); for (option_end=1; option_end<argc; ++option_end) { const char *name = argv[option_end]; if (strcmp(name, "--verbose") == 0) d.options = (d.options & ~LEVEL_MASK) | VERBOSE; else if (strcmp(name, "--warnings") == 0) d.options = (d.options & ~LEVEL_MASK) | WARNINGS; else if (strcmp(name, "--errors") == 0) d.options = (d.options & ~LEVEL_MASK) | ERRORS; else if (strcmp(name, "--quiet") == 0) d.options = (d.options & ~LEVEL_MASK) | QUIET; else if (strcmp(name, "--exhaustive") == 0) d.options |= EXHAUSTIVE; else if (strcmp(name, "--fast") == 0) d.options &= ~EXHAUSTIVE; else if (strcmp(name, "--strict") == 0) d.options |= STRICT; else if (strcmp(name, "--relaxed") == 0) d.options &= ~STRICT; else if (strcmp(name, "--log") == 0) { ilog = option_end; /* prevent display */ d.options |= LOG; } else if (strcmp(name, "--nolog") == 0) d.options &= ~LOG; else if (strcmp(name, "--continue") == 0) d.options |= CONTINUE; else if (strcmp(name, "--stop") == 0) d.options &= ~CONTINUE; else if (strcmp(name, "--skip-bugs") == 0) d.options |= SKIP_BUGS; else if (strcmp(name, "--test-all") == 0) d.options &= ~SKIP_BUGS; else if (strcmp(name, "--log-skipped") == 0) d.options |= LOG_SKIPPED; else if (strcmp(name, "--nolog-skipped") == 0) d.options &= ~LOG_SKIPPED; else if (strcmp(name, "--find-bad-combos") == 0) d.options |= FIND_BAD_COMBOS; else if (strcmp(name, "--nofind-bad-combos") == 0) d.options &= ~FIND_BAD_COMBOS; else if (strcmp(name, "--list-combos") == 0) d.options |= LIST_COMBOS; else if (strcmp(name, "--nolist-combos") == 0) d.options &= ~LIST_COMBOS; else if (name[0] == '-' && name[1] == '-') { fprintf(stderr, "pngimage: %s: unknown option\n", name); return 99; } else break; /* Not an option */ } { int i; int errors = 0; for (i=option_end; i<argc; ++i) { { int ret = do_test(&d, argv[i]); if (ret > QUIET) /* abort on user or internal error */ return 99; } /* Here on any return, including failures, except user/internal issues */ { const int pass = (d.options & STRICT) ? RESULT_STRICT(d.results) : RESULT_RELAXED(d.results); if (!pass) ++errors; if (d.options & LOG) { int j; printf("%s: pngimage ", pass ? "PASS" : "FAIL"); for (j=1; j<option_end; ++j) if (j != ilog) printf("%s ", argv[j]); printf("%s\n", d.filename); } } display_clean(&d); } /* Release allocated memory */ display_destroy(&d); return errors != 0; } }
173,589
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: check_compat_entry_size_and_hooks(struct compat_ipt_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ipt_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct ipt_entry *)e); if (ret) return ret; off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ip, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ipt_get_target(e); target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; } Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size Otherwise this function may read data beyond the ruleset blob. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-119
check_compat_entry_size_and_hooks(struct compat_ipt_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ipt_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct ipt_entry *)e); if (ret) return ret; off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ip, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ipt_get_target(e); target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; }
167,211
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ssh_packet_set_postauth(struct ssh *ssh) { struct sshcomp *comp; int r, mode; debug("%s: called", __func__); /* This was set in net child, but is not visible in user child */ ssh->state->after_authentication = 1; ssh->state->rekeying = 0; for (mode = 0; mode < MODE_MAX; mode++) { if (ssh->state->newkeys[mode] == NULL) continue; comp = &ssh->state->newkeys[mode]->comp; if (comp && comp->enabled && (r = ssh_packet_init_compression(ssh)) != 0) return r; } return 0; } Commit Message: Remove support for pre-authentication compression. Doing compression early in the protocol probably seemed reasonable in the 1990s, but today it's clearly a bad idea in terms of both cryptography (cf. multiple compression oracle attacks in TLS) and attack surface. Moreover, to support it across privilege-separation zlib needed the assistance of a complex shared-memory manager that made the required attack surface considerably larger. Prompted by Guido Vranken pointing out a compiler-elided security check in the shared memory manager found by Stack (http://css.csail.mit.edu/stack/); ok deraadt@ markus@ NB. pre-auth authentication has been disabled by default in sshd for >10 years. CWE ID: CWE-119
ssh_packet_set_postauth(struct ssh *ssh) { int r; debug("%s: called", __func__); /* This was set in net child, but is not visible in user child */ ssh->state->after_authentication = 1; ssh->state->rekeying = 0; if ((r = ssh_packet_enable_delayed_compress(ssh)) != 0) return r; return 0; }
168,655
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static M_bool M_fs_check_overwrite_allowed(const char *p1, const char *p2, M_uint32 mode) { M_fs_info_t *info = NULL; char *pold = NULL; char *pnew = NULL; M_fs_type_t type; M_bool ret = M_TRUE; if (mode & M_FS_FILE_MODE_OVERWRITE) return M_TRUE; /* If we're not overwriting we need to verify existance. * * For files we need to check if the file name exists in the * directory it's being copied to. * * For directories we need to check if the directory name * exists in the directory it's being copied to. */ if (M_fs_info(&info, p1, M_FS_PATH_INFO_FLAGS_BASIC) != M_FS_ERROR_SUCCESS) return M_FALSE; type = M_fs_info_get_type(info); M_fs_info_destroy(info); if (type != M_FS_TYPE_DIR) { /* File exists at path. */ if (M_fs_perms_can_access(p2, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) { ret = M_FALSE; goto done; } } /* Is dir */ pold = M_fs_path_basename(p1, M_FS_SYSTEM_AUTO); pnew = M_fs_path_join(p2, pnew, M_FS_SYSTEM_AUTO); if (M_fs_perms_can_access(pnew, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) { ret = M_FALSE; goto done; } done: M_free(pnew); M_free(pold); return ret; } Commit Message: fs: Don't try to delete the file when copying. It could cause a security issue if the file exists and doesn't allow other's to read/write. delete could allow someone to create the file and have access to the data. CWE ID: CWE-732
static M_bool M_fs_check_overwrite_allowed(const char *p1, const char *p2, M_uint32 mode) { M_fs_info_t *info = NULL; char *pold = NULL; char *pnew = NULL; M_fs_type_t type; M_bool ret = M_TRUE; if (mode & M_FS_FILE_MODE_OVERWRITE) return M_TRUE; /* If we're not overwriting we need to verify existance. * * For files we need to check if the file name exists in the * directory it's being copied to. * * For directories we need to check if the directory name * exists in the directory it's being copied to. */ if (M_fs_info(&info, p1, M_FS_PATH_INFO_FLAGS_BASIC) != M_FS_ERROR_SUCCESS) return M_FALSE; type = M_fs_info_get_type(info); M_fs_info_destroy(info); if (type != M_FS_TYPE_DIR) { /* File exists at path. */ if (M_fs_perms_can_access(p2, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) { ret = M_FALSE; goto done; } } /* Is dir */ pold = M_fs_path_basename(p1, M_FS_SYSTEM_AUTO); pnew = M_fs_path_join(p2, pnew, M_FS_SYSTEM_AUTO); if (M_fs_perms_can_access(pnew, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) { ret = M_FALSE; goto done; } done: M_free(pnew); M_free(pold); return ret; }
169,140
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: set_umask(const char *optarg) { long umask_long; mode_t umask_val; char *endptr; umask_long = strtoll(optarg, &endptr, 0); if (*endptr || umask_long < 0 || umask_long & ~0777L) { fprintf(stderr, "Invalid --umask option %s", optarg); return; } umask_val = umask_long & 0777; umask(umask_val); umask_cmdline = true; return umask_val; } Commit Message: Fix compile warning introduced in commit c6247a9 Commit c6247a9 - "Add command line and configuration option to set umask" introduced a compile warning, although the code would have worked OK. Signed-off-by: Quentin Armitage <[email protected]> CWE ID: CWE-200
set_umask(const char *optarg) { long umask_long; mode_t umask_val; char *endptr; umask_long = strtoll(optarg, &endptr, 0); if (*endptr || umask_long < 0 || umask_long & ~0777L) { fprintf(stderr, "Invalid --umask option %s", optarg); return 0; } umask_val = umask_long & 0777; umask(umask_val); umask_cmdline = true; return umask_val; }
170,158
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: MojoResult Core::WrapPlatformSharedBufferHandle( const MojoPlatformHandle* platform_handle, size_t size, const MojoSharedBufferGuid* guid, MojoPlatformSharedBufferHandleFlags flags, MojoHandle* mojo_handle) { DCHECK(size); ScopedPlatformHandle handle; MojoResult result = MojoPlatformHandleToScopedPlatformHandle(platform_handle, &handle); if (result != MOJO_RESULT_OK) return result; base::UnguessableToken token = base::UnguessableToken::Deserialize(guid->high, guid->low); bool read_only = flags & MOJO_PLATFORM_SHARED_BUFFER_HANDLE_FLAG_READ_ONLY; scoped_refptr<PlatformSharedBuffer> platform_buffer = PlatformSharedBuffer::CreateFromPlatformHandle(size, read_only, token, std::move(handle)); if (!platform_buffer) return MOJO_RESULT_UNKNOWN; scoped_refptr<SharedBufferDispatcher> dispatcher; result = SharedBufferDispatcher::CreateFromPlatformSharedBuffer( platform_buffer, &dispatcher); if (result != MOJO_RESULT_OK) return result; MojoHandle h = AddDispatcher(dispatcher); if (h == MOJO_HANDLE_INVALID) { dispatcher->Close(); return MOJO_RESULT_RESOURCE_EXHAUSTED; } *mojo_handle = h; return MOJO_RESULT_OK; } 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} CWE ID: CWE-787
MojoResult Core::WrapPlatformSharedBufferHandle( const MojoPlatformHandle* platform_handle, size_t size, const MojoSharedBufferGuid* guid, MojoPlatformSharedBufferHandleFlags flags, MojoHandle* mojo_handle) { DCHECK(size); ScopedPlatformHandle handle; MojoResult result = MojoPlatformHandleToScopedPlatformHandle(platform_handle, &handle); if (result != MOJO_RESULT_OK) return result; base::UnguessableToken token = base::UnguessableToken::Deserialize(guid->high, guid->low); const bool read_only = flags & MOJO_PLATFORM_SHARED_BUFFER_HANDLE_FLAG_HANDLE_IS_READ_ONLY; scoped_refptr<PlatformSharedBuffer> platform_buffer = PlatformSharedBuffer::CreateFromPlatformHandle(size, read_only, token, std::move(handle)); if (!platform_buffer) return MOJO_RESULT_UNKNOWN; scoped_refptr<SharedBufferDispatcher> dispatcher; result = SharedBufferDispatcher::CreateFromPlatformSharedBuffer( platform_buffer, &dispatcher); if (result != MOJO_RESULT_OK) return result; MojoHandle h = AddDispatcher(dispatcher); if (h == MOJO_HANDLE_INVALID) { dispatcher->Close(); return MOJO_RESULT_RESOURCE_EXHAUSTED; } *mojo_handle = h; return MOJO_RESULT_OK; }
172,883
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ih264d_parse_bslice(dec_struct_t * ps_dec, UWORD16 u2_first_mb_in_slice) { dec_pic_params_t * ps_pps = ps_dec->ps_cur_pps; dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; dec_bit_stream_t * ps_bitstrm = ps_dec->ps_bitstrm; UWORD8 u1_ref_idx_re_flag_lx; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; UWORD32 u4_temp, ui_temp1; WORD32 i_temp; WORD32 ret; /*--------------------------------------------------------------------*/ /* Read remaining contents of the slice header */ /*--------------------------------------------------------------------*/ { WORD8 *pi1_buf; WORD16 *pi2_mv = ps_dec->s_default_mv_pred.i2_mv; WORD32 *pi4_mv = (WORD32*)pi2_mv; WORD16 *pi16_refFrame; pi1_buf = ps_dec->s_default_mv_pred.i1_ref_frame; pi16_refFrame = (WORD16*)pi1_buf; *pi4_mv = 0; *(pi4_mv + 1) = 0; *pi16_refFrame = OUT_OF_RANGE_REF; ps_dec->s_default_mv_pred.u1_col_ref_pic_idx = (UWORD8)-1; ps_dec->s_default_mv_pred.u1_pic_type = (UWORD8)-1; } ps_slice->u1_num_ref_idx_active_override_flag = ih264d_get_bit_h264( ps_bitstrm); COPYTHECONTEXT("SH: num_ref_idx_override_flag", ps_slice->u1_num_ref_idx_active_override_flag); u4_temp = ps_dec->ps_cur_pps->u1_num_ref_idx_lx_active[0]; ui_temp1 = ps_dec->ps_cur_pps->u1_num_ref_idx_lx_active[1]; if(ps_slice->u1_num_ref_idx_active_override_flag) { u4_temp = 1 + ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SH: num_ref_idx_l0_active_minus1", u4_temp - 1); ui_temp1 = 1 + ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SH: num_ref_idx_l1_active_minus1", ui_temp1 - 1); } { UWORD8 u1_max_ref_idx = MAX_FRAMES; if(ps_slice->u1_field_pic_flag) { u1_max_ref_idx = MAX_FRAMES << 1; } if((u4_temp > u1_max_ref_idx) || (ui_temp1 > u1_max_ref_idx)) { return ERROR_NUM_REF; } ps_slice->u1_num_ref_idx_lx_active[0] = u4_temp; ps_slice->u1_num_ref_idx_lx_active[1] = ui_temp1; } /* Initialize the Reference list once in Picture if the slice type */ /* of first slice is between 5 to 9 defined in table 7.3 of standard */ /* If picture contains both P & B slices then Initialize the Reference*/ /* List only when it switches from P to B and B to P */ { UWORD8 init_idx_flg = (ps_dec->u1_pr_sl_type != ps_dec->ps_cur_slice->u1_slice_type); if(ps_dec->u1_first_pb_nal_in_pic || (init_idx_flg & !ps_dec->u1_sl_typ_5_9) || ps_dec->u1_num_ref_idx_lx_active_prev != ps_dec->ps_cur_slice->u1_num_ref_idx_lx_active[0]) ih264d_init_ref_idx_lx_b(ps_dec); if(ps_dec->u1_first_pb_nal_in_pic & ps_dec->u1_sl_typ_5_9) ps_dec->u1_first_pb_nal_in_pic = 0; } /* Store the value for future slices in the same picture */ ps_dec->u1_num_ref_idx_lx_active_prev = ps_dec->ps_cur_slice->u1_num_ref_idx_lx_active[0]; u1_ref_idx_re_flag_lx = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SH: ref_pic_list_reordering_flag_l0",u1_ref_idx_re_flag_lx); /* Modified temporarily */ if(u1_ref_idx_re_flag_lx) { WORD8 ret; ps_dec->ps_ref_pic_buf_lx[0] = ps_dec->ps_dpb_mgr->ps_mod_dpb[0]; ret = ih264d_ref_idx_reordering(ps_dec, 0); if(ret == -1) return ERROR_REFIDX_ORDER_T; } else ps_dec->ps_ref_pic_buf_lx[0] = ps_dec->ps_dpb_mgr->ps_init_dpb[0]; u1_ref_idx_re_flag_lx = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SH: ref_pic_list_reordering_flag_l1",u1_ref_idx_re_flag_lx); /* Modified temporarily */ if(u1_ref_idx_re_flag_lx) { WORD8 ret; ps_dec->ps_ref_pic_buf_lx[1] = ps_dec->ps_dpb_mgr->ps_mod_dpb[1]; ret = ih264d_ref_idx_reordering(ps_dec, 1); if(ret == -1) return ERROR_REFIDX_ORDER_T; } else ps_dec->ps_ref_pic_buf_lx[1] = ps_dec->ps_dpb_mgr->ps_init_dpb[1]; /* Create refIdx to POC mapping */ { void **ppv_map_ref_idx_to_poc_lx; WORD8 idx; struct pic_buffer_t *ps_pic; ppv_map_ref_idx_to_poc_lx = ps_dec->ppv_map_ref_idx_to_poc + FRM_LIST_L0; ppv_map_ref_idx_to_poc_lx[0] = 0; ppv_map_ref_idx_to_poc_lx++; for(idx = 0; idx < ps_dec->ps_cur_slice->u1_num_ref_idx_lx_active[0]; idx++) { ps_pic = ps_dec->ps_ref_pic_buf_lx[0][idx]; ppv_map_ref_idx_to_poc_lx[idx] = (ps_pic->pu1_buf1); } ppv_map_ref_idx_to_poc_lx = ps_dec->ppv_map_ref_idx_to_poc + FRM_LIST_L1; ppv_map_ref_idx_to_poc_lx[0] = 0; ppv_map_ref_idx_to_poc_lx++; for(idx = 0; idx < ps_dec->ps_cur_slice->u1_num_ref_idx_lx_active[1]; idx++) { ps_pic = ps_dec->ps_ref_pic_buf_lx[1][idx]; ppv_map_ref_idx_to_poc_lx[idx] = (ps_pic->pu1_buf1); } if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag) { void **ppv_map_ref_idx_to_poc_lx_t, **ppv_map_ref_idx_to_poc_lx_b; ppv_map_ref_idx_to_poc_lx_t = ps_dec->ppv_map_ref_idx_to_poc + TOP_LIST_FLD_L0; ppv_map_ref_idx_to_poc_lx_b = ps_dec->ppv_map_ref_idx_to_poc + BOT_LIST_FLD_L0; ppv_map_ref_idx_to_poc_lx_t[0] = 0; ppv_map_ref_idx_to_poc_lx_t++; ppv_map_ref_idx_to_poc_lx_b[0] = 0; ppv_map_ref_idx_to_poc_lx_b++; for(idx = 0; idx < ps_dec->ps_cur_slice->u1_num_ref_idx_lx_active[0]; idx++) { ps_pic = ps_dec->ps_ref_pic_buf_lx[0][idx]; ppv_map_ref_idx_to_poc_lx_t[0] = (ps_pic->pu1_buf1); ppv_map_ref_idx_to_poc_lx_b[1] = (ps_pic->pu1_buf1); ppv_map_ref_idx_to_poc_lx_b[0] = (ps_pic->pu1_buf1) + 1; ppv_map_ref_idx_to_poc_lx_t[1] = (ps_pic->pu1_buf1) + 1; ppv_map_ref_idx_to_poc_lx_t += 2; ppv_map_ref_idx_to_poc_lx_b += 2; } ppv_map_ref_idx_to_poc_lx_t = ps_dec->ppv_map_ref_idx_to_poc + TOP_LIST_FLD_L1; ppv_map_ref_idx_to_poc_lx_b = ps_dec->ppv_map_ref_idx_to_poc + BOT_LIST_FLD_L1; ppv_map_ref_idx_to_poc_lx_t[0] = 0; ppv_map_ref_idx_to_poc_lx_t++; ppv_map_ref_idx_to_poc_lx_b[0] = 0; ppv_map_ref_idx_to_poc_lx_b++; for(idx = 0; idx < ps_dec->ps_cur_slice->u1_num_ref_idx_lx_active[1]; idx++) { UWORD8 u1_tmp_idx = idx << 1; ps_pic = ps_dec->ps_ref_pic_buf_lx[1][idx]; ppv_map_ref_idx_to_poc_lx_t[u1_tmp_idx] = (ps_pic->pu1_buf1); ppv_map_ref_idx_to_poc_lx_b[u1_tmp_idx + 1] = (ps_pic->pu1_buf1); ppv_map_ref_idx_to_poc_lx_b[u1_tmp_idx] = (ps_pic->pu1_buf1) + 1; ppv_map_ref_idx_to_poc_lx_t[u1_tmp_idx + 1] = (ps_pic->pu1_buf1) + 1; } } if(ps_dec->u4_num_cores >= 3) { WORD32 num_entries; WORD32 size; num_entries = MIN(MAX_FRAMES, ps_dec->u4_num_ref_frames_at_init); num_entries = 2 * ((2 * num_entries) + 1); size = num_entries * sizeof(void *); size += PAD_MAP_IDX_POC * sizeof(void *); memcpy((void *)ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc, ps_dec->ppv_map_ref_idx_to_poc, size); } } if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag && (ps_dec->ps_cur_slice->u1_field_pic_flag == 0)) { ih264d_convert_frm_mbaff_list(ps_dec); } if(ps_pps->u1_wted_bipred_idc == 1) { ret = ih264d_parse_pred_weight_table(ps_slice, ps_bitstrm); if(ret != OK) return ret; ih264d_form_pred_weight_matrix(ps_dec); ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat; } else if(ps_pps->u1_wted_bipred_idc == 2) { /* Implicit Weighted prediction */ ps_slice->u2_log2Y_crwd = 0x0505; ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat; ih264d_get_implicit_weights(ps_dec); } else ps_dec->ps_cur_slice->u2_log2Y_crwd = 0; ps_dec->ps_parse_cur_slice->u2_log2Y_crwd = ps_dec->ps_cur_slice->u2_log2Y_crwd; /* G050 */ if(ps_slice->u1_nal_ref_idc != 0) { if(!ps_dec->ps_dpb_cmds->u1_dpb_commands_read) ps_dec->u4_bitoffset = ih264d_read_mmco_commands(ps_dec); else ps_bitstrm->u4_ofst += ps_dec->u4_bitoffset; } /* G050 */ if(ps_pps->u1_entropy_coding_mode == CABAC) { u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > MAX_CABAC_INIT_IDC) { return ERROR_INV_SLICE_HDR_T; } ps_slice->u1_cabac_init_idc = u4_temp; COPYTHECONTEXT("SH: cabac_init_idc",ps_slice->u1_cabac_init_idc); } /* Read slice_qp_delta */ i_temp = ps_pps->u1_pic_init_qp + ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if((i_temp < 0) || (i_temp > 51)) { return ERROR_INV_RANGE_QP_T; } ps_slice->u1_slice_qp = i_temp; COPYTHECONTEXT("SH: slice_qp_delta", (WORD8)(ps_slice->u1_slice_qp - ps_pps->u1_pic_init_qp)); if(ps_pps->u1_deblocking_filter_parameters_present_flag == 1) { u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > SLICE_BOUNDARY_DBLK_DISABLED) { return ERROR_INV_SLICE_HDR_T; } COPYTHECONTEXT("SH: disable_deblocking_filter_idc", u4_temp); ps_slice->u1_disable_dblk_filter_idc = u4_temp; if(u4_temp != 1) { i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf) << 1; if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF)) { return ERROR_INV_SLICE_HDR_T; } ps_slice->i1_slice_alpha_c0_offset = i_temp; COPYTHECONTEXT("SH: slice_alpha_c0_offset_div2", ps_slice->i1_slice_alpha_c0_offset >> 1); i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf) << 1; if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF)) { return ERROR_INV_SLICE_HDR_T; } ps_slice->i1_slice_beta_offset = i_temp; COPYTHECONTEXT("SH: slice_beta_offset_div2", ps_slice->i1_slice_beta_offset >> 1); } else { ps_slice->i1_slice_alpha_c0_offset = 0; ps_slice->i1_slice_beta_offset = 0; } } else { ps_slice->u1_disable_dblk_filter_idc = 0; ps_slice->i1_slice_alpha_c0_offset = 0; ps_slice->i1_slice_beta_offset = 0; } ps_dec->u1_slice_header_done = 2; if(ps_pps->u1_entropy_coding_mode) { SWITCHOFFTRACE; SWITCHONTRACECABAC; ps_dec->pf_parse_inter_slice = ih264d_parse_inter_slice_data_cabac; ps_dec->pf_parse_inter_mb = ih264d_parse_bmb_cabac; ih264d_init_cabac_contexts(B_SLICE, ps_dec); if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag) ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_mbaff; else ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_nonmbaff; } else { SWITCHONTRACE; SWITCHOFFTRACECABAC; ps_dec->pf_parse_inter_slice = ih264d_parse_inter_slice_data_cavlc; ps_dec->pf_parse_inter_mb = ih264d_parse_bmb_cavlc; if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag) ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_mbaff; else ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_nonmbaff; } ret = ih264d_cal_col_pic(ps_dec); if(ret != OK) return ret; ps_dec->u1_B = 1; ps_dec->pf_mvpred_ref_tfr_nby2mb = ih264d_mv_pred_ref_tfr_nby2_bmb; ret = ps_dec->pf_parse_inter_slice(ps_dec, ps_slice, u2_first_mb_in_slice); if(ret != OK) return ret; return OK; } Commit Message: Return error when there are more mmco params than allocated size Bug: 25818142 Change-Id: I5c1b23985eeca5192b42703c627ca3d060e4e13d CWE ID: CWE-119
WORD32 ih264d_parse_bslice(dec_struct_t * ps_dec, UWORD16 u2_first_mb_in_slice) { dec_pic_params_t * ps_pps = ps_dec->ps_cur_pps; dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; dec_bit_stream_t * ps_bitstrm = ps_dec->ps_bitstrm; UWORD8 u1_ref_idx_re_flag_lx; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; UWORD32 u4_temp, ui_temp1; WORD32 i_temp; WORD32 ret; /*--------------------------------------------------------------------*/ /* Read remaining contents of the slice header */ /*--------------------------------------------------------------------*/ { WORD8 *pi1_buf; WORD16 *pi2_mv = ps_dec->s_default_mv_pred.i2_mv; WORD32 *pi4_mv = (WORD32*)pi2_mv; WORD16 *pi16_refFrame; pi1_buf = ps_dec->s_default_mv_pred.i1_ref_frame; pi16_refFrame = (WORD16*)pi1_buf; *pi4_mv = 0; *(pi4_mv + 1) = 0; *pi16_refFrame = OUT_OF_RANGE_REF; ps_dec->s_default_mv_pred.u1_col_ref_pic_idx = (UWORD8)-1; ps_dec->s_default_mv_pred.u1_pic_type = (UWORD8)-1; } ps_slice->u1_num_ref_idx_active_override_flag = ih264d_get_bit_h264( ps_bitstrm); COPYTHECONTEXT("SH: num_ref_idx_override_flag", ps_slice->u1_num_ref_idx_active_override_flag); u4_temp = ps_dec->ps_cur_pps->u1_num_ref_idx_lx_active[0]; ui_temp1 = ps_dec->ps_cur_pps->u1_num_ref_idx_lx_active[1]; if(ps_slice->u1_num_ref_idx_active_override_flag) { u4_temp = 1 + ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SH: num_ref_idx_l0_active_minus1", u4_temp - 1); ui_temp1 = 1 + ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SH: num_ref_idx_l1_active_minus1", ui_temp1 - 1); } { UWORD8 u1_max_ref_idx = MAX_FRAMES; if(ps_slice->u1_field_pic_flag) { u1_max_ref_idx = MAX_FRAMES << 1; } if((u4_temp > u1_max_ref_idx) || (ui_temp1 > u1_max_ref_idx)) { return ERROR_NUM_REF; } ps_slice->u1_num_ref_idx_lx_active[0] = u4_temp; ps_slice->u1_num_ref_idx_lx_active[1] = ui_temp1; } /* Initialize the Reference list once in Picture if the slice type */ /* of first slice is between 5 to 9 defined in table 7.3 of standard */ /* If picture contains both P & B slices then Initialize the Reference*/ /* List only when it switches from P to B and B to P */ { UWORD8 init_idx_flg = (ps_dec->u1_pr_sl_type != ps_dec->ps_cur_slice->u1_slice_type); if(ps_dec->u1_first_pb_nal_in_pic || (init_idx_flg & !ps_dec->u1_sl_typ_5_9) || ps_dec->u1_num_ref_idx_lx_active_prev != ps_dec->ps_cur_slice->u1_num_ref_idx_lx_active[0]) ih264d_init_ref_idx_lx_b(ps_dec); if(ps_dec->u1_first_pb_nal_in_pic & ps_dec->u1_sl_typ_5_9) ps_dec->u1_first_pb_nal_in_pic = 0; } /* Store the value for future slices in the same picture */ ps_dec->u1_num_ref_idx_lx_active_prev = ps_dec->ps_cur_slice->u1_num_ref_idx_lx_active[0]; u1_ref_idx_re_flag_lx = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SH: ref_pic_list_reordering_flag_l0",u1_ref_idx_re_flag_lx); /* Modified temporarily */ if(u1_ref_idx_re_flag_lx) { WORD8 ret; ps_dec->ps_ref_pic_buf_lx[0] = ps_dec->ps_dpb_mgr->ps_mod_dpb[0]; ret = ih264d_ref_idx_reordering(ps_dec, 0); if(ret == -1) return ERROR_REFIDX_ORDER_T; } else ps_dec->ps_ref_pic_buf_lx[0] = ps_dec->ps_dpb_mgr->ps_init_dpb[0]; u1_ref_idx_re_flag_lx = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SH: ref_pic_list_reordering_flag_l1",u1_ref_idx_re_flag_lx); /* Modified temporarily */ if(u1_ref_idx_re_flag_lx) { WORD8 ret; ps_dec->ps_ref_pic_buf_lx[1] = ps_dec->ps_dpb_mgr->ps_mod_dpb[1]; ret = ih264d_ref_idx_reordering(ps_dec, 1); if(ret == -1) return ERROR_REFIDX_ORDER_T; } else ps_dec->ps_ref_pic_buf_lx[1] = ps_dec->ps_dpb_mgr->ps_init_dpb[1]; /* Create refIdx to POC mapping */ { void **ppv_map_ref_idx_to_poc_lx; WORD8 idx; struct pic_buffer_t *ps_pic; ppv_map_ref_idx_to_poc_lx = ps_dec->ppv_map_ref_idx_to_poc + FRM_LIST_L0; ppv_map_ref_idx_to_poc_lx[0] = 0; ppv_map_ref_idx_to_poc_lx++; for(idx = 0; idx < ps_dec->ps_cur_slice->u1_num_ref_idx_lx_active[0]; idx++) { ps_pic = ps_dec->ps_ref_pic_buf_lx[0][idx]; ppv_map_ref_idx_to_poc_lx[idx] = (ps_pic->pu1_buf1); } ppv_map_ref_idx_to_poc_lx = ps_dec->ppv_map_ref_idx_to_poc + FRM_LIST_L1; ppv_map_ref_idx_to_poc_lx[0] = 0; ppv_map_ref_idx_to_poc_lx++; for(idx = 0; idx < ps_dec->ps_cur_slice->u1_num_ref_idx_lx_active[1]; idx++) { ps_pic = ps_dec->ps_ref_pic_buf_lx[1][idx]; ppv_map_ref_idx_to_poc_lx[idx] = (ps_pic->pu1_buf1); } if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag) { void **ppv_map_ref_idx_to_poc_lx_t, **ppv_map_ref_idx_to_poc_lx_b; ppv_map_ref_idx_to_poc_lx_t = ps_dec->ppv_map_ref_idx_to_poc + TOP_LIST_FLD_L0; ppv_map_ref_idx_to_poc_lx_b = ps_dec->ppv_map_ref_idx_to_poc + BOT_LIST_FLD_L0; ppv_map_ref_idx_to_poc_lx_t[0] = 0; ppv_map_ref_idx_to_poc_lx_t++; ppv_map_ref_idx_to_poc_lx_b[0] = 0; ppv_map_ref_idx_to_poc_lx_b++; for(idx = 0; idx < ps_dec->ps_cur_slice->u1_num_ref_idx_lx_active[0]; idx++) { ps_pic = ps_dec->ps_ref_pic_buf_lx[0][idx]; ppv_map_ref_idx_to_poc_lx_t[0] = (ps_pic->pu1_buf1); ppv_map_ref_idx_to_poc_lx_b[1] = (ps_pic->pu1_buf1); ppv_map_ref_idx_to_poc_lx_b[0] = (ps_pic->pu1_buf1) + 1; ppv_map_ref_idx_to_poc_lx_t[1] = (ps_pic->pu1_buf1) + 1; ppv_map_ref_idx_to_poc_lx_t += 2; ppv_map_ref_idx_to_poc_lx_b += 2; } ppv_map_ref_idx_to_poc_lx_t = ps_dec->ppv_map_ref_idx_to_poc + TOP_LIST_FLD_L1; ppv_map_ref_idx_to_poc_lx_b = ps_dec->ppv_map_ref_idx_to_poc + BOT_LIST_FLD_L1; ppv_map_ref_idx_to_poc_lx_t[0] = 0; ppv_map_ref_idx_to_poc_lx_t++; ppv_map_ref_idx_to_poc_lx_b[0] = 0; ppv_map_ref_idx_to_poc_lx_b++; for(idx = 0; idx < ps_dec->ps_cur_slice->u1_num_ref_idx_lx_active[1]; idx++) { UWORD8 u1_tmp_idx = idx << 1; ps_pic = ps_dec->ps_ref_pic_buf_lx[1][idx]; ppv_map_ref_idx_to_poc_lx_t[u1_tmp_idx] = (ps_pic->pu1_buf1); ppv_map_ref_idx_to_poc_lx_b[u1_tmp_idx + 1] = (ps_pic->pu1_buf1); ppv_map_ref_idx_to_poc_lx_b[u1_tmp_idx] = (ps_pic->pu1_buf1) + 1; ppv_map_ref_idx_to_poc_lx_t[u1_tmp_idx + 1] = (ps_pic->pu1_buf1) + 1; } } if(ps_dec->u4_num_cores >= 3) { WORD32 num_entries; WORD32 size; num_entries = MIN(MAX_FRAMES, ps_dec->u4_num_ref_frames_at_init); num_entries = 2 * ((2 * num_entries) + 1); size = num_entries * sizeof(void *); size += PAD_MAP_IDX_POC * sizeof(void *); memcpy((void *)ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc, ps_dec->ppv_map_ref_idx_to_poc, size); } } if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag && (ps_dec->ps_cur_slice->u1_field_pic_flag == 0)) { ih264d_convert_frm_mbaff_list(ps_dec); } if(ps_pps->u1_wted_bipred_idc == 1) { ret = ih264d_parse_pred_weight_table(ps_slice, ps_bitstrm); if(ret != OK) return ret; ih264d_form_pred_weight_matrix(ps_dec); ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat; } else if(ps_pps->u1_wted_bipred_idc == 2) { /* Implicit Weighted prediction */ ps_slice->u2_log2Y_crwd = 0x0505; ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat; ih264d_get_implicit_weights(ps_dec); } else ps_dec->ps_cur_slice->u2_log2Y_crwd = 0; ps_dec->ps_parse_cur_slice->u2_log2Y_crwd = ps_dec->ps_cur_slice->u2_log2Y_crwd; /* G050 */ if(ps_slice->u1_nal_ref_idc != 0) { if(!ps_dec->ps_dpb_cmds->u1_dpb_commands_read) { i_temp = ih264d_read_mmco_commands(ps_dec); if (i_temp < 0) { return ERROR_DBP_MANAGER_T; } ps_dec->u4_bitoffset = i_temp; } else ps_bitstrm->u4_ofst += ps_dec->u4_bitoffset; } /* G050 */ if(ps_pps->u1_entropy_coding_mode == CABAC) { u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > MAX_CABAC_INIT_IDC) { return ERROR_INV_SLICE_HDR_T; } ps_slice->u1_cabac_init_idc = u4_temp; COPYTHECONTEXT("SH: cabac_init_idc",ps_slice->u1_cabac_init_idc); } /* Read slice_qp_delta */ i_temp = ps_pps->u1_pic_init_qp + ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if((i_temp < 0) || (i_temp > 51)) { return ERROR_INV_RANGE_QP_T; } ps_slice->u1_slice_qp = i_temp; COPYTHECONTEXT("SH: slice_qp_delta", (WORD8)(ps_slice->u1_slice_qp - ps_pps->u1_pic_init_qp)); if(ps_pps->u1_deblocking_filter_parameters_present_flag == 1) { u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > SLICE_BOUNDARY_DBLK_DISABLED) { return ERROR_INV_SLICE_HDR_T; } COPYTHECONTEXT("SH: disable_deblocking_filter_idc", u4_temp); ps_slice->u1_disable_dblk_filter_idc = u4_temp; if(u4_temp != 1) { i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf) << 1; if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF)) { return ERROR_INV_SLICE_HDR_T; } ps_slice->i1_slice_alpha_c0_offset = i_temp; COPYTHECONTEXT("SH: slice_alpha_c0_offset_div2", ps_slice->i1_slice_alpha_c0_offset >> 1); i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf) << 1; if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF)) { return ERROR_INV_SLICE_HDR_T; } ps_slice->i1_slice_beta_offset = i_temp; COPYTHECONTEXT("SH: slice_beta_offset_div2", ps_slice->i1_slice_beta_offset >> 1); } else { ps_slice->i1_slice_alpha_c0_offset = 0; ps_slice->i1_slice_beta_offset = 0; } } else { ps_slice->u1_disable_dblk_filter_idc = 0; ps_slice->i1_slice_alpha_c0_offset = 0; ps_slice->i1_slice_beta_offset = 0; } ps_dec->u1_slice_header_done = 2; if(ps_pps->u1_entropy_coding_mode) { SWITCHOFFTRACE; SWITCHONTRACECABAC; ps_dec->pf_parse_inter_slice = ih264d_parse_inter_slice_data_cabac; ps_dec->pf_parse_inter_mb = ih264d_parse_bmb_cabac; ih264d_init_cabac_contexts(B_SLICE, ps_dec); if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag) ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_mbaff; else ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_nonmbaff; } else { SWITCHONTRACE; SWITCHOFFTRACECABAC; ps_dec->pf_parse_inter_slice = ih264d_parse_inter_slice_data_cavlc; ps_dec->pf_parse_inter_mb = ih264d_parse_bmb_cavlc; if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag) ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_mbaff; else ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_nonmbaff; } ret = ih264d_cal_col_pic(ps_dec); if(ret != OK) return ret; ps_dec->u1_B = 1; ps_dec->pf_mvpred_ref_tfr_nby2mb = ih264d_mv_pred_ref_tfr_nby2_bmb; ret = ps_dec->pf_parse_inter_slice(ps_dec, ps_slice, u2_first_mb_in_slice); if(ret != OK) return ret; return OK; }
173,908
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: parse_wbxml_tag_defined (proto_tree *tree, tvbuff_t *tvb, guint32 offset, guint32 str_tbl, guint8 *level, guint8 *codepage_stag, guint8 *codepage_attr, const wbxml_decoding *map) { guint32 tvb_len = tvb_reported_length (tvb); guint32 off = offset; guint32 len; guint str_len; guint32 ent; guint32 idx; guint8 peek; guint32 tag_len; /* Length of the index (uintvar) from a LITERAL tag */ guint8 tag_save_known = 0; /* Will contain peek & 0x3F (tag identity) */ guint8 tag_new_known = 0; /* Will contain peek & 0x3F (tag identity) */ const char *tag_save_literal; /* Will contain the LITERAL tag identity */ const char *tag_new_literal; /* Will contain the LITERAL tag identity */ guint8 parsing_tag_content = FALSE; /* Are we parsing content from a tag with content: <x>Content</x> The initial state is FALSE. This state will trigger recursion. */ tag_save_literal = NULL; /* Prevents compiler warning */ DebugLog(("parse_wbxml_tag_defined (level = %u, offset = %u)\n", *level, offset)); while (off < tvb_len) { peek = tvb_get_guint8 (tvb, off); DebugLog(("STAG: (top of while) level = %3u, peek = 0x%02X, off = %u, tvb_len = %u\n", *level, peek, off, tvb_len)); if ((peek & 0x3F) < 4) switch (peek) { /* Global tokens in state = STAG but not the LITERAL tokens */ case 0x00: /* SWITCH_PAGE */ *codepage_stag = tvb_get_guint8 (tvb, off+1); proto_tree_add_text (tree, tvb, off, 2, " | Tag | T -->%3d " "| SWITCH_PAGE (Tag code page) " "|", *codepage_stag); off += 2; break; case 0x01: /* END: only possible for Tag with Content */ if (tag_save_known) { /* Known TAG */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| END (Known Tag 0x%02X) " "| %s</%s>", *level, *codepage_stag, tag_save_known, Indent (*level), tag_save_literal); /* We already looked it up! */ } else { /* Literal TAG */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| END (Literal Tag) " "| %s</%s>", *level, *codepage_stag, Indent (*level), tag_save_literal ? tag_save_literal : ""); } (*level)--; off++; /* Reset code page: not needed as return from recursion */ DebugLog(("STAG: 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 | Tag | T %3d " "| ENTITY " "| %s'&#%u;'", *level, *codepage_stag, 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 | Tag | T %3d " "| STR_I (Inline string) " "| %s\'%s\'", *level, *codepage_stag, Indent(*level), tvb_format_text (tvb, off+1, 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 | Tag | T %3d " "| EXT_I_%1x (Extension Token) " "| %s(%s: \'%s\')", *level, *codepage_stag, peek & 0x0f, Indent (*level), map_token (map->global, 0, peek), tvb_format_text (tvb, off+1, len-1)); off += 1+len; break; case 0x43: /* PI */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| PI (XML Processing Instruction) " "| %s<?xml", *level, *codepage_stag, Indent (*level)); len = parse_wbxml_attribute_list_defined (tree, tvb, off, str_tbl, *level, codepage_attr, map); /* Check that there is still room in packet */ off += len; if (off >= tvb_len) { DebugLog(("STAG: level = %u, ThrowException: len = %u (short frame)\n", *level, off - offset)); /* * TODO - Do we need to free g_malloc()ed memory? */ THROW(ReportedBoundsError); } proto_tree_add_text (tree, tvb, off-1, 1, " %3d | Tag | T %3d " "| END (PI) " "| %s?>", *level, *codepage_stag, Indent (*level)); break; 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); { char *s; if (map->ext_t[peek & 0x03]) s = (map->ext_t[peek & 0x03])(tvb, idx, str_tbl); else s = wmem_strdup_printf(wmem_packet_scope(), "EXT_T_%1x (%s)", peek & 0x03, map_token (map->global, 0, peek)); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Tag | T %3d " "| EXT_T_%1x (Extension Token) " "| %s%s", *level, *codepage_stag, peek & 0x0f, Indent (*level), s); } 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 | Tag | T %3d " "| STR_T (Tableref string) " "| %s\'%s\'", *level, *codepage_stag, Indent (*level), tvb_format_text (tvb, str_tbl+idx, str_len-1)); off += 1+len; break; case 0xC0: /* EXT_0 */ case 0xC1: /* EXT_1 */ case 0xC2: /* EXT_2 */ /* Extension tokens */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| EXT_%1x (Extension Token) " "| %s(%s)", *level, *codepage_stag, peek & 0x0f, Indent (*level), map_token (map->global, 0, peek)); off++; break; case 0xC3: /* OPAQUE - WBXML 1.1 and newer */ if (tvb_get_guint8 (tvb, 0)) { /* WBXML 1.x (x > 0) */ char *str; if (tag_save_known) { /* Knwon tag */ if (map->opaque_binary_tag) { str = map->opaque_binary_tag(tvb, off + 1, tag_save_known, *codepage_stag, &len); } else { str = default_opaque_binary_tag(tvb, off + 1, tag_save_known, *codepage_stag, &len); } } else { /* lITERAL tag */ if (map->opaque_literal_tag) { str = map->opaque_literal_tag(tvb, off + 1, tag_save_literal, *codepage_stag, &len); } else { str = default_opaque_literal_tag(tvb, off + 1, tag_save_literal, *codepage_stag, &len); } } proto_tree_add_text (tree, tvb, off, 1 + len, " %3d | Tag | T %3d " "| OPAQUE (Opaque data) " "| %s%s", *level, *codepage_stag, Indent (*level), str); off += 1 + len; } else { /* WBXML 1.0 - RESERVED_2 token (invalid) */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| RESERVED_2 (Invalid Token!) " "| WBXML 1.0 parsing stops here.", *level, *codepage_stag); /* Stop processing as it is impossible to parse now */ off = tvb_len; DebugLog(("STAG: level = %u, Return: len = %u\n", *level, off - offset)); return (off - offset); } break; /* No default clause, as all cases have been treated */ } else { /* LITERAL or Known TAG */ /* We must store the initial tag, and also retrieve the new tag. * For efficiency reasons, we store the literal tag representation * for known tags too, so we can easily close the tag without the * need of a new lookup and avoiding storage of token codepage. * * There are 4 possibilities: * * 1. Known tag followed by a known tag * 2. Known tag followed by a LITERAL tag * 3. LITERAL tag followed by Known tag * 4. LITERAL tag followed by LITERAL tag */ /* Store the new tag */ tag_len = 0; if ((peek & 0x3F) == 4) { /* LITERAL */ DebugLog(("STAG: LITERAL tag (peek = 0x%02X, off = %u) - TableRef follows!\n", peek, off)); idx = tvb_get_guintvar (tvb, off+1, &tag_len); str_len = tvb_strsize (tvb, str_tbl+idx); tag_new_literal = (const gchar*)tvb_get_ptr (tvb, str_tbl+idx, str_len); tag_new_known = 0; /* invalidate known tag_new */ } else { /* Known tag */ tag_new_known = peek & 0x3F; tag_new_literal = map_token (map->tags, *codepage_stag, tag_new_known); /* Stored looked up tag name string */ } /* Parsing of TAG starts HERE */ if (peek & 0x40) { /* Content present */ /* Content follows * [!] An explicit END token is expected in these cases! * ==> Recursion possible if we encounter a tag with content; * recursion will return at the explicit END token. */ if (parsing_tag_content) { /* Recurse */ DebugLog(("STAG: Tag in Tag - RECURSE! (off = %u)\n", off)); /* Do not process the attribute list: * recursion will take care of it */ (*level)++; len = parse_wbxml_tag_defined (tree, tvb, off, str_tbl, level, codepage_stag, codepage_attr, map); off += len; } else { /* Now we will have content to parse */ /* Save the start tag so we can properly close it later. */ if ((peek & 0x3F) == 4) { /* Literal tag */ tag_save_literal = tag_new_literal; tag_save_known = 0; } else { /* Known tag */ tag_save_known = tag_new_known; tag_save_literal = tag_new_literal; /* The last statement avoids needless lookups */ } /* Process the attribute list if present */ if (peek & 0x80) { /* Content and Attribute list present */ if (tag_new_known) { /* Known tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| Known Tag 0x%02X (AC) " "| %s<%s", *level, *codepage_stag, tag_new_known, Indent (*level), tag_new_literal); /* Tag string already looked up earlier! */ off++; } else { /* LITERAL tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| LITERAL_AC (Literal tag) (AC) " "| %s<%s", *level, *codepage_stag, Indent (*level), tag_new_literal); off += 1 + tag_len; } len = parse_wbxml_attribute_list_defined (tree, tvb, off, str_tbl, *level, codepage_attr, map); /* Check that there is still room in packet */ off += len; if (off >= tvb_len) { DebugLog(("STAG: level = %u, ThrowException: len = %u (short frame)\n", *level, off - offset)); /* * TODO - Do we need to free g_malloc()ed memory? */ THROW(ReportedBoundsError); } proto_tree_add_text (tree, tvb, off-1, 1, " %3d | Tag | T %3d " "| END (attribute list) " "| %s>", *level, *codepage_stag, Indent (*level)); } else { /* Content, no Attribute list */ if (tag_new_known) { /* Known tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| Known Tag 0x%02X (.C) " "| %s<%s>", *level, *codepage_stag, tag_new_known, Indent (*level), tag_new_literal); /* Tag string already looked up earlier! */ off++; } else { /* LITERAL tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| LITERAL_C (Literal Tag) (.C) " "| %s<%s>", *level, *codepage_stag, Indent (*level), tag_new_literal); off += 1 + tag_len; } } /* The data that follows in the parsing process * represents content for the opening tag * we've just processed in the lines above. * Next time we encounter a tag with content: recurse */ parsing_tag_content = TRUE; DebugLog(("Tag in Tag - No recursion this time! (off = %u)\n", off)); } } else { /* No Content */ DebugLog(("<Tag/> in Tag - No recursion! (off = %u)\n", off)); (*level)++; if (peek & 0x80) { /* No Content, Attribute list present */ if (tag_new_known) { /* Known tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| Known Tag 0x%02X (A.) " "| %s<%s", *level, *codepage_stag, tag_new_known, Indent (*level), tag_new_literal); /* Tag string already looked up earlier! */ off++; len = parse_wbxml_attribute_list_defined (tree, tvb, off, str_tbl, *level, codepage_attr, map); /* Check that there is still room in packet */ off += len; if (off > tvb_len) { DebugLog(("STAG: level = %u, ThrowException: len = %u (short frame)\n", *level, off - offset)); /* * TODO - Do we need to free g_malloc()ed memory? */ THROW(ReportedBoundsError); } proto_tree_add_text (tree, tvb, off-1, 1, " %3d | Tag | T %3d " "| END (Known Tag) " "| %s/>", *level, *codepage_stag, Indent (*level)); } else { /* LITERAL tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| LITERAL_A (Literal Tag) (A.) " "| %s<%s", *level, *codepage_stag, Indent (*level), tag_new_literal); off += 1 + tag_len; len = parse_wbxml_attribute_list_defined (tree, tvb, off, str_tbl, *level, codepage_attr, map); /* Check that there is still room in packet */ off += len; if (off >= tvb_len) { DebugLog(("STAG: level = %u, ThrowException: len = %u (short frame)\n", *level, off - offset)); /* * TODO - Do we need to free g_malloc()ed memory? */ THROW(ReportedBoundsError); } proto_tree_add_text (tree, tvb, off-1, 1, " %3d | Tag | T %3d " "| END (Literal Tag) " "| %s/>", *level, *codepage_stag, Indent (*level)); } } else { /* No Content, No Attribute list */ if (tag_new_known) { /* Known tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| Known Tag 0x%02x (..) " "| %s<%s />", *level, *codepage_stag, tag_new_known, Indent (*level), tag_new_literal); /* Tag string already looked up earlier! */ off++; } else { /* LITERAL tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| LITERAL (Literal Tag) (..) " "| %s<%s />", *level, *codepage_stag, Indent (*level), tag_new_literal); off += 1 + tag_len; } } (*level)--; /* TODO: Do I have to reset code page here? */ } } /* if (tag & 0x3F) >= 5 */ } /* while */ DebugLog(("STAG: level = %u, Return: len = %u (end of function body)\n", *level, off - offset)); return (off - offset); } 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]> CWE ID: CWE-119
parse_wbxml_tag_defined (proto_tree *tree, tvbuff_t *tvb, guint32 offset, guint32 str_tbl, guint8 *level, guint8 *codepage_stag, guint8 *codepage_attr, const wbxml_decoding *map) { guint32 tvb_len = tvb_reported_length (tvb); guint32 off = offset, last_off; guint32 len; guint str_len; guint32 ent; guint32 idx; guint8 peek; guint32 tag_len; /* Length of the index (uintvar) from a LITERAL tag */ guint8 tag_save_known = 0; /* Will contain peek & 0x3F (tag identity) */ guint8 tag_new_known = 0; /* Will contain peek & 0x3F (tag identity) */ const char *tag_save_literal; /* Will contain the LITERAL tag identity */ const char *tag_new_literal; /* Will contain the LITERAL tag identity */ guint8 parsing_tag_content = FALSE; /* Are we parsing content from a tag with content: <x>Content</x> The initial state is FALSE. This state will trigger recursion. */ tag_save_literal = NULL; /* Prevents compiler warning */ DebugLog(("parse_wbxml_tag_defined (level = %u, offset = %u)\n", *level, offset)); last_off = off; while (off < tvb_len) { peek = tvb_get_guint8 (tvb, off); DebugLog(("STAG: (top of while) level = %3u, peek = 0x%02X, off = %u, tvb_len = %u\n", *level, peek, off, tvb_len)); if ((peek & 0x3F) < 4) switch (peek) { /* Global tokens in state = STAG but not the LITERAL tokens */ case 0x00: /* SWITCH_PAGE */ *codepage_stag = tvb_get_guint8 (tvb, off+1); proto_tree_add_text (tree, tvb, off, 2, " | Tag | T -->%3d " "| SWITCH_PAGE (Tag code page) " "|", *codepage_stag); off += 2; break; case 0x01: /* END: only possible for Tag with Content */ if (tag_save_known) { /* Known TAG */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| END (Known Tag 0x%02X) " "| %s</%s>", *level, *codepage_stag, tag_save_known, Indent (*level), tag_save_literal); /* We already looked it up! */ } else { /* Literal TAG */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| END (Literal Tag) " "| %s</%s>", *level, *codepage_stag, Indent (*level), tag_save_literal ? tag_save_literal : ""); } (*level)--; off++; /* Reset code page: not needed as return from recursion */ DebugLog(("STAG: 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 | Tag | T %3d " "| ENTITY " "| %s'&#%u;'", *level, *codepage_stag, 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 | Tag | T %3d " "| STR_I (Inline string) " "| %s\'%s\'", *level, *codepage_stag, Indent(*level), tvb_format_text (tvb, off+1, 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 | Tag | T %3d " "| EXT_I_%1x (Extension Token) " "| %s(%s: \'%s\')", *level, *codepage_stag, peek & 0x0f, Indent (*level), map_token (map->global, 0, peek), tvb_format_text (tvb, off+1, len-1)); off += 1+len; break; case 0x43: /* PI */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| PI (XML Processing Instruction) " "| %s<?xml", *level, *codepage_stag, Indent (*level)); len = parse_wbxml_attribute_list_defined (tree, tvb, off, str_tbl, *level, codepage_attr, map); /* Check that there is still room in packet */ off += len; if (off >= tvb_len) { DebugLog(("STAG: level = %u, ThrowException: len = %u (short frame)\n", *level, off - offset)); /* * TODO - Do we need to free g_malloc()ed memory? */ THROW(ReportedBoundsError); } proto_tree_add_text (tree, tvb, off-1, 1, " %3d | Tag | T %3d " "| END (PI) " "| %s?>", *level, *codepage_stag, Indent (*level)); break; 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); { char *s; if (map->ext_t[peek & 0x03]) s = (map->ext_t[peek & 0x03])(tvb, idx, str_tbl); else s = wmem_strdup_printf(wmem_packet_scope(), "EXT_T_%1x (%s)", peek & 0x03, map_token (map->global, 0, peek)); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Tag | T %3d " "| EXT_T_%1x (Extension Token) " "| %s%s", *level, *codepage_stag, peek & 0x0f, Indent (*level), s); } 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 | Tag | T %3d " "| STR_T (Tableref string) " "| %s\'%s\'", *level, *codepage_stag, Indent (*level), tvb_format_text (tvb, str_tbl+idx, str_len-1)); off += 1+len; break; case 0xC0: /* EXT_0 */ case 0xC1: /* EXT_1 */ case 0xC2: /* EXT_2 */ /* Extension tokens */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| EXT_%1x (Extension Token) " "| %s(%s)", *level, *codepage_stag, peek & 0x0f, Indent (*level), map_token (map->global, 0, peek)); off++; break; case 0xC3: /* OPAQUE - WBXML 1.1 and newer */ if (tvb_get_guint8 (tvb, 0)) { /* WBXML 1.x (x > 0) */ char *str; if (tag_save_known) { /* Knwon tag */ if (map->opaque_binary_tag) { str = map->opaque_binary_tag(tvb, off + 1, tag_save_known, *codepage_stag, &len); } else { str = default_opaque_binary_tag(tvb, off + 1, tag_save_known, *codepage_stag, &len); } } else { /* lITERAL tag */ if (map->opaque_literal_tag) { str = map->opaque_literal_tag(tvb, off + 1, tag_save_literal, *codepage_stag, &len); } else { str = default_opaque_literal_tag(tvb, off + 1, tag_save_literal, *codepage_stag, &len); } } proto_tree_add_text (tree, tvb, off, 1 + len, " %3d | Tag | T %3d " "| OPAQUE (Opaque data) " "| %s%s", *level, *codepage_stag, Indent (*level), str); off += 1 + len; } else { /* WBXML 1.0 - RESERVED_2 token (invalid) */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| RESERVED_2 (Invalid Token!) " "| WBXML 1.0 parsing stops here.", *level, *codepage_stag); /* Stop processing as it is impossible to parse now */ off = tvb_len; DebugLog(("STAG: level = %u, Return: len = %u\n", *level, off - offset)); return (off - offset); } break; /* No default clause, as all cases have been treated */ } else { /* LITERAL or Known TAG */ /* We must store the initial tag, and also retrieve the new tag. * For efficiency reasons, we store the literal tag representation * for known tags too, so we can easily close the tag without the * need of a new lookup and avoiding storage of token codepage. * * There are 4 possibilities: * * 1. Known tag followed by a known tag * 2. Known tag followed by a LITERAL tag * 3. LITERAL tag followed by Known tag * 4. LITERAL tag followed by LITERAL tag */ /* Store the new tag */ tag_len = 0; if ((peek & 0x3F) == 4) { /* LITERAL */ DebugLog(("STAG: LITERAL tag (peek = 0x%02X, off = %u) - TableRef follows!\n", peek, off)); idx = tvb_get_guintvar (tvb, off+1, &tag_len); str_len = tvb_strsize (tvb, str_tbl+idx); tag_new_literal = (const gchar*)tvb_get_ptr (tvb, str_tbl+idx, str_len); tag_new_known = 0; /* invalidate known tag_new */ } else { /* Known tag */ tag_new_known = peek & 0x3F; tag_new_literal = map_token (map->tags, *codepage_stag, tag_new_known); /* Stored looked up tag name string */ } /* Parsing of TAG starts HERE */ if (peek & 0x40) { /* Content present */ /* Content follows * [!] An explicit END token is expected in these cases! * ==> Recursion possible if we encounter a tag with content; * recursion will return at the explicit END token. */ if (parsing_tag_content) { /* Recurse */ DebugLog(("STAG: Tag in Tag - RECURSE! (off = %u)\n", off)); /* Do not process the attribute list: * recursion will take care of it */ (*level)++; len = parse_wbxml_tag_defined (tree, tvb, off, str_tbl, level, codepage_stag, codepage_attr, map); off += len; } else { /* Now we will have content to parse */ /* Save the start tag so we can properly close it later. */ if ((peek & 0x3F) == 4) { /* Literal tag */ tag_save_literal = tag_new_literal; tag_save_known = 0; } else { /* Known tag */ tag_save_known = tag_new_known; tag_save_literal = tag_new_literal; /* The last statement avoids needless lookups */ } /* Process the attribute list if present */ if (peek & 0x80) { /* Content and Attribute list present */ if (tag_new_known) { /* Known tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| Known Tag 0x%02X (AC) " "| %s<%s", *level, *codepage_stag, tag_new_known, Indent (*level), tag_new_literal); /* Tag string already looked up earlier! */ off++; } else { /* LITERAL tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| LITERAL_AC (Literal tag) (AC) " "| %s<%s", *level, *codepage_stag, Indent (*level), tag_new_literal); off += 1 + tag_len; } len = parse_wbxml_attribute_list_defined (tree, tvb, off, str_tbl, *level, codepage_attr, map); /* Check that there is still room in packet */ off += len; if (off >= tvb_len) { DebugLog(("STAG: level = %u, ThrowException: len = %u (short frame)\n", *level, off - offset)); /* * TODO - Do we need to free g_malloc()ed memory? */ THROW(ReportedBoundsError); } proto_tree_add_text (tree, tvb, off-1, 1, " %3d | Tag | T %3d " "| END (attribute list) " "| %s>", *level, *codepage_stag, Indent (*level)); } else { /* Content, no Attribute list */ if (tag_new_known) { /* Known tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| Known Tag 0x%02X (.C) " "| %s<%s>", *level, *codepage_stag, tag_new_known, Indent (*level), tag_new_literal); /* Tag string already looked up earlier! */ off++; } else { /* LITERAL tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| LITERAL_C (Literal Tag) (.C) " "| %s<%s>", *level, *codepage_stag, Indent (*level), tag_new_literal); off += 1 + tag_len; } } /* The data that follows in the parsing process * represents content for the opening tag * we've just processed in the lines above. * Next time we encounter a tag with content: recurse */ parsing_tag_content = TRUE; DebugLog(("Tag in Tag - No recursion this time! (off = %u)\n", off)); } } else { /* No Content */ DebugLog(("<Tag/> in Tag - No recursion! (off = %u)\n", off)); (*level)++; if (peek & 0x80) { /* No Content, Attribute list present */ if (tag_new_known) { /* Known tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| Known Tag 0x%02X (A.) " "| %s<%s", *level, *codepage_stag, tag_new_known, Indent (*level), tag_new_literal); /* Tag string already looked up earlier! */ off++; len = parse_wbxml_attribute_list_defined (tree, tvb, off, str_tbl, *level, codepage_attr, map); /* Check that there is still room in packet */ off += len; if (off > tvb_len) { DebugLog(("STAG: level = %u, ThrowException: len = %u (short frame)\n", *level, off - offset)); /* * TODO - Do we need to free g_malloc()ed memory? */ THROW(ReportedBoundsError); } proto_tree_add_text (tree, tvb, off-1, 1, " %3d | Tag | T %3d " "| END (Known Tag) " "| %s/>", *level, *codepage_stag, Indent (*level)); } else { /* LITERAL tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| LITERAL_A (Literal Tag) (A.) " "| %s<%s", *level, *codepage_stag, Indent (*level), tag_new_literal); off += 1 + tag_len; len = parse_wbxml_attribute_list_defined (tree, tvb, off, str_tbl, *level, codepage_attr, map); /* Check that there is still room in packet */ off += len; if (off >= tvb_len) { DebugLog(("STAG: level = %u, ThrowException: len = %u (short frame)\n", *level, off - offset)); /* * TODO - Do we need to free g_malloc()ed memory? */ THROW(ReportedBoundsError); } proto_tree_add_text (tree, tvb, off-1, 1, " %3d | Tag | T %3d " "| END (Literal Tag) " "| %s/>", *level, *codepage_stag, Indent (*level)); } } else { /* No Content, No Attribute list */ if (tag_new_known) { /* Known tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| Known Tag 0x%02x (..) " "| %s<%s />", *level, *codepage_stag, tag_new_known, Indent (*level), tag_new_literal); /* Tag string already looked up earlier! */ off++; } else { /* LITERAL tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| LITERAL (Literal Tag) (..) " "| %s<%s />", *level, *codepage_stag, Indent (*level), tag_new_literal); off += 1 + tag_len; } } (*level)--; /* TODO: Do I have to reset code page here? */ } } /* if (tag & 0x3F) >= 5 */ if (off < last_off) { THROW(ReportedBoundsError); } last_off = off; } /* while */ DebugLog(("STAG: level = %u, Return: len = %u (end of function body)\n", *level, off - offset)); return (off - offset); }
167,142
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int get_siz(Jpeg2000DecoderContext *s) { int i; int ncomponents; uint32_t log2_chroma_wh = 0; const enum AVPixelFormat *possible_fmts = NULL; int possible_fmts_nb = 0; if (bytestream2_get_bytes_left(&s->g) < 36) return AVERROR_INVALIDDATA; s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz s->width = bytestream2_get_be32u(&s->g); // Width s->height = bytestream2_get_be32u(&s->g); // Height s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz ncomponents = bytestream2_get_be16u(&s->g); // CSiz if (ncomponents <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n", s->ncomponents); return AVERROR_INVALIDDATA; } if (ncomponents > 4) { avpriv_request_sample(s->avctx, "Support for %d components", s->ncomponents); return AVERROR_PATCHWELCOME; } s->ncomponents = ncomponents; if (s->tile_width <= 0 || s->tile_height <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n", s->tile_width, s->tile_height); return AVERROR_INVALIDDATA; } if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents) return AVERROR_INVALIDDATA; for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i uint8_t x = bytestream2_get_byteu(&s->g); s->cbps[i] = (x & 0x7f) + 1; s->precision = FFMAX(s->cbps[i], s->precision); s->sgnd[i] = !!(x & 0x80); s->cdx[i] = bytestream2_get_byteu(&s->g); s->cdy[i] = bytestream2_get_byteu(&s->g); if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4 || !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) { av_log(s->avctx, AV_LOG_ERROR, "Invalid sample separation %d/%d\n", s->cdx[i], s->cdy[i]); return AVERROR_INVALIDDATA; } log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2; } s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width); s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height); if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) { s->numXtiles = s->numYtiles = 0; return AVERROR(EINVAL); } s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile)); if (!s->tile) { s->numXtiles = s->numYtiles = 0; return AVERROR(ENOMEM); } for (i = 0; i < s->numXtiles * s->numYtiles; i++) { Jpeg2000Tile *tile = s->tile + i; tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp)); if (!tile->comp) return AVERROR(ENOMEM); } /* compute image size with reduction factor */ s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x, s->reduction_factor); s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y, s->reduction_factor); if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K || s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) { possible_fmts = xyz_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts); } else { switch (s->colour_space) { case 16: possible_fmts = rgb_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts); break; case 17: possible_fmts = gray_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts); break; case 18: possible_fmts = yuv_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts); break; default: possible_fmts = all_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts); break; } } for (i = 0; i < possible_fmts_nb; ++i) { if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) { s->avctx->pix_fmt = possible_fmts[i]; break; } } if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) { av_log(s->avctx, AV_LOG_ERROR, "Unknown pix_fmt, profile: %d, colour_space: %d, " "components: %d, precision: %d, " "cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\n", s->avctx->profile, s->colour_space, ncomponents, s->precision, ncomponents > 2 ? s->cdx[1] : 0, ncomponents > 2 ? s->cdy[1] : 0, ncomponents > 2 ? s->cdx[2] : 0, ncomponents > 2 ? s->cdy[2] : 0); } s->avctx->bits_per_raw_sample = s->precision; return 0; } Commit Message: avcodec/jpeg2000dec: non zero image offsets are not supported Fixes out of array accesses Fixes Ticket3080 Found-by: ami_stuff Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
static int get_siz(Jpeg2000DecoderContext *s) { int i; int ncomponents; uint32_t log2_chroma_wh = 0; const enum AVPixelFormat *possible_fmts = NULL; int possible_fmts_nb = 0; if (bytestream2_get_bytes_left(&s->g) < 36) return AVERROR_INVALIDDATA; s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz s->width = bytestream2_get_be32u(&s->g); // Width s->height = bytestream2_get_be32u(&s->g); // Height s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz ncomponents = bytestream2_get_be16u(&s->g); // CSiz if (s->image_offset_x || s->image_offset_y) { avpriv_request_sample(s->avctx, "Support for image offsets"); return AVERROR_PATCHWELCOME; } if (ncomponents <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n", s->ncomponents); return AVERROR_INVALIDDATA; } if (ncomponents > 4) { avpriv_request_sample(s->avctx, "Support for %d components", s->ncomponents); return AVERROR_PATCHWELCOME; } s->ncomponents = ncomponents; if (s->tile_width <= 0 || s->tile_height <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n", s->tile_width, s->tile_height); return AVERROR_INVALIDDATA; } if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents) return AVERROR_INVALIDDATA; for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i uint8_t x = bytestream2_get_byteu(&s->g); s->cbps[i] = (x & 0x7f) + 1; s->precision = FFMAX(s->cbps[i], s->precision); s->sgnd[i] = !!(x & 0x80); s->cdx[i] = bytestream2_get_byteu(&s->g); s->cdy[i] = bytestream2_get_byteu(&s->g); if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4 || !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) { av_log(s->avctx, AV_LOG_ERROR, "Invalid sample separation %d/%d\n", s->cdx[i], s->cdy[i]); return AVERROR_INVALIDDATA; } log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2; } s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width); s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height); if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) { s->numXtiles = s->numYtiles = 0; return AVERROR(EINVAL); } s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile)); if (!s->tile) { s->numXtiles = s->numYtiles = 0; return AVERROR(ENOMEM); } for (i = 0; i < s->numXtiles * s->numYtiles; i++) { Jpeg2000Tile *tile = s->tile + i; tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp)); if (!tile->comp) return AVERROR(ENOMEM); } /* compute image size with reduction factor */ s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x, s->reduction_factor); s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y, s->reduction_factor); if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K || s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) { possible_fmts = xyz_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts); } else { switch (s->colour_space) { case 16: possible_fmts = rgb_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts); break; case 17: possible_fmts = gray_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts); break; case 18: possible_fmts = yuv_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts); break; default: possible_fmts = all_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts); break; } } for (i = 0; i < possible_fmts_nb; ++i) { if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) { s->avctx->pix_fmt = possible_fmts[i]; break; } } if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) { av_log(s->avctx, AV_LOG_ERROR, "Unknown pix_fmt, profile: %d, colour_space: %d, " "components: %d, precision: %d, " "cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\n", s->avctx->profile, s->colour_space, ncomponents, s->precision, ncomponents > 2 ? s->cdx[1] : 0, ncomponents > 2 ? s->cdy[1] : 0, ncomponents > 2 ? s->cdx[2] : 0, ncomponents > 2 ? s->cdy[2] : 0); } s->avctx->bits_per_raw_sample = s->precision; return 0; }
165,927
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: spnego_gss_init_sec_context( OM_uint32 *minor_status, gss_cred_id_t claimant_cred_handle, gss_ctx_id_t *context_handle, gss_name_t target_name, gss_OID mech_type, OM_uint32 req_flags, OM_uint32 time_req, gss_channel_bindings_t input_chan_bindings, gss_buffer_t input_token, gss_OID *actual_mech, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec) { send_token_flag send_token = NO_TOKEN_SEND; OM_uint32 tmpmin, ret, negState; gss_buffer_t mechtok_in, mechListMIC_in, mechListMIC_out; gss_buffer_desc mechtok_out = GSS_C_EMPTY_BUFFER; spnego_gss_cred_id_t spcred = NULL; spnego_gss_ctx_id_t spnego_ctx = NULL; dsyslog("Entering init_sec_context\n"); mechtok_in = mechListMIC_out = mechListMIC_in = GSS_C_NO_BUFFER; negState = REJECT; /* * This function works in three steps: * * 1. Perform mechanism negotiation. * 2. Invoke the negotiated or optimistic mech's gss_init_sec_context * function and examine the results. * 3. Process or generate MICs if necessary. * * The three steps share responsibility for determining when the * exchange is complete. If the selected mech completed in a previous * call and no MIC exchange is expected, then step 1 will decide. If * the selected mech completes in this call and no MIC exchange is * expected, then step 2 will decide. If a MIC exchange is expected, * then step 3 will decide. If an error occurs in any step, the * exchange will be aborted, possibly with an error token. * * negState determines the state of the negotiation, and is * communicated to the acceptor if a continuing token is sent. * send_token is used to indicate what type of token, if any, should be * generated. */ /* Validate arguments. */ if (minor_status != NULL) *minor_status = 0; if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } if (minor_status == NULL || output_token == GSS_C_NO_BUFFER || context_handle == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; if (actual_mech != NULL) *actual_mech = GSS_C_NO_OID; /* Step 1: perform mechanism negotiation. */ spcred = (spnego_gss_cred_id_t)claimant_cred_handle; if (*context_handle == GSS_C_NO_CONTEXT) { ret = init_ctx_new(minor_status, spcred, context_handle, &send_token); if (ret != GSS_S_CONTINUE_NEEDED) { goto cleanup; } } else { ret = init_ctx_cont(minor_status, context_handle, input_token, &mechtok_in, &mechListMIC_in, &negState, &send_token); if (HARD_ERROR(ret)) { goto cleanup; } } /* Step 2: invoke the selected or optimistic mechanism's * gss_init_sec_context function, if it didn't complete previously. */ spnego_ctx = (spnego_gss_ctx_id_t)*context_handle; if (!spnego_ctx->mech_complete) { ret = init_ctx_call_init( minor_status, spnego_ctx, spcred, target_name, req_flags, time_req, mechtok_in, actual_mech, &mechtok_out, ret_flags, time_rec, &negState, &send_token); /* Give the mechanism a chance to force a mechlistMIC. */ if (!HARD_ERROR(ret) && mech_requires_mechlistMIC(spnego_ctx)) spnego_ctx->mic_reqd = 1; } /* Step 3: process or generate the MIC, if the negotiated mech is * complete and supports MICs. */ if (!HARD_ERROR(ret) && spnego_ctx->mech_complete && (spnego_ctx->ctx_flags & GSS_C_INTEG_FLAG)) { ret = handle_mic(minor_status, mechListMIC_in, (mechtok_out.length != 0), spnego_ctx, &mechListMIC_out, &negState, &send_token); } cleanup: if (send_token == INIT_TOKEN_SEND) { if (make_spnego_tokenInit_msg(spnego_ctx, 0, mechListMIC_out, req_flags, &mechtok_out, send_token, output_token) < 0) { ret = GSS_S_FAILURE; } } else if (send_token != NO_TOKEN_SEND) { if (make_spnego_tokenTarg_msg(negState, GSS_C_NO_OID, &mechtok_out, mechListMIC_out, send_token, output_token) < 0) { ret = GSS_S_FAILURE; } } gss_release_buffer(&tmpmin, &mechtok_out); if (ret == GSS_S_COMPLETE) { /* * Now, switch the output context to refer to the * negotiated mechanism's context. */ *context_handle = (gss_ctx_id_t)spnego_ctx->ctx_handle; if (actual_mech != NULL) *actual_mech = spnego_ctx->actual_mech; if (ret_flags != NULL) *ret_flags = spnego_ctx->ctx_flags; release_spnego_ctx(&spnego_ctx); } else if (ret != GSS_S_CONTINUE_NEEDED) { if (spnego_ctx != NULL) { gss_delete_sec_context(&tmpmin, &spnego_ctx->ctx_handle, GSS_C_NO_BUFFER); release_spnego_ctx(&spnego_ctx); } *context_handle = GSS_C_NO_CONTEXT; } if (mechtok_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechtok_in); free(mechtok_in); } if (mechListMIC_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechListMIC_in); free(mechListMIC_in); } if (mechListMIC_out != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechListMIC_out); free(mechListMIC_out); } return ret; } /* init_sec_context */ 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 CWE ID: CWE-18
spnego_gss_init_sec_context( OM_uint32 *minor_status, gss_cred_id_t claimant_cred_handle, gss_ctx_id_t *context_handle, gss_name_t target_name, gss_OID mech_type, OM_uint32 req_flags, OM_uint32 time_req, gss_channel_bindings_t input_chan_bindings, gss_buffer_t input_token, gss_OID *actual_mech, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec) { send_token_flag send_token = NO_TOKEN_SEND; OM_uint32 tmpmin, ret, negState; gss_buffer_t mechtok_in, mechListMIC_in, mechListMIC_out; gss_buffer_desc mechtok_out = GSS_C_EMPTY_BUFFER; spnego_gss_cred_id_t spcred = NULL; spnego_gss_ctx_id_t spnego_ctx = NULL; dsyslog("Entering init_sec_context\n"); mechtok_in = mechListMIC_out = mechListMIC_in = GSS_C_NO_BUFFER; negState = REJECT; /* * This function works in three steps: * * 1. Perform mechanism negotiation. * 2. Invoke the negotiated or optimistic mech's gss_init_sec_context * function and examine the results. * 3. Process or generate MICs if necessary. * * The three steps share responsibility for determining when the * exchange is complete. If the selected mech completed in a previous * call and no MIC exchange is expected, then step 1 will decide. If * the selected mech completes in this call and no MIC exchange is * expected, then step 2 will decide. If a MIC exchange is expected, * then step 3 will decide. If an error occurs in any step, the * exchange will be aborted, possibly with an error token. * * negState determines the state of the negotiation, and is * communicated to the acceptor if a continuing token is sent. * send_token is used to indicate what type of token, if any, should be * generated. */ /* Validate arguments. */ if (minor_status != NULL) *minor_status = 0; if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } if (minor_status == NULL || output_token == GSS_C_NO_BUFFER || context_handle == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; if (actual_mech != NULL) *actual_mech = GSS_C_NO_OID; /* Step 1: perform mechanism negotiation. */ spcred = (spnego_gss_cred_id_t)claimant_cred_handle; if (*context_handle == GSS_C_NO_CONTEXT) { ret = init_ctx_new(minor_status, spcred, context_handle, &send_token); if (ret != GSS_S_CONTINUE_NEEDED) { goto cleanup; } } else { ret = init_ctx_cont(minor_status, context_handle, input_token, &mechtok_in, &mechListMIC_in, &negState, &send_token); if (HARD_ERROR(ret)) { goto cleanup; } } /* Step 2: invoke the selected or optimistic mechanism's * gss_init_sec_context function, if it didn't complete previously. */ spnego_ctx = (spnego_gss_ctx_id_t)*context_handle; if (!spnego_ctx->mech_complete) { ret = init_ctx_call_init( minor_status, spnego_ctx, spcred, target_name, req_flags, time_req, mechtok_in, actual_mech, &mechtok_out, ret_flags, time_rec, &negState, &send_token); /* Give the mechanism a chance to force a mechlistMIC. */ if (!HARD_ERROR(ret) && mech_requires_mechlistMIC(spnego_ctx)) spnego_ctx->mic_reqd = 1; } /* Step 3: process or generate the MIC, if the negotiated mech is * complete and supports MICs. */ if (!HARD_ERROR(ret) && spnego_ctx->mech_complete && (spnego_ctx->ctx_flags & GSS_C_INTEG_FLAG)) { ret = handle_mic(minor_status, mechListMIC_in, (mechtok_out.length != 0), spnego_ctx, &mechListMIC_out, &negState, &send_token); } cleanup: if (send_token == INIT_TOKEN_SEND) { if (make_spnego_tokenInit_msg(spnego_ctx, 0, mechListMIC_out, req_flags, &mechtok_out, send_token, output_token) < 0) { ret = GSS_S_FAILURE; } } else if (send_token != NO_TOKEN_SEND) { if (make_spnego_tokenTarg_msg(negState, GSS_C_NO_OID, &mechtok_out, mechListMIC_out, send_token, output_token) < 0) { ret = GSS_S_FAILURE; } } gss_release_buffer(&tmpmin, &mechtok_out); if (ret == GSS_S_COMPLETE) { spnego_ctx->opened = 1; if (actual_mech != NULL) *actual_mech = spnego_ctx->actual_mech; if (ret_flags != NULL) *ret_flags = spnego_ctx->ctx_flags; } else if (ret != GSS_S_CONTINUE_NEEDED) { if (spnego_ctx != NULL) { gss_delete_sec_context(&tmpmin, &spnego_ctx->ctx_handle, GSS_C_NO_BUFFER); release_spnego_ctx(&spnego_ctx); } *context_handle = GSS_C_NO_CONTEXT; } if (mechtok_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechtok_in); free(mechtok_in); } if (mechListMIC_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechListMIC_in); free(mechListMIC_in); } if (mechListMIC_out != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechListMIC_out); free(mechListMIC_out); } return ret; } /* init_sec_context */
166,660
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t 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; } Commit Message: Skip track if verification fails Bug: 62187433 Test: ran poc, CTS Change-Id: Ib9b0b6de88d046d8149e9ea5073d6c40ffec7b0c (cherry picked from commit ef8c7830d838d877e6b37b75b47294b064c79397) CWE ID:
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', 'v') && mInitCheck == OK) { ALOGE("duplicate moov"); 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; } status_t err = verifyTrack(mLastTrack); if (err != OK) { 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; } } 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; }
173,974
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType load_tile(Image *image,Image *tile_image, XCFDocInfo *inDocInfo,XCFLayerInfo *inLayerInfo,size_t data_length, ExceptionInfo *exception) { ssize_t y; register ssize_t x; register Quantum *q; ssize_t count; unsigned char *graydata; XCFPixelInfo *xcfdata, *xcfodata; xcfdata=(XCFPixelInfo *) AcquireQuantumMemory(data_length,sizeof(*xcfdata)); if (xcfdata == (XCFPixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); xcfodata=xcfdata; graydata=(unsigned char *) xcfdata; /* used by gray and indexed */ count=ReadBlob(image,data_length,(unsigned char *) xcfdata); if (count != (ssize_t) data_length) ThrowBinaryException(CorruptImageError,"NotEnoughPixelData", image->filename); for (y=0; y < (ssize_t) tile_image->rows; y++) { q=GetAuthenticPixels(tile_image,0,y,tile_image->columns,1,exception); if (q == (Quantum *) NULL) break; if (inDocInfo->image_type == GIMP_GRAY) { for (x=0; x < (ssize_t) tile_image->columns; x++) { SetPixelGray(tile_image,ScaleCharToQuantum(*graydata),q); SetPixelAlpha(tile_image,ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q); graydata++; q+=GetPixelChannels(tile_image); } } else if (inDocInfo->image_type == GIMP_RGB) { for (x=0; x < (ssize_t) tile_image->columns; x++) { SetPixelRed(tile_image,ScaleCharToQuantum(xcfdata->red),q); SetPixelGreen(tile_image,ScaleCharToQuantum(xcfdata->green),q); SetPixelBlue(tile_image,ScaleCharToQuantum(xcfdata->blue),q); SetPixelAlpha(tile_image,xcfdata->alpha == 255U ? TransparentAlpha : ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q); xcfdata++; q+=GetPixelChannels(tile_image); } } if (SyncAuthenticPixels(tile_image,exception) == MagickFalse) break; } xcfodata=(XCFPixelInfo *) RelinquishMagickMemory(xcfodata); return MagickTrue; } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/104 CWE ID: CWE-125
static MagickBooleanType load_tile(Image *image,Image *tile_image, XCFDocInfo *inDocInfo,XCFLayerInfo *inLayerInfo,size_t data_length, ExceptionInfo *exception) { ssize_t y; register ssize_t x; register Quantum *q; ssize_t count; unsigned char *graydata; XCFPixelInfo *xcfdata, *xcfodata; xcfdata=(XCFPixelInfo *) AcquireQuantumMemory(MagickMax(data_length, tile_image->columns*tile_image->rows),sizeof(*xcfdata)); if (xcfdata == (XCFPixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); xcfodata=xcfdata; graydata=(unsigned char *) xcfdata; /* used by gray and indexed */ count=ReadBlob(image,data_length,(unsigned char *) xcfdata); if (count != (ssize_t) data_length) ThrowBinaryException(CorruptImageError,"NotEnoughPixelData", image->filename); for (y=0; y < (ssize_t) tile_image->rows; y++) { q=GetAuthenticPixels(tile_image,0,y,tile_image->columns,1,exception); if (q == (Quantum *) NULL) break; if (inDocInfo->image_type == GIMP_GRAY) { for (x=0; x < (ssize_t) tile_image->columns; x++) { SetPixelGray(tile_image,ScaleCharToQuantum(*graydata),q); SetPixelAlpha(tile_image,ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q); graydata++; q+=GetPixelChannels(tile_image); } } else if (inDocInfo->image_type == GIMP_RGB) { for (x=0; x < (ssize_t) tile_image->columns; x++) { SetPixelRed(tile_image,ScaleCharToQuantum(xcfdata->red),q); SetPixelGreen(tile_image,ScaleCharToQuantum(xcfdata->green),q); SetPixelBlue(tile_image,ScaleCharToQuantum(xcfdata->blue),q); SetPixelAlpha(tile_image,xcfdata->alpha == 255U ? TransparentAlpha : ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q); xcfdata++; q+=GetPixelChannels(tile_image); } } if (SyncAuthenticPixels(tile_image,exception) == MagickFalse) break; } xcfodata=(XCFPixelInfo *) RelinquishMagickMemory(xcfodata); return MagickTrue; }
168,800
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderViewImpl::OnSwapOut(const ViewMsg_SwapOut_Params& params) { OnStop(); if (!is_swapped_out_) { SyncNavigationState(); webview()->dispatchUnloadEvent(); SetSwappedOut(true); WebURLRequest request(GURL("about:swappedout")); webview()->mainFrame()->loadRequest(request); } Send(new ViewHostMsg_SwapOut_ACK(routing_id_, params)); } Commit Message: Use a new scheme for swapping out RenderViews. BUG=118664 TEST=none Review URL: http://codereview.chromium.org/9720004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@127986 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderViewImpl::OnSwapOut(const ViewMsg_SwapOut_Params& params) { OnStop(); if (!is_swapped_out_) { SyncNavigationState(); webview()->dispatchUnloadEvent(); SetSwappedOut(true); // to chrome::kSwappedOutURL. If that happens to be to the page we had been GURL swappedOutURL(chrome::kSwappedOutURL); WebURLRequest request(swappedOutURL); webview()->mainFrame()->loadRequest(request); } Send(new ViewHostMsg_SwapOut_ACK(routing_id_, params)); }
171,031
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: pcap_ng_check_header(const uint8_t *magic, FILE *fp, u_int precision, char *errbuf, int *err) { bpf_u_int32 magic_int; size_t amt_read; bpf_u_int32 total_length; bpf_u_int32 byte_order_magic; struct block_header *bhdrp; struct section_header_block *shbp; pcap_t *p; int swapped = 0; struct pcap_ng_sf *ps; int status; struct block_cursor cursor; struct interface_description_block *idbp; /* * Assume no read errors. */ *err = 0; /* * Check whether the first 4 bytes of the file are the block * type for a pcapng savefile. */ memcpy(&magic_int, magic, sizeof(magic_int)); if (magic_int != BT_SHB) { /* * XXX - check whether this looks like what the block * type would be after being munged by mapping between * UN*X and DOS/Windows text file format and, if it * does, look for the byte-order magic number in * the appropriate place and, if we find it, report * this as possibly being a pcapng file transferred * between UN*X and Windows in text file format? */ return (NULL); /* nope */ } /* * OK, they are. However, that's just \n\r\r\n, so it could, * conceivably, be an ordinary text file. * * It could not, however, conceivably be any other type of * capture file, so we can read the rest of the putative * Section Header Block; put the block type in the common * header, read the rest of the common header and the * fixed-length portion of the SHB, and look for the byte-order * magic value. */ amt_read = fread(&total_length, 1, sizeof(total_length), fp); if (amt_read < sizeof(total_length)) { if (ferror(fp)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "error reading dump file"); *err = 1; return (NULL); /* fail */ } /* * Possibly a weird short text file, so just say * "not pcapng". */ return (NULL); } amt_read = fread(&byte_order_magic, 1, sizeof(byte_order_magic), fp); if (amt_read < sizeof(byte_order_magic)) { if (ferror(fp)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "error reading dump file"); *err = 1; return (NULL); /* fail */ } /* * Possibly a weird short text file, so just say * "not pcapng". */ return (NULL); } if (byte_order_magic != BYTE_ORDER_MAGIC) { byte_order_magic = SWAPLONG(byte_order_magic); if (byte_order_magic != BYTE_ORDER_MAGIC) { /* * Not a pcapng file. */ return (NULL); } swapped = 1; total_length = SWAPLONG(total_length); } /* * Check the sanity of the total length. */ if (total_length < sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer)) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Section Header Block in pcapng dump file has a length of %u < %" PRIsize, total_length, sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer)); *err = 1; return (NULL); } /* * Make sure it's not too big. */ if (total_length > INITIAL_MAX_BLOCKSIZE) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "pcapng block size %u > maximum %u", total_length, INITIAL_MAX_BLOCKSIZE); *err = 1; return (NULL); } /* * OK, this is a good pcapng file. * Allocate a pcap_t for it. */ p = pcap_open_offline_common(errbuf, sizeof (struct pcap_ng_sf)); if (p == NULL) { /* Allocation failed. */ *err = 1; return (NULL); } p->swapped = swapped; ps = p->priv; /* * What precision does the user want? */ switch (precision) { case PCAP_TSTAMP_PRECISION_MICRO: ps->user_tsresol = 1000000; break; case PCAP_TSTAMP_PRECISION_NANO: ps->user_tsresol = 1000000000; break; default: pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "unknown time stamp resolution %u", precision); free(p); *err = 1; return (NULL); } p->opt.tstamp_precision = precision; /* * Allocate a buffer into which to read blocks. We default to * the maximum of: * * the total length of the SHB for which we read the header; * * 2K, which should be more than large enough for an Enhanced * Packet Block containing a full-size Ethernet frame, and * leaving room for some options. * * If we find a bigger block, we reallocate the buffer, up to * the maximum size. We start out with a maximum size of * INITIAL_MAX_BLOCKSIZE; if we see any link-layer header types * with a maximum snapshot that results in a larger maximum * block length, we boost the maximum. */ p->bufsize = 2048; if (p->bufsize < total_length) p->bufsize = total_length; p->buffer = malloc(p->bufsize); if (p->buffer == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory"); free(p); *err = 1; return (NULL); } ps->max_blocksize = INITIAL_MAX_BLOCKSIZE; /* * Copy the stuff we've read to the buffer, and read the rest * of the SHB. */ bhdrp = (struct block_header *)p->buffer; shbp = (struct section_header_block *)((u_char *)p->buffer + sizeof(struct block_header)); bhdrp->block_type = magic_int; bhdrp->total_length = total_length; shbp->byte_order_magic = byte_order_magic; if (read_bytes(fp, (u_char *)p->buffer + (sizeof(magic_int) + sizeof(total_length) + sizeof(byte_order_magic)), total_length - (sizeof(magic_int) + sizeof(total_length) + sizeof(byte_order_magic)), 1, errbuf) == -1) goto fail; if (p->swapped) { /* * Byte-swap the fields we've read. */ shbp->major_version = SWAPSHORT(shbp->major_version); shbp->minor_version = SWAPSHORT(shbp->minor_version); /* * XXX - we don't care about the section length. */ } /* currently only SHB version 1.0 is supported */ if (! (shbp->major_version == PCAP_NG_VERSION_MAJOR && shbp->minor_version == PCAP_NG_VERSION_MINOR)) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "unsupported pcapng savefile version %u.%u", shbp->major_version, shbp->minor_version); goto fail; } p->version_major = shbp->major_version; p->version_minor = shbp->minor_version; /* * Save the time stamp resolution the user requested. */ p->opt.tstamp_precision = precision; /* * Now start looking for an Interface Description Block. */ for (;;) { /* * Read the next block. */ status = read_block(fp, p, &cursor, errbuf); if (status == 0) { /* EOF - no IDB in this file */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "the capture file has no Interface Description Blocks"); goto fail; } if (status == -1) goto fail; /* error */ switch (cursor.block_type) { case BT_IDB: /* * Get a pointer to the fixed-length portion of the * IDB. */ idbp = get_from_block_data(&cursor, sizeof(*idbp), errbuf); if (idbp == NULL) goto fail; /* error */ /* * Byte-swap it if necessary. */ if (p->swapped) { idbp->linktype = SWAPSHORT(idbp->linktype); idbp->snaplen = SWAPLONG(idbp->snaplen); } /* * Try to add this interface. */ if (!add_interface(p, &cursor, errbuf)) goto fail; goto done; case BT_EPB: case BT_SPB: case BT_PB: /* * Saw a packet before we saw any IDBs. That's * not valid, as we don't know what link-layer * encapsulation the packet has. */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "the capture file has a packet block before any Interface Description Blocks"); goto fail; default: /* * Just ignore it. */ break; } } done: p->tzoff = 0; /* XXX - not used in pcap */ p->linktype = linktype_to_dlt(idbp->linktype); p->snapshot = pcap_adjust_snapshot(p->linktype, idbp->snaplen); p->linktype_ext = 0; /* * If the maximum block size for a packet with the maximum * snapshot length for this DLT_ is bigger than the current * maximum block size, increase the maximum. */ if (MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen_for_dlt(p->linktype)) > ps->max_blocksize) ps->max_blocksize = MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen_for_dlt(p->linktype)); p->next_packet_op = pcap_ng_next_packet; p->cleanup_op = pcap_ng_cleanup; return (p); fail: free(ps->ifaces); free(p->buffer); free(p); *err = 1; return (NULL); } Commit Message: do sanity checks on PHB header length before allocating memory. There was no fault; but doing the check results in a more consistent error CWE ID: CWE-20
pcap_ng_check_header(const uint8_t *magic, FILE *fp, u_int precision, char *errbuf, int *err) { bpf_u_int32 magic_int; size_t amt_read; bpf_u_int32 total_length; bpf_u_int32 byte_order_magic; struct block_header *bhdrp; struct section_header_block *shbp; pcap_t *p; int swapped = 0; struct pcap_ng_sf *ps; int status; struct block_cursor cursor; struct interface_description_block *idbp; /* * Assume no read errors. */ *err = 0; /* * Check whether the first 4 bytes of the file are the block * type for a pcapng savefile. */ memcpy(&magic_int, magic, sizeof(magic_int)); if (magic_int != BT_SHB) { /* * XXX - check whether this looks like what the block * type would be after being munged by mapping between * UN*X and DOS/Windows text file format and, if it * does, look for the byte-order magic number in * the appropriate place and, if we find it, report * this as possibly being a pcapng file transferred * between UN*X and Windows in text file format? */ return (NULL); /* nope */ } /* * OK, they are. However, that's just \n\r\r\n, so it could, * conceivably, be an ordinary text file. * * It could not, however, conceivably be any other type of * capture file, so we can read the rest of the putative * Section Header Block; put the block type in the common * header, read the rest of the common header and the * fixed-length portion of the SHB, and look for the byte-order * magic value. */ amt_read = fread(&total_length, 1, sizeof(total_length), fp); if (amt_read < sizeof(total_length)) { if (ferror(fp)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "error reading dump file"); *err = 1; return (NULL); /* fail */ } /* * Possibly a weird short text file, so just say * "not pcapng". */ return (NULL); } amt_read = fread(&byte_order_magic, 1, sizeof(byte_order_magic), fp); if (amt_read < sizeof(byte_order_magic)) { if (ferror(fp)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "error reading dump file"); *err = 1; return (NULL); /* fail */ } /* * Possibly a weird short text file, so just say * "not pcapng". */ return (NULL); } if (byte_order_magic != BYTE_ORDER_MAGIC) { byte_order_magic = SWAPLONG(byte_order_magic); if (byte_order_magic != BYTE_ORDER_MAGIC) { /* * Not a pcapng file. */ return (NULL); } swapped = 1; total_length = SWAPLONG(total_length); } /* * Check the sanity of the total length. */ if (total_length < sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer) || (total_length > BT_SHB_INSANE_MAX)) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Section Header Block in pcapng dump file has invalid length %" PRIsize " < _%lu_ < %lu (BT_SHB_INSANE_MAX)", sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer), total_length, BT_SHB_INSANE_MAX); *err = 1; return (NULL); } /* * OK, this is a good pcapng file. * Allocate a pcap_t for it. */ p = pcap_open_offline_common(errbuf, sizeof (struct pcap_ng_sf)); if (p == NULL) { /* Allocation failed. */ *err = 1; return (NULL); } p->swapped = swapped; ps = p->priv; /* * What precision does the user want? */ switch (precision) { case PCAP_TSTAMP_PRECISION_MICRO: ps->user_tsresol = 1000000; break; case PCAP_TSTAMP_PRECISION_NANO: ps->user_tsresol = 1000000000; break; default: pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "unknown time stamp resolution %u", precision); free(p); *err = 1; return (NULL); } p->opt.tstamp_precision = precision; /* * Allocate a buffer into which to read blocks. We default to * the maximum of: * * the total length of the SHB for which we read the header; * * 2K, which should be more than large enough for an Enhanced * Packet Block containing a full-size Ethernet frame, and * leaving room for some options. * * If we find a bigger block, we reallocate the buffer, up to * the maximum size. We start out with a maximum size of * INITIAL_MAX_BLOCKSIZE; if we see any link-layer header types * with a maximum snapshot that results in a larger maximum * block length, we boost the maximum. */ p->bufsize = 2048; if (p->bufsize < total_length) p->bufsize = total_length; p->buffer = malloc(p->bufsize); if (p->buffer == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory"); free(p); *err = 1; return (NULL); } ps->max_blocksize = INITIAL_MAX_BLOCKSIZE; /* * Copy the stuff we've read to the buffer, and read the rest * of the SHB. */ bhdrp = (struct block_header *)p->buffer; shbp = (struct section_header_block *)((u_char *)p->buffer + sizeof(struct block_header)); bhdrp->block_type = magic_int; bhdrp->total_length = total_length; shbp->byte_order_magic = byte_order_magic; if (read_bytes(fp, (u_char *)p->buffer + (sizeof(magic_int) + sizeof(total_length) + sizeof(byte_order_magic)), total_length - (sizeof(magic_int) + sizeof(total_length) + sizeof(byte_order_magic)), 1, errbuf) == -1) goto fail; if (p->swapped) { /* * Byte-swap the fields we've read. */ shbp->major_version = SWAPSHORT(shbp->major_version); shbp->minor_version = SWAPSHORT(shbp->minor_version); /* * XXX - we don't care about the section length. */ } /* currently only SHB version 1.0 is supported */ if (! (shbp->major_version == PCAP_NG_VERSION_MAJOR && shbp->minor_version == PCAP_NG_VERSION_MINOR)) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "unsupported pcapng savefile version %u.%u", shbp->major_version, shbp->minor_version); goto fail; } p->version_major = shbp->major_version; p->version_minor = shbp->minor_version; /* * Save the time stamp resolution the user requested. */ p->opt.tstamp_precision = precision; /* * Now start looking for an Interface Description Block. */ for (;;) { /* * Read the next block. */ status = read_block(fp, p, &cursor, errbuf); if (status == 0) { /* EOF - no IDB in this file */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "the capture file has no Interface Description Blocks"); goto fail; } if (status == -1) goto fail; /* error */ switch (cursor.block_type) { case BT_IDB: /* * Get a pointer to the fixed-length portion of the * IDB. */ idbp = get_from_block_data(&cursor, sizeof(*idbp), errbuf); if (idbp == NULL) goto fail; /* error */ /* * Byte-swap it if necessary. */ if (p->swapped) { idbp->linktype = SWAPSHORT(idbp->linktype); idbp->snaplen = SWAPLONG(idbp->snaplen); } /* * Try to add this interface. */ if (!add_interface(p, &cursor, errbuf)) goto fail; goto done; case BT_EPB: case BT_SPB: case BT_PB: /* * Saw a packet before we saw any IDBs. That's * not valid, as we don't know what link-layer * encapsulation the packet has. */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "the capture file has a packet block before any Interface Description Blocks"); goto fail; default: /* * Just ignore it. */ break; } } done: p->tzoff = 0; /* XXX - not used in pcap */ p->linktype = linktype_to_dlt(idbp->linktype); p->snapshot = pcap_adjust_snapshot(p->linktype, idbp->snaplen); p->linktype_ext = 0; /* * If the maximum block size for a packet with the maximum * snapshot length for this DLT_ is bigger than the current * maximum block size, increase the maximum. */ if (MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen_for_dlt(p->linktype)) > ps->max_blocksize) ps->max_blocksize = MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen_for_dlt(p->linktype)); p->next_packet_op = pcap_ng_next_packet; p->cleanup_op = pcap_ng_cleanup; return (p); fail: free(ps->ifaces); free(p->buffer); free(p); *err = 1; return (NULL); }
170,187
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ExtensionTtsController::FinishCurrentUtterance() { if (current_utterance_) { current_utterance_->FinishAndDestroy(); current_utterance_ = NULL; } } 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 CWE ID: CWE-20
void ExtensionTtsController::FinishCurrentUtterance() { bool can_enqueue = false; if (options->HasKey(constants::kEnqueueKey)) { EXTENSION_FUNCTION_VALIDATE( options->GetBoolean(constants::kEnqueueKey, &can_enqueue)); }
170,378
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track) { AC3HeaderInfo *hdr = NULL; struct eac3_info *info; int num_blocks, ret; if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info)))) return AVERROR(ENOMEM); info = track->eac3_priv; if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) { /* drop the packets until we see a good one */ if (!track->entry) { av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n"); ret = 0; } else ret = AVERROR_INVALIDDATA; goto end; } info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000); num_blocks = hdr->num_blocks; if (!info->ec3_done) { /* AC-3 substream must be the first one */ if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) { ret = AVERROR(EINVAL); goto end; } /* this should always be the case, given that our AC-3 parser * concatenates dependent frames to their independent parent */ if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) { /* substream ids must be incremental */ if (hdr->substreamid > info->num_ind_sub + 1) { ret = AVERROR(EINVAL); goto end; } if (hdr->substreamid == info->num_ind_sub + 1) { avpriv_request_sample(track->par, "Multiple independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } else if (hdr->substreamid < info->num_ind_sub || hdr->substreamid == 0 && info->substream[0].bsid) { info->ec3_done = 1; goto concatenate; } } /* fill the info needed for the "dec3" atom */ info->substream[hdr->substreamid].fscod = hdr->sr_code; info->substream[hdr->substreamid].bsid = hdr->bitstream_id; info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode; info->substream[hdr->substreamid].acmod = hdr->channel_mode; info->substream[hdr->substreamid].lfeon = hdr->lfe_on; /* Parse dependent substream(s), if any */ if (pkt->size != hdr->frame_size) { int cumul_size = hdr->frame_size; int parent = hdr->substreamid; while (cumul_size != pkt->size) { GetBitContext gbc; int i; ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size); if (ret < 0) goto end; if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) { ret = AVERROR(EINVAL); goto end; } info->substream[parent].num_dep_sub++; ret /= 8; /* header is parsed up to lfeon, but custom channel map may be needed */ init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret); /* skip bsid */ skip_bits(&gbc, 5); /* skip volume control params */ for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) { skip_bits(&gbc, 5); // skip dialog normalization if (get_bits1(&gbc)) { skip_bits(&gbc, 8); // skip compression gain word } } /* get the dependent stream channel map, if exists */ if (get_bits1(&gbc)) info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f; else info->substream[parent].chan_loc |= hdr->channel_mode; cumul_size += hdr->frame_size; } } } concatenate: if (!info->num_blocks && num_blocks == 6) { ret = pkt->size; goto end; } else if (info->num_blocks + num_blocks > 6) { ret = AVERROR_INVALIDDATA; goto end; } if (!info->num_blocks) { ret = av_packet_ref(&info->pkt, pkt); if (!ret) info->num_blocks = num_blocks; goto end; } else { if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0) goto end; memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size); info->num_blocks += num_blocks; info->pkt.duration += pkt->duration; if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0) goto end; if (info->num_blocks != 6) goto end; av_packet_unref(pkt); av_packet_move_ref(pkt, &info->pkt); info->num_blocks = 0; } ret = pkt->size; end: av_free(hdr); return ret; } Commit Message: avformat/movenc: Check that frame_types other than EAC3_FRAME_TYPE_INDEPENDENT have a supported substream id Fixes: out of array access Fixes: ffmpeg_bof_1.avi Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-129
static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track) { AC3HeaderInfo *hdr = NULL; struct eac3_info *info; int num_blocks, ret; if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info)))) return AVERROR(ENOMEM); info = track->eac3_priv; if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) { /* drop the packets until we see a good one */ if (!track->entry) { av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n"); ret = 0; } else ret = AVERROR_INVALIDDATA; goto end; } info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000); num_blocks = hdr->num_blocks; if (!info->ec3_done) { /* AC-3 substream must be the first one */ if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) { ret = AVERROR(EINVAL); goto end; } /* this should always be the case, given that our AC-3 parser * concatenates dependent frames to their independent parent */ if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) { /* substream ids must be incremental */ if (hdr->substreamid > info->num_ind_sub + 1) { ret = AVERROR(EINVAL); goto end; } if (hdr->substreamid == info->num_ind_sub + 1) { avpriv_request_sample(track->par, "Multiple independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } else if (hdr->substreamid < info->num_ind_sub || hdr->substreamid == 0 && info->substream[0].bsid) { info->ec3_done = 1; goto concatenate; } } else { if (hdr->substreamid != 0) { avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } } /* fill the info needed for the "dec3" atom */ info->substream[hdr->substreamid].fscod = hdr->sr_code; info->substream[hdr->substreamid].bsid = hdr->bitstream_id; info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode; info->substream[hdr->substreamid].acmod = hdr->channel_mode; info->substream[hdr->substreamid].lfeon = hdr->lfe_on; /* Parse dependent substream(s), if any */ if (pkt->size != hdr->frame_size) { int cumul_size = hdr->frame_size; int parent = hdr->substreamid; while (cumul_size != pkt->size) { GetBitContext gbc; int i; ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size); if (ret < 0) goto end; if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) { ret = AVERROR(EINVAL); goto end; } info->substream[parent].num_dep_sub++; ret /= 8; /* header is parsed up to lfeon, but custom channel map may be needed */ init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret); /* skip bsid */ skip_bits(&gbc, 5); /* skip volume control params */ for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) { skip_bits(&gbc, 5); // skip dialog normalization if (get_bits1(&gbc)) { skip_bits(&gbc, 8); // skip compression gain word } } /* get the dependent stream channel map, if exists */ if (get_bits1(&gbc)) info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f; else info->substream[parent].chan_loc |= hdr->channel_mode; cumul_size += hdr->frame_size; } } } concatenate: if (!info->num_blocks && num_blocks == 6) { ret = pkt->size; goto end; } else if (info->num_blocks + num_blocks > 6) { ret = AVERROR_INVALIDDATA; goto end; } if (!info->num_blocks) { ret = av_packet_ref(&info->pkt, pkt); if (!ret) info->num_blocks = num_blocks; goto end; } else { if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0) goto end; memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size); info->num_blocks += num_blocks; info->pkt.duration += pkt->duration; if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0) goto end; if (info->num_blocks != 6) goto end; av_packet_unref(pkt); av_packet_move_ref(pkt, &info->pkt); info->num_blocks = 0; } ret = pkt->size; end: av_free(hdr); return ret; }
169,159
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int kvm_guest_time_update(struct kvm_vcpu *v) { unsigned long flags, this_tsc_khz; struct kvm_vcpu_arch *vcpu = &v->arch; struct kvm_arch *ka = &v->kvm->arch; void *shared_kaddr; s64 kernel_ns, max_kernel_ns; u64 tsc_timestamp, host_tsc; struct pvclock_vcpu_time_info *guest_hv_clock; u8 pvclock_flags; bool use_master_clock; kernel_ns = 0; host_tsc = 0; /* * If the host uses TSC clock, then passthrough TSC as stable * to the guest. */ spin_lock(&ka->pvclock_gtod_sync_lock); use_master_clock = ka->use_master_clock; if (use_master_clock) { host_tsc = ka->master_cycle_now; kernel_ns = ka->master_kernel_ns; } spin_unlock(&ka->pvclock_gtod_sync_lock); /* Keep irq disabled to prevent changes to the clock */ local_irq_save(flags); this_tsc_khz = __get_cpu_var(cpu_tsc_khz); if (unlikely(this_tsc_khz == 0)) { local_irq_restore(flags); kvm_make_request(KVM_REQ_CLOCK_UPDATE, v); return 1; } if (!use_master_clock) { host_tsc = native_read_tsc(); kernel_ns = get_kernel_ns(); } tsc_timestamp = kvm_x86_ops->read_l1_tsc(v, host_tsc); /* * We may have to catch up the TSC to match elapsed wall clock * time for two reasons, even if kvmclock is used. * 1) CPU could have been running below the maximum TSC rate * 2) Broken TSC compensation resets the base at each VCPU * entry to avoid unknown leaps of TSC even when running * again on the same CPU. This may cause apparent elapsed * time to disappear, and the guest to stand still or run * very slowly. */ if (vcpu->tsc_catchup) { u64 tsc = compute_guest_tsc(v, kernel_ns); if (tsc > tsc_timestamp) { adjust_tsc_offset_guest(v, tsc - tsc_timestamp); tsc_timestamp = tsc; } } local_irq_restore(flags); if (!vcpu->time_page) return 0; /* * Time as measured by the TSC may go backwards when resetting the base * tsc_timestamp. The reason for this is that the TSC resolution is * higher than the resolution of the other clock scales. Thus, many * possible measurments of the TSC correspond to one measurement of any * other clock, and so a spread of values is possible. This is not a * problem for the computation of the nanosecond clock; with TSC rates * around 1GHZ, there can only be a few cycles which correspond to one * nanosecond value, and any path through this code will inevitably * take longer than that. However, with the kernel_ns value itself, * the precision may be much lower, down to HZ granularity. If the * first sampling of TSC against kernel_ns ends in the low part of the * range, and the second in the high end of the range, we can get: * * (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new * * As the sampling errors potentially range in the thousands of cycles, * it is possible such a time value has already been observed by the * guest. To protect against this, we must compute the system time as * observed by the guest and ensure the new system time is greater. */ max_kernel_ns = 0; if (vcpu->hv_clock.tsc_timestamp) { max_kernel_ns = vcpu->last_guest_tsc - vcpu->hv_clock.tsc_timestamp; max_kernel_ns = pvclock_scale_delta(max_kernel_ns, vcpu->hv_clock.tsc_to_system_mul, vcpu->hv_clock.tsc_shift); max_kernel_ns += vcpu->last_kernel_ns; } if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) { kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz, &vcpu->hv_clock.tsc_shift, &vcpu->hv_clock.tsc_to_system_mul); vcpu->hw_tsc_khz = this_tsc_khz; } /* with a master <monotonic time, tsc value> tuple, * pvclock clock reads always increase at the (scaled) rate * of guest TSC - no need to deal with sampling errors. */ if (!use_master_clock) { if (max_kernel_ns > kernel_ns) kernel_ns = max_kernel_ns; } /* With all the info we got, fill in the values */ vcpu->hv_clock.tsc_timestamp = tsc_timestamp; vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset; vcpu->last_kernel_ns = kernel_ns; vcpu->last_guest_tsc = tsc_timestamp; /* * The interface expects us to write an even number signaling that the * update is finished. Since the guest won't see the intermediate * state, we just increase by 2 at the end. */ vcpu->hv_clock.version += 2; shared_kaddr = kmap_atomic(vcpu->time_page); guest_hv_clock = shared_kaddr + vcpu->time_offset; /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */ pvclock_flags = (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED); if (vcpu->pvclock_set_guest_stopped_request) { pvclock_flags |= PVCLOCK_GUEST_STOPPED; vcpu->pvclock_set_guest_stopped_request = false; } /* If the host uses TSC clocksource, then it is stable */ if (use_master_clock) pvclock_flags |= PVCLOCK_TSC_STABLE_BIT; vcpu->hv_clock.flags = pvclock_flags; memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock, sizeof(vcpu->hv_clock)); kunmap_atomic(shared_kaddr); mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT); return 0; } Commit Message: KVM: x86: Convert MSR_KVM_SYSTEM_TIME to use gfn_to_hva_cache functions (CVE-2013-1797) There is a potential use after free issue with the handling of MSR_KVM_SYSTEM_TIME. If the guest specifies a GPA in a movable or removable memory such as frame buffers then KVM might continue to write to that address even after it's removed via KVM_SET_USER_MEMORY_REGION. KVM pins the page in memory so it's unlikely to cause an issue, but if the user space component re-purposes the memory previously used for the guest, then the guest will be able to corrupt that memory. Tested: Tested against kvmclock unit test Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]> CWE ID: CWE-399
static int kvm_guest_time_update(struct kvm_vcpu *v) { unsigned long flags, this_tsc_khz; struct kvm_vcpu_arch *vcpu = &v->arch; struct kvm_arch *ka = &v->kvm->arch; s64 kernel_ns, max_kernel_ns; u64 tsc_timestamp, host_tsc; struct pvclock_vcpu_time_info guest_hv_clock; u8 pvclock_flags; bool use_master_clock; kernel_ns = 0; host_tsc = 0; /* * If the host uses TSC clock, then passthrough TSC as stable * to the guest. */ spin_lock(&ka->pvclock_gtod_sync_lock); use_master_clock = ka->use_master_clock; if (use_master_clock) { host_tsc = ka->master_cycle_now; kernel_ns = ka->master_kernel_ns; } spin_unlock(&ka->pvclock_gtod_sync_lock); /* Keep irq disabled to prevent changes to the clock */ local_irq_save(flags); this_tsc_khz = __get_cpu_var(cpu_tsc_khz); if (unlikely(this_tsc_khz == 0)) { local_irq_restore(flags); kvm_make_request(KVM_REQ_CLOCK_UPDATE, v); return 1; } if (!use_master_clock) { host_tsc = native_read_tsc(); kernel_ns = get_kernel_ns(); } tsc_timestamp = kvm_x86_ops->read_l1_tsc(v, host_tsc); /* * We may have to catch up the TSC to match elapsed wall clock * time for two reasons, even if kvmclock is used. * 1) CPU could have been running below the maximum TSC rate * 2) Broken TSC compensation resets the base at each VCPU * entry to avoid unknown leaps of TSC even when running * again on the same CPU. This may cause apparent elapsed * time to disappear, and the guest to stand still or run * very slowly. */ if (vcpu->tsc_catchup) { u64 tsc = compute_guest_tsc(v, kernel_ns); if (tsc > tsc_timestamp) { adjust_tsc_offset_guest(v, tsc - tsc_timestamp); tsc_timestamp = tsc; } } local_irq_restore(flags); if (!vcpu->pv_time_enabled) return 0; /* * Time as measured by the TSC may go backwards when resetting the base * tsc_timestamp. The reason for this is that the TSC resolution is * higher than the resolution of the other clock scales. Thus, many * possible measurments of the TSC correspond to one measurement of any * other clock, and so a spread of values is possible. This is not a * problem for the computation of the nanosecond clock; with TSC rates * around 1GHZ, there can only be a few cycles which correspond to one * nanosecond value, and any path through this code will inevitably * take longer than that. However, with the kernel_ns value itself, * the precision may be much lower, down to HZ granularity. If the * first sampling of TSC against kernel_ns ends in the low part of the * range, and the second in the high end of the range, we can get: * * (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new * * As the sampling errors potentially range in the thousands of cycles, * it is possible such a time value has already been observed by the * guest. To protect against this, we must compute the system time as * observed by the guest and ensure the new system time is greater. */ max_kernel_ns = 0; if (vcpu->hv_clock.tsc_timestamp) { max_kernel_ns = vcpu->last_guest_tsc - vcpu->hv_clock.tsc_timestamp; max_kernel_ns = pvclock_scale_delta(max_kernel_ns, vcpu->hv_clock.tsc_to_system_mul, vcpu->hv_clock.tsc_shift); max_kernel_ns += vcpu->last_kernel_ns; } if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) { kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz, &vcpu->hv_clock.tsc_shift, &vcpu->hv_clock.tsc_to_system_mul); vcpu->hw_tsc_khz = this_tsc_khz; } /* with a master <monotonic time, tsc value> tuple, * pvclock clock reads always increase at the (scaled) rate * of guest TSC - no need to deal with sampling errors. */ if (!use_master_clock) { if (max_kernel_ns > kernel_ns) kernel_ns = max_kernel_ns; } /* With all the info we got, fill in the values */ vcpu->hv_clock.tsc_timestamp = tsc_timestamp; vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset; vcpu->last_kernel_ns = kernel_ns; vcpu->last_guest_tsc = tsc_timestamp; /* * The interface expects us to write an even number signaling that the * update is finished. Since the guest won't see the intermediate * state, we just increase by 2 at the end. */ vcpu->hv_clock.version += 2; if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time, &guest_hv_clock, sizeof(guest_hv_clock)))) return 0; /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */ pvclock_flags = (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED); if (vcpu->pvclock_set_guest_stopped_request) { pvclock_flags |= PVCLOCK_GUEST_STOPPED; vcpu->pvclock_set_guest_stopped_request = false; } /* If the host uses TSC clocksource, then it is stable */ if (use_master_clock) pvclock_flags |= PVCLOCK_TSC_STABLE_BIT; vcpu->hv_clock.flags = pvclock_flags; kvm_write_guest_cached(v->kvm, &vcpu->pv_time, &vcpu->hv_clock, sizeof(vcpu->hv_clock)); return 0; }
166,116
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void VP8XChunk::width(XMP_Uns32 val) { PutLE24(&this->data[4], val - 1); } Commit Message: CWE ID: CWE-20
void VP8XChunk::width(XMP_Uns32 val) { PutLE24(&this->data[4], val > 0 ? val - 1 : 0); }
165,366
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(PharFileInfo, __construct) { char *fname, *arch, *entry, *error; size_t fname_len; int arch_len, entry_len; phar_entry_object *entry_obj; phar_entry_info *entry_info; phar_archive_data *phar_data; zval *zobj = getThis(), arg1; if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) { return; } entry_obj = (phar_entry_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); if (entry_obj->entry) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice"); return; } if (fname_len < 7 || memcmp(fname, "phar://", 7) || phar_split_fname(fname, (int)fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0) == FAILURE) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "'%s' is not a valid phar archive URL (must have at least phar://filename.phar)", fname); return; } if (phar_open_from_filename(arch, arch_len, NULL, 0, REPORT_ERRORS, &phar_data, &error) == FAILURE) { efree(arch); efree(entry); if (error) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot open phar file '%s': %s", fname, error); efree(error); } else { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot open phar file '%s'", fname); } return; } if ((entry_info = phar_get_entry_info_dir(phar_data, entry, entry_len, 1, &error, 1)) == NULL) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot access phar file entry '%s' in archive '%s'%s%s", entry, arch, error ? ", " : "", error ? error : ""); efree(arch); efree(entry); return; } efree(arch); efree(entry); entry_obj->entry = entry_info; ZVAL_STRINGL(&arg1, fname, fname_len); zend_call_method_with_1_params(zobj, Z_OBJCE_P(zobj), &spl_ce_SplFileInfo->constructor, "__construct", NULL, &arg1); zval_ptr_dtor(&arg1); } Commit Message: CWE ID: CWE-20
PHP_METHOD(PharFileInfo, __construct) { char *fname, *arch, *entry, *error; size_t fname_len; int arch_len, entry_len; phar_entry_object *entry_obj; phar_entry_info *entry_info; phar_archive_data *phar_data; zval *zobj = getThis(), arg1; if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) { return; } entry_obj = (phar_entry_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); if (entry_obj->entry) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice"); return; } if (fname_len < 7 || memcmp(fname, "phar://", 7) || phar_split_fname(fname, (int)fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0) == FAILURE) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "'%s' is not a valid phar archive URL (must have at least phar://filename.phar)", fname); return; } if (phar_open_from_filename(arch, arch_len, NULL, 0, REPORT_ERRORS, &phar_data, &error) == FAILURE) { efree(arch); efree(entry); if (error) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot open phar file '%s': %s", fname, error); efree(error); } else { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot open phar file '%s'", fname); } return; } if ((entry_info = phar_get_entry_info_dir(phar_data, entry, entry_len, 1, &error, 1)) == NULL) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot access phar file entry '%s' in archive '%s'%s%s", entry, arch, error ? ", " : "", error ? error : ""); efree(arch); efree(entry); return; } efree(arch); efree(entry); entry_obj->entry = entry_info; ZVAL_STRINGL(&arg1, fname, fname_len); zend_call_method_with_1_params(zobj, Z_OBJCE_P(zobj), &spl_ce_SplFileInfo->constructor, "__construct", NULL, &arg1); zval_ptr_dtor(&arg1); }
165,073
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SyncType GetSyncType(const Extension* extension) { if (!IsSyncable(extension)) { return SYNC_TYPE_NONE; } if (!ManifestURL::GetUpdateURL(extension).is_empty() && !ManifestURL::UpdatesFromGallery(extension)) { return SYNC_TYPE_NONE; } if (PluginInfo::HasPlugins(extension)) return SYNC_TYPE_NONE; switch (extension->GetType()) { case Manifest::TYPE_EXTENSION: return SYNC_TYPE_EXTENSION; case Manifest::TYPE_USER_SCRIPT: if (ManifestURL::UpdatesFromGallery(extension)) return SYNC_TYPE_EXTENSION; return SYNC_TYPE_NONE; case Manifest::TYPE_HOSTED_APP: case Manifest::TYPE_LEGACY_PACKAGED_APP: case Manifest::TYPE_PLATFORM_APP: return SYNC_TYPE_APP; case Manifest::TYPE_UNKNOWN: case Manifest::TYPE_THEME: case Manifest::TYPE_SHARED_MODULE: return SYNC_TYPE_NONE; } NOTREACHED(); return SYNC_TYPE_NONE; } Commit Message: Fix syncing of NPAPI plugins. This fix adds a check for |plugin| permission while syncing NPAPI plugins. BUG=252034 Review URL: https://chromiumcodereview.appspot.com/16816024 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207830 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
SyncType GetSyncType(const Extension* extension) { if (!IsSyncable(extension)) { return SYNC_TYPE_NONE; } if (!ManifestURL::GetUpdateURL(extension).is_empty() && !ManifestURL::UpdatesFromGallery(extension)) { return SYNC_TYPE_NONE; } if (PluginInfo::HasPlugins(extension) || extension->HasAPIPermission(APIPermission::kPlugin)) { return SYNC_TYPE_NONE; } switch (extension->GetType()) { case Manifest::TYPE_EXTENSION: return SYNC_TYPE_EXTENSION; case Manifest::TYPE_USER_SCRIPT: if (ManifestURL::UpdatesFromGallery(extension)) return SYNC_TYPE_EXTENSION; return SYNC_TYPE_NONE; case Manifest::TYPE_HOSTED_APP: case Manifest::TYPE_LEGACY_PACKAGED_APP: case Manifest::TYPE_PLATFORM_APP: return SYNC_TYPE_APP; case Manifest::TYPE_UNKNOWN: case Manifest::TYPE_THEME: case Manifest::TYPE_SHARED_MODULE: return SYNC_TYPE_NONE; } NOTREACHED(); return SYNC_TYPE_NONE; }
171,248
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: run_cmd(int fd, ...) { pid_t pid; sigset_t sigm, sigm_old; /* block signals, let child establish its own handlers */ sigemptyset(&sigm); sigaddset(&sigm, SIGTERM); sigprocmask(SIG_BLOCK, &sigm, &sigm_old); pid = fork(); if ( pid < 0 ) { sigprocmask(SIG_SETMASK, &sigm_old, NULL); fd_printf(STO, "*** cannot fork: %s ***\r\n", strerror(errno)); return -1; } else if ( pid ) { /* father: picocom */ int status, r; /* reset the mask */ sigprocmask(SIG_SETMASK, &sigm_old, NULL); /* wait for child to finish */ do { r = waitpid(pid, &status, 0); } while ( r < 0 && errno == EINTR ); /* reset terminal (back to raw mode) */ term_apply(STI); /* check and report child return status */ if ( WIFEXITED(status) ) { fd_printf(STO, "\r\n*** exit status: %d ***\r\n", WEXITSTATUS(status)); return WEXITSTATUS(status); } else if ( WIFSIGNALED(status) ) { fd_printf(STO, "\r\n*** killed by signal: %d ***\r\n", WTERMSIG(status)); return -1; } else { fd_printf(STO, "\r\n*** abnormal termination: 0x%x ***\r\n", r); return -1; } } else { /* child: external program */ long fl; char cmd[512]; /* unmanage terminal, and reset it to canonical mode */ term_remove(STI); /* unmanage serial port fd, without reset */ term_erase(fd); /* set serial port fd to blocking mode */ fl = fcntl(fd, F_GETFL); fl &= ~O_NONBLOCK; fcntl(fd, F_SETFL, fl); /* connect stdin and stdout to serial port */ close(STI); close(STO); dup2(fd, STI); dup2(fd, STO); { /* build command-line */ char *c, *ce; const char *s; int n; va_list vls; strcpy(cmd, EXEC); c = &cmd[sizeof(EXEC)- 1]; ce = cmd + sizeof(cmd) - 1; va_start(vls, fd); while ( (s = va_arg(vls, const char *)) ) { n = strlen(s); if ( c + n + 1 >= ce ) break; memcpy(c, s, n); c += n; *c++ = ' '; } va_end(vls); *c = '\0'; } /* run extenral command */ fd_printf(STDERR_FILENO, "%s\n", &cmd[sizeof(EXEC) - 1]); establish_child_signal_handlers(); sigprocmask(SIG_SETMASK, &sigm_old, NULL); execl("/bin/sh", "sh", "-c", cmd, NULL); exit(42); } } Commit Message: Do not use "/bin/sh" to run external commands. Picocom no longer uses /bin/sh to run external commands for file-transfer operations. Parsing the command line and spliting it into arguments is now performed internally by picocom, using quoting rules very similar to those of the Unix shell. Hopefully, this makes it impossible to inject shell-commands when supplying filenames or extra arguments to the send- and receive-file commands. CWE ID: CWE-77
run_cmd(int fd, ...) run_cmd(int fd, const char *cmd, const char *args_extra) { pid_t pid; sigset_t sigm, sigm_old; /* block signals, let child establish its own handlers */ sigemptyset(&sigm); sigaddset(&sigm, SIGTERM); sigprocmask(SIG_BLOCK, &sigm, &sigm_old); pid = fork(); if ( pid < 0 ) { sigprocmask(SIG_SETMASK, &sigm_old, NULL); fd_printf(STO, "*** cannot fork: %s ***\r\n", strerror(errno)); return -1; } else if ( pid ) { /* father: picocom */ int status, r; /* reset the mask */ sigprocmask(SIG_SETMASK, &sigm_old, NULL); /* wait for child to finish */ do { r = waitpid(pid, &status, 0); } while ( r < 0 && errno == EINTR ); /* reset terminal (back to raw mode) */ term_apply(STI); /* check and report child return status */ if ( WIFEXITED(status) ) { fd_printf(STO, "\r\n*** exit status: %d ***\r\n", WEXITSTATUS(status)); return WEXITSTATUS(status); } else if ( WIFSIGNALED(status) ) { fd_printf(STO, "\r\n*** killed by signal: %d ***\r\n", WTERMSIG(status)); return -1; } else { fd_printf(STO, "\r\n*** abnormal termination: 0x%x ***\r\n", r); return -1; } } else { /* child: external program */ long fl; int argc; char *argv[RUNCMD_ARGS_MAX + 1]; int r; /* unmanage terminal, and reset it to canonical mode */ term_remove(STI); /* unmanage serial port fd, without reset */ term_erase(fd); /* set serial port fd to blocking mode */ fl = fcntl(fd, F_GETFL); fl &= ~O_NONBLOCK; fcntl(fd, F_SETFL, fl); /* connect stdin and stdout to serial port */ close(STI); close(STO); dup2(fd, STI); dup2(fd, STO); /* build command arguments vector */ argc = 0; r = split_quoted(cmd, &argc, argv, RUNCMD_ARGS_MAX); if ( r < 0 ) { fd_printf(STDERR_FILENO, "Cannot parse command\n"); exit(RUNCMD_EXEC_FAIL); } r = split_quoted(args_extra, &argc, argv, RUNCMD_ARGS_MAX); if ( r < 0 ) { fd_printf(STDERR_FILENO, "Cannot parse extra args\n"); exit(RUNCMD_EXEC_FAIL); } if ( argc < 1 ) { fd_printf(STDERR_FILENO, "No command given\n"); exit(RUNCMD_EXEC_FAIL); } argv[argc] = NULL; /* run extenral command */ fd_printf(STDERR_FILENO, "$ %s %s\n", cmd, args_extra); establish_child_signal_handlers(); sigprocmask(SIG_SETMASK, &sigm_old, NULL); execvp(argv[0], argv); fd_printf(STDERR_FILENO, "exec: %s\n", strerror(errno)); exit(RUNCMD_EXEC_FAIL); } }
168,850
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MessageService::OpenChannelToExtension( int source_process_id, int source_routing_id, int receiver_port_id, const std::string& source_extension_id, const std::string& target_extension_id, const std::string& channel_name) { content::RenderProcessHost* source = content::RenderProcessHost::FromID(source_process_id); if (!source) return; Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext()); MessagePort* receiver = new ExtensionMessagePort( GetExtensionProcess(profile, target_extension_id), MSG_ROUTING_CONTROL, target_extension_id); WebContents* source_contents = tab_util::GetWebContentsByID( source_process_id, source_routing_id); std::string tab_json = "null"; if (source_contents) { scoped_ptr<DictionaryValue> tab_value(ExtensionTabUtil::CreateTabValue( source_contents, ExtensionTabUtil::INCLUDE_PRIVACY_SENSITIVE_FIELDS)); base::JSONWriter::Write(tab_value.get(), &tab_json); } OpenChannelParams* params = new OpenChannelParams(source, tab_json, receiver, receiver_port_id, source_extension_id, target_extension_id, channel_name); if (MaybeAddPendingOpenChannelTask(profile, params)) { return; } OpenChannelImpl(scoped_ptr<OpenChannelParams>(params)); } Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the "tabs" permission. BUG=168442 Review URL: https://chromiumcodereview.appspot.com/11824004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void MessageService::OpenChannelToExtension( int source_process_id, int source_routing_id, int receiver_port_id, const std::string& source_extension_id, const std::string& target_extension_id, const std::string& channel_name) { content::RenderProcessHost* source = content::RenderProcessHost::FromID(source_process_id); if (!source) return; Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext()); MessagePort* receiver = new ExtensionMessagePort( GetExtensionProcess(profile, target_extension_id), MSG_ROUTING_CONTROL, target_extension_id); WebContents* source_contents = tab_util::GetWebContentsByID( source_process_id, source_routing_id); std::string tab_json = "null"; if (source_contents) { scoped_ptr<DictionaryValue> tab_value(ExtensionTabUtil::CreateTabValue( source_contents)); base::JSONWriter::Write(tab_value.get(), &tab_json); } OpenChannelParams* params = new OpenChannelParams(source, tab_json, receiver, receiver_port_id, source_extension_id, target_extension_id, channel_name); if (MaybeAddPendingOpenChannelTask(profile, params)) { return; } OpenChannelImpl(scoped_ptr<OpenChannelParams>(params)); }
171,446
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: TEE_Result tee_mmu_check_access_rights(const struct user_ta_ctx *utc, uint32_t flags, uaddr_t uaddr, size_t len) { uaddr_t a; size_t addr_incr = MIN(CORE_MMU_USER_CODE_SIZE, CORE_MMU_USER_PARAM_SIZE); if (ADD_OVERFLOW(uaddr, len, &a)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_NONSECURE) && (flags & TEE_MEMORY_ACCESS_SECURE)) return TEE_ERROR_ACCESS_DENIED; /* * Rely on TA private memory test to check if address range is private * to TA or not. */ if (!(flags & TEE_MEMORY_ACCESS_ANY_OWNER) && !tee_mmu_is_vbuf_inside_ta_private(utc, (void *)uaddr, len)) return TEE_ERROR_ACCESS_DENIED; for (a = uaddr; a < (uaddr + len); a += addr_incr) { uint32_t attr; TEE_Result res; res = tee_mmu_user_va2pa_attr(utc, (void *)a, NULL, &attr); if (res != TEE_SUCCESS) return res; if ((flags & TEE_MEMORY_ACCESS_NONSECURE) && (attr & TEE_MATTR_SECURE)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_SECURE) && !(attr & TEE_MATTR_SECURE)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_WRITE) && !(attr & TEE_MATTR_UW)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_READ) && !(attr & TEE_MATTR_UR)) return TEE_ERROR_ACCESS_DENIED; } return TEE_SUCCESS; } Commit Message: core: tee_mmu_check_access_rights() check all pages Prior to this patch tee_mmu_check_access_rights() checks an address in each page of a supplied range. If both the start and length of that range is unaligned the last page in the range is sometimes not checked. With this patch the first address of each page in the range is checked to simplify the logic of checking each page and the range and also to cover the last page under all circumstances. Fixes: OP-TEE-2018-0005: "tee_mmu_check_access_rights does not check final page of TA buffer" Signed-off-by: Jens Wiklander <[email protected]> Tested-by: Joakim Bech <[email protected]> (QEMU v7, v8) Reviewed-by: Joakim Bech <[email protected]> Reported-by: Riscure <[email protected]> Reported-by: Alyssa Milburn <[email protected]> Acked-by: Etienne Carriere <[email protected]> CWE ID: CWE-20
TEE_Result tee_mmu_check_access_rights(const struct user_ta_ctx *utc, uint32_t flags, uaddr_t uaddr, size_t len) { uaddr_t a; uaddr_t end_addr = 0; size_t addr_incr = MIN(CORE_MMU_USER_CODE_SIZE, CORE_MMU_USER_PARAM_SIZE); if (ADD_OVERFLOW(uaddr, len, &end_addr)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_NONSECURE) && (flags & TEE_MEMORY_ACCESS_SECURE)) return TEE_ERROR_ACCESS_DENIED; /* * Rely on TA private memory test to check if address range is private * to TA or not. */ if (!(flags & TEE_MEMORY_ACCESS_ANY_OWNER) && !tee_mmu_is_vbuf_inside_ta_private(utc, (void *)uaddr, len)) return TEE_ERROR_ACCESS_DENIED; for (a = ROUNDDOWN(uaddr, addr_incr); a < end_addr; a += addr_incr) { uint32_t attr; TEE_Result res; res = tee_mmu_user_va2pa_attr(utc, (void *)a, NULL, &attr); if (res != TEE_SUCCESS) return res; if ((flags & TEE_MEMORY_ACCESS_NONSECURE) && (attr & TEE_MATTR_SECURE)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_SECURE) && !(attr & TEE_MATTR_SECURE)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_WRITE) && !(attr & TEE_MATTR_UW)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_READ) && !(attr & TEE_MATTR_UR)) return TEE_ERROR_ACCESS_DENIED; } return TEE_SUCCESS; }
169,473
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MojoJpegDecodeAccelerator::Decode( const BitstreamBuffer& bitstream_buffer, const scoped_refptr<VideoFrame>& video_frame) { DCHECK(io_task_runner_->BelongsToCurrentThread()); DCHECK(jpeg_decoder_.is_bound()); DCHECK( base::SharedMemory::IsHandleValid(video_frame->shared_memory_handle())); base::SharedMemoryHandle output_handle = base::SharedMemory::DuplicateHandle(video_frame->shared_memory_handle()); if (!base::SharedMemory::IsHandleValid(output_handle)) { DLOG(ERROR) << "Failed to duplicate handle of VideoFrame"; return; } size_t output_buffer_size = VideoFrame::AllocationSize( video_frame->format(), video_frame->coded_size()); mojo::ScopedSharedBufferHandle output_frame_handle = mojo::WrapSharedMemoryHandle(output_handle, output_buffer_size, false /* read_only */); jpeg_decoder_->Decode(bitstream_buffer, video_frame->coded_size(), std::move(output_frame_handle), base::checked_cast<uint32_t>(output_buffer_size), base::Bind(&MojoJpegDecodeAccelerator::OnDecodeAck, base::Unretained(this))); } 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} CWE ID: CWE-787
void MojoJpegDecodeAccelerator::Decode( const BitstreamBuffer& bitstream_buffer, const scoped_refptr<VideoFrame>& video_frame) { DCHECK(io_task_runner_->BelongsToCurrentThread()); DCHECK(jpeg_decoder_.is_bound()); DCHECK( base::SharedMemory::IsHandleValid(video_frame->shared_memory_handle())); base::SharedMemoryHandle output_handle = base::SharedMemory::DuplicateHandle(video_frame->shared_memory_handle()); if (!base::SharedMemory::IsHandleValid(output_handle)) { DLOG(ERROR) << "Failed to duplicate handle of VideoFrame"; return; } size_t output_buffer_size = VideoFrame::AllocationSize( video_frame->format(), video_frame->coded_size()); mojo::ScopedSharedBufferHandle output_frame_handle = mojo::WrapSharedMemoryHandle( output_handle, output_buffer_size, mojo::UnwrappedSharedMemoryHandleProtection::kReadWrite); jpeg_decoder_->Decode(bitstream_buffer, video_frame->coded_size(), std::move(output_frame_handle), base::checked_cast<uint32_t>(output_buffer_size), base::Bind(&MojoJpegDecodeAccelerator::OnDecodeAck, base::Unretained(this))); }
172,872
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: jas_matrix_t *jas_seq2d_create(int xstart, int ystart, int xend, int yend) { jas_matrix_t *matrix; assert(xstart <= xend && ystart <= yend); if (!(matrix = jas_matrix_create(yend - ystart, xend - xstart))) { return 0; } matrix->xstart_ = xstart; matrix->ystart_ = ystart; matrix->xend_ = xend; matrix->yend_ = yend; return matrix; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190
jas_matrix_t *jas_seq2d_create(int xstart, int ystart, int xend, int yend) jas_matrix_t *jas_seq2d_create(jas_matind_t xstart, jas_matind_t ystart, jas_matind_t xend, jas_matind_t yend) { jas_matrix_t *matrix; assert(xstart <= xend && ystart <= yend); if (!(matrix = jas_matrix_create(yend - ystart, xend - xstart))) { return 0; } matrix->xstart_ = xstart; matrix->ystart_ = ystart; matrix->xend_ = xend; matrix->yend_ = yend; return matrix; }
168,709
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void net_tx_pkt_init(struct NetTxPkt **pkt, PCIDevice *pci_dev, uint32_t max_frags, bool has_virt_hdr) { struct NetTxPkt *p = g_malloc0(sizeof *p); p->pci_dev = pci_dev; p->vec = g_malloc((sizeof *p->vec) * (max_frags + NET_TX_PKT_PL_START_FRAG)); p->raw = g_malloc((sizeof *p->raw) * max_frags); p->max_payload_frags = max_frags; p->max_raw_frags = max_frags; p->max_raw_frags = max_frags; p->has_virt_hdr = has_virt_hdr; p->vec[NET_TX_PKT_VHDR_FRAG].iov_base = &p->virt_hdr; p->vec[NET_TX_PKT_VHDR_FRAG].iov_len = p->has_virt_hdr ? sizeof p->virt_hdr : 0; p->vec[NET_TX_PKT_L2HDR_FRAG].iov_base = &p->l2_hdr; p->vec[NET_TX_PKT_L3HDR_FRAG].iov_base = &p->l3_hdr; *pkt = p; } Commit Message: CWE ID: CWE-190
void net_tx_pkt_init(struct NetTxPkt **pkt, PCIDevice *pci_dev, uint32_t max_frags, bool has_virt_hdr) { struct NetTxPkt *p = g_malloc0(sizeof *p); p->pci_dev = pci_dev; p->vec = g_new(struct iovec, max_frags + NET_TX_PKT_PL_START_FRAG); p->raw = g_new(struct iovec, max_frags); p->max_payload_frags = max_frags; p->max_raw_frags = max_frags; p->max_raw_frags = max_frags; p->has_virt_hdr = has_virt_hdr; p->vec[NET_TX_PKT_VHDR_FRAG].iov_base = &p->virt_hdr; p->vec[NET_TX_PKT_VHDR_FRAG].iov_len = p->has_virt_hdr ? sizeof p->virt_hdr : 0; p->vec[NET_TX_PKT_L2HDR_FRAG].iov_base = &p->l2_hdr; p->vec[NET_TX_PKT_L3HDR_FRAG].iov_base = &p->l3_hdr; *pkt = p; }
164,947
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void mpage_put_bnr_to_bhs(struct mpage_da_data *mpd, sector_t logical, struct buffer_head *exbh) { struct inode *inode = mpd->inode; struct address_space *mapping = inode->i_mapping; int blocks = exbh->b_size >> inode->i_blkbits; sector_t pblock = exbh->b_blocknr, cur_logical; struct buffer_head *head, *bh; pgoff_t index, end; struct pagevec pvec; int nr_pages, i; index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits); end = (logical + blocks - 1) >> (PAGE_CACHE_SHIFT - inode->i_blkbits); cur_logical = index << (PAGE_CACHE_SHIFT - inode->i_blkbits); pagevec_init(&pvec, 0); while (index <= end) { /* XXX: optimize tail */ nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE); if (nr_pages == 0) break; for (i = 0; i < nr_pages; i++) { struct page *page = pvec.pages[i]; index = page->index; if (index > end) break; index++; BUG_ON(!PageLocked(page)); BUG_ON(PageWriteback(page)); BUG_ON(!page_has_buffers(page)); bh = page_buffers(page); head = bh; /* skip blocks out of the range */ do { if (cur_logical >= logical) break; cur_logical++; } while ((bh = bh->b_this_page) != head); do { if (cur_logical >= logical + blocks) break; if (buffer_delay(bh) || buffer_unwritten(bh)) { BUG_ON(bh->b_bdev != inode->i_sb->s_bdev); if (buffer_delay(bh)) { clear_buffer_delay(bh); bh->b_blocknr = pblock; } else { /* * unwritten already should have * blocknr assigned. Verify that */ clear_buffer_unwritten(bh); BUG_ON(bh->b_blocknr != pblock); } } else if (buffer_mapped(bh)) BUG_ON(bh->b_blocknr != pblock); cur_logical++; pblock++; } while ((bh = bh->b_this_page) != head); } pagevec_release(&pvec); } } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID:
static void mpage_put_bnr_to_bhs(struct mpage_da_data *mpd, sector_t logical, struct buffer_head *exbh) { struct inode *inode = mpd->inode; struct address_space *mapping = inode->i_mapping; int blocks = exbh->b_size >> inode->i_blkbits; sector_t pblock = exbh->b_blocknr, cur_logical; struct buffer_head *head, *bh; pgoff_t index, end; struct pagevec pvec; int nr_pages, i; index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits); end = (logical + blocks - 1) >> (PAGE_CACHE_SHIFT - inode->i_blkbits); cur_logical = index << (PAGE_CACHE_SHIFT - inode->i_blkbits); pagevec_init(&pvec, 0); while (index <= end) { /* XXX: optimize tail */ nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE); if (nr_pages == 0) break; for (i = 0; i < nr_pages; i++) { struct page *page = pvec.pages[i]; index = page->index; if (index > end) break; index++; BUG_ON(!PageLocked(page)); BUG_ON(PageWriteback(page)); BUG_ON(!page_has_buffers(page)); bh = page_buffers(page); head = bh; /* skip blocks out of the range */ do { if (cur_logical >= logical) break; cur_logical++; } while ((bh = bh->b_this_page) != head); do { if (cur_logical >= logical + blocks) break; if (buffer_delay(bh) || buffer_unwritten(bh)) { BUG_ON(bh->b_bdev != inode->i_sb->s_bdev); if (buffer_delay(bh)) { clear_buffer_delay(bh); bh->b_blocknr = pblock; } else { /* * unwritten already should have * blocknr assigned. Verify that */ clear_buffer_unwritten(bh); BUG_ON(bh->b_blocknr != pblock); } } else if (buffer_mapped(bh)) BUG_ON(bh->b_blocknr != pblock); if (buffer_uninit(exbh)) set_buffer_uninit(bh); cur_logical++; pblock++; } while ((bh = bh->b_this_page) != head); } pagevec_release(&pvec); } }
167,552
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Add(int original_content_length, int received_content_length) { AddInt64ToListPref( kNumDaysInHistory - 1, original_content_length, original_update_.Get()); AddInt64ToListPref( kNumDaysInHistory - 1, received_content_length, received_update_.Get()); } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
void Add(int original_content_length, int received_content_length) { original_.Add(original_content_length); received_.Add(received_content_length); }
171,321
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: pam_sm_close_session (pam_handle_t *pamh, int flags UNUSED, int argc, const char **argv) { void *cookiefile; int i, debug = 0; const char* user; struct passwd *tpwd = NULL; uid_t unlinkuid, fsuid; if (pam_get_user(pamh, &user, NULL) != PAM_SUCCESS) pam_syslog(pamh, LOG_ERR, "error determining target user's name"); else { tpwd = pam_modutil_getpwnam(pamh, user); if (!tpwd) pam_syslog(pamh, LOG_ERR, "error determining target user's UID"); else unlinkuid = tpwd->pw_uid; } /* Parse arguments. We don't understand many, so no sense in breaking * this into a separate function. */ for (i = 0; i < argc; i++) { if (strcmp(argv[i], "debug") == 0) { debug = 1; continue; } if (strncmp(argv[i], "xauthpath=", 10) == 0) { continue; } if (strncmp(argv[i], "systemuser=", 11) == 0) { continue; } if (strncmp(argv[i], "targetuser=", 11) == 0) { continue; } pam_syslog(pamh, LOG_WARNING, "unrecognized option `%s'", argv[i]); } /* Try to retrieve the name of a file we created when the session was * opened. */ if (pam_get_data(pamh, DATANAME, (const void**) &cookiefile) == PAM_SUCCESS) { /* We'll only try to remove the file once. */ if (strlen((char*)cookiefile) > 0) { if (debug) { pam_syslog(pamh, LOG_DEBUG, "removing `%s'", (char*)cookiefile); } /* NFS with root_squash requires non-root user */ if (tpwd) fsuid = setfsuid(unlinkuid); unlink((char*)cookiefile); if (tpwd) setfsuid(fsuid); *((char*)cookiefile) = '\0'; } } return PAM_SUCCESS; } Commit Message: CWE ID:
pam_sm_close_session (pam_handle_t *pamh, int flags UNUSED, int argc, const char **argv) { int i, debug = 0; const char *user; const void *data; const char *cookiefile; struct passwd *tpwd; uid_t fsuid; /* Try to retrieve the name of a file we created when * the session was opened. */ if (pam_get_data(pamh, DATANAME, &data) != PAM_SUCCESS) return PAM_SUCCESS; cookiefile = data; /* Parse arguments. We don't understand many, so * no sense in breaking this into a separate function. */ for (i = 0; i < argc; i++) { if (strcmp(argv[i], "debug") == 0) { debug = 1; continue; } if (strncmp(argv[i], "xauthpath=", 10) == 0) continue; if (strncmp(argv[i], "systemuser=", 11) == 0) continue; if (strncmp(argv[i], "targetuser=", 11) == 0) continue; pam_syslog(pamh, LOG_WARNING, "unrecognized option `%s'", argv[i]); } if (pam_get_user(pamh, &user, NULL) != PAM_SUCCESS) { pam_syslog(pamh, LOG_ERR, "error determining target user's name"); return PAM_SESSION_ERR; } if (!(tpwd = pam_modutil_getpwnam(pamh, user))) { pam_syslog(pamh, LOG_ERR, "error determining target user's UID"); return PAM_SESSION_ERR; } if (debug) pam_syslog(pamh, LOG_DEBUG, "removing `%s'", cookiefile); fsuid = setfsuid(tpwd->pw_uid); unlink(cookiefile); setfsuid(fsuid); return PAM_SUCCESS; }
164,789
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static char *print_string_ptr( const char *str ) { const char *ptr; char *ptr2, *out; int len = 0; unsigned char token; if ( ! str ) return cJSON_strdup( "" ); ptr = str; while ( ( token = *ptr ) && ++len ) { if ( strchr( "\"\\\b\f\n\r\t", token ) ) ++len; else if ( token < 32 ) len += 5; ++ptr; } if ( ! ( out = (char*) cJSON_malloc( len + 3 ) ) ) return 0; ptr2 = out; ptr = str; *ptr2++ = '\"'; while ( *ptr ) { if ( (unsigned char) *ptr > 31 && *ptr != '\"' && *ptr != '\\' ) *ptr2++ = *ptr++; else { *ptr2++ = '\\'; switch ( token = *ptr++ ) { case '\\': *ptr2++ = '\\'; break; case '\"': *ptr2++ = '\"'; break; case '\b': *ptr2++ = 'b'; break; case '\f': *ptr2++ = 'f'; break; case '\n': *ptr2++ = 'n'; break; case '\r': *ptr2++ = 'r'; break; case '\t': *ptr2++ = 't'; break; default: /* Escape and print. */ sprintf( ptr2, "u%04x", token ); ptr2 += 5; break; } } } *ptr2++ = '\"'; *ptr2++ = 0; return out; } 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]> CWE ID: CWE-119
static char *print_string_ptr( const char *str ) static char *print_string_ptr(const char *str,printbuffer *p) { const char *ptr;char *ptr2,*out;int len=0,flag=0;unsigned char token; if (!str) { if (p) out=ensure(p,3); else out=(char*)cJSON_malloc(3); if (!out) return 0; strcpy(out,"\"\""); return out; } for (ptr=str;*ptr;ptr++) flag|=((*ptr>0 && *ptr<32)||(*ptr=='\"')||(*ptr=='\\'))?1:0; if (!flag) { len=ptr-str; if (p) out=ensure(p,len+3); else out=(char*)cJSON_malloc(len+3); if (!out) return 0; ptr2=out;*ptr2++='\"'; strcpy(ptr2,str); ptr2[len]='\"'; ptr2[len+1]=0; return out; } ptr=str;while ((token=*ptr) && ++len) {if (strchr("\"\\\b\f\n\r\t",token)) len++; else if (token<32) len+=5;ptr++;} if (p) out=ensure(p,len+3); else out=(char*)cJSON_malloc(len+3); if (!out) return 0; ptr2=out;ptr=str; *ptr2++='\"'; while (*ptr) { if ((unsigned char)*ptr>31 && *ptr!='\"' && *ptr!='\\') *ptr2++=*ptr++; else { *ptr2++='\\'; switch (token=*ptr++) { case '\\': *ptr2++='\\'; break; case '\"': *ptr2++='\"'; break; case '\b': *ptr2++='b'; break; case '\f': *ptr2++='f'; break; case '\n': *ptr2++='n'; break; case '\r': *ptr2++='r'; break; case '\t': *ptr2++='t'; break; default: sprintf(ptr2,"u%04x",token);ptr2+=5; break; /* escape and print */ } } } *ptr2++='\"';*ptr2++=0; return out; }
167,310
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void build_l4proto_icmp(const struct nf_conntrack *ct, struct nethdr *n) { ct_build_u8(ct, ATTR_ICMP_TYPE, n, NTA_ICMP_TYPE); ct_build_u8(ct, ATTR_ICMP_CODE, n, NTA_ICMP_CODE); ct_build_u16(ct, ATTR_ICMP_ID, n, NTA_ICMP_ID); ct_build_group(ct, ATTR_GRP_ORIG_PORT, n, NTA_PORT, sizeof(struct nfct_attr_grp_port)); } Commit Message: CWE ID: CWE-17
static void build_l4proto_icmp(const struct nf_conntrack *ct, struct nethdr *n) { /* This is also used by ICMPv6 and nf_conntrack_ipv6 is optional */ if (!nfct_attr_is_set(ct, ATTR_ICMP_TYPE)) return; ct_build_u8(ct, ATTR_ICMP_TYPE, n, NTA_ICMP_TYPE); ct_build_u8(ct, ATTR_ICMP_CODE, n, NTA_ICMP_CODE); ct_build_u16(ct, ATTR_ICMP_ID, n, NTA_ICMP_ID); ct_build_group(ct, ATTR_GRP_ORIG_PORT, n, NTA_PORT, sizeof(struct nfct_attr_grp_port)); }
164,630
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: jbig2_find_changing_element(const byte *line, int x, int w) { int a, b; if (line == 0) return w; if (x == -1) { a = 0; x = 0; } else { } while (x < w) { b = getbit(line, x); if (a != b) break; x++; } return x; } Commit Message: CWE ID: CWE-119
jbig2_find_changing_element(const byte *line, int x, int w) jbig2_find_changing_element(const byte *line, uint32_t x, uint32_t w) { int a, b; if (line == 0) return (int)w; if (x == MINUS1) { a = 0; x = 0; } else { } while (x < w) { b = getbit(line, x); if (a != b) break; x++; } return x; }
165,494
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: chrand_principal3_2_svc(chrand3_arg *arg, struct svc_req *rqstp) { static chrand_ret ret; krb5_keyblock *k; int nkeys; char *prime_arg, *funcname; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_chrand_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; funcname = "kadm5_randkey_principal"; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ)) { ret.code = randkey_principal_wrapper_3((void *)handle, arg->princ, arg->keepold, arg->n_ks_tuple, arg->ks_tuple, &k, &nkeys); } else if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_CHANGEPW, arg->princ, NULL)) { ret.code = kadm5_randkey_principal_3((void *)handle, arg->princ, arg->keepold, arg->n_ks_tuple, arg->ks_tuple, &k, &nkeys); } else { log_unauth(funcname, prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_CHANGEPW; } if(ret.code == KADM5_OK) { ret.keys = k; ret.n_keys = nkeys; } if(ret.code != KADM5_AUTH_CHANGEPW) { if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done(funcname, prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
chrand_principal3_2_svc(chrand3_arg *arg, struct svc_req *rqstp) { static chrand_ret ret; krb5_keyblock *k; int nkeys; char *prime_arg, *funcname; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_chrand_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; funcname = "kadm5_randkey_principal"; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ)) { ret.code = randkey_principal_wrapper_3((void *)handle, arg->princ, arg->keepold, arg->n_ks_tuple, arg->ks_tuple, &k, &nkeys); } else if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_CHANGEPW, arg->princ, NULL)) { ret.code = kadm5_randkey_principal_3((void *)handle, arg->princ, arg->keepold, arg->n_ks_tuple, arg->ks_tuple, &k, &nkeys); } else { log_unauth(funcname, prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_CHANGEPW; } if(ret.code == KADM5_OK) { ret.keys = k; ret.n_keys = nkeys; } if(ret.code != KADM5_AUTH_CHANGEPW) { if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done(funcname, prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,506
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: dtls1_process_record(SSL *s) { int i,al; int enc_err; SSL_SESSION *sess; SSL3_RECORD *rr; unsigned int mac_size; unsigned char md[EVP_MAX_MD_SIZE]; rr= &(s->s3->rrec); sess = s->session; /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, * and we have that many bytes in s->packet */ rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]); /* ok, we can now read from 's->packet' data into 'rr' * rr->input points at rr->length bytes, which * need to be copied into rr->data by either * the decryption or by the decompression * When the data is 'copied' into the rr->data buffer, * rr->input will be pointed at the new buffer */ /* We now have - encrypted [ MAC [ compressed [ plain ] ] ] * rr->length bytes of encrypted compressed stuff. */ /* check is not needed I believe */ if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG); goto f_err; } /* decrypt in place in 'rr->input' */ rr->data=rr->input; rr->orig_len=rr->length; enc_err = s->method->ssl3_enc->enc(s,0); /* enc_err is: * 0: (in non-constant time) if the record is publically invalid. * 1: if the padding is valid * -1: if the padding is invalid */ if (enc_err == 0) { /* For DTLS we simply ignore bad packets. */ rr->length = 0; s->packet_length = 0; goto err; } #ifdef TLS_DEBUG printf("dec %d\n",rr->length); { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); } printf("\n"); #endif /* r->length is now the compressed data plus mac */ if ((sess != NULL) && (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) { /* s->read_hash != NULL => mac_size != -1 */ unsigned char *mac = NULL; unsigned char mac_tmp[EVP_MAX_MD_SIZE]; mac_size=EVP_MD_CTX_size(s->read_hash); OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE); /* orig_len is the length of the record before any padding was * removed. This is public information, as is the MAC in use, * therefore we can safely process the record in a different * amount of time if it's too short to possibly contain a MAC. */ if (rr->orig_len < mac_size || /* CBC records must have a padding length byte too. */ (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE && rr->orig_len < mac_size+1)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_LENGTH_TOO_SHORT); goto f_err; } if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) { /* We update the length so that the TLS header bytes * can be constructed correctly but we need to extract * the MAC in constant time from within the record, * without leaking the contents of the padding bytes. * */ mac = mac_tmp; ssl3_cbc_copy_mac(mac_tmp, rr, mac_size); rr->length -= mac_size; } else { /* In this case there's no padding, so |rec->orig_len| * equals |rec->length| and we checked that there's * enough bytes for |mac_size| above. */ rr->length -= mac_size; mac = &rr->data[rr->length]; } i=s->method->ssl3_enc->mac(s,md,0 /* not send */); if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) enc_err = -1; if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size) enc_err = -1; } if (enc_err < 0) { /* decryption failed, silently discard message */ rr->length = 0; s->packet_length = 0; goto err; } /* r->length is now just compressed */ if (s->expand != NULL) { if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG); goto f_err; } if (!ssl3_do_uncompress(s)) { al=SSL_AD_DECOMPRESSION_FAILURE; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_BAD_DECOMPRESSION); goto f_err; } } if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } rr->off=0; /*- * So at this point the following is true * ssl->s3->rrec.type is the type of record * ssl->s3->rrec.length == number of bytes in record * ssl->s3->rrec.off == offset to first valid byte * ssl->s3->rrec.data == where to take bytes from, increment * after use :-). */ /* we have pulled in a full packet so zero things */ s->packet_length=0; dtls1_record_bitmap_update(s, &(s->d1->bitmap));/* Mark receipt of record. */ return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(0); } Commit Message: A memory leak can occur in dtls1_buffer_record if either of the calls to ssl3_setup_buffers or pqueue_insert fail. The former will fail if there is a malloc failure, whilst the latter will fail if attempting to add a duplicate record to the queue. This should never happen because duplicate records should be detected and dropped before any attempt to add them to the queue. Unfortunately records that arrive that are for the next epoch are not being recorded correctly, and therefore replays are not being detected. Additionally, these "should not happen" failures that can occur in dtls1_buffer_record are not being treated as fatal and therefore an attacker could exploit this by sending repeated replay records for the next epoch, eventually causing a DoS through memory exhaustion. Thanks to Chris Mueller for reporting this issue and providing initial analysis and a patch. Further analysis and the final patch was performed by Matt Caswell from the OpenSSL development team. CVE-2015-0206 Reviewed-by: Dr Stephen Henson <[email protected]> CWE ID: CWE-119
dtls1_process_record(SSL *s) { int i,al; int enc_err; SSL_SESSION *sess; SSL3_RECORD *rr; unsigned int mac_size; unsigned char md[EVP_MAX_MD_SIZE]; rr= &(s->s3->rrec); sess = s->session; /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, * and we have that many bytes in s->packet */ rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]); /* ok, we can now read from 's->packet' data into 'rr' * rr->input points at rr->length bytes, which * need to be copied into rr->data by either * the decryption or by the decompression * When the data is 'copied' into the rr->data buffer, * rr->input will be pointed at the new buffer */ /* We now have - encrypted [ MAC [ compressed [ plain ] ] ] * rr->length bytes of encrypted compressed stuff. */ /* check is not needed I believe */ if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG); goto f_err; } /* decrypt in place in 'rr->input' */ rr->data=rr->input; rr->orig_len=rr->length; enc_err = s->method->ssl3_enc->enc(s,0); /* enc_err is: * 0: (in non-constant time) if the record is publically invalid. * 1: if the padding is valid * -1: if the padding is invalid */ if (enc_err == 0) { /* For DTLS we simply ignore bad packets. */ rr->length = 0; s->packet_length = 0; goto err; } #ifdef TLS_DEBUG printf("dec %d\n",rr->length); { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); } printf("\n"); #endif /* r->length is now the compressed data plus mac */ if ((sess != NULL) && (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) { /* s->read_hash != NULL => mac_size != -1 */ unsigned char *mac = NULL; unsigned char mac_tmp[EVP_MAX_MD_SIZE]; mac_size=EVP_MD_CTX_size(s->read_hash); OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE); /* orig_len is the length of the record before any padding was * removed. This is public information, as is the MAC in use, * therefore we can safely process the record in a different * amount of time if it's too short to possibly contain a MAC. */ if (rr->orig_len < mac_size || /* CBC records must have a padding length byte too. */ (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE && rr->orig_len < mac_size+1)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_LENGTH_TOO_SHORT); goto f_err; } if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) { /* We update the length so that the TLS header bytes * can be constructed correctly but we need to extract * the MAC in constant time from within the record, * without leaking the contents of the padding bytes. * */ mac = mac_tmp; ssl3_cbc_copy_mac(mac_tmp, rr, mac_size); rr->length -= mac_size; } else { /* In this case there's no padding, so |rec->orig_len| * equals |rec->length| and we checked that there's * enough bytes for |mac_size| above. */ rr->length -= mac_size; mac = &rr->data[rr->length]; } i=s->method->ssl3_enc->mac(s,md,0 /* not send */); if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) enc_err = -1; if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size) enc_err = -1; } if (enc_err < 0) { /* decryption failed, silently discard message */ rr->length = 0; s->packet_length = 0; goto err; } /* r->length is now just compressed */ if (s->expand != NULL) { if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG); goto f_err; } if (!ssl3_do_uncompress(s)) { al=SSL_AD_DECOMPRESSION_FAILURE; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_BAD_DECOMPRESSION); goto f_err; } } if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } rr->off=0; /*- * So at this point the following is true * ssl->s3->rrec.type is the type of record * ssl->s3->rrec.length == number of bytes in record * ssl->s3->rrec.off == offset to first valid byte * ssl->s3->rrec.data == where to take bytes from, increment * after use :-). */ /* we have pulled in a full packet so zero things */ s->packet_length=0; return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(0); }
166,748
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(Phar, unlinkArchive) { char *fname, *error, *zname, *arch, *entry; size_t fname_len; int zname_len, arch_len, entry_len; phar_archive_data *phar; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) { RETURN_FALSE; } if (!fname_len) { zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"\""); return; } if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error)) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"%s\": %s", fname, error); efree(error); } else { zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"%s\"", fname); } return; } zname = (char*)zend_get_executed_filename(); zname_len = strlen(zname); if (zname_len > 7 && !memcmp(zname, "phar://", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) { if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" cannot be unlinked from within itself", fname); efree(arch); efree(entry); return; } efree(arch); efree(entry); } if (phar->is_persistent) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" is in phar.cache_list, cannot unlinkArchive()", fname); return; } if (phar->refcount) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()", fname); return; } fname = estrndup(phar->fname, phar->fname_len); /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; phar_archive_delref(phar); unlink(fname); efree(fname); RETURN_TRUE; } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, unlinkArchive) { char *fname, *error, *zname, *arch, *entry; size_t fname_len; int zname_len, arch_len, entry_len; phar_archive_data *phar; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) { RETURN_FALSE; } if (!fname_len) { zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"\""); return; } if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error)) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"%s\": %s", fname, error); efree(error); } else { zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"%s\"", fname); } return; } zname = (char*)zend_get_executed_filename(); zname_len = strlen(zname); if (zname_len > 7 && !memcmp(zname, "phar://", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) { if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" cannot be unlinked from within itself", fname); efree(arch); efree(entry); return; } efree(arch); efree(entry); } if (phar->is_persistent) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" is in phar.cache_list, cannot unlinkArchive()", fname); return; } if (phar->refcount) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()", fname); return; } fname = estrndup(phar->fname, phar->fname_len); /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; phar_archive_delref(phar); unlink(fname); efree(fname); RETURN_TRUE; }
165,061
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PageInfo::RecordPasswordReuseEvent() { if (!password_protection_service_) { return; } if (safe_browsing_status_ == SAFE_BROWSING_STATUS_SIGN_IN_PASSWORD_REUSE) { safe_browsing::LogWarningAction( safe_browsing::WarningUIType::PAGE_INFO, safe_browsing::WarningAction::SHOWN, safe_browsing::LoginReputationClientRequest::PasswordReuseEvent:: SIGN_IN_PASSWORD, password_protection_service_->GetSyncAccountType()); } else { safe_browsing::LogWarningAction( safe_browsing::WarningUIType::PAGE_INFO, safe_browsing::WarningAction::SHOWN, safe_browsing::LoginReputationClientRequest::PasswordReuseEvent:: ENTERPRISE_PASSWORD, password_protection_service_->GetSyncAccountType()); } } Commit Message: Revert "PageInfo: decouple safe browsing and TLS statii." This reverts commit ee95bc44021230127c7e6e9a8cf9d3820760f77c. Reason for revert: suspect causing unit_tests failure on Linux MSAN Tests: https://ci.chromium.org/p/chromium/builders/ci/Linux%20MSan%20Tests/17649 PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered PageInfoBubbleViewTest.EnsureCloseCallback PageInfoBubbleViewTest.NotificationPermissionRevokeUkm PageInfoBubbleViewTest.OpenPageInfoBubbleAfterNavigationStart PageInfoBubbleViewTest.SetPermissionInfo PageInfoBubbleViewTest.SetPermissionInfoForUsbGuard PageInfoBubbleViewTest.SetPermissionInfoWithPolicyUsbDevices PageInfoBubbleViewTest.SetPermissionInfoWithUsbDevice PageInfoBubbleViewTest.SetPermissionInfoWithUserAndPolicyUsbDevices PageInfoBubbleViewTest.UpdatingSiteDataRetainsLayout https://logs.chromium.org/logs/chromium/buildbucket/cr-buildbucket.appspot.com/8909718923797040064/+/steps/unit_tests/0/logs/Deterministic_failure:_PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered__status_CRASH_/0 [ RUN ] PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered ==9056==WARNING: MemorySanitizer: use-of-uninitialized-value #0 0x561baaab15ec in PageInfoUI::GetSecurityDescription(PageInfoUI::IdentityInfo const&) const ./../../chrome/browser/ui/page_info/page_info_ui.cc:250:3 #1 0x561bab6a1548 in PageInfoBubbleView::SetIdentityInfo(PageInfoUI::IdentityInfo const&) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:802:7 #2 0x561baaaab3bb in PageInfo::PresentSiteIdentity() ./../../chrome/browser/ui/page_info/page_info.cc:969:8 #3 0x561baaaa0a21 in PageInfo::PageInfo(PageInfoUI*, Profile*, TabSpecificContentSettings*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&) ./../../chrome/browser/ui/page_info/page_info.cc:344:3 #4 0x561bab69b6dd in PageInfoBubbleView::PageInfoBubbleView(views::View*, gfx::Rect const&, aura::Window*, Profile*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&, base::OnceCallback<void (views::Widget::ClosedReason, bool)>) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:576:24 ... Original change's description: > PageInfo: decouple safe browsing and TLS statii. > > Previously, the Page Info bubble maintained a single variable to > identify all reasons that a page might have a non-standard status. This > lead to the display logic making assumptions about, for instance, the > validity of a certificate when the page was flagged by Safe Browsing. > > This CL separates out the Safe Browsing status from the site identity > status so that the page info bubble can inform the user that the site's > certificate is invalid, even if it's also flagged by Safe Browsing. > > Bug: 869925 > Change-Id: I34107225b4206c8f32771ccd75e9367668d0a72b > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1662537 > Reviewed-by: Mustafa Emre Acer <[email protected]> > Reviewed-by: Bret Sepulveda <[email protected]> > Auto-Submit: Joe DeBlasio <[email protected]> > Commit-Queue: Joe DeBlasio <[email protected]> > Cr-Commit-Position: refs/heads/master@{#671847} [email protected],[email protected],[email protected] Change-Id: I8be652952e7276bcc9266124693352e467159cc4 No-Presubmit: true No-Tree-Checks: true No-Try: true Bug: 869925 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1673985 Reviewed-by: Takashi Sakamoto <[email protected]> Commit-Queue: Takashi Sakamoto <[email protected]> Cr-Commit-Position: refs/heads/master@{#671932} CWE ID: CWE-311
void PageInfo::RecordPasswordReuseEvent() { if (!password_protection_service_) { return; } if (site_identity_status_ == SITE_IDENTITY_STATUS_SIGN_IN_PASSWORD_REUSE) { safe_browsing::LogWarningAction( safe_browsing::WarningUIType::PAGE_INFO, safe_browsing::WarningAction::SHOWN, safe_browsing::LoginReputationClientRequest::PasswordReuseEvent:: SIGN_IN_PASSWORD, password_protection_service_->GetSyncAccountType()); } else { safe_browsing::LogWarningAction( safe_browsing::WarningUIType::PAGE_INFO, safe_browsing::WarningAction::SHOWN, safe_browsing::LoginReputationClientRequest::PasswordReuseEvent:: ENTERPRISE_PASSWORD, password_protection_service_->GetSyncAccountType()); } }
172,439
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int trusted_update(struct key *key, struct key_preparsed_payload *prep) { struct trusted_key_payload *p = key->payload.data[0]; struct trusted_key_payload *new_p; struct trusted_key_options *new_o; size_t datalen = prep->datalen; char *datablob; int ret = 0; if (!p->migratable) return -EPERM; if (datalen <= 0 || datalen > 32767 || !prep->data) return -EINVAL; datablob = kmalloc(datalen + 1, GFP_KERNEL); if (!datablob) return -ENOMEM; new_o = trusted_options_alloc(); if (!new_o) { ret = -ENOMEM; goto out; } new_p = trusted_payload_alloc(key); if (!new_p) { ret = -ENOMEM; goto out; } memcpy(datablob, prep->data, datalen); datablob[datalen] = '\0'; ret = datablob_parse(datablob, new_p, new_o); if (ret != Opt_update) { ret = -EINVAL; kfree(new_p); goto out; } if (!new_o->keyhandle) { ret = -EINVAL; kfree(new_p); goto out; } /* copy old key values, and reseal with new pcrs */ new_p->migratable = p->migratable; new_p->key_len = p->key_len; memcpy(new_p->key, p->key, p->key_len); dump_payload(p); dump_payload(new_p); ret = key_seal(new_p, new_o); if (ret < 0) { pr_info("trusted_key: key_seal failed (%d)\n", ret); kfree(new_p); goto out; } if (new_o->pcrlock) { ret = pcrlock(new_o->pcrlock); if (ret < 0) { pr_info("trusted_key: pcrlock failed (%d)\n", ret); kfree(new_p); goto out; } } rcu_assign_keypointer(key, new_p); call_rcu(&p->rcu, trusted_rcu_free); out: kfree(datablob); kfree(new_o); return ret; } Commit Message: KEYS: Fix handling of stored error in a negatively instantiated user key If a user key gets negatively instantiated, an error code is cached in the payload area. A negatively instantiated key may be then be positively instantiated by updating it with valid data. However, the ->update key type method must be aware that the error code may be there. The following may be used to trigger the bug in the user key type: keyctl request2 user user "" @u keyctl add user user "a" @u which manifests itself as: BUG: unable to handle kernel paging request at 00000000ffffff8a IP: [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046 PGD 7cc30067 PUD 0 Oops: 0002 [#1] SMP Modules linked in: CPU: 3 PID: 2644 Comm: a.out Not tainted 4.3.0+ #49 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011 task: ffff88003ddea700 ti: ffff88003dd88000 task.ti: ffff88003dd88000 RIP: 0010:[<ffffffff810a376f>] [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046 RSP: 0018:ffff88003dd8bdb0 EFLAGS: 00010246 RAX: 00000000ffffff82 RBX: 0000000000000000 RCX: 0000000000000001 RDX: ffffffff81e3fe40 RSI: 0000000000000000 RDI: 00000000ffffff82 RBP: ffff88003dd8bde0 R08: ffff88007d2d2da0 R09: 0000000000000000 R10: 0000000000000000 R11: ffff88003e8073c0 R12: 00000000ffffff82 R13: ffff88003dd8be68 R14: ffff88007d027600 R15: ffff88003ddea700 FS: 0000000000b92880(0063) GS:ffff88007fd00000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b CR2: 00000000ffffff8a CR3: 000000007cc5f000 CR4: 00000000000006e0 Stack: ffff88003dd8bdf0 ffffffff81160a8a 0000000000000000 00000000ffffff82 ffff88003dd8be68 ffff88007d027600 ffff88003dd8bdf0 ffffffff810a39e5 ffff88003dd8be20 ffffffff812a31ab ffff88007d027600 ffff88007d027620 Call Trace: [<ffffffff810a39e5>] kfree_call_rcu+0x15/0x20 kernel/rcu/tree.c:3136 [<ffffffff812a31ab>] user_update+0x8b/0xb0 security/keys/user_defined.c:129 [< inline >] __key_update security/keys/key.c:730 [<ffffffff8129e5c1>] key_create_or_update+0x291/0x440 security/keys/key.c:908 [< inline >] SYSC_add_key security/keys/keyctl.c:125 [<ffffffff8129fc21>] SyS_add_key+0x101/0x1e0 security/keys/keyctl.c:60 [<ffffffff8185f617>] entry_SYSCALL_64_fastpath+0x12/0x6a arch/x86/entry/entry_64.S:185 Note the error code (-ENOKEY) in EDX. A similar bug can be tripped by: keyctl request2 trusted user "" @u keyctl add trusted user "a" @u This should also affect encrypted keys - but that has to be correctly parameterised or it will fail with EINVAL before getting to the bit that will crashes. Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: David Howells <[email protected]> Acked-by: Mimi Zohar <[email protected]> Signed-off-by: James Morris <[email protected]> CWE ID: CWE-264
static int trusted_update(struct key *key, struct key_preparsed_payload *prep) { struct trusted_key_payload *p; struct trusted_key_payload *new_p; struct trusted_key_options *new_o; size_t datalen = prep->datalen; char *datablob; int ret = 0; if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) return -ENOKEY; p = key->payload.data[0]; if (!p->migratable) return -EPERM; if (datalen <= 0 || datalen > 32767 || !prep->data) return -EINVAL; datablob = kmalloc(datalen + 1, GFP_KERNEL); if (!datablob) return -ENOMEM; new_o = trusted_options_alloc(); if (!new_o) { ret = -ENOMEM; goto out; } new_p = trusted_payload_alloc(key); if (!new_p) { ret = -ENOMEM; goto out; } memcpy(datablob, prep->data, datalen); datablob[datalen] = '\0'; ret = datablob_parse(datablob, new_p, new_o); if (ret != Opt_update) { ret = -EINVAL; kfree(new_p); goto out; } if (!new_o->keyhandle) { ret = -EINVAL; kfree(new_p); goto out; } /* copy old key values, and reseal with new pcrs */ new_p->migratable = p->migratable; new_p->key_len = p->key_len; memcpy(new_p->key, p->key, p->key_len); dump_payload(p); dump_payload(new_p); ret = key_seal(new_p, new_o); if (ret < 0) { pr_info("trusted_key: key_seal failed (%d)\n", ret); kfree(new_p); goto out; } if (new_o->pcrlock) { ret = pcrlock(new_o->pcrlock); if (ret < 0) { pr_info("trusted_key: pcrlock failed (%d)\n", ret); kfree(new_p); goto out; } } rcu_assign_keypointer(key, new_p); call_rcu(&p->rcu, trusted_rcu_free); out: kfree(datablob); kfree(new_o); return ret; }
167,534
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: gfx::Size LockScreenMediaControlsView::CalculatePreferredSize() const { return gfx::Size(kMediaControlsTotalWidthDp, kMediaControlsTotalHeightDp); } Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks This CL rearranges the different components of the CrOS lock screen media controls based on the newest mocks. This involves resizing most of the child views and their spacings. The artwork was also resized and re-positioned. Additionally, the close button was moved from the main view to the header row child view. Artist and title data about the current session will eventually be placed to the right of the artwork, but right now this space is empty. See the bug for before and after pictures. Bug: 991647 Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554 Reviewed-by: Xiyuan Xia <[email protected]> Reviewed-by: Becca Hughes <[email protected]> Commit-Queue: Mia Bergeron <[email protected]> Cr-Commit-Position: refs/heads/master@{#686253} CWE ID: CWE-200
gfx::Size LockScreenMediaControlsView::CalculatePreferredSize() const { return contents_view_->GetPreferredSize(); }
172,338
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void UrlFetcherDownloader::OnNetworkFetcherComplete(base::FilePath file_path, int net_error, int64_t content_size) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); const base::TimeTicks download_end_time(base::TimeTicks::Now()); const base::TimeDelta download_time = download_end_time >= download_start_time_ ? download_end_time - download_start_time_ : base::TimeDelta(); int error = -1; if (!file_path.empty() && response_code_ == 200) { DCHECK_EQ(0, net_error); error = 0; } else if (response_code_ != -1) { error = response_code_; } else { error = net_error; } const bool is_handled = error == 0 || IsHttpServerError(error); Result result; result.error = error; if (!error) { result.response = file_path; } DownloadMetrics download_metrics; download_metrics.url = url(); download_metrics.downloader = DownloadMetrics::kUrlFetcher; download_metrics.error = error; download_metrics.downloaded_bytes = error ? -1 : content_size; download_metrics.total_bytes = total_bytes_; download_metrics.download_time_ms = download_time.InMilliseconds(); VLOG(1) << "Downloaded " << content_size << " bytes in " << download_time.InMilliseconds() << "ms from " << url().spec() << " to " << result.response.value(); if (error && !download_dir_.empty()) { base::PostTask(FROM_HERE, kTaskTraits, base::BindOnce(IgnoreResult(&base::DeleteFileRecursively), download_dir_)); } main_task_runner()->PostTask( FROM_HERE, base::BindOnce(&UrlFetcherDownloader::OnDownloadComplete, base::Unretained(this), is_handled, result, download_metrics)); } Commit Message: Fix error handling in the request sender and url fetcher downloader. That means handling the network errors by primarily looking at net_error. Bug: 1028369 Change-Id: I8181bced25f8b56144ea336a03883d0dceea5108 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1935428 Reviewed-by: Joshua Pawlicki <[email protected]> Commit-Queue: Sorin Jianu <[email protected]> Cr-Commit-Position: refs/heads/master@{#719199} CWE ID: CWE-20
void UrlFetcherDownloader::OnNetworkFetcherComplete(base::FilePath file_path, void UrlFetcherDownloader::OnNetworkFetcherComplete(int net_error, int64_t content_size) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); const base::TimeTicks download_end_time(base::TimeTicks::Now()); const base::TimeDelta download_time = download_end_time >= download_start_time_ ? download_end_time - download_start_time_ : base::TimeDelta(); int error = -1; if (!net_error && response_code_ == 200) error = 0; else if (response_code_ != -1) error = response_code_; else error = net_error; const bool is_handled = error == 0 || IsHttpServerError(error); Result result; result.error = error; if (!error) result.response = file_path_; DownloadMetrics download_metrics; download_metrics.url = url(); download_metrics.downloader = DownloadMetrics::kUrlFetcher; download_metrics.error = error; download_metrics.downloaded_bytes = error ? -1 : content_size; download_metrics.total_bytes = total_bytes_; download_metrics.download_time_ms = download_time.InMilliseconds(); VLOG(1) << "Downloaded " << content_size << " bytes in " << download_time.InMilliseconds() << "ms from " << url().spec() << " to " << result.response.value(); if (error && !download_dir_.empty()) { base::PostTask(FROM_HERE, kTaskTraits, base::BindOnce(IgnoreResult(&base::DeleteFileRecursively), download_dir_)); } main_task_runner()->PostTask( FROM_HERE, base::BindOnce(&UrlFetcherDownloader::OnDownloadComplete, base::Unretained(this), is_handled, result, download_metrics)); }
172,365
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image) { const char *option, *property; int jp2_status; MagickBooleanType status; opj_codec_t *jp2_codec; OPJ_COLOR_SPACE jp2_colorspace; opj_cparameters_t parameters; opj_image_cmptparm_t jp2_info[5]; opj_image_t *jp2_image; opj_stream_t *jp2_stream; register ssize_t i; ssize_t y; unsigned int channels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); /* Initialize JPEG 2000 encoder parameters. */ opj_set_default_encoder_parameters(&parameters); for (i=1; i < 6; i++) if (((size_t) (1 << (i+2)) > image->columns) && ((size_t) (1 << (i+2)) > image->rows)) break; parameters.numresolution=i; option=GetImageOption(image_info,"jp2:number-resolutions"); if (option != (const char *) NULL) parameters.numresolution=StringToInteger(option); parameters.tcp_numlayers=1; parameters.tcp_rates[0]=0; /* lossless */ parameters.cp_disto_alloc=1; if ((image_info->quality != 0) && (image_info->quality != 100)) { parameters.tcp_distoratio[0]=(double) image_info->quality; parameters.cp_fixed_quality=OPJ_TRUE; } if (image_info->extract != (char *) NULL) { RectangleInfo geometry; int flags; /* Set tile size. */ flags=ParseAbsoluteGeometry(image_info->extract,&geometry); parameters.cp_tdx=(int) geometry.width; parameters.cp_tdy=(int) geometry.width; if ((flags & HeightValue) != 0) parameters.cp_tdy=(int) geometry.height; if ((flags & XValue) != 0) parameters.cp_tx0=geometry.x; if ((flags & YValue) != 0) parameters.cp_ty0=geometry.y; parameters.tile_size_on=OPJ_TRUE; } option=GetImageOption(image_info,"jp2:quality"); if (option != (const char *) NULL) { register const char *p; /* Set quality PSNR. */ p=option; for (i=0; sscanf(p,"%f",&parameters.tcp_distoratio[i]) == 1; i++) { if (i >= 100) break; while ((*p != '\0') && (*p != ',')) p++; if (*p == '\0') break; p++; } parameters.tcp_numlayers=i+1; parameters.cp_fixed_quality=OPJ_TRUE; } option=GetImageOption(image_info,"jp2:progression-order"); if (option != (const char *) NULL) { if (LocaleCompare(option,"LRCP") == 0) parameters.prog_order=OPJ_LRCP; if (LocaleCompare(option,"RLCP") == 0) parameters.prog_order=OPJ_RLCP; if (LocaleCompare(option,"RPCL") == 0) parameters.prog_order=OPJ_RPCL; if (LocaleCompare(option,"PCRL") == 0) parameters.prog_order=OPJ_PCRL; if (LocaleCompare(option,"CPRL") == 0) parameters.prog_order=OPJ_CPRL; } option=GetImageOption(image_info,"jp2:rate"); if (option != (const char *) NULL) { register const char *p; /* Set compression rate. */ p=option; for (i=0; sscanf(p,"%f",&parameters.tcp_rates[i]) == 1; i++) { if (i > 100) break; while ((*p != '\0') && (*p != ',')) p++; if (*p == '\0') break; p++; } parameters.tcp_numlayers=i+1; parameters.cp_disto_alloc=OPJ_TRUE; } if (image_info->sampling_factor != (const char *) NULL) (void) sscanf(image_info->sampling_factor,"%d,%d", &parameters.subsampling_dx,&parameters.subsampling_dy); property=GetImageProperty(image,"comment"); if (property != (const char *) NULL) parameters.cp_comment=property; channels=3; jp2_colorspace=OPJ_CLRSPC_SRGB; if (image->colorspace == YUVColorspace) { jp2_colorspace=OPJ_CLRSPC_SYCC; parameters.subsampling_dx=2; } else { if (IsGrayColorspace(image->colorspace) != MagickFalse) { channels=1; jp2_colorspace=OPJ_CLRSPC_GRAY; } else (void) TransformImageColorspace(image,sRGBColorspace); if (image->matte != MagickFalse) channels++; } parameters.tcp_mct=channels == 3 ? 1 : 0; ResetMagickMemory(jp2_info,0,sizeof(jp2_info)); for (i=0; i < (ssize_t) channels; i++) { jp2_info[i].prec=(unsigned int) image->depth; jp2_info[i].bpp=(unsigned int) image->depth; if ((image->depth == 1) && ((LocaleCompare(image_info->magick,"JPT") == 0) || (LocaleCompare(image_info->magick,"JP2") == 0))) { jp2_info[i].prec++; /* OpenJPEG returns exception for depth @ 1 */ jp2_info[i].bpp++; } jp2_info[i].sgnd=0; jp2_info[i].dx=parameters.subsampling_dx; jp2_info[i].dy=parameters.subsampling_dy; jp2_info[i].w=(unsigned int) image->columns; jp2_info[i].h=(unsigned int) image->rows; } jp2_image=opj_image_create(channels,jp2_info,jp2_colorspace); if (jp2_image == (opj_image_t *) NULL) ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); jp2_image->x0=parameters.image_offset_x0; jp2_image->y0=parameters.image_offset_y0; jp2_image->x1=(unsigned int) (2*parameters.image_offset_x0+(image->columns-1)* parameters.subsampling_dx+1); jp2_image->y1=(unsigned int) (2*parameters.image_offset_y0+(image->rows-1)* parameters.subsampling_dx+1); if ((image->depth == 12) && ((image->columns == 2048) || (image->rows == 1080) || (image->columns == 4096) || (image->rows == 2160))) CinemaProfileCompliance(jp2_image,&parameters); if (channels == 4) jp2_image->comps[3].alpha=1; else if ((channels == 2) && (jp2_colorspace == OPJ_CLRSPC_GRAY)) jp2_image->comps[1].alpha=1; /* Convert to JP2 pixels. */ for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *p; ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) channels; i++) { double scale; register int *q; scale=(double) ((1UL << jp2_image->comps[i].prec)-1)/QuantumRange; q=jp2_image->comps[i].data+(y/jp2_image->comps[i].dy* image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx); switch (i) { case 0: { if (jp2_colorspace == OPJ_CLRSPC_GRAY) { *q=(int) (scale*GetPixelLuma(image,p)); break; } *q=(int) (scale*p->red); break; } case 1: { if (jp2_colorspace == OPJ_CLRSPC_GRAY) { *q=(int) (scale*(QuantumRange-p->opacity)); break; } *q=(int) (scale*p->green); break; } case 2: { *q=(int) (scale*p->blue); break; } case 3: { *q=(int) (scale*(QuantumRange-p->opacity)); break; } } } p++; } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (LocaleCompare(image_info->magick,"JPT") == 0) jp2_codec=opj_create_compress(OPJ_CODEC_JPT); else if (LocaleCompare(image_info->magick,"J2K") == 0) jp2_codec=opj_create_compress(OPJ_CODEC_J2K); else jp2_codec=opj_create_compress(OPJ_CODEC_JP2); opj_set_warning_handler(jp2_codec,JP2WarningHandler,&image->exception); opj_set_error_handler(jp2_codec,JP2ErrorHandler,&image->exception); opj_setup_encoder(jp2_codec,&parameters,jp2_image); jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_FALSE); opj_stream_set_read_function(jp2_stream,JP2ReadHandler); opj_stream_set_write_function(jp2_stream,JP2WriteHandler); opj_stream_set_seek_function(jp2_stream,JP2SeekHandler); opj_stream_set_skip_function(jp2_stream,JP2SkipHandler); opj_stream_set_user_data(jp2_stream,image,NULL); if (jp2_stream == (opj_stream_t *) NULL) ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); jp2_status=opj_start_compress(jp2_codec,jp2_image,jp2_stream); if (jp2_status == 0) ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); if ((opj_encode(jp2_codec,jp2_stream) == 0) || (opj_end_compress(jp2_codec,jp2_stream) == 0)) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); } /* Free resources. */ opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); (void) CloseBlob(image); return(MagickTrue); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/571 CWE ID: CWE-772
static MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image) { const char *option, *property; int jp2_status; MagickBooleanType status; opj_codec_t *jp2_codec; OPJ_COLOR_SPACE jp2_colorspace; opj_cparameters_t parameters; opj_image_cmptparm_t jp2_info[5]; opj_image_t *jp2_image; opj_stream_t *jp2_stream; register ssize_t i; ssize_t y; unsigned int channels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); /* Initialize JPEG 2000 encoder parameters. */ opj_set_default_encoder_parameters(&parameters); for (i=1; i < 6; i++) if (((size_t) (1 << (i+2)) > image->columns) && ((size_t) (1 << (i+2)) > image->rows)) break; parameters.numresolution=i; option=GetImageOption(image_info,"jp2:number-resolutions"); if (option != (const char *) NULL) parameters.numresolution=StringToInteger(option); parameters.tcp_numlayers=1; parameters.tcp_rates[0]=0; /* lossless */ parameters.cp_disto_alloc=1; if ((image_info->quality != 0) && (image_info->quality != 100)) { parameters.tcp_distoratio[0]=(double) image_info->quality; parameters.cp_fixed_quality=OPJ_TRUE; } if (image_info->extract != (char *) NULL) { RectangleInfo geometry; int flags; /* Set tile size. */ flags=ParseAbsoluteGeometry(image_info->extract,&geometry); parameters.cp_tdx=(int) geometry.width; parameters.cp_tdy=(int) geometry.width; if ((flags & HeightValue) != 0) parameters.cp_tdy=(int) geometry.height; if ((flags & XValue) != 0) parameters.cp_tx0=geometry.x; if ((flags & YValue) != 0) parameters.cp_ty0=geometry.y; parameters.tile_size_on=OPJ_TRUE; } option=GetImageOption(image_info,"jp2:quality"); if (option != (const char *) NULL) { register const char *p; /* Set quality PSNR. */ p=option; for (i=0; sscanf(p,"%f",&parameters.tcp_distoratio[i]) == 1; i++) { if (i >= 100) break; while ((*p != '\0') && (*p != ',')) p++; if (*p == '\0') break; p++; } parameters.tcp_numlayers=i+1; parameters.cp_fixed_quality=OPJ_TRUE; } option=GetImageOption(image_info,"jp2:progression-order"); if (option != (const char *) NULL) { if (LocaleCompare(option,"LRCP") == 0) parameters.prog_order=OPJ_LRCP; if (LocaleCompare(option,"RLCP") == 0) parameters.prog_order=OPJ_RLCP; if (LocaleCompare(option,"RPCL") == 0) parameters.prog_order=OPJ_RPCL; if (LocaleCompare(option,"PCRL") == 0) parameters.prog_order=OPJ_PCRL; if (LocaleCompare(option,"CPRL") == 0) parameters.prog_order=OPJ_CPRL; } option=GetImageOption(image_info,"jp2:rate"); if (option != (const char *) NULL) { register const char *p; /* Set compression rate. */ p=option; for (i=0; sscanf(p,"%f",&parameters.tcp_rates[i]) == 1; i++) { if (i > 100) break; while ((*p != '\0') && (*p != ',')) p++; if (*p == '\0') break; p++; } parameters.tcp_numlayers=i+1; parameters.cp_disto_alloc=OPJ_TRUE; } if (image_info->sampling_factor != (const char *) NULL) (void) sscanf(image_info->sampling_factor,"%d,%d", &parameters.subsampling_dx,&parameters.subsampling_dy); property=GetImageProperty(image,"comment"); if (property != (const char *) NULL) parameters.cp_comment=(char *) property; channels=3; jp2_colorspace=OPJ_CLRSPC_SRGB; if (image->colorspace == YUVColorspace) { jp2_colorspace=OPJ_CLRSPC_SYCC; parameters.subsampling_dx=2; } else { if (IsGrayColorspace(image->colorspace) != MagickFalse) { channels=1; jp2_colorspace=OPJ_CLRSPC_GRAY; } else (void) TransformImageColorspace(image,sRGBColorspace); if (image->matte != MagickFalse) channels++; } parameters.tcp_mct=channels == 3 ? 1 : 0; ResetMagickMemory(jp2_info,0,sizeof(jp2_info)); for (i=0; i < (ssize_t) channels; i++) { jp2_info[i].prec=(unsigned int) image->depth; jp2_info[i].bpp=(unsigned int) image->depth; if ((image->depth == 1) && ((LocaleCompare(image_info->magick,"JPT") == 0) || (LocaleCompare(image_info->magick,"JP2") == 0))) { jp2_info[i].prec++; /* OpenJPEG returns exception for depth @ 1 */ jp2_info[i].bpp++; } jp2_info[i].sgnd=0; jp2_info[i].dx=parameters.subsampling_dx; jp2_info[i].dy=parameters.subsampling_dy; jp2_info[i].w=(unsigned int) image->columns; jp2_info[i].h=(unsigned int) image->rows; } jp2_image=opj_image_create(channels,jp2_info,jp2_colorspace); if (jp2_image == (opj_image_t *) NULL) ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); jp2_image->x0=parameters.image_offset_x0; jp2_image->y0=parameters.image_offset_y0; jp2_image->x1=(unsigned int) (2*parameters.image_offset_x0+(image->columns-1)* parameters.subsampling_dx+1); jp2_image->y1=(unsigned int) (2*parameters.image_offset_y0+(image->rows-1)* parameters.subsampling_dx+1); if ((image->depth == 12) && ((image->columns == 2048) || (image->rows == 1080) || (image->columns == 4096) || (image->rows == 2160))) CinemaProfileCompliance(jp2_image,&parameters); if (channels == 4) jp2_image->comps[3].alpha=1; else if ((channels == 2) && (jp2_colorspace == OPJ_CLRSPC_GRAY)) jp2_image->comps[1].alpha=1; /* Convert to JP2 pixels. */ for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *p; ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) channels; i++) { double scale; register int *q; scale=(double) ((1UL << jp2_image->comps[i].prec)-1)/QuantumRange; q=jp2_image->comps[i].data+(y/jp2_image->comps[i].dy* image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx); switch (i) { case 0: { if (jp2_colorspace == OPJ_CLRSPC_GRAY) { *q=(int) (scale*GetPixelLuma(image,p)); break; } *q=(int) (scale*p->red); break; } case 1: { if (jp2_colorspace == OPJ_CLRSPC_GRAY) { *q=(int) (scale*(QuantumRange-p->opacity)); break; } *q=(int) (scale*p->green); break; } case 2: { *q=(int) (scale*p->blue); break; } case 3: { *q=(int) (scale*(QuantumRange-p->opacity)); break; } } } p++; } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (LocaleCompare(image_info->magick,"JPT") == 0) jp2_codec=opj_create_compress(OPJ_CODEC_JPT); else if (LocaleCompare(image_info->magick,"J2K") == 0) jp2_codec=opj_create_compress(OPJ_CODEC_J2K); else jp2_codec=opj_create_compress(OPJ_CODEC_JP2); opj_set_warning_handler(jp2_codec,JP2WarningHandler,&image->exception); opj_set_error_handler(jp2_codec,JP2ErrorHandler,&image->exception); opj_setup_encoder(jp2_codec,&parameters,jp2_image); jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_FALSE); opj_stream_set_read_function(jp2_stream,JP2ReadHandler); opj_stream_set_write_function(jp2_stream,JP2WriteHandler); opj_stream_set_seek_function(jp2_stream,JP2SeekHandler); opj_stream_set_skip_function(jp2_stream,JP2SkipHandler); opj_stream_set_user_data(jp2_stream,image,NULL); if (jp2_stream == (opj_stream_t *) NULL) ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); jp2_status=opj_start_compress(jp2_codec,jp2_image,jp2_stream); if (jp2_status == 0) ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); if ((opj_encode(jp2_codec,jp2_stream) == 0) || (opj_end_compress(jp2_codec,jp2_stream) == 0)) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); } /* Free resources. */ opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); (void) CloseBlob(image); return(MagickTrue); }
167,968
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: main (int argc, char *argv[]) { struct gengetopt_args_info args_info; char *line = NULL; size_t linelen = 0; char *p, *r; uint32_t *q; unsigned cmdn = 0; int rc; setlocale (LC_ALL, ""); set_program_name (argv[0]); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); if (cmdline_parser (argc, argv, &args_info) != 0) return EXIT_FAILURE; if (args_info.version_given) { version_etc (stdout, "idn", PACKAGE_NAME, VERSION, "Simon Josefsson", (char *) NULL); return EXIT_SUCCESS; } if (args_info.help_given) usage (EXIT_SUCCESS); /* Backwards compatibility: -n has always been the documented short form for --nfkc but, before v1.10, -k was the implemented short form. We now accept both to avoid documentation changes. */ if (args_info.hidden_nfkc_given) args_info.nfkc_given = 1; if (!args_info.stringprep_given && !args_info.punycode_encode_given && !args_info.punycode_decode_given && !args_info.idna_to_ascii_given && !args_info.idna_to_unicode_given && !args_info.nfkc_given) args_info.idna_to_ascii_given = 1; if ((args_info.stringprep_given ? 1 : 0) + (args_info.punycode_encode_given ? 1 : 0) + (args_info.punycode_decode_given ? 1 : 0) + (args_info.idna_to_ascii_given ? 1 : 0) + (args_info.idna_to_unicode_given ? 1 : 0) + (args_info.nfkc_given ? 1 : 0) != 1) { error (0, 0, _("only one of -s, -e, -d, -a, -u or -n can be specified")); usage (EXIT_FAILURE); } if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, "%s %s\n" GREETING, PACKAGE, VERSION); if (args_info.debug_given) fprintf (stderr, _("Charset `%s'.\n"), stringprep_locale_charset ()); if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, _("Type each input string on a line by itself, " "terminated by a newline character.\n")); do { if (cmdn < args_info.inputs_num) line = strdup (args_info.inputs[cmdn++]); else if (getline (&line, &linelen, stdin) == -1) { if (feof (stdin)) break; error (EXIT_FAILURE, errno, _("input error")); } if (line[strlen (line) - 1] == '\n') line[strlen (line) - 1] = '\0'; if (args_info.stringprep_given) { if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); q = stringprep_utf8_to_ucs4 (p, -1, NULL); if (!q) { free (p); error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); } if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); } free (q); rc = stringprep_profile (p, &r, args_info.profile_given ? args_info.profile_arg : "Nameprep", 0); free (p); if (rc != STRINGPREP_OK) error (EXIT_FAILURE, 0, _("stringprep_profile: %s"), stringprep_strerror (rc)); q = stringprep_utf8_to_ucs4 (r, -1, NULL); if (!q) { free (r); error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); } if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, q[i]); } free (q); p = stringprep_utf8_to_locale (r); free (r); if (!p) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } if (args_info.punycode_encode_given) { char encbuf[BUFSIZ]; size_t len, len2; p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); q = stringprep_utf8_to_ucs4 (p, -1, &len); free (p); if (!q) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); if (args_info.debug_given) { size_t i; for (i = 0; i < len; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); } len2 = BUFSIZ - 1; rc = punycode_encode (len, q, NULL, &len2, encbuf); free (q); if (rc != PUNYCODE_SUCCESS) error (EXIT_FAILURE, 0, _("punycode_encode: %s"), punycode_strerror (rc)); encbuf[len2] = '\0'; p = stringprep_utf8_to_locale (encbuf); if (!p) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } if (args_info.punycode_decode_given) { size_t len; len = BUFSIZ; q = (uint32_t *) malloc (len * sizeof (q[0])); if (!q) error (EXIT_FAILURE, ENOMEM, N_("malloc")); rc = punycode_decode (strlen (line), line, &len, q, NULL); if (rc != PUNYCODE_SUCCESS) { free (q); error (EXIT_FAILURE, 0, _("punycode_decode: %s"), punycode_strerror (rc)); } if (args_info.debug_given) { size_t i; for (i = 0; i < len; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, q[i]); } q[len] = 0; r = stringprep_ucs4_to_utf8 (q, -1, NULL, NULL); free (q); if (!r) error (EXIT_FAILURE, 0, _("could not convert from UCS-4 to UTF-8")); p = stringprep_utf8_to_locale (r); free (r); if (!r) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } if (args_info.idna_to_ascii_given) { p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); q = stringprep_utf8_to_ucs4 (p, -1, NULL); free (p); if (!q) error (EXIT_FAILURE, 0, _("could not convert from UCS-4 to UTF-8")); if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); } rc = idna_to_ascii_4z (q, &p, (args_info.allow_unassigned_given ? IDNA_ALLOW_UNASSIGNED : 0) | (args_info.usestd3asciirules_given ? IDNA_USE_STD3_ASCII_RULES : 0)); free (q); if (rc != IDNA_SUCCESS) error (EXIT_FAILURE, 0, _("idna_to_ascii_4z: %s"), idna_strerror (rc)); #ifdef WITH_TLD if (args_info.tld_flag && !args_info.no_tld_flag) { size_t errpos; rc = idna_to_unicode_8z4z (p, &q, (args_info.allow_unassigned_given ? IDNA_ALLOW_UNASSIGNED : 0) | (args_info.usestd3asciirules_given ? IDNA_USE_STD3_ASCII_RULES : 0)); if (rc != IDNA_SUCCESS) error (EXIT_FAILURE, 0, _("idna_to_unicode_8z4z (TLD): %s"), idna_strerror (rc)); if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "tld[%lu] = U+%04x\n", (unsigned long) i, q[i]); } rc = tld_check_4z (q, &errpos, NULL); free (q); if (rc == TLD_INVALID) error (EXIT_FAILURE, 0, _("tld_check_4z (position %lu): %s"), (unsigned long) errpos, tld_strerror (rc)); if (rc != TLD_SUCCESS) error (EXIT_FAILURE, 0, _("tld_check_4z: %s"), tld_strerror (rc)); } #endif if (args_info.debug_given) { size_t i; for (i = 0; p[i]; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, p[i]); } fprintf (stdout, "%s\n", p); free (p); } if (args_info.idna_to_unicode_given) { p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); q = stringprep_utf8_to_ucs4 (p, -1, NULL); if (!q) { free (p); error (EXIT_FAILURE, 0, _("could not convert from UCS-4 to UTF-8")); } if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); } free (q); rc = idna_to_unicode_8z4z (p, &q, (args_info.allow_unassigned_given ? IDNA_ALLOW_UNASSIGNED : 0) | (args_info.usestd3asciirules_given ? IDNA_USE_STD3_ASCII_RULES : 0)); free (p); if (rc != IDNA_SUCCESS) error (EXIT_FAILURE, 0, _("idna_to_unicode_8z4z: %s"), idna_strerror (rc)); if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, q[i]); } #ifdef WITH_TLD if (args_info.tld_flag) { size_t errpos; rc = tld_check_4z (q, &errpos, NULL); if (rc == TLD_INVALID) { free (q); error (EXIT_FAILURE, 0, _("tld_check_4z (position %lu): %s"), (unsigned long) errpos, tld_strerror (rc)); } if (rc != TLD_SUCCESS) { free (q); error (EXIT_FAILURE, 0, _("tld_check_4z: %s"), tld_strerror (rc)); } } #endif r = stringprep_ucs4_to_utf8 (q, -1, NULL, NULL); free (q); if (!r) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); p = stringprep_utf8_to_locale (r); free (r); if (!p) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } if (args_info.nfkc_given) { p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); if (args_info.debug_given) { size_t i; q = stringprep_utf8_to_ucs4 (p, -1, NULL); if (!q) { free (p); error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); } for (i = 0; q[i]; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); free (q); } r = stringprep_utf8_nfkc_normalize (p, -1); free (p); if (!r) error (EXIT_FAILURE, 0, _("could not do NFKC normalization")); if (args_info.debug_given) { size_t i; q = stringprep_utf8_to_ucs4 (r, -1, NULL); if (!q) { free (r); error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); } for (i = 0; q[i]; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, q[i]); free (q); } p = stringprep_utf8_to_locale (r); free (r); if (!p) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } fflush (stdout); } while (!feof (stdin) && !ferror (stdin) && (args_info.inputs_num == 0 || cmdn < args_info.inputs_num)); free (line); return EXIT_SUCCESS; } Commit Message: CWE ID: CWE-125
main (int argc, char *argv[]) { struct gengetopt_args_info args_info; char *line = NULL; size_t linelen = 0; char *p, *r; uint32_t *q; unsigned cmdn = 0; int rc; setlocale (LC_ALL, ""); set_program_name (argv[0]); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); if (cmdline_parser (argc, argv, &args_info) != 0) return EXIT_FAILURE; if (args_info.version_given) { version_etc (stdout, "idn", PACKAGE_NAME, VERSION, "Simon Josefsson", (char *) NULL); return EXIT_SUCCESS; } if (args_info.help_given) usage (EXIT_SUCCESS); /* Backwards compatibility: -n has always been the documented short form for --nfkc but, before v1.10, -k was the implemented short form. We now accept both to avoid documentation changes. */ if (args_info.hidden_nfkc_given) args_info.nfkc_given = 1; if (!args_info.stringprep_given && !args_info.punycode_encode_given && !args_info.punycode_decode_given && !args_info.idna_to_ascii_given && !args_info.idna_to_unicode_given && !args_info.nfkc_given) args_info.idna_to_ascii_given = 1; if ((args_info.stringprep_given ? 1 : 0) + (args_info.punycode_encode_given ? 1 : 0) + (args_info.punycode_decode_given ? 1 : 0) + (args_info.idna_to_ascii_given ? 1 : 0) + (args_info.idna_to_unicode_given ? 1 : 0) + (args_info.nfkc_given ? 1 : 0) != 1) { error (0, 0, _("only one of -s, -e, -d, -a, -u or -n can be specified")); usage (EXIT_FAILURE); } if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, "%s %s\n" GREETING, PACKAGE, VERSION); if (args_info.debug_given) fprintf (stderr, _("Charset `%s'.\n"), stringprep_locale_charset ()); if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, _("Type each input string on a line by itself, " "terminated by a newline character.\n")); do { if (cmdn < args_info.inputs_num) line = strdup (args_info.inputs[cmdn++]); else if (getline (&line, &linelen, stdin) == -1) { if (feof (stdin)) break; error (EXIT_FAILURE, errno, _("input error")); } if (strlen (line) > 0) if (line[strlen (line) - 1] == '\n') line[strlen (line) - 1] = '\0'; if (args_info.stringprep_given) { if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); q = stringprep_utf8_to_ucs4 (p, -1, NULL); if (!q) { free (p); error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); } if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); } free (q); rc = stringprep_profile (p, &r, args_info.profile_given ? args_info.profile_arg : "Nameprep", 0); free (p); if (rc != STRINGPREP_OK) error (EXIT_FAILURE, 0, _("stringprep_profile: %s"), stringprep_strerror (rc)); q = stringprep_utf8_to_ucs4 (r, -1, NULL); if (!q) { free (r); error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); } if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, q[i]); } free (q); p = stringprep_utf8_to_locale (r); free (r); if (!p) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } if (args_info.punycode_encode_given) { char encbuf[BUFSIZ]; size_t len, len2; p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); q = stringprep_utf8_to_ucs4 (p, -1, &len); free (p); if (!q) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); if (args_info.debug_given) { size_t i; for (i = 0; i < len; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); } len2 = BUFSIZ - 1; rc = punycode_encode (len, q, NULL, &len2, encbuf); free (q); if (rc != PUNYCODE_SUCCESS) error (EXIT_FAILURE, 0, _("punycode_encode: %s"), punycode_strerror (rc)); encbuf[len2] = '\0'; p = stringprep_utf8_to_locale (encbuf); if (!p) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } if (args_info.punycode_decode_given) { size_t len; len = BUFSIZ; q = (uint32_t *) malloc (len * sizeof (q[0])); if (!q) error (EXIT_FAILURE, ENOMEM, N_("malloc")); rc = punycode_decode (strlen (line), line, &len, q, NULL); if (rc != PUNYCODE_SUCCESS) { free (q); error (EXIT_FAILURE, 0, _("punycode_decode: %s"), punycode_strerror (rc)); } if (args_info.debug_given) { size_t i; for (i = 0; i < len; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, q[i]); } q[len] = 0; r = stringprep_ucs4_to_utf8 (q, -1, NULL, NULL); free (q); if (!r) error (EXIT_FAILURE, 0, _("could not convert from UCS-4 to UTF-8")); p = stringprep_utf8_to_locale (r); free (r); if (!r) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } if (args_info.idna_to_ascii_given) { p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); q = stringprep_utf8_to_ucs4 (p, -1, NULL); free (p); if (!q) error (EXIT_FAILURE, 0, _("could not convert from UCS-4 to UTF-8")); if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); } rc = idna_to_ascii_4z (q, &p, (args_info.allow_unassigned_given ? IDNA_ALLOW_UNASSIGNED : 0) | (args_info.usestd3asciirules_given ? IDNA_USE_STD3_ASCII_RULES : 0)); free (q); if (rc != IDNA_SUCCESS) error (EXIT_FAILURE, 0, _("idna_to_ascii_4z: %s"), idna_strerror (rc)); #ifdef WITH_TLD if (args_info.tld_flag && !args_info.no_tld_flag) { size_t errpos; rc = idna_to_unicode_8z4z (p, &q, (args_info.allow_unassigned_given ? IDNA_ALLOW_UNASSIGNED : 0) | (args_info.usestd3asciirules_given ? IDNA_USE_STD3_ASCII_RULES : 0)); if (rc != IDNA_SUCCESS) error (EXIT_FAILURE, 0, _("idna_to_unicode_8z4z (TLD): %s"), idna_strerror (rc)); if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "tld[%lu] = U+%04x\n", (unsigned long) i, q[i]); } rc = tld_check_4z (q, &errpos, NULL); free (q); if (rc == TLD_INVALID) error (EXIT_FAILURE, 0, _("tld_check_4z (position %lu): %s"), (unsigned long) errpos, tld_strerror (rc)); if (rc != TLD_SUCCESS) error (EXIT_FAILURE, 0, _("tld_check_4z: %s"), tld_strerror (rc)); } #endif if (args_info.debug_given) { size_t i; for (i = 0; p[i]; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, p[i]); } fprintf (stdout, "%s\n", p); free (p); } if (args_info.idna_to_unicode_given) { p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); q = stringprep_utf8_to_ucs4 (p, -1, NULL); if (!q) { free (p); error (EXIT_FAILURE, 0, _("could not convert from UCS-4 to UTF-8")); } if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); } free (q); rc = idna_to_unicode_8z4z (p, &q, (args_info.allow_unassigned_given ? IDNA_ALLOW_UNASSIGNED : 0) | (args_info.usestd3asciirules_given ? IDNA_USE_STD3_ASCII_RULES : 0)); free (p); if (rc != IDNA_SUCCESS) error (EXIT_FAILURE, 0, _("idna_to_unicode_8z4z: %s"), idna_strerror (rc)); if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, q[i]); } #ifdef WITH_TLD if (args_info.tld_flag) { size_t errpos; rc = tld_check_4z (q, &errpos, NULL); if (rc == TLD_INVALID) { free (q); error (EXIT_FAILURE, 0, _("tld_check_4z (position %lu): %s"), (unsigned long) errpos, tld_strerror (rc)); } if (rc != TLD_SUCCESS) { free (q); error (EXIT_FAILURE, 0, _("tld_check_4z: %s"), tld_strerror (rc)); } } #endif r = stringprep_ucs4_to_utf8 (q, -1, NULL, NULL); free (q); if (!r) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); p = stringprep_utf8_to_locale (r); free (r); if (!p) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } if (args_info.nfkc_given) { p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); if (args_info.debug_given) { size_t i; q = stringprep_utf8_to_ucs4 (p, -1, NULL); if (!q) { free (p); error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); } for (i = 0; q[i]; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); free (q); } r = stringprep_utf8_nfkc_normalize (p, -1); free (p); if (!r) error (EXIT_FAILURE, 0, _("could not do NFKC normalization")); if (args_info.debug_given) { size_t i; q = stringprep_utf8_to_ucs4 (r, -1, NULL); if (!q) { free (r); error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); } for (i = 0; q[i]; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, q[i]); free (q); } p = stringprep_utf8_to_locale (r); free (r); if (!p) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } fflush (stdout); } while (!feof (stdin) && !ferror (stdin) && (args_info.inputs_num == 0 || cmdn < args_info.inputs_num)); free (line); return EXIT_SUCCESS; }
164,985
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ldap_encode_response(struct asn1_data *data, struct ldap_Result *result) { asn1_write_enumerated(data, result->resultcode); asn1_write_OctetString(data, result->dn, (result->dn) ? strlen(result->dn) : 0); asn1_write_OctetString(data, result->errormessage, (result->errormessage) ? strlen(result->errormessage) : 0); if (result->referral) { asn1_push_tag(data, ASN1_CONTEXT(3)); asn1_write_OctetString(data, result->referral, strlen(result->referral)); asn1_pop_tag(data); } } Commit Message: CWE ID: CWE-399
static void ldap_encode_response(struct asn1_data *data, struct ldap_Result *result) static bool ldap_encode_response(struct asn1_data *data, struct ldap_Result *result) { if (!asn1_write_enumerated(data, result->resultcode)) return false; if (!asn1_write_OctetString(data, result->dn, (result->dn) ? strlen(result->dn) : 0)) return false; if (!asn1_write_OctetString(data, result->errormessage, (result->errormessage) ? strlen(result->errormessage) : 0)) return false; if (result->referral) { if (!asn1_push_tag(data, ASN1_CONTEXT(3))) return false; if (!asn1_write_OctetString(data, result->referral, strlen(result->referral))) return false; if (!asn1_pop_tag(data)) return false; } return true; }
164,593
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: get_pols_2_svc(gpols_arg *arg, struct svc_req *rqstp) { static gpols_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_gpols_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->exp; if (prime_arg == NULL) prime_arg = "*"; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_LIST, NULL, NULL)) { ret.code = KADM5_AUTH_LIST; log_unauth("kadm5_get_policies", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_get_policies((void *)handle, arg->exp, &ret.pols, &ret.count); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_get_policies", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
get_pols_2_svc(gpols_arg *arg, struct svc_req *rqstp) { static gpols_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_gpols_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->exp; if (prime_arg == NULL) prime_arg = "*"; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_LIST, NULL, NULL)) { ret.code = KADM5_AUTH_LIST; log_unauth("kadm5_get_policies", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_get_policies((void *)handle, arg->exp, &ret.pols, &ret.count); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_get_policies", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,514
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: Gfx::Gfx(XRef *xrefA, OutputDev *outA, Dict *resDict, Catalog *catalogA, PDFRectangle *box, PDFRectangle *cropBox, GBool (*abortCheckCbkA)(void *data), void *abortCheckCbkDataA) #ifdef USE_CMS : iccColorSpaceCache(5) #endif { int i; xref = xrefA; catalog = catalogA; subPage = gTrue; printCommands = globalParams->getPrintCommands(); profileCommands = globalParams->getProfileCommands(); textHaveCSPattern = gFalse; drawText = gFalse; drawText = gFalse; maskHaveCSPattern = gFalse; mcStack = NULL; res = new GfxResources(xref, resDict, NULL); out = outA; state = new GfxState(72, 72, box, 0, gFalse); stackHeight = 1; pushStateGuard(); fontChanged = gFalse; clip = clipNone; ignoreUndef = 0; for (i = 0; i < 6; ++i) { baseMatrix[i] = state->getCTM()[i]; } formDepth = 0; abortCheckCbk = abortCheckCbkA; abortCheckCbkData = abortCheckCbkDataA; if (cropBox) { state->moveTo(cropBox->x1, cropBox->y1); state->lineTo(cropBox->x2, cropBox->y1); state->lineTo(cropBox->x2, cropBox->y2); state->lineTo(cropBox->x1, cropBox->y2); state->closePath(); state->clip(); out->clip(state); state->clearPath(); } } Commit Message: CWE ID: CWE-20
Gfx::Gfx(XRef *xrefA, OutputDev *outA, Dict *resDict, Catalog *catalogA, PDFRectangle *box, PDFRectangle *cropBox, GBool (*abortCheckCbkA)(void *data), void *abortCheckCbkDataA) #ifdef USE_CMS : iccColorSpaceCache(5) #endif { int i; xref = xrefA; catalog = catalogA; subPage = gTrue; printCommands = globalParams->getPrintCommands(); profileCommands = globalParams->getProfileCommands(); textHaveCSPattern = gFalse; drawText = gFalse; drawText = gFalse; maskHaveCSPattern = gFalse; mcStack = NULL; parser = NULL; res = new GfxResources(xref, resDict, NULL); out = outA; state = new GfxState(72, 72, box, 0, gFalse); stackHeight = 1; pushStateGuard(); fontChanged = gFalse; clip = clipNone; ignoreUndef = 0; for (i = 0; i < 6; ++i) { baseMatrix[i] = state->getCTM()[i]; } formDepth = 0; abortCheckCbk = abortCheckCbkA; abortCheckCbkData = abortCheckCbkDataA; if (cropBox) { state->moveTo(cropBox->x1, cropBox->y1); state->lineTo(cropBox->x2, cropBox->y1); state->lineTo(cropBox->x2, cropBox->y2); state->lineTo(cropBox->x1, cropBox->y2); state->closePath(); state->clip(); out->clip(state); state->clearPath(); } }
164,905
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: jbig2_decode_gray_scale_image(Jbig2Ctx *ctx, Jbig2Segment *segment, const byte *data, const size_t size, bool GSMMR, uint32_t GSW, uint32_t GSH, uint32_t GSBPP, bool GSUSESKIP, Jbig2Image *GSKIP, int GSTEMPLATE, Jbig2ArithCx *GB_stats) { uint8_t **GSVALS = NULL; size_t consumed_bytes = 0; int i, j, code, stride; int x, y; Jbig2Image **GSPLANES; Jbig2GenericRegionParams rparams; Jbig2WordStream *ws = NULL; Jbig2ArithState *as = NULL; /* allocate GSPLANES */ GSPLANES = jbig2_new(ctx, Jbig2Image *, GSBPP); if (GSPLANES == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate %d bytes for GSPLANES", GSBPP); return NULL; } for (i = 0; i < GSBPP; ++i) { GSPLANES[i] = jbig2_image_new(ctx, GSW, GSH); if (GSPLANES[i] == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate %dx%d image for GSPLANES", GSW, GSH); /* free already allocated */ for (j = i - 1; j >= 0; --j) { jbig2_image_release(ctx, GSPLANES[j]); } jbig2_free(ctx->allocator, GSPLANES); return NULL; } } } Commit Message: CWE ID: CWE-119
jbig2_decode_gray_scale_image(Jbig2Ctx *ctx, Jbig2Segment *segment, const byte *data, const size_t size, bool GSMMR, uint32_t GSW, uint32_t GSH, uint32_t GSBPP, bool GSUSESKIP, Jbig2Image *GSKIP, int GSTEMPLATE, Jbig2ArithCx *GB_stats) { uint8_t **GSVALS = NULL; size_t consumed_bytes = 0; uint32_t i, j, stride, x, y; int code; Jbig2Image **GSPLANES; Jbig2GenericRegionParams rparams; Jbig2WordStream *ws = NULL; Jbig2ArithState *as = NULL; /* allocate GSPLANES */ GSPLANES = jbig2_new(ctx, Jbig2Image *, GSBPP); if (GSPLANES == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate %d bytes for GSPLANES", GSBPP); return NULL; } for (i = 0; i < GSBPP; ++i) { GSPLANES[i] = jbig2_image_new(ctx, GSW, GSH); if (GSPLANES[i] == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate %dx%d image for GSPLANES", GSW, GSH); /* free already allocated */ for (j = i; j > 0;) jbig2_image_release(ctx, GSPLANES[--j]); jbig2_free(ctx->allocator, GSPLANES); return NULL; } } }
165,487
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: BGD_DECLARE(void) gdImageWebp (gdImagePtr im, FILE * outFile) { gdIOCtx *out = gdNewFileCtx(outFile); if (out == NULL) { return; } gdImageWebpCtx(im, out, -1); out->gd_free(out); } Commit Message: Fix double-free in gdImageWebPtr() The issue is that gdImageWebpCtx() (which is called by gdImageWebpPtr() and the other WebP output functions to do the real work) does not return whether it succeeded or failed, so this is not checked in gdImageWebpPtr() and the function wrongly assumes everything is okay, which is not, in this case, because there is a size limitation for WebP, namely that the width and height must by less than 16383. We can't change the signature of gdImageWebpCtx() for API compatibility reasons, so we introduce the static helper _gdImageWebpCtx() which returns success respective failure, so gdImageWebpPtr() and gdImageWebpPtrEx() can check the return value. We leave it solely to libwebp for now to report warnings regarding the failing write. This issue had been reported by Ibrahim El-Sayed to [email protected]. CVE-2016-6912 CWE ID: CWE-415
BGD_DECLARE(void) gdImageWebp (gdImagePtr im, FILE * outFile) { gdIOCtx *out = gdNewFileCtx(outFile); if (out == NULL) { return; } _gdImageWebpCtx(im, out, -1); out->gd_free(out); }
168,816
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int tt_s2_4600_frontend_attach(struct dvb_usb_adapter *adap) { struct dvb_usb_device *d = adap->dev; struct dw2102_state *state = d->priv; u8 obuf[3] = { 0xe, 0x80, 0 }; u8 ibuf[] = { 0 }; struct i2c_adapter *i2c_adapter; struct i2c_client *client; struct i2c_board_info board_info; struct m88ds3103_platform_data m88ds3103_pdata = {}; struct ts2020_config ts2020_config = {}; if (dvb_usb_generic_rw(d, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0xe; obuf[1] = 0x02; obuf[2] = 1; if (dvb_usb_generic_rw(d, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); msleep(300); obuf[0] = 0xe; obuf[1] = 0x83; obuf[2] = 0; if (dvb_usb_generic_rw(d, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0xe; obuf[1] = 0x83; obuf[2] = 1; if (dvb_usb_generic_rw(d, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0x51; if (dvb_usb_generic_rw(d, obuf, 1, ibuf, 1, 0) < 0) err("command 0x51 transfer failed."); /* attach demod */ m88ds3103_pdata.clk = 27000000; m88ds3103_pdata.i2c_wr_max = 33; m88ds3103_pdata.ts_mode = M88DS3103_TS_CI; m88ds3103_pdata.ts_clk = 16000; m88ds3103_pdata.ts_clk_pol = 0; m88ds3103_pdata.spec_inv = 0; m88ds3103_pdata.agc = 0x99; m88ds3103_pdata.agc_inv = 0; m88ds3103_pdata.clk_out = M88DS3103_CLOCK_OUT_ENABLED; m88ds3103_pdata.envelope_mode = 0; m88ds3103_pdata.lnb_hv_pol = 1; m88ds3103_pdata.lnb_en_pol = 0; memset(&board_info, 0, sizeof(board_info)); strlcpy(board_info.type, "m88ds3103", I2C_NAME_SIZE); board_info.addr = 0x68; board_info.platform_data = &m88ds3103_pdata; request_module("m88ds3103"); client = i2c_new_device(&d->i2c_adap, &board_info); if (client == NULL || client->dev.driver == NULL) return -ENODEV; if (!try_module_get(client->dev.driver->owner)) { i2c_unregister_device(client); return -ENODEV; } adap->fe_adap[0].fe = m88ds3103_pdata.get_dvb_frontend(client); i2c_adapter = m88ds3103_pdata.get_i2c_adapter(client); state->i2c_client_demod = client; /* attach tuner */ ts2020_config.fe = adap->fe_adap[0].fe; memset(&board_info, 0, sizeof(board_info)); strlcpy(board_info.type, "ts2022", I2C_NAME_SIZE); board_info.addr = 0x60; board_info.platform_data = &ts2020_config; request_module("ts2020"); client = i2c_new_device(i2c_adapter, &board_info); if (client == NULL || client->dev.driver == NULL) { dvb_frontend_detach(adap->fe_adap[0].fe); return -ENODEV; } if (!try_module_get(client->dev.driver->owner)) { i2c_unregister_device(client); dvb_frontend_detach(adap->fe_adap[0].fe); return -ENODEV; } /* delegate signal strength measurement to tuner */ adap->fe_adap[0].fe->ops.read_signal_strength = adap->fe_adap[0].fe->ops.tuner_ops.get_rf_strength; state->i2c_client_tuner = client; /* hook fe: need to resync the slave fifo when signal locks */ state->fe_read_status = adap->fe_adap[0].fe->ops.read_status; adap->fe_adap[0].fe->ops.read_status = tt_s2_4600_read_status; state->last_lock = 0; return 0; } Commit Message: [media] dw2102: don't do DMA on stack On Kernel 4.9, WARNINGs about doing DMA on stack are hit at the dw2102 driver: one in su3000_power_ctrl() and the other in tt_s2_4600_frontend_attach(). Both were due to the use of buffers on the stack as parameters to dvb_usb_generic_rw() and the resulting attempt to do DMA with them. The device was non-functional as a result. So, switch this driver over to use a buffer within the device state structure, as has been done with other DVB-USB drivers. Tested with TechnoTrend TT-connect S2-4600. [[email protected]: fixed a warning at su3000_i2c_transfer() that state var were dereferenced before check 'd'] Signed-off-by: Jonathan McDowell <[email protected]> Cc: <[email protected]> Signed-off-by: Mauro Carvalho Chehab <[email protected]> CWE ID: CWE-119
static int tt_s2_4600_frontend_attach(struct dvb_usb_adapter *adap) { struct dvb_usb_device *d = adap->dev; struct dw2102_state *state = d->priv; struct i2c_adapter *i2c_adapter; struct i2c_client *client; struct i2c_board_info board_info; struct m88ds3103_platform_data m88ds3103_pdata = {}; struct ts2020_config ts2020_config = {}; mutex_lock(&d->data_mutex); state->data[0] = 0xe; state->data[1] = 0x80; state->data[2] = 0x0; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) err("command 0x0e transfer failed."); state->data[0] = 0xe; state->data[1] = 0x02; state->data[2] = 1; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) err("command 0x0e transfer failed."); msleep(300); state->data[0] = 0xe; state->data[1] = 0x83; state->data[2] = 0; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) err("command 0x0e transfer failed."); state->data[0] = 0xe; state->data[1] = 0x83; state->data[2] = 1; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) err("command 0x0e transfer failed."); state->data[0] = 0x51; if (dvb_usb_generic_rw(d, state->data, 1, state->data, 1, 0) < 0) err("command 0x51 transfer failed."); mutex_unlock(&d->data_mutex); /* attach demod */ m88ds3103_pdata.clk = 27000000; m88ds3103_pdata.i2c_wr_max = 33; m88ds3103_pdata.ts_mode = M88DS3103_TS_CI; m88ds3103_pdata.ts_clk = 16000; m88ds3103_pdata.ts_clk_pol = 0; m88ds3103_pdata.spec_inv = 0; m88ds3103_pdata.agc = 0x99; m88ds3103_pdata.agc_inv = 0; m88ds3103_pdata.clk_out = M88DS3103_CLOCK_OUT_ENABLED; m88ds3103_pdata.envelope_mode = 0; m88ds3103_pdata.lnb_hv_pol = 1; m88ds3103_pdata.lnb_en_pol = 0; memset(&board_info, 0, sizeof(board_info)); strlcpy(board_info.type, "m88ds3103", I2C_NAME_SIZE); board_info.addr = 0x68; board_info.platform_data = &m88ds3103_pdata; request_module("m88ds3103"); client = i2c_new_device(&d->i2c_adap, &board_info); if (client == NULL || client->dev.driver == NULL) return -ENODEV; if (!try_module_get(client->dev.driver->owner)) { i2c_unregister_device(client); return -ENODEV; } adap->fe_adap[0].fe = m88ds3103_pdata.get_dvb_frontend(client); i2c_adapter = m88ds3103_pdata.get_i2c_adapter(client); state->i2c_client_demod = client; /* attach tuner */ ts2020_config.fe = adap->fe_adap[0].fe; memset(&board_info, 0, sizeof(board_info)); strlcpy(board_info.type, "ts2022", I2C_NAME_SIZE); board_info.addr = 0x60; board_info.platform_data = &ts2020_config; request_module("ts2020"); client = i2c_new_device(i2c_adapter, &board_info); if (client == NULL || client->dev.driver == NULL) { dvb_frontend_detach(adap->fe_adap[0].fe); return -ENODEV; } if (!try_module_get(client->dev.driver->owner)) { i2c_unregister_device(client); dvb_frontend_detach(adap->fe_adap[0].fe); return -ENODEV; } /* delegate signal strength measurement to tuner */ adap->fe_adap[0].fe->ops.read_signal_strength = adap->fe_adap[0].fe->ops.tuner_ops.get_rf_strength; state->i2c_client_tuner = client; /* hook fe: need to resync the slave fifo when signal locks */ state->fe_read_status = adap->fe_adap[0].fe->ops.read_status; adap->fe_adap[0].fe->ops.read_status = tt_s2_4600_read_status; state->last_lock = 0; return 0; }
168,229
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RemoteFrame::ScheduleNavigation(Document& origin_document, const KURL& url, WebFrameLoadType frame_load_type, UserGestureStatus user_gesture_status) { FrameLoadRequest frame_request(&origin_document, ResourceRequest(url)); frame_request.GetResourceRequest().SetHasUserGesture( user_gesture_status == UserGestureStatus::kActive); frame_request.GetResourceRequest().SetFrameType( IsMainFrame() ? network::mojom::RequestContextFrameType::kTopLevel : network::mojom::RequestContextFrameType::kNested); Navigate(frame_request, frame_load_type); } Commit Message: Add a check for disallowing remote frame navigations to local resources. Previously, RemoteFrame navigations did not perform any renderer-side checks and relied solely on the browser-side logic to block disallowed navigations via mechanisms like FilterURL. This means that blocked remote frame navigations were silently navigated to about:blank without any console error message. This CL adds a CanDisplay check to the remote navigation path to match an equivalent check done for local frame navigations. This way, the renderer can consistently block disallowed navigations in both cases and output an error message. Bug: 894399 Change-Id: I172f68f77c1676f6ca0172d2a6c78f7edc0e3b7a Reviewed-on: https://chromium-review.googlesource.com/c/1282390 Reviewed-by: Charlie Reis <[email protected]> Reviewed-by: Nate Chapin <[email protected]> Commit-Queue: Alex Moshchuk <[email protected]> Cr-Commit-Position: refs/heads/master@{#601022} CWE ID: CWE-732
void RemoteFrame::ScheduleNavigation(Document& origin_document, const KURL& url, WebFrameLoadType frame_load_type, UserGestureStatus user_gesture_status) { if (!origin_document.GetSecurityOrigin()->CanDisplay(url)) { origin_document.AddConsoleMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "Not allowed to load local resource: " + url.ElidedString())); return; } FrameLoadRequest frame_request(&origin_document, ResourceRequest(url)); frame_request.GetResourceRequest().SetHasUserGesture( user_gesture_status == UserGestureStatus::kActive); frame_request.GetResourceRequest().SetFrameType( IsMainFrame() ? network::mojom::RequestContextFrameType::kTopLevel : network::mojom::RequestContextFrameType::kNested); Navigate(frame_request, frame_load_type); }
172,614
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: DictionaryValue* ExtensionTabUtil::CreateTabValue( const WebContents* contents, TabStripModel* tab_strip, int tab_index, const Extension* extension) { bool has_permission = extension && extension->HasAPIPermissionForTab( GetTabId(contents), APIPermission::kTab); return CreateTabValue(contents, tab_strip, tab_index, has_permission ? INCLUDE_PRIVACY_SENSITIVE_FIELDS : OMIT_PRIVACY_SENSITIVE_FIELDS); } Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the "tabs" permission. BUG=168442 Review URL: https://chromiumcodereview.appspot.com/11824004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
DictionaryValue* ExtensionTabUtil::CreateTabValue( const WebContents* contents, TabStripModel* tab_strip, int tab_index, const Extension* extension) { DictionaryValue *result = CreateTabValue(contents, tab_strip, tab_index); ScrubTabValueForExtension(contents, extension, result); return result; }
171,454
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void HistoryModelWorker::DoWorkAndWaitUntilDone(Callback0::Type* work) { WaitableEvent done(false, false); scoped_refptr<WorkerTask> task(new WorkerTask(work, &done)); history_service_->ScheduleDBTask(task.get(), this); done.Wait(); } Commit Message: Enable HistoryModelWorker by default, now that bug 69561 is fixed. BUG=69561 TEST=Run sync manually and run integration tests, sync should not crash. Review URL: http://codereview.chromium.org/7016007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@85211 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void HistoryModelWorker::DoWorkAndWaitUntilDone(Callback0::Type* work) { WaitableEvent done(false, false); scoped_refptr<WorkerTask> task(new WorkerTask(work, &done)); history_service_->ScheduleDBTask(task.get(), &cancelable_consumer_); done.Wait(); }
170,613
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool WebContentsImpl::IsLoading() const { return frame_tree_.IsLoading() && !(ShowingInterstitialPage() && GetRenderManager()->interstitial_page()->pause_throbber()); } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20
bool WebContentsImpl::IsLoading() const { return frame_tree_.IsLoading() && !(ShowingInterstitialPage() && interstitial_page_->pause_throbber()); }
172,331
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: uint8_t smb2cli_session_security_mode(struct smbXcli_session *session) { struct smbXcli_conn *conn = session->conn; uint8_t security_mode = 0; if (conn == NULL) { return security_mode; } security_mode = SMB2_NEGOTIATE_SIGNING_ENABLED; if (conn->mandatory_signing) { security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED; } return security_mode; } Commit Message: CWE ID: CWE-20
uint8_t smb2cli_session_security_mode(struct smbXcli_session *session) { struct smbXcli_conn *conn = session->conn; uint8_t security_mode = 0; if (conn == NULL) { return security_mode; } security_mode = SMB2_NEGOTIATE_SIGNING_ENABLED; if (conn->mandatory_signing) { security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED; } if (session->smb2->should_sign) { security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED; } return security_mode; }
164,675
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int rds_loop_xmit(struct rds_connection *conn, struct rds_message *rm, unsigned int hdr_off, unsigned int sg, unsigned int off) { /* Do not send cong updates to loopback */ if (rm->m_inc.i_hdr.h_flags & RDS_FLAG_CONG_BITMAP) { rds_cong_map_updated(conn->c_fcong, ~(u64) 0); return sizeof(struct rds_header) + RDS_CONG_MAP_BYTES; } BUG_ON(hdr_off || sg || off); rds_inc_init(&rm->m_inc, conn, conn->c_laddr); /* For the embedded inc. Matching put is in loop_inc_free() */ rds_message_addref(rm); rds_recv_incoming(conn, conn->c_laddr, conn->c_faddr, &rm->m_inc, GFP_KERNEL, KM_USER0); rds_send_drop_acked(conn, be64_to_cpu(rm->m_inc.i_hdr.h_sequence), NULL); rds_inc_put(&rm->m_inc); return sizeof(struct rds_header) + be32_to_cpu(rm->m_inc.i_hdr.h_len); } Commit Message: rds: prevent BUG_ON triggering on congestion map updates Recently had this bug halt reported to me: kernel BUG at net/rds/send.c:329! Oops: Exception in kernel mode, sig: 5 [#1] SMP NR_CPUS=1024 NUMA pSeries Modules linked in: rds sunrpc ipv6 dm_mirror dm_region_hash dm_log ibmveth sg ext4 jbd2 mbcache sd_mod crc_t10dif ibmvscsic scsi_transport_srp scsi_tgt dm_mod [last unloaded: scsi_wait_scan] NIP: d000000003ca68f4 LR: d000000003ca67fc CTR: d000000003ca8770 REGS: c000000175cab980 TRAP: 0700 Not tainted (2.6.32-118.el6.ppc64) MSR: 8000000000029032 <EE,ME,CE,IR,DR> CR: 44000022 XER: 00000000 TASK = c00000017586ec90[1896] 'krdsd' THREAD: c000000175ca8000 CPU: 0 GPR00: 0000000000000150 c000000175cabc00 d000000003cb7340 0000000000002030 GPR04: ffffffffffffffff 0000000000000030 0000000000000000 0000000000000030 GPR08: 0000000000000001 0000000000000001 c0000001756b1e30 0000000000010000 GPR12: d000000003caac90 c000000000fa2500 c0000001742b2858 c0000001742b2a00 GPR16: c0000001742b2a08 c0000001742b2820 0000000000000001 0000000000000001 GPR20: 0000000000000040 c0000001742b2814 c000000175cabc70 0800000000000000 GPR24: 0000000000000004 0200000000000000 0000000000000000 c0000001742b2860 GPR28: 0000000000000000 c0000001756b1c80 d000000003cb68e8 c0000001742b27b8 NIP [d000000003ca68f4] .rds_send_xmit+0x4c4/0x8a0 [rds] LR [d000000003ca67fc] .rds_send_xmit+0x3cc/0x8a0 [rds] Call Trace: [c000000175cabc00] [d000000003ca67fc] .rds_send_xmit+0x3cc/0x8a0 [rds] (unreliable) [c000000175cabd30] [d000000003ca7e64] .rds_send_worker+0x54/0x100 [rds] [c000000175cabdb0] [c0000000000b475c] .worker_thread+0x1dc/0x3c0 [c000000175cabed0] [c0000000000baa9c] .kthread+0xbc/0xd0 [c000000175cabf90] [c000000000032114] .kernel_thread+0x54/0x70 Instruction dump: 4bfffd50 60000000 60000000 39080001 935f004c f91f0040 41820024 813d017c 7d094a78 7d290074 7929d182 394a0020 <0b090000> 40e2ff68 4bffffa4 39200000 Kernel panic - not syncing: Fatal exception Call Trace: [c000000175cab560] [c000000000012e04] .show_stack+0x74/0x1c0 (unreliable) [c000000175cab610] [c0000000005a365c] .panic+0x80/0x1b4 [c000000175cab6a0] [c00000000002fbcc] .die+0x21c/0x2a0 [c000000175cab750] [c000000000030000] ._exception+0x110/0x220 [c000000175cab910] [c000000000004b9c] program_check_common+0x11c/0x180 Signed-off-by: David S. Miller <[email protected]> CWE ID:
static int rds_loop_xmit(struct rds_connection *conn, struct rds_message *rm, unsigned int hdr_off, unsigned int sg, unsigned int off) { struct scatterlist *sgp = &rm->data.op_sg[sg]; int ret = sizeof(struct rds_header) + be32_to_cpu(rm->m_inc.i_hdr.h_len); /* Do not send cong updates to loopback */ if (rm->m_inc.i_hdr.h_flags & RDS_FLAG_CONG_BITMAP) { rds_cong_map_updated(conn->c_fcong, ~(u64) 0); ret = min_t(int, ret, sgp->length - conn->c_xmit_data_off); goto out; } BUG_ON(hdr_off || sg || off); rds_inc_init(&rm->m_inc, conn, conn->c_laddr); /* For the embedded inc. Matching put is in loop_inc_free() */ rds_message_addref(rm); rds_recv_incoming(conn, conn->c_laddr, conn->c_faddr, &rm->m_inc, GFP_KERNEL, KM_USER0); rds_send_drop_acked(conn, be64_to_cpu(rm->m_inc.i_hdr.h_sequence), NULL); rds_inc_put(&rm->m_inc); out: return ret; }
165,900
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static pngquant_error rwpng_read_image24_libpng(FILE *infile, png24_image *mainprog_ptr, int verbose) { png_structp png_ptr = NULL; png_infop info_ptr = NULL; png_size_t rowbytes; int color_type, bit_depth; png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr, rwpng_error_handler, verbose ? rwpng_warning_stderr_handler : rwpng_warning_silent_handler); if (!png_ptr) { return PNG_OUT_OF_MEMORY_ERROR; /* out of memory */ } info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, NULL, NULL); return PNG_OUT_OF_MEMORY_ERROR; /* out of memory */ } /* setjmp() must be called in every function that calls a non-trivial * libpng function */ if (setjmp(mainprog_ptr->jmpbuf)) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return LIBPNG_FATAL_ERROR; /* fatal libpng error (via longjmp()) */ } #if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED) png_set_option(png_ptr, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON); #endif #if PNG_LIBPNG_VER >= 10500 && defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) /* copy standard chunks too */ png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_IF_SAFE, (png_const_bytep)"pHYs\0iTXt\0tEXt\0zTXt", 4); #endif png_set_read_user_chunk_fn(png_ptr, &mainprog_ptr->chunks, read_chunk_callback); struct rwpng_read_data read_data = {infile, 0}; png_set_read_fn(png_ptr, &read_data, user_read_data); png_read_info(png_ptr, info_ptr); /* read all PNG info up to image data */ /* alternatively, could make separate calls to png_get_image_width(), * etc., but want bit_depth and color_type for later [don't care about * compression_type and filter_type => NULLs] */ png_get_IHDR(png_ptr, info_ptr, &mainprog_ptr->width, &mainprog_ptr->height, &bit_depth, &color_type, NULL, NULL, NULL); if (mainprog_ptr->width > INT_MAX/mainprog_ptr->height) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return PNG_OUT_OF_MEMORY_ERROR; /* not quite true, but whatever */ } /* expand palette images to RGB, low-bit-depth grayscale images to 8 bits, * transparency chunks to full alpha channel; strip 16-bit-per-sample * images to 8 bits per sample; and convert grayscale to RGB[A] */ /* GRR TO DO: preserve all safe-to-copy ancillary PNG chunks */ if (!(color_type & PNG_COLOR_MASK_ALPHA)) { #ifdef PNG_READ_FILLER_SUPPORTED png_set_expand(png_ptr); png_set_filler(png_ptr, 65535L, PNG_FILLER_AFTER); #else fprintf(stderr, "pngquant readpng: image is neither RGBA nor GA\n"); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); mainprog_ptr->retval = WRONG_INPUT_COLOR_TYPE; return mainprog_ptr->retval; #endif } if (bit_depth == 16) { png_set_strip_16(png_ptr); } if (!(color_type & PNG_COLOR_MASK_COLOR)) { png_set_gray_to_rgb(png_ptr); } /* get source gamma for gamma correction, or use sRGB default */ double gamma = 0.45455; if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) { mainprog_ptr->input_color = RWPNG_SRGB; mainprog_ptr->output_color = RWPNG_SRGB; } else { png_get_gAMA(png_ptr, info_ptr, &gamma); if (gamma > 0 && gamma <= 1.0) { mainprog_ptr->input_color = RWPNG_GAMA_ONLY; mainprog_ptr->output_color = RWPNG_GAMA_ONLY; } else { fprintf(stderr, "pngquant readpng: ignored out-of-range gamma %f\n", gamma); mainprog_ptr->input_color = RWPNG_NONE; mainprog_ptr->output_color = RWPNG_NONE; gamma = 0.45455; } } mainprog_ptr->gamma = gamma; png_set_interlace_handling(png_ptr); /* all transformations have been registered; now update info_ptr data, * get rowbytes and channels, and allocate image memory */ png_read_update_info(png_ptr, info_ptr); rowbytes = png_get_rowbytes(png_ptr, info_ptr); if ((mainprog_ptr->rgba_data = malloc(rowbytes * mainprog_ptr->height)) == NULL) { fprintf(stderr, "pngquant readpng: unable to allocate image data\n"); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return PNG_OUT_OF_MEMORY_ERROR; } png_bytepp row_pointers = rwpng_create_row_pointers(info_ptr, png_ptr, mainprog_ptr->rgba_data, mainprog_ptr->height, 0); /* now we can go ahead and just read the whole image */ png_read_image(png_ptr, row_pointers); /* and we're done! (png_read_end() can be omitted if no processing of * post-IDAT text/time/etc. is desired) */ png_read_end(png_ptr, NULL); #if USE_LCMS #if PNG_LIBPNG_VER < 10500 png_charp ProfileData; #else png_bytep ProfileData; #endif png_uint_32 ProfileLen; cmsHPROFILE hInProfile = NULL; /* color_type is read from the image before conversion to RGBA */ int COLOR_PNG = color_type & PNG_COLOR_MASK_COLOR; /* embedded ICC profile */ if (png_get_iCCP(png_ptr, info_ptr, &(png_charp){0}, &(int){0}, &ProfileData, &ProfileLen)) { hInProfile = cmsOpenProfileFromMem(ProfileData, ProfileLen); cmsColorSpaceSignature colorspace = cmsGetColorSpace(hInProfile); /* only RGB (and GRAY) valid for PNGs */ if (colorspace == cmsSigRgbData && COLOR_PNG) { mainprog_ptr->input_color = RWPNG_ICCP; mainprog_ptr->output_color = RWPNG_SRGB; } else { if (colorspace == cmsSigGrayData && !COLOR_PNG) { mainprog_ptr->input_color = RWPNG_ICCP_WARN_GRAY; mainprog_ptr->output_color = RWPNG_SRGB; } cmsCloseProfile(hInProfile); hInProfile = NULL; } } /* build RGB profile from cHRM and gAMA */ if (hInProfile == NULL && COLOR_PNG && !png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB) && png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA) && png_get_valid(png_ptr, info_ptr, PNG_INFO_cHRM)) { cmsCIExyY WhitePoint; cmsCIExyYTRIPLE Primaries; png_get_cHRM(png_ptr, info_ptr, &WhitePoint.x, &WhitePoint.y, &Primaries.Red.x, &Primaries.Red.y, &Primaries.Green.x, &Primaries.Green.y, &Primaries.Blue.x, &Primaries.Blue.y); WhitePoint.Y = Primaries.Red.Y = Primaries.Green.Y = Primaries.Blue.Y = 1.0; cmsToneCurve *GammaTable[3]; GammaTable[0] = GammaTable[1] = GammaTable[2] = cmsBuildGamma(NULL, 1/gamma); hInProfile = cmsCreateRGBProfile(&WhitePoint, &Primaries, GammaTable); cmsFreeToneCurve(GammaTable[0]); mainprog_ptr->input_color = RWPNG_GAMA_CHRM; mainprog_ptr->output_color = RWPNG_SRGB; } /* transform image to sRGB colorspace */ if (hInProfile != NULL) { cmsHPROFILE hOutProfile = cmsCreate_sRGBProfile(); cmsHTRANSFORM hTransform = cmsCreateTransform(hInProfile, TYPE_RGBA_8, hOutProfile, TYPE_RGBA_8, INTENT_PERCEPTUAL, omp_get_max_threads() > 1 ? cmsFLAGS_NOCACHE : 0); #pragma omp parallel for \ if (mainprog_ptr->height*mainprog_ptr->width > 8000) \ schedule(static) for (unsigned int i = 0; i < mainprog_ptr->height; i++) { /* It is safe to use the same block for input and output, when both are of the same TYPE. */ cmsDoTransform(hTransform, row_pointers[i], row_pointers[i], mainprog_ptr->width); } cmsDeleteTransform(hTransform); cmsCloseProfile(hOutProfile); cmsCloseProfile(hInProfile); mainprog_ptr->gamma = 0.45455; } #endif png_destroy_read_struct(&png_ptr, &info_ptr, NULL); mainprog_ptr->file_size = read_data.bytes_read; mainprog_ptr->row_pointers = (unsigned char **)row_pointers; return SUCCESS; } Commit Message: Fix integer overflow in rwpng.h (CVE-2016-5735) Reported by Choi Jaeseung Found with Sparrow (http://ropas.snu.ac.kr/sparrow) CWE ID: CWE-190
static pngquant_error rwpng_read_image24_libpng(FILE *infile, png24_image *mainprog_ptr, int verbose) { png_structp png_ptr = NULL; png_infop info_ptr = NULL; png_size_t rowbytes; int color_type, bit_depth; png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr, rwpng_error_handler, verbose ? rwpng_warning_stderr_handler : rwpng_warning_silent_handler); if (!png_ptr) { return PNG_OUT_OF_MEMORY_ERROR; /* out of memory */ } info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, NULL, NULL); return PNG_OUT_OF_MEMORY_ERROR; /* out of memory */ } /* setjmp() must be called in every function that calls a non-trivial * libpng function */ if (setjmp(mainprog_ptr->jmpbuf)) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return LIBPNG_FATAL_ERROR; /* fatal libpng error (via longjmp()) */ } #if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED) png_set_option(png_ptr, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON); #endif #if PNG_LIBPNG_VER >= 10500 && defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) /* copy standard chunks too */ png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_IF_SAFE, (png_const_bytep)"pHYs\0iTXt\0tEXt\0zTXt", 4); #endif png_set_read_user_chunk_fn(png_ptr, &mainprog_ptr->chunks, read_chunk_callback); struct rwpng_read_data read_data = {infile, 0}; png_set_read_fn(png_ptr, &read_data, user_read_data); png_read_info(png_ptr, info_ptr); /* read all PNG info up to image data */ /* alternatively, could make separate calls to png_get_image_width(), * etc., but want bit_depth and color_type for later [don't care about * compression_type and filter_type => NULLs] */ png_get_IHDR(png_ptr, info_ptr, &mainprog_ptr->width, &mainprog_ptr->height, &bit_depth, &color_type, NULL, NULL, NULL); /* expand palette images to RGB, low-bit-depth grayscale images to 8 bits, * transparency chunks to full alpha channel; strip 16-bit-per-sample * images to 8 bits per sample; and convert grayscale to RGB[A] */ /* GRR TO DO: preserve all safe-to-copy ancillary PNG chunks */ if (!(color_type & PNG_COLOR_MASK_ALPHA)) { #ifdef PNG_READ_FILLER_SUPPORTED png_set_expand(png_ptr); png_set_filler(png_ptr, 65535L, PNG_FILLER_AFTER); #else fprintf(stderr, "pngquant readpng: image is neither RGBA nor GA\n"); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); mainprog_ptr->retval = WRONG_INPUT_COLOR_TYPE; return mainprog_ptr->retval; #endif } if (bit_depth == 16) { png_set_strip_16(png_ptr); } if (!(color_type & PNG_COLOR_MASK_COLOR)) { png_set_gray_to_rgb(png_ptr); } /* get source gamma for gamma correction, or use sRGB default */ double gamma = 0.45455; if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) { mainprog_ptr->input_color = RWPNG_SRGB; mainprog_ptr->output_color = RWPNG_SRGB; } else { png_get_gAMA(png_ptr, info_ptr, &gamma); if (gamma > 0 && gamma <= 1.0) { mainprog_ptr->input_color = RWPNG_GAMA_ONLY; mainprog_ptr->output_color = RWPNG_GAMA_ONLY; } else { fprintf(stderr, "pngquant readpng: ignored out-of-range gamma %f\n", gamma); mainprog_ptr->input_color = RWPNG_NONE; mainprog_ptr->output_color = RWPNG_NONE; gamma = 0.45455; } } mainprog_ptr->gamma = gamma; png_set_interlace_handling(png_ptr); /* all transformations have been registered; now update info_ptr data, * get rowbytes and channels, and allocate image memory */ png_read_update_info(png_ptr, info_ptr); rowbytes = png_get_rowbytes(png_ptr, info_ptr); // For overflow safety reject images that won't fit in 32-bit if (rowbytes > INT_MAX/mainprog_ptr->height) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return PNG_OUT_OF_MEMORY_ERROR; } if ((mainprog_ptr->rgba_data = malloc(rowbytes * mainprog_ptr->height)) == NULL) { fprintf(stderr, "pngquant readpng: unable to allocate image data\n"); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return PNG_OUT_OF_MEMORY_ERROR; } png_bytepp row_pointers = rwpng_create_row_pointers(info_ptr, png_ptr, mainprog_ptr->rgba_data, mainprog_ptr->height, 0); /* now we can go ahead and just read the whole image */ png_read_image(png_ptr, row_pointers); /* and we're done! (png_read_end() can be omitted if no processing of * post-IDAT text/time/etc. is desired) */ png_read_end(png_ptr, NULL); #if USE_LCMS #if PNG_LIBPNG_VER < 10500 png_charp ProfileData; #else png_bytep ProfileData; #endif png_uint_32 ProfileLen; cmsHPROFILE hInProfile = NULL; /* color_type is read from the image before conversion to RGBA */ int COLOR_PNG = color_type & PNG_COLOR_MASK_COLOR; /* embedded ICC profile */ if (png_get_iCCP(png_ptr, info_ptr, &(png_charp){0}, &(int){0}, &ProfileData, &ProfileLen)) { hInProfile = cmsOpenProfileFromMem(ProfileData, ProfileLen); cmsColorSpaceSignature colorspace = cmsGetColorSpace(hInProfile); /* only RGB (and GRAY) valid for PNGs */ if (colorspace == cmsSigRgbData && COLOR_PNG) { mainprog_ptr->input_color = RWPNG_ICCP; mainprog_ptr->output_color = RWPNG_SRGB; } else { if (colorspace == cmsSigGrayData && !COLOR_PNG) { mainprog_ptr->input_color = RWPNG_ICCP_WARN_GRAY; mainprog_ptr->output_color = RWPNG_SRGB; } cmsCloseProfile(hInProfile); hInProfile = NULL; } } /* build RGB profile from cHRM and gAMA */ if (hInProfile == NULL && COLOR_PNG && !png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB) && png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA) && png_get_valid(png_ptr, info_ptr, PNG_INFO_cHRM)) { cmsCIExyY WhitePoint; cmsCIExyYTRIPLE Primaries; png_get_cHRM(png_ptr, info_ptr, &WhitePoint.x, &WhitePoint.y, &Primaries.Red.x, &Primaries.Red.y, &Primaries.Green.x, &Primaries.Green.y, &Primaries.Blue.x, &Primaries.Blue.y); WhitePoint.Y = Primaries.Red.Y = Primaries.Green.Y = Primaries.Blue.Y = 1.0; cmsToneCurve *GammaTable[3]; GammaTable[0] = GammaTable[1] = GammaTable[2] = cmsBuildGamma(NULL, 1/gamma); hInProfile = cmsCreateRGBProfile(&WhitePoint, &Primaries, GammaTable); cmsFreeToneCurve(GammaTable[0]); mainprog_ptr->input_color = RWPNG_GAMA_CHRM; mainprog_ptr->output_color = RWPNG_SRGB; } /* transform image to sRGB colorspace */ if (hInProfile != NULL) { cmsHPROFILE hOutProfile = cmsCreate_sRGBProfile(); cmsHTRANSFORM hTransform = cmsCreateTransform(hInProfile, TYPE_RGBA_8, hOutProfile, TYPE_RGBA_8, INTENT_PERCEPTUAL, omp_get_max_threads() > 1 ? cmsFLAGS_NOCACHE : 0); #pragma omp parallel for \ if (mainprog_ptr->height*mainprog_ptr->width > 8000) \ schedule(static) for (unsigned int i = 0; i < mainprog_ptr->height; i++) { /* It is safe to use the same block for input and output, when both are of the same TYPE. */ cmsDoTransform(hTransform, row_pointers[i], row_pointers[i], mainprog_ptr->width); } cmsDeleteTransform(hTransform); cmsCloseProfile(hOutProfile); cmsCloseProfile(hInProfile); mainprog_ptr->gamma = 0.45455; } #endif png_destroy_read_struct(&png_ptr, &info_ptr, NULL); mainprog_ptr->file_size = read_data.bytes_read; mainprog_ptr->row_pointers = (unsigned char **)row_pointers; return SUCCESS; }
168,835
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: read_pbm_integer(j_compress_ptr cinfo, FILE *infile, unsigned int maxval) /* Read an unsigned decimal integer from the PPM file */ /* Swallows one trailing character after the integer */ /* Note that on a 16-bit-int machine, only values up to 64k can be read. */ /* This should not be a problem in practice. */ { register int ch; register unsigned int val; /* Skip any leading whitespace */ do { ch = pbm_getc(infile); if (ch == EOF) ERREXIT(cinfo, JERR_INPUT_EOF); } while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'); if (ch < '0' || ch > '9') ERREXIT(cinfo, JERR_PPM_NONNUMERIC); val = ch - '0'; while ((ch = pbm_getc(infile)) >= '0' && ch <= '9') { val *= 10; val += ch - '0'; } if (val > maxval) ERREXIT(cinfo, JERR_PPM_TOOLARGE); return val; } Commit Message: cjpeg: Fix OOB read caused by malformed 8-bit BMP ... in which one or more of the color indices is out of range for the number of palette entries. Fix partly borrowed from jpeg-9c. This commit also adopts Guido's JERR_PPM_OUTOFRANGE enum value in lieu of our project-specific JERR_PPM_TOOLARGE enum value. Fixes #258 CWE ID: CWE-125
read_pbm_integer(j_compress_ptr cinfo, FILE *infile, unsigned int maxval) /* Read an unsigned decimal integer from the PPM file */ /* Swallows one trailing character after the integer */ /* Note that on a 16-bit-int machine, only values up to 64k can be read. */ /* This should not be a problem in practice. */ { register int ch; register unsigned int val; /* Skip any leading whitespace */ do { ch = pbm_getc(infile); if (ch == EOF) ERREXIT(cinfo, JERR_INPUT_EOF); } while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'); if (ch < '0' || ch > '9') ERREXIT(cinfo, JERR_PPM_NONNUMERIC); val = ch - '0'; while ((ch = pbm_getc(infile)) >= '0' && ch <= '9') { val *= 10; val += ch - '0'; } if (val > maxval) ERREXIT(cinfo, JERR_PPM_OUTOFRANGE); return val; }
169,840
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXNodeInstance::useGraphicBuffer2_l( OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer, OMX::buffer_id *buffer) { OMX_PARAM_PORTDEFINITIONTYPE def; InitOMXParams(&def); def.nPortIndex = portIndex; OMX_ERRORTYPE err = OMX_GetParameter(mHandle, OMX_IndexParamPortDefinition, &def); if (err != OMX_ErrorNone) { OMX_INDEXTYPE index = OMX_IndexParamPortDefinition; CLOG_ERROR(getParameter, err, "%s(%#x): %s:%u", asString(index), index, portString(portIndex), portIndex); return UNKNOWN_ERROR; } BufferMeta *bufferMeta = new BufferMeta(graphicBuffer); OMX_BUFFERHEADERTYPE *header = NULL; OMX_U8* bufferHandle = const_cast<OMX_U8*>( reinterpret_cast<const OMX_U8*>(graphicBuffer->handle)); err = OMX_UseBuffer( mHandle, &header, portIndex, bufferMeta, def.nBufferSize, bufferHandle); if (err != OMX_ErrorNone) { CLOG_ERROR(useBuffer, err, BUFFER_FMT(portIndex, "%u@%p", def.nBufferSize, bufferHandle)); delete bufferMeta; bufferMeta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pBuffer, bufferHandle); CHECK_EQ(header->pAppPrivate, bufferMeta); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); CLOG_BUFFER(useGraphicBuffer2, NEW_BUFFER_FMT( *buffer, portIndex, "%u@%p", def.nBufferSize, bufferHandle)); return OK; } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119
status_t OMXNodeInstance::useGraphicBuffer2_l( OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer, OMX::buffer_id *buffer) { OMX_PARAM_PORTDEFINITIONTYPE def; InitOMXParams(&def); def.nPortIndex = portIndex; OMX_ERRORTYPE err = OMX_GetParameter(mHandle, OMX_IndexParamPortDefinition, &def); if (err != OMX_ErrorNone) { OMX_INDEXTYPE index = OMX_IndexParamPortDefinition; CLOG_ERROR(getParameter, err, "%s(%#x): %s:%u", asString(index), index, portString(portIndex), portIndex); return UNKNOWN_ERROR; } BufferMeta *bufferMeta = new BufferMeta(graphicBuffer, portIndex); OMX_BUFFERHEADERTYPE *header = NULL; OMX_U8* bufferHandle = const_cast<OMX_U8*>( reinterpret_cast<const OMX_U8*>(graphicBuffer->handle)); err = OMX_UseBuffer( mHandle, &header, portIndex, bufferMeta, def.nBufferSize, bufferHandle); if (err != OMX_ErrorNone) { CLOG_ERROR(useBuffer, err, BUFFER_FMT(portIndex, "%u@%p", def.nBufferSize, bufferHandle)); delete bufferMeta; bufferMeta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pBuffer, bufferHandle); CHECK_EQ(header->pAppPrivate, bufferMeta); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); CLOG_BUFFER(useGraphicBuffer2, NEW_BUFFER_FMT( *buffer, portIndex, "%u@%p", def.nBufferSize, bufferHandle)); return OK; }
173,535
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PageCaptureSaveAsMHTMLFunction::RunAsync() { params_ = SaveAsMHTML::Params::Create(*args_); EXTENSION_FUNCTION_VALIDATE(params_.get()); AddRef(); // Balanced in ReturnFailure/ReturnSuccess() #if defined(OS_CHROMEOS) if (profiles::ArePublicSessionRestrictionsEnabled()) { WebContents* web_contents = GetWebContents(); if (!web_contents) { ReturnFailure(kTabClosedError); return true; } auto callback = base::Bind(&PageCaptureSaveAsMHTMLFunction::ResolvePermissionRequest, base::Unretained(this)); permission_helper::HandlePermissionRequest( *extension(), {APIPermission::kPageCapture}, web_contents, callback, permission_helper::PromptFactory()); return true; } #endif base::PostTaskWithTraits( FROM_HERE, kCreateTemporaryFileTaskTraits, base::BindOnce(&PageCaptureSaveAsMHTMLFunction::CreateTemporaryFile, this)); return true; } Commit Message: Call CanCaptureVisiblePage in page capture API. Currently the pageCapture permission allows access to arbitrary local files and chrome:// pages which can be a security concern. In order to address this, the page capture API needs to be changed similar to the captureVisibleTab API. The API will now only allow extensions to capture otherwise-restricted URLs if the user has granted activeTab. In addition, file:// URLs are only capturable with the "Allow on file URLs" option enabled. Bug: 893087 Change-Id: I6d6225a3efb70fc033e2e1c031c633869afac624 Reviewed-on: https://chromium-review.googlesource.com/c/1330689 Commit-Queue: Bettina Dea <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Varun Khaneja <[email protected]> Cr-Commit-Position: refs/heads/master@{#615248} CWE ID: CWE-20
bool PageCaptureSaveAsMHTMLFunction::RunAsync() { params_ = SaveAsMHTML::Params::Create(*args_); EXTENSION_FUNCTION_VALIDATE(params_.get()); AddRef(); // Balanced in ReturnFailure/ReturnSuccess() #if defined(OS_CHROMEOS) if (profiles::ArePublicSessionRestrictionsEnabled()) { WebContents* web_contents = GetWebContents(); if (!web_contents) { ReturnFailure(kTabClosedError); return true; } auto callback = base::Bind(&PageCaptureSaveAsMHTMLFunction::ResolvePermissionRequest, base::Unretained(this)); permission_helper::HandlePermissionRequest( *extension(), {APIPermission::kPageCapture}, web_contents, callback, permission_helper::PromptFactory()); return true; } #endif if (!CanCaptureCurrentPage()) { return false; } base::PostTaskWithTraits( FROM_HERE, kCreateTemporaryFileTaskTraits, base::BindOnce(&PageCaptureSaveAsMHTMLFunction::CreateTemporaryFile, this)); return true; }
173,004
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: gss_init_sec_context (minor_status, claimant_cred_handle, context_handle, target_name, req_mech_type, req_flags, time_req, input_chan_bindings, input_token, actual_mech_type, output_token, ret_flags, time_rec) OM_uint32 * minor_status; gss_cred_id_t claimant_cred_handle; gss_ctx_id_t * context_handle; gss_name_t target_name; gss_OID req_mech_type; OM_uint32 req_flags; OM_uint32 time_req; gss_channel_bindings_t input_chan_bindings; gss_buffer_t input_token; gss_OID * actual_mech_type; gss_buffer_t output_token; OM_uint32 * ret_flags; OM_uint32 * time_rec; { OM_uint32 status, temp_minor_status; gss_union_name_t union_name; gss_union_cred_t union_cred; gss_name_t internal_name; gss_union_ctx_id_t union_ctx_id; gss_OID selected_mech; gss_mechanism mech; gss_cred_id_t input_cred_handle; status = val_init_sec_ctx_args(minor_status, claimant_cred_handle, context_handle, target_name, req_mech_type, req_flags, time_req, input_chan_bindings, input_token, actual_mech_type, output_token, ret_flags, time_rec); if (status != GSS_S_COMPLETE) return (status); status = gssint_select_mech_type(minor_status, req_mech_type, &selected_mech); if (status != GSS_S_COMPLETE) return (status); union_name = (gss_union_name_t)target_name; /* * obtain the gss mechanism information for the requested * mechanism. If mech_type is NULL, set it to the resultant * mechanism */ mech = gssint_get_mechanism(selected_mech); if (mech == NULL) return (GSS_S_BAD_MECH); if (mech->gss_init_sec_context == NULL) return (GSS_S_UNAVAILABLE); /* * If target_name is mechanism_specific, then it must match the * mech_type that we're about to use. Otherwise, do an import on * the external_name form of the target name. */ if (union_name->mech_type && g_OID_equal(union_name->mech_type, selected_mech)) { internal_name = union_name->mech_name; } else { if ((status = gssint_import_internal_name(minor_status, selected_mech, union_name, &internal_name)) != GSS_S_COMPLETE) return (status); } /* * if context_handle is GSS_C_NO_CONTEXT, allocate a union context * descriptor to hold the mech type information as well as the * underlying mechanism context handle. Otherwise, cast the * value of *context_handle to the union context variable. */ if(*context_handle == GSS_C_NO_CONTEXT) { status = GSS_S_FAILURE; union_ctx_id = (gss_union_ctx_id_t) malloc(sizeof(gss_union_ctx_id_desc)); if (union_ctx_id == NULL) goto end; if (generic_gss_copy_oid(&temp_minor_status, selected_mech, &union_ctx_id->mech_type) != GSS_S_COMPLETE) { free(union_ctx_id); goto end; } /* copy the supplied context handle */ union_ctx_id->internal_ctx_id = GSS_C_NO_CONTEXT; } else union_ctx_id = (gss_union_ctx_id_t)*context_handle; /* * get the appropriate cred handle from the union cred struct. * defaults to GSS_C_NO_CREDENTIAL if there is no cred, which will * use the default credential. */ union_cred = (gss_union_cred_t) claimant_cred_handle; input_cred_handle = gssint_get_mechanism_cred(union_cred, selected_mech); /* * now call the approprate underlying mechanism routine */ status = mech->gss_init_sec_context( minor_status, input_cred_handle, &union_ctx_id->internal_ctx_id, internal_name, gssint_get_public_oid(selected_mech), req_flags, time_req, input_chan_bindings, input_token, actual_mech_type, output_token, ret_flags, time_rec); if (status != GSS_S_COMPLETE && status != GSS_S_CONTINUE_NEEDED) { /* * The spec says the preferred method is to delete all context info on * the first call to init, and on all subsequent calls make the caller * responsible for calling gss_delete_sec_context. However, if the * mechanism decided to delete the internal context, we should also * delete the union context. */ map_error(minor_status, mech); if (union_ctx_id->internal_ctx_id == GSS_C_NO_CONTEXT) *context_handle = GSS_C_NO_CONTEXT; if (*context_handle == GSS_C_NO_CONTEXT) { free(union_ctx_id->mech_type->elements); free(union_ctx_id->mech_type); free(union_ctx_id); } } else if (*context_handle == GSS_C_NO_CONTEXT) { union_ctx_id->loopback = union_ctx_id; *context_handle = (gss_ctx_id_t)union_ctx_id; } end: if (union_name->mech_name == NULL || union_name->mech_name != internal_name) { (void) gssint_release_internal_name(&temp_minor_status, selected_mech, &internal_name); } return(status); } Commit Message: Preserve GSS context on init/accept failure After gss_init_sec_context() or gss_accept_sec_context() has created a context, don't delete the mechglue context on failures from subsequent calls, even if the mechanism deletes the mech-specific context (which is allowed by RFC 2744 but not preferred). Check for union contexts with no mechanism context in each GSS function which accepts a gss_ctx_id_t. CVE-2017-11462: RFC 2744 permits a GSS-API implementation to delete an existing security context on a second or subsequent call to gss_init_sec_context() or gss_accept_sec_context() if the call results in an error. This API behavior has been found to be dangerous, leading to the possibility of memory errors in some callers. For safety, GSS-API implementations should instead preserve existing security contexts on error until the caller deletes them. All versions of MIT krb5 prior to this change may delete acceptor contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through 1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on error. ticket: 8598 (new) target_version: 1.15-next target_version: 1.14-next tags: pullup CWE ID: CWE-415
gss_init_sec_context (minor_status, claimant_cred_handle, context_handle, target_name, req_mech_type, req_flags, time_req, input_chan_bindings, input_token, actual_mech_type, output_token, ret_flags, time_rec) OM_uint32 * minor_status; gss_cred_id_t claimant_cred_handle; gss_ctx_id_t * context_handle; gss_name_t target_name; gss_OID req_mech_type; OM_uint32 req_flags; OM_uint32 time_req; gss_channel_bindings_t input_chan_bindings; gss_buffer_t input_token; gss_OID * actual_mech_type; gss_buffer_t output_token; OM_uint32 * ret_flags; OM_uint32 * time_rec; { OM_uint32 status, temp_minor_status; gss_union_name_t union_name; gss_union_cred_t union_cred; gss_name_t internal_name; gss_union_ctx_id_t union_ctx_id; gss_OID selected_mech; gss_mechanism mech; gss_cred_id_t input_cred_handle; status = val_init_sec_ctx_args(minor_status, claimant_cred_handle, context_handle, target_name, req_mech_type, req_flags, time_req, input_chan_bindings, input_token, actual_mech_type, output_token, ret_flags, time_rec); if (status != GSS_S_COMPLETE) return (status); status = gssint_select_mech_type(minor_status, req_mech_type, &selected_mech); if (status != GSS_S_COMPLETE) return (status); union_name = (gss_union_name_t)target_name; /* * obtain the gss mechanism information for the requested * mechanism. If mech_type is NULL, set it to the resultant * mechanism */ mech = gssint_get_mechanism(selected_mech); if (mech == NULL) return (GSS_S_BAD_MECH); if (mech->gss_init_sec_context == NULL) return (GSS_S_UNAVAILABLE); /* * If target_name is mechanism_specific, then it must match the * mech_type that we're about to use. Otherwise, do an import on * the external_name form of the target name. */ if (union_name->mech_type && g_OID_equal(union_name->mech_type, selected_mech)) { internal_name = union_name->mech_name; } else { if ((status = gssint_import_internal_name(minor_status, selected_mech, union_name, &internal_name)) != GSS_S_COMPLETE) return (status); } /* * if context_handle is GSS_C_NO_CONTEXT, allocate a union context * descriptor to hold the mech type information as well as the * underlying mechanism context handle. Otherwise, cast the * value of *context_handle to the union context variable. */ if(*context_handle == GSS_C_NO_CONTEXT) { status = GSS_S_FAILURE; union_ctx_id = (gss_union_ctx_id_t) malloc(sizeof(gss_union_ctx_id_desc)); if (union_ctx_id == NULL) goto end; if (generic_gss_copy_oid(&temp_minor_status, selected_mech, &union_ctx_id->mech_type) != GSS_S_COMPLETE) { free(union_ctx_id); goto end; } /* copy the supplied context handle */ union_ctx_id->internal_ctx_id = GSS_C_NO_CONTEXT; } else { union_ctx_id = (gss_union_ctx_id_t)*context_handle; if (union_ctx_id->internal_ctx_id == GSS_C_NO_CONTEXT) { status = GSS_S_NO_CONTEXT; goto end; } } /* * get the appropriate cred handle from the union cred struct. * defaults to GSS_C_NO_CREDENTIAL if there is no cred, which will * use the default credential. */ union_cred = (gss_union_cred_t) claimant_cred_handle; input_cred_handle = gssint_get_mechanism_cred(union_cred, selected_mech); /* * now call the approprate underlying mechanism routine */ status = mech->gss_init_sec_context( minor_status, input_cred_handle, &union_ctx_id->internal_ctx_id, internal_name, gssint_get_public_oid(selected_mech), req_flags, time_req, input_chan_bindings, input_token, actual_mech_type, output_token, ret_flags, time_rec); if (status != GSS_S_COMPLETE && status != GSS_S_CONTINUE_NEEDED) { /* * RFC 2744 5.19 requires that we not create a context on a failed * first call to init, and recommends that on a failed subsequent call * we make the caller responsible for calling gss_delete_sec_context. * Even if the mech deleted its context, keep the union context around * for the caller to delete. */ map_error(minor_status, mech); if (*context_handle == GSS_C_NO_CONTEXT) { free(union_ctx_id->mech_type->elements); free(union_ctx_id->mech_type); free(union_ctx_id); } } else if (*context_handle == GSS_C_NO_CONTEXT) { union_ctx_id->loopback = union_ctx_id; *context_handle = (gss_ctx_id_t)union_ctx_id; } end: if (union_name->mech_name == NULL || union_name->mech_name != internal_name) { (void) gssint_release_internal_name(&temp_minor_status, selected_mech, &internal_name); } return(status); }
168,016
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: UrlData::UrlData(const GURL& url, CORSMode cors_mode, UrlIndex* url_index) : url_(url), have_data_origin_(false), cors_mode_(cors_mode), url_index_(url_index), length_(kPositionNotSpecified), range_supported_(false), cacheable_(false), has_opaque_data_(false), last_used_(), multibuffer_(this, url_index_->block_shift_) {} Commit Message: Simplify "WouldTaintOrigin" concept in media/blink Currently WebMediaPlayer has three predicates: - DidGetOpaqueResponseFromServiceWorker - HasSingleSecurityOrigin - DidPassCORSAccessCheck . These are used to determine whether the response body is available for scripts. They are known to be confusing, and actually MediaElementAudioSourceHandler::WouldTaintOrigin misuses them. This CL merges the three predicates to one, WouldTaintOrigin, to remove the confusion. Now the "response type" concept is available and we don't need a custom CORS check, so this CL removes BaseAudioContext::WouldTaintOrigin. This CL also renames URLData::has_opaque_data_ and its (direct and indirect) data accessors to match the spec. Bug: 849942, 875153 Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a Reviewed-on: https://chromium-review.googlesource.com/c/1238098 Reviewed-by: Fredrik Hubinette <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Reviewed-by: Raymond Toy <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#598258} CWE ID: CWE-732
UrlData::UrlData(const GURL& url, CORSMode cors_mode, UrlIndex* url_index) : url_(url), have_data_origin_(false), cors_mode_(cors_mode), url_index_(url_index), length_(kPositionNotSpecified), range_supported_(false), cacheable_(false), last_used_(), multibuffer_(this, url_index_->block_shift_) {}
172,628
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void perf_callchain_user_64(struct perf_callchain_entry *entry, struct pt_regs *regs) { unsigned long sp, next_sp; unsigned long next_ip; unsigned long lr; long level = 0; struct signal_frame_64 __user *sigframe; unsigned long __user *fp, *uregs; next_ip = perf_instruction_pointer(regs); lr = regs->link; sp = regs->gpr[1]; perf_callchain_store(entry, next_ip); for (;;) { fp = (unsigned long __user *) sp; if (!valid_user_sp(sp, 1) || read_user_stack_64(fp, &next_sp)) return; if (level > 0 && read_user_stack_64(&fp[2], &next_ip)) return; /* * Note: the next_sp - sp >= signal frame size check * is true when next_sp < sp, which can happen when * transitioning from an alternate signal stack to the * normal stack. */ if (next_sp - sp >= sizeof(struct signal_frame_64) && (is_sigreturn_64_address(next_ip, sp) || (level <= 1 && is_sigreturn_64_address(lr, sp))) && sane_signal_64_frame(sp)) { /* * This looks like an signal frame */ sigframe = (struct signal_frame_64 __user *) sp; uregs = sigframe->uc.uc_mcontext.gp_regs; if (read_user_stack_64(&uregs[PT_NIP], &next_ip) || read_user_stack_64(&uregs[PT_LNK], &lr) || read_user_stack_64(&uregs[PT_R1], &sp)) return; level = 0; perf_callchain_store(entry, PERF_CONTEXT_USER); perf_callchain_store(entry, next_ip); continue; } if (level == 0) next_ip = lr; perf_callchain_store(entry, next_ip); ++level; sp = next_sp; } } Commit Message: powerpc/perf: Cap 64bit userspace backtraces to PERF_MAX_STACK_DEPTH We cap 32bit userspace backtraces to PERF_MAX_STACK_DEPTH (currently 127), but we forgot to do the same for 64bit backtraces. Cc: [email protected] Signed-off-by: Anton Blanchard <[email protected]> Signed-off-by: Michael Ellerman <[email protected]> CWE ID: CWE-399
static void perf_callchain_user_64(struct perf_callchain_entry *entry, struct pt_regs *regs) { unsigned long sp, next_sp; unsigned long next_ip; unsigned long lr; long level = 0; struct signal_frame_64 __user *sigframe; unsigned long __user *fp, *uregs; next_ip = perf_instruction_pointer(regs); lr = regs->link; sp = regs->gpr[1]; perf_callchain_store(entry, next_ip); while (entry->nr < PERF_MAX_STACK_DEPTH) { fp = (unsigned long __user *) sp; if (!valid_user_sp(sp, 1) || read_user_stack_64(fp, &next_sp)) return; if (level > 0 && read_user_stack_64(&fp[2], &next_ip)) return; /* * Note: the next_sp - sp >= signal frame size check * is true when next_sp < sp, which can happen when * transitioning from an alternate signal stack to the * normal stack. */ if (next_sp - sp >= sizeof(struct signal_frame_64) && (is_sigreturn_64_address(next_ip, sp) || (level <= 1 && is_sigreturn_64_address(lr, sp))) && sane_signal_64_frame(sp)) { /* * This looks like an signal frame */ sigframe = (struct signal_frame_64 __user *) sp; uregs = sigframe->uc.uc_mcontext.gp_regs; if (read_user_stack_64(&uregs[PT_NIP], &next_ip) || read_user_stack_64(&uregs[PT_LNK], &lr) || read_user_stack_64(&uregs[PT_R1], &sp)) return; level = 0; perf_callchain_store(entry, PERF_CONTEXT_USER); perf_callchain_store(entry, next_ip); continue; } if (level == 0) next_ip = lr; perf_callchain_store(entry, next_ip); ++level; sp = next_sp; } }
166,587
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: build_unc_path_to_root(const struct smb_vol *vol, const struct cifs_sb_info *cifs_sb) { char *full_path, *pos; unsigned int pplen = vol->prepath ? strlen(vol->prepath) + 1 : 0; unsigned int unc_len = strnlen(vol->UNC, MAX_TREE_SIZE + 1); full_path = kmalloc(unc_len + pplen + 1, GFP_KERNEL); if (full_path == NULL) return ERR_PTR(-ENOMEM); strncpy(full_path, vol->UNC, unc_len); pos = full_path + unc_len; if (pplen) { *pos++ = CIFS_DIR_SEP(cifs_sb); strncpy(pos, vol->prepath, pplen); pos += pplen; } *pos = '\0'; /* add trailing null */ convert_delimiter(full_path, CIFS_DIR_SEP(cifs_sb)); cifs_dbg(FYI, "%s: full_path=%s\n", __func__, full_path); return full_path; } Commit Message: cifs: fix off-by-one bug in build_unc_path_to_root commit 839db3d10a (cifs: fix up handling of prefixpath= option) changed the code such that the vol->prepath no longer contained a leading delimiter and then fixed up the places that accessed that field to account for that change. One spot in build_unc_path_to_root was missed however. When doing the pointer addition on pos, that patch failed to account for the fact that we had already incremented "pos" by one when adding the length of the prepath. This caused a buffer overrun by one byte. This patch fixes the problem by correcting the handling of "pos". Cc: <[email protected]> # v3.8+ Reported-by: Marcus Moeller <[email protected]> Reported-by: Ken Fallon <[email protected]> Signed-off-by: Jeff Layton <[email protected]> Signed-off-by: Steve French <[email protected]> CWE ID: CWE-189
build_unc_path_to_root(const struct smb_vol *vol, const struct cifs_sb_info *cifs_sb) { char *full_path, *pos; unsigned int pplen = vol->prepath ? strlen(vol->prepath) + 1 : 0; unsigned int unc_len = strnlen(vol->UNC, MAX_TREE_SIZE + 1); full_path = kmalloc(unc_len + pplen + 1, GFP_KERNEL); if (full_path == NULL) return ERR_PTR(-ENOMEM); strncpy(full_path, vol->UNC, unc_len); pos = full_path + unc_len; if (pplen) { *pos = CIFS_DIR_SEP(cifs_sb); strncpy(pos + 1, vol->prepath, pplen); pos += pplen; } *pos = '\0'; /* add trailing null */ convert_delimiter(full_path, CIFS_DIR_SEP(cifs_sb)); cifs_dbg(FYI, "%s: full_path=%s\n", __func__, full_path); return full_path; }
166,010
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: NTSTATUS check_reduced_name_with_privilege(connection_struct *conn, const char *fname, struct smb_request *smbreq) { NTSTATUS status; TALLOC_CTX *ctx = talloc_tos(); const char *conn_rootdir; size_t rootdir_len; char *dir_name = NULL; const char *last_component = NULL; char *resolved_name = NULL; char *saved_dir = NULL; struct smb_filename *smb_fname_cwd = NULL; struct privilege_paths *priv_paths = NULL; int ret; DEBUG(3,("check_reduced_name_with_privilege [%s] [%s]\n", fname, priv_paths = talloc_zero(smbreq, struct privilege_paths); if (!priv_paths) { status = NT_STATUS_NO_MEMORY; goto err; } if (!parent_dirname(ctx, fname, &dir_name, &last_component)) { status = NT_STATUS_NO_MEMORY; goto err; } priv_paths->parent_name.base_name = talloc_strdup(priv_paths, dir_name); priv_paths->file_name.base_name = talloc_strdup(priv_paths, last_component); if (priv_paths->parent_name.base_name == NULL || priv_paths->file_name.base_name == NULL) { status = NT_STATUS_NO_MEMORY; goto err; } if (SMB_VFS_STAT(conn, &priv_paths->parent_name) != 0) { status = map_nt_error_from_unix(errno); goto err; } /* Remember where we were. */ saved_dir = vfs_GetWd(ctx, conn); if (!saved_dir) { status = map_nt_error_from_unix(errno); goto err; } /* Go to the parent directory to lock in memory. */ if (vfs_ChDir(conn, priv_paths->parent_name.base_name) == -1) { status = map_nt_error_from_unix(errno); goto err; } /* Get the absolute path of the parent directory. */ resolved_name = SMB_VFS_REALPATH(conn,"."); if (!resolved_name) { status = map_nt_error_from_unix(errno); goto err; } if (*resolved_name != '/') { DEBUG(0,("check_reduced_name_with_privilege: realpath " "doesn't return absolute paths !\n")); status = NT_STATUS_OBJECT_NAME_INVALID; goto err; } DEBUG(10,("check_reduced_name_with_privilege: realpath [%s] -> [%s]\n", priv_paths->parent_name.base_name, resolved_name)); /* Now check the stat value is the same. */ smb_fname_cwd = synthetic_smb_fname(talloc_tos(), ".", NULL, NULL); if (smb_fname_cwd == NULL) { status = NT_STATUS_NO_MEMORY; goto err; } if (SMB_VFS_LSTAT(conn, smb_fname_cwd) != 0) { status = map_nt_error_from_unix(errno); goto err; } /* Ensure we're pointing at the same place. */ if (!check_same_stat(&smb_fname_cwd->st, &priv_paths->parent_name.st)) { DEBUG(0,("check_reduced_name_with_privilege: " "device/inode/uid/gid on directory %s changed. " "Denying access !\n", priv_paths->parent_name.base_name)); status = NT_STATUS_ACCESS_DENIED; goto err; } /* Ensure we're below the connect path. */ conn_rootdir = SMB_VFS_CONNECTPATH(conn, fname); if (conn_rootdir == NULL) { DEBUG(2, ("check_reduced_name_with_privilege: Could not get " "conn_rootdir\n")); status = NT_STATUS_ACCESS_DENIED; goto err; } } Commit Message: CWE ID: CWE-264
NTSTATUS check_reduced_name_with_privilege(connection_struct *conn, const char *fname, struct smb_request *smbreq) { NTSTATUS status; TALLOC_CTX *ctx = talloc_tos(); const char *conn_rootdir; size_t rootdir_len; char *dir_name = NULL; const char *last_component = NULL; char *resolved_name = NULL; char *saved_dir = NULL; struct smb_filename *smb_fname_cwd = NULL; struct privilege_paths *priv_paths = NULL; int ret; bool matched; DEBUG(3,("check_reduced_name_with_privilege [%s] [%s]\n", fname, priv_paths = talloc_zero(smbreq, struct privilege_paths); if (!priv_paths) { status = NT_STATUS_NO_MEMORY; goto err; } if (!parent_dirname(ctx, fname, &dir_name, &last_component)) { status = NT_STATUS_NO_MEMORY; goto err; } priv_paths->parent_name.base_name = talloc_strdup(priv_paths, dir_name); priv_paths->file_name.base_name = talloc_strdup(priv_paths, last_component); if (priv_paths->parent_name.base_name == NULL || priv_paths->file_name.base_name == NULL) { status = NT_STATUS_NO_MEMORY; goto err; } if (SMB_VFS_STAT(conn, &priv_paths->parent_name) != 0) { status = map_nt_error_from_unix(errno); goto err; } /* Remember where we were. */ saved_dir = vfs_GetWd(ctx, conn); if (!saved_dir) { status = map_nt_error_from_unix(errno); goto err; } /* Go to the parent directory to lock in memory. */ if (vfs_ChDir(conn, priv_paths->parent_name.base_name) == -1) { status = map_nt_error_from_unix(errno); goto err; } /* Get the absolute path of the parent directory. */ resolved_name = SMB_VFS_REALPATH(conn,"."); if (!resolved_name) { status = map_nt_error_from_unix(errno); goto err; } if (*resolved_name != '/') { DEBUG(0,("check_reduced_name_with_privilege: realpath " "doesn't return absolute paths !\n")); status = NT_STATUS_OBJECT_NAME_INVALID; goto err; } DEBUG(10,("check_reduced_name_with_privilege: realpath [%s] -> [%s]\n", priv_paths->parent_name.base_name, resolved_name)); /* Now check the stat value is the same. */ smb_fname_cwd = synthetic_smb_fname(talloc_tos(), ".", NULL, NULL); if (smb_fname_cwd == NULL) { status = NT_STATUS_NO_MEMORY; goto err; } if (SMB_VFS_LSTAT(conn, smb_fname_cwd) != 0) { status = map_nt_error_from_unix(errno); goto err; } /* Ensure we're pointing at the same place. */ if (!check_same_stat(&smb_fname_cwd->st, &priv_paths->parent_name.st)) { DEBUG(0,("check_reduced_name_with_privilege: " "device/inode/uid/gid on directory %s changed. " "Denying access !\n", priv_paths->parent_name.base_name)); status = NT_STATUS_ACCESS_DENIED; goto err; } /* Ensure we're below the connect path. */ conn_rootdir = SMB_VFS_CONNECTPATH(conn, fname); if (conn_rootdir == NULL) { DEBUG(2, ("check_reduced_name_with_privilege: Could not get " "conn_rootdir\n")); status = NT_STATUS_ACCESS_DENIED; goto err; } }
164,683
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void sas_eh_finish_cmd(struct scsi_cmnd *cmd) { struct sas_ha_struct *sas_ha = SHOST_TO_SAS_HA(cmd->device->host); struct sas_task *task = TO_SAS_TASK(cmd); /* At this point, we only get called following an actual abort * of the task, so we should be guaranteed not to be racing with * any completions from the LLD. Task is freed after this. */ sas_end_task(cmd, task); /* now finish the command and move it on to the error * handler done list, this also takes it off the * error handler pending list. */ scsi_eh_finish_cmd(cmd, &sas_ha->eh_done_q); } Commit Message: scsi: libsas: defer ata device eh commands to libata When ata device doing EH, some commands still attached with tasks are not passed to libata when abort failed or recover failed, so libata did not handle these commands. After these commands done, sas task is freed, but ata qc is not freed. This will cause ata qc leak and trigger a warning like below: WARNING: CPU: 0 PID: 28512 at drivers/ata/libata-eh.c:4037 ata_eh_finish+0xb4/0xcc CPU: 0 PID: 28512 Comm: kworker/u32:2 Tainted: G W OE 4.14.0#1 ...... Call trace: [<ffff0000088b7bd0>] ata_eh_finish+0xb4/0xcc [<ffff0000088b8420>] ata_do_eh+0xc4/0xd8 [<ffff0000088b8478>] ata_std_error_handler+0x44/0x8c [<ffff0000088b8068>] ata_scsi_port_error_handler+0x480/0x694 [<ffff000008875fc4>] async_sas_ata_eh+0x4c/0x80 [<ffff0000080f6be8>] async_run_entry_fn+0x4c/0x170 [<ffff0000080ebd70>] process_one_work+0x144/0x390 [<ffff0000080ec100>] worker_thread+0x144/0x418 [<ffff0000080f2c98>] kthread+0x10c/0x138 [<ffff0000080855dc>] ret_from_fork+0x10/0x18 If ata qc leaked too many, ata tag allocation will fail and io blocked for ever. As suggested by Dan Williams, defer ata device commands to libata and merge sas_eh_finish_cmd() with sas_eh_defer_cmd(). libata will handle ata qcs correctly after this. Signed-off-by: Jason Yan <[email protected]> CC: Xiaofei Tan <[email protected]> CC: John Garry <[email protected]> CC: Dan Williams <[email protected]> Reviewed-by: Dan Williams <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID:
static void sas_eh_finish_cmd(struct scsi_cmnd *cmd) { struct sas_ha_struct *sas_ha = SHOST_TO_SAS_HA(cmd->device->host); struct domain_device *dev = cmd_to_domain_dev(cmd); struct sas_task *task = TO_SAS_TASK(cmd); /* At this point, we only get called following an actual abort * of the task, so we should be guaranteed not to be racing with * any completions from the LLD. Task is freed after this. */ sas_end_task(cmd, task); if (dev_is_sata(dev)) { /* defer commands to libata so that libata EH can * handle ata qcs correctly */ list_move_tail(&cmd->eh_entry, &sas_ha->eh_ata_q); return; } /* now finish the command and move it on to the error * handler done list, this also takes it off the * error handler pending list. */ scsi_eh_finish_cmd(cmd, &sas_ha->eh_done_q); }
169,261
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void snd_timer_check_master(struct snd_timer_instance *master) { struct snd_timer_instance *slave, *tmp; /* check all pending slaves */ list_for_each_entry_safe(slave, tmp, &snd_timer_slave_list, open_list) { if (slave->slave_class == master->slave_class && slave->slave_id == master->slave_id) { list_move_tail(&slave->open_list, &master->slave_list_head); spin_lock_irq(&slave_active_lock); slave->master = master; slave->timer = master->timer; if (slave->flags & SNDRV_TIMER_IFLG_RUNNING) list_add_tail(&slave->active_list, &master->slave_active_head); spin_unlock_irq(&slave_active_lock); } } } Commit Message: ALSA: timer: Harden slave timer list handling A slave timer instance might be still accessible in a racy way while operating the master instance as it lacks of locking. Since the master operation is mostly protected with timer->lock, we should cope with it while changing the slave instance, too. Also, some linked lists (active_list and ack_list) of slave instances aren't unlinked immediately at stopping or closing, and this may lead to unexpected accesses. This patch tries to address these issues. It adds spin lock of timer->lock (either from master or slave, which is equivalent) in a few places. For avoiding a deadlock, we ensure that the global slave_active_lock is always locked at first before each timer lock. Also, ack and active_list of slave instances are properly unlinked at snd_timer_stop() and snd_timer_close(). Last but not least, remove the superfluous call of _snd_timer_stop() at removing slave links. This is a noop, and calling it may confuse readers wrt locking. Further cleanup will follow in a later patch. Actually we've got reports of use-after-free by syzkaller fuzzer, and this hopefully fixes these issues. Reported-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-20
static void snd_timer_check_master(struct snd_timer_instance *master) { struct snd_timer_instance *slave, *tmp; /* check all pending slaves */ list_for_each_entry_safe(slave, tmp, &snd_timer_slave_list, open_list) { if (slave->slave_class == master->slave_class && slave->slave_id == master->slave_id) { list_move_tail(&slave->open_list, &master->slave_list_head); spin_lock_irq(&slave_active_lock); spin_lock(&master->timer->lock); slave->master = master; slave->timer = master->timer; if (slave->flags & SNDRV_TIMER_IFLG_RUNNING) list_add_tail(&slave->active_list, &master->slave_active_head); spin_unlock(&master->timer->lock); spin_unlock_irq(&slave_active_lock); } } }
167,401
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: XRRGetMonitors(Display *dpy, Window window, Bool get_active, int *nmonitors) { XExtDisplayInfo *info = XRRFindDisplay(dpy); xRRGetMonitorsReply rep; xRRGetMonitorsReq *req; int nbytes, nbytesRead, rbytes; int nmon, noutput; int m, o; char *buf, *buf_head; xRRMonitorInfo *xmon; CARD32 *xoutput; XRRMonitorInfo *mon = NULL; RROutput *output; RRCheckExtension (dpy, info, NULL); *nmonitors = -1; LockDisplay (dpy); GetReq (RRGetMonitors, req); req->reqType = info->codes->major_opcode; req->randrReqType = X_RRGetMonitors; req->window = window; req->get_active = get_active; if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) { UnlockDisplay (dpy); SyncHandle (); return NULL; return NULL; } nbytes = (long) rep.length << 2; nmon = rep.nmonitors; noutput = rep.noutputs; rbytes = nmon * sizeof (XRRMonitorInfo) + noutput * sizeof(RROutput); buf = buf_head = Xmalloc (nbytesRead); mon = Xmalloc (rbytes); if (buf == NULL || mon == NULL) { Xfree(buf); Xfree(mon); _XEatDataWords (dpy, rep.length); UnlockDisplay (dpy); SyncHandle (); return NULL; } _XReadPad(dpy, buf, nbytesRead); output = (RROutput *) (mon + nmon); for (m = 0; m < nmon; m++) { xmon = (xRRMonitorInfo *) buf; mon[m].name = xmon->name; mon[m].primary = xmon->primary; mon[m].automatic = xmon->automatic; mon[m].noutput = xmon->noutput; mon[m].x = xmon->x; mon[m].y = xmon->y; mon[m].width = xmon->width; mon[m].height = xmon->height; mon[m].mwidth = xmon->widthInMillimeters; mon[m].mheight = xmon->heightInMillimeters; mon[m].outputs = output; buf += SIZEOF (xRRMonitorInfo); xoutput = (CARD32 *) buf; for (o = 0; o < xmon->noutput; o++) output[o] = xoutput[o]; output += xmon->noutput; buf += xmon->noutput * 4; } Xfree(buf_head); } Commit Message: CWE ID: CWE-787
XRRGetMonitors(Display *dpy, Window window, Bool get_active, int *nmonitors) { XExtDisplayInfo *info = XRRFindDisplay(dpy); xRRGetMonitorsReply rep; xRRGetMonitorsReq *req; int nbytes, nbytesRead, rbytes; int nmon, noutput; int m, o; char *buf, *buf_head; xRRMonitorInfo *xmon; CARD32 *xoutput; XRRMonitorInfo *mon = NULL; RROutput *output; RRCheckExtension (dpy, info, NULL); *nmonitors = -1; LockDisplay (dpy); GetReq (RRGetMonitors, req); req->reqType = info->codes->major_opcode; req->randrReqType = X_RRGetMonitors; req->window = window; req->get_active = get_active; if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) { UnlockDisplay (dpy); SyncHandle (); return NULL; return NULL; } if (rep.length > INT_MAX >> 2 || rep.nmonitors > INT_MAX / SIZEOF(xRRMonitorInfo) || rep.noutputs > INT_MAX / 4 || rep.nmonitors * SIZEOF(xRRMonitorInfo) > INT_MAX - rep.noutputs * 4) { _XEatData (dpy, rep.length); UnlockDisplay (dpy); SyncHandle (); return NULL; } nbytes = (long) rep.length << 2; nmon = rep.nmonitors; noutput = rep.noutputs; rbytes = nmon * sizeof (XRRMonitorInfo) + noutput * sizeof(RROutput); buf = buf_head = Xmalloc (nbytesRead); mon = Xmalloc (rbytes); if (buf == NULL || mon == NULL) { Xfree(buf); Xfree(mon); _XEatDataWords (dpy, rep.length); UnlockDisplay (dpy); SyncHandle (); return NULL; } _XReadPad(dpy, buf, nbytesRead); output = (RROutput *) (mon + nmon); for (m = 0; m < nmon; m++) { xmon = (xRRMonitorInfo *) buf; mon[m].name = xmon->name; mon[m].primary = xmon->primary; mon[m].automatic = xmon->automatic; mon[m].noutput = xmon->noutput; mon[m].x = xmon->x; mon[m].y = xmon->y; mon[m].width = xmon->width; mon[m].height = xmon->height; mon[m].mwidth = xmon->widthInMillimeters; mon[m].mheight = xmon->heightInMillimeters; mon[m].outputs = output; buf += SIZEOF (xRRMonitorInfo); xoutput = (CARD32 *) buf; for (o = 0; o < xmon->noutput; o++) output[o] = xoutput[o]; output += xmon->noutput; buf += xmon->noutput * 4; } Xfree(buf_head); }
164,914
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WebGL2RenderingContextBase::texImage3D( GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, MaybeShared<DOMArrayBufferView> pixels, GLuint src_offset) { if (isContextLost()) return; if (bound_pixel_unpack_buffer_) { SynthesizeGLError(GL_INVALID_OPERATION, "texImage3D", "a buffer is bound to PIXEL_UNPACK_BUFFER"); return; } TexImageHelperDOMArrayBufferView( kTexImage3D, target, level, internalformat, width, height, depth, border, format, type, 0, 0, 0, pixels.View(), kNullNotReachable, src_offset); } Commit Message: Implement 2D texture uploading from client array with FLIP_Y or PREMULTIPLY_ALPHA. BUG=774174 TEST=https://github.com/KhronosGroup/WebGL/pull/2555 [email protected] Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2;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: I4f4e7636314502451104730501a5048a5d7b9f3f Reviewed-on: https://chromium-review.googlesource.com/808665 Commit-Queue: Zhenyao Mo <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#522003} CWE ID: CWE-125
void WebGL2RenderingContextBase::texImage3D( GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, MaybeShared<DOMArrayBufferView> pixels, GLuint src_offset) { if (isContextLost()) return; if (bound_pixel_unpack_buffer_) { SynthesizeGLError(GL_INVALID_OPERATION, "texImage3D", "a buffer is bound to PIXEL_UNPACK_BUFFER"); return; } if (unpack_flip_y_ || unpack_premultiply_alpha_) { DCHECK(pixels); SynthesizeGLError( GL_INVALID_OPERATION, "texImage3D", "FLIP_Y or PREMULTIPLY_ALPHA isn't allowed for uploading 3D textures"); return; } TexImageHelperDOMArrayBufferView( kTexImage3D, target, level, internalformat, width, height, depth, border, format, type, 0, 0, 0, pixels.View(), kNullNotReachable, src_offset); }
172,676
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long VideoTrack::Parse(Segment* pSegment, const Info& info, long long element_start, long long element_size, VideoTrack*& pResult) { if (pResult) return -1; if (info.type != Track::kVideo) return -1; long long width = 0; long long height = 0; double rate = 0.0; IMkvReader* const pReader = pSegment->m_pReader; const Settings& s = info.settings; assert(s.start >= 0); assert(s.size >= 0); long long pos = s.start; assert(pos >= 0); const long long stop = pos + s.size; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x30) { // pixel width width = UnserializeUInt(pReader, pos, size); if (width <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x3A) { // pixel height height = UnserializeUInt(pReader, pos, size); if (height <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0383E3) { // frame rate const long status = UnserializeFloat(pReader, pos, size, rate); if (status < 0) return status; if (rate <= 0) return E_FILE_FORMAT_INVALID; } pos += size; // consume payload assert(pos <= stop); } assert(pos == stop); VideoTrack* const pTrack = new (std::nothrow) VideoTrack(pSegment, element_start, element_size); if (pTrack == NULL) return -1; // generic error const int status = info.Copy(pTrack->m_info); if (status) { // error delete pTrack; return status; } pTrack->m_width = width; pTrack->m_height = height; pTrack->m_rate = rate; pResult = pTrack; return 0; // success } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long VideoTrack::Parse(Segment* pSegment, const Info& info, long long element_start, long long element_size, VideoTrack*& pResult) { if (pResult) return -1; if (info.type != Track::kVideo) return -1; long long width = 0; long long height = 0; long long display_width = 0; long long display_height = 0; long long display_unit = 0; long long stereo_mode = 0; double rate = 0.0; IMkvReader* const pReader = pSegment->m_pReader; const Settings& s = info.settings; assert(s.start >= 0); assert(s.size >= 0); long long pos = s.start; assert(pos >= 0); const long long stop = pos + s.size; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x30) { // pixel width width = UnserializeUInt(pReader, pos, size); if (width <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x3A) { // pixel height height = UnserializeUInt(pReader, pos, size); if (height <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x14B0) { // display width display_width = UnserializeUInt(pReader, pos, size); if (display_width <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x14BA) { // display height display_height = UnserializeUInt(pReader, pos, size); if (display_height <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x14B2) { // display unit display_unit = UnserializeUInt(pReader, pos, size); if (display_unit < 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x13B8) { // stereo mode stereo_mode = UnserializeUInt(pReader, pos, size); if (stereo_mode < 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0383E3) { // frame rate const long status = UnserializeFloat(pReader, pos, size, rate); if (status < 0) return status; if (rate <= 0) return E_FILE_FORMAT_INVALID; } pos += size; // consume payload if (pos > stop) return E_FILE_FORMAT_INVALID; } if (pos != stop) return E_FILE_FORMAT_INVALID; VideoTrack* const pTrack = new (std::nothrow) VideoTrack(pSegment, element_start, element_size); if (pTrack == NULL) return -1; // generic error const int status = info.Copy(pTrack->m_info); if (status) { // error delete pTrack; return status; } pTrack->m_width = width; pTrack->m_height = height; pTrack->m_display_width = display_width; pTrack->m_display_height = display_height; pTrack->m_display_unit = display_unit; pTrack->m_stereo_mode = stereo_mode; pTrack->m_rate = rate; pResult = pTrack; return 0; // success }
173,843
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ChromeWebUIControllerFactory::HasWebUIScheme(const GURL& url) const { return url.SchemeIs(chrome::kChromeDevToolsScheme) || url.SchemeIs(chrome::kChromeInternalScheme) || url.SchemeIs(chrome::kChromeUIScheme); } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool ChromeWebUIControllerFactory::HasWebUIScheme(const GURL& url) const {
171,008
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::OutputPicture( const scoped_refptr<VP8Picture>& pic) { scoped_refptr<VaapiDecodeSurface> dec_surface = VP8PictureToVaapiDecodeSurface(pic); dec_surface->set_visible_rect(pic->visible_rect); vaapi_dec_->SurfaceReady(dec_surface); return true; } Commit Message: vaapi vda: Delete owned objects on worker thread in Cleanup() This CL adds a SEQUENCE_CHECKER to Vaapi*Accelerator classes, and posts the destruction of those objects to the appropriate thread on Cleanup(). Also makes {H264,VP8,VP9}Picture RefCountedThreadSafe, see miu@ comment in https://chromium-review.googlesource.com/c/chromium/src/+/794091#message-a64bed985cfaf8a19499a517bb110a7ce581dc0f TEST=play back VP9/VP8/H264 w/ simplechrome on soraka, Release build unstripped, let video play for a few seconds then navigate back; no crashes. Unittests as before: video_decode_accelerator_unittest --test_video_data=test-25fps.vp9:320:240:250:250:35:150:12 video_decode_accelerator_unittest --test_video_data=test-25fps.vp8:320:240:250:250:35:150:11 video_decode_accelerator_unittest --test_video_data=test-25fps.h264:320:240:250:258:35:150:1 Bug: 789160 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: I7d96aaf89c92bf46f00c8b8b36798e057a842ed2 Reviewed-on: https://chromium-review.googlesource.com/794091 Reviewed-by: Pawel Osciak <[email protected]> Commit-Queue: Miguel Casas <[email protected]> Cr-Commit-Position: refs/heads/master@{#523372} CWE ID: CWE-362
bool VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::OutputPicture( const scoped_refptr<VP8Picture>& pic) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); scoped_refptr<VaapiDecodeSurface> dec_surface = VP8PictureToVaapiDecodeSurface(pic); dec_surface->set_visible_rect(pic->visible_rect); vaapi_dec_->SurfaceReady(dec_surface); return true; }
172,805
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool asn1_write_LDAPString(struct asn1_data *data, const char *s) { asn1_write(data, s, strlen(s)); return !data->has_error; } Commit Message: CWE ID: CWE-399
bool asn1_write_LDAPString(struct asn1_data *data, const char *s) { return asn1_write(data, s, strlen(s)); }
164,590
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void umount_tree(struct mount *mnt, enum umount_tree_flags how) { LIST_HEAD(tmp_list); struct mount *p; if (how & UMOUNT_PROPAGATE) propagate_mount_unlock(mnt); /* Gather the mounts to umount */ for (p = mnt; p; p = next_mnt(p, mnt)) { p->mnt.mnt_flags |= MNT_UMOUNT; list_move(&p->mnt_list, &tmp_list); } /* Hide the mounts from mnt_mounts */ list_for_each_entry(p, &tmp_list, mnt_list) { list_del_init(&p->mnt_child); } /* Add propogated mounts to the tmp_list */ if (how & UMOUNT_PROPAGATE) propagate_umount(&tmp_list); while (!list_empty(&tmp_list)) { bool disconnect; p = list_first_entry(&tmp_list, struct mount, mnt_list); list_del_init(&p->mnt_expire); list_del_init(&p->mnt_list); __touch_mnt_namespace(p->mnt_ns); p->mnt_ns = NULL; if (how & UMOUNT_SYNC) p->mnt.mnt_flags |= MNT_SYNC_UMOUNT; disconnect = !IS_MNT_LOCKED_AND_LAZY(p); pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt, disconnect ? &unmounted : NULL); if (mnt_has_parent(p)) { mnt_add_count(p->mnt_parent, -1); if (!disconnect) { /* Don't forget about p */ list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts); } else { umount_mnt(p); } } change_mnt_propagation(p, MS_PRIVATE); } } Commit Message: mnt: Update detach_mounts to leave mounts connected Now that it is possible to lazily unmount an entire mount tree and leave the individual mounts connected to each other add a new flag UMOUNT_CONNECTED to umount_tree to force this behavior and use this flag in detach_mounts. This closes a bug where the deletion of a file or directory could trigger an unmount and reveal data under a mount point. Cc: [email protected] Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: CWE-200
static void umount_tree(struct mount *mnt, enum umount_tree_flags how) { LIST_HEAD(tmp_list); struct mount *p; if (how & UMOUNT_PROPAGATE) propagate_mount_unlock(mnt); /* Gather the mounts to umount */ for (p = mnt; p; p = next_mnt(p, mnt)) { p->mnt.mnt_flags |= MNT_UMOUNT; list_move(&p->mnt_list, &tmp_list); } /* Hide the mounts from mnt_mounts */ list_for_each_entry(p, &tmp_list, mnt_list) { list_del_init(&p->mnt_child); } /* Add propogated mounts to the tmp_list */ if (how & UMOUNT_PROPAGATE) propagate_umount(&tmp_list); while (!list_empty(&tmp_list)) { bool disconnect; p = list_first_entry(&tmp_list, struct mount, mnt_list); list_del_init(&p->mnt_expire); list_del_init(&p->mnt_list); __touch_mnt_namespace(p->mnt_ns); p->mnt_ns = NULL; if (how & UMOUNT_SYNC) p->mnt.mnt_flags |= MNT_SYNC_UMOUNT; disconnect = !(((how & UMOUNT_CONNECTED) && mnt_has_parent(p) && (p->mnt_parent->mnt.mnt_flags & MNT_UMOUNT)) || IS_MNT_LOCKED_AND_LAZY(p)); pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt, disconnect ? &unmounted : NULL); if (mnt_has_parent(p)) { mnt_add_count(p->mnt_parent, -1); if (!disconnect) { /* Don't forget about p */ list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts); } else { umount_mnt(p); } } change_mnt_propagation(p, MS_PRIVATE); } }
167,565
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PPB_Buffer_Proxy::OnMsgCreate( PP_Instance instance, uint32_t size, HostResource* result_resource, ppapi::proxy::SerializedHandle* result_shm_handle) { result_shm_handle->set_null_shmem(); HostDispatcher* dispatcher = HostDispatcher::GetForInstance(instance); if (!dispatcher) return; thunk::EnterResourceCreation enter(instance); if (enter.failed()) return; PP_Resource local_buffer_resource = enter.functions()->CreateBuffer(instance, size); if (local_buffer_resource == 0) return; thunk::EnterResourceNoLock<thunk::PPB_BufferTrusted_API> trusted_buffer( local_buffer_resource, false); if (trusted_buffer.failed()) return; int local_fd; if (trusted_buffer.object()->GetSharedMemory(&local_fd) != PP_OK) return; result_resource->SetHostResource(instance, local_buffer_resource); base::PlatformFile platform_file = #if defined(OS_WIN) reinterpret_cast<HANDLE>(static_cast<intptr_t>(local_fd)); #elif defined(OS_POSIX) local_fd; #else #error Not implemented. #endif result_shm_handle->set_shmem( dispatcher->ShareHandleWithRemote(platform_file, false), size); } Commit Message: Add permission checks for PPB_Buffer. BUG=116317 TEST=browser_tests Review URL: https://chromiumcodereview.appspot.com/11446075 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171951 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void PPB_Buffer_Proxy::OnMsgCreate( PP_Instance instance, uint32_t size, HostResource* result_resource, ppapi::proxy::SerializedHandle* result_shm_handle) { result_shm_handle->set_null_shmem(); HostDispatcher* dispatcher = HostDispatcher::GetForInstance(instance); if (!dispatcher) return; if (!dispatcher->permissions().HasPermission(ppapi::PERMISSION_DEV)) return; thunk::EnterResourceCreation enter(instance); if (enter.failed()) return; PP_Resource local_buffer_resource = enter.functions()->CreateBuffer(instance, size); if (local_buffer_resource == 0) return; thunk::EnterResourceNoLock<thunk::PPB_BufferTrusted_API> trusted_buffer( local_buffer_resource, false); if (trusted_buffer.failed()) return; int local_fd; if (trusted_buffer.object()->GetSharedMemory(&local_fd) != PP_OK) return; result_resource->SetHostResource(instance, local_buffer_resource); base::PlatformFile platform_file = #if defined(OS_WIN) reinterpret_cast<HANDLE>(static_cast<intptr_t>(local_fd)); #elif defined(OS_POSIX) local_fd; #else #error Not implemented. #endif result_shm_handle->set_shmem( dispatcher->ShareHandleWithRemote(platform_file, false), size); }
171,341
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ih264d_mark_err_slice_skip(dec_struct_t * ps_dec, WORD32 num_mb_skip, UWORD8 u1_is_idr_slice, UWORD16 u2_frame_num, pocstruct_t *ps_cur_poc, WORD32 prev_slice_err) { WORD32 i2_cur_mb_addr; UWORD32 u1_num_mbs, u1_num_mbsNby2; UWORD32 u1_mb_idx = ps_dec->u1_mb_idx; UWORD32 i2_mb_skip_run; UWORD32 u1_num_mbs_next, u1_end_of_row; const UWORD32 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs; UWORD32 u1_slice_end; UWORD32 u1_tfr_n_mb; UWORD32 u1_decode_nmb; dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm; dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; deblk_mb_t *ps_cur_deblk_mb; dec_mb_info_t *ps_cur_mb_info; parse_pmbarams_t *ps_parse_mb_data; UWORD32 u1_inter_mb_type; UWORD32 u1_deblk_mb_type; UWORD16 u2_total_mbs_coded; UWORD32 u1_mbaff = ps_slice->u1_mbaff_frame_flag; parse_part_params_t *ps_part_info; WORD32 ret; if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) { ih264d_err_pic_dispbuf_mgr(ps_dec); return 0; } if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag && (num_mb_skip & 1)) { num_mb_skip++; } ps_dec->ps_dpb_cmds->u1_long_term_reference_flag = 0; if(prev_slice_err == 1) { /* first slice - missing/header corruption */ ps_dec->ps_cur_slice->u2_frame_num = u2_frame_num; if(!ps_dec->u1_first_slice_in_stream) { ih264d_end_of_pic(ps_dec, u1_is_idr_slice, ps_dec->ps_cur_slice->u2_frame_num); ps_dec->s_cur_pic_poc.u2_frame_num = ps_dec->ps_cur_slice->u2_frame_num; } { WORD32 i, j, poc = 0; ps_dec->ps_cur_slice->u2_first_mb_in_slice = 0; ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff; ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp; ps_dec->p_motion_compensate = ih264d_motion_compensate_bp; if(ps_dec->ps_cur_pic != NULL) poc = ps_dec->ps_cur_pic->i4_poc + 2; j = -1; for(i = 0; i < MAX_NUM_PIC_PARAMS; i++) { if(ps_dec->ps_pps[i].u1_is_valid == TRUE) { if(ps_dec->ps_pps[i].ps_sps->u1_is_valid == TRUE) { j = i; break; } } } if(j == -1) { return ERROR_INV_SLICE_HDR_T; } /* call ih264d_start_of_pic only if it was not called earlier*/ if(ps_dec->u4_pic_buf_got == 0) { ps_dec->ps_cur_slice->u1_slice_type = P_SLICE; ps_dec->ps_cur_slice->u1_nal_ref_idc = 1; ps_dec->ps_cur_slice->u1_nal_unit_type = 1; ret = ih264d_start_of_pic(ps_dec, poc, ps_cur_poc, ps_dec->ps_cur_slice->u2_frame_num, &ps_dec->ps_pps[j]); if(ret != OK) { return ret; } } ps_dec->ps_ref_pic_buf_lx[0][0]->u1_pic_buf_id = 0; ps_dec->u4_output_present = 0; { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); /* If error code is non-zero then there is no buffer available for display, hence avoid format conversion */ if(0 != ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht; } else ps_dec->u4_output_present = 1; } if(ps_dec->u1_separate_parse == 1) { if(ps_dec->u4_dec_thread_created == 0) { ithread_create(ps_dec->pv_dec_thread_handle, NULL, (void *)ih264d_decode_picture_thread, (void *)ps_dec); ps_dec->u4_dec_thread_created = 1; } if((ps_dec->u4_num_cores == 3) && ((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag) && (ps_dec->u4_bs_deblk_thread_created == 0)) { ps_dec->u4_start_recon_deblk = 0; ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL, (void *)ih264d_recon_deblk_thread, (void *)ps_dec); ps_dec->u4_bs_deblk_thread_created = 1; } } } ps_dec->u4_first_slice_in_pic = 0; } else { dec_slice_struct_t *ps_parse_cur_slice; ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num; if(ps_dec->u1_slice_header_done && ps_parse_cur_slice == ps_dec->ps_parse_cur_slice) { if((u1_mbaff) && (ps_dec->u4_num_mbs_cur_nmb & 1)) { ps_dec->u4_num_mbs_cur_nmb = ps_dec->u4_num_mbs_cur_nmb - 1; ps_dec->u2_cur_mb_addr--; } u1_num_mbs = ps_dec->u4_num_mbs_cur_nmb; if(u1_num_mbs) { ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs - 1; } else { if(ps_dec->u1_separate_parse) { ps_cur_mb_info = ps_dec->ps_nmb_info; } else { ps_cur_mb_info = ps_dec->ps_nmb_info + ps_dec->u4_num_mbs_prev_nmb - 1; } } ps_dec->u2_mby = ps_cur_mb_info->u2_mby; ps_dec->u2_mbx = ps_cur_mb_info->u2_mbx; ps_dec->u1_mb_ngbr_availablity = ps_cur_mb_info->u1_mb_ngbr_availablity; if(u1_num_mbs) { ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_prev_mb_parse_tu_coeff_data; ps_dec->u2_cur_mb_addr--; ps_dec->i4_submb_ofst -= SUB_BLK_SIZE; if (ps_dec->u1_pr_sl_type == P_SLICE || ps_dec->u1_pr_sl_type == B_SLICE) { ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs); ps_dec->ps_part = ps_dec->ps_parse_part_params; } u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); u1_slice_end = 1; u1_tfr_n_mb = 1; ps_cur_mb_info->u1_end_of_slice = u1_slice_end; if(ps_dec->u1_separate_parse) { ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); ps_dec->ps_nmb_info += u1_num_mbs; } else { ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); } ps_dec->u2_total_mbs_coded += u1_num_mbs; ps_dec->u1_mb_idx = 0; ps_dec->u4_num_mbs_cur_nmb = 0; } if(ps_dec->u2_total_mbs_coded >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { ps_dec->u1_pic_decode_done = 1; return 0; } /* Inserting new slice only if the current slice has atleast 1 MB*/ if(ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice < (UWORD32)(ps_dec->u2_total_mbs_coded >> ps_slice->u1_mbaff_frame_flag)) { ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; ps_dec->u2_cur_slice_num++; ps_dec->ps_parse_cur_slice++; } } else { ps_dec->ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num; } } /******************************************************/ /* Initializations to new slice */ /******************************************************/ { WORD32 num_entries; WORD32 size; UWORD8 *pu1_buf; num_entries = MIN(MAX_FRAMES, ps_dec->u4_num_ref_frames_at_init); num_entries = 2 * ((2 * num_entries) + 1); size = num_entries * sizeof(void *); size += PAD_MAP_IDX_POC * sizeof(void *); pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf; pu1_buf += size * ps_dec->u2_cur_slice_num; ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = (volatile void **)pu1_buf; } ps_dec->ps_cur_slice->u2_first_mb_in_slice = ps_dec->u2_total_mbs_coded >> u1_mbaff; ps_dec->ps_cur_slice->i1_slice_alpha_c0_offset = 0; ps_dec->ps_cur_slice->i1_slice_beta_offset = 0; if(ps_dec->ps_cur_slice->u1_field_pic_flag) ps_dec->u2_prv_frame_num = ps_dec->ps_cur_slice->u2_frame_num; ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice = ps_dec->u2_total_mbs_coded >> u1_mbaff; ps_dec->ps_parse_cur_slice->u2_log2Y_crwd = ps_dec->ps_cur_slice->u2_log2Y_crwd; if(ps_dec->u1_separate_parse) { ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data; } else { ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data; } /******************************************************/ /* Initializations specific to P slice */ /******************************************************/ u1_inter_mb_type = P_MB; u1_deblk_mb_type = D_INTER_MB; ps_dec->ps_cur_slice->u1_slice_type = P_SLICE; ps_dec->ps_parse_cur_slice->slice_type = P_SLICE; ps_dec->pf_mvpred_ref_tfr_nby2mb = ih264d_mv_pred_ref_tfr_nby2_pmb; ps_dec->ps_part = ps_dec->ps_parse_part_params; ps_dec->u2_mbx = (MOD(ps_dec->ps_cur_slice->u2_first_mb_in_slice - 1, ps_dec->u2_frm_wd_in_mbs)); ps_dec->u2_mby = (DIV(ps_dec->ps_cur_slice->u2_first_mb_in_slice - 1, ps_dec->u2_frm_wd_in_mbs)); ps_dec->u2_mby <<= u1_mbaff; /******************************************************/ /* Parsing / decoding the slice */ /******************************************************/ ps_dec->u1_slice_header_done = 2; ps_dec->u1_qp = ps_slice->u1_slice_qp; ih264d_update_qp(ps_dec, 0); u1_mb_idx = ps_dec->u1_mb_idx; ps_parse_mb_data = ps_dec->ps_parse_mb_data; u1_num_mbs = u1_mb_idx; u1_slice_end = 0; u1_tfr_n_mb = 0; u1_decode_nmb = 0; u1_num_mbsNby2 = 0; i2_cur_mb_addr = ps_dec->u2_total_mbs_coded; i2_mb_skip_run = num_mb_skip; while(!u1_slice_end) { UWORD8 u1_mb_type; if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr) break; ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs; ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs; ps_cur_mb_info->u1_Mux = 0; ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff); ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs; ps_cur_mb_info->u1_end_of_slice = 0; /* Storing Default partition info */ ps_parse_mb_data->u1_num_part = 1; ps_parse_mb_data->u1_isI_mb = 0; /**************************************************************/ /* Get the required information for decoding of MB */ /**************************************************************/ /* mb_x, mb_y, neighbor availablity, */ if (u1_mbaff) ih264d_get_mb_info_cavlc_mbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run); else ih264d_get_mb_info_cavlc_nonmbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run); /* Set the deblocking parameters for this MB */ if(ps_dec->u4_app_disable_deblk_frm == 0) { ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice, ps_dec->u1_mb_ngbr_availablity, ps_dec->u1_cur_mb_fld_dec_flag); } /* Set appropriate flags in ps_cur_mb_info and ps_dec */ ps_dec->i1_prev_mb_qp_delta = 0; ps_dec->u1_sub_mb_num = 0; ps_cur_mb_info->u1_mb_type = MB_SKIP; ps_cur_mb_info->u1_mb_mc_mode = PRED_16x16; ps_cur_mb_info->u1_cbp = 0; /* Storing Skip partition info */ ps_part_info = ps_dec->ps_part; ps_part_info->u1_is_direct = PART_DIRECT_16x16; ps_part_info->u1_sub_mb_num = 0; ps_dec->ps_part++; /* Update Nnzs */ ih264d_update_nnz_for_skipmb(ps_dec, ps_cur_mb_info, CAVLC); ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type; ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type; i2_mb_skip_run--; ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp; if (u1_mbaff) { ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info); } /**************************************************************/ /* Get next Macroblock address */ /**************************************************************/ i2_cur_mb_addr++; u1_num_mbs++; u1_num_mbsNby2++; ps_parse_mb_data++; /****************************************************************/ /* Check for End Of Row and other flags that determine when to */ /* do DMA setup for N/2-Mb, Decode for N-Mb, and Transfer for */ /* N-Mb */ /****************************************************************/ u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); u1_slice_end = !i2_mb_skip_run; u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row || u1_slice_end; u1_decode_nmb = u1_tfr_n_mb || u1_slice_end; ps_cur_mb_info->u1_end_of_slice = u1_slice_end; if(u1_decode_nmb) { ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs); u1_num_mbsNby2 = 0; ps_parse_mb_data = ps_dec->ps_parse_mb_data; ps_dec->ps_part = ps_dec->ps_parse_part_params; if(ps_dec->u1_separate_parse) { ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); ps_dec->ps_nmb_info += u1_num_mbs; } else { ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); } ps_dec->u2_total_mbs_coded += u1_num_mbs; if(u1_tfr_n_mb) u1_num_mbs = 0; u1_mb_idx = u1_num_mbs; ps_dec->u1_mb_idx = u1_num_mbs; } } ps_dec->u4_num_mbs_cur_nmb = 0; ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr - ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice; H264_DEC_DEBUG_PRINT("Mbs in slice: %d\n", ps_dec->ps_cur_slice->u4_mbs_in_slice); /* incremented here only if first slice is inserted */ if(ps_dec->u4_first_slice_in_pic != 0) { ps_dec->ps_parse_cur_slice++; ps_dec->u2_cur_slice_num++; } ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; if(ps_dec->u2_total_mbs_coded >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { ps_dec->u1_pic_decode_done = 1; } return 0; } Commit Message: Decoder: Moved end of pic processing to end of decode call ih264d_end_of_pic() was called after parsing slice of a new picture. This is now being done at the end of decode of the current picture. decode_gaps_in_frame_num which needs frame_num of new slice is now done after decoding frame_num in new slice. This helps in handling errors in picaff streams with gaps in frames Bug: 33588051 Bug: 33641588 Bug: 34097231 Change-Id: I1a26e611aaa2c19e2043e05a210849bd21b22220 CWE ID: CWE-119
WORD32 ih264d_mark_err_slice_skip(dec_struct_t * ps_dec, WORD32 num_mb_skip, UWORD8 u1_is_idr_slice, UWORD16 u2_frame_num, pocstruct_t *ps_cur_poc, WORD32 prev_slice_err) { WORD32 i2_cur_mb_addr; UWORD32 u1_num_mbs, u1_num_mbsNby2; UWORD32 u1_mb_idx = ps_dec->u1_mb_idx; UWORD32 i2_mb_skip_run; UWORD32 u1_num_mbs_next, u1_end_of_row; const UWORD32 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs; UWORD32 u1_slice_end; UWORD32 u1_tfr_n_mb; UWORD32 u1_decode_nmb; dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm; dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; deblk_mb_t *ps_cur_deblk_mb; dec_mb_info_t *ps_cur_mb_info; parse_pmbarams_t *ps_parse_mb_data; UWORD32 u1_inter_mb_type; UWORD32 u1_deblk_mb_type; UWORD16 u2_total_mbs_coded; UWORD32 u1_mbaff = ps_slice->u1_mbaff_frame_flag; parse_part_params_t *ps_part_info; WORD32 ret; UNUSED(u1_is_idr_slice); if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) { ih264d_err_pic_dispbuf_mgr(ps_dec); return 0; } if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag && (num_mb_skip & 1)) { num_mb_skip++; } ps_dec->ps_dpb_cmds->u1_long_term_reference_flag = 0; if(prev_slice_err == 1) { /* first slice - missing/header corruption */ ps_dec->ps_cur_slice->u2_frame_num = u2_frame_num; { WORD32 i, j, poc = 0; ps_dec->ps_cur_slice->u2_first_mb_in_slice = 0; ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff; ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp; ps_dec->p_motion_compensate = ih264d_motion_compensate_bp; if(ps_dec->ps_cur_pic != NULL) poc = ps_dec->ps_cur_pic->i4_poc + 2; j = -1; for(i = 0; i < MAX_NUM_PIC_PARAMS; i++) { if(ps_dec->ps_pps[i].u1_is_valid == TRUE) { if(ps_dec->ps_pps[i].ps_sps->u1_is_valid == TRUE) { j = i; break; } } } if(j == -1) { return ERROR_INV_SLICE_HDR_T; } /* call ih264d_start_of_pic only if it was not called earlier*/ if(ps_dec->u4_pic_buf_got == 0) { ps_dec->ps_cur_slice->u1_slice_type = P_SLICE; ps_dec->ps_cur_slice->u1_nal_ref_idc = 1; ps_dec->ps_cur_slice->u1_nal_unit_type = 1; ret = ih264d_start_of_pic(ps_dec, poc, ps_cur_poc, ps_dec->ps_cur_slice->u2_frame_num, &ps_dec->ps_pps[j]); if(ret != OK) { return ret; } } ps_dec->ps_ref_pic_buf_lx[0][0]->u1_pic_buf_id = 0; ps_dec->u4_output_present = 0; { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); /* If error code is non-zero then there is no buffer available for display, hence avoid format conversion */ if(0 != ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht; } else ps_dec->u4_output_present = 1; } if(ps_dec->u1_separate_parse == 1) { if(ps_dec->u4_dec_thread_created == 0) { ithread_create(ps_dec->pv_dec_thread_handle, NULL, (void *)ih264d_decode_picture_thread, (void *)ps_dec); ps_dec->u4_dec_thread_created = 1; } if((ps_dec->u4_num_cores == 3) && ((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag) && (ps_dec->u4_bs_deblk_thread_created == 0)) { ps_dec->u4_start_recon_deblk = 0; ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL, (void *)ih264d_recon_deblk_thread, (void *)ps_dec); ps_dec->u4_bs_deblk_thread_created = 1; } } } ps_dec->u4_first_slice_in_pic = 0; } else { dec_slice_struct_t *ps_parse_cur_slice; ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num; if(ps_dec->u1_slice_header_done && ps_parse_cur_slice == ps_dec->ps_parse_cur_slice) { if((u1_mbaff) && (ps_dec->u4_num_mbs_cur_nmb & 1)) { ps_dec->u4_num_mbs_cur_nmb = ps_dec->u4_num_mbs_cur_nmb - 1; ps_dec->u2_cur_mb_addr--; } u1_num_mbs = ps_dec->u4_num_mbs_cur_nmb; if(u1_num_mbs) { ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs - 1; } else { if(ps_dec->u1_separate_parse) { ps_cur_mb_info = ps_dec->ps_nmb_info; } else { ps_cur_mb_info = ps_dec->ps_nmb_info + ps_dec->u4_num_mbs_prev_nmb - 1; } } ps_dec->u2_mby = ps_cur_mb_info->u2_mby; ps_dec->u2_mbx = ps_cur_mb_info->u2_mbx; ps_dec->u1_mb_ngbr_availablity = ps_cur_mb_info->u1_mb_ngbr_availablity; if(u1_num_mbs) { ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_prev_mb_parse_tu_coeff_data; ps_dec->u2_cur_mb_addr--; ps_dec->i4_submb_ofst -= SUB_BLK_SIZE; if (ps_dec->u1_pr_sl_type == P_SLICE || ps_dec->u1_pr_sl_type == B_SLICE) { ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs); ps_dec->ps_part = ps_dec->ps_parse_part_params; } u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); u1_slice_end = 1; u1_tfr_n_mb = 1; ps_cur_mb_info->u1_end_of_slice = u1_slice_end; if(ps_dec->u1_separate_parse) { ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); ps_dec->ps_nmb_info += u1_num_mbs; } else { ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); } ps_dec->u2_total_mbs_coded += u1_num_mbs; ps_dec->u1_mb_idx = 0; ps_dec->u4_num_mbs_cur_nmb = 0; } if(ps_dec->u2_total_mbs_coded >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { ps_dec->u1_pic_decode_done = 1; return 0; } /* Inserting new slice only if the current slice has atleast 1 MB*/ if(ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice < (UWORD32)(ps_dec->u2_total_mbs_coded >> ps_slice->u1_mbaff_frame_flag)) { ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; ps_dec->u2_cur_slice_num++; ps_dec->ps_parse_cur_slice++; } } else { ps_dec->ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num; } } /******************************************************/ /* Initializations to new slice */ /******************************************************/ { WORD32 num_entries; WORD32 size; UWORD8 *pu1_buf; num_entries = MIN(MAX_FRAMES, ps_dec->u4_num_ref_frames_at_init); num_entries = 2 * ((2 * num_entries) + 1); size = num_entries * sizeof(void *); size += PAD_MAP_IDX_POC * sizeof(void *); pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf; pu1_buf += size * ps_dec->u2_cur_slice_num; ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = (volatile void **)pu1_buf; } ps_dec->ps_cur_slice->u2_first_mb_in_slice = ps_dec->u2_total_mbs_coded >> u1_mbaff; ps_dec->ps_cur_slice->i1_slice_alpha_c0_offset = 0; ps_dec->ps_cur_slice->i1_slice_beta_offset = 0; if(ps_dec->ps_cur_slice->u1_field_pic_flag) ps_dec->u2_prv_frame_num = ps_dec->ps_cur_slice->u2_frame_num; ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice = ps_dec->u2_total_mbs_coded >> u1_mbaff; ps_dec->ps_parse_cur_slice->u2_log2Y_crwd = ps_dec->ps_cur_slice->u2_log2Y_crwd; if(ps_dec->u1_separate_parse) { ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data; } else { ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data; } /******************************************************/ /* Initializations specific to P slice */ /******************************************************/ u1_inter_mb_type = P_MB; u1_deblk_mb_type = D_INTER_MB; ps_dec->ps_cur_slice->u1_slice_type = P_SLICE; ps_dec->ps_parse_cur_slice->slice_type = P_SLICE; ps_dec->pf_mvpred_ref_tfr_nby2mb = ih264d_mv_pred_ref_tfr_nby2_pmb; ps_dec->ps_part = ps_dec->ps_parse_part_params; ps_dec->u2_mbx = (MOD(ps_dec->ps_cur_slice->u2_first_mb_in_slice - 1, ps_dec->u2_frm_wd_in_mbs)); ps_dec->u2_mby = (DIV(ps_dec->ps_cur_slice->u2_first_mb_in_slice - 1, ps_dec->u2_frm_wd_in_mbs)); ps_dec->u2_mby <<= u1_mbaff; /******************************************************/ /* Parsing / decoding the slice */ /******************************************************/ ps_dec->u1_slice_header_done = 2; ps_dec->u1_qp = ps_slice->u1_slice_qp; ih264d_update_qp(ps_dec, 0); u1_mb_idx = ps_dec->u1_mb_idx; ps_parse_mb_data = ps_dec->ps_parse_mb_data; u1_num_mbs = u1_mb_idx; u1_slice_end = 0; u1_tfr_n_mb = 0; u1_decode_nmb = 0; u1_num_mbsNby2 = 0; i2_cur_mb_addr = ps_dec->u2_total_mbs_coded; i2_mb_skip_run = num_mb_skip; while(!u1_slice_end) { UWORD8 u1_mb_type; if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr) break; ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs; ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs; ps_cur_mb_info->u1_Mux = 0; ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff); ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs; ps_cur_mb_info->u1_end_of_slice = 0; /* Storing Default partition info */ ps_parse_mb_data->u1_num_part = 1; ps_parse_mb_data->u1_isI_mb = 0; /**************************************************************/ /* Get the required information for decoding of MB */ /**************************************************************/ /* mb_x, mb_y, neighbor availablity, */ if (u1_mbaff) ih264d_get_mb_info_cavlc_mbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run); else ih264d_get_mb_info_cavlc_nonmbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run); /* Set the deblocking parameters for this MB */ if(ps_dec->u4_app_disable_deblk_frm == 0) { ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice, ps_dec->u1_mb_ngbr_availablity, ps_dec->u1_cur_mb_fld_dec_flag); } /* Set appropriate flags in ps_cur_mb_info and ps_dec */ ps_dec->i1_prev_mb_qp_delta = 0; ps_dec->u1_sub_mb_num = 0; ps_cur_mb_info->u1_mb_type = MB_SKIP; ps_cur_mb_info->u1_mb_mc_mode = PRED_16x16; ps_cur_mb_info->u1_cbp = 0; /* Storing Skip partition info */ ps_part_info = ps_dec->ps_part; ps_part_info->u1_is_direct = PART_DIRECT_16x16; ps_part_info->u1_sub_mb_num = 0; ps_dec->ps_part++; /* Update Nnzs */ ih264d_update_nnz_for_skipmb(ps_dec, ps_cur_mb_info, CAVLC); ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type; ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type; i2_mb_skip_run--; ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp; if (u1_mbaff) { ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info); } /**************************************************************/ /* Get next Macroblock address */ /**************************************************************/ i2_cur_mb_addr++; u1_num_mbs++; u1_num_mbsNby2++; ps_parse_mb_data++; /****************************************************************/ /* Check for End Of Row and other flags that determine when to */ /* do DMA setup for N/2-Mb, Decode for N-Mb, and Transfer for */ /* N-Mb */ /****************************************************************/ u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); u1_slice_end = !i2_mb_skip_run; u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row || u1_slice_end; u1_decode_nmb = u1_tfr_n_mb || u1_slice_end; ps_cur_mb_info->u1_end_of_slice = u1_slice_end; if(u1_decode_nmb) { ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs); u1_num_mbsNby2 = 0; ps_parse_mb_data = ps_dec->ps_parse_mb_data; ps_dec->ps_part = ps_dec->ps_parse_part_params; if(ps_dec->u1_separate_parse) { ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); ps_dec->ps_nmb_info += u1_num_mbs; } else { ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); } ps_dec->u2_total_mbs_coded += u1_num_mbs; if(u1_tfr_n_mb) u1_num_mbs = 0; u1_mb_idx = u1_num_mbs; ps_dec->u1_mb_idx = u1_num_mbs; } } ps_dec->u4_num_mbs_cur_nmb = 0; ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr - ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice; H264_DEC_DEBUG_PRINT("Mbs in slice: %d\n", ps_dec->ps_cur_slice->u4_mbs_in_slice); /* incremented here only if first slice is inserted */ if(ps_dec->u4_first_slice_in_pic != 0) { ps_dec->ps_parse_cur_slice++; ps_dec->u2_cur_slice_num++; } ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; if(ps_dec->u2_total_mbs_coded >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { ps_dec->u1_pic_decode_done = 1; } return 0; }
174,055
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ExtensionTtsPlatformImpl* ExtensionTtsController::GetPlatformImpl() { if (!platform_impl_) platform_impl_ = ExtensionTtsPlatformImpl::GetInstance(); return platform_impl_; } 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 CWE ID: CWE-20
ExtensionTtsPlatformImpl* ExtensionTtsController::GetPlatformImpl() {
170,381
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void silk_NLSF_stabilize( opus_int16 *NLSF_Q15, /* I/O Unstable/stabilized normalized LSF vector in Q15 [L] */ const opus_int16 *NDeltaMin_Q15, /* I Min distance vector, NDeltaMin_Q15[L] must be >= 1 [L+1] */ const opus_int L /* I Number of NLSF parameters in the input vector */ ) { opus_int i, I=0, k, loops; opus_int16 center_freq_Q15; opus_int32 diff_Q15, min_diff_Q15, min_center_Q15, max_center_Q15; /* This is necessary to ensure an output within range of a opus_int16 */ silk_assert( NDeltaMin_Q15[L] >= 1 ); for( loops = 0; loops < MAX_LOOPS; loops++ ) { /**************************/ /* Find smallest distance */ /**************************/ /* First element */ min_diff_Q15 = NLSF_Q15[0] - NDeltaMin_Q15[0]; I = 0; /* Middle elements */ for( i = 1; i <= L-1; i++ ) { diff_Q15 = NLSF_Q15[i] - ( NLSF_Q15[i-1] + NDeltaMin_Q15[i] ); if( diff_Q15 < min_diff_Q15 ) { min_diff_Q15 = diff_Q15; I = i; } } /* Last element */ diff_Q15 = ( 1 << 15 ) - ( NLSF_Q15[L-1] + NDeltaMin_Q15[L] ); if( diff_Q15 < min_diff_Q15 ) { min_diff_Q15 = diff_Q15; I = L; } /***************************************************/ /* Now check if the smallest distance non-negative */ /***************************************************/ if( min_diff_Q15 >= 0 ) { return; } if( I == 0 ) { /* Move away from lower limit */ NLSF_Q15[0] = NDeltaMin_Q15[0]; } else if( I == L) { /* Move away from higher limit */ NLSF_Q15[L-1] = ( 1 << 15 ) - NDeltaMin_Q15[L]; } else { /* Find the lower extreme for the location of the current center frequency */ min_center_Q15 = 0; for( k = 0; k < I; k++ ) { min_center_Q15 += NDeltaMin_Q15[k]; } min_center_Q15 += silk_RSHIFT( NDeltaMin_Q15[I], 1 ); /* Find the upper extreme for the location of the current center frequency */ max_center_Q15 = 1 << 15; for( k = L; k > I; k-- ) { max_center_Q15 -= NDeltaMin_Q15[k]; } max_center_Q15 -= silk_RSHIFT( NDeltaMin_Q15[I], 1 ); /* Move apart, sorted by value, keeping the same center frequency */ center_freq_Q15 = (opus_int16)silk_LIMIT_32( silk_RSHIFT_ROUND( (opus_int32)NLSF_Q15[I-1] + (opus_int32)NLSF_Q15[I], 1 ), min_center_Q15, max_center_Q15 ); NLSF_Q15[I-1] = center_freq_Q15 - silk_RSHIFT( NDeltaMin_Q15[I], 1 ); NLSF_Q15[I] = NLSF_Q15[I-1] + NDeltaMin_Q15[I]; } } /* Safe and simple fall back method, which is less ideal than the above */ if( loops == MAX_LOOPS ) { /* Insertion sort (fast for already almost sorted arrays): */ /* Best case: O(n) for an already sorted array */ /* Worst case: O(n^2) for an inversely sorted array */ silk_insertion_sort_increasing_all_values_int16( &NLSF_Q15[0], L ); /* First NLSF should be no less than NDeltaMin[0] */ NLSF_Q15[0] = silk_max_int( NLSF_Q15[0], NDeltaMin_Q15[0] ); /* Keep delta_min distance between the NLSFs */ for( i = 1; i < L; i++ ) NLSF_Q15[i] = silk_max_int( NLSF_Q15[i], NLSF_Q15[i-1] + NDeltaMin_Q15[i] ); /* Last NLSF should be no higher than 1 - NDeltaMin[L] */ NLSF_Q15[L-1] = silk_min_int( NLSF_Q15[L-1], (1<<15) - NDeltaMin_Q15[L] ); /* Keep NDeltaMin distance between the NLSFs */ for( i = L-2; i >= 0; i-- ) NLSF_Q15[i] = silk_min_int( NLSF_Q15[i], NLSF_Q15[i+1] - NDeltaMin_Q15[i+1] ); } } Commit Message: Ensure that NLSF cannot be negative when computing a min distance between them b/31607432 Signed-off-by: Jean-Marc Valin <[email protected]> (cherry picked from commit d9d5ac4027c5ee1da2ff1c6572ae3b35a845db19) CWE ID: CWE-190
void silk_NLSF_stabilize( opus_int16 *NLSF_Q15, /* I/O Unstable/stabilized normalized LSF vector in Q15 [L] */ const opus_int16 *NDeltaMin_Q15, /* I Min distance vector, NDeltaMin_Q15[L] must be >= 1 [L+1] */ const opus_int L /* I Number of NLSF parameters in the input vector */ ) { opus_int i, I=0, k, loops; opus_int16 center_freq_Q15; opus_int32 diff_Q15, min_diff_Q15, min_center_Q15, max_center_Q15; /* This is necessary to ensure an output within range of a opus_int16 */ silk_assert( NDeltaMin_Q15[L] >= 1 ); for( loops = 0; loops < MAX_LOOPS; loops++ ) { /**************************/ /* Find smallest distance */ /**************************/ /* First element */ min_diff_Q15 = NLSF_Q15[0] - NDeltaMin_Q15[0]; I = 0; /* Middle elements */ for( i = 1; i <= L-1; i++ ) { diff_Q15 = NLSF_Q15[i] - ( NLSF_Q15[i-1] + NDeltaMin_Q15[i] ); if( diff_Q15 < min_diff_Q15 ) { min_diff_Q15 = diff_Q15; I = i; } } /* Last element */ diff_Q15 = ( 1 << 15 ) - ( NLSF_Q15[L-1] + NDeltaMin_Q15[L] ); if( diff_Q15 < min_diff_Q15 ) { min_diff_Q15 = diff_Q15; I = L; } /***************************************************/ /* Now check if the smallest distance non-negative */ /***************************************************/ if( min_diff_Q15 >= 0 ) { return; } if( I == 0 ) { /* Move away from lower limit */ NLSF_Q15[0] = NDeltaMin_Q15[0]; } else if( I == L) { /* Move away from higher limit */ NLSF_Q15[L-1] = ( 1 << 15 ) - NDeltaMin_Q15[L]; } else { /* Find the lower extreme for the location of the current center frequency */ min_center_Q15 = 0; for( k = 0; k < I; k++ ) { min_center_Q15 += NDeltaMin_Q15[k]; } min_center_Q15 += silk_RSHIFT( NDeltaMin_Q15[I], 1 ); /* Find the upper extreme for the location of the current center frequency */ max_center_Q15 = 1 << 15; for( k = L; k > I; k-- ) { max_center_Q15 -= NDeltaMin_Q15[k]; } max_center_Q15 -= silk_RSHIFT( NDeltaMin_Q15[I], 1 ); /* Move apart, sorted by value, keeping the same center frequency */ center_freq_Q15 = (opus_int16)silk_LIMIT_32( silk_RSHIFT_ROUND( (opus_int32)NLSF_Q15[I-1] + (opus_int32)NLSF_Q15[I], 1 ), min_center_Q15, max_center_Q15 ); NLSF_Q15[I-1] = center_freq_Q15 - silk_RSHIFT( NDeltaMin_Q15[I], 1 ); NLSF_Q15[I] = NLSF_Q15[I-1] + NDeltaMin_Q15[I]; } } /* Safe and simple fall back method, which is less ideal than the above */ if( loops == MAX_LOOPS ) { /* Insertion sort (fast for already almost sorted arrays): */ /* Best case: O(n) for an already sorted array */ /* Worst case: O(n^2) for an inversely sorted array */ silk_insertion_sort_increasing_all_values_int16( &NLSF_Q15[0], L ); /* First NLSF should be no less than NDeltaMin[0] */ NLSF_Q15[0] = silk_max_int( NLSF_Q15[0], NDeltaMin_Q15[0] ); /* Keep delta_min distance between the NLSFs */ for( i = 1; i < L; i++ ) NLSF_Q15[i] = silk_max_int( NLSF_Q15[i], silk_ADD_SAT16( NLSF_Q15[i-1], NDeltaMin_Q15[i] ) ); /* Last NLSF should be no higher than 1 - NDeltaMin[L] */ NLSF_Q15[L-1] = silk_min_int( NLSF_Q15[L-1], (1<<15) - NDeltaMin_Q15[L] ); /* Keep NDeltaMin distance between the NLSFs */ for( i = L-2; i >= 0; i-- ) NLSF_Q15[i] = silk_min_int( NLSF_Q15[i], NLSF_Q15[i+1] - NDeltaMin_Q15[i+1] ); } }
174,071
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long Segment::ParseHeaders() { long long total, available; const int status = m_pReader->Length(&total, &available); if (status < 0) // error return status; assert((total < 0) || (available <= total)); const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; assert((segment_stop < 0) || (total < 0) || (segment_stop <= total)); assert((segment_stop < 0) || (m_pos <= segment_stop)); for (;;) { if ((total >= 0) && (m_pos >= total)) break; if ((segment_stop >= 0) && (m_pos >= segment_stop)) break; long long pos = m_pos; const long long element_start = pos; if ((pos + 1) > available) return (pos + 1); long len; long long result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return result; if (result > 0) // underflow (weird) return (pos + 1); if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > available) return pos + len; const long long idpos = pos; const long long id = ReadUInt(m_pReader, idpos, len); if (id < 0) // error return id; if (id == 0x0F43B675) // Cluster ID break; pos += len; // consume ID if ((pos + 1) > available) return (pos + 1); result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return result; if (result > 0) // underflow (weird) return (pos + 1); if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > available) return pos + len; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0) // error return size; pos += len; // consume length of size of element const long long element_size = size + pos - element_start; if ((segment_stop >= 0) && ((pos + size) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + size) > available) return pos + size; if (id == 0x0549A966) { // Segment Info ID if (m_pInfo) return E_FILE_FORMAT_INVALID; m_pInfo = new (std::nothrow) SegmentInfo(this, pos, size, element_start, element_size); if (m_pInfo == NULL) return -1; const long status = m_pInfo->Parse(); if (status) return status; } else if (id == 0x0654AE6B) { // Tracks ID if (m_pTracks) return E_FILE_FORMAT_INVALID; m_pTracks = new (std::nothrow) Tracks(this, pos, size, element_start, element_size); if (m_pTracks == NULL) return -1; const long status = m_pTracks->Parse(); if (status) return status; } else if (id == 0x0C53BB6B) { // Cues ID if (m_pCues == NULL) { m_pCues = new (std::nothrow) Cues(this, pos, size, element_start, element_size); if (m_pCues == NULL) return -1; } } else if (id == 0x014D9B74) { // SeekHead ID if (m_pSeekHead == NULL) { m_pSeekHead = new (std::nothrow) SeekHead(this, pos, size, element_start, element_size); if (m_pSeekHead == NULL) return -1; const long status = m_pSeekHead->Parse(); if (status) return status; } } else if (id == 0x0043A770) { // Chapters ID if (m_pChapters == NULL) { m_pChapters = new (std::nothrow) Chapters(this, pos, size, element_start, element_size); if (m_pChapters == NULL) return -1; const long status = m_pChapters->Parse(); if (status) return status; } } m_pos = pos + size; // consume payload } assert((segment_stop < 0) || (m_pos <= segment_stop)); if (m_pInfo == NULL) // TODO: liberalize this behavior return E_FILE_FORMAT_INVALID; if (m_pTracks == NULL) return E_FILE_FORMAT_INVALID; return 0; // success } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long long Segment::ParseHeaders() { long long total, available; const int status = m_pReader->Length(&total, &available); if (status < 0) // error return status; if (total > 0 && available > total) return E_FILE_FORMAT_INVALID; const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; if ((segment_stop >= 0 && total >= 0 && segment_stop > total) || (segment_stop >= 0 && m_pos > segment_stop)) { return E_FILE_FORMAT_INVALID; } for (;;) { if ((total >= 0) && (m_pos >= total)) break; if ((segment_stop >= 0) && (m_pos >= segment_stop)) break; long long pos = m_pos; const long long element_start = pos; // Avoid rolling over pos when very close to LONG_LONG_MAX. unsigned long long rollover_check = pos + 1ULL; if (rollover_check > LONG_LONG_MAX) return E_FILE_FORMAT_INVALID; if ((pos + 1) > available) return (pos + 1); long len; long long result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return result; if (result > 0) { // MkvReader doesn't have enough data to satisfy this read attempt. return (pos + 1); } if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > available) return pos + len; const long long idpos = pos; const long long id = ReadID(m_pReader, idpos, len); if (id < 0) return E_FILE_FORMAT_INVALID; if (id == 0x0F43B675) // Cluster ID break; pos += len; // consume ID if ((pos + 1) > available) return (pos + 1); result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return result; if (result > 0) { // MkvReader doesn't have enough data to satisfy this read attempt. return (pos + 1); } if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > available) return pos + len; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0 || len < 1 || len > 8) { // TODO(tomfinegan): ReadUInt should return an error when len is < 1 or // len > 8 is true instead of checking this _everywhere_. return size; } pos += len; // consume length of size of element // Avoid rolling over pos when very close to LONG_LONG_MAX. rollover_check = static_cast<unsigned long long>(pos) + size; if (rollover_check > LONG_LONG_MAX) return E_FILE_FORMAT_INVALID; const long long element_size = size + pos - element_start; if ((segment_stop >= 0) && ((pos + size) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + size) > available) return pos + size; if (id == 0x0549A966) { // Segment Info ID if (m_pInfo) return E_FILE_FORMAT_INVALID; m_pInfo = new (std::nothrow) SegmentInfo(this, pos, size, element_start, element_size); if (m_pInfo == NULL) return -1; const long status = m_pInfo->Parse(); if (status) return status; } else if (id == 0x0654AE6B) { // Tracks ID if (m_pTracks) return E_FILE_FORMAT_INVALID; m_pTracks = new (std::nothrow) Tracks(this, pos, size, element_start, element_size); if (m_pTracks == NULL) return -1; const long status = m_pTracks->Parse(); if (status) return status; } else if (id == 0x0C53BB6B) { // Cues ID if (m_pCues == NULL) { m_pCues = new (std::nothrow) Cues(this, pos, size, element_start, element_size); if (m_pCues == NULL) return -1; } } else if (id == 0x014D9B74) { // SeekHead ID if (m_pSeekHead == NULL) { m_pSeekHead = new (std::nothrow) SeekHead(this, pos, size, element_start, element_size); if (m_pSeekHead == NULL) return -1; const long status = m_pSeekHead->Parse(); if (status) return status; } } else if (id == 0x0043A770) { // Chapters ID if (m_pChapters == NULL) { m_pChapters = new (std::nothrow) Chapters(this, pos, size, element_start, element_size); if (m_pChapters == NULL) return -1; const long status = m_pChapters->Parse(); if (status) return status; } } else if (id == 0x0254C367) { // Tags ID if (m_pTags == NULL) { m_pTags = new (std::nothrow) Tags(this, pos, size, element_start, element_size); if (m_pTags == NULL) return -1; const long status = m_pTags->Parse(); if (status) return status; } } m_pos = pos + size; // consume payload } if (segment_stop >= 0 && m_pos > segment_stop) return E_FILE_FORMAT_INVALID; if (m_pInfo == NULL) // TODO: liberalize this behavior return E_FILE_FORMAT_INVALID; if (m_pTracks == NULL) return E_FILE_FORMAT_INVALID; return 0; // success }
173,856
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) { size_t cipher_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { cipher_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { cipher_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { cipher_len = in[2] * 0x100; cipher_len += in[3]; i = 5; } else { return -1; } if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext) return -1; /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) cipher_len--; if (2 == cipher_len) return -1; memcpy(out, plaintext, cipher_len - 2); *out_len = cipher_len - 2; return 0; } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. CWE ID: CWE-415
decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) { size_t cipher_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { cipher_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { cipher_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { cipher_len = in[2] * 0x100; cipher_len += in[3]; i = 5; } else { return -1; } if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext) return -1; /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) cipher_len--; if (2 == cipher_len || *out_len < cipher_len - 2) return -1; memcpy(out, plaintext, cipher_len - 2); *out_len = cipher_len - 2; return 0; }
169,072
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: const Chapters* Segment::GetChapters() const { return m_pChapters; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
const Chapters* Segment::GetChapters() const
174,290
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(locale_accept_from_http) { UEnumeration *available; char *http_accept = NULL; int http_accept_len; UErrorCode status = 0; int len; char resultLocale[INTL_MAX_LOCALE_LEN+1]; UAcceptResult outResult; if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &http_accept, &http_accept_len) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_accept_from_http: unable to parse input parameters", 0 TSRMLS_CC ); RETURN_FALSE; } available = ures_openAvailableLocales(NULL, &status); INTL_CHECK_STATUS(status, "locale_accept_from_http: failed to retrieve locale list"); len = uloc_acceptLanguageFromHTTP(resultLocale, INTL_MAX_LOCALE_LEN, &outResult, http_accept, available, &status); uenum_close(available); INTL_CHECK_STATUS(status, "locale_accept_from_http: failed to find acceptable locale"); if (len < 0 || outResult == ULOC_ACCEPT_FAILED) { RETURN_FALSE; } RETURN_STRINGL(resultLocale, len, 1); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
PHP_FUNCTION(locale_accept_from_http) { UEnumeration *available; char *http_accept = NULL; int http_accept_len; UErrorCode status = 0; int len; char resultLocale[INTL_MAX_LOCALE_LEN+1]; UAcceptResult outResult; if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &http_accept, &http_accept_len) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_accept_from_http: unable to parse input parameters", 0 TSRMLS_CC ); RETURN_FALSE; } available = ures_openAvailableLocales(NULL, &status); INTL_CHECK_STATUS(status, "locale_accept_from_http: failed to retrieve locale list"); len = uloc_acceptLanguageFromHTTP(resultLocale, INTL_MAX_LOCALE_LEN, &outResult, http_accept, available, &status); uenum_close(available); INTL_CHECK_STATUS(status, "locale_accept_from_http: failed to find acceptable locale"); if (len < 0 || outResult == ULOC_ACCEPT_FAILED) { RETURN_FALSE; } RETURN_STRINGL(resultLocale, len, 1); }
167,195
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ext4_orphan_add(handle_t *handle, struct inode *inode) { struct super_block *sb = inode->i_sb; struct ext4_iloc iloc; int err = 0, rc; if (!ext4_handle_valid(handle)) return 0; mutex_lock(&EXT4_SB(sb)->s_orphan_lock); if (!list_empty(&EXT4_I(inode)->i_orphan)) goto out_unlock; /* * Orphan handling is only valid for files with data blocks * being truncated, or files being unlinked. Note that we either * hold i_mutex, or the inode can not be referenced from outside, * so i_nlink should not be bumped due to race */ J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) || inode->i_nlink == 0); BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get_write_access"); err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh); if (err) goto out_unlock; err = ext4_reserve_inode_write(handle, inode, &iloc); if (err) goto out_unlock; /* * Due to previous errors inode may be already a part of on-disk * orphan list. If so skip on-disk list modification. */ if (NEXT_ORPHAN(inode) && NEXT_ORPHAN(inode) <= (le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))) goto mem_insert; /* Insert this inode at the head of the on-disk orphan list... */ NEXT_ORPHAN(inode) = le32_to_cpu(EXT4_SB(sb)->s_es->s_last_orphan); EXT4_SB(sb)->s_es->s_last_orphan = cpu_to_le32(inode->i_ino); err = ext4_handle_dirty_super(handle, sb); rc = ext4_mark_iloc_dirty(handle, inode, &iloc); if (!err) err = rc; /* Only add to the head of the in-memory list if all the * previous operations succeeded. If the orphan_add is going to * fail (possibly taking the journal offline), we can't risk * leaving the inode on the orphan list: stray orphan-list * entries can cause panics at unmount time. * * This is safe: on error we're going to ignore the orphan list * anyway on the next recovery. */ mem_insert: if (!err) list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan); jbd_debug(4, "superblock will point to %lu\n", inode->i_ino); jbd_debug(4, "orphan inode %lu will point to %d\n", inode->i_ino, NEXT_ORPHAN(inode)); out_unlock: mutex_unlock(&EXT4_SB(sb)->s_orphan_lock); ext4_std_error(inode->i_sb, err); return err; } Commit Message: ext4: make orphan functions be no-op in no-journal mode Instead of checking whether the handle is valid, we check if journal is enabled. This avoids taking the s_orphan_lock mutex in all cases when there is no journal in use, including the error paths where ext4_orphan_del() is called with a handle set to NULL. Signed-off-by: Anatol Pomozov <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID: CWE-20
int ext4_orphan_add(handle_t *handle, struct inode *inode) { struct super_block *sb = inode->i_sb; struct ext4_iloc iloc; int err = 0, rc; if (!EXT4_SB(sb)->s_journal) return 0; mutex_lock(&EXT4_SB(sb)->s_orphan_lock); if (!list_empty(&EXT4_I(inode)->i_orphan)) goto out_unlock; /* * Orphan handling is only valid for files with data blocks * being truncated, or files being unlinked. Note that we either * hold i_mutex, or the inode can not be referenced from outside, * so i_nlink should not be bumped due to race */ J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) || inode->i_nlink == 0); BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get_write_access"); err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh); if (err) goto out_unlock; err = ext4_reserve_inode_write(handle, inode, &iloc); if (err) goto out_unlock; /* * Due to previous errors inode may be already a part of on-disk * orphan list. If so skip on-disk list modification. */ if (NEXT_ORPHAN(inode) && NEXT_ORPHAN(inode) <= (le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))) goto mem_insert; /* Insert this inode at the head of the on-disk orphan list... */ NEXT_ORPHAN(inode) = le32_to_cpu(EXT4_SB(sb)->s_es->s_last_orphan); EXT4_SB(sb)->s_es->s_last_orphan = cpu_to_le32(inode->i_ino); err = ext4_handle_dirty_super(handle, sb); rc = ext4_mark_iloc_dirty(handle, inode, &iloc); if (!err) err = rc; /* Only add to the head of the in-memory list if all the * previous operations succeeded. If the orphan_add is going to * fail (possibly taking the journal offline), we can't risk * leaving the inode on the orphan list: stray orphan-list * entries can cause panics at unmount time. * * This is safe: on error we're going to ignore the orphan list * anyway on the next recovery. */ mem_insert: if (!err) list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan); jbd_debug(4, "superblock will point to %lu\n", inode->i_ino); jbd_debug(4, "orphan inode %lu will point to %d\n", inode->i_ino, NEXT_ORPHAN(inode)); out_unlock: mutex_unlock(&EXT4_SB(sb)->s_orphan_lock); ext4_std_error(inode->i_sb, err); return err; }
166,581
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: _ksba_name_new_from_der (ksba_name_t *r_name, const unsigned char *image, size_t imagelen) { gpg_error_t err; ksba_name_t name; struct tag_info ti; const unsigned char *der; size_t derlen; int n; char *p; if (!r_name || !image) return gpg_error (GPG_ERR_INV_VALUE); *r_name = NULL; /* count and check for encoding errors - we won;t do this again during the second pass */ der = image; derlen = imagelen; n = 0; while (derlen) { err = _ksba_ber_parse_tl (&der, &derlen, &ti); if (err) return err; if (ti.class != CLASS_CONTEXT) return gpg_error (GPG_ERR_INV_CERT_OBJ); /* we expected a tag */ if (ti.ndef) return gpg_error (GPG_ERR_NOT_DER_ENCODED); if (derlen < ti.length) return gpg_error (GPG_ERR_BAD_BER); switch (ti.tag) { case 1: /* rfc822Name - this is an imlicit IA5_STRING */ case 4: /* Name */ case 6: /* URI */ n++; break; default: break; } /* advance pointer */ der += ti.length; derlen -= ti.length; } /* allocate array and set all slots to NULL for easier error recovery */ err = ksba_name_new (&name); if (err) return err; if (!n) return 0; /* empty GeneralNames */ name->names = xtrycalloc (n, sizeof *name->names); if (!name->names) { ksba_name_release (name); return gpg_error (GPG_ERR_ENOMEM); } name->n_names = n; /* start the second pass */ der = image; derlen = imagelen; n = 0; while (derlen) { char numbuf[21]; err = _ksba_ber_parse_tl (&der, &derlen, &ti); assert (!err); switch (ti.tag) { case 1: /* rfc822Name - this is an imlicit IA5_STRING */ p = name->names[n] = xtrymalloc (ti.length+3); if (!p) { ksba_name_release (name); return gpg_error (GPG_ERR_ENOMEM); } *p++ = '<'; memcpy (p, der, ti.length); p += ti.length; *p++ = '>'; *p = 0; n++; break; case 4: /* Name */ err = _ksba_derdn_to_str (der, ti.length, &p); if (err) return err; /* FIXME: we need to release some of the memory */ name->names[n++] = p; break; case 6: /* URI */ sprintf (numbuf, "%u:", (unsigned int)ti.length); p = name->names[n] = xtrymalloc (1+5+strlen (numbuf) + ti.length +1+1); if (!p) { ksba_name_release (name); return gpg_error (GPG_ERR_ENOMEM); } p = stpcpy (p, "(3:uri"); p = stpcpy (p, numbuf); memcpy (p, der, ti.length); p += ti.length; *p++ = ')'; *p = 0; /* extra safeguard null */ n++; break; default: break; } /* advance pointer */ der += ti.length; derlen -= ti.length; } *r_name = name; return 0; } Commit Message: CWE ID: CWE-20
_ksba_name_new_from_der (ksba_name_t *r_name, const unsigned char *image, size_t imagelen) { gpg_error_t err; ksba_name_t name; struct tag_info ti; const unsigned char *der; size_t derlen; int n; char *p; if (!r_name || !image) return gpg_error (GPG_ERR_INV_VALUE); *r_name = NULL; /* Count and check for encoding errors - we won't do this again during the second pass */ der = image; derlen = imagelen; n = 0; while (derlen) { err = _ksba_ber_parse_tl (&der, &derlen, &ti); if (err) return err; if (ti.class != CLASS_CONTEXT) return gpg_error (GPG_ERR_INV_CERT_OBJ); /* we expected a tag */ if (ti.ndef) return gpg_error (GPG_ERR_NOT_DER_ENCODED); if (derlen < ti.length) return gpg_error (GPG_ERR_BAD_BER); switch (ti.tag) { case 1: /* rfc822Name - this is an imlicit IA5_STRING */ case 4: /* Name */ case 6: /* URI */ n++; break; default: break; } /* advance pointer */ der += ti.length; derlen -= ti.length; } /* allocate array and set all slots to NULL for easier error recovery */ err = ksba_name_new (&name); if (err) return err; if (!n) return 0; /* empty GeneralNames */ name->names = xtrycalloc (n, sizeof *name->names); if (!name->names) { ksba_name_release (name); return gpg_error (GPG_ERR_ENOMEM); } name->n_names = n; /* start the second pass */ der = image; derlen = imagelen; n = 0; while (derlen) { char numbuf[21]; err = _ksba_ber_parse_tl (&der, &derlen, &ti); assert (!err); switch (ti.tag) { case 1: /* rfc822Name - this is an imlicit IA5_STRING */ p = name->names[n] = xtrymalloc (ti.length+3); if (!p) { ksba_name_release (name); return gpg_error (GPG_ERR_ENOMEM); } *p++ = '<'; memcpy (p, der, ti.length); p += ti.length; *p++ = '>'; *p = 0; n++; break; case 4: /* Name */ err = _ksba_derdn_to_str (der, ti.length, &p); if (err) return err; /* FIXME: we need to release some of the memory */ name->names[n++] = p; break; case 6: /* URI */ sprintf (numbuf, "%u:", (unsigned int)ti.length); p = name->names[n] = xtrymalloc (1+5+strlen (numbuf) + ti.length +1+1); if (!p) { ksba_name_release (name); return gpg_error (GPG_ERR_ENOMEM); } p = stpcpy (p, "(3:uri"); p = stpcpy (p, numbuf); memcpy (p, der, ti.length); p += ti.length; *p++ = ')'; *p = 0; /* extra safeguard null */ n++; break; default: break; } /* advance pointer */ der += ti.length; derlen -= ti.length; } *r_name = name; return 0; }
165,029
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: cmsSEQ* CMSEXPORT cmsAllocProfileSequenceDescription(cmsContext ContextID, cmsUInt32Number n) { cmsSEQ* Seq; cmsUInt32Number i; if (n == 0) return NULL; if (n > 255) return NULL; Seq = (cmsSEQ*) _cmsMallocZero(ContextID, sizeof(cmsSEQ)); if (Seq == NULL) return NULL; Seq -> ContextID = ContextID; Seq -> seq = (cmsPSEQDESC*) _cmsCalloc(ContextID, n, sizeof(cmsPSEQDESC)); Seq -> n = n; for (i=0; i < n; i++) { Seq -> seq[i].Manufacturer = NULL; Seq -> seq[i].Model = NULL; Seq -> seq[i].Description = NULL; } return Seq; } Commit Message: Non happy-path fixes CWE ID:
cmsSEQ* CMSEXPORT cmsAllocProfileSequenceDescription(cmsContext ContextID, cmsUInt32Number n) { cmsSEQ* Seq; cmsUInt32Number i; if (n == 0) return NULL; if (n > 255) return NULL; Seq = (cmsSEQ*) _cmsMallocZero(ContextID, sizeof(cmsSEQ)); if (Seq == NULL) return NULL; Seq -> ContextID = ContextID; Seq -> seq = (cmsPSEQDESC*) _cmsCalloc(ContextID, n, sizeof(cmsPSEQDESC)); Seq -> n = n; if (Seq -> seq == NULL) { _cmsFree(ContextID, Seq); return NULL; } for (i=0; i < n; i++) { Seq -> seq[i].Manufacturer = NULL; Seq -> seq[i].Model = NULL; Seq -> seq[i].Description = NULL; } return Seq; }
166,542
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void do_free_upto(BIO *f, BIO *upto) { if (upto) { BIO *tbio; do { tbio = BIO_pop(f); BIO_free(f); f = tbio; } while (f != upto); } else BIO_free_all(f); } Commit Message: Canonicalise input in CMS_verify. If content is detached and not binary mode translate the input to CRLF format. Before this change the input was verified verbatim which lead to a discrepancy between sign and verify. CWE ID: CWE-399
static void do_free_upto(BIO *f, BIO *upto) { if (upto) { BIO *tbio; do { tbio = BIO_pop(f); BIO_free(f); f = tbio; } while (f && f != upto); } else BIO_free_all(f); }
166,690
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AudioOutputDevice::Stop() { { base::AutoLock auto_lock(audio_thread_lock_); audio_thread_->Stop(MessageLoop::current()); audio_thread_.reset(); } message_loop()->PostTask(FROM_HERE, base::Bind(&AudioOutputDevice::ShutDownOnIOThread, this)); } Commit Message: Revert r157378 as it caused WebRTC to dereference null pointers when restarting a call. I've kept my unit test changes intact but disabled until I get a proper fix. BUG=147499,150805 TBR=henrika Review URL: https://codereview.chromium.org/10946040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@157626 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void AudioOutputDevice::Stop() { { base::AutoLock auto_lock(audio_thread_lock_); audio_thread_.Stop(MessageLoop::current()); } message_loop()->PostTask(FROM_HERE, base::Bind(&AudioOutputDevice::ShutDownOnIOThread, this)); }
170,707
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: 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; } 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. CWE ID: CWE-399
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 + m->num_mask, 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 + m->num_mask, 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 + m->num_mask, 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 + m->num_mask, 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 + m->num_mask, 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; }
166,361