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: void dvb_usbv2_disconnect(struct usb_interface *intf) { struct dvb_usb_device *d = usb_get_intfdata(intf); const char *name = d->name; struct device dev = d->udev->dev; dev_dbg(&d->udev->dev, "%s: bInterfaceNumber=%d\n", __func__, intf->cur_altsetting->desc.bInterfaceNumber); if (d->props->exit) d->props->exit(d); dvb_usbv2_exit(d); dev_info(&dev, "%s: '%s' successfully deinitialized and disconnected\n", KBUILD_MODNAME, name); } Commit Message: [media] dvb-usb-v2: avoid use-after-free I ran into a stack frame size warning because of the on-stack copy of the USB device structure: drivers/media/usb/dvb-usb-v2/dvb_usb_core.c: In function 'dvb_usbv2_disconnect': drivers/media/usb/dvb-usb-v2/dvb_usb_core.c:1029:1: error: the frame size of 1104 bytes is larger than 1024 bytes [-Werror=frame-larger-than=] Copying a device structure like this is wrong for a number of other reasons too aside from the possible stack overflow. One of them is that the dev_info() call will print the name of the device later, but AFAICT we have only copied a pointer to the name earlier and the actual name has been freed by the time it gets printed. This removes the on-stack copy of the device and instead copies the device name using kstrdup(). I'm ignoring the possible failure here as both printk() and kfree() are able to deal with NULL pointers. Signed-off-by: Arnd Bergmann <[email protected]> Signed-off-by: Mauro Carvalho Chehab <[email protected]> CWE ID: CWE-119
void dvb_usbv2_disconnect(struct usb_interface *intf) { struct dvb_usb_device *d = usb_get_intfdata(intf); const char *devname = kstrdup(dev_name(&d->udev->dev), GFP_KERNEL); const char *drvname = d->name; dev_dbg(&d->udev->dev, "%s: bInterfaceNumber=%d\n", __func__, intf->cur_altsetting->desc.bInterfaceNumber); if (d->props->exit) d->props->exit(d); dvb_usbv2_exit(d); pr_info("%s: '%s:%s' successfully deinitialized and disconnected\n", KBUILD_MODNAME, drvname, devname); kfree(devname); }
168,222
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 LogoService::GetLogo(search_provider_logos::LogoObserver* observer) { LogoCallbacks callbacks; callbacks.on_cached_decoded_logo_available = base::BindOnce(ObserverOnLogoAvailable, observer, true); callbacks.on_fresh_decoded_logo_available = base::BindOnce(ObserverOnLogoAvailable, observer, false); GetLogo(std::move(callbacks)); } Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <[email protected]> Reviewed-by: Marc Treib <[email protected]> Commit-Queue: Chris Pickel <[email protected]> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119
void LogoService::GetLogo(search_provider_logos::LogoObserver* observer) {
171,951
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 AcceleratedStaticBitmapImage::CheckThread() { if (detach_thread_at_next_check_) { thread_checker_.DetachFromThread(); detach_thread_at_next_check_ = false; } CHECK(thread_checker_.CalledOnValidThread()); } Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy - AcceleratedStaticBitmapImage was misusing ThreadChecker by having its own detach logic. Using proper DetachThread is simpler, cleaner and correct. - UnacceleratedStaticBitmapImage didn't destroy the SkImage in the proper thread, leading to GrContext/SkSp problems. Bug: 890576 Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723 Reviewed-on: https://chromium-review.googlesource.com/c/1307775 Reviewed-by: Gabriel Charette <[email protected]> Reviewed-by: Jeremy Roman <[email protected]> Commit-Queue: Fernando Serboncini <[email protected]> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119
void AcceleratedStaticBitmapImage::CheckThread() {
172,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: xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) { xmlChar *buf = NULL; int len = 0; int size = XML_PARSER_BUFFER_SIZE; int c, l; xmlChar stop; xmlChar *ret = NULL; const xmlChar *cur = NULL; xmlParserInputPtr input; if (RAW == '"') stop = '"'; else if (RAW == '\'') stop = '\''; else { xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_STARTED, NULL); return(NULL); } buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } /* * The content of the entity definition is copied in a buffer. */ ctxt->instate = XML_PARSER_ENTITY_VALUE; input = ctxt->input; GROW; NEXT; c = CUR_CHAR(l); /* * NOTE: 4.4.5 Included in Literal * When a parameter entity reference appears in a literal entity * value, ... a single or double quote character in the replacement * text is always treated as a normal data character and will not * terminate the literal. * In practice it means we stop the loop only when back at parsing * the initial entity and the quote is found */ while ((IS_CHAR(c)) && ((c != stop) || /* checked */ (ctxt->input != input))) { if (len + 5 >= size) { xmlChar *tmp; size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buf); return(NULL); } buf = tmp; } COPY_BUF(l,buf,len,c); NEXTL(l); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) /* non input consuming */ xmlPopInput(ctxt); GROW; c = CUR_CHAR(l); if (c == 0) { GROW; c = CUR_CHAR(l); } } buf[len] = 0; /* * Raise problem w.r.t. '&' and '%' being used in non-entities * reference constructs. Note Charref will be handled in * xmlStringDecodeEntities() */ cur = buf; while (*cur != 0) { /* non input consuming */ if ((*cur == '%') || ((*cur == '&') && (cur[1] != '#'))) { xmlChar *name; xmlChar tmp = *cur; cur++; name = xmlParseStringName(ctxt, &cur); if ((name == NULL) || (*cur != ';')) { xmlFatalErrMsgInt(ctxt, XML_ERR_ENTITY_CHAR_ERROR, "EntityValue: '%c' forbidden except for entities references\n", tmp); } if ((tmp == '%') && (ctxt->inSubset == 1) && (ctxt->inputNr == 1)) { xmlFatalErr(ctxt, XML_ERR_ENTITY_PE_INTERNAL, NULL); } if (name != NULL) xmlFree(name); if (*cur == 0) break; } cur++; } /* * Then PEReference entities are substituted. */ if (c != stop) { xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_FINISHED, NULL); xmlFree(buf); } else { NEXT; /* * NOTE: 4.4.7 Bypassed * When a general entity reference appears in the EntityValue in * an entity declaration, it is bypassed and left as is. * so XML_SUBSTITUTE_REF is not set here. */ ret = xmlStringDecodeEntities(ctxt, buf, XML_SUBSTITUTE_PEREF, 0, 0, 0); if (orig != NULL) *orig = buf; else xmlFree(buf); } return(ret); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) { xmlChar *buf = NULL; int len = 0; int size = XML_PARSER_BUFFER_SIZE; int c, l; xmlChar stop; xmlChar *ret = NULL; const xmlChar *cur = NULL; xmlParserInputPtr input; if (RAW == '"') stop = '"'; else if (RAW == '\'') stop = '\''; else { xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_STARTED, NULL); return(NULL); } buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } /* * The content of the entity definition is copied in a buffer. */ ctxt->instate = XML_PARSER_ENTITY_VALUE; input = ctxt->input; GROW; if (ctxt->instate == XML_PARSER_EOF) { xmlFree(buf); return(NULL); } NEXT; c = CUR_CHAR(l); /* * NOTE: 4.4.5 Included in Literal * When a parameter entity reference appears in a literal entity * value, ... a single or double quote character in the replacement * text is always treated as a normal data character and will not * terminate the literal. * In practice it means we stop the loop only when back at parsing * the initial entity and the quote is found */ while (((IS_CHAR(c)) && ((c != stop) || /* checked */ (ctxt->input != input))) && (ctxt->instate != XML_PARSER_EOF)) { if (len + 5 >= size) { xmlChar *tmp; size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buf); return(NULL); } buf = tmp; } COPY_BUF(l,buf,len,c); NEXTL(l); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) /* non input consuming */ xmlPopInput(ctxt); GROW; c = CUR_CHAR(l); if (c == 0) { GROW; c = CUR_CHAR(l); } } buf[len] = 0; if (ctxt->instate == XML_PARSER_EOF) { xmlFree(buf); return(NULL); } /* * Raise problem w.r.t. '&' and '%' being used in non-entities * reference constructs. Note Charref will be handled in * xmlStringDecodeEntities() */ cur = buf; while (*cur != 0) { /* non input consuming */ if ((*cur == '%') || ((*cur == '&') && (cur[1] != '#'))) { xmlChar *name; xmlChar tmp = *cur; cur++; name = xmlParseStringName(ctxt, &cur); if ((name == NULL) || (*cur != ';')) { xmlFatalErrMsgInt(ctxt, XML_ERR_ENTITY_CHAR_ERROR, "EntityValue: '%c' forbidden except for entities references\n", tmp); } if ((tmp == '%') && (ctxt->inSubset == 1) && (ctxt->inputNr == 1)) { xmlFatalErr(ctxt, XML_ERR_ENTITY_PE_INTERNAL, NULL); } if (name != NULL) xmlFree(name); if (*cur == 0) break; } cur++; } /* * Then PEReference entities are substituted. */ if (c != stop) { xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_FINISHED, NULL); xmlFree(buf); } else { NEXT; /* * NOTE: 4.4.7 Bypassed * When a general entity reference appears in the EntityValue in * an entity declaration, it is bypassed and left as is. * so XML_SUBSTITUTE_REF is not set here. */ ret = xmlStringDecodeEntities(ctxt, buf, XML_SUBSTITUTE_PEREF, 0, 0, 0); if (orig != NULL) *orig = buf; else xmlFree(buf); } return(ret); }
171,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: xmlParseNmtoken(xmlParserCtxtPtr ctxt) { xmlChar buf[XML_MAX_NAMELEN + 5]; int len = 0, l; int c; int count = 0; #ifdef DEBUG nbParseNmToken++; #endif GROW; c = CUR_CHAR(l); while (xmlIsNameChar(ctxt, c)) { if (count++ > 100) { count = 0; GROW; } COPY_BUF(l,buf,len,c); NEXTL(l); c = CUR_CHAR(l); if (len >= XML_MAX_NAMELEN) { /* * Okay someone managed to make a huge token, so he's ready to pay * for the processing speed. */ xmlChar *buffer; int max = len * 2; buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar)); if (buffer == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } memcpy(buffer, buf, len); while (xmlIsNameChar(ctxt, c)) { if (count++ > 100) { count = 0; GROW; } if (len + 10 > max) { xmlChar *tmp; max *= 2; tmp = (xmlChar *) xmlRealloc(buffer, max * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buffer); return(NULL); } buffer = tmp; } COPY_BUF(l,buffer,len,c); NEXTL(l); c = CUR_CHAR(l); } buffer[len] = 0; return(buffer); } } if (len == 0) return(NULL); return(xmlStrndup(buf, len)); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseNmtoken(xmlParserCtxtPtr ctxt) { xmlChar buf[XML_MAX_NAMELEN + 5]; int len = 0, l; int c; int count = 0; #ifdef DEBUG nbParseNmToken++; #endif GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); c = CUR_CHAR(l); while (xmlIsNameChar(ctxt, c)) { if (count++ > 100) { count = 0; GROW; } COPY_BUF(l,buf,len,c); NEXTL(l); c = CUR_CHAR(l); if (len >= XML_MAX_NAMELEN) { /* * Okay someone managed to make a huge token, so he's ready to pay * for the processing speed. */ xmlChar *buffer; int max = len * 2; buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar)); if (buffer == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } memcpy(buffer, buf, len); while (xmlIsNameChar(ctxt, c)) { if (count++ > 100) { count = 0; GROW; if (ctxt->instate == XML_PARSER_EOF) { xmlFree(buffer); return(NULL); } } if (len + 10 > max) { xmlChar *tmp; max *= 2; tmp = (xmlChar *) xmlRealloc(buffer, max * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buffer); return(NULL); } buffer = tmp; } COPY_BUF(l,buffer,len,c); NEXTL(l); c = CUR_CHAR(l); } buffer[len] = 0; return(buffer); } } if (len == 0) return(NULL); return(xmlStrndup(buf, len)); }
171,298
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 MBMotionComp( VideoDecData *video, int CBP ) { /*---------------------------------------------------------------------------- ; Define all local variables ----------------------------------------------------------------------------*/ /* Previous Video Object Plane */ Vop *prev = video->prevVop; /* Current Macroblock (MB) in the VOP */ int mbnum = video->mbnum; /* Number of MB per data row */ int MB_in_width = video->nMBPerRow; int ypos, xpos; PIXEL *c_comp, *c_prev; PIXEL *cu_comp, *cu_prev; PIXEL *cv_comp, *cv_prev; int height, width, pred_width; int imv, mvwidth; int32 offset; uint8 mode; uint8 *pred_block, *pred; /* Motion vector (dx,dy) in half-pel resolution */ int dx, dy; MOT px[4], py[4]; int xpred, ypred; int xsum; int round1; #ifdef PV_POSTPROC_ON // 2/14/2001 /* Total number of pixels in the VOL */ int32 size = (int32) video->nTotalMB << 8; uint8 *pp_dec_y, *pp_dec_u; int ll[4]; int tmp = 0; uint8 msk_deblock = 0; #endif /*---------------------------------------------------------------------------- ; Function body here ----------------------------------------------------------------------------*/ /* Set rounding type */ /* change from array to single 09/29/2000 */ round1 = (int)(1 - video->currVop->roundingType); /* width of luminance data in pixels (y axis) */ width = video->width; /* heigth of luminance data in pixels (x axis) */ height = video->height; /* number of blocks per row */ mvwidth = MB_in_width << 1; /* starting y position in current MB; origin of MB */ ypos = video->mbnum_row << 4 ; /* starting x position in current MB; origin of MB */ xpos = video->mbnum_col << 4 ; /* offset to (x,y) position in current luminance MB */ /* in pixel resolution */ /* ypos*width -> row, +x -> column */ offset = (int32)ypos * width + xpos; /* get mode for current MB */ mode = video->headerInfo.Mode[mbnum]; /* block index */ /* imv = (xpos/8) + ((ypos/8) * mvwidth) */ imv = (offset >> 6) - (xpos >> 6) + (xpos >> 3); if (mode & INTER_1VMASK) { dx = px[0] = px[1] = px[2] = px[3] = video->motX[imv]; dy = py[0] = py[1] = py[2] = py[3] = video->motY[imv]; if ((dx & 3) == 0) { dx = dx >> 1; } else { /* x component of MV is or'ed for rounding (?) */ dx = (dx >> 1) | 1; } /* y component of motion vector; divide by 2 for to */ /* convert to full-pel resolution. */ if ((dy & 3) == 0) { dy = dy >> 1; } else { /* y component of MV is or'ed for rounding (?) */ dy = (dy >> 1) | 1; } } else { px[0] = video->motX[imv]; px[1] = video->motX[imv+1]; px[2] = video->motX[imv+mvwidth]; px[3] = video->motX[imv+mvwidth+1]; xsum = px[0] + px[1] + px[2] + px[3]; dx = PV_SIGN(xsum) * (roundtab16[(PV_ABS(xsum)) & 0xF] + (((PV_ABS(xsum)) >> 4) << 1)); py[0] = video->motY[imv]; py[1] = video->motY[imv+1]; py[2] = video->motY[imv+mvwidth]; py[3] = video->motY[imv+mvwidth+1]; xsum = py[0] + py[1] + py[2] + py[3]; dy = PV_SIGN(xsum) * (roundtab16[(PV_ABS(xsum)) & 0xF] + (((PV_ABS(xsum)) >> 4) << 1)); } /* Pointer to previous luminance frame */ c_prev = prev->yChan; pred_block = video->mblock->pred_block; /* some blocks have no residue or INTER4V */ /*if (mode == MODE_INTER4V) 05/08/15 */ /* Motion Compensation for an 8x8 block within a MB */ /* (4 MV per MB) */ /* Call function that performs luminance prediction */ /* luminance_pred_mode_inter4v(xpos, ypos, px, py, c_prev, video->mblock->pred_block, width, height, round1, mvwidth, &xsum, &ysum);*/ c_comp = video->currVop->yChan + offset; xpred = (int)((xpos << 1) + px[0]); ypred = (int)((ypos << 1) + py[0]); if ((CBP >> 5)&1) { pred = pred_block; pred_width = 16; } else { pred = c_comp; pred_width = width; } /* check whether the MV points outside the frame */ if (xpred >= 0 && xpred <= ((width << 1) - (2*B_SIZE)) && ypred >= 0 && ypred <= ((height << 1) - (2*B_SIZE))) { /*****************************/ /* (x,y) is inside the frame */ /*****************************/ ; GetPredAdvBTable[ypred&1][xpred&1](c_prev + (xpred >> 1) + ((ypred >> 1)*width), pred, width, (pred_width << 1) | round1); } else { /******************************/ /* (x,y) is outside the frame */ /******************************/ GetPredOutside(xpred, ypred, c_prev, pred, width, height, round1, pred_width); } /* Compute prediction values over current luminance MB */ /* (blocks 1); add motion vector prior to input; */ /* add 8 to x_pos to advance to next block */ xpred = (int)(((xpos + B_SIZE) << 1) + px[1]); ypred = (int)((ypos << 1) + py[1]); if ((CBP >> 4)&1) { pred = pred_block + 8; pred_width = 16; } else { pred = c_comp + 8; pred_width = width; } /* check whether the MV points outside the frame */ if (xpred >= 0 && xpred <= ((width << 1) - (2*B_SIZE)) && ypred >= 0 && ypred <= ((height << 1) - (2*B_SIZE))) { /*****************************/ /* (x,y) is inside the frame */ /*****************************/ GetPredAdvBTable[ypred&1][xpred&1](c_prev + (xpred >> 1) + ((ypred >> 1)*width), pred, width, (pred_width << 1) | round1); } else { /******************************/ /* (x,y) is outside the frame */ /******************************/ GetPredOutside(xpred, ypred, c_prev, pred, width, height, round1, pred_width); } /* Compute prediction values over current luminance MB */ /* (blocks 2); add motion vector prior to input */ /* add 8 to y_pos to advance to block on next row */ xpred = (int)((xpos << 1) + px[2]); ypred = (int)(((ypos + B_SIZE) << 1) + py[2]); if ((CBP >> 3)&1) { pred = pred_block + 128; pred_width = 16; } else { pred = c_comp + (width << 3); pred_width = width; } /* check whether the MV points outside the frame */ if (xpred >= 0 && xpred <= ((width << 1) - (2*B_SIZE)) && ypred >= 0 && ypred <= ((height << 1) - (2*B_SIZE))) { /*****************************/ /* (x,y) is inside the frame */ /*****************************/ GetPredAdvBTable[ypred&1][xpred&1](c_prev + (xpred >> 1) + ((ypred >> 1)*width), pred, width, (pred_width << 1) | round1); } else { /******************************/ /* (x,y) is outside the frame */ /******************************/ GetPredOutside(xpred, ypred, c_prev, pred, width, height, round1, pred_width); } /* Compute prediction values over current luminance MB */ /* (blocks 3); add motion vector prior to input; */ /* add 8 to x_pos and y_pos to advance to next block */ /* on next row */ xpred = (int)(((xpos + B_SIZE) << 1) + px[3]); ypred = (int)(((ypos + B_SIZE) << 1) + py[3]); if ((CBP >> 2)&1) { pred = pred_block + 136; pred_width = 16; } else { pred = c_comp + (width << 3) + 8; pred_width = width; } /* check whether the MV points outside the frame */ if (xpred >= 0 && xpred <= ((width << 1) - (2*B_SIZE)) && ypred >= 0 && ypred <= ((height << 1) - (2*B_SIZE))) { /*****************************/ /* (x,y) is inside the frame */ /*****************************/ GetPredAdvBTable[ypred&1][xpred&1](c_prev + (xpred >> 1) + ((ypred >> 1)*width), pred, width, (pred_width << 1) | round1); } else { /******************************/ /* (x,y) is outside the frame */ /******************************/ GetPredOutside(xpred, ypred, c_prev, pred, width, height, round1, pred_width); } /* Call function to set de-blocking and de-ringing */ /* semaphores for luminance */ #ifdef PV_POSTPROC_ON if (video->postFilterType != PV_NO_POST_PROC) { if (mode&INTER_1VMASK) { pp_dec_y = video->pstprcTypCur + imv; ll[0] = 1; ll[1] = mvwidth - 1; ll[2] = 1; ll[3] = -mvwidth - 1; msk_deblock = pp_semaphore_luma(xpred, ypred, pp_dec_y, video->pstprcTypPrv, ll, &tmp, px[0], py[0], mvwidth, width, height); pp_dec_u = video->pstprcTypCur + (size >> 6) + ((imv + (xpos >> 3)) >> 2); pp_semaphore_chroma_inter(xpred, ypred, pp_dec_u, video->pstprcTypPrv, dx, dy, mvwidth, height, size, tmp, msk_deblock); } else { /* Post-processing mode (MBM_INTER8) */ /* deblocking and deringing) */ pp_dec_y = video->pstprcTypCur + imv; *pp_dec_y = 4; *(pp_dec_y + 1) = 4; *(pp_dec_y + mvwidth) = 4; *(pp_dec_y + mvwidth + 1) = 4; pp_dec_u = video->pstprcTypCur + (size >> 6) + ((imv + (xpos >> 3)) >> 2); *pp_dec_u = 4; pp_dec_u[size>>8] = 4; } } #endif /* xpred and ypred calculation for Chrominance is */ /* in full-pel resolution. */ /* Chrominance */ /* width of chrominance data in pixels (y axis) */ width >>= 1; /* heigth of chrominance data in pixels (x axis) */ height >>= 1; /* Pointer to previous chrominance b frame */ cu_prev = prev->uChan; /* Pointer to previous chrominance r frame */ cv_prev = prev->vChan; /* x position in prediction data offset by motion vector */ /* xpred calculation for Chrominance is in full-pel */ /* resolution. */ xpred = xpos + dx; /* y position in prediction data offset by motion vector */ /* ypred calculation for Chrominance is in full-pel */ /* resolution. */ ypred = ypos + dy; cu_comp = video->currVop->uChan + (offset >> 2) + (xpos >> 2); cv_comp = video->currVop->vChan + (offset >> 2) + (xpos >> 2); /* Call function that performs chrominance prediction */ /* chrominance_pred(xpred, ypred, cu_prev, cv_prev, pred_block, width_uv, height_uv, round1);*/ if (xpred >= 0 && xpred <= ((width << 1) - (2*B_SIZE)) && ypred >= 0 && ypred <= ((height << 1) - (2*B_SIZE))) { /*****************************/ /* (x,y) is inside the frame */ /*****************************/ if ((CBP >> 1)&1) { pred = pred_block + 256; pred_width = 16; } else { pred = cu_comp; pred_width = width; } /* Compute prediction for Chrominance b (block[4]) */ GetPredAdvBTable[ypred&1][xpred&1](cu_prev + (xpred >> 1) + ((ypred >> 1)*width), pred, width, (pred_width << 1) | round1); if (CBP&1) { pred = pred_block + 264; pred_width = 16; } else { pred = cv_comp; pred_width = width; } /* Compute prediction for Chrominance r (block[5]) */ GetPredAdvBTable[ypred&1][xpred&1](cv_prev + (xpred >> 1) + ((ypred >> 1)*width), pred, width, (pred_width << 1) | round1); return ; } else { /******************************/ /* (x,y) is outside the frame */ /******************************/ if ((CBP >> 1)&1) { pred = pred_block + 256; pred_width = 16; } else { pred = cu_comp; pred_width = width; } /* Compute prediction for Chrominance b (block[4]) */ GetPredOutside(xpred, ypred, cu_prev, pred, width, height, round1, pred_width); if (CBP&1) { pred = pred_block + 264; pred_width = 16; } else { pred = cv_comp; pred_width = width; } /* Compute prediction for Chrominance r (block[5]) */ GetPredOutside(xpred, ypred, cv_prev, pred, width, height, round1, pred_width); return ; } } Commit Message: Fix NPDs in h263 decoder Bug: 35269635 Test: decoded PoC with and without patch Change-Id: I636a14360c7801cc5bca63c9cb44d1d235df8fd8 (cherry picked from commit 2ad2a92318a3b9daf78ebcdc597085adbf32600d) CWE ID:
void MBMotionComp( VideoDecData *video, int CBP ) { /*---------------------------------------------------------------------------- ; Define all local variables ----------------------------------------------------------------------------*/ /* Previous Video Object Plane */ Vop *prev = video->prevVop; /* Current Macroblock (MB) in the VOP */ int mbnum = video->mbnum; /* Number of MB per data row */ int MB_in_width = video->nMBPerRow; int ypos, xpos; PIXEL *c_comp, *c_prev; PIXEL *cu_comp, *cu_prev; PIXEL *cv_comp, *cv_prev; int height, width, pred_width; int imv, mvwidth; int32 offset; uint8 mode; uint8 *pred_block, *pred; /* Motion vector (dx,dy) in half-pel resolution */ int dx, dy; MOT px[4], py[4]; int xpred, ypred; int xsum; int round1; #ifdef PV_POSTPROC_ON // 2/14/2001 /* Total number of pixels in the VOL */ int32 size = (int32) video->nTotalMB << 8; uint8 *pp_dec_y, *pp_dec_u; int ll[4]; int tmp = 0; uint8 msk_deblock = 0; #endif /*---------------------------------------------------------------------------- ; Function body here ----------------------------------------------------------------------------*/ /* Set rounding type */ /* change from array to single 09/29/2000 */ round1 = (int)(1 - video->currVop->roundingType); /* width of luminance data in pixels (y axis) */ width = video->width; /* heigth of luminance data in pixels (x axis) */ height = video->height; /* number of blocks per row */ mvwidth = MB_in_width << 1; /* starting y position in current MB; origin of MB */ ypos = video->mbnum_row << 4 ; /* starting x position in current MB; origin of MB */ xpos = video->mbnum_col << 4 ; /* offset to (x,y) position in current luminance MB */ /* in pixel resolution */ /* ypos*width -> row, +x -> column */ offset = (int32)ypos * width + xpos; /* get mode for current MB */ mode = video->headerInfo.Mode[mbnum]; /* block index */ /* imv = (xpos/8) + ((ypos/8) * mvwidth) */ imv = (offset >> 6) - (xpos >> 6) + (xpos >> 3); if (mode & INTER_1VMASK) { dx = px[0] = px[1] = px[2] = px[3] = video->motX[imv]; dy = py[0] = py[1] = py[2] = py[3] = video->motY[imv]; if ((dx & 3) == 0) { dx = dx >> 1; } else { /* x component of MV is or'ed for rounding (?) */ dx = (dx >> 1) | 1; } /* y component of motion vector; divide by 2 for to */ /* convert to full-pel resolution. */ if ((dy & 3) == 0) { dy = dy >> 1; } else { /* y component of MV is or'ed for rounding (?) */ dy = (dy >> 1) | 1; } } else { px[0] = video->motX[imv]; px[1] = video->motX[imv+1]; px[2] = video->motX[imv+mvwidth]; px[3] = video->motX[imv+mvwidth+1]; xsum = px[0] + px[1] + px[2] + px[3]; dx = PV_SIGN(xsum) * (roundtab16[(PV_ABS(xsum)) & 0xF] + (((PV_ABS(xsum)) >> 4) << 1)); py[0] = video->motY[imv]; py[1] = video->motY[imv+1]; py[2] = video->motY[imv+mvwidth]; py[3] = video->motY[imv+mvwidth+1]; xsum = py[0] + py[1] + py[2] + py[3]; dy = PV_SIGN(xsum) * (roundtab16[(PV_ABS(xsum)) & 0xF] + (((PV_ABS(xsum)) >> 4) << 1)); } /* Pointer to previous luminance frame */ c_prev = prev->yChan; if (!c_prev) { ALOGE("b/35269635"); android_errorWriteLog(0x534e4554, "35269635"); return; } pred_block = video->mblock->pred_block; /* some blocks have no residue or INTER4V */ /*if (mode == MODE_INTER4V) 05/08/15 */ /* Motion Compensation for an 8x8 block within a MB */ /* (4 MV per MB) */ /* Call function that performs luminance prediction */ /* luminance_pred_mode_inter4v(xpos, ypos, px, py, c_prev, video->mblock->pred_block, width, height, round1, mvwidth, &xsum, &ysum);*/ c_comp = video->currVop->yChan + offset; xpred = (int)((xpos << 1) + px[0]); ypred = (int)((ypos << 1) + py[0]); if ((CBP >> 5)&1) { pred = pred_block; pred_width = 16; } else { pred = c_comp; pred_width = width; } /* check whether the MV points outside the frame */ if (xpred >= 0 && xpred <= ((width << 1) - (2*B_SIZE)) && ypred >= 0 && ypred <= ((height << 1) - (2*B_SIZE))) { /*****************************/ /* (x,y) is inside the frame */ /*****************************/ ; GetPredAdvBTable[ypred&1][xpred&1](c_prev + (xpred >> 1) + ((ypred >> 1)*width), pred, width, (pred_width << 1) | round1); } else { /******************************/ /* (x,y) is outside the frame */ /******************************/ GetPredOutside(xpred, ypred, c_prev, pred, width, height, round1, pred_width); } /* Compute prediction values over current luminance MB */ /* (blocks 1); add motion vector prior to input; */ /* add 8 to x_pos to advance to next block */ xpred = (int)(((xpos + B_SIZE) << 1) + px[1]); ypred = (int)((ypos << 1) + py[1]); if ((CBP >> 4)&1) { pred = pred_block + 8; pred_width = 16; } else { pred = c_comp + 8; pred_width = width; } /* check whether the MV points outside the frame */ if (xpred >= 0 && xpred <= ((width << 1) - (2*B_SIZE)) && ypred >= 0 && ypred <= ((height << 1) - (2*B_SIZE))) { /*****************************/ /* (x,y) is inside the frame */ /*****************************/ GetPredAdvBTable[ypred&1][xpred&1](c_prev + (xpred >> 1) + ((ypred >> 1)*width), pred, width, (pred_width << 1) | round1); } else { /******************************/ /* (x,y) is outside the frame */ /******************************/ GetPredOutside(xpred, ypred, c_prev, pred, width, height, round1, pred_width); } /* Compute prediction values over current luminance MB */ /* (blocks 2); add motion vector prior to input */ /* add 8 to y_pos to advance to block on next row */ xpred = (int)((xpos << 1) + px[2]); ypred = (int)(((ypos + B_SIZE) << 1) + py[2]); if ((CBP >> 3)&1) { pred = pred_block + 128; pred_width = 16; } else { pred = c_comp + (width << 3); pred_width = width; } /* check whether the MV points outside the frame */ if (xpred >= 0 && xpred <= ((width << 1) - (2*B_SIZE)) && ypred >= 0 && ypred <= ((height << 1) - (2*B_SIZE))) { /*****************************/ /* (x,y) is inside the frame */ /*****************************/ GetPredAdvBTable[ypred&1][xpred&1](c_prev + (xpred >> 1) + ((ypred >> 1)*width), pred, width, (pred_width << 1) | round1); } else { /******************************/ /* (x,y) is outside the frame */ /******************************/ GetPredOutside(xpred, ypred, c_prev, pred, width, height, round1, pred_width); } /* Compute prediction values over current luminance MB */ /* (blocks 3); add motion vector prior to input; */ /* add 8 to x_pos and y_pos to advance to next block */ /* on next row */ xpred = (int)(((xpos + B_SIZE) << 1) + px[3]); ypred = (int)(((ypos + B_SIZE) << 1) + py[3]); if ((CBP >> 2)&1) { pred = pred_block + 136; pred_width = 16; } else { pred = c_comp + (width << 3) + 8; pred_width = width; } /* check whether the MV points outside the frame */ if (xpred >= 0 && xpred <= ((width << 1) - (2*B_SIZE)) && ypred >= 0 && ypred <= ((height << 1) - (2*B_SIZE))) { /*****************************/ /* (x,y) is inside the frame */ /*****************************/ GetPredAdvBTable[ypred&1][xpred&1](c_prev + (xpred >> 1) + ((ypred >> 1)*width), pred, width, (pred_width << 1) | round1); } else { /******************************/ /* (x,y) is outside the frame */ /******************************/ GetPredOutside(xpred, ypred, c_prev, pred, width, height, round1, pred_width); } /* Call function to set de-blocking and de-ringing */ /* semaphores for luminance */ #ifdef PV_POSTPROC_ON if (video->postFilterType != PV_NO_POST_PROC) { if (mode&INTER_1VMASK) { pp_dec_y = video->pstprcTypCur + imv; ll[0] = 1; ll[1] = mvwidth - 1; ll[2] = 1; ll[3] = -mvwidth - 1; msk_deblock = pp_semaphore_luma(xpred, ypred, pp_dec_y, video->pstprcTypPrv, ll, &tmp, px[0], py[0], mvwidth, width, height); pp_dec_u = video->pstprcTypCur + (size >> 6) + ((imv + (xpos >> 3)) >> 2); pp_semaphore_chroma_inter(xpred, ypred, pp_dec_u, video->pstprcTypPrv, dx, dy, mvwidth, height, size, tmp, msk_deblock); } else { /* Post-processing mode (MBM_INTER8) */ /* deblocking and deringing) */ pp_dec_y = video->pstprcTypCur + imv; *pp_dec_y = 4; *(pp_dec_y + 1) = 4; *(pp_dec_y + mvwidth) = 4; *(pp_dec_y + mvwidth + 1) = 4; pp_dec_u = video->pstprcTypCur + (size >> 6) + ((imv + (xpos >> 3)) >> 2); *pp_dec_u = 4; pp_dec_u[size>>8] = 4; } } #endif /* xpred and ypred calculation for Chrominance is */ /* in full-pel resolution. */ /* Chrominance */ /* width of chrominance data in pixels (y axis) */ width >>= 1; /* heigth of chrominance data in pixels (x axis) */ height >>= 1; /* Pointer to previous chrominance b frame */ cu_prev = prev->uChan; /* Pointer to previous chrominance r frame */ cv_prev = prev->vChan; /* x position in prediction data offset by motion vector */ /* xpred calculation for Chrominance is in full-pel */ /* resolution. */ xpred = xpos + dx; /* y position in prediction data offset by motion vector */ /* ypred calculation for Chrominance is in full-pel */ /* resolution. */ ypred = ypos + dy; cu_comp = video->currVop->uChan + (offset >> 2) + (xpos >> 2); cv_comp = video->currVop->vChan + (offset >> 2) + (xpos >> 2); /* Call function that performs chrominance prediction */ /* chrominance_pred(xpred, ypred, cu_prev, cv_prev, pred_block, width_uv, height_uv, round1);*/ if (xpred >= 0 && xpred <= ((width << 1) - (2*B_SIZE)) && ypred >= 0 && ypred <= ((height << 1) - (2*B_SIZE))) { /*****************************/ /* (x,y) is inside the frame */ /*****************************/ if ((CBP >> 1)&1) { pred = pred_block + 256; pred_width = 16; } else { pred = cu_comp; pred_width = width; } /* Compute prediction for Chrominance b (block[4]) */ GetPredAdvBTable[ypred&1][xpred&1](cu_prev + (xpred >> 1) + ((ypred >> 1)*width), pred, width, (pred_width << 1) | round1); if (CBP&1) { pred = pred_block + 264; pred_width = 16; } else { pred = cv_comp; pred_width = width; } /* Compute prediction for Chrominance r (block[5]) */ GetPredAdvBTable[ypred&1][xpred&1](cv_prev + (xpred >> 1) + ((ypred >> 1)*width), pred, width, (pred_width << 1) | round1); return ; } else { /******************************/ /* (x,y) is outside the frame */ /******************************/ if ((CBP >> 1)&1) { pred = pred_block + 256; pred_width = 16; } else { pred = cu_comp; pred_width = width; } /* Compute prediction for Chrominance b (block[4]) */ GetPredOutside(xpred, ypred, cu_prev, pred, width, height, round1, pred_width); if (CBP&1) { pred = pred_block + 264; pred_width = 16; } else { pred = cv_comp; pred_width = width; } /* Compute prediction for Chrominance r (block[5]) */ GetPredOutside(xpred, ypred, cv_prev, pred, width, height, round1, pred_width); return ; } }
174,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: void AddServiceRequestHandlerOnIoThread( const std::string& name, const ServiceRequestHandler& handler) { DCHECK(io_thread_checker_.CalledOnValidThread()); auto result = request_handlers_.insert(std::make_pair(name, handler)); DCHECK(result.second); } Commit Message: media: Support hosting mojo CDM in a standalone service Currently when mojo CDM is enabled it is hosted in the MediaService running in the process specified by "mojo_media_host". However, on some platforms we need to run mojo CDM and other mojo media services in different processes. For example, on desktop platforms, we want to run mojo video decoder in the GPU process, but run the mojo CDM in the utility process. This CL adds a new build flag "enable_standalone_cdm_service". When enabled, the mojo CDM service will be hosted in a standalone "cdm" service running in the utility process. All other mojo media services will sill be hosted in the "media" servie running in the process specified by "mojo_media_host". BUG=664364 TEST=Encrypted media browser tests using mojo CDM is still working. Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487 Reviewed-on: https://chromium-review.googlesource.com/567172 Commit-Queue: Xiaohan Wang <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Dan Sanders <[email protected]> Cr-Commit-Position: refs/heads/master@{#486947} CWE ID: CWE-119
void AddServiceRequestHandlerOnIoThread( const std::string& name, const ServiceRequestHandler& handler) { DCHECK(io_thread_checker_.CalledOnValidThread()); auto result = request_handlers_.insert(std::make_pair(name, handler)); DCHECK(result.second) << "ServiceRequestHandler for " << name << " already exists."; }
171,940
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 filter_frame(AVFilterLink *inlink, AVFrame *in) { GradFunContext *s = inlink->dst->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *out; int p, direct; if (av_frame_is_writable(in)) { direct = 1; out = in; } else { direct = 0; out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); } for (p = 0; p < 4 && in->data[p]; p++) { int w = inlink->w; int h = inlink->h; int r = s->radius; if (p) { w = s->chroma_w; h = s->chroma_h; r = s->chroma_r; } if (FFMIN(w, h) > 2 * r) filter(s, out->data[p], in->data[p], w, h, out->linesize[p], in->linesize[p], r); else if (out->data[p] != in->data[p]) av_image_copy_plane(out->data[p], out->linesize[p], in->data[p], in->linesize[p], w, h); } if (!direct) av_frame_free(&in); return ff_filter_frame(outlink, out); } Commit Message: avfilter: fix plane validity checks Fixes out of array accesses Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
static int filter_frame(AVFilterLink *inlink, AVFrame *in) { GradFunContext *s = inlink->dst->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *out; int p, direct; if (av_frame_is_writable(in)) { direct = 1; out = in; } else { direct = 0; out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); } for (p = 0; p < 4 && in->data[p] && in->linesize[p]; p++) { int w = inlink->w; int h = inlink->h; int r = s->radius; if (p) { w = s->chroma_w; h = s->chroma_h; r = s->chroma_r; } if (FFMIN(w, h) > 2 * r) filter(s, out->data[p], in->data[p], w, h, out->linesize[p], in->linesize[p], r); else if (out->data[p] != in->data[p]) av_image_copy_plane(out->data[p], out->linesize[p], in->data[p], in->linesize[p], w, h); } if (!direct) av_frame_free(&in); return ff_filter_frame(outlink, out); }
166,001
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 LayoutSVGTransformableContainer::calculateLocalTransform() { SVGGraphicsElement* element = toSVGGraphicsElement(this->element()); ASSERT(element); SVGUseElement* useElement = nullptr; if (isSVGUseElement(*element)) { useElement = toSVGUseElement(element); } else if (isSVGGElement(*element) && toSVGGElement(element)->inUseShadowTree()) { SVGElement* correspondingElement = element->correspondingElement(); if (isSVGUseElement(correspondingElement)) useElement = toSVGUseElement(correspondingElement); } if (useElement) { SVGLengthContext lengthContext(useElement); FloatSize translation( useElement->x()->currentValue()->value(lengthContext), useElement->y()->currentValue()->value(lengthContext)); if (translation != m_additionalTranslation) m_needsTransformUpdate = true; m_additionalTranslation = translation; } if (!m_needsTransformUpdate) return false; m_localTransform = element->calculateAnimatedLocalTransform(); m_localTransform.translate(m_additionalTranslation.width(), m_additionalTranslation.height()); m_needsTransformUpdate = false; return true; } Commit Message: Avoid using forced layout to trigger paint invalidation for SVG containers Currently, SVG containers in the LayoutObject hierarchy force layout of their children if the transform changes. The main reason for this is to trigger paint invalidation of the subtree. In some cases - changes to the scale factor - there are other reasons to trigger layout, like computing a new scale factor for <text> or re-layout nodes with non-scaling stroke. Compute a "scale-factor change" in addition to the "transform change" already computed, then use this new signal to determine if layout should be forced for the subtree. Trigger paint invalidation using the LayoutObject flags instead. The downside to this is that paint invalidation will walk into "hidden" containers which rarely require repaint (since they are not technically visible). This will hopefully be rectified in a follow-up CL. For the testcase from 603850, this essentially eliminates the cost of layout (from ~350ms to ~0ms on authors machine; layout cost is related to text metrics recalculation), bumping frame rate significantly. BUG=603956,603850 Review-Url: https://codereview.chromium.org/1996543002 Cr-Commit-Position: refs/heads/master@{#400950} CWE ID:
bool LayoutSVGTransformableContainer::calculateLocalTransform() void LayoutSVGTransformableContainer::setNeedsTransformUpdate() { setMayNeedPaintInvalidationSubtree(); m_needsTransformUpdate = true; } static std::pair<double, double> scaleReference(const AffineTransform& transform) { return std::make_pair(transform.xScaleSquared(), transform.yScaleSquared()); } LayoutSVGContainer::TransformChange LayoutSVGTransformableContainer::calculateLocalTransform() { SVGGraphicsElement* element = toSVGGraphicsElement(this->element()); ASSERT(element); SVGUseElement* useElement = nullptr; if (isSVGUseElement(*element)) { useElement = toSVGUseElement(element); } else if (isSVGGElement(*element) && toSVGGElement(element)->inUseShadowTree()) { SVGElement* correspondingElement = element->correspondingElement(); if (isSVGUseElement(correspondingElement)) useElement = toSVGUseElement(correspondingElement); } if (useElement) { SVGLengthContext lengthContext(useElement); FloatSize translation( useElement->x()->currentValue()->value(lengthContext), useElement->y()->currentValue()->value(lengthContext)); // TODO(fs): Signal this on style update instead. (Since these are // suppose to be presentation attributes now, this does feel a bit // broken...) if (translation != m_additionalTranslation) setNeedsTransformUpdate(); m_additionalTranslation = translation; } if (!m_needsTransformUpdate) return TransformChange::None; std::pair<double, double> oldScale = scaleReference(m_localTransform); m_localTransform = element->calculateAnimatedLocalTransform(); m_localTransform.translate(m_additionalTranslation.width(), m_additionalTranslation.height()); m_needsTransformUpdate = false; return scaleReference(m_localTransform) != oldScale ? TransformChange::Full : TransformChange::ScaleInvariant; }
171,666
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const double bias, ExceptionInfo *exception) { #define AdaptiveThresholdImageTag "AdaptiveThreshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickSizeType number_pixels; ssize_t y; /* Initialize threshold image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if (width == 0) return(threshold_image); status=SetImageStorageClass(threshold_image,DirectClass,exception); if (status == MagickFalse) { threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Threshold image. */ status=MagickTrue; progress=0; number_pixels=(MagickSizeType) width*height; image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double channel_bias[MaxPixelChannels], channel_sum[MaxPixelChannels]; register const Quantum *magick_restrict p, *magick_restrict pixels; register Quantum *magick_restrict q; register ssize_t i, x; ssize_t center, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) (height/2L),image->columns+width,height,exception); q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+ GetPixelChannels(image)*(width/2); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } pixels=p; channel_bias[channel]=0.0; channel_sum[channel]=0.0; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) channel_bias[channel]+=pixels[i]; channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image); } pixels+=GetPixelChannels(image)*image->columns; } } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double mean; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } channel_sum[channel]-=channel_bias[channel]; channel_bias[channel]=0.0; pixels=p; for (v=0; v < (ssize_t) height; v++) { channel_bias[channel]+=pixels[i]; pixels+=(width-1)*GetPixelChannels(image); channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image)*(image->columns+1); } mean=(double) (channel_sum[channel]/number_pixels+bias); SetPixelChannel(threshold_image,channel,(Quantum) ((double) p[center+i] <= mean ? 0 : QuantumRange),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(threshold_image); } if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_image->type=image->type; threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1609 CWE ID: CWE-125
MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const double bias, ExceptionInfo *exception) { #define AdaptiveThresholdImageTag "AdaptiveThreshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickSizeType number_pixels; ssize_t y; /* Initialize threshold image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if ((width == 0) || (height == 0)) return(threshold_image); status=SetImageStorageClass(threshold_image,DirectClass,exception); if (status == MagickFalse) { threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Threshold image. */ status=MagickTrue; progress=0; number_pixels=(MagickSizeType) width*height; image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double channel_bias[MaxPixelChannels], channel_sum[MaxPixelChannels]; register const Quantum *magick_restrict p, *magick_restrict pixels; register Quantum *magick_restrict q; register ssize_t i, x; ssize_t center, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) (height/2L),image->columns+width,height,exception); q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+ GetPixelChannels(image)*(width/2); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } pixels=p; channel_bias[channel]=0.0; channel_sum[channel]=0.0; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) channel_bias[channel]+=pixels[i]; channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image); } pixels+=GetPixelChannels(image)*image->columns; } } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double mean; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } channel_sum[channel]-=channel_bias[channel]; channel_bias[channel]=0.0; pixels=p; for (v=0; v < (ssize_t) height; v++) { channel_bias[channel]+=pixels[i]; pixels+=(width-1)*GetPixelChannels(image); channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image)*(image->columns+1); } mean=(double) (channel_sum[channel]/number_pixels+bias); SetPixelChannel(threshold_image,channel,(Quantum) ((double) p[center+i] <= mean ? 0 : QuantumRange),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(threshold_image); } if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_image->type=image->type; threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); }
170,206
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct o2nm_cluster *to_o2nm_cluster_from_node(struct o2nm_node *node) { /* through the first node_set .parent * mycluster/nodes/mynode == o2nm_cluster->o2nm_node_group->o2nm_node */ return to_o2nm_cluster(node->nd_item.ci_parent->ci_parent); } Commit Message: ocfs2: subsystem.su_mutex is required while accessing the item->ci_parent The subsystem.su_mutex is required while accessing the item->ci_parent, otherwise, NULL pointer dereference to the item->ci_parent will be triggered in the following situation: add node delete node sys_write vfs_write configfs_write_file o2nm_node_store o2nm_node_local_write do_rmdir vfs_rmdir configfs_rmdir mutex_lock(&subsys->su_mutex); unlink_obj item->ci_group = NULL; item->ci_parent = NULL; to_o2nm_cluster_from_node node->nd_item.ci_parent->ci_parent BUG since of NULL pointer dereference to nd_item.ci_parent Moreover, the o2nm_cluster also should be protected by the subsystem.su_mutex. [[email protected]: v2] Link: http://lkml.kernel.org/r/[email protected] Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Alex Chen <[email protected]> Reviewed-by: Jun Piao <[email protected]> Reviewed-by: Joseph Qi <[email protected]> Cc: Mark Fasheh <[email protected]> Cc: Joel Becker <[email protected]> Cc: Junxiao Bi <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-476
static struct o2nm_cluster *to_o2nm_cluster_from_node(struct o2nm_node *node) { /* through the first node_set .parent * mycluster/nodes/mynode == o2nm_cluster->o2nm_node_group->o2nm_node */ if (node->nd_item.ci_parent) return to_o2nm_cluster(node->nd_item.ci_parent->ci_parent); else return NULL; }
169,408
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 GetEXIFProperty(const Image *image, const char *property,ExceptionInfo *exception) { #define MaxDirectoryStack 16 #define EXIF_DELIMITER "\n" #define EXIF_NUM_FORMATS 12 #define EXIF_FMT_BYTE 1 #define EXIF_FMT_STRING 2 #define EXIF_FMT_USHORT 3 #define EXIF_FMT_ULONG 4 #define EXIF_FMT_URATIONAL 5 #define EXIF_FMT_SBYTE 6 #define EXIF_FMT_UNDEFINED 7 #define EXIF_FMT_SSHORT 8 #define EXIF_FMT_SLONG 9 #define EXIF_FMT_SRATIONAL 10 #define EXIF_FMT_SINGLE 11 #define EXIF_FMT_DOUBLE 12 #define TAG_EXIF_OFFSET 0x8769 #define TAG_GPS_OFFSET 0x8825 #define TAG_INTEROP_OFFSET 0xa005 #define EXIFMultipleValues(size,format,arg) \ { \ ssize_t \ component; \ \ size_t \ length; \ \ unsigned char \ *p1; \ \ length=0; \ p1=p; \ for (component=0; component < components; component++) \ { \ length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \ format", ",arg); \ if (length >= (MagickPathExtent-1)) \ length=MagickPathExtent-1; \ p1+=size; \ } \ if (length > 1) \ buffer[length-2]='\0'; \ value=AcquireString(buffer); \ } #define EXIFMultipleFractions(size,format,arg1,arg2) \ { \ ssize_t \ component; \ \ size_t \ length; \ \ unsigned char \ *p1; \ \ length=0; \ p1=p; \ for (component=0; component < components; component++) \ { \ length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \ format", ",(arg1),(arg2)); \ if (length >= (MagickPathExtent-1)) \ length=MagickPathExtent-1; \ p1+=size; \ } \ if (length > 1) \ buffer[length-2]='\0'; \ value=AcquireString(buffer); \ } typedef struct _DirectoryInfo { const unsigned char *directory; size_t entry; ssize_t offset; } DirectoryInfo; typedef struct _TagInfo { size_t tag; const char *description; } TagInfo; static TagInfo EXIFTag[] = { { 0x001, "exif:InteroperabilityIndex" }, { 0x002, "exif:InteroperabilityVersion" }, { 0x100, "exif:ImageWidth" }, { 0x101, "exif:ImageLength" }, { 0x102, "exif:BitsPerSample" }, { 0x103, "exif:Compression" }, { 0x106, "exif:PhotometricInterpretation" }, { 0x10a, "exif:FillOrder" }, { 0x10d, "exif:DocumentName" }, { 0x10e, "exif:ImageDescription" }, { 0x10f, "exif:Make" }, { 0x110, "exif:Model" }, { 0x111, "exif:StripOffsets" }, { 0x112, "exif:Orientation" }, { 0x115, "exif:SamplesPerPixel" }, { 0x116, "exif:RowsPerStrip" }, { 0x117, "exif:StripByteCounts" }, { 0x11a, "exif:XResolution" }, { 0x11b, "exif:YResolution" }, { 0x11c, "exif:PlanarConfiguration" }, { 0x11d, "exif:PageName" }, { 0x11e, "exif:XPosition" }, { 0x11f, "exif:YPosition" }, { 0x118, "exif:MinSampleValue" }, { 0x119, "exif:MaxSampleValue" }, { 0x120, "exif:FreeOffsets" }, { 0x121, "exif:FreeByteCounts" }, { 0x122, "exif:GrayResponseUnit" }, { 0x123, "exif:GrayResponseCurve" }, { 0x124, "exif:T4Options" }, { 0x125, "exif:T6Options" }, { 0x128, "exif:ResolutionUnit" }, { 0x12d, "exif:TransferFunction" }, { 0x131, "exif:Software" }, { 0x132, "exif:DateTime" }, { 0x13b, "exif:Artist" }, { 0x13e, "exif:WhitePoint" }, { 0x13f, "exif:PrimaryChromaticities" }, { 0x140, "exif:ColorMap" }, { 0x141, "exif:HalfToneHints" }, { 0x142, "exif:TileWidth" }, { 0x143, "exif:TileLength" }, { 0x144, "exif:TileOffsets" }, { 0x145, "exif:TileByteCounts" }, { 0x14a, "exif:SubIFD" }, { 0x14c, "exif:InkSet" }, { 0x14d, "exif:InkNames" }, { 0x14e, "exif:NumberOfInks" }, { 0x150, "exif:DotRange" }, { 0x151, "exif:TargetPrinter" }, { 0x152, "exif:ExtraSample" }, { 0x153, "exif:SampleFormat" }, { 0x154, "exif:SMinSampleValue" }, { 0x155, "exif:SMaxSampleValue" }, { 0x156, "exif:TransferRange" }, { 0x157, "exif:ClipPath" }, { 0x158, "exif:XClipPathUnits" }, { 0x159, "exif:YClipPathUnits" }, { 0x15a, "exif:Indexed" }, { 0x15b, "exif:JPEGTables" }, { 0x15f, "exif:OPIProxy" }, { 0x200, "exif:JPEGProc" }, { 0x201, "exif:JPEGInterchangeFormat" }, { 0x202, "exif:JPEGInterchangeFormatLength" }, { 0x203, "exif:JPEGRestartInterval" }, { 0x205, "exif:JPEGLosslessPredictors" }, { 0x206, "exif:JPEGPointTransforms" }, { 0x207, "exif:JPEGQTables" }, { 0x208, "exif:JPEGDCTables" }, { 0x209, "exif:JPEGACTables" }, { 0x211, "exif:YCbCrCoefficients" }, { 0x212, "exif:YCbCrSubSampling" }, { 0x213, "exif:YCbCrPositioning" }, { 0x214, "exif:ReferenceBlackWhite" }, { 0x2bc, "exif:ExtensibleMetadataPlatform" }, { 0x301, "exif:Gamma" }, { 0x302, "exif:ICCProfileDescriptor" }, { 0x303, "exif:SRGBRenderingIntent" }, { 0x320, "exif:ImageTitle" }, { 0x5001, "exif:ResolutionXUnit" }, { 0x5002, "exif:ResolutionYUnit" }, { 0x5003, "exif:ResolutionXLengthUnit" }, { 0x5004, "exif:ResolutionYLengthUnit" }, { 0x5005, "exif:PrintFlags" }, { 0x5006, "exif:PrintFlagsVersion" }, { 0x5007, "exif:PrintFlagsCrop" }, { 0x5008, "exif:PrintFlagsBleedWidth" }, { 0x5009, "exif:PrintFlagsBleedWidthScale" }, { 0x500A, "exif:HalftoneLPI" }, { 0x500B, "exif:HalftoneLPIUnit" }, { 0x500C, "exif:HalftoneDegree" }, { 0x500D, "exif:HalftoneShape" }, { 0x500E, "exif:HalftoneMisc" }, { 0x500F, "exif:HalftoneScreen" }, { 0x5010, "exif:JPEGQuality" }, { 0x5011, "exif:GridSize" }, { 0x5012, "exif:ThumbnailFormat" }, { 0x5013, "exif:ThumbnailWidth" }, { 0x5014, "exif:ThumbnailHeight" }, { 0x5015, "exif:ThumbnailColorDepth" }, { 0x5016, "exif:ThumbnailPlanes" }, { 0x5017, "exif:ThumbnailRawBytes" }, { 0x5018, "exif:ThumbnailSize" }, { 0x5019, "exif:ThumbnailCompressedSize" }, { 0x501a, "exif:ColorTransferFunction" }, { 0x501b, "exif:ThumbnailData" }, { 0x5020, "exif:ThumbnailImageWidth" }, { 0x5021, "exif:ThumbnailImageHeight" }, { 0x5022, "exif:ThumbnailBitsPerSample" }, { 0x5023, "exif:ThumbnailCompression" }, { 0x5024, "exif:ThumbnailPhotometricInterp" }, { 0x5025, "exif:ThumbnailImageDescription" }, { 0x5026, "exif:ThumbnailEquipMake" }, { 0x5027, "exif:ThumbnailEquipModel" }, { 0x5028, "exif:ThumbnailStripOffsets" }, { 0x5029, "exif:ThumbnailOrientation" }, { 0x502a, "exif:ThumbnailSamplesPerPixel" }, { 0x502b, "exif:ThumbnailRowsPerStrip" }, { 0x502c, "exif:ThumbnailStripBytesCount" }, { 0x502d, "exif:ThumbnailResolutionX" }, { 0x502e, "exif:ThumbnailResolutionY" }, { 0x502f, "exif:ThumbnailPlanarConfig" }, { 0x5030, "exif:ThumbnailResolutionUnit" }, { 0x5031, "exif:ThumbnailTransferFunction" }, { 0x5032, "exif:ThumbnailSoftwareUsed" }, { 0x5033, "exif:ThumbnailDateTime" }, { 0x5034, "exif:ThumbnailArtist" }, { 0x5035, "exif:ThumbnailWhitePoint" }, { 0x5036, "exif:ThumbnailPrimaryChromaticities" }, { 0x5037, "exif:ThumbnailYCbCrCoefficients" }, { 0x5038, "exif:ThumbnailYCbCrSubsampling" }, { 0x5039, "exif:ThumbnailYCbCrPositioning" }, { 0x503A, "exif:ThumbnailRefBlackWhite" }, { 0x503B, "exif:ThumbnailCopyRight" }, { 0x5090, "exif:LuminanceTable" }, { 0x5091, "exif:ChrominanceTable" }, { 0x5100, "exif:FrameDelay" }, { 0x5101, "exif:LoopCount" }, { 0x5110, "exif:PixelUnit" }, { 0x5111, "exif:PixelPerUnitX" }, { 0x5112, "exif:PixelPerUnitY" }, { 0x5113, "exif:PaletteHistogram" }, { 0x1000, "exif:RelatedImageFileFormat" }, { 0x1001, "exif:RelatedImageLength" }, { 0x1002, "exif:RelatedImageWidth" }, { 0x800d, "exif:ImageID" }, { 0x80e3, "exif:Matteing" }, { 0x80e4, "exif:DataType" }, { 0x80e5, "exif:ImageDepth" }, { 0x80e6, "exif:TileDepth" }, { 0x828d, "exif:CFARepeatPatternDim" }, { 0x828e, "exif:CFAPattern2" }, { 0x828f, "exif:BatteryLevel" }, { 0x8298, "exif:Copyright" }, { 0x829a, "exif:ExposureTime" }, { 0x829d, "exif:FNumber" }, { 0x83bb, "exif:IPTC/NAA" }, { 0x84e3, "exif:IT8RasterPadding" }, { 0x84e5, "exif:IT8ColorTable" }, { 0x8649, "exif:ImageResourceInformation" }, { 0x8769, "exif:ExifOffset" }, { 0x8773, "exif:InterColorProfile" }, { 0x8822, "exif:ExposureProgram" }, { 0x8824, "exif:SpectralSensitivity" }, { 0x8825, "exif:GPSInfo" }, { 0x8827, "exif:ISOSpeedRatings" }, { 0x8828, "exif:OECF" }, { 0x8829, "exif:Interlace" }, { 0x882a, "exif:TimeZoneOffset" }, { 0x882b, "exif:SelfTimerMode" }, { 0x9000, "exif:ExifVersion" }, { 0x9003, "exif:DateTimeOriginal" }, { 0x9004, "exif:DateTimeDigitized" }, { 0x9101, "exif:ComponentsConfiguration" }, { 0x9102, "exif:CompressedBitsPerPixel" }, { 0x9201, "exif:ShutterSpeedValue" }, { 0x9202, "exif:ApertureValue" }, { 0x9203, "exif:BrightnessValue" }, { 0x9204, "exif:ExposureBiasValue" }, { 0x9205, "exif:MaxApertureValue" }, { 0x9206, "exif:SubjectDistance" }, { 0x9207, "exif:MeteringMode" }, { 0x9208, "exif:LightSource" }, { 0x9209, "exif:Flash" }, { 0x920a, "exif:FocalLength" }, { 0x920b, "exif:FlashEnergy" }, { 0x920c, "exif:SpatialFrequencyResponse" }, { 0x920d, "exif:Noise" }, { 0x9211, "exif:ImageNumber" }, { 0x9212, "exif:SecurityClassification" }, { 0x9213, "exif:ImageHistory" }, { 0x9214, "exif:SubjectArea" }, { 0x9215, "exif:ExposureIndex" }, { 0x9216, "exif:TIFF-EPStandardID" }, { 0x927c, "exif:MakerNote" }, { 0x9C9b, "exif:WinXP-Title" }, { 0x9C9c, "exif:WinXP-Comments" }, { 0x9C9d, "exif:WinXP-Author" }, { 0x9C9e, "exif:WinXP-Keywords" }, { 0x9C9f, "exif:WinXP-Subject" }, { 0x9286, "exif:UserComment" }, { 0x9290, "exif:SubSecTime" }, { 0x9291, "exif:SubSecTimeOriginal" }, { 0x9292, "exif:SubSecTimeDigitized" }, { 0xa000, "exif:FlashPixVersion" }, { 0xa001, "exif:ColorSpace" }, { 0xa002, "exif:ExifImageWidth" }, { 0xa003, "exif:ExifImageLength" }, { 0xa004, "exif:RelatedSoundFile" }, { 0xa005, "exif:InteroperabilityOffset" }, { 0xa20b, "exif:FlashEnergy" }, { 0xa20c, "exif:SpatialFrequencyResponse" }, { 0xa20d, "exif:Noise" }, { 0xa20e, "exif:FocalPlaneXResolution" }, { 0xa20f, "exif:FocalPlaneYResolution" }, { 0xa210, "exif:FocalPlaneResolutionUnit" }, { 0xa214, "exif:SubjectLocation" }, { 0xa215, "exif:ExposureIndex" }, { 0xa216, "exif:TIFF/EPStandardID" }, { 0xa217, "exif:SensingMethod" }, { 0xa300, "exif:FileSource" }, { 0xa301, "exif:SceneType" }, { 0xa302, "exif:CFAPattern" }, { 0xa401, "exif:CustomRendered" }, { 0xa402, "exif:ExposureMode" }, { 0xa403, "exif:WhiteBalance" }, { 0xa404, "exif:DigitalZoomRatio" }, { 0xa405, "exif:FocalLengthIn35mmFilm" }, { 0xa406, "exif:SceneCaptureType" }, { 0xa407, "exif:GainControl" }, { 0xa408, "exif:Contrast" }, { 0xa409, "exif:Saturation" }, { 0xa40a, "exif:Sharpness" }, { 0xa40b, "exif:DeviceSettingDescription" }, { 0xa40c, "exif:SubjectDistanceRange" }, { 0xa420, "exif:ImageUniqueID" }, { 0xc4a5, "exif:PrintImageMatching" }, { 0xa500, "exif:Gamma" }, { 0xc640, "exif:CR2Slice" }, { 0x10000, "exif:GPSVersionID" }, { 0x10001, "exif:GPSLatitudeRef" }, { 0x10002, "exif:GPSLatitude" }, { 0x10003, "exif:GPSLongitudeRef" }, { 0x10004, "exif:GPSLongitude" }, { 0x10005, "exif:GPSAltitudeRef" }, { 0x10006, "exif:GPSAltitude" }, { 0x10007, "exif:GPSTimeStamp" }, { 0x10008, "exif:GPSSatellites" }, { 0x10009, "exif:GPSStatus" }, { 0x1000a, "exif:GPSMeasureMode" }, { 0x1000b, "exif:GPSDop" }, { 0x1000c, "exif:GPSSpeedRef" }, { 0x1000d, "exif:GPSSpeed" }, { 0x1000e, "exif:GPSTrackRef" }, { 0x1000f, "exif:GPSTrack" }, { 0x10010, "exif:GPSImgDirectionRef" }, { 0x10011, "exif:GPSImgDirection" }, { 0x10012, "exif:GPSMapDatum" }, { 0x10013, "exif:GPSDestLatitudeRef" }, { 0x10014, "exif:GPSDestLatitude" }, { 0x10015, "exif:GPSDestLongitudeRef" }, { 0x10016, "exif:GPSDestLongitude" }, { 0x10017, "exif:GPSDestBearingRef" }, { 0x10018, "exif:GPSDestBearing" }, { 0x10019, "exif:GPSDestDistanceRef" }, { 0x1001a, "exif:GPSDestDistance" }, { 0x1001b, "exif:GPSProcessingMethod" }, { 0x1001c, "exif:GPSAreaInformation" }, { 0x1001d, "exif:GPSDateStamp" }, { 0x1001e, "exif:GPSDifferential" }, { 0x00000, (const char *) NULL } }; const StringInfo *profile; const unsigned char *directory, *exif; DirectoryInfo directory_stack[MaxDirectoryStack]; EndianType endian; MagickBooleanType status; register ssize_t i; size_t entry, length, number_entries, tag, tag_value; SplayTreeInfo *exif_resources; ssize_t all, id, level, offset, tag_offset; static int tag_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; /* If EXIF data exists, then try to parse the request for a tag. */ profile=GetImageProfile(image,"exif"); if (profile == (const StringInfo *) NULL) return(MagickFalse); if ((property == (const char *) NULL) || (*property == '\0')) return(MagickFalse); while (isspace((int) ((unsigned char) *property)) != 0) property++; if (strlen(property) <= 5) return(MagickFalse); all=0; tag=(~0UL); switch (*(property+5)) { case '*': { /* Caller has asked for all the tags in the EXIF data. */ tag=0; all=1; /* return the data in description=value format */ break; } case '!': { tag=0; all=2; /* return the data in tagid=value format */ break; } case '#': case '@': { int c; size_t n; /* Check for a hex based tag specification first. */ tag=(*(property+5) == '@') ? 1UL : 0UL; property+=6; n=strlen(property); if (n != 4) return(MagickFalse); /* Parse tag specification as a hex number. */ n/=4; do { for (i=(ssize_t) n-1L; i >= 0; i--) { c=(*property++); tag<<=4; if ((c >= '0') && (c <= '9')) tag|=(c-'0'); else if ((c >= 'A') && (c <= 'F')) tag|=(c-('A'-10)); else if ((c >= 'a') && (c <= 'f')) tag|=(c-('a'-10)); else return(MagickFalse); } } while (*property != '\0'); break; } default: { /* Try to match the text with a tag name instead. */ for (i=0; ; i++) { if (EXIFTag[i].tag == 0) break; if (LocaleCompare(EXIFTag[i].description,property) == 0) { tag=(size_t) EXIFTag[i].tag; break; } } break; } } if (tag == (~0UL)) return(MagickFalse); length=GetStringInfoLength(profile); exif=GetStringInfoDatum(profile); while (length != 0) { if (ReadPropertyByte(&exif,&length) != 0x45) continue; if (ReadPropertyByte(&exif,&length) != 0x78) continue; if (ReadPropertyByte(&exif,&length) != 0x69) continue; if (ReadPropertyByte(&exif,&length) != 0x66) continue; if (ReadPropertyByte(&exif,&length) != 0x00) continue; if (ReadPropertyByte(&exif,&length) != 0x00) continue; break; } if (length < 16) return(MagickFalse); id=(ssize_t) ReadPropertySignedShort(LSBEndian,exif); endian=LSBEndian; if (id == 0x4949) endian=LSBEndian; else if (id == 0x4D4D) endian=MSBEndian; else return(MagickFalse); if (ReadPropertyUnsignedShort(endian,exif+2) != 0x002a) return(MagickFalse); /* This the offset to the first IFD. */ offset=(ssize_t) ReadPropertySignedLong(endian,exif+4); if ((offset < 0) || (size_t) offset >= length) return(MagickFalse); /* Set the pointer to the first IFD and follow it were it leads. */ status=MagickFalse; directory=exif+offset; level=0; entry=0; tag_offset=0; exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL, (void *(*)(void *)) NULL,(void *(*)(void *)) NULL); do { /* If there is anything on the stack then pop it off. */ if (level > 0) { level--; directory=directory_stack[level].directory; entry=directory_stack[level].entry; tag_offset=directory_stack[level].offset; } if ((directory < exif) || (directory > (exif+length-2))) break; /* Determine how many entries there are in the current IFD. */ number_entries=(size_t) ReadPropertyUnsignedShort(endian,directory); for ( ; entry < number_entries; entry++) { register unsigned char *p, *q; size_t format; ssize_t number_bytes, components; q=(unsigned char *) (directory+(12*entry)+2); if (GetValueFromSplayTree(exif_resources,q) == q) break; (void) AddValueToSplayTree(exif_resources,q,q); tag_value=(size_t) ReadPropertyUnsignedShort(endian,q)+tag_offset; format=(size_t) ReadPropertyUnsignedShort(endian,q+2); if (format >= (sizeof(tag_bytes)/sizeof(*tag_bytes))) break; components=(ssize_t) ReadPropertySignedLong(endian,q+4); number_bytes=(size_t) components*tag_bytes[format]; if (number_bytes < components) break; /* prevent overflow */ if (number_bytes <= 4) p=q+8; else { ssize_t offset; /* The directory entry contains an offset. */ offset=(ssize_t) ReadPropertySignedLong(endian,q+8); if ((offset < 0) || (size_t) offset >= length) continue; if ((ssize_t) (offset+number_bytes) < offset) continue; /* prevent overflow */ if ((size_t) (offset+number_bytes) > length) continue; p=(unsigned char *) (exif+offset); } if ((all != 0) || (tag == (size_t) tag_value)) { char buffer[MagickPathExtent], *value; value=(char *) NULL; *buffer='\0'; switch (format) { case EXIF_FMT_BYTE: case EXIF_FMT_UNDEFINED: { EXIFMultipleValues(1,"%.20g",(double) (*(unsigned char *) p1)); break; } case EXIF_FMT_SBYTE: { EXIFMultipleValues(1,"%.20g",(double) (*(signed char *) p1)); break; } case EXIF_FMT_SSHORT: { EXIFMultipleValues(2,"%hd",ReadPropertySignedShort(endian,p1)); break; } case EXIF_FMT_USHORT: { EXIFMultipleValues(2,"%hu",ReadPropertyUnsignedShort(endian,p1)); break; } case EXIF_FMT_ULONG: { EXIFMultipleValues(4,"%.20g",(double) ReadPropertyUnsignedLong(endian,p1)); break; } case EXIF_FMT_SLONG: { EXIFMultipleValues(4,"%.20g",(double) ReadPropertySignedLong(endian,p1)); break; } case EXIF_FMT_URATIONAL: { EXIFMultipleFractions(8,"%.20g/%.20g",(double) ReadPropertyUnsignedLong(endian,p1),(double) ReadPropertyUnsignedLong(endian,p1+4)); break; } case EXIF_FMT_SRATIONAL: { EXIFMultipleFractions(8,"%.20g/%.20g",(double) ReadPropertySignedLong(endian,p1),(double) ReadPropertySignedLong(endian,p1+4)); break; } case EXIF_FMT_SINGLE: { EXIFMultipleValues(4,"%f",(double) *(float *) p1); break; } case EXIF_FMT_DOUBLE: { EXIFMultipleValues(8,"%f",*(double *) p1); break; } default: case EXIF_FMT_STRING: { value=(char *) NULL; if (~((size_t) number_bytes) >= 1) value=(char *) AcquireQuantumMemory((size_t) number_bytes+1UL, sizeof(*value)); if (value != (char *) NULL) { register ssize_t i; for (i=0; i < (ssize_t) number_bytes; i++) { value[i]='.'; if ((isprint((int) p[i]) != 0) || (p[i] == '\0')) value[i]=(char) p[i]; } value[i]='\0'; } break; } } if (value != (char *) NULL) { char *key; register const char *p; key=AcquireString(property); switch (all) { case 1: { const char *description; register ssize_t i; description="unknown"; for (i=0; ; i++) { if (EXIFTag[i].tag == 0) break; if (EXIFTag[i].tag == tag_value) { description=EXIFTag[i].description; break; } } (void) FormatLocaleString(key,MagickPathExtent,"%s", description); if (level == 2) (void) SubstituteString(&key,"exif:","exif:thumbnail:"); break; } case 2: { if (tag_value < 0x10000) (void) FormatLocaleString(key,MagickPathExtent,"#%04lx", (unsigned long) tag_value); else if (tag_value < 0x20000) (void) FormatLocaleString(key,MagickPathExtent,"@%04lx", (unsigned long) (tag_value & 0xffff)); else (void) FormatLocaleString(key,MagickPathExtent,"unknown"); break; } default: { if (level == 2) (void) SubstituteString(&key,"exif:","exif:thumbnail:"); } } p=(const char *) NULL; if (image->properties != (void *) NULL) p=(const char *) GetValueFromSplayTree((SplayTreeInfo *) image->properties,key); if (p == (const char *) NULL) (void) SetImageProperty((Image *) image,key,value,exception); value=DestroyString(value); key=DestroyString(key); status=MagickTrue; } } if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET) || (tag_value == TAG_GPS_OFFSET)) { ssize_t offset; offset=(ssize_t) ReadPropertySignedLong(endian,p); if (((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { ssize_t tag_offset1; tag_offset1=(ssize_t) ((tag_value == TAG_GPS_OFFSET) ? 0x10000 : 0); directory_stack[level].directory=directory; entry++; directory_stack[level].entry=entry; directory_stack[level].offset=tag_offset; level++; directory_stack[level].directory=exif+offset; directory_stack[level].offset=tag_offset1; directory_stack[level].entry=0; level++; if ((directory+2+(12*number_entries)) > (exif+length)) break; offset=(ssize_t) ReadPropertySignedLong(endian,directory+2+(12* number_entries)); if ((offset != 0) && ((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; directory_stack[level].offset=tag_offset1; level++; } } break; } } } while (level > 0); exif_resources=DestroySplayTree(exif_resources); return(status); } Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed) CWE ID: CWE-125
static MagickBooleanType GetEXIFProperty(const Image *image, const char *property,ExceptionInfo *exception) { #define MaxDirectoryStack 16 #define EXIF_DELIMITER "\n" #define EXIF_NUM_FORMATS 12 #define EXIF_FMT_BYTE 1 #define EXIF_FMT_STRING 2 #define EXIF_FMT_USHORT 3 #define EXIF_FMT_ULONG 4 #define EXIF_FMT_URATIONAL 5 #define EXIF_FMT_SBYTE 6 #define EXIF_FMT_UNDEFINED 7 #define EXIF_FMT_SSHORT 8 #define EXIF_FMT_SLONG 9 #define EXIF_FMT_SRATIONAL 10 #define EXIF_FMT_SINGLE 11 #define EXIF_FMT_DOUBLE 12 #define TAG_EXIF_OFFSET 0x8769 #define TAG_GPS_OFFSET 0x8825 #define TAG_INTEROP_OFFSET 0xa005 #define EXIFMultipleValues(size,format,arg) \ { \ ssize_t \ component; \ \ size_t \ length; \ \ unsigned char \ *p1; \ \ length=0; \ p1=p; \ for (component=0; component < components; component++) \ { \ length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \ format", ",arg); \ if (length >= (MagickPathExtent-1)) \ length=MagickPathExtent-1; \ p1+=size; \ } \ if (length > 1) \ buffer[length-2]='\0'; \ value=AcquireString(buffer); \ } #define EXIFMultipleFractions(size,format,arg1,arg2) \ { \ ssize_t \ component; \ \ size_t \ length; \ \ unsigned char \ *p1; \ \ length=0; \ p1=p; \ for (component=0; component < components; component++) \ { \ length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \ format", ",(arg1),(arg2)); \ if (length >= (MagickPathExtent-1)) \ length=MagickPathExtent-1; \ p1+=size; \ } \ if (length > 1) \ buffer[length-2]='\0'; \ value=AcquireString(buffer); \ } typedef struct _DirectoryInfo { const unsigned char *directory; size_t entry; ssize_t offset; } DirectoryInfo; typedef struct _TagInfo { size_t tag; const char *description; } TagInfo; static TagInfo EXIFTag[] = { { 0x001, "exif:InteroperabilityIndex" }, { 0x002, "exif:InteroperabilityVersion" }, { 0x100, "exif:ImageWidth" }, { 0x101, "exif:ImageLength" }, { 0x102, "exif:BitsPerSample" }, { 0x103, "exif:Compression" }, { 0x106, "exif:PhotometricInterpretation" }, { 0x10a, "exif:FillOrder" }, { 0x10d, "exif:DocumentName" }, { 0x10e, "exif:ImageDescription" }, { 0x10f, "exif:Make" }, { 0x110, "exif:Model" }, { 0x111, "exif:StripOffsets" }, { 0x112, "exif:Orientation" }, { 0x115, "exif:SamplesPerPixel" }, { 0x116, "exif:RowsPerStrip" }, { 0x117, "exif:StripByteCounts" }, { 0x11a, "exif:XResolution" }, { 0x11b, "exif:YResolution" }, { 0x11c, "exif:PlanarConfiguration" }, { 0x11d, "exif:PageName" }, { 0x11e, "exif:XPosition" }, { 0x11f, "exif:YPosition" }, { 0x118, "exif:MinSampleValue" }, { 0x119, "exif:MaxSampleValue" }, { 0x120, "exif:FreeOffsets" }, { 0x121, "exif:FreeByteCounts" }, { 0x122, "exif:GrayResponseUnit" }, { 0x123, "exif:GrayResponseCurve" }, { 0x124, "exif:T4Options" }, { 0x125, "exif:T6Options" }, { 0x128, "exif:ResolutionUnit" }, { 0x12d, "exif:TransferFunction" }, { 0x131, "exif:Software" }, { 0x132, "exif:DateTime" }, { 0x13b, "exif:Artist" }, { 0x13e, "exif:WhitePoint" }, { 0x13f, "exif:PrimaryChromaticities" }, { 0x140, "exif:ColorMap" }, { 0x141, "exif:HalfToneHints" }, { 0x142, "exif:TileWidth" }, { 0x143, "exif:TileLength" }, { 0x144, "exif:TileOffsets" }, { 0x145, "exif:TileByteCounts" }, { 0x14a, "exif:SubIFD" }, { 0x14c, "exif:InkSet" }, { 0x14d, "exif:InkNames" }, { 0x14e, "exif:NumberOfInks" }, { 0x150, "exif:DotRange" }, { 0x151, "exif:TargetPrinter" }, { 0x152, "exif:ExtraSample" }, { 0x153, "exif:SampleFormat" }, { 0x154, "exif:SMinSampleValue" }, { 0x155, "exif:SMaxSampleValue" }, { 0x156, "exif:TransferRange" }, { 0x157, "exif:ClipPath" }, { 0x158, "exif:XClipPathUnits" }, { 0x159, "exif:YClipPathUnits" }, { 0x15a, "exif:Indexed" }, { 0x15b, "exif:JPEGTables" }, { 0x15f, "exif:OPIProxy" }, { 0x200, "exif:JPEGProc" }, { 0x201, "exif:JPEGInterchangeFormat" }, { 0x202, "exif:JPEGInterchangeFormatLength" }, { 0x203, "exif:JPEGRestartInterval" }, { 0x205, "exif:JPEGLosslessPredictors" }, { 0x206, "exif:JPEGPointTransforms" }, { 0x207, "exif:JPEGQTables" }, { 0x208, "exif:JPEGDCTables" }, { 0x209, "exif:JPEGACTables" }, { 0x211, "exif:YCbCrCoefficients" }, { 0x212, "exif:YCbCrSubSampling" }, { 0x213, "exif:YCbCrPositioning" }, { 0x214, "exif:ReferenceBlackWhite" }, { 0x2bc, "exif:ExtensibleMetadataPlatform" }, { 0x301, "exif:Gamma" }, { 0x302, "exif:ICCProfileDescriptor" }, { 0x303, "exif:SRGBRenderingIntent" }, { 0x320, "exif:ImageTitle" }, { 0x5001, "exif:ResolutionXUnit" }, { 0x5002, "exif:ResolutionYUnit" }, { 0x5003, "exif:ResolutionXLengthUnit" }, { 0x5004, "exif:ResolutionYLengthUnit" }, { 0x5005, "exif:PrintFlags" }, { 0x5006, "exif:PrintFlagsVersion" }, { 0x5007, "exif:PrintFlagsCrop" }, { 0x5008, "exif:PrintFlagsBleedWidth" }, { 0x5009, "exif:PrintFlagsBleedWidthScale" }, { 0x500A, "exif:HalftoneLPI" }, { 0x500B, "exif:HalftoneLPIUnit" }, { 0x500C, "exif:HalftoneDegree" }, { 0x500D, "exif:HalftoneShape" }, { 0x500E, "exif:HalftoneMisc" }, { 0x500F, "exif:HalftoneScreen" }, { 0x5010, "exif:JPEGQuality" }, { 0x5011, "exif:GridSize" }, { 0x5012, "exif:ThumbnailFormat" }, { 0x5013, "exif:ThumbnailWidth" }, { 0x5014, "exif:ThumbnailHeight" }, { 0x5015, "exif:ThumbnailColorDepth" }, { 0x5016, "exif:ThumbnailPlanes" }, { 0x5017, "exif:ThumbnailRawBytes" }, { 0x5018, "exif:ThumbnailSize" }, { 0x5019, "exif:ThumbnailCompressedSize" }, { 0x501a, "exif:ColorTransferFunction" }, { 0x501b, "exif:ThumbnailData" }, { 0x5020, "exif:ThumbnailImageWidth" }, { 0x5021, "exif:ThumbnailImageHeight" }, { 0x5022, "exif:ThumbnailBitsPerSample" }, { 0x5023, "exif:ThumbnailCompression" }, { 0x5024, "exif:ThumbnailPhotometricInterp" }, { 0x5025, "exif:ThumbnailImageDescription" }, { 0x5026, "exif:ThumbnailEquipMake" }, { 0x5027, "exif:ThumbnailEquipModel" }, { 0x5028, "exif:ThumbnailStripOffsets" }, { 0x5029, "exif:ThumbnailOrientation" }, { 0x502a, "exif:ThumbnailSamplesPerPixel" }, { 0x502b, "exif:ThumbnailRowsPerStrip" }, { 0x502c, "exif:ThumbnailStripBytesCount" }, { 0x502d, "exif:ThumbnailResolutionX" }, { 0x502e, "exif:ThumbnailResolutionY" }, { 0x502f, "exif:ThumbnailPlanarConfig" }, { 0x5030, "exif:ThumbnailResolutionUnit" }, { 0x5031, "exif:ThumbnailTransferFunction" }, { 0x5032, "exif:ThumbnailSoftwareUsed" }, { 0x5033, "exif:ThumbnailDateTime" }, { 0x5034, "exif:ThumbnailArtist" }, { 0x5035, "exif:ThumbnailWhitePoint" }, { 0x5036, "exif:ThumbnailPrimaryChromaticities" }, { 0x5037, "exif:ThumbnailYCbCrCoefficients" }, { 0x5038, "exif:ThumbnailYCbCrSubsampling" }, { 0x5039, "exif:ThumbnailYCbCrPositioning" }, { 0x503A, "exif:ThumbnailRefBlackWhite" }, { 0x503B, "exif:ThumbnailCopyRight" }, { 0x5090, "exif:LuminanceTable" }, { 0x5091, "exif:ChrominanceTable" }, { 0x5100, "exif:FrameDelay" }, { 0x5101, "exif:LoopCount" }, { 0x5110, "exif:PixelUnit" }, { 0x5111, "exif:PixelPerUnitX" }, { 0x5112, "exif:PixelPerUnitY" }, { 0x5113, "exif:PaletteHistogram" }, { 0x1000, "exif:RelatedImageFileFormat" }, { 0x1001, "exif:RelatedImageLength" }, { 0x1002, "exif:RelatedImageWidth" }, { 0x800d, "exif:ImageID" }, { 0x80e3, "exif:Matteing" }, { 0x80e4, "exif:DataType" }, { 0x80e5, "exif:ImageDepth" }, { 0x80e6, "exif:TileDepth" }, { 0x828d, "exif:CFARepeatPatternDim" }, { 0x828e, "exif:CFAPattern2" }, { 0x828f, "exif:BatteryLevel" }, { 0x8298, "exif:Copyright" }, { 0x829a, "exif:ExposureTime" }, { 0x829d, "exif:FNumber" }, { 0x83bb, "exif:IPTC/NAA" }, { 0x84e3, "exif:IT8RasterPadding" }, { 0x84e5, "exif:IT8ColorTable" }, { 0x8649, "exif:ImageResourceInformation" }, { 0x8769, "exif:ExifOffset" }, { 0x8773, "exif:InterColorProfile" }, { 0x8822, "exif:ExposureProgram" }, { 0x8824, "exif:SpectralSensitivity" }, { 0x8825, "exif:GPSInfo" }, { 0x8827, "exif:ISOSpeedRatings" }, { 0x8828, "exif:OECF" }, { 0x8829, "exif:Interlace" }, { 0x882a, "exif:TimeZoneOffset" }, { 0x882b, "exif:SelfTimerMode" }, { 0x9000, "exif:ExifVersion" }, { 0x9003, "exif:DateTimeOriginal" }, { 0x9004, "exif:DateTimeDigitized" }, { 0x9101, "exif:ComponentsConfiguration" }, { 0x9102, "exif:CompressedBitsPerPixel" }, { 0x9201, "exif:ShutterSpeedValue" }, { 0x9202, "exif:ApertureValue" }, { 0x9203, "exif:BrightnessValue" }, { 0x9204, "exif:ExposureBiasValue" }, { 0x9205, "exif:MaxApertureValue" }, { 0x9206, "exif:SubjectDistance" }, { 0x9207, "exif:MeteringMode" }, { 0x9208, "exif:LightSource" }, { 0x9209, "exif:Flash" }, { 0x920a, "exif:FocalLength" }, { 0x920b, "exif:FlashEnergy" }, { 0x920c, "exif:SpatialFrequencyResponse" }, { 0x920d, "exif:Noise" }, { 0x9211, "exif:ImageNumber" }, { 0x9212, "exif:SecurityClassification" }, { 0x9213, "exif:ImageHistory" }, { 0x9214, "exif:SubjectArea" }, { 0x9215, "exif:ExposureIndex" }, { 0x9216, "exif:TIFF-EPStandardID" }, { 0x927c, "exif:MakerNote" }, { 0x9C9b, "exif:WinXP-Title" }, { 0x9C9c, "exif:WinXP-Comments" }, { 0x9C9d, "exif:WinXP-Author" }, { 0x9C9e, "exif:WinXP-Keywords" }, { 0x9C9f, "exif:WinXP-Subject" }, { 0x9286, "exif:UserComment" }, { 0x9290, "exif:SubSecTime" }, { 0x9291, "exif:SubSecTimeOriginal" }, { 0x9292, "exif:SubSecTimeDigitized" }, { 0xa000, "exif:FlashPixVersion" }, { 0xa001, "exif:ColorSpace" }, { 0xa002, "exif:ExifImageWidth" }, { 0xa003, "exif:ExifImageLength" }, { 0xa004, "exif:RelatedSoundFile" }, { 0xa005, "exif:InteroperabilityOffset" }, { 0xa20b, "exif:FlashEnergy" }, { 0xa20c, "exif:SpatialFrequencyResponse" }, { 0xa20d, "exif:Noise" }, { 0xa20e, "exif:FocalPlaneXResolution" }, { 0xa20f, "exif:FocalPlaneYResolution" }, { 0xa210, "exif:FocalPlaneResolutionUnit" }, { 0xa214, "exif:SubjectLocation" }, { 0xa215, "exif:ExposureIndex" }, { 0xa216, "exif:TIFF/EPStandardID" }, { 0xa217, "exif:SensingMethod" }, { 0xa300, "exif:FileSource" }, { 0xa301, "exif:SceneType" }, { 0xa302, "exif:CFAPattern" }, { 0xa401, "exif:CustomRendered" }, { 0xa402, "exif:ExposureMode" }, { 0xa403, "exif:WhiteBalance" }, { 0xa404, "exif:DigitalZoomRatio" }, { 0xa405, "exif:FocalLengthIn35mmFilm" }, { 0xa406, "exif:SceneCaptureType" }, { 0xa407, "exif:GainControl" }, { 0xa408, "exif:Contrast" }, { 0xa409, "exif:Saturation" }, { 0xa40a, "exif:Sharpness" }, { 0xa40b, "exif:DeviceSettingDescription" }, { 0xa40c, "exif:SubjectDistanceRange" }, { 0xa420, "exif:ImageUniqueID" }, { 0xc4a5, "exif:PrintImageMatching" }, { 0xa500, "exif:Gamma" }, { 0xc640, "exif:CR2Slice" }, { 0x10000, "exif:GPSVersionID" }, { 0x10001, "exif:GPSLatitudeRef" }, { 0x10002, "exif:GPSLatitude" }, { 0x10003, "exif:GPSLongitudeRef" }, { 0x10004, "exif:GPSLongitude" }, { 0x10005, "exif:GPSAltitudeRef" }, { 0x10006, "exif:GPSAltitude" }, { 0x10007, "exif:GPSTimeStamp" }, { 0x10008, "exif:GPSSatellites" }, { 0x10009, "exif:GPSStatus" }, { 0x1000a, "exif:GPSMeasureMode" }, { 0x1000b, "exif:GPSDop" }, { 0x1000c, "exif:GPSSpeedRef" }, { 0x1000d, "exif:GPSSpeed" }, { 0x1000e, "exif:GPSTrackRef" }, { 0x1000f, "exif:GPSTrack" }, { 0x10010, "exif:GPSImgDirectionRef" }, { 0x10011, "exif:GPSImgDirection" }, { 0x10012, "exif:GPSMapDatum" }, { 0x10013, "exif:GPSDestLatitudeRef" }, { 0x10014, "exif:GPSDestLatitude" }, { 0x10015, "exif:GPSDestLongitudeRef" }, { 0x10016, "exif:GPSDestLongitude" }, { 0x10017, "exif:GPSDestBearingRef" }, { 0x10018, "exif:GPSDestBearing" }, { 0x10019, "exif:GPSDestDistanceRef" }, { 0x1001a, "exif:GPSDestDistance" }, { 0x1001b, "exif:GPSProcessingMethod" }, { 0x1001c, "exif:GPSAreaInformation" }, { 0x1001d, "exif:GPSDateStamp" }, { 0x1001e, "exif:GPSDifferential" }, { 0x00000, (const char *) NULL } }; const StringInfo *profile; const unsigned char *directory, *exif; DirectoryInfo directory_stack[MaxDirectoryStack]; EndianType endian; MagickBooleanType status; register ssize_t i; size_t entry, length, number_entries, tag, tag_value; SplayTreeInfo *exif_resources; ssize_t all, id, level, offset, tag_offset; static int tag_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; /* If EXIF data exists, then try to parse the request for a tag. */ profile=GetImageProfile(image,"exif"); if (profile == (const StringInfo *) NULL) return(MagickFalse); if ((property == (const char *) NULL) || (*property == '\0')) return(MagickFalse); while (isspace((int) ((unsigned char) *property)) != 0) property++; if (strlen(property) <= 5) return(MagickFalse); all=0; tag=(~0UL); switch (*(property+5)) { case '*': { /* Caller has asked for all the tags in the EXIF data. */ tag=0; all=1; /* return the data in description=value format */ break; } case '!': { tag=0; all=2; /* return the data in tagid=value format */ break; } case '#': case '@': { int c; size_t n; /* Check for a hex based tag specification first. */ tag=(*(property+5) == '@') ? 1UL : 0UL; property+=6; n=strlen(property); if (n != 4) return(MagickFalse); /* Parse tag specification as a hex number. */ n/=4; do { for (i=(ssize_t) n-1L; i >= 0; i--) { c=(*property++); tag<<=4; if ((c >= '0') && (c <= '9')) tag|=(c-'0'); else if ((c >= 'A') && (c <= 'F')) tag|=(c-('A'-10)); else if ((c >= 'a') && (c <= 'f')) tag|=(c-('a'-10)); else return(MagickFalse); } } while (*property != '\0'); break; } default: { /* Try to match the text with a tag name instead. */ for (i=0; ; i++) { if (EXIFTag[i].tag == 0) break; if (LocaleCompare(EXIFTag[i].description,property) == 0) { tag=(size_t) EXIFTag[i].tag; break; } } break; } } if (tag == (~0UL)) return(MagickFalse); length=GetStringInfoLength(profile); exif=GetStringInfoDatum(profile); while (length != 0) { if (ReadPropertyByte(&exif,&length) != 0x45) continue; if (ReadPropertyByte(&exif,&length) != 0x78) continue; if (ReadPropertyByte(&exif,&length) != 0x69) continue; if (ReadPropertyByte(&exif,&length) != 0x66) continue; if (ReadPropertyByte(&exif,&length) != 0x00) continue; if (ReadPropertyByte(&exif,&length) != 0x00) continue; break; } if (length < 16) return(MagickFalse); id=(ssize_t) ReadPropertySignedShort(LSBEndian,exif); endian=LSBEndian; if (id == 0x4949) endian=LSBEndian; else if (id == 0x4D4D) endian=MSBEndian; else return(MagickFalse); if (ReadPropertyUnsignedShort(endian,exif+2) != 0x002a) return(MagickFalse); /* This the offset to the first IFD. */ offset=(ssize_t) ReadPropertySignedLong(endian,exif+4); if ((offset < 0) || (size_t) offset >= length) return(MagickFalse); /* Set the pointer to the first IFD and follow it were it leads. */ status=MagickFalse; directory=exif+offset; level=0; entry=0; tag_offset=0; exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL, (void *(*)(void *)) NULL,(void *(*)(void *)) NULL); do { /* If there is anything on the stack then pop it off. */ if (level > 0) { level--; directory=directory_stack[level].directory; entry=directory_stack[level].entry; tag_offset=directory_stack[level].offset; } if ((directory < exif) || (directory > (exif+length-2))) break; /* Determine how many entries there are in the current IFD. */ number_entries=(size_t) ReadPropertyUnsignedShort(endian,directory); for ( ; entry < number_entries; entry++) { register unsigned char *p, *q; size_t format; ssize_t number_bytes, components; q=(unsigned char *) (directory+(12*entry)+2); if (q > (exif+length-12)) break; /* corrupt EXIF */ if (GetValueFromSplayTree(exif_resources,q) == q) break; (void) AddValueToSplayTree(exif_resources,q,q); tag_value=(size_t) ReadPropertyUnsignedShort(endian,q)+tag_offset; format=(size_t) ReadPropertyUnsignedShort(endian,q+2); if (format >= (sizeof(tag_bytes)/sizeof(*tag_bytes))) break; components=(ssize_t) ReadPropertySignedLong(endian,q+4); if (components < 0) break; /* corrupt EXIF */ number_bytes=(size_t) components*tag_bytes[format]; if (number_bytes < components) break; /* prevent overflow */ if (number_bytes <= 4) p=q+8; else { ssize_t offset; /* The directory entry contains an offset. */ offset=(ssize_t) ReadPropertySignedLong(endian,q+8); if ((offset < 0) || (size_t) offset >= length) continue; if ((ssize_t) (offset+number_bytes) < offset) continue; /* prevent overflow */ if ((size_t) (offset+number_bytes) > length) continue; p=(unsigned char *) (exif+offset); } if ((all != 0) || (tag == (size_t) tag_value)) { char buffer[MagickPathExtent], *value; value=(char *) NULL; *buffer='\0'; switch (format) { case EXIF_FMT_BYTE: case EXIF_FMT_UNDEFINED: { EXIFMultipleValues(1,"%.20g",(double) (*(unsigned char *) p1)); break; } case EXIF_FMT_SBYTE: { EXIFMultipleValues(1,"%.20g",(double) (*(signed char *) p1)); break; } case EXIF_FMT_SSHORT: { EXIFMultipleValues(2,"%hd",ReadPropertySignedShort(endian,p1)); break; } case EXIF_FMT_USHORT: { EXIFMultipleValues(2,"%hu",ReadPropertyUnsignedShort(endian,p1)); break; } case EXIF_FMT_ULONG: { EXIFMultipleValues(4,"%.20g",(double) ReadPropertyUnsignedLong(endian,p1)); break; } case EXIF_FMT_SLONG: { EXIFMultipleValues(4,"%.20g",(double) ReadPropertySignedLong(endian,p1)); break; } case EXIF_FMT_URATIONAL: { EXIFMultipleFractions(8,"%.20g/%.20g",(double) ReadPropertyUnsignedLong(endian,p1),(double) ReadPropertyUnsignedLong(endian,p1+4)); break; } case EXIF_FMT_SRATIONAL: { EXIFMultipleFractions(8,"%.20g/%.20g",(double) ReadPropertySignedLong(endian,p1),(double) ReadPropertySignedLong(endian,p1+4)); break; } case EXIF_FMT_SINGLE: { EXIFMultipleValues(4,"%f",(double) *(float *) p1); break; } case EXIF_FMT_DOUBLE: { EXIFMultipleValues(8,"%f",*(double *) p1); break; } default: case EXIF_FMT_STRING: { value=(char *) NULL; if (~((size_t) number_bytes) >= 1) value=(char *) AcquireQuantumMemory((size_t) number_bytes+1UL, sizeof(*value)); if (value != (char *) NULL) { register ssize_t i; for (i=0; i < (ssize_t) number_bytes; i++) { value[i]='.'; if ((isprint((int) p[i]) != 0) || (p[i] == '\0')) value[i]=(char) p[i]; } value[i]='\0'; } break; } } if (value != (char *) NULL) { char *key; register const char *p; key=AcquireString(property); switch (all) { case 1: { const char *description; register ssize_t i; description="unknown"; for (i=0; ; i++) { if (EXIFTag[i].tag == 0) break; if (EXIFTag[i].tag == tag_value) { description=EXIFTag[i].description; break; } } (void) FormatLocaleString(key,MagickPathExtent,"%s", description); if (level == 2) (void) SubstituteString(&key,"exif:","exif:thumbnail:"); break; } case 2: { if (tag_value < 0x10000) (void) FormatLocaleString(key,MagickPathExtent,"#%04lx", (unsigned long) tag_value); else if (tag_value < 0x20000) (void) FormatLocaleString(key,MagickPathExtent,"@%04lx", (unsigned long) (tag_value & 0xffff)); else (void) FormatLocaleString(key,MagickPathExtent,"unknown"); break; } default: { if (level == 2) (void) SubstituteString(&key,"exif:","exif:thumbnail:"); } } p=(const char *) NULL; if (image->properties != (void *) NULL) p=(const char *) GetValueFromSplayTree((SplayTreeInfo *) image->properties,key); if (p == (const char *) NULL) (void) SetImageProperty((Image *) image,key,value,exception); value=DestroyString(value); key=DestroyString(key); status=MagickTrue; } } if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET) || (tag_value == TAG_GPS_OFFSET)) { ssize_t offset; offset=(ssize_t) ReadPropertySignedLong(endian,p); if (((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { ssize_t tag_offset1; tag_offset1=(ssize_t) ((tag_value == TAG_GPS_OFFSET) ? 0x10000 : 0); directory_stack[level].directory=directory; entry++; directory_stack[level].entry=entry; directory_stack[level].offset=tag_offset; level++; directory_stack[level].directory=exif+offset; directory_stack[level].offset=tag_offset1; directory_stack[level].entry=0; level++; if ((directory+2+(12*number_entries)) > (exif+length)) break; offset=(ssize_t) ReadPropertySignedLong(endian,directory+2+(12* number_entries)); if ((offset != 0) && ((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; directory_stack[level].offset=tag_offset1; level++; } } break; } } } while (level > 0); exif_resources=DestroySplayTree(exif_resources); return(status); }
169,951
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 Browser::FindInPage(bool find_next, bool forward_direction) { ShowFindBar(); if (find_next) { string16 find_text; #if defined(OS_MACOSX) find_text = GetFindPboardText(); #endif GetSelectedTabContentsWrapper()-> GetFindManager()->StartFinding(find_text, forward_direction, false); // Not case sensitive. } } Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature. BUG=71097 TEST=zero visible change Review URL: http://codereview.chromium.org/6480117 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void Browser::FindInPage(bool find_next, bool forward_direction) { ShowFindBar(); if (find_next) { string16 find_text; #if defined(OS_MACOSX) find_text = GetFindPboardText(); #endif GetSelectedTabContentsWrapper()-> find_tab_helper()->StartFinding(find_text, forward_direction, false); // Not case sensitive. } }
170,656
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 ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al) { unsigned short length; unsigned short type; unsigned short size; unsigned char *data = *p; int tlsext_servername = 0; int renegotiate_seen = 0; # ifndef OPENSSL_NO_NEXTPROTONEG s->s3->next_proto_neg_seen = 0; # endif s->tlsext_ticket_expected = 0; if (s->s3->alpn_selected) { OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = NULL; } # ifndef OPENSSL_NO_HEARTBEATS s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED | SSL_TLSEXT_HB_DONT_SEND_REQUESTS); # endif if (data >= (d + n - 2)) goto ri_check; n2s(data, length); if (data + length != d + n) { *al = SSL_AD_DECODE_ERROR; return 0; } while (data <= (d + n - 4)) { n2s(data, type); n2s(data, size); if (data + size > (d + n)) goto ri_check; if (s->tlsext_debug_cb) s->tlsext_debug_cb(s, 1, type, data, size, s->tlsext_debug_arg); if (type == TLSEXT_TYPE_server_name) { if (s->tlsext_hostname == NULL || size > 0) { *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } tlsext_servername = 1; } # ifndef OPENSSL_NO_EC else if (type == TLSEXT_TYPE_ec_point_formats) { unsigned char *sdata = data; int ecpointformatlist_length = *(sdata++); if (ecpointformatlist_length != size - 1) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (!s->hit) { s->session->tlsext_ecpointformatlist_length = 0; if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist); if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length; memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length); } # if 0 fprintf(stderr, "ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist "); sdata = s->session->tlsext_ecpointformatlist; for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) fprintf(stderr, "%i ", *(sdata++)); fprintf(stderr, "\n"); # endif } # endif /* OPENSSL_NO_EC */ else if (type == TLSEXT_TYPE_session_ticket) { if (s->tls_session_ticket_ext_cb && !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } if ((SSL_get_options(s) & SSL_OP_NO_TICKET) || (size > 0)) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } s->tlsext_ticket_expected = 1; } # ifdef TLSEXT_TYPE_opaque_prf_input else if (type == TLSEXT_TYPE_opaque_prf_input) { unsigned char *sdata = data; if (size < 2) { *al = SSL_AD_DECODE_ERROR; return 0; } n2s(sdata, s->s3->server_opaque_prf_input_len); if (s->s3->server_opaque_prf_input_len != size - 2) { *al = SSL_AD_DECODE_ERROR; return 0; } if (s->s3->server_opaque_prf_input != NULL) { /* shouldn't really happen */ OPENSSL_free(s->s3->server_opaque_prf_input); } if (s->s3->server_opaque_prf_input_len == 0) { /* dummy byte just to get non-NULL */ s->s3->server_opaque_prf_input = OPENSSL_malloc(1); } else { s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len); } if (s->s3->server_opaque_prf_input == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } # endif else if (type == TLSEXT_TYPE_status_request) { /* * MUST be empty and only sent if we've requested a status * request message. */ if ((s->tlsext_status_type == -1) || (size > 0)) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } /* Set flag to expect CertificateStatus message */ s->tlsext_status_expected = 1; } # ifndef OPENSSL_NO_NEXTPROTONEG else if (type == TLSEXT_TYPE_next_proto_neg && s->s3->tmp.finish_md_len == 0) { unsigned char *selected; unsigned char selected_len; /* We must have requested it. */ if (s->ctx->next_proto_select_cb == NULL) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } /* The data must be valid */ if (!ssl_next_proto_validate(data, size)) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (s-> ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->next_proto_negotiated = OPENSSL_malloc(selected_len); if (!s->next_proto_negotiated) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->next_proto_negotiated, selected, selected_len); s->next_proto_negotiated_len = selected_len; s->s3->next_proto_neg_seen = 1; } # endif else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation) { unsigned len; /* We must have requested it. */ if (!s->cert->alpn_sent) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } if (size < 4) { *al = TLS1_AD_DECODE_ERROR; return 0; } /*- * The extension data consists of: * uint16 list_length * uint8 proto_length; * uint8 proto[proto_length]; */ len = data[0]; len <<= 8; len |= data[1]; if (len != (unsigned)size - 2) { *al = TLS1_AD_DECODE_ERROR; return 0; } len = data[2]; if (len != (unsigned)size - 3) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (s->s3->alpn_selected) OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = OPENSSL_malloc(len); if (!s->s3->alpn_selected) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->s3->alpn_selected, data + 3, len); s->s3->alpn_selected_len = len; } else if (type == TLSEXT_TYPE_renegotiate) { if (!ssl_parse_serverhello_renegotiate_ext(s, data, size, al)) return 0; renegotiate_seen = 1; } # ifndef OPENSSL_NO_HEARTBEATS else if (type == TLSEXT_TYPE_heartbeat) { switch (data[0]) { case 0x01: /* Server allows us to send HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; break; case 0x02: /* Server doesn't accept HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS; break; default: *al = SSL_AD_ILLEGAL_PARAMETER; return 0; } } # endif # ifndef OPENSSL_NO_SRTP else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_use_srtp) { if (ssl_parse_serverhello_use_srtp_ext(s, data, size, al)) return 0; } # endif /* * If this extension type was not otherwise handled, but matches a * custom_cli_ext_record, then send it to the c callback */ else if (custom_ext_parse(s, 0, type, data, size, al) <= 0) return 0; data += size; } if (data != d + n) { *al = SSL_AD_DECODE_ERROR; return 0; } if (!s->hit && tlsext_servername == 1) { if (s->tlsext_hostname) { if (s->session->tlsext_hostname == NULL) { s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname); if (!s->session->tlsext_hostname) { *al = SSL_AD_UNRECOGNIZED_NAME; return 0; } } else { *al = SSL_AD_DECODE_ERROR; return 0; } } } *p = data; ri_check: /* * Determine if we need to see RI. Strictly speaking if we want to avoid * an attack we should *always* see RI even on initial server hello * because the client doesn't see any renegotiation during an attack. * However this would mean we could not connect to any server which * doesn't support RI so for the immediate future tolerate RI absence on * initial connect only. */ if (!renegotiate_seen && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT) && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); return 0; } return 1; } Commit Message: CWE ID: CWE-190
static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al) { unsigned short length; unsigned short type; unsigned short size; unsigned char *data = *p; int tlsext_servername = 0; int renegotiate_seen = 0; # ifndef OPENSSL_NO_NEXTPROTONEG s->s3->next_proto_neg_seen = 0; # endif s->tlsext_ticket_expected = 0; if (s->s3->alpn_selected) { OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = NULL; } # ifndef OPENSSL_NO_HEARTBEATS s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED | SSL_TLSEXT_HB_DONT_SEND_REQUESTS); # endif if ((d + n) - data <= 2) goto ri_check; n2s(data, length); if ((d + n) - data != length) { *al = SSL_AD_DECODE_ERROR; return 0; } while ((d + n) - data >= 4) { n2s(data, type); n2s(data, size); if ((d + n) - data < size) goto ri_check; if (s->tlsext_debug_cb) s->tlsext_debug_cb(s, 1, type, data, size, s->tlsext_debug_arg); if (type == TLSEXT_TYPE_server_name) { if (s->tlsext_hostname == NULL || size > 0) { *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } tlsext_servername = 1; } # ifndef OPENSSL_NO_EC else if (type == TLSEXT_TYPE_ec_point_formats) { unsigned char *sdata = data; int ecpointformatlist_length = *(sdata++); if (ecpointformatlist_length != size - 1) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (!s->hit) { s->session->tlsext_ecpointformatlist_length = 0; if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist); if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length; memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length); } # if 0 fprintf(stderr, "ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist "); sdata = s->session->tlsext_ecpointformatlist; for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) fprintf(stderr, "%i ", *(sdata++)); fprintf(stderr, "\n"); # endif } # endif /* OPENSSL_NO_EC */ else if (type == TLSEXT_TYPE_session_ticket) { if (s->tls_session_ticket_ext_cb && !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } if ((SSL_get_options(s) & SSL_OP_NO_TICKET) || (size > 0)) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } s->tlsext_ticket_expected = 1; } # ifdef TLSEXT_TYPE_opaque_prf_input else if (type == TLSEXT_TYPE_opaque_prf_input) { unsigned char *sdata = data; if (size < 2) { *al = SSL_AD_DECODE_ERROR; return 0; } n2s(sdata, s->s3->server_opaque_prf_input_len); if (s->s3->server_opaque_prf_input_len != size - 2) { *al = SSL_AD_DECODE_ERROR; return 0; } if (s->s3->server_opaque_prf_input != NULL) { /* shouldn't really happen */ OPENSSL_free(s->s3->server_opaque_prf_input); } if (s->s3->server_opaque_prf_input_len == 0) { /* dummy byte just to get non-NULL */ s->s3->server_opaque_prf_input = OPENSSL_malloc(1); } else { s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len); } if (s->s3->server_opaque_prf_input == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } # endif else if (type == TLSEXT_TYPE_status_request) { /* * MUST be empty and only sent if we've requested a status * request message. */ if ((s->tlsext_status_type == -1) || (size > 0)) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } /* Set flag to expect CertificateStatus message */ s->tlsext_status_expected = 1; } # ifndef OPENSSL_NO_NEXTPROTONEG else if (type == TLSEXT_TYPE_next_proto_neg && s->s3->tmp.finish_md_len == 0) { unsigned char *selected; unsigned char selected_len; /* We must have requested it. */ if (s->ctx->next_proto_select_cb == NULL) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } /* The data must be valid */ if (!ssl_next_proto_validate(data, size)) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (s-> ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->next_proto_negotiated = OPENSSL_malloc(selected_len); if (!s->next_proto_negotiated) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->next_proto_negotiated, selected, selected_len); s->next_proto_negotiated_len = selected_len; s->s3->next_proto_neg_seen = 1; } # endif else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation) { unsigned len; /* We must have requested it. */ if (!s->cert->alpn_sent) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } if (size < 4) { *al = TLS1_AD_DECODE_ERROR; return 0; } /*- * The extension data consists of: * uint16 list_length * uint8 proto_length; * uint8 proto[proto_length]; */ len = data[0]; len <<= 8; len |= data[1]; if (len != (unsigned)size - 2) { *al = TLS1_AD_DECODE_ERROR; return 0; } len = data[2]; if (len != (unsigned)size - 3) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (s->s3->alpn_selected) OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = OPENSSL_malloc(len); if (!s->s3->alpn_selected) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->s3->alpn_selected, data + 3, len); s->s3->alpn_selected_len = len; } else if (type == TLSEXT_TYPE_renegotiate) { if (!ssl_parse_serverhello_renegotiate_ext(s, data, size, al)) return 0; renegotiate_seen = 1; } # ifndef OPENSSL_NO_HEARTBEATS else if (type == TLSEXT_TYPE_heartbeat) { switch (data[0]) { case 0x01: /* Server allows us to send HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; break; case 0x02: /* Server doesn't accept HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS; break; default: *al = SSL_AD_ILLEGAL_PARAMETER; return 0; } } # endif # ifndef OPENSSL_NO_SRTP else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_use_srtp) { if (ssl_parse_serverhello_use_srtp_ext(s, data, size, al)) return 0; } # endif /* * If this extension type was not otherwise handled, but matches a * custom_cli_ext_record, then send it to the c callback */ else if (custom_ext_parse(s, 0, type, data, size, al) <= 0) return 0; data += size; } if (data != d + n) { *al = SSL_AD_DECODE_ERROR; return 0; } if (!s->hit && tlsext_servername == 1) { if (s->tlsext_hostname) { if (s->session->tlsext_hostname == NULL) { s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname); if (!s->session->tlsext_hostname) { *al = SSL_AD_UNRECOGNIZED_NAME; return 0; } } else { *al = SSL_AD_DECODE_ERROR; return 0; } } } *p = data; ri_check: /* * Determine if we need to see RI. Strictly speaking if we want to avoid * an attack we should *always* see RI even on initial server hello * because the client doesn't see any renegotiation during an attack. * However this would mean we could not connect to any server which * doesn't support RI so for the immediate future tolerate RI absence on * initial connect only. */ if (!renegotiate_seen && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT) && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); return 0; } return 1; }
165,205
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_wrap_iov_length(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, int *conf_state, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 ret; ret = gss_wrap_iov_length(minor_status, context_handle, conf_req_flag, qop_req, conf_state, iov, iov_count); return (ret); } 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_wrap_iov_length(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, int *conf_state, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 ret; spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle; if (sc->ctx_handle == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); ret = gss_wrap_iov_length(minor_status, sc->ctx_handle, conf_req_flag, qop_req, conf_state, iov, iov_count); return (ret); }
166,674
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: const char* Track::GetNameAsUTF8() const { return m_info.nameAsUTF8; } 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 char* Track::GetNameAsUTF8() const
174,343
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 Segment::DoLoadClusterUnknownSize(long long& pos, long& len) { assert(m_pos < 0); assert(m_pUnknownSize); #if 0 assert(m_pUnknownSize->GetElementSize() < 0); //TODO: verify this const long long element_start = m_pUnknownSize->m_element_start; pos = -m_pos; assert(pos > element_start); long long total, avail; long status = m_pReader->Length(&total, &avail); if (status < 0) //error return status; assert((total < 0) || (avail <= total)); const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; long long element_size = -1; for (;;) { //determine cluster size if ((total >= 0) && (pos >= total)) { element_size = total - element_start; assert(element_size > 0); break; } if ((segment_stop >= 0) && (pos >= segment_stop)) { element_size = segment_stop - element_start; assert(element_size > 0); break; } if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(m_pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long idpos = pos; const long long id = ReadUInt(m_pReader, idpos, len); if (id < 0) //error (or underflow) return static_cast<long>(id); if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) { //Cluster ID or Cues ID element_size = pos - element_start; assert(element_size > 0); break; } #ifdef _DEBUG switch (id) { case 0x20: //BlockGroup case 0x23: //Simple Block case 0x67: //TimeCode case 0x2B: //PrevSize break; default: assert(false); break; } #endif pos += len; //consume ID (of sub-element) if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(m_pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0) //error return static_cast<long>(size); pos += len; //consume size field of element if (size == 0) //weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; //not allowed for sub-elements if ((segment_stop >= 0) && ((pos + size) > segment_stop)) //weird return E_FILE_FORMAT_INVALID; pos += size; //consume payload of sub-element assert((segment_stop < 0) || (pos <= segment_stop)); } //determine cluster size assert(element_size >= 0); m_pos = element_start + element_size; m_pUnknownSize = 0; return 2; //continue parsing #else const long status = m_pUnknownSize->Parse(pos, len); if (status < 0) // error or underflow return status; if (status == 0) // parsed a block return 2; // continue parsing assert(status > 0); // nothing left to parse of this cluster const long long start = m_pUnknownSize->m_element_start; const long long size = m_pUnknownSize->GetElementSize(); assert(size >= 0); pos = start + size; m_pos = pos; m_pUnknownSize = 0; return 2; // continue parsing #endif } 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 Segment::DoLoadClusterUnknownSize(long long& pos, long& len) { if (m_pos >= 0 || m_pUnknownSize == NULL) return E_PARSE_FAILED; const long status = m_pUnknownSize->Parse(pos, len); if (status < 0) // error or underflow return status; if (status == 0) // parsed a block return 2; // continue parsing const long long start = m_pUnknownSize->m_element_start; const long long size = m_pUnknownSize->GetElementSize(); if (size < 0) return E_FILE_FORMAT_INVALID; pos = start + size; m_pos = pos; m_pUnknownSize = 0; return 2; // continue parsing }
173,809
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: xscale2pmu_handle_irq(int irq_num, void *dev) { unsigned long pmnc, of_flags; struct perf_sample_data data; struct cpu_hw_events *cpuc; struct pt_regs *regs; int idx; /* Disable the PMU. */ pmnc = xscale2pmu_read_pmnc(); xscale2pmu_write_pmnc(pmnc & ~XSCALE_PMU_ENABLE); /* Check the overflow flag register. */ of_flags = xscale2pmu_read_overflow_flags(); if (!(of_flags & XSCALE2_OVERFLOWED_MASK)) return IRQ_NONE; /* Clear the overflow bits. */ xscale2pmu_write_overflow_flags(of_flags); regs = get_irq_regs(); perf_sample_data_init(&data, 0); cpuc = &__get_cpu_var(cpu_hw_events); for (idx = 0; idx <= armpmu->num_events; ++idx) { struct perf_event *event = cpuc->events[idx]; struct hw_perf_event *hwc; if (!test_bit(idx, cpuc->active_mask)) continue; if (!xscale2_pmnc_counter_has_overflowed(pmnc, idx)) continue; hwc = &event->hw; armpmu_event_update(event, hwc, idx, 1); data.period = event->hw.last_period; if (!armpmu_event_set_period(event, hwc, idx)) continue; if (perf_event_overflow(event, 0, &data, regs)) armpmu->disable(hwc, idx); } irq_work_run(); /* * Re-enable the PMU. */ pmnc = xscale2pmu_read_pmnc() | XSCALE_PMU_ENABLE; xscale2pmu_write_pmnc(pmnc); return IRQ_HANDLED; } 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
xscale2pmu_handle_irq(int irq_num, void *dev) { unsigned long pmnc, of_flags; struct perf_sample_data data; struct cpu_hw_events *cpuc; struct pt_regs *regs; int idx; /* Disable the PMU. */ pmnc = xscale2pmu_read_pmnc(); xscale2pmu_write_pmnc(pmnc & ~XSCALE_PMU_ENABLE); /* Check the overflow flag register. */ of_flags = xscale2pmu_read_overflow_flags(); if (!(of_flags & XSCALE2_OVERFLOWED_MASK)) return IRQ_NONE; /* Clear the overflow bits. */ xscale2pmu_write_overflow_flags(of_flags); regs = get_irq_regs(); perf_sample_data_init(&data, 0); cpuc = &__get_cpu_var(cpu_hw_events); for (idx = 0; idx <= armpmu->num_events; ++idx) { struct perf_event *event = cpuc->events[idx]; struct hw_perf_event *hwc; if (!test_bit(idx, cpuc->active_mask)) continue; if (!xscale2_pmnc_counter_has_overflowed(pmnc, idx)) continue; hwc = &event->hw; armpmu_event_update(event, hwc, idx, 1); data.period = event->hw.last_period; if (!armpmu_event_set_period(event, hwc, idx)) continue; if (perf_event_overflow(event, &data, regs)) armpmu->disable(hwc, idx); } irq_work_run(); /* * Re-enable the PMU. */ pmnc = xscale2pmu_read_pmnc() | XSCALE_PMU_ENABLE; xscale2pmu_write_pmnc(pmnc); return IRQ_HANDLED; }
165,776
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_inquire_context( OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_name_t *src_name, gss_name_t *targ_name, OM_uint32 *lifetime_rec, gss_OID *mech_type, OM_uint32 *ctx_flags, int *locally_initiated, int *opened) { gss_union_ctx_id_t ctx; gss_mechanism mech; OM_uint32 status, temp_minor; gss_OID actual_mech; gss_name_t localTargName = NULL, localSourceName = NULL; status = val_inq_ctx_args(minor_status, context_handle, src_name, targ_name, lifetime_rec, mech_type, ctx_flags, locally_initiated, opened); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (!mech || !mech->gss_inquire_context || !mech->gss_display_name || !mech->gss_release_name) { return (GSS_S_UNAVAILABLE); } status = mech->gss_inquire_context( minor_status, ctx->internal_ctx_id, (src_name ? &localSourceName : NULL), (targ_name ? &localTargName : NULL), lifetime_rec, &actual_mech, ctx_flags, locally_initiated, opened); if (status != GSS_S_COMPLETE) { map_error(minor_status, mech); return status; } /* need to convert names */ if (src_name) { if (localSourceName) { status = gssint_convert_name_to_union_name(minor_status, mech, localSourceName, src_name); if (status != GSS_S_COMPLETE) { if (localTargName) mech->gss_release_name(&temp_minor, &localTargName); return (status); } } else { *src_name = GSS_C_NO_NAME; } } if (targ_name) { if (localTargName) { status = gssint_convert_name_to_union_name(minor_status, mech, localTargName, targ_name); if (status != GSS_S_COMPLETE) { if (src_name) (void) gss_release_name(&temp_minor, src_name); return (status); } } else { *targ_name = GSS_C_NO_NAME; } } if (mech_type) *mech_type = gssint_get_public_oid(actual_mech); return(GSS_S_COMPLETE); } 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_inquire_context( OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_name_t *src_name, gss_name_t *targ_name, OM_uint32 *lifetime_rec, gss_OID *mech_type, OM_uint32 *ctx_flags, int *locally_initiated, int *opened) { gss_union_ctx_id_t ctx; gss_mechanism mech; OM_uint32 status, temp_minor; gss_OID actual_mech; gss_name_t localTargName = NULL, localSourceName = NULL; status = val_inq_ctx_args(minor_status, context_handle, src_name, targ_name, lifetime_rec, mech_type, ctx_flags, locally_initiated, opened); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); mech = gssint_get_mechanism (ctx->mech_type); if (!mech || !mech->gss_inquire_context || !mech->gss_display_name || !mech->gss_release_name) { return (GSS_S_UNAVAILABLE); } status = mech->gss_inquire_context( minor_status, ctx->internal_ctx_id, (src_name ? &localSourceName : NULL), (targ_name ? &localTargName : NULL), lifetime_rec, &actual_mech, ctx_flags, locally_initiated, opened); if (status != GSS_S_COMPLETE) { map_error(minor_status, mech); return status; } /* need to convert names */ if (src_name) { if (localSourceName) { status = gssint_convert_name_to_union_name(minor_status, mech, localSourceName, src_name); if (status != GSS_S_COMPLETE) { if (localTargName) mech->gss_release_name(&temp_minor, &localTargName); return (status); } } else { *src_name = GSS_C_NO_NAME; } } if (targ_name) { if (localTargName) { status = gssint_convert_name_to_union_name(minor_status, mech, localTargName, targ_name); if (status != GSS_S_COMPLETE) { if (src_name) (void) gss_release_name(&temp_minor, src_name); return (status); } } else { *targ_name = GSS_C_NO_NAME; } } if (mech_type) *mech_type = gssint_get_public_oid(actual_mech); return(GSS_S_COMPLETE); }
168,017
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: oxide::BrowserContext* WebContext::GetContext() { if (context_.get()) { return context_.get(); } DCHECK(construct_props_); oxide::BrowserContext::Params params( construct_props_->data_path, construct_props_->cache_path, construct_props_->max_cache_size_hint, construct_props_->session_cookie_mode); params.host_mapping_rules = construct_props_->host_mapping_rules; context_ = oxide::BrowserContext::Create(params); UserAgentSettings* ua_settings = UserAgentSettings::Get(context_.get()); if (!construct_props_->product.empty()) { ua_settings->SetProduct(construct_props_->product); } if (!construct_props_->user_agent.empty()) { ua_settings->SetUserAgent(construct_props_->user_agent); } if (!construct_props_->accept_langs.empty()) { ua_settings->SetAcceptLangs(construct_props_->accept_langs); } ua_settings->SetUserAgentOverrides(construct_props_->user_agent_overrides); ua_settings->SetLegacyUserAgentOverrideEnabled( construct_props_->legacy_user_agent_override_enabled); context_->SetCookiePolicy(construct_props_->cookie_policy); context_->SetIsPopupBlockerEnabled(construct_props_->popup_blocker_enabled); context_->SetDoNotTrack(construct_props_->do_not_track); MediaCaptureDevicesContext* dc = MediaCaptureDevicesContext::Get(context_.get()); if (!construct_props_->default_audio_capture_device_id.empty()) { if (!dc->SetDefaultAudioDeviceId( construct_props_->default_audio_capture_device_id)) { client_->DefaultAudioCaptureDeviceChanged(); } } if (!construct_props_->default_video_capture_device_id.empty()) { if (!dc->SetDefaultVideoDeviceId( construct_props_->default_video_capture_device_id)) { client_->DefaultVideoCaptureDeviceChanged(); } } dc->set_client(this); DevToolsManager* devtools = DevToolsManager::Get(context_.get()); if (!construct_props_->devtools_ip.empty()) { devtools->SetAddress(construct_props_->devtools_ip); } if (construct_props_->devtools_port != -1) { devtools->SetPort(construct_props_->devtools_port); } devtools->SetEnabled(construct_props_->devtools_enabled); context_->SetDelegate(delegate_.get()); construct_props_.reset(); UpdateUserScripts(); return context_.get(); } Commit Message: CWE ID: CWE-20
oxide::BrowserContext* WebContext::GetContext() { BrowserContext* WebContext::GetContext() { if (context_.get()) { return context_.get(); } DCHECK(construct_props_); BrowserContext::Params params( construct_props_->data_path, construct_props_->cache_path, construct_props_->max_cache_size_hint, construct_props_->session_cookie_mode); params.host_mapping_rules = construct_props_->host_mapping_rules; context_ = BrowserContext::Create(params); UserAgentSettings* ua_settings = UserAgentSettings::Get(context_.get()); if (!construct_props_->product.empty()) { ua_settings->SetProduct(construct_props_->product); } if (!construct_props_->user_agent.empty()) { ua_settings->SetUserAgent(construct_props_->user_agent); } if (!construct_props_->accept_langs.empty()) { ua_settings->SetAcceptLangs(construct_props_->accept_langs); } ua_settings->SetUserAgentOverrides(construct_props_->user_agent_overrides); ua_settings->SetLegacyUserAgentOverrideEnabled( construct_props_->legacy_user_agent_override_enabled); context_->SetCookiePolicy(construct_props_->cookie_policy); context_->SetIsPopupBlockerEnabled(construct_props_->popup_blocker_enabled); context_->SetDoNotTrack(construct_props_->do_not_track); MediaCaptureDevicesContext* dc = MediaCaptureDevicesContext::Get(context_.get()); if (!construct_props_->default_audio_capture_device_id.empty()) { if (!dc->SetDefaultAudioDeviceId( construct_props_->default_audio_capture_device_id)) { client_->DefaultAudioCaptureDeviceChanged(); } } if (!construct_props_->default_video_capture_device_id.empty()) { if (!dc->SetDefaultVideoDeviceId( construct_props_->default_video_capture_device_id)) { client_->DefaultVideoCaptureDeviceChanged(); } } dc->set_client(this); DevToolsManager* devtools = DevToolsManager::Get(context_.get()); if (!construct_props_->devtools_ip.empty()) { devtools->SetAddress(construct_props_->devtools_ip); } if (construct_props_->devtools_port != -1) { devtools->SetPort(construct_props_->devtools_port); } devtools->SetEnabled(construct_props_->devtools_enabled); context_->SetDelegate(delegate_.get()); construct_props_.reset(); UpdateUserScripts(); return context_.get(); }
165,412
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: ref_param_read_signal_error(gs_param_list * plist, gs_param_name pkey, int code) { iparam_list *const iplist = (iparam_list *) plist; iparam_loc loc; ref_param_read(iplist, pkey, &loc, -1); /* can't fail */ *loc.presult = code; switch (ref_param_read_get_policy(plist, pkey)) { case gs_param_policy_ignore: return 0; return_error(gs_error_configurationerror); default: return code; } } Commit Message: CWE ID: CWE-704
ref_param_read_signal_error(gs_param_list * plist, gs_param_name pkey, int code) { iparam_list *const iplist = (iparam_list *) plist; iparam_loc loc = {0}; ref_param_read(iplist, pkey, &loc, -1); if (loc.presult) *loc.presult = code; switch (ref_param_read_get_policy(plist, pkey)) { case gs_param_policy_ignore: return 0; return_error(gs_error_configurationerror); default: return code; } }
164,705
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 dsa_priv_decode(EVP_PKEY *pkey, PKCS8_PRIV_KEY_INFO *p8) { const unsigned char *p, *pm; int pklen, pmlen; int ptype; void *pval; ASN1_STRING *pstr; X509_ALGOR *palg; ASN1_INTEGER *privkey = NULL; BN_CTX *ctx = NULL; STACK_OF(ASN1_TYPE) *ndsa = NULL; DSA *dsa = NULL; if (!PKCS8_pkey_get0(NULL, &p, &pklen, &palg, p8)) return 0; X509_ALGOR_get0(NULL, &ptype, &pval, palg); if (*p == (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)) { ASN1_TYPE *t1, *t2; if (!(ndsa = d2i_ASN1_SEQUENCE_ANY(NULL, &p, pklen))) goto decerr; if (sk_ASN1_TYPE_num(ndsa) != 2) goto decerr; /*- * Handle Two broken types: * SEQUENCE {parameters, priv_key} * SEQUENCE {pub_key, priv_key} */ t1 = sk_ASN1_TYPE_value(ndsa, 0); t2 = sk_ASN1_TYPE_value(ndsa, 1); if (t1->type == V_ASN1_SEQUENCE) { p8->broken = PKCS8_EMBEDDED_PARAM; pval = t1->value.ptr; } else if (ptype == V_ASN1_SEQUENCE) p8->broken = PKCS8_NS_DB; else goto decerr; if (t2->type != V_ASN1_INTEGER) goto decerr; privkey = t2->value.integer; } else { const unsigned char *q = p; if (!(privkey = d2i_ASN1_INTEGER(NULL, &p, pklen))) goto decerr; if (privkey->type == V_ASN1_NEG_INTEGER) { p8->broken = PKCS8_NEG_PRIVKEY; ASN1_STRING_clear_free(privkey); if (!(privkey = d2i_ASN1_UINTEGER(NULL, &q, pklen))) goto decerr; } if (ptype != V_ASN1_SEQUENCE) goto decerr; } pstr = pval; pm = pstr->data; pmlen = pstr->length; if (!(dsa = d2i_DSAparams(NULL, &pm, pmlen))) goto decerr; /* We have parameters now set private key */ if (!(dsa->priv_key = ASN1_INTEGER_to_BN(privkey, NULL))) { DSAerr(DSA_F_DSA_PRIV_DECODE, DSA_R_BN_ERROR); goto dsaerr; } /* Calculate public key */ if (!(dsa->pub_key = BN_new())) { DSAerr(DSA_F_DSA_PRIV_DECODE, ERR_R_MALLOC_FAILURE); goto dsaerr; } if (!(ctx = BN_CTX_new())) { DSAerr(DSA_F_DSA_PRIV_DECODE, ERR_R_MALLOC_FAILURE); goto dsaerr; } if (!BN_mod_exp(dsa->pub_key, dsa->g, dsa->priv_key, dsa->p, ctx)) { DSAerr(DSA_F_DSA_PRIV_DECODE, DSA_R_BN_ERROR); goto dsaerr; } } Commit Message: CWE ID:
static int dsa_priv_decode(EVP_PKEY *pkey, PKCS8_PRIV_KEY_INFO *p8) { const unsigned char *p, *pm; int pklen, pmlen; int ptype; void *pval; ASN1_STRING *pstr; X509_ALGOR *palg; ASN1_INTEGER *privkey = NULL; BN_CTX *ctx = NULL; STACK_OF(ASN1_TYPE) *ndsa = NULL; DSA *dsa = NULL; int ret = 0; if (!PKCS8_pkey_get0(NULL, &p, &pklen, &palg, p8)) return 0; X509_ALGOR_get0(NULL, &ptype, &pval, palg); if (*p == (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)) { ASN1_TYPE *t1, *t2; if (!(ndsa = d2i_ASN1_SEQUENCE_ANY(NULL, &p, pklen))) goto decerr; if (sk_ASN1_TYPE_num(ndsa) != 2) goto decerr; /*- * Handle Two broken types: * SEQUENCE {parameters, priv_key} * SEQUENCE {pub_key, priv_key} */ t1 = sk_ASN1_TYPE_value(ndsa, 0); t2 = sk_ASN1_TYPE_value(ndsa, 1); if (t1->type == V_ASN1_SEQUENCE) { p8->broken = PKCS8_EMBEDDED_PARAM; pval = t1->value.ptr; } else if (ptype == V_ASN1_SEQUENCE) p8->broken = PKCS8_NS_DB; else goto decerr; if (t2->type != V_ASN1_INTEGER) goto decerr; privkey = t2->value.integer; } else { const unsigned char *q = p; if (!(privkey = d2i_ASN1_INTEGER(NULL, &p, pklen))) goto decerr; if (privkey->type == V_ASN1_NEG_INTEGER) { p8->broken = PKCS8_NEG_PRIVKEY; ASN1_STRING_clear_free(privkey); if (!(privkey = d2i_ASN1_UINTEGER(NULL, &q, pklen))) goto decerr; } if (ptype != V_ASN1_SEQUENCE) goto decerr; } pstr = pval; pm = pstr->data; pmlen = pstr->length; if (!(dsa = d2i_DSAparams(NULL, &pm, pmlen))) goto decerr; /* We have parameters now set private key */ if (!(dsa->priv_key = ASN1_INTEGER_to_BN(privkey, NULL))) { DSAerr(DSA_F_DSA_PRIV_DECODE, DSA_R_BN_ERROR); goto dsaerr; } /* Calculate public key */ if (!(dsa->pub_key = BN_new())) { DSAerr(DSA_F_DSA_PRIV_DECODE, ERR_R_MALLOC_FAILURE); goto dsaerr; } if (!(ctx = BN_CTX_new())) { DSAerr(DSA_F_DSA_PRIV_DECODE, ERR_R_MALLOC_FAILURE); goto dsaerr; } if (!BN_mod_exp(dsa->pub_key, dsa->g, dsa->priv_key, dsa->p, ctx)) { DSAerr(DSA_F_DSA_PRIV_DECODE, DSA_R_BN_ERROR); goto dsaerr; } }
165,253
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 SkipRGBMipmaps(Image *image,DDSInfo *dds_info, int pixel_size,ExceptionInfo *exception) { MagickOffsetType offset; register ssize_t i; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) w * h * pixel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } return(MagickTrue); } Commit Message: Moved EOF check. CWE ID: CWE-20
static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info, int pixel_size,ExceptionInfo *exception) { MagickOffsetType offset; register ssize_t i; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) w * h * pixel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } return(MagickTrue); }
170,155
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 can_open_delegated(struct nfs_delegation *delegation, mode_t open_flags) { if ((delegation->type & open_flags) != open_flags) return 0; if (test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags)) return 0; nfs_mark_delegation_referenced(delegation); return 1; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
static int can_open_delegated(struct nfs_delegation *delegation, mode_t open_flags) static int can_open_delegated(struct nfs_delegation *delegation, fmode_t fmode) { if ((delegation->type & fmode) != fmode) return 0; if (test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags)) return 0; nfs_mark_delegation_referenced(delegation); return 1; }
165,687
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 Cues::DoneParsing() const { const long long stop = m_start + m_size; return (m_pos >= stop); } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
bool Cues::DoneParsing() const
174,267
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 u_int mp_dss_len(const struct mp_dss *m, int csum) { u_int len; len = 4; if (m->flags & MP_DSS_A) { /* Ack present - 4 or 8 octets */ len += (m->flags & MP_DSS_a) ? 8 : 4; } if (m->flags & MP_DSS_M) { /* * Data Sequence Number (DSN), Subflow Sequence Number (SSN), * Data-Level Length present, and Checksum possibly present. * All but the Checksum are 10 bytes if the m flag is * clear (4-byte DSN) and 14 bytes if the m flag is set * (8-byte DSN). */ len += (m->flags & MP_DSS_m) ? 14 : 10; /* * The Checksum is present only if negotiated. */ if (csum) len += 2; } return len; } Commit Message: CVE-2017-13040/MPTCP: Clean up printing DSS suboption. Do the length checking inline; that means we print stuff up to the point at which we run out of option data. First check to make sure we have at least 4 bytes of option, so we have flags to check. This fixes a buffer over-read discovered by Kim Gwan Yeong. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
static u_int mp_dss_len(const struct mp_dss *m, int csum)
167,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 em_sysenter(struct x86_emulate_ctxt *ctxt) { const struct x86_emulate_ops *ops = ctxt->ops; struct desc_struct cs, ss; u64 msr_data; u16 cs_sel, ss_sel; u64 efer = 0; ops->get_msr(ctxt, MSR_EFER, &efer); /* inject #GP if in real mode */ if (ctxt->mode == X86EMUL_MODE_REAL) return emulate_gp(ctxt, 0); /* * Not recognized on AMD in compat mode (but is recognized in legacy * mode). */ if ((ctxt->mode == X86EMUL_MODE_PROT32) && (efer & EFER_LMA) && !vendor_intel(ctxt)) return emulate_ud(ctxt); /* sysenter/sysexit have not been tested in 64bit mode. */ if (ctxt->mode == X86EMUL_MODE_PROT64) return X86EMUL_UNHANDLEABLE; setup_syscalls_segments(ctxt, &cs, &ss); ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data); switch (ctxt->mode) { case X86EMUL_MODE_PROT32: if ((msr_data & 0xfffc) == 0x0) return emulate_gp(ctxt, 0); break; case X86EMUL_MODE_PROT64: if (msr_data == 0x0) return emulate_gp(ctxt, 0); break; default: break; } ctxt->eflags &= ~(EFLG_VM | EFLG_IF); cs_sel = (u16)msr_data; cs_sel &= ~SELECTOR_RPL_MASK; ss_sel = cs_sel + 8; ss_sel &= ~SELECTOR_RPL_MASK; if (ctxt->mode == X86EMUL_MODE_PROT64 || (efer & EFER_LMA)) { cs.d = 0; cs.l = 1; } ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS); ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS); ops->get_msr(ctxt, MSR_IA32_SYSENTER_EIP, &msr_data); ctxt->_eip = msr_data; ops->get_msr(ctxt, MSR_IA32_SYSENTER_ESP, &msr_data); *reg_write(ctxt, VCPU_REGS_RSP) = msr_data; return X86EMUL_CONTINUE; } Commit Message: KVM: x86: SYSENTER emulation is broken SYSENTER emulation is broken in several ways: 1. It misses the case of 16-bit code segments completely (CVE-2015-0239). 2. MSR_IA32_SYSENTER_CS is checked in 64-bit mode incorrectly (bits 0 and 1 can still be set without causing #GP). 3. MSR_IA32_SYSENTER_EIP and MSR_IA32_SYSENTER_ESP are not masked in legacy-mode. 4. There is some unneeded code. Fix it. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-362
static int em_sysenter(struct x86_emulate_ctxt *ctxt) { const struct x86_emulate_ops *ops = ctxt->ops; struct desc_struct cs, ss; u64 msr_data; u16 cs_sel, ss_sel; u64 efer = 0; ops->get_msr(ctxt, MSR_EFER, &efer); /* inject #GP if in real mode */ if (ctxt->mode == X86EMUL_MODE_REAL) return emulate_gp(ctxt, 0); /* * Not recognized on AMD in compat mode (but is recognized in legacy * mode). */ if ((ctxt->mode != X86EMUL_MODE_PROT64) && (efer & EFER_LMA) && !vendor_intel(ctxt)) return emulate_ud(ctxt); /* sysenter/sysexit have not been tested in 64bit mode. */ if (ctxt->mode == X86EMUL_MODE_PROT64) return X86EMUL_UNHANDLEABLE; setup_syscalls_segments(ctxt, &cs, &ss); ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data); if ((msr_data & 0xfffc) == 0x0) return emulate_gp(ctxt, 0); ctxt->eflags &= ~(EFLG_VM | EFLG_IF); cs_sel = (u16)msr_data & ~SELECTOR_RPL_MASK; ss_sel = cs_sel + 8; if (efer & EFER_LMA) { cs.d = 0; cs.l = 1; } ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS); ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS); ops->get_msr(ctxt, MSR_IA32_SYSENTER_EIP, &msr_data); ctxt->_eip = (efer & EFER_LMA) ? msr_data : (u32)msr_data; ops->get_msr(ctxt, MSR_IA32_SYSENTER_ESP, &msr_data); *reg_write(ctxt, VCPU_REGS_RSP) = (efer & EFER_LMA) ? msr_data : (u32)msr_data; return X86EMUL_CONTINUE; }
166,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: void processRequest(struct reqelem * req) { ssize_t n; unsigned int l, m; unsigned char buf[2048]; const unsigned char * p; enum request_type type; struct device * d = devlist; unsigned char rbuf[RESPONSE_BUFFER_SIZE]; unsigned char * rp; unsigned char nrep = 0; time_t t; struct service * newserv = NULL; struct service * serv; n = read(req->socket, buf, sizeof(buf)); if(n<0) { if(errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) return; /* try again later */ syslog(LOG_ERR, "(s=%d) processRequest(): read(): %m", req->socket); goto error; } if(n==0) { syslog(LOG_INFO, "(s=%d) request connection closed", req->socket); goto error; } t = time(NULL); type = buf[0]; p = buf + 1; DECODELENGTH_CHECKLIMIT(l, p, buf + n); if(p+l > buf+n) { syslog(LOG_WARNING, "bad request (length encoding l=%u n=%u)", l, (unsigned)n); goto error; } if(l == 0 && type != MINISSDPD_SEARCH_ALL && type != MINISSDPD_GET_VERSION && type != MINISSDPD_NOTIF) { syslog(LOG_WARNING, "bad request (length=0, type=%d)", type); goto error; } syslog(LOG_INFO, "(s=%d) request type=%d str='%.*s'", req->socket, type, l, p); switch(type) { case MINISSDPD_GET_VERSION: rp = rbuf; CODELENGTH((sizeof(MINISSDPD_VERSION) - 1), rp); memcpy(rp, MINISSDPD_VERSION, sizeof(MINISSDPD_VERSION) - 1); rp += (sizeof(MINISSDPD_VERSION) - 1); if(write_or_buffer(req, rbuf, rp - rbuf) < 0) { syslog(LOG_ERR, "(s=%d) write: %m", req->socket); goto error; } break; case MINISSDPD_SEARCH_TYPE: /* request by type */ case MINISSDPD_SEARCH_USN: /* request by USN (unique id) */ case MINISSDPD_SEARCH_ALL: /* everything */ rp = rbuf+1; while(d && (nrep < 255)) { if(d->t < t) { syslog(LOG_INFO, "outdated device"); } else { /* test if we can put more responses in the buffer */ if(d->headers[HEADER_LOCATION].l + d->headers[HEADER_NT].l + d->headers[HEADER_USN].l + 6 + (rp - rbuf) >= (int)sizeof(rbuf)) break; if( (type==MINISSDPD_SEARCH_TYPE && 0==memcmp(d->headers[HEADER_NT].p, p, l)) ||(type==MINISSDPD_SEARCH_USN && 0==memcmp(d->headers[HEADER_USN].p, p, l)) ||(type==MINISSDPD_SEARCH_ALL) ) { /* response : * 1 - Location * 2 - NT (device/service type) * 3 - usn */ m = d->headers[HEADER_LOCATION].l; CODELENGTH(m, rp); memcpy(rp, d->headers[HEADER_LOCATION].p, d->headers[HEADER_LOCATION].l); rp += d->headers[HEADER_LOCATION].l; m = d->headers[HEADER_NT].l; CODELENGTH(m, rp); memcpy(rp, d->headers[HEADER_NT].p, d->headers[HEADER_NT].l); rp += d->headers[HEADER_NT].l; m = d->headers[HEADER_USN].l; CODELENGTH(m, rp); memcpy(rp, d->headers[HEADER_USN].p, d->headers[HEADER_USN].l); rp += d->headers[HEADER_USN].l; nrep++; } } d = d->next; } /* Also look in service list */ for(serv = servicelisthead.lh_first; serv && (nrep < 255); serv = serv->entries.le_next) { /* test if we can put more responses in the buffer */ if(strlen(serv->location) + strlen(serv->st) + strlen(serv->usn) + 6 + (rp - rbuf) >= sizeof(rbuf)) break; if( (type==MINISSDPD_SEARCH_TYPE && 0==strncmp(serv->st, (const char *)p, l)) ||(type==MINISSDPD_SEARCH_USN && 0==strncmp(serv->usn, (const char *)p, l)) ||(type==MINISSDPD_SEARCH_ALL) ) { /* response : * 1 - Location * 2 - NT (device/service type) * 3 - usn */ m = strlen(serv->location); CODELENGTH(m, rp); memcpy(rp, serv->location, m); rp += m; m = strlen(serv->st); CODELENGTH(m, rp); memcpy(rp, serv->st, m); rp += m; m = strlen(serv->usn); CODELENGTH(m, rp); memcpy(rp, serv->usn, m); rp += m; nrep++; } } rbuf[0] = nrep; syslog(LOG_DEBUG, "(s=%d) response : %d device%s", req->socket, nrep, (nrep > 1) ? "s" : ""); if(write_or_buffer(req, rbuf, rp - rbuf) < 0) { syslog(LOG_ERR, "(s=%d) write: %m", req->socket); goto error; } break; case MINISSDPD_SUBMIT: /* submit service */ newserv = malloc(sizeof(struct service)); if(!newserv) { syslog(LOG_ERR, "cannot allocate memory"); goto error; } memset(newserv, 0, sizeof(struct service)); /* set pointers to NULL */ if(containsForbiddenChars(p, l)) { syslog(LOG_ERR, "bad request (st contains forbidden chars)"); goto error; } newserv->st = malloc(l + 1); if(!newserv->st) { syslog(LOG_ERR, "cannot allocate memory"); goto error; } memcpy(newserv->st, p, l); newserv->st[l] = '\0'; p += l; if(p >= buf + n) { syslog(LOG_WARNING, "bad request (missing usn)"); goto error; } DECODELENGTH_CHECKLIMIT(l, p, buf + n); if(p+l > buf+n) { syslog(LOG_WARNING, "bad request (length encoding)"); goto error; } if(containsForbiddenChars(p, l)) { syslog(LOG_ERR, "bad request (usn contains forbidden chars)"); goto error; } syslog(LOG_INFO, "usn='%.*s'", l, p); newserv->usn = malloc(l + 1); if(!newserv->usn) { syslog(LOG_ERR, "cannot allocate memory"); goto error; } memcpy(newserv->usn, p, l); newserv->usn[l] = '\0'; p += l; DECODELENGTH_CHECKLIMIT(l, p, buf + n); if(p+l > buf+n) { syslog(LOG_WARNING, "bad request (length encoding)"); goto error; } if(containsForbiddenChars(p, l)) { syslog(LOG_ERR, "bad request (server contains forbidden chars)"); goto error; } syslog(LOG_INFO, "server='%.*s'", l, p); newserv->server = malloc(l + 1); if(!newserv->server) { syslog(LOG_ERR, "cannot allocate memory"); goto error; } memcpy(newserv->server, p, l); newserv->server[l] = '\0'; p += l; DECODELENGTH_CHECKLIMIT(l, p, buf + n); if(p+l > buf+n) { syslog(LOG_WARNING, "bad request (length encoding)"); goto error; } if(containsForbiddenChars(p, l)) { syslog(LOG_ERR, "bad request (location contains forbidden chars)"); goto error; } syslog(LOG_INFO, "location='%.*s'", l, p); newserv->location = malloc(l + 1); if(!newserv->location) { syslog(LOG_ERR, "cannot allocate memory"); goto error; } memcpy(newserv->location, p, l); newserv->location[l] = '\0'; /* look in service list for duplicate */ for(serv = servicelisthead.lh_first; serv; serv = serv->entries.le_next) { if(0 == strcmp(newserv->usn, serv->usn) && 0 == strcmp(newserv->st, serv->st)) { syslog(LOG_INFO, "Service already in the list. Updating..."); free(newserv->st); free(newserv->usn); free(serv->server); serv->server = newserv->server; free(serv->location); serv->location = newserv->location; free(newserv); newserv = NULL; return; } } /* Inserting new service */ LIST_INSERT_HEAD(&servicelisthead, newserv, entries); sendNotifications(NOTIF_NEW, NULL, newserv); newserv = NULL; break; case MINISSDPD_NOTIF: /* switch socket to notify */ rbuf[0] = '\0'; if(write_or_buffer(req, rbuf, 1) < 0) { syslog(LOG_ERR, "(s=%d) write: %m", req->socket); goto error; } req->is_notify = 1; break; default: syslog(LOG_WARNING, "Unknown request type %d", type); rbuf[0] = '\0'; if(write_or_buffer(req, rbuf, 1) < 0) { syslog(LOG_ERR, "(s=%d) write: %m", req->socket); goto error; } } return; error: if(newserv) { free(newserv->st); free(newserv->usn); free(newserv->server); free(newserv->location); free(newserv); newserv = NULL; } close(req->socket); req->socket = -1; return; } Commit Message: minissdpd: Fix broken overflow test (p+l > buf+n) thanks to Salva Piero CWE ID: CWE-125
void processRequest(struct reqelem * req) { ssize_t n; unsigned int l, m; unsigned char buf[2048]; const unsigned char * p; enum request_type type; struct device * d = devlist; unsigned char rbuf[RESPONSE_BUFFER_SIZE]; unsigned char * rp; unsigned char nrep = 0; time_t t; struct service * newserv = NULL; struct service * serv; n = read(req->socket, buf, sizeof(buf)); if(n<0) { if(errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) return; /* try again later */ syslog(LOG_ERR, "(s=%d) processRequest(): read(): %m", req->socket); goto error; } if(n==0) { syslog(LOG_INFO, "(s=%d) request connection closed", req->socket); goto error; } t = time(NULL); type = buf[0]; p = buf + 1; DECODELENGTH_CHECKLIMIT(l, p, buf + n); if(l > (unsigned)(buf+n-p)) { syslog(LOG_WARNING, "bad request (length encoding l=%u n=%u)", l, (unsigned)n); goto error; } if(l == 0 && type != MINISSDPD_SEARCH_ALL && type != MINISSDPD_GET_VERSION && type != MINISSDPD_NOTIF) { syslog(LOG_WARNING, "bad request (length=0, type=%d)", type); goto error; } syslog(LOG_INFO, "(s=%d) request type=%d str='%.*s'", req->socket, type, l, p); switch(type) { case MINISSDPD_GET_VERSION: rp = rbuf; CODELENGTH((sizeof(MINISSDPD_VERSION) - 1), rp); memcpy(rp, MINISSDPD_VERSION, sizeof(MINISSDPD_VERSION) - 1); rp += (sizeof(MINISSDPD_VERSION) - 1); if(write_or_buffer(req, rbuf, rp - rbuf) < 0) { syslog(LOG_ERR, "(s=%d) write: %m", req->socket); goto error; } break; case MINISSDPD_SEARCH_TYPE: /* request by type */ case MINISSDPD_SEARCH_USN: /* request by USN (unique id) */ case MINISSDPD_SEARCH_ALL: /* everything */ rp = rbuf+1; while(d && (nrep < 255)) { if(d->t < t) { syslog(LOG_INFO, "outdated device"); } else { /* test if we can put more responses in the buffer */ if(d->headers[HEADER_LOCATION].l + d->headers[HEADER_NT].l + d->headers[HEADER_USN].l + 6 + (rp - rbuf) >= (int)sizeof(rbuf)) break; if( (type==MINISSDPD_SEARCH_TYPE && 0==memcmp(d->headers[HEADER_NT].p, p, l)) ||(type==MINISSDPD_SEARCH_USN && 0==memcmp(d->headers[HEADER_USN].p, p, l)) ||(type==MINISSDPD_SEARCH_ALL) ) { /* response : * 1 - Location * 2 - NT (device/service type) * 3 - usn */ m = d->headers[HEADER_LOCATION].l; CODELENGTH(m, rp); memcpy(rp, d->headers[HEADER_LOCATION].p, d->headers[HEADER_LOCATION].l); rp += d->headers[HEADER_LOCATION].l; m = d->headers[HEADER_NT].l; CODELENGTH(m, rp); memcpy(rp, d->headers[HEADER_NT].p, d->headers[HEADER_NT].l); rp += d->headers[HEADER_NT].l; m = d->headers[HEADER_USN].l; CODELENGTH(m, rp); memcpy(rp, d->headers[HEADER_USN].p, d->headers[HEADER_USN].l); rp += d->headers[HEADER_USN].l; nrep++; } } d = d->next; } /* Also look in service list */ for(serv = servicelisthead.lh_first; serv && (nrep < 255); serv = serv->entries.le_next) { /* test if we can put more responses in the buffer */ if(strlen(serv->location) + strlen(serv->st) + strlen(serv->usn) + 6 + (rp - rbuf) >= sizeof(rbuf)) break; if( (type==MINISSDPD_SEARCH_TYPE && 0==strncmp(serv->st, (const char *)p, l)) ||(type==MINISSDPD_SEARCH_USN && 0==strncmp(serv->usn, (const char *)p, l)) ||(type==MINISSDPD_SEARCH_ALL) ) { /* response : * 1 - Location * 2 - NT (device/service type) * 3 - usn */ m = strlen(serv->location); CODELENGTH(m, rp); memcpy(rp, serv->location, m); rp += m; m = strlen(serv->st); CODELENGTH(m, rp); memcpy(rp, serv->st, m); rp += m; m = strlen(serv->usn); CODELENGTH(m, rp); memcpy(rp, serv->usn, m); rp += m; nrep++; } } rbuf[0] = nrep; syslog(LOG_DEBUG, "(s=%d) response : %d device%s", req->socket, nrep, (nrep > 1) ? "s" : ""); if(write_or_buffer(req, rbuf, rp - rbuf) < 0) { syslog(LOG_ERR, "(s=%d) write: %m", req->socket); goto error; } break; case MINISSDPD_SUBMIT: /* submit service */ newserv = malloc(sizeof(struct service)); if(!newserv) { syslog(LOG_ERR, "cannot allocate memory"); goto error; } memset(newserv, 0, sizeof(struct service)); /* set pointers to NULL */ if(containsForbiddenChars(p, l)) { syslog(LOG_ERR, "bad request (st contains forbidden chars)"); goto error; } newserv->st = malloc(l + 1); if(!newserv->st) { syslog(LOG_ERR, "cannot allocate memory"); goto error; } memcpy(newserv->st, p, l); newserv->st[l] = '\0'; p += l; if(p >= buf + n) { syslog(LOG_WARNING, "bad request (missing usn)"); goto error; } DECODELENGTH_CHECKLIMIT(l, p, buf + n); if(l > (unsigned)(buf+n-p)) { syslog(LOG_WARNING, "bad request (length encoding)"); goto error; } if(containsForbiddenChars(p, l)) { syslog(LOG_ERR, "bad request (usn contains forbidden chars)"); goto error; } syslog(LOG_INFO, "usn='%.*s'", l, p); newserv->usn = malloc(l + 1); if(!newserv->usn) { syslog(LOG_ERR, "cannot allocate memory"); goto error; } memcpy(newserv->usn, p, l); newserv->usn[l] = '\0'; p += l; DECODELENGTH_CHECKLIMIT(l, p, buf + n); if(l > (unsigned)(buf+n-p)) { syslog(LOG_WARNING, "bad request (length encoding)"); goto error; } if(containsForbiddenChars(p, l)) { syslog(LOG_ERR, "bad request (server contains forbidden chars)"); goto error; } syslog(LOG_INFO, "server='%.*s'", l, p); newserv->server = malloc(l + 1); if(!newserv->server) { syslog(LOG_ERR, "cannot allocate memory"); goto error; } memcpy(newserv->server, p, l); newserv->server[l] = '\0'; p += l; DECODELENGTH_CHECKLIMIT(l, p, buf + n); if(l > (unsigned)(buf+n-p)) { syslog(LOG_WARNING, "bad request (length encoding)"); goto error; } if(containsForbiddenChars(p, l)) { syslog(LOG_ERR, "bad request (location contains forbidden chars)"); goto error; } syslog(LOG_INFO, "location='%.*s'", l, p); newserv->location = malloc(l + 1); if(!newserv->location) { syslog(LOG_ERR, "cannot allocate memory"); goto error; } memcpy(newserv->location, p, l); newserv->location[l] = '\0'; /* look in service list for duplicate */ for(serv = servicelisthead.lh_first; serv; serv = serv->entries.le_next) { if(0 == strcmp(newserv->usn, serv->usn) && 0 == strcmp(newserv->st, serv->st)) { syslog(LOG_INFO, "Service already in the list. Updating..."); free(newserv->st); free(newserv->usn); free(serv->server); serv->server = newserv->server; free(serv->location); serv->location = newserv->location; free(newserv); newserv = NULL; return; } } /* Inserting new service */ LIST_INSERT_HEAD(&servicelisthead, newserv, entries); sendNotifications(NOTIF_NEW, NULL, newserv); newserv = NULL; break; case MINISSDPD_NOTIF: /* switch socket to notify */ rbuf[0] = '\0'; if(write_or_buffer(req, rbuf, 1) < 0) { syslog(LOG_ERR, "(s=%d) write: %m", req->socket); goto error; } req->is_notify = 1; break; default: syslog(LOG_WARNING, "Unknown request type %d", type); rbuf[0] = '\0'; if(write_or_buffer(req, rbuf, 1) < 0) { syslog(LOG_ERR, "(s=%d) write: %m", req->socket); goto error; } } return; error: if(newserv) { free(newserv->st); free(newserv->usn); free(newserv->server); free(newserv->location); free(newserv); newserv = NULL; } close(req->socket); req->socket = -1; return; }
168,844
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 RunFwdTxfm(const int16_t *in, int16_t *out, int stride) { fwd_txfm_(in, out, stride); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void RunFwdTxfm(const int16_t *in, int16_t *out, int stride) { void RunFwdTxfm(const int16_t *in, tran_low_t *out, int stride) { fwd_txfm_(in, out, stride); }
174,549
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 hugepage_madvise(struct vm_area_struct *vma, unsigned long *vm_flags, int advice) { switch (advice) { case MADV_HUGEPAGE: /* * Be somewhat over-protective like KSM for now! */ if (*vm_flags & (VM_HUGEPAGE | VM_SHARED | VM_MAYSHARE | VM_PFNMAP | VM_IO | VM_DONTEXPAND | VM_RESERVED | VM_HUGETLB | VM_INSERTPAGE | VM_MIXEDMAP | VM_SAO)) return -EINVAL; *vm_flags &= ~VM_NOHUGEPAGE; *vm_flags |= VM_HUGEPAGE; /* * If the vma become good for khugepaged to scan, * register it here without waiting a page fault that * may not happen any time soon. */ if (unlikely(khugepaged_enter_vma_merge(vma))) return -ENOMEM; break; case MADV_NOHUGEPAGE: /* * Be somewhat over-protective like KSM for now! */ if (*vm_flags & (VM_NOHUGEPAGE | VM_SHARED | VM_MAYSHARE | VM_PFNMAP | VM_IO | VM_DONTEXPAND | VM_RESERVED | VM_HUGETLB | VM_INSERTPAGE | VM_MIXEDMAP | VM_SAO)) return -EINVAL; *vm_flags &= ~VM_HUGEPAGE; *vm_flags |= VM_NOHUGEPAGE; /* * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning * this vma even if we leave the mm registered in khugepaged if * it got registered before VM_NOHUGEPAGE was set. */ break; } return 0; } Commit Message: mm: thp: fix /dev/zero MAP_PRIVATE and vm_flags cleanups The huge_memory.c THP page fault was allowed to run if vm_ops was null (which would succeed for /dev/zero MAP_PRIVATE, as the f_op->mmap wouldn't setup a special vma->vm_ops and it would fallback to regular anonymous memory) but other THP logics weren't fully activated for vmas with vm_file not NULL (/dev/zero has a not NULL vma->vm_file). So this removes the vm_file checks so that /dev/zero also can safely use THP (the other albeit safer approach to fix this bug would have been to prevent the THP initial page fault to run if vm_file was set). After removing the vm_file checks, this also makes huge_memory.c stricter in khugepaged for the DEBUG_VM=y case. It doesn't replace the vm_file check with a is_pfn_mapping check (but it keeps checking for VM_PFNMAP under VM_BUG_ON) because for a is_cow_mapping() mapping VM_PFNMAP should only be allowed to exist before the first page fault, and in turn when vma->anon_vma is null (so preventing khugepaged registration). So I tend to think the previous comment saying if vm_file was set, VM_PFNMAP might have been set and we could still be registered in khugepaged (despite anon_vma was not NULL to be registered in khugepaged) was too paranoid. The is_linear_pfn_mapping check is also I think superfluous (as described by comment) but under DEBUG_VM it is safe to stay. Addresses https://bugzilla.kernel.org/show_bug.cgi?id=33682 Signed-off-by: Andrea Arcangeli <[email protected]> Reported-by: Caspar Zhang <[email protected]> Acked-by: Mel Gorman <[email protected]> Acked-by: Rik van Riel <[email protected]> Cc: <[email protected]> [2.6.38.x] Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399
int hugepage_madvise(struct vm_area_struct *vma, unsigned long *vm_flags, int advice) { switch (advice) { case MADV_HUGEPAGE: /* * Be somewhat over-protective like KSM for now! */ if (*vm_flags & (VM_HUGEPAGE | VM_NO_THP)) return -EINVAL; *vm_flags &= ~VM_NOHUGEPAGE; *vm_flags |= VM_HUGEPAGE; /* * If the vma become good for khugepaged to scan, * register it here without waiting a page fault that * may not happen any time soon. */ if (unlikely(khugepaged_enter_vma_merge(vma))) return -ENOMEM; break; case MADV_NOHUGEPAGE: /* * Be somewhat over-protective like KSM for now! */ if (*vm_flags & (VM_NOHUGEPAGE | VM_NO_THP)) return -EINVAL; *vm_flags &= ~VM_HUGEPAGE; *vm_flags |= VM_NOHUGEPAGE; /* * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning * this vma even if we leave the mm registered in khugepaged if * it got registered before VM_NOHUGEPAGE was set. */ break; } return 0; }
166,226
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 Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { const char *section_name = ""; const char *link_section_name = ""; char *end = NULL; Elf_(Shdr) *link_shdr = NULL; ut8 dfs[sizeof (Elf_(Verdef))] = {0}; Sdb *sdb; int cnt, i; if (shdr->sh_link > bin->ehdr.e_shnum) { return false; } link_shdr = &bin->shdr[shdr->sh_link]; if (shdr->sh_size < 1) { return false; } Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char)); if (!defs) { return false; } if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!defs) { bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n"); return NULL; } sdb = sdb_new0 (); end = (char *)defs + shdr->sh_size; sdb_set (sdb, "section_name", section_name, 0); sdb_num_set (sdb, "entries", shdr->sh_info, 0); sdb_num_set (sdb, "addr", shdr->sh_addr, 0); sdb_num_set (sdb, "offset", shdr->sh_offset, 0); sdb_num_set (sdb, "link", shdr->sh_link, 0); sdb_set (sdb, "link_section_name", link_section_name, 0); for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) { Sdb *sdb_verdef = sdb_new0 (); char *vstart = ((char*)defs) + i; char key[32] = {0}; Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart; Elf_(Verdaux) aux = {0}; int j = 0; int isum = 0; r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef))); verdef->vd_version = READ16 (dfs, j) verdef->vd_flags = READ16 (dfs, j) verdef->vd_ndx = READ16 (dfs, j) verdef->vd_cnt = READ16 (dfs, j) verdef->vd_hash = READ32 (dfs, j) verdef->vd_aux = READ32 (dfs, j) verdef->vd_next = READ32 (dfs, j) vstart += verdef->vd_aux; if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); goto out_error; } j = 0; aux.vda_name = READ32 (vstart, j) aux.vda_next = READ32 (vstart, j) isum = i + verdef->vd_aux; if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); goto out_error; } sdb_num_set (sdb_verdef, "idx", i, 0); sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0); sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0); sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0); sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0); sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0); for (j = 1; j < verdef->vd_cnt; ++j) { int k; Sdb *sdb_parent = sdb_new0 (); isum += aux.vda_next; vstart += aux.vda_next; if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } k = 0; aux.vda_name = READ32 (vstart, k) aux.vda_next = READ32 (vstart, k) if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } sdb_num_set (sdb_parent, "idx", isum, 0); sdb_num_set (sdb_parent, "parent", j, 0); sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0); snprintf (key, sizeof (key), "parent%d", j - 1); sdb_ns_set (sdb_verdef, key, sdb_parent); } snprintf (key, sizeof (key), "verdef%d", cnt); sdb_ns_set (sdb, key, sdb_verdef); if (!verdef->vd_next) { sdb_free (sdb_verdef); goto out_error; } if ((st32)verdef->vd_next < 1) { eprintf ("Warning: Invalid vd_next in the ELF version\n"); break; } i += verdef->vd_next; } free (defs); return sdb; out_error: free (defs); sdb_free (sdb); return NULL; } Commit Message: Fix #8743 - Crash in ELF version parser on 32bit systems CWE ID: CWE-125
static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { const char *section_name = ""; const char *link_section_name = ""; char *end = NULL; Elf_(Shdr) *link_shdr = NULL; ut8 dfs[sizeof (Elf_(Verdef))] = {0}; Sdb *sdb; int cnt, i; if (shdr->sh_link > bin->ehdr.e_shnum) { return false; } link_shdr = &bin->shdr[shdr->sh_link]; if (shdr->sh_size < 1) { return false; } Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char)); if (!defs) { return false; } if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!defs) { bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n"); return NULL; } sdb = sdb_new0 (); end = (char *)defs + shdr->sh_size; sdb_set (sdb, "section_name", section_name, 0); sdb_num_set (sdb, "entries", shdr->sh_info, 0); sdb_num_set (sdb, "addr", shdr->sh_addr, 0); sdb_num_set (sdb, "offset", shdr->sh_offset, 0); sdb_num_set (sdb, "link", shdr->sh_link, 0); sdb_set (sdb, "link_section_name", link_section_name, 0); for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) { Sdb *sdb_verdef = sdb_new0 (); char *vstart = ((char*)defs) + i; char key[32] = {0}; Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart; Elf_(Verdaux) aux = {0}; int j = 0; int isum = 0; r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef))); verdef->vd_version = READ16 (dfs, j) verdef->vd_flags = READ16 (dfs, j) verdef->vd_ndx = READ16 (dfs, j) verdef->vd_cnt = READ16 (dfs, j) verdef->vd_hash = READ32 (dfs, j) verdef->vd_aux = READ32 (dfs, j) verdef->vd_next = READ32 (dfs, j) int vdaux = verdef->vd_aux; if (vdaux < 1) { sdb_free (sdb_verdef); goto out_error; } vstart += vdaux; if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); goto out_error; } j = 0; aux.vda_name = READ32 (vstart, j) aux.vda_next = READ32 (vstart, j) isum = i + verdef->vd_aux; if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); goto out_error; } sdb_num_set (sdb_verdef, "idx", i, 0); sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0); sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0); sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0); sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0); sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0); for (j = 1; j < verdef->vd_cnt; ++j) { int k; Sdb *sdb_parent = sdb_new0 (); isum += aux.vda_next; vstart += aux.vda_next; if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } k = 0; aux.vda_name = READ32 (vstart, k) aux.vda_next = READ32 (vstart, k) if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } sdb_num_set (sdb_parent, "idx", isum, 0); sdb_num_set (sdb_parent, "parent", j, 0); sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0); snprintf (key, sizeof (key), "parent%d", j - 1); sdb_ns_set (sdb_verdef, key, sdb_parent); } snprintf (key, sizeof (key), "verdef%d", cnt); sdb_ns_set (sdb, key, sdb_verdef); if (!verdef->vd_next) { sdb_free (sdb_verdef); goto out_error; } if ((st32)verdef->vd_next < 1) { eprintf ("Warning: Invalid vd_next in the ELF version\n"); break; } i += verdef->vd_next; } free (defs); return sdb; out_error: free (defs); sdb_free (sdb); return NULL; }
167,711
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: OMX_ERRORTYPE omx_video::use_input_buffer( OMX_IN OMX_HANDLETYPE hComp, OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr, OMX_IN OMX_U32 port, OMX_IN OMX_PTR appData, OMX_IN OMX_U32 bytes, OMX_IN OMX_U8* buffer) { (void) hComp; OMX_ERRORTYPE eRet = OMX_ErrorNone; unsigned i = 0; unsigned char *buf_addr = NULL; DEBUG_PRINT_HIGH("use_input_buffer: port = %u appData = %p bytes = %u buffer = %p",(unsigned int)port,appData,(unsigned int)bytes,buffer); if (bytes != m_sInPortDef.nBufferSize) { DEBUG_PRINT_ERROR("ERROR: use_input_buffer: Size Mismatch!! " "bytes[%u] != Port.nBufferSize[%u]", (unsigned int)bytes, (unsigned int)m_sInPortDef.nBufferSize); return OMX_ErrorBadParameter; } if (!m_inp_mem_ptr) { input_use_buffer = true; m_inp_mem_ptr = (OMX_BUFFERHEADERTYPE*) \ calloc( (sizeof(OMX_BUFFERHEADERTYPE)), m_sInPortDef.nBufferCountActual); if (m_inp_mem_ptr == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_inp_mem_ptr"); return OMX_ErrorInsufficientResources; } DEBUG_PRINT_LOW("Successfully allocated m_inp_mem_ptr = %p", m_inp_mem_ptr); m_pInput_pmem = (struct pmem *) calloc(sizeof (struct pmem), m_sInPortDef.nBufferCountActual); if (m_pInput_pmem == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_pmem"); return OMX_ErrorInsufficientResources; } #ifdef USE_ION m_pInput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sInPortDef.nBufferCountActual); if (m_pInput_ion == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_ion"); return OMX_ErrorInsufficientResources; } #endif for (i=0; i< m_sInPortDef.nBufferCountActual; i++) { m_pInput_pmem[i].fd = -1; #ifdef USE_ION m_pInput_ion[i].ion_device_fd =-1; m_pInput_ion[i].fd_ion_data.fd =-1; m_pInput_ion[i].ion_alloc_data.handle = 0; #endif } } for (i=0; i< m_sInPortDef.nBufferCountActual; i++) { if (BITMASK_ABSENT(&m_inp_bm_count,i)) { break; } } if (i < m_sInPortDef.nBufferCountActual) { *bufferHdr = (m_inp_mem_ptr + i); BITMASK_SET(&m_inp_bm_count,i); (*bufferHdr)->pBuffer = (OMX_U8 *)buffer; (*bufferHdr)->nSize = sizeof(OMX_BUFFERHEADERTYPE); (*bufferHdr)->nVersion.nVersion = OMX_SPEC_VERSION; (*bufferHdr)->nAllocLen = m_sInPortDef.nBufferSize; (*bufferHdr)->pAppPrivate = appData; (*bufferHdr)->nInputPortIndex = PORT_INDEX_IN; if (!m_use_input_pmem) { #ifdef USE_ION #ifdef _MSM8974_ m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize, &m_pInput_ion[i].ion_alloc_data, &m_pInput_ion[i].fd_ion_data,0); #else m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize, &m_pInput_ion[i].ion_alloc_data, &m_pInput_ion[i].fd_ion_data,ION_FLAG_CACHED); #endif if (m_pInput_ion[i].ion_device_fd < 0) { DEBUG_PRINT_ERROR("ERROR:ION device open() Failed"); return OMX_ErrorInsufficientResources; } m_pInput_pmem[i].fd = m_pInput_ion[i].fd_ion_data.fd; #else m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); if (m_pInput_pmem[i].fd == 0) { m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); } if (m_pInput_pmem[i] .fd < 0) { DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() Failed"); return OMX_ErrorInsufficientResources; } #endif m_pInput_pmem[i].size = m_sInPortDef.nBufferSize; m_pInput_pmem[i].offset = 0; m_pInput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR; if(!secure_session) { m_pInput_pmem[i].buffer = (unsigned char *)mmap( NULL,m_pInput_pmem[i].size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pInput_pmem[i].fd,0); if (m_pInput_pmem[i].buffer == MAP_FAILED) { DEBUG_PRINT_ERROR("ERROR: mmap() Failed"); close(m_pInput_pmem[i].fd); #ifdef USE_ION free_ion_memory(&m_pInput_ion[i]); #endif return OMX_ErrorInsufficientResources; } } } else { OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *pParam = reinterpret_cast<OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *>((*bufferHdr)->pAppPrivate); DEBUG_PRINT_LOW("Inside qcom_ext with luma:(fd:%lu,offset:0x%x)", pParam->pmem_fd, (unsigned)pParam->offset); if (pParam) { m_pInput_pmem[i].fd = pParam->pmem_fd; m_pInput_pmem[i].offset = pParam->offset; m_pInput_pmem[i].size = m_sInPortDef.nBufferSize; m_pInput_pmem[i].buffer = (unsigned char *)buffer; DEBUG_PRINT_LOW("DBG:: pParam->pmem_fd = %u, pParam->offset = %u", (unsigned int)pParam->pmem_fd, (unsigned int)pParam->offset); } else { DEBUG_PRINT_ERROR("ERROR: Invalid AppData given for PMEM i/p UseBuffer case"); return OMX_ErrorBadParameter; } } DEBUG_PRINT_LOW("use_inp:: bufhdr = %p, pBuffer = %p, m_pInput_pmem[i].buffer = %p", (*bufferHdr), (*bufferHdr)->pBuffer, m_pInput_pmem[i].buffer); if ( dev_use_buf(&m_pInput_pmem[i],PORT_INDEX_IN,i) != true) { DEBUG_PRINT_ERROR("ERROR: dev_use_buf() Failed for i/p buf"); return OMX_ErrorInsufficientResources; } } else { DEBUG_PRINT_ERROR("ERROR: All buffers are already used, invalid use_buf call for " "index = %u", i); eRet = OMX_ErrorInsufficientResources; } return eRet; } Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers Heap pointers do not point to user virtual addresses in case of secure session. Set them to NULL and add checks to avoid accesing them Bug: 28815329 Bug: 28920116 Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26 CWE ID: CWE-200
OMX_ERRORTYPE omx_video::use_input_buffer( OMX_IN OMX_HANDLETYPE hComp, OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr, OMX_IN OMX_U32 port, OMX_IN OMX_PTR appData, OMX_IN OMX_U32 bytes, OMX_IN OMX_U8* buffer) { (void) hComp; OMX_ERRORTYPE eRet = OMX_ErrorNone; unsigned i = 0; unsigned char *buf_addr = NULL; DEBUG_PRINT_HIGH("use_input_buffer: port = %u appData = %p bytes = %u buffer = %p",(unsigned int)port,appData,(unsigned int)bytes,buffer); if (bytes != m_sInPortDef.nBufferSize) { DEBUG_PRINT_ERROR("ERROR: use_input_buffer: Size Mismatch!! " "bytes[%u] != Port.nBufferSize[%u]", (unsigned int)bytes, (unsigned int)m_sInPortDef.nBufferSize); return OMX_ErrorBadParameter; } if (!m_inp_mem_ptr) { input_use_buffer = true; m_inp_mem_ptr = (OMX_BUFFERHEADERTYPE*) \ calloc( (sizeof(OMX_BUFFERHEADERTYPE)), m_sInPortDef.nBufferCountActual); if (m_inp_mem_ptr == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_inp_mem_ptr"); return OMX_ErrorInsufficientResources; } DEBUG_PRINT_LOW("Successfully allocated m_inp_mem_ptr = %p", m_inp_mem_ptr); m_pInput_pmem = (struct pmem *) calloc(sizeof (struct pmem), m_sInPortDef.nBufferCountActual); if (m_pInput_pmem == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_pmem"); return OMX_ErrorInsufficientResources; } #ifdef USE_ION m_pInput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sInPortDef.nBufferCountActual); if (m_pInput_ion == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_ion"); return OMX_ErrorInsufficientResources; } #endif for (i=0; i< m_sInPortDef.nBufferCountActual; i++) { m_pInput_pmem[i].fd = -1; #ifdef USE_ION m_pInput_ion[i].ion_device_fd =-1; m_pInput_ion[i].fd_ion_data.fd =-1; m_pInput_ion[i].ion_alloc_data.handle = 0; #endif } } for (i=0; i< m_sInPortDef.nBufferCountActual; i++) { if (BITMASK_ABSENT(&m_inp_bm_count,i)) { break; } } if (i < m_sInPortDef.nBufferCountActual) { *bufferHdr = (m_inp_mem_ptr + i); BITMASK_SET(&m_inp_bm_count,i); (*bufferHdr)->pBuffer = (OMX_U8 *)buffer; (*bufferHdr)->nSize = sizeof(OMX_BUFFERHEADERTYPE); (*bufferHdr)->nVersion.nVersion = OMX_SPEC_VERSION; (*bufferHdr)->nAllocLen = m_sInPortDef.nBufferSize; (*bufferHdr)->pAppPrivate = appData; (*bufferHdr)->nInputPortIndex = PORT_INDEX_IN; if (!m_use_input_pmem) { #ifdef USE_ION #ifdef _MSM8974_ m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize, &m_pInput_ion[i].ion_alloc_data, &m_pInput_ion[i].fd_ion_data,0); #else m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize, &m_pInput_ion[i].ion_alloc_data, &m_pInput_ion[i].fd_ion_data,ION_FLAG_CACHED); #endif if (m_pInput_ion[i].ion_device_fd < 0) { DEBUG_PRINT_ERROR("ERROR:ION device open() Failed"); return OMX_ErrorInsufficientResources; } m_pInput_pmem[i].fd = m_pInput_ion[i].fd_ion_data.fd; #else m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); if (m_pInput_pmem[i].fd == 0) { m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); } if (m_pInput_pmem[i] .fd < 0) { DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() Failed"); return OMX_ErrorInsufficientResources; } #endif m_pInput_pmem[i].size = m_sInPortDef.nBufferSize; m_pInput_pmem[i].offset = 0; m_pInput_pmem[i].buffer = NULL; if(!secure_session) { m_pInput_pmem[i].buffer = (unsigned char *)mmap( NULL,m_pInput_pmem[i].size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pInput_pmem[i].fd,0); if (m_pInput_pmem[i].buffer == MAP_FAILED) { DEBUG_PRINT_ERROR("ERROR: mmap() Failed"); m_pInput_pmem[i].buffer = NULL; close(m_pInput_pmem[i].fd); #ifdef USE_ION free_ion_memory(&m_pInput_ion[i]); #endif return OMX_ErrorInsufficientResources; } } } else { OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *pParam = reinterpret_cast<OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *>((*bufferHdr)->pAppPrivate); DEBUG_PRINT_LOW("Inside qcom_ext with luma:(fd:%lu,offset:0x%x)", pParam->pmem_fd, (unsigned)pParam->offset); if (pParam) { m_pInput_pmem[i].fd = pParam->pmem_fd; m_pInput_pmem[i].offset = pParam->offset; m_pInput_pmem[i].size = m_sInPortDef.nBufferSize; m_pInput_pmem[i].buffer = (unsigned char *)buffer; DEBUG_PRINT_LOW("DBG:: pParam->pmem_fd = %u, pParam->offset = %u", (unsigned int)pParam->pmem_fd, (unsigned int)pParam->offset); } else { DEBUG_PRINT_ERROR("ERROR: Invalid AppData given for PMEM i/p UseBuffer case"); return OMX_ErrorBadParameter; } } DEBUG_PRINT_LOW("use_inp:: bufhdr = %p, pBuffer = %p, m_pInput_pmem[i].buffer = %p", (*bufferHdr), (*bufferHdr)->pBuffer, m_pInput_pmem[i].buffer); if ( dev_use_buf(&m_pInput_pmem[i],PORT_INDEX_IN,i) != true) { DEBUG_PRINT_ERROR("ERROR: dev_use_buf() Failed for i/p buf"); return OMX_ErrorInsufficientResources; } } else { DEBUG_PRINT_ERROR("ERROR: All buffers are already used, invalid use_buf call for " "index = %u", i); eRet = OMX_ErrorInsufficientResources; } return eRet; }
173,503
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 IsTraceEventArgsWhitelisted(const char* category_group_name, const char* event_name) { if (base::MatchPattern(category_group_name, "toplevel") && base::MatchPattern(event_name, "*")) { return true; } return false; } Commit Message: Tracing: Add support for PII whitelisting of individual trace event arguments R=dsinclair,shatch BUG=546093 Review URL: https://codereview.chromium.org/1415013003 Cr-Commit-Position: refs/heads/master@{#356690} CWE ID: CWE-399
bool IsTraceEventArgsWhitelisted(const char* category_group_name, const char* event_name, ArgumentNameFilterPredicate* arg_filter) { if (base::MatchPattern(category_group_name, "toplevel") && base::MatchPattern(event_name, "*")) { return true; } if (base::MatchPattern(category_group_name, "benchmark") && base::MatchPattern(event_name, "granularly_whitelisted")) { *arg_filter = base::Bind(&IsArgNameWhitelisted); return true; } return false; }
171,679
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 MediaStreamManager::StopStreamDevice(int render_process_id, int render_frame_id, const std::string& device_id, int session_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DVLOG(1) << "StopStreamDevice({render_frame_id = " << render_frame_id << "} " << ", {device_id = " << device_id << "}, session_id = " << session_id << "})"; Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Reviewed-by: Olga Sharonova <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#616347} CWE ID: CWE-189
void MediaStreamManager::StopStreamDevice(int render_process_id, int render_frame_id, int requester_id, const std::string& device_id, int session_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DVLOG(1) << "StopStreamDevice({render_frame_id = " << render_frame_id << "} " << ", {device_id = " << device_id << "}, session_id = " << session_id << "})";
173,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 HttpAuthFilterWhitelist::AddRuleToBypassLocal() { rules_.AddRuleToBypassLocal(); } Commit Message: Implicitly bypass localhost when proxying requests. This aligns Chrome's behavior with the Windows and macOS proxy resolvers (but not Firefox). Concretely: * localhost names (as determined by net::IsLocalhost) now implicitly bypass the proxy * link-local IP addresses implicitly bypass the proxy The implicit rules are handled by ProxyBypassRules, and it is possible to override them when manually configuring proxy settings (but not when using PAC or auto-detect). This change also adds support for the "<-loopback>" proxy bypass rule, with similar semantics as it has on Windows (removes the implicit bypass rules for localhost and link-local). The compatibility risk of this change should be low as proxying through localhost was not universally supported. It is however an idiom used in testing (a number of our own tests had such a dependency). Impacted users can use the "<-loopback>" bypass rule as a workaround. Bug: 413511, 899126, 901896 Change-Id: I263ca21ef9f12d4759a20cb4751dc3261bda6ac0 Reviewed-on: https://chromium-review.googlesource.com/c/1303626 Commit-Queue: Eric Roman <[email protected]> Reviewed-by: Dominick Ng <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Reviewed-by: Matt Menke <[email protected]> Reviewed-by: Sami Kyöstilä <[email protected]> Cr-Commit-Position: refs/heads/master@{#606112} CWE ID: CWE-20
void HttpAuthFilterWhitelist::AddRuleToBypassLocal() {
172,643
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 vcc_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct atm_vcc *vcc; struct sk_buff *skb; int copied, error = -EINVAL; msg->msg_namelen = 0; if (sock->state != SS_CONNECTED) return -ENOTCONN; /* only handle MSG_DONTWAIT and MSG_PEEK */ if (flags & ~(MSG_DONTWAIT | MSG_PEEK)) return -EOPNOTSUPP; vcc = ATM_SD(sock); if (test_bit(ATM_VF_RELEASED, &vcc->flags) || test_bit(ATM_VF_CLOSE, &vcc->flags) || !test_bit(ATM_VF_READY, &vcc->flags)) return 0; skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &error); if (!skb) return error; copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } error = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (error) return error; sock_recv_ts_and_drops(msg, sk, skb); if (!(flags & MSG_PEEK)) { pr_debug("%d -= %d\n", atomic_read(&sk->sk_rmem_alloc), skb->truesize); atm_return(vcc, skb->truesize); } skb_free_datagram(sk, skb); return copied; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
int vcc_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct atm_vcc *vcc; struct sk_buff *skb; int copied, error = -EINVAL; if (sock->state != SS_CONNECTED) return -ENOTCONN; /* only handle MSG_DONTWAIT and MSG_PEEK */ if (flags & ~(MSG_DONTWAIT | MSG_PEEK)) return -EOPNOTSUPP; vcc = ATM_SD(sock); if (test_bit(ATM_VF_RELEASED, &vcc->flags) || test_bit(ATM_VF_CLOSE, &vcc->flags) || !test_bit(ATM_VF_READY, &vcc->flags)) return 0; skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &error); if (!skb) return error; copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } error = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (error) return error; sock_recv_ts_and_drops(msg, sk, skb); if (!(flags & MSG_PEEK)) { pr_debug("%d -= %d\n", atomic_read(&sk->sk_rmem_alloc), skb->truesize); atm_return(vcc, skb->truesize); } skb_free_datagram(sk, skb); return copied; }
166,489
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int setup_ttydir_console(const struct lxc_rootfs *rootfs, const struct lxc_console *console, char *ttydir) { char path[MAXPATHLEN], lxcpath[MAXPATHLEN]; int ret; /* create rootfs/dev/<ttydir> directory */ ret = snprintf(path, sizeof(path), "%s/dev/%s", rootfs->mount, ttydir); if (ret >= sizeof(path)) return -1; ret = mkdir(path, 0755); if (ret && errno != EEXIST) { SYSERROR("failed with errno %d to create %s", errno, path); return -1; } INFO("created %s", path); ret = snprintf(lxcpath, sizeof(lxcpath), "%s/dev/%s/console", rootfs->mount, ttydir); if (ret >= sizeof(lxcpath)) { ERROR("console path too long"); return -1; } snprintf(path, sizeof(path), "%s/dev/console", rootfs->mount); ret = unlink(path); if (ret && errno != ENOENT) { SYSERROR("error unlinking %s", path); return -1; } ret = creat(lxcpath, 0660); if (ret==-1 && errno != EEXIST) { SYSERROR("error %d creating %s", errno, lxcpath); return -1; } if (ret >= 0) close(ret); if (console->master < 0) { INFO("no console"); return 0; } if (mount(console->name, lxcpath, "none", MS_BIND, 0)) { ERROR("failed to mount '%s' on '%s'", console->name, lxcpath); return -1; } /* create symlink from rootfs/dev/console to 'lxc/console' */ ret = snprintf(lxcpath, sizeof(lxcpath), "%s/console", ttydir); if (ret >= sizeof(lxcpath)) { ERROR("lxc/console path too long"); return -1; } ret = symlink(lxcpath, path); if (ret) { SYSERROR("failed to create symlink for console"); return -1; } INFO("console has been setup on %s", lxcpath); return 0; } Commit Message: CVE-2015-1335: Protect container mounts against symlinks When a container starts up, lxc sets up the container's inital fstree by doing a bunch of mounting, guided by the container configuration file. The container config is owned by the admin or user on the host, so we do not try to guard against bad entries. However, since the mount target is in the container, it's possible that the container admin could divert the mount with symbolic links. This could bypass proper container startup (i.e. confinement of a root-owned container by the restrictive apparmor policy, by diverting the required write to /proc/self/attr/current), or bypass the (path-based) apparmor policy by diverting, say, /proc to /mnt in the container. To prevent this, 1. do not allow mounts to paths containing symbolic links 2. do not allow bind mounts from relative paths containing symbolic links. Details: Define safe_mount which ensures that the container has not inserted any symbolic links into any mount targets for mounts to be done during container setup. The host's mount path may contain symbolic links. As it is under the control of the administrator, that's ok. So safe_mount begins the check for symbolic links after the rootfs->mount, by opening that directory. It opens each directory along the path using openat() relative to the parent directory using O_NOFOLLOW. When the target is reached, it mounts onto /proc/self/fd/<targetfd>. Use safe_mount() in mount_entry(), when mounting container proc, and when needed. In particular, safe_mount() need not be used in any case where: 1. the mount is done in the container's namespace 2. the mount is for the container's rootfs 3. the mount is relative to a tmpfs or proc/sysfs which we have just safe_mount()ed ourselves Since we were using proc/net as a temporary placeholder for /proc/sys/net during container startup, and proc/net is a symbolic link, use proc/tty instead. Update the lxc.container.conf manpage with details about the new restrictions. Finally, add a testcase to test some symbolic link possibilities. Reported-by: Roman Fiedler Signed-off-by: Serge Hallyn <[email protected]> Acked-by: Stéphane Graber <[email protected]> CWE ID: CWE-59
static int setup_ttydir_console(const struct lxc_rootfs *rootfs, const struct lxc_console *console, char *ttydir) { char path[MAXPATHLEN], lxcpath[MAXPATHLEN]; int ret; /* create rootfs/dev/<ttydir> directory */ ret = snprintf(path, sizeof(path), "%s/dev/%s", rootfs->mount, ttydir); if (ret >= sizeof(path)) return -1; ret = mkdir(path, 0755); if (ret && errno != EEXIST) { SYSERROR("failed with errno %d to create %s", errno, path); return -1; } INFO("created %s", path); ret = snprintf(lxcpath, sizeof(lxcpath), "%s/dev/%s/console", rootfs->mount, ttydir); if (ret >= sizeof(lxcpath)) { ERROR("console path too long"); return -1; } snprintf(path, sizeof(path), "%s/dev/console", rootfs->mount); ret = unlink(path); if (ret && errno != ENOENT) { SYSERROR("error unlinking %s", path); return -1; } ret = creat(lxcpath, 0660); if (ret==-1 && errno != EEXIST) { SYSERROR("error %d creating %s", errno, lxcpath); return -1; } if (ret >= 0) close(ret); if (console->master < 0) { INFO("no console"); return 0; } if (safe_mount(console->name, lxcpath, "none", MS_BIND, 0, rootfs->mount)) { ERROR("failed to mount '%s' on '%s'", console->name, lxcpath); return -1; } /* create symlink from rootfs/dev/console to 'lxc/console' */ ret = snprintf(lxcpath, sizeof(lxcpath), "%s/console", ttydir); if (ret >= sizeof(lxcpath)) { ERROR("lxc/console path too long"); return -1; } ret = symlink(lxcpath, path); if (ret) { SYSERROR("failed to create symlink for console"); return -1; } INFO("console has been setup on %s", lxcpath); return 0; }
166,721
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 CameraClient::dump(int fd, const Vector<String16>& args) { const size_t SIZE = 256; char buffer[SIZE]; size_t len = snprintf(buffer, SIZE, "Client[%d] (%p) PID: %d\n", mCameraId, getRemoteCallback()->asBinder().get(), mClientPid); len = (len > SIZE - 1) ? SIZE - 1 : len; write(fd, buffer, len); return mHardware->dump(fd, args); } Commit Message: Camera: Disallow dumping clients directly Camera service dumps should only be initiated through ICameraService::dump. Bug: 26265403 Change-Id: If3ca4718ed74bf33ad8a416192689203029e2803 CWE ID: CWE-264
status_t CameraClient::dump(int fd, const Vector<String16>& args) { return BasicClient::dump(fd, args); } status_t CameraClient::dumpClient(int fd, const Vector<String16>& args) { const size_t SIZE = 256; char buffer[SIZE]; size_t len = snprintf(buffer, SIZE, "Client[%d] (%p) PID: %d\n", mCameraId, getRemoteCallback()->asBinder().get(), mClientPid); len = (len > SIZE - 1) ? SIZE - 1 : len; write(fd, buffer, len); return mHardware->dump(fd, args); }
173,938
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_put_le_8byte (SF_PRIVATE *psf, sf_count_t x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8) { psf->header [psf->headindex++] = x ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = (x >> 32) ; psf->header [psf->headindex++] = (x >> 40) ; psf->header [psf->headindex++] = (x >> 48) ; psf->header [psf->headindex++] = (x >> 56) ; } ; } /* header_put_le_8byte */ 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_put_le_8byte (SF_PRIVATE *psf, sf_count_t x) { psf->header.ptr [psf->header.indx++] = x ; psf->header.ptr [psf->header.indx++] = (x >> 8) ; psf->header.ptr [psf->header.indx++] = (x >> 16) ; psf->header.ptr [psf->header.indx++] = (x >> 24) ; psf->header.ptr [psf->header.indx++] = (x >> 32) ; psf->header.ptr [psf->header.indx++] = (x >> 40) ; psf->header.ptr [psf->header.indx++] = (x >> 48) ; psf->header.ptr [psf->header.indx++] = (x >> 56) ; } /* header_put_le_8byte */
170,056
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: nfs3svc_decode_symlinkargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_symlinkargs *args) { unsigned int len, avail; char *old, *new; struct kvec *vec; if (!(p = decode_fh(p, &args->ffh)) || !(p = decode_filename(p, &args->fname, &args->flen)) ) return 0; p = decode_sattr3(p, &args->attrs); /* now decode the pathname, which might be larger than the first page. * As we have to check for nul's anyway, we copy it into a new page * This page appears in the rq_res.pages list, but as pages_len is always * 0, it won't get in the way */ len = ntohl(*p++); if (len == 0 || len > NFS3_MAXPATHLEN || len >= PAGE_SIZE) return 0; args->tname = new = page_address(*(rqstp->rq_next_page++)); args->tlen = len; /* first copy and check from the first page */ old = (char*)p; vec = &rqstp->rq_arg.head[0]; avail = vec->iov_len - (old - (char*)vec->iov_base); while (len && avail && *old) { *new++ = *old++; len--; avail--; } /* now copy next page if there is one */ if (len && !avail && rqstp->rq_arg.page_len) { avail = min_t(unsigned int, rqstp->rq_arg.page_len, PAGE_SIZE); old = page_address(rqstp->rq_arg.pages[0]); } while (len && avail && *old) { *new++ = *old++; len--; avail--; } *new = '\0'; if (len) return 0; return 1; } Commit Message: nfsd: stricter decoding of write-like NFSv2/v3 ops The NFSv2/v3 code does not systematically check whether we decode past the end of the buffer. This generally appears to be harmless, but there are a few places where we do arithmetic on the pointers involved and don't account for the possibility that a length could be negative. Add checks to catch these. Reported-by: Tuomas Haanpää <[email protected]> Reported-by: Ari Kauppi <[email protected]> Reviewed-by: NeilBrown <[email protected]> Cc: [email protected] Signed-off-by: J. Bruce Fields <[email protected]> CWE ID: CWE-119
nfs3svc_decode_symlinkargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_symlinkargs *args) { unsigned int len, avail; char *old, *new; struct kvec *vec; if (!(p = decode_fh(p, &args->ffh)) || !(p = decode_filename(p, &args->fname, &args->flen)) ) return 0; p = decode_sattr3(p, &args->attrs); /* now decode the pathname, which might be larger than the first page. * As we have to check for nul's anyway, we copy it into a new page * This page appears in the rq_res.pages list, but as pages_len is always * 0, it won't get in the way */ len = ntohl(*p++); if (len == 0 || len > NFS3_MAXPATHLEN || len >= PAGE_SIZE) return 0; args->tname = new = page_address(*(rqstp->rq_next_page++)); args->tlen = len; /* first copy and check from the first page */ old = (char*)p; vec = &rqstp->rq_arg.head[0]; if ((void *)old > vec->iov_base + vec->iov_len) return 0; avail = vec->iov_len - (old - (char*)vec->iov_base); while (len && avail && *old) { *new++ = *old++; len--; avail--; } /* now copy next page if there is one */ if (len && !avail && rqstp->rq_arg.page_len) { avail = min_t(unsigned int, rqstp->rq_arg.page_len, PAGE_SIZE); old = page_address(rqstp->rq_arg.pages[0]); } while (len && avail && *old) { *new++ = *old++; len--; avail--; } *new = '\0'; if (len) return 0; return 1; }
168,238
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 CompositorImpl::InitializeVizLayerTreeFrameSink( scoped_refptr<ws::ContextProviderCommandBuffer> context_provider) { DCHECK(enable_viz_); pending_frames_ = 0; gpu_capabilities_ = context_provider->ContextCapabilities(); scoped_refptr<base::SingleThreadTaskRunner> task_runner = base::ThreadTaskRunnerHandle::Get(); auto root_params = viz::mojom::RootCompositorFrameSinkParams::New(); root_params->send_swap_size_notifications = true; viz::mojom::CompositorFrameSinkAssociatedPtrInfo sink_info; root_params->compositor_frame_sink = mojo::MakeRequest(&sink_info); viz::mojom::CompositorFrameSinkClientRequest client_request = mojo::MakeRequest(&root_params->compositor_frame_sink_client); root_params->display_private = mojo::MakeRequest(&display_private_); display_client_ = std::make_unique<AndroidHostDisplayClient>( base::BindRepeating(&CompositorImpl::DidSwapBuffers, weak_factory_.GetWeakPtr()), base::BindRepeating( &CompositorImpl::OnFatalOrSurfaceContextCreationFailure, weak_factory_.GetWeakPtr())); root_params->display_client = display_client_->GetBoundPtr(task_runner).PassInterface(); viz::RendererSettings renderer_settings; renderer_settings.allow_antialiasing = false; renderer_settings.highp_threshold_min = 2048; renderer_settings.requires_alpha_channel = requires_alpha_channel_; renderer_settings.initial_screen_size = display::Screen::GetScreen() ->GetDisplayNearestWindow(root_window_) .GetSizeInPixel(); renderer_settings.use_skia_renderer = features::IsUsingSkiaRenderer(); renderer_settings.color_space = display_color_space_; root_params->frame_sink_id = frame_sink_id_; root_params->widget = surface_handle_; root_params->gpu_compositing = true; root_params->renderer_settings = renderer_settings; GetHostFrameSinkManager()->CreateRootCompositorFrameSink( std::move(root_params)); cc::mojo_embedder::AsyncLayerTreeFrameSink::InitParams params; params.compositor_task_runner = task_runner; params.gpu_memory_buffer_manager = BrowserMainLoop::GetInstance() ->gpu_channel_establish_factory() ->GetGpuMemoryBufferManager(); params.pipes.compositor_frame_sink_associated_info = std::move(sink_info); params.pipes.client_request = std::move(client_request); params.enable_surface_synchronization = true; params.hit_test_data_provider = std::make_unique<viz::HitTestDataProviderDrawQuad>( false /* should_ask_for_child_region */, true /* root_accepts_events */); params.client_name = kBrowser; auto layer_tree_frame_sink = std::make_unique<cc::mojo_embedder::AsyncLayerTreeFrameSink>( std::move(context_provider), nullptr, &params); host_->SetLayerTreeFrameSink(std::move(layer_tree_frame_sink)); display_private_->SetDisplayVisible(true); display_private_->Resize(size_); display_private_->SetDisplayColorSpace(display_color_space_, display_color_space_); display_private_->SetVSyncPaused(vsync_paused_); } Commit Message: gpu/android : Add support for partial swap with surface control. Add support for PostSubBuffer to GLSurfaceEGLSurfaceControl. This should allow the display compositor to draw the minimum sub-rect necessary from the damage tracking in BufferQueue on the client-side, and also to pass this damage rect to the framework. [email protected] Bug: 926020 Change-Id: I73d3320cab68250d4c6865bf21c5531682d8bf61 Reviewed-on: https://chromium-review.googlesource.com/c/1457467 Commit-Queue: Khushal <[email protected]> Commit-Queue: Antoine Labour <[email protected]> Reviewed-by: Antoine Labour <[email protected]> Auto-Submit: Khushal <[email protected]> Cr-Commit-Position: refs/heads/master@{#629852} CWE ID:
void CompositorImpl::InitializeVizLayerTreeFrameSink( scoped_refptr<ws::ContextProviderCommandBuffer> context_provider) { DCHECK(enable_viz_); pending_frames_ = 0; gpu_capabilities_ = context_provider->ContextCapabilities(); scoped_refptr<base::SingleThreadTaskRunner> task_runner = base::ThreadTaskRunnerHandle::Get(); auto root_params = viz::mojom::RootCompositorFrameSinkParams::New(); root_params->send_swap_size_notifications = true; viz::mojom::CompositorFrameSinkAssociatedPtrInfo sink_info; root_params->compositor_frame_sink = mojo::MakeRequest(&sink_info); viz::mojom::CompositorFrameSinkClientRequest client_request = mojo::MakeRequest(&root_params->compositor_frame_sink_client); root_params->display_private = mojo::MakeRequest(&display_private_); display_client_ = std::make_unique<AndroidHostDisplayClient>( base::BindRepeating(&CompositorImpl::DidSwapBuffers, weak_factory_.GetWeakPtr()), base::BindRepeating( &CompositorImpl::OnFatalOrSurfaceContextCreationFailure, weak_factory_.GetWeakPtr())); root_params->display_client = display_client_->GetBoundPtr(task_runner).PassInterface(); viz::RendererSettings renderer_settings; renderer_settings.partial_swap_enabled = true; renderer_settings.allow_antialiasing = false; renderer_settings.highp_threshold_min = 2048; renderer_settings.requires_alpha_channel = requires_alpha_channel_; renderer_settings.initial_screen_size = display::Screen::GetScreen() ->GetDisplayNearestWindow(root_window_) .GetSizeInPixel(); renderer_settings.use_skia_renderer = features::IsUsingSkiaRenderer(); renderer_settings.color_space = display_color_space_; root_params->frame_sink_id = frame_sink_id_; root_params->widget = surface_handle_; root_params->gpu_compositing = true; root_params->renderer_settings = renderer_settings; GetHostFrameSinkManager()->CreateRootCompositorFrameSink( std::move(root_params)); cc::mojo_embedder::AsyncLayerTreeFrameSink::InitParams params; params.compositor_task_runner = task_runner; params.gpu_memory_buffer_manager = BrowserMainLoop::GetInstance() ->gpu_channel_establish_factory() ->GetGpuMemoryBufferManager(); params.pipes.compositor_frame_sink_associated_info = std::move(sink_info); params.pipes.client_request = std::move(client_request); params.enable_surface_synchronization = true; params.hit_test_data_provider = std::make_unique<viz::HitTestDataProviderDrawQuad>( false /* should_ask_for_child_region */, true /* root_accepts_events */); params.client_name = kBrowser; auto layer_tree_frame_sink = std::make_unique<cc::mojo_embedder::AsyncLayerTreeFrameSink>( std::move(context_provider), nullptr, &params); host_->SetLayerTreeFrameSink(std::move(layer_tree_frame_sink)); display_private_->SetDisplayVisible(true); display_private_->Resize(size_); display_private_->SetDisplayColorSpace(display_color_space_, display_color_space_); display_private_->SetVSyncPaused(vsync_paused_); }
172,105
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 mainloop(CLIENT *client) { struct nbd_request request; struct nbd_reply reply; gboolean go_on=TRUE; #ifdef DODBG int i = 0; #endif negotiate(client->net, client, NULL); DEBUG("Entering request loop!\n"); reply.magic = htonl(NBD_REPLY_MAGIC); reply.error = 0; while (go_on) { char buf[BUFSIZE]; size_t len; #ifdef DODBG i++; printf("%d: ", i); #endif readit(client->net, &request, sizeof(request)); request.from = ntohll(request.from); request.type = ntohl(request.type); if (request.type==NBD_CMD_DISC) { msg2(LOG_INFO, "Disconnect request received."); if (client->server->flags & F_COPYONWRITE) { if (client->difmap) g_free(client->difmap) ; close(client->difffile); unlink(client->difffilename); free(client->difffilename); } go_on=FALSE; continue; } len = ntohl(request.len); if (request.magic != htonl(NBD_REQUEST_MAGIC)) err("Not enough magic."); if (len > BUFSIZE + sizeof(struct nbd_reply)) err("Request too big!"); #ifdef DODBG printf("%s from %llu (%llu) len %d, ", request.type ? "WRITE" : "READ", (unsigned long long)request.from, (unsigned long long)request.from / 512, len); #endif memcpy(reply.handle, request.handle, sizeof(reply.handle)); if ((request.from + len) > (OFFT_MAX)) { DEBUG("[Number too large!]"); ERROR(client, reply, EINVAL); continue; } if (((ssize_t)((off_t)request.from + len) > client->exportsize)) { DEBUG("[RANGE!]"); ERROR(client, reply, EINVAL); continue; } if (request.type==NBD_CMD_WRITE) { DEBUG("wr: net->buf, "); readit(client->net, buf, len); DEBUG("buf->exp, "); if ((client->server->flags & F_READONLY) || (client->server->flags & F_AUTOREADONLY)) { DEBUG("[WRITE to READONLY!]"); ERROR(client, reply, EPERM); continue; } if (expwrite(request.from, buf, len, client)) { DEBUG("Write failed: %m" ); ERROR(client, reply, errno); continue; } SEND(client->net, reply); DEBUG("OK!\n"); continue; } /* READ */ DEBUG("exp->buf, "); if (expread(request.from, buf + sizeof(struct nbd_reply), len, client)) { DEBUG("Read failed: %m"); ERROR(client, reply, errno); continue; } DEBUG("buf->net, "); memcpy(buf, &reply, sizeof(struct nbd_reply)); writeit(client->net, buf, len + sizeof(struct nbd_reply)); DEBUG("OK!\n"); } return 0; } Commit Message: Fix buffer size checking Yes, this means we've re-introduced CVE-2005-3534. Sigh. CWE ID: CWE-119
int mainloop(CLIENT *client) { struct nbd_request request; struct nbd_reply reply; gboolean go_on=TRUE; #ifdef DODBG int i = 0; #endif negotiate(client->net, client, NULL); DEBUG("Entering request loop!\n"); reply.magic = htonl(NBD_REPLY_MAGIC); reply.error = 0; while (go_on) { char buf[BUFSIZE]; size_t len; #ifdef DODBG i++; printf("%d: ", i); #endif readit(client->net, &request, sizeof(request)); request.from = ntohll(request.from); request.type = ntohl(request.type); if (request.type==NBD_CMD_DISC) { msg2(LOG_INFO, "Disconnect request received."); if (client->server->flags & F_COPYONWRITE) { if (client->difmap) g_free(client->difmap) ; close(client->difffile); unlink(client->difffilename); free(client->difffilename); } go_on=FALSE; continue; } len = ntohl(request.len); if (request.magic != htonl(NBD_REQUEST_MAGIC)) err("Not enough magic."); if (len > BUFSIZE - sizeof(struct nbd_reply)) err("Request too big!"); #ifdef DODBG printf("%s from %llu (%llu) len %d, ", request.type ? "WRITE" : "READ", (unsigned long long)request.from, (unsigned long long)request.from / 512, len); #endif memcpy(reply.handle, request.handle, sizeof(reply.handle)); if ((request.from + len) > (OFFT_MAX)) { DEBUG("[Number too large!]"); ERROR(client, reply, EINVAL); continue; } if (((ssize_t)((off_t)request.from + len) > client->exportsize)) { DEBUG("[RANGE!]"); ERROR(client, reply, EINVAL); continue; } if (request.type==NBD_CMD_WRITE) { DEBUG("wr: net->buf, "); readit(client->net, buf, len); DEBUG("buf->exp, "); if ((client->server->flags & F_READONLY) || (client->server->flags & F_AUTOREADONLY)) { DEBUG("[WRITE to READONLY!]"); ERROR(client, reply, EPERM); continue; } if (expwrite(request.from, buf, len, client)) { DEBUG("Write failed: %m" ); ERROR(client, reply, errno); continue; } SEND(client->net, reply); DEBUG("OK!\n"); continue; } /* READ */ DEBUG("exp->buf, "); if (expread(request.from, buf + sizeof(struct nbd_reply), len, client)) { DEBUG("Read failed: %m"); ERROR(client, reply, errno); continue; } DEBUG("buf->net, "); memcpy(buf, &reply, sizeof(struct nbd_reply)); writeit(client->net, buf, len + sizeof(struct nbd_reply)); DEBUG("OK!\n"); } return 0; }
165,527
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ParseNameValue(const char * buffer, int bufsize, struct NameValueParserData * data) { struct xmlparser parser; data->l_head = NULL; data->portListing = NULL; data->portListingLength = 0; /* init xmlparser object */ parser.xmlstart = buffer; parser.xmlsize = bufsize; parser.data = data; parser.starteltfunc = NameValueParserStartElt; parser.endeltfunc = NameValueParserEndElt; parser.datafunc = NameValueParserGetData; parser.attfunc = 0; parsexml(&parser); } Commit Message: properly initialize data structure for SOAP parsing in ParseNameValue() topelt field was not properly initialized. should fix #268 CWE ID: CWE-119
ParseNameValue(const char * buffer, int bufsize, struct NameValueParserData * data) { struct xmlparser parser; memset(data, 0, sizeof(struct NameValueParserData)); /* init xmlparser object */ parser.xmlstart = buffer; parser.xmlsize = bufsize; parser.data = data; parser.starteltfunc = NameValueParserStartElt; parser.endeltfunc = NameValueParserEndElt; parser.datafunc = NameValueParserGetData; parser.attfunc = 0; parsexml(&parser); }
169,368
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 AwContents::UpdateScrollState(gfx::Vector2d max_scroll_offset, gfx::SizeF contents_size_dip, float page_scale_factor, float min_page_scale_factor, float max_page_scale_factor) { DCHECK_CURRENTLY_ON(BrowserThread::UI); JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> obj = java_ref_.get(env); if (obj.is_null()) return; Java_AwContents_updateScrollState(env, obj.obj(), max_scroll_offset.x(), max_scroll_offset.y(), contents_size_dip.width(), contents_size_dip.height(), page_scale_factor, min_page_scale_factor, max_page_scale_factor); } Commit Message: sync compositor: pass simple gfx types by const ref See bug for reasoning BUG=159273 Review URL: https://codereview.chromium.org/1417893006 Cr-Commit-Position: refs/heads/master@{#356653} CWE ID: CWE-399
void AwContents::UpdateScrollState(gfx::Vector2d max_scroll_offset, void AwContents::UpdateScrollState(const gfx::Vector2d& max_scroll_offset, const gfx::SizeF& contents_size_dip, float page_scale_factor, float min_page_scale_factor, float max_page_scale_factor) { DCHECK_CURRENTLY_ON(BrowserThread::UI); JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> obj = java_ref_.get(env); if (obj.is_null()) return; Java_AwContents_updateScrollState(env, obj.obj(), max_scroll_offset.x(), max_scroll_offset.y(), contents_size_dip.width(), contents_size_dip.height(), page_scale_factor, min_page_scale_factor, max_page_scale_factor); }
171,618
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: ossl_cipher_initialize(VALUE self, VALUE str) { EVP_CIPHER_CTX *ctx; const EVP_CIPHER *cipher; char *name; unsigned char dummy_key[EVP_MAX_KEY_LENGTH] = { 0 }; name = StringValueCStr(str); GetCipherInit(self, ctx); if (ctx) { ossl_raise(rb_eRuntimeError, "Cipher already inititalized!"); } AllocCipher(self, ctx); if (!(cipher = EVP_get_cipherbyname(name))) { ossl_raise(rb_eRuntimeError, "unsupported cipher algorithm (%"PRIsVALUE")", str); } /* * EVP_CipherInit_ex() allows to specify NULL to key and IV, however some * ciphers don't handle well (OpenSSL's bug). [Bug #2768] * * The EVP which has EVP_CIPH_RAND_KEY flag (such as DES3) allows * uninitialized key, but other EVPs (such as AES) does not allow it. * Calling EVP_CipherUpdate() without initializing key causes SEGV so we * set the data filled with "\0" as the key by default. */ if (EVP_CipherInit_ex(ctx, cipher, NULL, dummy_key, NULL, -1) != 1) ossl_raise(eCipherError, NULL); return self; } Commit Message: cipher: don't set dummy encryption key in Cipher#initialize Remove the encryption key initialization from Cipher#initialize. This is effectively a revert of r32723 ("Avoid possible SEGV from AES encryption/decryption", 2011-07-28). r32723, which added the key initialization, was a workaround for Ruby Bug #2768. For some certain ciphers, calling EVP_CipherUpdate() before setting an encryption key caused segfault. It was not a problem until OpenSSL implemented GCM mode - the encryption key could be overridden by repeated calls of EVP_CipherInit_ex(). But, it is not the case for AES-GCM ciphers. Setting a key, an IV, a key, in this order causes the IV to be reset to an all-zero IV. The problem of Bug #2768 persists on the current versions of OpenSSL. So, make Cipher#update raise an exception if a key is not yet set by the user. Since encrypting or decrypting without key does not make any sense, this should not break existing applications. Users can still call Cipher#key= and Cipher#iv= multiple times with their own responsibility. Reference: https://bugs.ruby-lang.org/issues/2768 Reference: https://bugs.ruby-lang.org/issues/8221 Reference: https://github.com/ruby/openssl/issues/49 CWE ID: CWE-310
ossl_cipher_initialize(VALUE self, VALUE str) { EVP_CIPHER_CTX *ctx; const EVP_CIPHER *cipher; char *name; name = StringValueCStr(str); GetCipherInit(self, ctx); if (ctx) { ossl_raise(rb_eRuntimeError, "Cipher already inititalized!"); } AllocCipher(self, ctx); if (!(cipher = EVP_get_cipherbyname(name))) { ossl_raise(rb_eRuntimeError, "unsupported cipher algorithm (%"PRIsVALUE")", str); } if (EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, -1) != 1) ossl_raise(eCipherError, NULL); return self; }
168,780
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 jas_stream_gobble(jas_stream_t *stream, int n) { int m; m = n; for (m = n; m > 0; --m) { if (jas_stream_getc(stream) == EOF) { return n - m; } } return n; } Commit Message: Made some changes to the I/O stream library for memory streams. There were a number of potential problems due to the possibility of integer overflow. Changed some integral types to the larger types size_t or ssize_t. For example, the function mem_resize now takes the buffer size parameter as a size_t. Added a new function jas_stream_memopen2, which takes a buffer size specified as a size_t instead of an int. This can be used in jas_image_cmpt_create to avoid potential overflow problems. Added a new function jas_deprecated to warn about reliance on deprecated library behavior. CWE ID: CWE-190
int jas_stream_gobble(jas_stream_t *stream, int n) { int m; if (n < 0) { jas_deprecated("negative count for jas_stream_gobble"); } m = n; for (m = n; m > 0; --m) { if (jas_stream_getc(stream) == EOF) { return n - m; } } return n; }
168,745
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 SimpleBlock::Parse() { return m_block.Parse(m_pCluster); } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long SimpleBlock::Parse()
174,410
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 security_decrypt(BYTE* data, int length, rdpRdp* rdp) { if (rdp->decrypt_use_count >= 4096) { security_key_update(rdp->decrypt_key, rdp->decrypt_update_key, rdp->rc4_key_len); crypto_rc4_free(rdp->rc4_decrypt_key); rdp->rc4_decrypt_key = crypto_rc4_init(rdp->decrypt_key, rdp->rc4_key_len); rdp->decrypt_use_count = 0; } crypto_rc4(rdp->rc4_decrypt_key, length, data, data); rdp->decrypt_use_count += 1; rdp->decrypt_checksum_use_count++; return TRUE; } Commit Message: security: add a NULL pointer check to fix a server crash. CWE ID: CWE-476
BOOL security_decrypt(BYTE* data, int length, rdpRdp* rdp) { if (rdp->rc4_decrypt_key == NULL) return FALSE; if (rdp->decrypt_use_count >= 4096) { security_key_update(rdp->decrypt_key, rdp->decrypt_update_key, rdp->rc4_key_len); crypto_rc4_free(rdp->rc4_decrypt_key); rdp->rc4_decrypt_key = crypto_rc4_init(rdp->decrypt_key, rdp->rc4_key_len); rdp->decrypt_use_count = 0; } crypto_rc4(rdp->rc4_decrypt_key, length, data, data); rdp->decrypt_use_count += 1; rdp->decrypt_checksum_use_count++; return TRUE; }
167,607
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 ContextImpl::CreateFrame( fidl::InterfaceHandle<chromium::web::FrameObserver> observer, fidl::InterfaceRequest<chromium::web::Frame> frame_request) { auto web_contents = content::WebContents::Create( content::WebContents::CreateParams(browser_context_, nullptr)); frame_bindings_.AddBinding( std::make_unique<FrameImpl>(std::move(web_contents), observer.Bind()), std::move(frame_request)); } Commit Message: [fuchsia] Implement browser tests for WebRunner Context service. Tests may interact with the WebRunner FIDL services and the underlying browser objects for end to end testing of service and browser functionality. * Add a browser test launcher main() for WebRunner. * Add some simple navigation tests. * Wire up GoBack()/GoForward() FIDL calls. * Add embedded test server resources and initialization logic. * Add missing deletion & notification calls to BrowserContext dtor. * Use FIDL events for navigation state changes. * Bug fixes: ** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(), so that they may use the MessageLoop during teardown. ** Fix Frame dtor to allow for null WindowTreeHosts (headless case) ** Fix std::move logic in Frame ctor which lead to no WebContents observer being registered. Bug: 871594 Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac Reviewed-on: https://chromium-review.googlesource.com/1164539 Commit-Queue: Kevin Marshall <[email protected]> Reviewed-by: Wez <[email protected]> Reviewed-by: Fabrice de Gans-Riberi <[email protected]> Reviewed-by: Scott Violet <[email protected]> Cr-Commit-Position: refs/heads/master@{#584155} CWE ID: CWE-264
void ContextImpl::CreateFrame( fidl::InterfaceRequest<chromium::web::Frame> frame_request) { auto web_contents = content::WebContents::Create( content::WebContents::CreateParams(browser_context_, nullptr)); frames_.insert(std::make_unique<FrameImpl>(std::move(web_contents), this, std::move(frame_request))); } void ContextImpl::DestroyFrame(FrameImpl* frame) { DCHECK(frames_.find(frame) != frames_.end()); frames_.erase(frames_.find(frame)); } FrameImpl* ContextImpl::GetFrameImplForTest( chromium::web::FramePtr* frame_ptr) { DCHECK(frame_ptr); // Find the FrameImpl whose channel is connected to |frame_ptr| by inspecting // the related_koids of active FrameImpls. zx_info_handle_basic_t handle_info; zx_status_t status = frame_ptr->channel().get_info( ZX_INFO_HANDLE_BASIC, &handle_info, sizeof(zx_info_handle_basic_t), nullptr, nullptr); ZX_CHECK(status == ZX_OK, status) << "zx_object_get_info"; zx_handle_t client_handle_koid = handle_info.koid; for (const std::unique_ptr<FrameImpl>& frame : frames_) { status = frame->GetBindingChannelForTest()->get_info( ZX_INFO_HANDLE_BASIC, &handle_info, sizeof(zx_info_handle_basic_t), nullptr, nullptr); ZX_CHECK(status == ZX_OK, status) << "zx_object_get_info"; if (client_handle_koid == handle_info.related_koid) return frame.get(); } return nullptr; }
172,151
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: struct crypto_alg *crypto_larval_lookup(const char *name, u32 type, u32 mask) { struct crypto_alg *alg; if (!name) return ERR_PTR(-ENOENT); mask &= ~(CRYPTO_ALG_LARVAL | CRYPTO_ALG_DEAD); type &= mask; alg = crypto_alg_lookup(name, type, mask); if (!alg) { request_module("%s", name); if (!((type ^ CRYPTO_ALG_NEED_FALLBACK) & mask & CRYPTO_ALG_NEED_FALLBACK)) request_module("%s-all", name); alg = crypto_alg_lookup(name, type, mask); } if (alg) return crypto_is_larval(alg) ? crypto_larval_wait(alg) : alg; return crypto_larval_add(name, type, mask); } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-264
struct crypto_alg *crypto_larval_lookup(const char *name, u32 type, u32 mask) { struct crypto_alg *alg; if (!name) return ERR_PTR(-ENOENT); mask &= ~(CRYPTO_ALG_LARVAL | CRYPTO_ALG_DEAD); type &= mask; alg = crypto_alg_lookup(name, type, mask); if (!alg) { request_module("crypto-%s", name); if (!((type ^ CRYPTO_ALG_NEED_FALLBACK) & mask & CRYPTO_ALG_NEED_FALLBACK)) request_module("crypto-%s-all", name); alg = crypto_alg_lookup(name, type, mask); } if (alg) return crypto_is_larval(alg) ? crypto_larval_wait(alg) : alg; return crypto_larval_add(name, type, mask); }
166,839
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xfs_acl_from_disk(struct xfs_acl *aclp) { struct posix_acl_entry *acl_e; struct posix_acl *acl; struct xfs_acl_entry *ace; int count, i; count = be32_to_cpu(aclp->acl_cnt); if (count > XFS_ACL_MAX_ENTRIES) return ERR_PTR(-EFSCORRUPTED); acl = posix_acl_alloc(count, GFP_KERNEL); if (!acl) return ERR_PTR(-ENOMEM); for (i = 0; i < count; i++) { acl_e = &acl->a_entries[i]; ace = &aclp->acl_entry[i]; /* * The tag is 32 bits on disk and 16 bits in core. * * Because every access to it goes through the core * format first this is not a problem. */ acl_e->e_tag = be32_to_cpu(ace->ae_tag); acl_e->e_perm = be16_to_cpu(ace->ae_perm); switch (acl_e->e_tag) { case ACL_USER: case ACL_GROUP: acl_e->e_id = be32_to_cpu(ace->ae_id); break; case ACL_USER_OBJ: case ACL_GROUP_OBJ: case ACL_MASK: case ACL_OTHER: acl_e->e_id = ACL_UNDEFINED_ID; break; default: goto fail; } } return acl; fail: posix_acl_release(acl); return ERR_PTR(-EINVAL); } Commit Message: xfs: fix acl count validation in xfs_acl_from_disk() Commit fa8b18ed didn't prevent the integer overflow and possible memory corruption. "count" can go negative and bypass the check. Signed-off-by: Xi Wang <[email protected]> Reviewed-by: Christoph Hellwig <[email protected]> Signed-off-by: Ben Myers <[email protected]> CWE ID: CWE-189
xfs_acl_from_disk(struct xfs_acl *aclp) { struct posix_acl_entry *acl_e; struct posix_acl *acl; struct xfs_acl_entry *ace; unsigned int count, i; count = be32_to_cpu(aclp->acl_cnt); if (count > XFS_ACL_MAX_ENTRIES) return ERR_PTR(-EFSCORRUPTED); acl = posix_acl_alloc(count, GFP_KERNEL); if (!acl) return ERR_PTR(-ENOMEM); for (i = 0; i < count; i++) { acl_e = &acl->a_entries[i]; ace = &aclp->acl_entry[i]; /* * The tag is 32 bits on disk and 16 bits in core. * * Because every access to it goes through the core * format first this is not a problem. */ acl_e->e_tag = be32_to_cpu(ace->ae_tag); acl_e->e_perm = be16_to_cpu(ace->ae_perm); switch (acl_e->e_tag) { case ACL_USER: case ACL_GROUP: acl_e->e_id = be32_to_cpu(ace->ae_id); break; case ACL_USER_OBJ: case ACL_GROUP_OBJ: case ACL_MASK: case ACL_OTHER: acl_e->e_id = ACL_UNDEFINED_ID; break; default: goto fail; } } return acl; fail: posix_acl_release(acl); return ERR_PTR(-EINVAL); }
169,888
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: ethertype_print(netdissect_options *ndo, u_short ether_type, const u_char *p, u_int length, u_int caplen, const struct lladdr_info *src, const struct lladdr_info *dst) { switch (ether_type) { case ETHERTYPE_IP: ip_print(ndo, p, length); return (1); case ETHERTYPE_IPV6: ip6_print(ndo, p, length); return (1); case ETHERTYPE_ARP: case ETHERTYPE_REVARP: arp_print(ndo, p, length, caplen); return (1); case ETHERTYPE_DN: decnet_print(ndo, p, length, caplen); return (1); case ETHERTYPE_ATALK: if (ndo->ndo_vflag) ND_PRINT((ndo, "et1 ")); atalk_print(ndo, p, length); return (1); case ETHERTYPE_AARP: aarp_print(ndo, p, length); return (1); case ETHERTYPE_IPX: ND_PRINT((ndo, "(NOV-ETHII) ")); ipx_print(ndo, p, length); return (1); case ETHERTYPE_ISO: if (length == 0 || caplen == 0) { ND_PRINT((ndo, " [|osi]")); return (1); } isoclns_print(ndo, p + 1, length - 1, caplen - 1); return(1); case ETHERTYPE_PPPOED: case ETHERTYPE_PPPOES: case ETHERTYPE_PPPOED2: case ETHERTYPE_PPPOES2: pppoe_print(ndo, p, length); return (1); case ETHERTYPE_EAPOL: eap_print(ndo, p, length); return (1); case ETHERTYPE_RRCP: rrcp_print(ndo, p, length, src, dst); return (1); case ETHERTYPE_PPP: if (length) { ND_PRINT((ndo, ": ")); ppp_print(ndo, p, length); } return (1); case ETHERTYPE_MPCP: mpcp_print(ndo, p, length); return (1); case ETHERTYPE_SLOW: slow_print(ndo, p, length); return (1); case ETHERTYPE_CFM: case ETHERTYPE_CFM_OLD: cfm_print(ndo, p, length); return (1); case ETHERTYPE_LLDP: lldp_print(ndo, p, length); return (1); case ETHERTYPE_NSH: nsh_print(ndo, p, length); return (1); case ETHERTYPE_LOOPBACK: loopback_print(ndo, p, length); return (1); case ETHERTYPE_MPLS: case ETHERTYPE_MPLS_MULTI: mpls_print(ndo, p, length); return (1); case ETHERTYPE_TIPC: tipc_print(ndo, p, length, caplen); return (1); case ETHERTYPE_MS_NLB_HB: msnlb_print(ndo, p); return (1); case ETHERTYPE_GEONET_OLD: case ETHERTYPE_GEONET: geonet_print(ndo, p, length, src); return (1); case ETHERTYPE_CALM_FAST: calm_fast_print(ndo, p, length, src); return (1); case ETHERTYPE_AOE: aoe_print(ndo, p, length); return (1); case ETHERTYPE_MEDSA: medsa_print(ndo, p, length, caplen, src, dst); return (1); case ETHERTYPE_LAT: case ETHERTYPE_SCA: case ETHERTYPE_MOPRC: case ETHERTYPE_MOPDL: case ETHERTYPE_IEEE1905_1: /* default_print for now */ default: return (0); } } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
ethertype_print(netdissect_options *ndo, u_short ether_type, const u_char *p, u_int length, u_int caplen, const struct lladdr_info *src, const struct lladdr_info *dst) { switch (ether_type) { case ETHERTYPE_IP: ip_print(ndo, p, length); return (1); case ETHERTYPE_IPV6: ip6_print(ndo, p, length); return (1); case ETHERTYPE_ARP: case ETHERTYPE_REVARP: arp_print(ndo, p, length, caplen); return (1); case ETHERTYPE_DN: decnet_print(ndo, p, length, caplen); return (1); case ETHERTYPE_ATALK: if (ndo->ndo_vflag) ND_PRINT((ndo, "et1 ")); atalk_print(ndo, p, length); return (1); case ETHERTYPE_AARP: aarp_print(ndo, p, length); return (1); case ETHERTYPE_IPX: ND_PRINT((ndo, "(NOV-ETHII) ")); ipx_print(ndo, p, length); return (1); case ETHERTYPE_ISO: if (length == 0 || caplen == 0) { ND_PRINT((ndo, " [|osi]")); return (1); } isoclns_print(ndo, p + 1, length - 1); return(1); case ETHERTYPE_PPPOED: case ETHERTYPE_PPPOES: case ETHERTYPE_PPPOED2: case ETHERTYPE_PPPOES2: pppoe_print(ndo, p, length); return (1); case ETHERTYPE_EAPOL: eap_print(ndo, p, length); return (1); case ETHERTYPE_RRCP: rrcp_print(ndo, p, length, src, dst); return (1); case ETHERTYPE_PPP: if (length) { ND_PRINT((ndo, ": ")); ppp_print(ndo, p, length); } return (1); case ETHERTYPE_MPCP: mpcp_print(ndo, p, length); return (1); case ETHERTYPE_SLOW: slow_print(ndo, p, length); return (1); case ETHERTYPE_CFM: case ETHERTYPE_CFM_OLD: cfm_print(ndo, p, length); return (1); case ETHERTYPE_LLDP: lldp_print(ndo, p, length); return (1); case ETHERTYPE_NSH: nsh_print(ndo, p, length); return (1); case ETHERTYPE_LOOPBACK: loopback_print(ndo, p, length); return (1); case ETHERTYPE_MPLS: case ETHERTYPE_MPLS_MULTI: mpls_print(ndo, p, length); return (1); case ETHERTYPE_TIPC: tipc_print(ndo, p, length, caplen); return (1); case ETHERTYPE_MS_NLB_HB: msnlb_print(ndo, p); return (1); case ETHERTYPE_GEONET_OLD: case ETHERTYPE_GEONET: geonet_print(ndo, p, length, src); return (1); case ETHERTYPE_CALM_FAST: calm_fast_print(ndo, p, length, src); return (1); case ETHERTYPE_AOE: aoe_print(ndo, p, length); return (1); case ETHERTYPE_MEDSA: medsa_print(ndo, p, length, caplen, src, dst); return (1); case ETHERTYPE_LAT: case ETHERTYPE_SCA: case ETHERTYPE_MOPRC: case ETHERTYPE_MOPDL: case ETHERTYPE_IEEE1905_1: /* default_print for now */ default: return (0); } }
167,944
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: Document* LocalDOMWindow::InstallNewDocument(const String& mime_type, const DocumentInit& init, bool force_xhtml) { DCHECK_EQ(init.GetFrame(), GetFrame()); ClearDocument(); document_ = CreateDocument(mime_type, init, force_xhtml); event_queue_ = DOMWindowEventQueue::Create(document_.Get()); document_->Initialize(); if (!GetFrame()) return document_; GetFrame()->GetScriptController().UpdateDocument(); document_->UpdateViewportDescription(); if (GetFrame()->GetPage() && GetFrame()->View()) { GetFrame()->GetPage()->GetChromeClient().InstallSupplements(*GetFrame()); if (ScrollingCoordinator* scrolling_coordinator = GetFrame()->GetPage()->GetScrollingCoordinator()) { scrolling_coordinator->ScrollableAreaScrollbarLayerDidChange( GetFrame()->View(), kHorizontalScrollbar); scrolling_coordinator->ScrollableAreaScrollbarLayerDidChange( GetFrame()->View(), kVerticalScrollbar); scrolling_coordinator->ScrollableAreaScrollLayerDidChange( GetFrame()->View()); } } GetFrame()->Selection().UpdateSecureKeyboardEntryIfActive(); if (GetFrame()->IsCrossOriginSubframe()) document_->RecordDeferredLoadReason(WouldLoadReason::kCreated); return document_; } Commit Message: MacViews: Enable secure text input for password Textfields. In Cocoa the NSTextInputContext automatically enables secure text input when activated and it's in the secure text entry mode. RenderWidgetHostViewMac did the similar thing for ages following the WebKit example. views::Textfield needs to do the same thing in a fashion that's sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions are possible when the Textfield gets focus, activates the secure text input mode and the RWHVM loses focus immediately afterwards and disables the secure text input instead of leaving it in the enabled state. BUG=818133,677220 Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b Reviewed-on: https://chromium-review.googlesource.com/943064 Commit-Queue: Michail Pishchagin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#542517} CWE ID:
Document* LocalDOMWindow::InstallNewDocument(const String& mime_type, const DocumentInit& init, bool force_xhtml) { DCHECK_EQ(init.GetFrame(), GetFrame()); ClearDocument(); document_ = CreateDocument(mime_type, init, force_xhtml); event_queue_ = DOMWindowEventQueue::Create(document_.Get()); document_->Initialize(); if (!GetFrame()) return document_; GetFrame()->GetScriptController().UpdateDocument(); document_->UpdateViewportDescription(); if (GetFrame()->GetPage() && GetFrame()->View()) { GetFrame()->GetPage()->GetChromeClient().InstallSupplements(*GetFrame()); if (ScrollingCoordinator* scrolling_coordinator = GetFrame()->GetPage()->GetScrollingCoordinator()) { scrolling_coordinator->ScrollableAreaScrollbarLayerDidChange( GetFrame()->View(), kHorizontalScrollbar); scrolling_coordinator->ScrollableAreaScrollbarLayerDidChange( GetFrame()->View(), kVerticalScrollbar); scrolling_coordinator->ScrollableAreaScrollLayerDidChange( GetFrame()->View()); } } if (GetFrame()->IsCrossOriginSubframe()) document_->RecordDeferredLoadReason(WouldLoadReason::kCreated); return document_; }
171,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 Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (SetImageBackgroundColor(image,exception) == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace,exception); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace,exception); image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait : UndefinedPixelTrait; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536, exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait : UndefinedPixelTrait; } else image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait : UndefinedPixelTrait; /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->alpha_trait=UndefinedPixelTrait; } } has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image, exception); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1)) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && (length != 0)) { SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception); if (status != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1)) { Image *merged; SetImageAlphaChannel(image,TransparentAlphaChannel,exception); image->background_color.alpha=TransparentAlpha; image->background_color.alpha_trait=BlendPixelTrait; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: Added check for bit depth 1. CWE ID: CWE-125
static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (SetImageBackgroundColor(image,exception) == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace,exception); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace,exception); image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait : UndefinedPixelTrait; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536, exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait : UndefinedPixelTrait; } else image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait : UndefinedPixelTrait; /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->alpha_trait=UndefinedPixelTrait; } } if ((image->depth == 1) && (image->storage_class != PseudoClass)) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image, exception); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1)) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && (length != 0)) { SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception); if (status != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1)) { Image *merged; SetImageAlphaChannel(image,TransparentAlphaChannel,exception); image->background_color.alpha=TransparentAlpha; image->background_color.alpha_trait=BlendPixelTrait; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); }
170,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: static int encode_open_downgrade(struct xdr_stream *xdr, const struct nfs_closeargs *arg) { __be32 *p; RESERVE_SPACE(4+NFS4_STATEID_SIZE+4); WRITE32(OP_OPEN_DOWNGRADE); WRITEMEM(arg->stateid->data, NFS4_STATEID_SIZE); WRITE32(arg->seqid->sequence->counter); encode_share_access(xdr, arg->open_flags); return 0; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
static int encode_open_downgrade(struct xdr_stream *xdr, const struct nfs_closeargs *arg) { __be32 *p; RESERVE_SPACE(4+NFS4_STATEID_SIZE+4); WRITE32(OP_OPEN_DOWNGRADE); WRITEMEM(arg->stateid->data, NFS4_STATEID_SIZE); WRITE32(arg->seqid->sequence->counter); encode_share_access(xdr, arg->fmode); return 0; }
165,713
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: OMX_ERRORTYPE SoftAMRWBEncoder::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPortFormat: { OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } formatParams->eEncoding = (formatParams->nPortIndex == 0) ? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAMR; return OMX_ErrorNone; } case OMX_IndexParamAudioAmr: { OMX_AUDIO_PARAM_AMRTYPE *amrParams = (OMX_AUDIO_PARAM_AMRTYPE *)params; if (amrParams->nPortIndex != 1) { return OMX_ErrorUndefined; } amrParams->nChannels = 1; amrParams->nBitRate = mBitRate; amrParams->eAMRBandMode = (OMX_AUDIO_AMRBANDMODETYPE)(mMode + OMX_AUDIO_AMRBandModeWB0); amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff; amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF; return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelCF; pcmParams->nChannels = 1; pcmParams->nSamplingRate = kSampleRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftAMRWBEncoder::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPortFormat: { OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (!isValidOMXParam(formatParams)) { return OMX_ErrorBadParameter; } if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } formatParams->eEncoding = (formatParams->nPortIndex == 0) ? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAMR; return OMX_ErrorNone; } case OMX_IndexParamAudioAmr: { OMX_AUDIO_PARAM_AMRTYPE *amrParams = (OMX_AUDIO_PARAM_AMRTYPE *)params; if (!isValidOMXParam(amrParams)) { return OMX_ErrorBadParameter; } if (amrParams->nPortIndex != 1) { return OMX_ErrorUndefined; } amrParams->nChannels = 1; amrParams->nBitRate = mBitRate; amrParams->eAMRBandMode = (OMX_AUDIO_AMRBANDMODETYPE)(mMode + OMX_AUDIO_AMRBandModeWB0); amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff; amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF; return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelCF; pcmParams->nChannels = 1; pcmParams->nSamplingRate = kSampleRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } }
174,196
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 put_chars(u32 vtermno, const char *buf, int count) { struct port *port; struct scatterlist sg[1]; if (unlikely(early_put_chars)) return early_put_chars(vtermno, buf, count); port = find_port_by_vtermno(vtermno); if (!port) return -EPIPE; sg_init_one(sg, buf, count); return __send_to_port(port, sg, 1, count, (void *)buf, false); } Commit Message: virtio-console: avoid DMA from stack put_chars() stuffs the buffer it gets into an sg, but that buffer may be on the stack. This breaks with CONFIG_VMAP_STACK=y (for me, it manifested as printks getting turned into NUL bytes). Signed-off-by: Omar Sandoval <[email protected]> Signed-off-by: Michael S. Tsirkin <[email protected]> Reviewed-by: Amit Shah <[email protected]> CWE ID: CWE-119
static int put_chars(u32 vtermno, const char *buf, int count) { struct port *port; struct scatterlist sg[1]; void *data; int ret; if (unlikely(early_put_chars)) return early_put_chars(vtermno, buf, count); port = find_port_by_vtermno(vtermno); if (!port) return -EPIPE; data = kmemdup(buf, count, GFP_ATOMIC); if (!data) return -ENOMEM; sg_init_one(sg, data, count); ret = __send_to_port(port, sg, 1, count, data, false); kfree(data); return ret; }
168,219
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 LockScreenMediaControlsView::OnMouseExited(const ui::MouseEvent& event) { if (is_in_drag_ || contents_view_->layer()->GetAnimator()->is_animating()) return; close_button_->SetVisible(false); } 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
void LockScreenMediaControlsView::OnMouseExited(const ui::MouseEvent& event) { if (is_in_drag_ || contents_view_->layer()->GetAnimator()->is_animating()) return; header_row_->SetCloseButtonVisibility(false); }
172,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: static void copyMultiCh16(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels) { for (unsigned i = 0; i < nSamples; ++i) { for (unsigned c = 0; c < nChannels; ++c) { *dst++ = src[c][i]; } } } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 CWE ID: CWE-119
static void copyMultiCh16(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels) static void copyMultiCh16(short *dst, const int * src[FLACParser::kMaxChannels], unsigned nSamples, unsigned nChannels) { for (unsigned i = 0; i < nSamples; ++i) { for (unsigned c = 0; c < nChannels; ++c) { *dst++ = src[c][i]; } } }
174,018
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 ApiTestEnvironment::RegisterModules() { v8_schema_registry_.reset(new V8SchemaRegistry); const std::vector<std::pair<std::string, int> > resources = Dispatcher::GetJsResources(); for (std::vector<std::pair<std::string, int> >::const_iterator resource = resources.begin(); resource != resources.end(); ++resource) { if (resource->first != "test_environment_specific_bindings") env()->RegisterModule(resource->first, resource->second); } Dispatcher::RegisterNativeHandlers(env()->module_system(), env()->context(), NULL, NULL, v8_schema_registry_.get()); env()->module_system()->RegisterNativeHandler( "process", scoped_ptr<NativeHandler>(new ProcessInfoNativeHandler( env()->context(), env()->context()->GetExtensionID(), env()->context()->GetContextTypeDescription(), false, false, 2, false))); env()->RegisterTestFile("test_environment_specific_bindings", "unit_test_environment_specific_bindings.js"); env()->OverrideNativeHandler("activityLogger", "exports.LogAPICall = function() {};"); env()->OverrideNativeHandler( "apiDefinitions", "exports.GetExtensionAPIDefinitionsForTest = function() { return [] };"); env()->OverrideNativeHandler( "event_natives", "exports.AttachEvent = function() {};" "exports.DetachEvent = function() {};" "exports.AttachFilteredEvent = function() {};" "exports.AttachFilteredEvent = function() {};" "exports.MatchAgainstEventFilter = function() { return [] };"); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), mojo::js::Core::kModuleName, mojo::js::Core::GetModule(env()->isolate())); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), mojo::js::Support::kModuleName, mojo::js::Support::GetModule(env()->isolate())); gin::Handle<TestServiceProvider> service_provider = TestServiceProvider::Create(env()->isolate()); service_provider_ = service_provider.get(); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), "content/public/renderer/service_provider", service_provider.ToV8()); } Commit Message: [Extensions] Don't allow built-in extensions code to be overridden BUG=546677 Review URL: https://codereview.chromium.org/1417513003 Cr-Commit-Position: refs/heads/master@{#356654} CWE ID: CWE-264
void ApiTestEnvironment::RegisterModules() { v8_schema_registry_.reset(new V8SchemaRegistry); const std::vector<std::pair<std::string, int> > resources = Dispatcher::GetJsResources(); for (std::vector<std::pair<std::string, int> >::const_iterator resource = resources.begin(); resource != resources.end(); ++resource) { if (resource->first != "test_environment_specific_bindings") env()->RegisterModule(resource->first, resource->second); } Dispatcher::RegisterNativeHandlers(env()->module_system(), env()->context(), NULL, NULL, v8_schema_registry_.get()); env()->module_system()->RegisterNativeHandler( "process", scoped_ptr<NativeHandler>(new ProcessInfoNativeHandler( env()->context(), env()->context()->GetExtensionID(), env()->context()->GetContextTypeDescription(), false, false, 2, false))); env()->RegisterTestFile("test_environment_specific_bindings", "unit_test_environment_specific_bindings.js"); env()->OverrideNativeHandler("activityLogger", "exports.$set('LogAPICall', function() {});"); env()->OverrideNativeHandler( "apiDefinitions", "exports.$set('GetExtensionAPIDefinitionsForTest'," "function() { return [] });"); env()->OverrideNativeHandler( "event_natives", "exports.$set('AttachEvent', function() {});" "exports.$set('DetachEvent', function() {});" "exports.$set('AttachFilteredEvent', function() {});" "exports.$set('AttachFilteredEvent', function() {});" "exports.$set('MatchAgainstEventFilter', function() { return [] });"); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), mojo::js::Core::kModuleName, mojo::js::Core::GetModule(env()->isolate())); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), mojo::js::Support::kModuleName, mojo::js::Support::GetModule(env()->isolate())); gin::Handle<TestServiceProvider> service_provider = TestServiceProvider::Create(env()->isolate()); service_provider_ = service_provider.get(); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), "content/public/renderer/service_provider", service_provider.ToV8()); }
172,286
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 cg_open(const char *path, struct fuse_file_info *fi) { const char *cgroup; char *fpath = NULL, *path1, *path2, * cgdir = NULL, *controller; struct cgfs_files *k = NULL; struct file_info *file_info; struct fuse_context *fc = fuse_get_context(); int ret; if (!fc) return -EIO; controller = pick_controller_from_path(fc, path); if (!controller) return -EIO; cgroup = find_cgroup_in_path(path); if (!cgroup) return -EINVAL; get_cgdir_and_path(cgroup, &cgdir, &fpath); if (!fpath) { path1 = "/"; path2 = cgdir; } else { path1 = cgdir; path2 = fpath; } k = cgfs_get_key(controller, path1, path2); if (!k) { ret = -EINVAL; goto out; } free_key(k); if (!fc_may_access(fc, controller, path1, path2, fi->flags)) { ret = -EACCES; goto out; } /* we'll free this at cg_release */ file_info = malloc(sizeof(*file_info)); if (!file_info) { ret = -ENOMEM; goto out; } file_info->controller = must_copy_string(controller); file_info->cgroup = must_copy_string(path1); file_info->file = must_copy_string(path2); file_info->type = LXC_TYPE_CGFILE; file_info->buf = NULL; file_info->buflen = 0; fi->fh = (unsigned long)file_info; ret = 0; out: free(cgdir); return ret; } Commit Message: Fix checking of parent directories Taken from the justification in the launchpad bug: To a task in freezer cgroup /a/b/c/d, it should appear that there are no cgroups other than its descendents. Since this is a filesystem, we must have the parent directories, but each parent cgroup should only contain the child which the task can see. So, when this task looks at /a/b, it should see only directory 'c' and no files. Attempt to create /a/b/x should result in -EPERM, whether /a/b/x already exists or not. Attempts to query /a/b/x should result in -ENOENT whether /a/b/x exists or not. Opening /a/b/tasks should result in -ENOENT. The caller_may_see_dir checks specifically whether a task may see a cgroup directory - i.e. /a/b/x if opening /a/b/x/tasks, and /a/b/c/d if doing opendir('/a/b/c/d'). caller_is_in_ancestor() will return true if the caller in /a/b/c/d looks at /a/b/c/d/e. If the caller is in a child cgroup of the queried one - i.e. if the task in /a/b/c/d queries /a/b, then *nextcg will container the next (the only) directory which he can see in the path - 'c'. Beyond this, regular DAC permissions should apply, with the root-in-user-namespace privilege over its mapped uids being respected. The fc_may_access check does this check for both directories and files. This is CVE-2015-1342 (LP: #1508481) Signed-off-by: Serge Hallyn <[email protected]> CWE ID: CWE-264
static int cg_open(const char *path, struct fuse_file_info *fi) { const char *cgroup; char *fpath = NULL, *path1, *path2, * cgdir = NULL, *controller; struct cgfs_files *k = NULL; struct file_info *file_info; struct fuse_context *fc = fuse_get_context(); int ret; if (!fc) return -EIO; controller = pick_controller_from_path(fc, path); if (!controller) return -EIO; cgroup = find_cgroup_in_path(path); if (!cgroup) return -EINVAL; get_cgdir_and_path(cgroup, &cgdir, &fpath); if (!fpath) { path1 = "/"; path2 = cgdir; } else { path1 = cgdir; path2 = fpath; } k = cgfs_get_key(controller, path1, path2); if (!k) { ret = -EINVAL; goto out; } free_key(k); if (!caller_may_see_dir(fc->pid, controller, path1)) { ret = -ENOENT; goto out; } if (!fc_may_access(fc, controller, path1, path2, fi->flags)) { ret = -EACCES; goto out; } /* we'll free this at cg_release */ file_info = malloc(sizeof(*file_info)); if (!file_info) { ret = -ENOMEM; goto out; } file_info->controller = must_copy_string(controller); file_info->cgroup = must_copy_string(path1); file_info->file = must_copy_string(path2); file_info->type = LXC_TYPE_CGFILE; file_info->buf = NULL; file_info->buflen = 0; fi->fh = (unsigned long)file_info; ret = 0; out: free(cgdir); return ret; }
166,706
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 yr_re_match( RE* re, const char* target) { return yr_re_exec( re->code, (uint8_t*) target, strlen(target), re->flags | RE_FLAGS_SCAN, NULL, NULL); } Commit Message: Fix issue #646 (#648) * Fix issue #646 and some edge cases with wide regexps using \b and \B * Rename function IS_WORD_CHAR to _yr_re_is_word_char CWE ID: CWE-125
int yr_re_match( RE* re, const char* target) { return yr_re_exec( re->code, (uint8_t*) target, strlen(target), 0, re->flags | RE_FLAGS_SCAN, NULL, NULL); }
168,203
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadMONOImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType status; register IndexPacket *indexes; register PixelPacket *q; register ssize_t x; size_t bit, byte; ssize_t y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); /* Initialize image colormap. */ image->depth=1; if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Convert bi-level image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { if (bit == 0) byte=(size_t) ReadBlobByte(image); if (image_info->endian == LSBEndian) SetPixelIndex(indexes+x,((byte & 0x01) != 0) ? 0x00 : 0x01) else SetPixelIndex(indexes+x,((byte & 0x01) != 0) ? 0x01 : 0x00) bit++; if (bit == 8) bit=0; byte>>=1; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadMONOImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType status; register IndexPacket *indexes; register PixelPacket *q; register ssize_t x; size_t bit, byte; ssize_t y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); /* Initialize image colormap. */ image->depth=1; if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Convert bi-level image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { if (bit == 0) byte=(size_t) ReadBlobByte(image); if (image_info->endian == LSBEndian) SetPixelIndex(indexes+x,((byte & 0x01) != 0) ? 0x00 : 0x01) else SetPixelIndex(indexes+x,((byte & 0x01) != 0) ? 0x01 : 0x00) bit++; if (bit == 8) bit=0; byte>>=1; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,582
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 UnprivilegedProcessDelegate::CreateConnectedIpcChannel( const std::string& channel_name, IPC::Listener* delegate, ScopedHandle* client_out, scoped_ptr<IPC::ChannelProxy>* server_out) { scoped_ptr<IPC::ChannelProxy> server; if (!CreateIpcChannel(channel_name, kDaemonIpcSecurityDescriptor, io_task_runner_, delegate, &server)) { return false; } std::string pipe_name(kChromePipeNamePrefix); pipe_name.append(channel_name); SECURITY_ATTRIBUTES security_attributes; security_attributes.nLength = sizeof(security_attributes); security_attributes.lpSecurityDescriptor = NULL; security_attributes.bInheritHandle = TRUE; ScopedHandle client; client.Set(CreateFile(UTF8ToUTF16(pipe_name).c_str(), GENERIC_READ | GENERIC_WRITE, 0, &security_attributes, OPEN_EXISTING, SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION | FILE_FLAG_OVERLAPPED, NULL)); if (!client.IsValid()) return false; *client_out = client.Pass(); *server_out = server.Pass(); return true; } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool UnprivilegedProcessDelegate::CreateConnectedIpcChannel(
171,544
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 CanOnlyDiscardOnceTest(DiscardReason reason) { LifecycleUnit* background_lifecycle_unit = nullptr; LifecycleUnit* foreground_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit, &foreground_lifecycle_unit); content::WebContents* initial_web_contents = tab_strip_model_->GetWebContentsAt(0); ExpectCanDiscardTrueAllReasons(background_lifecycle_unit); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, true)); background_lifecycle_unit->Discard(reason); testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, background_lifecycle_unit); EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0)); EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, false)); tab_strip_model_->GetWebContentsAt(0)->GetController().Reload( content::ReloadType::NORMAL, false); testing::Mock::VerifyAndClear(&tab_observer_); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); ExpectCanDiscardFalseTrivial(background_lifecycle_unit, DiscardReason::kExternal); ExpectCanDiscardFalseTrivial(background_lifecycle_unit, DiscardReason::kProactive); #if defined(OS_CHROMEOS) ExpectCanDiscardTrue(background_lifecycle_unit, DiscardReason::kUrgent); #else ExpectCanDiscardFalseTrivial(background_lifecycle_unit, DiscardReason::kUrgent); #endif } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
void CanOnlyDiscardOnceTest(DiscardReason reason) { LifecycleUnit* background_lifecycle_unit = nullptr; LifecycleUnit* foreground_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit, &foreground_lifecycle_unit); content::WebContents* initial_web_contents = tab_strip_model_->GetWebContentsAt(0); ExpectCanDiscardTrueAllReasons(background_lifecycle_unit); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, true)); background_lifecycle_unit->Discard(reason); ::testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, background_lifecycle_unit); EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0)); EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, false)); tab_strip_model_->GetWebContentsAt(0)->GetController().Reload( content::ReloadType::NORMAL, false); ::testing::Mock::VerifyAndClear(&tab_observer_); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); ExpectCanDiscardFalseTrivial(background_lifecycle_unit, DiscardReason::kExternal); ExpectCanDiscardFalseTrivial(background_lifecycle_unit, DiscardReason::kProactive); #if defined(OS_CHROMEOS) ExpectCanDiscardTrue(background_lifecycle_unit, DiscardReason::kUrgent); #else ExpectCanDiscardFalseTrivial(background_lifecycle_unit, DiscardReason::kUrgent); #endif }
172,220
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: ieee802_11_print(netdissect_options *ndo, const u_char *p, u_int length, u_int orig_caplen, int pad, u_int fcslen) { uint16_t fc; u_int caplen, hdrlen, meshdrlen; struct lladdr_info src, dst; int llc_hdrlen; caplen = orig_caplen; /* Remove FCS, if present */ if (length < fcslen) { ND_PRINT((ndo, "%s", tstr)); return caplen; } length -= fcslen; if (caplen > length) { /* Amount of FCS in actual packet data, if any */ fcslen = caplen - length; caplen -= fcslen; ndo->ndo_snapend -= fcslen; } if (caplen < IEEE802_11_FC_LEN) { ND_PRINT((ndo, "%s", tstr)); return orig_caplen; } fc = EXTRACT_LE_16BITS(p); hdrlen = extract_header_length(ndo, fc); if (hdrlen == 0) { /* Unknown frame type or control frame subtype; quit. */ return (0); } if (pad) hdrlen = roundup2(hdrlen, 4); if (ndo->ndo_Hflag && FC_TYPE(fc) == T_DATA && DATA_FRAME_IS_QOS(FC_SUBTYPE(fc))) { meshdrlen = extract_mesh_header_length(p+hdrlen); hdrlen += meshdrlen; } else meshdrlen = 0; if (caplen < hdrlen) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } if (ndo->ndo_eflag) ieee_802_11_hdr_print(ndo, fc, p, hdrlen, meshdrlen); /* * Go past the 802.11 header. */ length -= hdrlen; caplen -= hdrlen; p += hdrlen; src.addr_string = etheraddr_string; dst.addr_string = etheraddr_string; switch (FC_TYPE(fc)) { case T_MGMT: get_mgmt_src_dst_mac(p - hdrlen, &src.addr, &dst.addr); if (!mgmt_body_print(ndo, fc, src.addr, p, length)) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } break; case T_CTRL: if (!ctrl_body_print(ndo, fc, p - hdrlen)) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } break; case T_DATA: if (DATA_FRAME_IS_NULL(FC_SUBTYPE(fc))) return hdrlen; /* no-data frame */ /* There may be a problem w/ AP not having this bit set */ if (FC_PROTECTED(fc)) { ND_PRINT((ndo, "Data")); if (!wep_print(ndo, p)) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } } else { get_data_src_dst_mac(fc, p - hdrlen, &src.addr, &dst.addr); llc_hdrlen = llc_print(ndo, p, length, caplen, &src, &dst); if (llc_hdrlen < 0) { /* * Some kinds of LLC packet we cannot * handle intelligently */ if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); llc_hdrlen = -llc_hdrlen; } hdrlen += llc_hdrlen; } break; default: /* We shouldn't get here - we should already have quit */ break; } return hdrlen; } Commit Message: (for 4.9.3) CVE-2018-16227/IEEE 802.11: add a missing bounds check ieee802_11_print() tried to access the Mesh Flags subfield of the Mesh Control field to find the size of the latter and increment the expected 802.11 header length before checking it is fully present in the input buffer. Add an intermediate bounds check to make it safe. This fixes a buffer over-read discovered by Ryan Ackroyd. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
ieee802_11_print(netdissect_options *ndo, const u_char *p, u_int length, u_int orig_caplen, int pad, u_int fcslen) { uint16_t fc; u_int caplen, hdrlen, meshdrlen; struct lladdr_info src, dst; int llc_hdrlen; caplen = orig_caplen; /* Remove FCS, if present */ if (length < fcslen) { ND_PRINT((ndo, "%s", tstr)); return caplen; } length -= fcslen; if (caplen > length) { /* Amount of FCS in actual packet data, if any */ fcslen = caplen - length; caplen -= fcslen; ndo->ndo_snapend -= fcslen; } if (caplen < IEEE802_11_FC_LEN) { ND_PRINT((ndo, "%s", tstr)); return orig_caplen; } fc = EXTRACT_LE_16BITS(p); hdrlen = extract_header_length(ndo, fc); if (hdrlen == 0) { /* Unknown frame type or control frame subtype; quit. */ return (0); } if (pad) hdrlen = roundup2(hdrlen, 4); if (ndo->ndo_Hflag && FC_TYPE(fc) == T_DATA && DATA_FRAME_IS_QOS(FC_SUBTYPE(fc))) { if (caplen < hdrlen + 1) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } meshdrlen = extract_mesh_header_length(p+hdrlen); hdrlen += meshdrlen; } else meshdrlen = 0; if (caplen < hdrlen) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } if (ndo->ndo_eflag) ieee_802_11_hdr_print(ndo, fc, p, hdrlen, meshdrlen); /* * Go past the 802.11 header. */ length -= hdrlen; caplen -= hdrlen; p += hdrlen; src.addr_string = etheraddr_string; dst.addr_string = etheraddr_string; switch (FC_TYPE(fc)) { case T_MGMT: get_mgmt_src_dst_mac(p - hdrlen, &src.addr, &dst.addr); if (!mgmt_body_print(ndo, fc, src.addr, p, length)) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } break; case T_CTRL: if (!ctrl_body_print(ndo, fc, p - hdrlen)) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } break; case T_DATA: if (DATA_FRAME_IS_NULL(FC_SUBTYPE(fc))) return hdrlen; /* no-data frame */ /* There may be a problem w/ AP not having this bit set */ if (FC_PROTECTED(fc)) { ND_PRINT((ndo, "Data")); if (!wep_print(ndo, p)) { ND_PRINT((ndo, "%s", tstr)); return hdrlen; } } else { get_data_src_dst_mac(fc, p - hdrlen, &src.addr, &dst.addr); llc_hdrlen = llc_print(ndo, p, length, caplen, &src, &dst); if (llc_hdrlen < 0) { /* * Some kinds of LLC packet we cannot * handle intelligently */ if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); llc_hdrlen = -llc_hdrlen; } hdrlen += llc_hdrlen; } break; default: /* We shouldn't get here - we should already have quit */ break; } return hdrlen; }
169,821
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: checked_xmalloc (size_t size) { alloc_limit_assert ("checked_xmalloc", size); return xmalloc (size); } Commit Message: Fix integer overflows and harden memory allocator. CWE ID: CWE-190
checked_xmalloc (size_t size) checked_xmalloc (size_t num, size_t size) { size_t res; if (check_mul_overflow(num, size, &res)) abort(); alloc_limit_assert ("checked_xmalloc", res); return xmalloc (num, size); }
168,357
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 nbd_negotiate_write(QIOChannel *ioc, const void *buffer, size_t size) { ssize_t ret; guint watch; assert(qemu_in_coroutine()); /* Negotiation are always in main loop. */ watch = qio_channel_add_watch(ioc, G_IO_OUT, nbd_negotiate_continue, qemu_coroutine_self(), NULL); ret = nbd_write(ioc, buffer, size, NULL); g_source_remove(watch); return ret; } Commit Message: CWE ID: CWE-20
static int nbd_negotiate_write(QIOChannel *ioc, const void *buffer, size_t size)
165,455
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 ResourceLoader::WillFollowRedirect( const WebURL& new_url, const WebURL& new_site_for_cookies, const WebString& new_referrer, WebReferrerPolicy new_referrer_policy, const WebString& new_method, const WebURLResponse& passed_redirect_response, bool& report_raw_headers) { DCHECK(!passed_redirect_response.IsNull()); if (is_cache_aware_loading_activated_) { HandleError( ResourceError::CacheMissError(resource_->LastResourceRequest().Url())); return false; } const ResourceRequest& last_request = resource_->LastResourceRequest(); ResourceRequest new_request(new_url); new_request.SetSiteForCookies(new_site_for_cookies); new_request.SetDownloadToFile(last_request.DownloadToFile()); new_request.SetUseStreamOnResponse(last_request.UseStreamOnResponse()); new_request.SetRequestContext(last_request.GetRequestContext()); new_request.SetFrameType(last_request.GetFrameType()); new_request.SetServiceWorkerMode( passed_redirect_response.WasFetchedViaServiceWorker() ? WebURLRequest::ServiceWorkerMode::kAll : WebURLRequest::ServiceWorkerMode::kNone); new_request.SetShouldResetAppCache(last_request.ShouldResetAppCache()); new_request.SetFetchRequestMode(last_request.GetFetchRequestMode()); new_request.SetFetchCredentialsMode(last_request.GetFetchCredentialsMode()); new_request.SetKeepalive(last_request.GetKeepalive()); String referrer = new_referrer.IsEmpty() ? Referrer::NoReferrer() : String(new_referrer); new_request.SetHTTPReferrer( Referrer(referrer, static_cast<ReferrerPolicy>(new_referrer_policy))); new_request.SetPriority(last_request.Priority()); new_request.SetHTTPMethod(new_method); if (new_request.HttpMethod() == last_request.HttpMethod()) new_request.SetHTTPBody(last_request.HttpBody()); new_request.SetCheckForBrowserSideNavigation( last_request.CheckForBrowserSideNavigation()); Resource::Type resource_type = resource_->GetType(); const ResourceRequest& initial_request = resource_->GetResourceRequest(); WebURLRequest::RequestContext request_context = initial_request.GetRequestContext(); WebURLRequest::FrameType frame_type = initial_request.GetFrameType(); WebURLRequest::FetchRequestMode fetch_request_mode = initial_request.GetFetchRequestMode(); WebURLRequest::FetchCredentialsMode fetch_credentials_mode = initial_request.GetFetchCredentialsMode(); const ResourceLoaderOptions& options = resource_->Options(); const ResourceResponse& redirect_response( passed_redirect_response.ToResourceResponse()); new_request.SetRedirectStatus( ResourceRequest::RedirectStatus::kFollowedRedirect); if (!IsManualRedirectFetchRequest(initial_request)) { bool unused_preload = resource_->IsUnusedPreload(); SecurityViolationReportingPolicy reporting_policy = unused_preload ? SecurityViolationReportingPolicy::kSuppressReporting : SecurityViolationReportingPolicy::kReport; Context().CheckCSPForRequest( request_context, new_url, options, reporting_policy, ResourceRequest::RedirectStatus::kFollowedRedirect); ResourceRequestBlockedReason blocked_reason = Context().CanRequest( resource_type, new_request, new_url, options, reporting_policy, FetchParameters::kUseDefaultOriginRestrictionForType, ResourceRequest::RedirectStatus::kFollowedRedirect); if (blocked_reason != ResourceRequestBlockedReason::kNone) { CancelForRedirectAccessCheckError(new_url, blocked_reason); return false; } if (options.cors_handling_by_resource_fetcher == kEnableCORSHandlingByResourceFetcher && fetch_request_mode == WebURLRequest::kFetchRequestModeCORS) { RefPtr<SecurityOrigin> source_origin = options.security_origin; if (!source_origin.get()) source_origin = Context().GetSecurityOrigin(); WebSecurityOrigin source_web_origin(source_origin.get()); WrappedResourceRequest new_request_wrapper(new_request); WebString cors_error_msg; if (!WebCORS::HandleRedirect( source_web_origin, new_request_wrapper, redirect_response.Url(), redirect_response.HttpStatusCode(), redirect_response.HttpHeaderFields(), fetch_credentials_mode, resource_->MutableOptions(), cors_error_msg)) { resource_->SetCORSStatus(CORSStatus::kFailed); if (!unused_preload) { Context().AddErrorConsoleMessage(cors_error_msg, FetchContext::kJSSource); } CancelForRedirectAccessCheckError(new_url, ResourceRequestBlockedReason::kOther); return false; } source_origin = source_web_origin; } if (resource_type == Resource::kImage && fetcher_->ShouldDeferImageLoad(new_url)) { CancelForRedirectAccessCheckError(new_url, ResourceRequestBlockedReason::kOther); return false; } } bool cross_origin = !SecurityOrigin::AreSameSchemeHostPort(redirect_response.Url(), new_url); fetcher_->RecordResourceTimingOnRedirect(resource_.Get(), redirect_response, cross_origin); if (options.cors_handling_by_resource_fetcher == kEnableCORSHandlingByResourceFetcher && fetch_request_mode == WebURLRequest::kFetchRequestModeCORS) { bool allow_stored_credentials = false; switch (fetch_credentials_mode) { case WebURLRequest::kFetchCredentialsModeOmit: break; case WebURLRequest::kFetchCredentialsModeSameOrigin: allow_stored_credentials = !options.cors_flag; break; case WebURLRequest::kFetchCredentialsModeInclude: case WebURLRequest::kFetchCredentialsModePassword: allow_stored_credentials = true; break; } new_request.SetAllowStoredCredentials(allow_stored_credentials); } Context().PrepareRequest(new_request, FetchContext::RedirectType::kForRedirect); Context().DispatchWillSendRequest(resource_->Identifier(), new_request, redirect_response, options.initiator_info); DCHECK(KURL(new_site_for_cookies) == new_request.SiteForCookies()); DCHECK_EQ(new_request.GetRequestContext(), request_context); DCHECK_EQ(new_request.GetFrameType(), frame_type); DCHECK_EQ(new_request.GetFetchRequestMode(), fetch_request_mode); DCHECK_EQ(new_request.GetFetchCredentialsMode(), fetch_credentials_mode); if (new_request.Url() != KURL(new_url)) { CancelForRedirectAccessCheckError(new_request.Url(), ResourceRequestBlockedReason::kOther); return false; } if (!resource_->WillFollowRedirect(new_request, redirect_response)) { CancelForRedirectAccessCheckError(new_request.Url(), ResourceRequestBlockedReason::kOther); return false; } report_raw_headers = new_request.ReportRawHeaders(); return true; } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119
bool ResourceLoader::WillFollowRedirect( const WebURL& new_url, const WebURL& new_site_for_cookies, const WebString& new_referrer, WebReferrerPolicy new_referrer_policy, const WebString& new_method, const WebURLResponse& passed_redirect_response, bool& report_raw_headers) { DCHECK(!passed_redirect_response.IsNull()); if (is_cache_aware_loading_activated_) { HandleError( ResourceError::CacheMissError(resource_->LastResourceRequest().Url())); return false; } const ResourceRequest& last_request = resource_->LastResourceRequest(); ResourceRequest new_request(new_url); new_request.SetSiteForCookies(new_site_for_cookies); new_request.SetDownloadToFile(last_request.DownloadToFile()); new_request.SetUseStreamOnResponse(last_request.UseStreamOnResponse()); new_request.SetRequestContext(last_request.GetRequestContext()); new_request.SetFrameType(last_request.GetFrameType()); new_request.SetServiceWorkerMode( passed_redirect_response.WasFetchedViaServiceWorker() ? WebURLRequest::ServiceWorkerMode::kAll : WebURLRequest::ServiceWorkerMode::kNone); new_request.SetShouldResetAppCache(last_request.ShouldResetAppCache()); new_request.SetFetchRequestMode(last_request.GetFetchRequestMode()); new_request.SetFetchCredentialsMode(last_request.GetFetchCredentialsMode()); new_request.SetKeepalive(last_request.GetKeepalive()); String referrer = new_referrer.IsEmpty() ? Referrer::NoReferrer() : String(new_referrer); new_request.SetHTTPReferrer( Referrer(referrer, static_cast<ReferrerPolicy>(new_referrer_policy))); new_request.SetPriority(last_request.Priority()); new_request.SetHTTPMethod(new_method); if (new_request.HttpMethod() == last_request.HttpMethod()) new_request.SetHTTPBody(last_request.HttpBody()); new_request.SetCheckForBrowserSideNavigation( last_request.CheckForBrowserSideNavigation()); Resource::Type resource_type = resource_->GetType(); const ResourceRequest& initial_request = resource_->GetResourceRequest(); WebURLRequest::RequestContext request_context = initial_request.GetRequestContext(); WebURLRequest::FrameType frame_type = initial_request.GetFrameType(); WebURLRequest::FetchRequestMode fetch_request_mode = initial_request.GetFetchRequestMode(); WebURLRequest::FetchCredentialsMode fetch_credentials_mode = initial_request.GetFetchCredentialsMode(); const ResourceLoaderOptions& options = resource_->Options(); const ResourceResponse& redirect_response( passed_redirect_response.ToResourceResponse()); new_request.SetRedirectStatus( ResourceRequest::RedirectStatus::kFollowedRedirect); if (!IsManualRedirectFetchRequest(initial_request)) { bool unused_preload = resource_->IsUnusedPreload(); SecurityViolationReportingPolicy reporting_policy = unused_preload ? SecurityViolationReportingPolicy::kSuppressReporting : SecurityViolationReportingPolicy::kReport; Context().CheckCSPForRequest( request_context, new_url, options, reporting_policy, ResourceRequest::RedirectStatus::kFollowedRedirect); ResourceRequestBlockedReason blocked_reason = Context().CanRequest( resource_type, new_request, new_url, options, reporting_policy, FetchParameters::kUseDefaultOriginRestrictionForType, ResourceRequest::RedirectStatus::kFollowedRedirect); if (blocked_reason != ResourceRequestBlockedReason::kNone) { CancelForRedirectAccessCheckError(new_url, blocked_reason); return false; } if (options.cors_handling_by_resource_fetcher == kEnableCORSHandlingByResourceFetcher && fetch_request_mode == WebURLRequest::kFetchRequestModeCORS) { RefPtr<SecurityOrigin> source_origin = options.security_origin; if (!source_origin.get()) source_origin = Context().GetSecurityOrigin(); WebSecurityOrigin source_web_origin(source_origin.get()); WrappedResourceRequest new_request_wrapper(new_request); WebString cors_error_msg; if (!WebCORS::HandleRedirect( source_web_origin, new_request_wrapper, redirect_response.Url(), redirect_response.HttpStatusCode(), redirect_response.HttpHeaderFields(), fetch_credentials_mode, resource_->MutableOptions(), cors_error_msg)) { resource_->SetCORSStatus(CORSStatus::kFailed); if (!unused_preload) { Context().AddErrorConsoleMessage(cors_error_msg, FetchContext::kJSSource); } CancelForRedirectAccessCheckError(new_url, ResourceRequestBlockedReason::kOther); return false; } source_origin = source_web_origin; } if (resource_type == Resource::kImage && fetcher_->ShouldDeferImageLoad(new_url)) { CancelForRedirectAccessCheckError(new_url, ResourceRequestBlockedReason::kOther); return false; } } bool cross_origin = !SecurityOrigin::AreSameSchemeHostPort(redirect_response.Url(), new_url); fetcher_->RecordResourceTimingOnRedirect(resource_.Get(), redirect_response, cross_origin); if (options.cors_handling_by_resource_fetcher == kEnableCORSHandlingByResourceFetcher && fetch_request_mode == WebURLRequest::kFetchRequestModeCORS) { bool allow_stored_credentials = false; switch (fetch_credentials_mode) { case WebURLRequest::kFetchCredentialsModeOmit: break; case WebURLRequest::kFetchCredentialsModeSameOrigin: allow_stored_credentials = !options.cors_flag; break; case WebURLRequest::kFetchCredentialsModeInclude: case WebURLRequest::kFetchCredentialsModePassword: allow_stored_credentials = true; break; } new_request.SetAllowStoredCredentials(allow_stored_credentials); } Context().PrepareRequest(new_request, FetchContext::RedirectType::kForRedirect); Context().DispatchWillSendRequest(resource_->Identifier(), new_request, redirect_response, resource_->GetType(), options.initiator_info); DCHECK(KURL(new_site_for_cookies) == new_request.SiteForCookies()); DCHECK_EQ(new_request.GetRequestContext(), request_context); DCHECK_EQ(new_request.GetFrameType(), frame_type); DCHECK_EQ(new_request.GetFetchRequestMode(), fetch_request_mode); DCHECK_EQ(new_request.GetFetchCredentialsMode(), fetch_credentials_mode); if (new_request.Url() != KURL(new_url)) { CancelForRedirectAccessCheckError(new_request.Url(), ResourceRequestBlockedReason::kOther); return false; } if (!resource_->WillFollowRedirect(new_request, redirect_response)) { CancelForRedirectAccessCheckError(new_request.Url(), ResourceRequestBlockedReason::kOther); return false; } report_raw_headers = new_request.ReportRawHeaders(); return true; }
172,480
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 ZEXPORT inflateMark(strm) z_streamp strm; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16; state = (struct inflate_state FAR *)strm->state; return ((long)(state->back) << 16) + (state->mode == COPY ? state->length : (state->mode == MATCH ? state->was - state->length : 0)); } Commit Message: Avoid shifts of negative values inflateMark(). The C standard says that bit shifts of negative integers is undefined. This casts to unsigned values to assure a known result. CWE ID: CWE-189
long ZEXPORT inflateMark(strm) z_streamp strm; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->state == Z_NULL) return (long)(((unsigned long)0 - 1) << 16); state = (struct inflate_state FAR *)strm->state; return (long)(((unsigned long)((long)state->back)) << 16) + (state->mode == COPY ? state->length : (state->mode == MATCH ? state->was - state->length : 0)); }
168,673
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 evm_update_evmxattr(struct dentry *dentry, const char *xattr_name, const char *xattr_value, size_t xattr_value_len) { struct inode *inode = dentry->d_inode; struct evm_ima_xattr_data xattr_data; int rc = 0; rc = evm_calc_hmac(dentry, xattr_name, xattr_value, xattr_value_len, xattr_data.digest); if (rc == 0) { xattr_data.type = EVM_XATTR_HMAC; rc = __vfs_setxattr_noperm(dentry, XATTR_NAME_EVM, &xattr_data, sizeof(xattr_data), 0); } else if (rc == -ENODATA) rc = inode->i_op->removexattr(dentry, XATTR_NAME_EVM); return rc; } Commit Message: evm: checking if removexattr is not a NULL The following lines of code produce a kernel oops. fd = socket(PF_FILE, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0); fchmod(fd, 0666); [ 139.922364] BUG: unable to handle kernel NULL pointer dereference at (null) [ 139.924982] IP: [< (null)>] (null) [ 139.924982] *pde = 00000000 [ 139.924982] Oops: 0000 [#5] SMP [ 139.924982] Modules linked in: fuse dm_crypt dm_mod i2c_piix4 serio_raw evdev binfmt_misc button [ 139.924982] Pid: 3070, comm: acpid Tainted: G D 3.8.0-rc2-kds+ #465 Bochs Bochs [ 139.924982] EIP: 0060:[<00000000>] EFLAGS: 00010246 CPU: 0 [ 139.924982] EIP is at 0x0 [ 139.924982] EAX: cf5ef000 EBX: cf5ef000 ECX: c143d600 EDX: c15225f2 [ 139.924982] ESI: cf4d2a1c EDI: cf4d2a1c EBP: cc02df10 ESP: cc02dee4 [ 139.924982] DS: 007b ES: 007b FS: 00d8 GS: 0033 SS: 0068 [ 139.924982] CR0: 80050033 CR2: 00000000 CR3: 0c059000 CR4: 000006d0 [ 139.924982] DR0: 00000000 DR1: 00000000 DR2: 00000000 DR3: 00000000 [ 139.924982] DR6: ffff0ff0 DR7: 00000400 [ 139.924982] Process acpid (pid: 3070, ti=cc02c000 task=d7705340 task.ti=cc02c000) [ 139.924982] Stack: [ 139.924982] c1203c88 00000000 cc02def4 cf4d2a1c ae21eefa 471b60d5 1083c1ba c26a5940 [ 139.924982] e891fb5e 00000041 00000004 cc02df1c c1203964 00000000 cc02df4c c10e20c3 [ 139.924982] 00000002 00000000 00000000 22222222 c1ff2222 cf5ef000 00000000 d76efb08 [ 139.924982] Call Trace: [ 139.924982] [<c1203c88>] ? evm_update_evmxattr+0x5b/0x62 [ 139.924982] [<c1203964>] evm_inode_post_setattr+0x22/0x26 [ 139.924982] [<c10e20c3>] notify_change+0x25f/0x281 [ 139.924982] [<c10cbf56>] chmod_common+0x59/0x76 [ 139.924982] [<c10e27a1>] ? put_unused_fd+0x33/0x33 [ 139.924982] [<c10cca09>] sys_fchmod+0x39/0x5c [ 139.924982] [<c13f4f30>] syscall_call+0x7/0xb [ 139.924982] Code: Bad EIP value. This happens because sockets do not define the removexattr operation. Before removing the xattr, verify the removexattr function pointer is not NULL. Signed-off-by: Dmitry Kasatkin <[email protected]> Signed-off-by: Mimi Zohar <[email protected]> Cc: [email protected] Signed-off-by: James Morris <[email protected]> CWE ID:
int evm_update_evmxattr(struct dentry *dentry, const char *xattr_name, const char *xattr_value, size_t xattr_value_len) { struct inode *inode = dentry->d_inode; struct evm_ima_xattr_data xattr_data; int rc = 0; rc = evm_calc_hmac(dentry, xattr_name, xattr_value, xattr_value_len, xattr_data.digest); if (rc == 0) { xattr_data.type = EVM_XATTR_HMAC; rc = __vfs_setxattr_noperm(dentry, XATTR_NAME_EVM, &xattr_data, sizeof(xattr_data), 0); } else if (rc == -ENODATA && inode->i_op->removexattr) { rc = inode->i_op->removexattr(dentry, XATTR_NAME_EVM); } return rc; }
166,141
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 futex_wait_requeue_pi(u32 __user *uaddr, int fshared, u32 val, ktime_t *abs_time, u32 bitset, int clockrt, u32 __user *uaddr2) { struct hrtimer_sleeper timeout, *to = NULL; struct rt_mutex_waiter rt_waiter; struct rt_mutex *pi_mutex = NULL; struct futex_hash_bucket *hb; union futex_key key2; struct futex_q q; int res, ret; if (!bitset) return -EINVAL; if (abs_time) { to = &timeout; hrtimer_init_on_stack(&to->timer, clockrt ? CLOCK_REALTIME : CLOCK_MONOTONIC, HRTIMER_MODE_ABS); hrtimer_init_sleeper(to, current); hrtimer_set_expires_range_ns(&to->timer, *abs_time, current->timer_slack_ns); } /* * The waiter is allocated on our stack, manipulated by the requeue * code while we sleep on uaddr. */ debug_rt_mutex_init_waiter(&rt_waiter); rt_waiter.task = NULL; key2 = FUTEX_KEY_INIT; ret = get_futex_key(uaddr2, fshared, &key2); if (unlikely(ret != 0)) goto out; q.pi_state = NULL; q.bitset = bitset; q.rt_waiter = &rt_waiter; q.requeue_pi_key = &key2; /* Prepare to wait on uaddr. */ ret = futex_wait_setup(uaddr, val, fshared, &q, &hb); if (ret) goto out_key2; /* Queue the futex_q, drop the hb lock, wait for wakeup. */ futex_wait_queue_me(hb, &q, to); spin_lock(&hb->lock); ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to); spin_unlock(&hb->lock); if (ret) goto out_put_keys; /* * In order for us to be here, we know our q.key == key2, and since * we took the hb->lock above, we also know that futex_requeue() has * completed and we no longer have to concern ourselves with a wakeup * race with the atomic proxy lock acquition by the requeue code. */ /* Check if the requeue code acquired the second futex for us. */ if (!q.rt_waiter) { /* * Got the lock. We might not be the anticipated owner if we * did a lock-steal - fix up the PI-state in that case. */ if (q.pi_state && (q.pi_state->owner != current)) { spin_lock(q.lock_ptr); ret = fixup_pi_state_owner(uaddr2, &q, current, fshared); spin_unlock(q.lock_ptr); } } else { /* * We have been woken up by futex_unlock_pi(), a timeout, or a * signal. futex_unlock_pi() will not destroy the lock_ptr nor * the pi_state. */ WARN_ON(!&q.pi_state); pi_mutex = &q.pi_state->pi_mutex; ret = rt_mutex_finish_proxy_lock(pi_mutex, to, &rt_waiter, 1); debug_rt_mutex_free_waiter(&rt_waiter); spin_lock(q.lock_ptr); /* * Fixup the pi_state owner and possibly acquire the lock if we * haven't already. */ res = fixup_owner(uaddr2, fshared, &q, !ret); /* * If fixup_owner() returned an error, proprogate that. If it * acquired the lock, clear -ETIMEDOUT or -EINTR. */ if (res) ret = (res < 0) ? res : 0; /* Unqueue and drop the lock. */ unqueue_me_pi(&q); } /* * If fixup_pi_state_owner() faulted and was unable to handle the * fault, unlock the rt_mutex and return the fault to userspace. */ if (ret == -EFAULT) { if (rt_mutex_owner(pi_mutex) == current) rt_mutex_unlock(pi_mutex); } else if (ret == -EINTR) { /* * We've already been requeued, but cannot restart by calling * futex_lock_pi() directly. We could restart this syscall, but * it would detect that the user space "val" changed and return * -EWOULDBLOCK. Save the overhead of the restart and return * -EWOULDBLOCK directly. */ ret = -EWOULDBLOCK; } out_put_keys: put_futex_key(fshared, &q.key); out_key2: put_futex_key(fshared, &key2); out: if (to) { hrtimer_cancel(&to->timer); destroy_hrtimer_on_stack(&to->timer); } return ret; } Commit Message: futex: Fix errors in nested key ref-counting futex_wait() is leaking key references due to futex_wait_setup() acquiring an additional reference via the queue_lock() routine. The nested key ref-counting has been masking bugs and complicating code analysis. queue_lock() is only called with a previously ref-counted key, so remove the additional ref-counting from the queue_(un)lock() functions. Also futex_wait_requeue_pi() drops one key reference too many in unqueue_me_pi(). Remove the key reference handling from unqueue_me_pi(). This was paired with a queue_lock() in futex_lock_pi(), so the count remains unchanged. Document remaining nested key ref-counting sites. Signed-off-by: Darren Hart <[email protected]> Reported-and-tested-by: Matthieu Fertré<[email protected]> Reported-by: Louis Rilling<[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Eric Dumazet <[email protected]> Cc: John Kacur <[email protected]> Cc: Rusty Russell <[email protected]> LKML-Reference: <[email protected]> Signed-off-by: Thomas Gleixner <[email protected]> Cc: [email protected] CWE ID: CWE-119
static int futex_wait_requeue_pi(u32 __user *uaddr, int fshared, u32 val, ktime_t *abs_time, u32 bitset, int clockrt, u32 __user *uaddr2) { struct hrtimer_sleeper timeout, *to = NULL; struct rt_mutex_waiter rt_waiter; struct rt_mutex *pi_mutex = NULL; struct futex_hash_bucket *hb; union futex_key key2; struct futex_q q; int res, ret; if (!bitset) return -EINVAL; if (abs_time) { to = &timeout; hrtimer_init_on_stack(&to->timer, clockrt ? CLOCK_REALTIME : CLOCK_MONOTONIC, HRTIMER_MODE_ABS); hrtimer_init_sleeper(to, current); hrtimer_set_expires_range_ns(&to->timer, *abs_time, current->timer_slack_ns); } /* * The waiter is allocated on our stack, manipulated by the requeue * code while we sleep on uaddr. */ debug_rt_mutex_init_waiter(&rt_waiter); rt_waiter.task = NULL; key2 = FUTEX_KEY_INIT; ret = get_futex_key(uaddr2, fshared, &key2); if (unlikely(ret != 0)) goto out; q.pi_state = NULL; q.bitset = bitset; q.rt_waiter = &rt_waiter; q.requeue_pi_key = &key2; /* * Prepare to wait on uaddr. On success, increments q.key (key1) ref * count. */ ret = futex_wait_setup(uaddr, val, fshared, &q, &hb); if (ret) goto out_key2; /* Queue the futex_q, drop the hb lock, wait for wakeup. */ futex_wait_queue_me(hb, &q, to); spin_lock(&hb->lock); ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to); spin_unlock(&hb->lock); if (ret) goto out_put_keys; /* * In order for us to be here, we know our q.key == key2, and since * we took the hb->lock above, we also know that futex_requeue() has * completed and we no longer have to concern ourselves with a wakeup * race with the atomic proxy lock acquisition by the requeue code. The * futex_requeue dropped our key1 reference and incremented our key2 * reference count. */ /* Check if the requeue code acquired the second futex for us. */ if (!q.rt_waiter) { /* * Got the lock. We might not be the anticipated owner if we * did a lock-steal - fix up the PI-state in that case. */ if (q.pi_state && (q.pi_state->owner != current)) { spin_lock(q.lock_ptr); ret = fixup_pi_state_owner(uaddr2, &q, current, fshared); spin_unlock(q.lock_ptr); } } else { /* * We have been woken up by futex_unlock_pi(), a timeout, or a * signal. futex_unlock_pi() will not destroy the lock_ptr nor * the pi_state. */ WARN_ON(!&q.pi_state); pi_mutex = &q.pi_state->pi_mutex; ret = rt_mutex_finish_proxy_lock(pi_mutex, to, &rt_waiter, 1); debug_rt_mutex_free_waiter(&rt_waiter); spin_lock(q.lock_ptr); /* * Fixup the pi_state owner and possibly acquire the lock if we * haven't already. */ res = fixup_owner(uaddr2, fshared, &q, !ret); /* * If fixup_owner() returned an error, proprogate that. If it * acquired the lock, clear -ETIMEDOUT or -EINTR. */ if (res) ret = (res < 0) ? res : 0; /* Unqueue and drop the lock. */ unqueue_me_pi(&q); } /* * If fixup_pi_state_owner() faulted and was unable to handle the * fault, unlock the rt_mutex and return the fault to userspace. */ if (ret == -EFAULT) { if (rt_mutex_owner(pi_mutex) == current) rt_mutex_unlock(pi_mutex); } else if (ret == -EINTR) { /* * We've already been requeued, but cannot restart by calling * futex_lock_pi() directly. We could restart this syscall, but * it would detect that the user space "val" changed and return * -EWOULDBLOCK. Save the overhead of the restart and return * -EWOULDBLOCK directly. */ ret = -EWOULDBLOCK; } out_put_keys: put_futex_key(fshared, &q.key); out_key2: put_futex_key(fshared, &key2); out: if (to) { hrtimer_cancel(&to->timer); destroy_hrtimer_on_stack(&to->timer); } return ret; }
166,450
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 CtcpHandler::handleAction(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param) { Q_UNUSED(ctcptype) emit displayMsg(Message::Action, typeByTarget(target), target, param, prefix); } Commit Message: CWE ID: CWE-399
void CtcpHandler::handleAction(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param) { void CtcpHandler::handleAction(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param, QString &/*reply*/) { Q_UNUSED(ctcptype) emit displayMsg(Message::Action, typeByTarget(target), target, param, prefix); }
164,877
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 SQLWriteFileDSN( LPCSTR pszFileName, LPCSTR pszAppName, LPCSTR pszKeyName, LPCSTR pszString ) { HINI hIni; char szFileName[ODBC_FILENAME_MAX+1]; if ( pszFileName[0] == '/' ) { strncpy( szFileName, sizeof(szFileName) - 5, pszFileName ); } else { char szPath[ODBC_FILENAME_MAX+1]; *szPath = '\0'; _odbcinst_FileINI( szPath ); snprintf( szFileName, sizeof(szFileName) - 5, "%s/%s", szPath, pszFileName ); } if ( strlen( szFileName ) < 4 || strcmp( szFileName + strlen( szFileName ) - 4, ".dsn" )) { strcat( szFileName, ".dsn" ); } #ifdef __OS2__ if ( iniOpen( &hIni, szFileName, "#;", '[', ']', '=', TRUE, 0L ) != INI_SUCCESS ) #else if ( iniOpen( &hIni, szFileName, "#;", '[', ']', '=', TRUE ) != INI_SUCCESS ) #endif { inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_INVALID_PATH, "" ); return FALSE; } /* delete section */ if ( pszString == NULL && pszKeyName == NULL ) { if ( iniObjectSeek( hIni, (char *)pszAppName ) == INI_SUCCESS ) { iniObjectDelete( hIni ); } } /* delete entry */ else if ( pszString == NULL ) { if ( iniPropertySeek( hIni, (char *)pszAppName, (char *)pszKeyName, "" ) == INI_SUCCESS ) { iniPropertyDelete( hIni ); } } else { /* add section */ if ( iniObjectSeek( hIni, (char *)pszAppName ) != INI_SUCCESS ) { iniObjectInsert( hIni, (char *)pszAppName ); } /* update entry */ if ( iniPropertySeek( hIni, (char *)pszAppName, (char *)pszKeyName, "" ) == INI_SUCCESS ) { iniObjectSeek( hIni, (char *)pszAppName ); iniPropertyUpdate( hIni, (char *)pszKeyName, (char *)pszString ); } /* add entry */ else { iniObjectSeek( hIni, (char *)pszAppName ); iniPropertyInsert( hIni, (char *)pszKeyName, (char *)pszString ); } } if ( iniCommit( hIni ) != INI_SUCCESS ) { iniClose( hIni ); inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_REQUEST_FAILED, "" ); return FALSE; } iniClose( hIni ); return TRUE; } Commit Message: New Pre Source CWE ID: CWE-119
BOOL SQLWriteFileDSN( LPCSTR pszFileName, LPCSTR pszAppName, LPCSTR pszKeyName, LPCSTR pszString ) { HINI hIni; char szFileName[ODBC_FILENAME_MAX+1]; if ( pszFileName[0] == '/' ) { strncpy( szFileName, pszFileName, sizeof(szFileName) - 5 ); } else { char szPath[ODBC_FILENAME_MAX+1]; *szPath = '\0'; _odbcinst_FileINI( szPath ); snprintf( szFileName, sizeof(szFileName) - 5, "%s/%s", szPath, pszFileName ); } if ( strlen( szFileName ) < 4 || strcmp( szFileName + strlen( szFileName ) - 4, ".dsn" )) { strcat( szFileName, ".dsn" ); } #ifdef __OS2__ if ( iniOpen( &hIni, szFileName, "#;", '[', ']', '=', TRUE, 0L ) != INI_SUCCESS ) #else if ( iniOpen( &hIni, szFileName, "#;", '[', ']', '=', TRUE ) != INI_SUCCESS ) #endif { inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_INVALID_PATH, "" ); return FALSE; } /* delete section */ if ( pszString == NULL && pszKeyName == NULL ) { if ( iniObjectSeek( hIni, (char *)pszAppName ) == INI_SUCCESS ) { iniObjectDelete( hIni ); } } /* delete entry */ else if ( pszString == NULL ) { if ( iniPropertySeek( hIni, (char *)pszAppName, (char *)pszKeyName, "" ) == INI_SUCCESS ) { iniPropertyDelete( hIni ); } } else { /* add section */ if ( iniObjectSeek( hIni, (char *)pszAppName ) != INI_SUCCESS ) { iniObjectInsert( hIni, (char *)pszAppName ); } /* update entry */ if ( iniPropertySeek( hIni, (char *)pszAppName, (char *)pszKeyName, "" ) == INI_SUCCESS ) { iniObjectSeek( hIni, (char *)pszAppName ); iniPropertyUpdate( hIni, (char *)pszKeyName, (char *)pszString ); } /* add entry */ else { iniObjectSeek( hIni, (char *)pszAppName ); iniPropertyInsert( hIni, (char *)pszKeyName, (char *)pszString ); } } if ( iniCommit( hIni ) != INI_SUCCESS ) { iniClose( hIni ); inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_REQUEST_FAILED, "" ); return FALSE; } iniClose( hIni ); return TRUE; }
169,317
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 Segment::LoadCluster( long long& pos, long& len) { for (;;) { const long result = DoLoadCluster(pos, len); if (result <= 1) return result; } } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Segment::LoadCluster( if (result <= 1) return result; } } long Segment::DoLoadCluster(long long& pos, long& len) { if (m_pos < 0) return DoLoadClusterUnknownSize(pos, len); long long total, avail; long status = m_pReader->Length(&total, &avail); if (status < 0) // error return status; assert((total < 0) || (avail <= total)); const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; long long cluster_off = -1; // offset relative to start of segment long long cluster_size = -1; // size of cluster payload for (;;) { if ((total >= 0) && (m_pos >= total)) return 1; // no more clusters if ((segment_stop >= 0) && (m_pos >= segment_stop)) return 1; // no more clusters pos = m_pos; // Read ID if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; }
174,396
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 set_core_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg) { __u32 __user *uaddr = (__u32 __user *)(unsigned long)reg->addr; struct kvm_regs *regs = vcpu_gp_regs(vcpu); int nr_regs = sizeof(*regs) / sizeof(__u32); __uint128_t tmp; void *valp = &tmp; u64 off; int err = 0; /* Our ID is an index into the kvm_regs struct. */ off = core_reg_offset_from_id(reg->id); if (off >= nr_regs || (off + (KVM_REG_SIZE(reg->id) / sizeof(__u32))) >= nr_regs) return -ENOENT; if (KVM_REG_SIZE(reg->id) > sizeof(tmp)) return -EINVAL; if (copy_from_user(valp, uaddr, KVM_REG_SIZE(reg->id))) { err = -EFAULT; goto out; } if (off == KVM_REG_ARM_CORE_REG(regs.pstate)) { u32 mode = (*(u32 *)valp) & PSR_AA32_MODE_MASK; switch (mode) { case PSR_AA32_MODE_USR: case PSR_AA32_MODE_FIQ: case PSR_AA32_MODE_IRQ: case PSR_AA32_MODE_SVC: case PSR_AA32_MODE_ABT: case PSR_AA32_MODE_UND: case PSR_MODE_EL0t: case PSR_MODE_EL1t: case PSR_MODE_EL1h: break; default: err = -EINVAL; goto out; } } memcpy((u32 *)regs + off, valp, KVM_REG_SIZE(reg->id)); out: return err; } Commit Message: arm64: KVM: Tighten guest core register access from userspace We currently allow userspace to access the core register file in about any possible way, including straddling multiple registers and doing unaligned accesses. This is not the expected use of the ABI, and nobody is actually using it that way. Let's tighten it by explicitly checking the size and alignment for each field of the register file. Cc: <[email protected]> Fixes: 2f4a07c5f9fe ("arm64: KVM: guest one-reg interface") Reviewed-by: Christoffer Dall <[email protected]> Reviewed-by: Mark Rutland <[email protected]> Signed-off-by: Dave Martin <[email protected]> [maz: rewrote Dave's initial patch to be more easily backported] Signed-off-by: Marc Zyngier <[email protected]> Signed-off-by: Will Deacon <[email protected]> CWE ID: CWE-20
static int set_core_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg) { __u32 __user *uaddr = (__u32 __user *)(unsigned long)reg->addr; struct kvm_regs *regs = vcpu_gp_regs(vcpu); int nr_regs = sizeof(*regs) / sizeof(__u32); __uint128_t tmp; void *valp = &tmp; u64 off; int err = 0; /* Our ID is an index into the kvm_regs struct. */ off = core_reg_offset_from_id(reg->id); if (off >= nr_regs || (off + (KVM_REG_SIZE(reg->id) / sizeof(__u32))) >= nr_regs) return -ENOENT; if (validate_core_offset(reg)) return -EINVAL; if (KVM_REG_SIZE(reg->id) > sizeof(tmp)) return -EINVAL; if (copy_from_user(valp, uaddr, KVM_REG_SIZE(reg->id))) { err = -EFAULT; goto out; } if (off == KVM_REG_ARM_CORE_REG(regs.pstate)) { u32 mode = (*(u32 *)valp) & PSR_AA32_MODE_MASK; switch (mode) { case PSR_AA32_MODE_USR: case PSR_AA32_MODE_FIQ: case PSR_AA32_MODE_IRQ: case PSR_AA32_MODE_SVC: case PSR_AA32_MODE_ABT: case PSR_AA32_MODE_UND: case PSR_MODE_EL0t: case PSR_MODE_EL1t: case PSR_MODE_EL1h: break; default: err = -EINVAL; goto out; } } memcpy((u32 *)regs + off, valp, KVM_REG_SIZE(reg->id)); out: return err; }
169,012
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: xsltParseStylesheetAttributeSet(xsltStylesheetPtr style, xmlNodePtr cur) { const xmlChar *ncname; const xmlChar *prefix; xmlChar *value; xmlNodePtr child; xsltAttrElemPtr attrItems; if ((cur == NULL) || (style == NULL) || (cur->type != XML_ELEMENT_NODE)) return; value = xmlGetNsProp(cur, (const xmlChar *)"name", NULL); if (value == NULL) { xsltGenericError(xsltGenericErrorContext, "xsl:attribute-set : name is missing\n"); return; } ncname = xsltSplitQName(style->dict, value, &prefix); xmlFree(value); value = NULL; if (style->attributeSets == NULL) { #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "creating attribute set table\n"); #endif style->attributeSets = xmlHashCreate(10); } if (style->attributeSets == NULL) return; attrItems = xmlHashLookup2(style->attributeSets, ncname, prefix); /* * Parse the content. Only xsl:attribute elements are allowed. */ child = cur->children; while (child != NULL) { /* * Report invalid nodes. */ if ((child->type != XML_ELEMENT_NODE) || (child->ns == NULL) || (! IS_XSLT_ELEM(child))) { if (child->type == XML_ELEMENT_NODE) xsltTransformError(NULL, style, child, "xsl:attribute-set : unexpected child %s\n", child->name); else xsltTransformError(NULL, style, child, "xsl:attribute-set : child of unexpected type\n"); } else if (!IS_XSLT_NAME(child, "attribute")) { xsltTransformError(NULL, style, child, "xsl:attribute-set : unexpected child xsl:%s\n", child->name); } else { #ifdef XSLT_REFACTORED xsltAttrElemPtr nextAttr, curAttr; /* * Process xsl:attribute * --------------------- */ #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "add attribute to list %s\n", ncname); #endif /* * The following was taken over from * xsltAddAttrElemList(). */ if (attrItems == NULL) { attrItems = xsltNewAttrElem(child); } else { curAttr = attrItems; while (curAttr != NULL) { nextAttr = curAttr->next; if (curAttr->attr == child) { /* * URGENT TODO: Can somebody explain * why attrItems is set to curAttr * here? Is this somehow related to * avoidance of recursions? */ attrItems = curAttr; goto next_child; } if (curAttr->next == NULL) curAttr->next = xsltNewAttrElem(child); curAttr = nextAttr; } } /* * Parse the xsl:attribute and its content. */ xsltParseAnyXSLTElem(XSLT_CCTXT(style), child); #else #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "add attribute to list %s\n", ncname); #endif /* * OLD behaviour: */ attrItems = xsltAddAttrElemList(attrItems, child); #endif } #ifdef XSLT_REFACTORED next_child: #endif child = child->next; } /* * Process attribue "use-attribute-sets". */ /* TODO check recursion */ value = xmlGetNsProp(cur, (const xmlChar *)"use-attribute-sets", NULL); if (value != NULL) { const xmlChar *curval, *endval; curval = value; while (*curval != 0) { while (IS_BLANK(*curval)) curval++; if (*curval == 0) break; endval = curval; while ((*endval != 0) && (!IS_BLANK(*endval))) endval++; curval = xmlDictLookup(style->dict, curval, endval - curval); if (curval) { const xmlChar *ncname2 = NULL; const xmlChar *prefix2 = NULL; xsltAttrElemPtr refAttrItems; #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "xsl:attribute-set : %s adds use %s\n", ncname, curval); #endif ncname2 = xsltSplitQName(style->dict, curval, &prefix2); refAttrItems = xsltNewAttrElem(NULL); if (refAttrItems != NULL) { refAttrItems->set = ncname2; refAttrItems->ns = prefix2; attrItems = xsltMergeAttrElemList(style, attrItems, refAttrItems); xsltFreeAttrElem(refAttrItems); } } curval = endval; } xmlFree(value); value = NULL; } /* * Update the value */ /* * TODO: Why is this dummy entry needed.? */ if (attrItems == NULL) attrItems = xsltNewAttrElem(NULL); xmlHashUpdateEntry2(style->attributeSets, ncname, prefix, attrItems, NULL); #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "updated attribute list %s\n", ncname); #endif } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
xsltParseStylesheetAttributeSet(xsltStylesheetPtr style, xmlNodePtr cur) { const xmlChar *ncname; const xmlChar *prefix; xmlChar *value; xmlNodePtr child; xsltAttrElemPtr attrItems; if ((cur == NULL) || (style == NULL) || (cur->type != XML_ELEMENT_NODE)) return; value = xmlGetNsProp(cur, (const xmlChar *)"name", NULL); if ((value == NULL) || (*value == 0)) { xsltGenericError(xsltGenericErrorContext, "xsl:attribute-set : name is missing\n"); if (value) xmlFree(value); return; } ncname = xsltSplitQName(style->dict, value, &prefix); xmlFree(value); value = NULL; if (style->attributeSets == NULL) { #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "creating attribute set table\n"); #endif style->attributeSets = xmlHashCreate(10); } if (style->attributeSets == NULL) return; attrItems = xmlHashLookup2(style->attributeSets, ncname, prefix); /* * Parse the content. Only xsl:attribute elements are allowed. */ child = cur->children; while (child != NULL) { /* * Report invalid nodes. */ if ((child->type != XML_ELEMENT_NODE) || (child->ns == NULL) || (! IS_XSLT_ELEM(child))) { if (child->type == XML_ELEMENT_NODE) xsltTransformError(NULL, style, child, "xsl:attribute-set : unexpected child %s\n", child->name); else xsltTransformError(NULL, style, child, "xsl:attribute-set : child of unexpected type\n"); } else if (!IS_XSLT_NAME(child, "attribute")) { xsltTransformError(NULL, style, child, "xsl:attribute-set : unexpected child xsl:%s\n", child->name); } else { #ifdef XSLT_REFACTORED xsltAttrElemPtr nextAttr, curAttr; /* * Process xsl:attribute * --------------------- */ #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "add attribute to list %s\n", ncname); #endif /* * The following was taken over from * xsltAddAttrElemList(). */ if (attrItems == NULL) { attrItems = xsltNewAttrElem(child); } else { curAttr = attrItems; while (curAttr != NULL) { nextAttr = curAttr->next; if (curAttr->attr == child) { /* * URGENT TODO: Can somebody explain * why attrItems is set to curAttr * here? Is this somehow related to * avoidance of recursions? */ attrItems = curAttr; goto next_child; } if (curAttr->next == NULL) curAttr->next = xsltNewAttrElem(child); curAttr = nextAttr; } } /* * Parse the xsl:attribute and its content. */ xsltParseAnyXSLTElem(XSLT_CCTXT(style), child); #else #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "add attribute to list %s\n", ncname); #endif /* * OLD behaviour: */ attrItems = xsltAddAttrElemList(attrItems, child); #endif } #ifdef XSLT_REFACTORED next_child: #endif child = child->next; } /* * Process attribue "use-attribute-sets". */ /* TODO check recursion */ value = xmlGetNsProp(cur, (const xmlChar *)"use-attribute-sets", NULL); if (value != NULL) { const xmlChar *curval, *endval; curval = value; while (*curval != 0) { while (IS_BLANK(*curval)) curval++; if (*curval == 0) break; endval = curval; while ((*endval != 0) && (!IS_BLANK(*endval))) endval++; curval = xmlDictLookup(style->dict, curval, endval - curval); if (curval) { const xmlChar *ncname2 = NULL; const xmlChar *prefix2 = NULL; xsltAttrElemPtr refAttrItems; #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "xsl:attribute-set : %s adds use %s\n", ncname, curval); #endif ncname2 = xsltSplitQName(style->dict, curval, &prefix2); refAttrItems = xsltNewAttrElem(NULL); if (refAttrItems != NULL) { refAttrItems->set = ncname2; refAttrItems->ns = prefix2; attrItems = xsltMergeAttrElemList(style, attrItems, refAttrItems); xsltFreeAttrElem(refAttrItems); } } curval = endval; } xmlFree(value); value = NULL; } /* * Update the value */ /* * TODO: Why is this dummy entry needed.? */ if (attrItems == NULL) attrItems = xsltNewAttrElem(NULL); xmlHashUpdateEntry2(style->attributeSets, ncname, prefix, attrItems, NULL); #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "updated attribute list %s\n", ncname); #endif }
173,298
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: mobility_print(netdissect_options *ndo, const u_char *bp, const u_char *bp2 _U_) { const struct ip6_mobility *mh; const u_char *ep; unsigned mhlen, hlen; uint8_t type; mh = (const struct ip6_mobility *)bp; /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; if (!ND_TTEST(mh->ip6m_len)) { /* * There's not enough captured data to include the * mobility header length. * * Our caller expects us to return the length, however, * so return a value that will run to the end of the * captured data. * * XXX - "ip6_print()" doesn't do anything with the * returned length, however, as it breaks out of the * header-processing loop. */ mhlen = ep - bp; goto trunc; } mhlen = (mh->ip6m_len + 1) << 3; /* XXX ip6m_cksum */ ND_TCHECK(mh->ip6m_type); type = mh->ip6m_type; if (type <= IP6M_MAX && mhlen < ip6m_hdrlen[type]) { ND_PRINT((ndo, "(header length %u is too small for type %u)", mhlen, type)); goto trunc; } ND_PRINT((ndo, "mobility: %s", tok2str(ip6m_str, "type-#%u", type))); switch (type) { case IP6M_BINDING_REQUEST: hlen = IP6M_MINLEN; break; case IP6M_HOME_TEST_INIT: case IP6M_CAREOF_TEST_INIT: hlen = IP6M_MINLEN; if (ndo->ndo_vflag) { ND_TCHECK2(*mh, hlen + 8); ND_PRINT((ndo, " %s Init Cookie=%08x:%08x", type == IP6M_HOME_TEST_INIT ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; break; case IP6M_HOME_TEST: case IP6M_CAREOF_TEST: ND_TCHECK(mh->ip6m_data16[0]); ND_PRINT((ndo, " nonce id=0x%x", EXTRACT_16BITS(&mh->ip6m_data16[0]))); hlen = IP6M_MINLEN; if (ndo->ndo_vflag) { ND_TCHECK2(*mh, hlen + 8); ND_PRINT((ndo, " %s Init Cookie=%08x:%08x", type == IP6M_HOME_TEST ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; if (ndo->ndo_vflag) { ND_TCHECK2(*mh, hlen + 8); ND_PRINT((ndo, " %s Keygen Token=%08x:%08x", type == IP6M_HOME_TEST ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; break; case IP6M_BINDING_UPDATE: ND_TCHECK(mh->ip6m_data16[0]); ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&mh->ip6m_data16[0]))); hlen = IP6M_MINLEN; ND_TCHECK2(*mh, hlen + 1); if (bp[hlen] & 0xf0) ND_PRINT((ndo, " ")); if (bp[hlen] & 0x80) ND_PRINT((ndo, "A")); if (bp[hlen] & 0x40) ND_PRINT((ndo, "H")); if (bp[hlen] & 0x20) ND_PRINT((ndo, "L")); if (bp[hlen] & 0x10) ND_PRINT((ndo, "K")); /* Reserved (4bits) */ hlen += 1; /* Reserved (8bits) */ hlen += 1; ND_TCHECK2(*mh, hlen + 2); /* units of 4 secs */ ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2)); hlen += 2; break; case IP6M_BINDING_ACK: ND_TCHECK(mh->ip6m_data8[0]); ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0])); if (mh->ip6m_data8[1] & 0x80) ND_PRINT((ndo, " K")); /* Reserved (7bits) */ hlen = IP6M_MINLEN; ND_TCHECK2(*mh, hlen + 2); ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&bp[hlen]))); hlen += 2; ND_TCHECK2(*mh, hlen + 2); /* units of 4 secs */ ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2)); hlen += 2; break; case IP6M_BINDING_ERROR: ND_TCHECK(mh->ip6m_data8[0]); ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0])); /* Reserved */ hlen = IP6M_MINLEN; ND_TCHECK2(*mh, hlen + 16); ND_PRINT((ndo, " homeaddr %s", ip6addr_string(ndo, &bp[hlen]))); hlen += 16; break; default: ND_PRINT((ndo, " len=%u", mh->ip6m_len)); return(mhlen); break; } if (ndo->ndo_vflag) if (mobility_opt_print(ndo, &bp[hlen], mhlen - hlen)) goto trunc; return(mhlen); trunc: ND_PRINT((ndo, "%s", tstr)); return(-1); } Commit Message: CVE-2017-13009/IPv6 mobility: Add a bounds check. This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter. Add a test using the capture file supplied by the reporter(s). While we're at it: Add a comment giving the RFC for IPv6 mobility headers. Clean up some bounds checks to make it clearer what they're checking, by matching the subsequent EXTRACT_ calls or memcpy. For the binding update, if none of the flag bits are set, don't check the individual flag bits. CWE ID: CWE-125
mobility_print(netdissect_options *ndo, const u_char *bp, const u_char *bp2 _U_) { const struct ip6_mobility *mh; const u_char *ep; unsigned mhlen, hlen; uint8_t type; mh = (const struct ip6_mobility *)bp; /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; if (!ND_TTEST(mh->ip6m_len)) { /* * There's not enough captured data to include the * mobility header length. * * Our caller expects us to return the length, however, * so return a value that will run to the end of the * captured data. * * XXX - "ip6_print()" doesn't do anything with the * returned length, however, as it breaks out of the * header-processing loop. */ mhlen = ep - bp; goto trunc; } mhlen = (mh->ip6m_len + 1) << 3; /* XXX ip6m_cksum */ ND_TCHECK(mh->ip6m_type); type = mh->ip6m_type; if (type <= IP6M_MAX && mhlen < ip6m_hdrlen[type]) { ND_PRINT((ndo, "(header length %u is too small for type %u)", mhlen, type)); goto trunc; } ND_PRINT((ndo, "mobility: %s", tok2str(ip6m_str, "type-#%u", type))); switch (type) { case IP6M_BINDING_REQUEST: hlen = IP6M_MINLEN; break; case IP6M_HOME_TEST_INIT: case IP6M_CAREOF_TEST_INIT: hlen = IP6M_MINLEN; if (ndo->ndo_vflag) { ND_TCHECK_32BITS(&bp[hlen + 4]); ND_PRINT((ndo, " %s Init Cookie=%08x:%08x", type == IP6M_HOME_TEST_INIT ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; break; case IP6M_HOME_TEST: case IP6M_CAREOF_TEST: ND_TCHECK(mh->ip6m_data16[0]); ND_PRINT((ndo, " nonce id=0x%x", EXTRACT_16BITS(&mh->ip6m_data16[0]))); hlen = IP6M_MINLEN; if (ndo->ndo_vflag) { ND_TCHECK_32BITS(&bp[hlen + 4]); ND_PRINT((ndo, " %s Init Cookie=%08x:%08x", type == IP6M_HOME_TEST ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; if (ndo->ndo_vflag) { ND_TCHECK_32BITS(&bp[hlen + 4]); ND_PRINT((ndo, " %s Keygen Token=%08x:%08x", type == IP6M_HOME_TEST ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; break; case IP6M_BINDING_UPDATE: ND_TCHECK(mh->ip6m_data16[0]); ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&mh->ip6m_data16[0]))); hlen = IP6M_MINLEN; ND_TCHECK_16BITS(&bp[hlen]); if (bp[hlen] & 0xf0) { ND_PRINT((ndo, " ")); if (bp[hlen] & 0x80) ND_PRINT((ndo, "A")); if (bp[hlen] & 0x40) ND_PRINT((ndo, "H")); if (bp[hlen] & 0x20) ND_PRINT((ndo, "L")); if (bp[hlen] & 0x10) ND_PRINT((ndo, "K")); } /* Reserved (4bits) */ hlen += 1; /* Reserved (8bits) */ hlen += 1; ND_TCHECK_16BITS(&bp[hlen]); /* units of 4 secs */ ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2)); hlen += 2; break; case IP6M_BINDING_ACK: ND_TCHECK(mh->ip6m_data8[0]); ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0])); ND_TCHECK(mh->ip6m_data8[1]); if (mh->ip6m_data8[1] & 0x80) ND_PRINT((ndo, " K")); /* Reserved (7bits) */ hlen = IP6M_MINLEN; ND_TCHECK_16BITS(&bp[hlen]); ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&bp[hlen]))); hlen += 2; ND_TCHECK_16BITS(&bp[hlen]); /* units of 4 secs */ ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2)); hlen += 2; break; case IP6M_BINDING_ERROR: ND_TCHECK(mh->ip6m_data8[0]); ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0])); /* Reserved */ hlen = IP6M_MINLEN; ND_TCHECK2(bp[hlen], 16); ND_PRINT((ndo, " homeaddr %s", ip6addr_string(ndo, &bp[hlen]))); hlen += 16; break; default: ND_PRINT((ndo, " len=%u", mh->ip6m_len)); return(mhlen); break; } if (ndo->ndo_vflag) if (mobility_opt_print(ndo, &bp[hlen], mhlen - hlen)) goto trunc; return(mhlen); trunc: ND_PRINT((ndo, "%s", tstr)); return(-1); }
167,886
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 ec_mul_consttime(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar, const EC_POINT *point, BN_CTX *ctx) { int i, cardinality_bits, group_top, kbit, pbit, Z_is_one; EC_POINT *s = NULL; BIGNUM *k = NULL; BIGNUM *lambda = NULL; BIGNUM *cardinality = NULL; BN_CTX *new_ctx = NULL; int ret = 0; if (ctx == NULL && (ctx = new_ctx = BN_CTX_secure_new()) == NULL) return 0; BN_CTX_start(ctx); s = EC_POINT_new(group); if (s == NULL) goto err; if (point == NULL) { if (!EC_POINT_copy(s, group->generator)) goto err; } else { if (!EC_POINT_copy(s, point)) goto err; } EC_POINT_BN_set_flags(s, BN_FLG_CONSTTIME); cardinality = BN_CTX_get(ctx); lambda = BN_CTX_get(ctx); k = BN_CTX_get(ctx); if (k == NULL || !BN_mul(cardinality, group->order, group->cofactor, ctx)) goto err; /* * Group cardinalities are often on a word boundary. * So when we pad the scalar, some timing diff might * pop if it needs to be expanded due to carries. * So expand ahead of time. */ cardinality_bits = BN_num_bits(cardinality); group_top = bn_get_top(cardinality); if ((bn_wexpand(k, group_top + 1) == NULL) || (bn_wexpand(lambda, group_top + 1) == NULL)) goto err; if (!BN_copy(k, scalar)) goto err; BN_set_flags(k, BN_FLG_CONSTTIME); if ((BN_num_bits(k) > cardinality_bits) || (BN_is_negative(k))) { /*- * this is an unusual input, and we don't guarantee * constant-timeness */ if (!BN_nnmod(k, k, cardinality, ctx)) goto err; } if (!BN_add(lambda, k, cardinality)) goto err; BN_set_flags(lambda, BN_FLG_CONSTTIME); if (!BN_add(k, lambda, cardinality)) goto err; /* * lambda := scalar + cardinality * k := scalar + 2*cardinality */ kbit = BN_is_bit_set(lambda, cardinality_bits); BN_consttime_swap(kbit, k, lambda, group_top + 1); group_top = bn_get_top(group->field); if ((bn_wexpand(s->X, group_top) == NULL) || (bn_wexpand(s->Y, group_top) == NULL) || (bn_wexpand(s->Z, group_top) == NULL) || (bn_wexpand(r->X, group_top) == NULL) || (bn_wexpand(r->Y, group_top) == NULL) || (bn_wexpand(r->Z, group_top) == NULL)) goto err; /*- * Apply coordinate blinding for EC_POINT. * * The underlying EC_METHOD can optionally implement this function: * ec_point_blind_coordinates() returns 0 in case of errors or 1 on * success or if coordinate blinding is not implemented for this * group. */ if (!ec_point_blind_coordinates(group, s, ctx)) goto err; /* top bit is a 1, in a fixed pos */ if (!EC_POINT_copy(r, s)) goto err; EC_POINT_BN_set_flags(r, BN_FLG_CONSTTIME); if (!EC_POINT_dbl(group, s, s, ctx)) goto err; pbit = 0; #define EC_POINT_CSWAP(c, a, b, w, t) do { \ BN_consttime_swap(c, (a)->X, (b)->X, w); \ BN_consttime_swap(c, (a)->Y, (b)->Y, w); \ BN_consttime_swap(c, (a)->Z, (b)->Z, w); \ t = ((a)->Z_is_one ^ (b)->Z_is_one) & (c); \ (a)->Z_is_one ^= (t); \ (b)->Z_is_one ^= (t); \ } while(0) /*- * The ladder step, with branches, is * * k[i] == 0: S = add(R, S), R = dbl(R) * k[i] == 1: R = add(S, R), S = dbl(S) * * Swapping R, S conditionally on k[i] leaves you with state * * k[i] == 0: T, U = R, S * k[i] == 1: T, U = S, R * * Then perform the ECC ops. * * U = add(T, U) * T = dbl(T) * * Which leaves you with state * * k[i] == 0: U = add(R, S), T = dbl(R) * k[i] == 1: U = add(S, R), T = dbl(S) * * Swapping T, U conditionally on k[i] leaves you with state * * k[i] == 0: R, S = T, U * k[i] == 1: R, S = U, T * * Which leaves you with state * * k[i] == 0: S = add(R, S), R = dbl(R) * k[i] == 1: R = add(S, R), S = dbl(S) * * So we get the same logic, but instead of a branch it's a * conditional swap, followed by ECC ops, then another conditional swap. * * Optimization: The end of iteration i and start of i-1 looks like * * ... * CSWAP(k[i], R, S) * ECC * CSWAP(k[i], R, S) * (next iteration) * CSWAP(k[i-1], R, S) * ECC * CSWAP(k[i-1], R, S) * ... * * So instead of two contiguous swaps, you can merge the condition * bits and do a single swap. * * k[i] k[i-1] Outcome * 0 0 No Swap * 0 1 Swap * 1 0 Swap * 1 1 No Swap * * This is XOR. pbit tracks the previous bit of k. */ for (i = cardinality_bits - 1; i >= 0; i--) { kbit = BN_is_bit_set(k, i) ^ pbit; EC_POINT_CSWAP(kbit, r, s, group_top, Z_is_one); if (!EC_POINT_add(group, s, r, s, ctx)) goto err; if (!EC_POINT_dbl(group, r, r, ctx)) goto err; /* * pbit logic merges this cswap with that of the * next iteration */ pbit ^= kbit; } /* one final cswap to move the right value into r */ EC_POINT_CSWAP(pbit, r, s, group_top, Z_is_one); #undef EC_POINT_CSWAP ret = 1; err: EC_POINT_free(s); BN_CTX_end(ctx); BN_CTX_free(new_ctx); return ret; } Commit Message: CWE ID: CWE-320
static int ec_mul_consttime(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar, const EC_POINT *point, BN_CTX *ctx) { int i, cardinality_bits, group_top, kbit, pbit, Z_is_one; EC_POINT *s = NULL; BIGNUM *k = NULL; BIGNUM *lambda = NULL; BIGNUM *cardinality = NULL; BN_CTX *new_ctx = NULL; int ret = 0; if (ctx == NULL && (ctx = new_ctx = BN_CTX_secure_new()) == NULL) return 0; BN_CTX_start(ctx); s = EC_POINT_new(group); if (s == NULL) goto err; if (point == NULL) { if (!EC_POINT_copy(s, group->generator)) goto err; } else { if (!EC_POINT_copy(s, point)) goto err; } EC_POINT_BN_set_flags(s, BN_FLG_CONSTTIME); cardinality = BN_CTX_get(ctx); lambda = BN_CTX_get(ctx); k = BN_CTX_get(ctx); if (k == NULL || !BN_mul(cardinality, group->order, group->cofactor, ctx)) goto err; /* * Group cardinalities are often on a word boundary. * So when we pad the scalar, some timing diff might * pop if it needs to be expanded due to carries. * So expand ahead of time. */ cardinality_bits = BN_num_bits(cardinality); group_top = bn_get_top(cardinality); if ((bn_wexpand(k, group_top + 2) == NULL) || (bn_wexpand(lambda, group_top + 2) == NULL)) { goto err; if (!BN_copy(k, scalar)) goto err; BN_set_flags(k, BN_FLG_CONSTTIME); if ((BN_num_bits(k) > cardinality_bits) || (BN_is_negative(k))) { /*- * this is an unusual input, and we don't guarantee * constant-timeness */ if (!BN_nnmod(k, k, cardinality, ctx)) goto err; } if (!BN_add(lambda, k, cardinality)) goto err; BN_set_flags(lambda, BN_FLG_CONSTTIME); if (!BN_add(k, lambda, cardinality)) goto err; /* * lambda := scalar + cardinality * k := scalar + 2*cardinality */ kbit = BN_is_bit_set(lambda, cardinality_bits); BN_consttime_swap(kbit, k, lambda, group_top + 2); group_top = bn_get_top(group->field); if ((bn_wexpand(s->X, group_top) == NULL) || (bn_wexpand(s->Y, group_top) == NULL) || (bn_wexpand(s->Z, group_top) == NULL) || (bn_wexpand(r->X, group_top) == NULL) || (bn_wexpand(r->Y, group_top) == NULL) || (bn_wexpand(r->Z, group_top) == NULL)) goto err; /*- * Apply coordinate blinding for EC_POINT. * * The underlying EC_METHOD can optionally implement this function: * ec_point_blind_coordinates() returns 0 in case of errors or 1 on * success or if coordinate blinding is not implemented for this * group. */ if (!ec_point_blind_coordinates(group, s, ctx)) goto err; /* top bit is a 1, in a fixed pos */ if (!EC_POINT_copy(r, s)) goto err; EC_POINT_BN_set_flags(r, BN_FLG_CONSTTIME); if (!EC_POINT_dbl(group, s, s, ctx)) goto err; pbit = 0; #define EC_POINT_CSWAP(c, a, b, w, t) do { \ BN_consttime_swap(c, (a)->X, (b)->X, w); \ BN_consttime_swap(c, (a)->Y, (b)->Y, w); \ BN_consttime_swap(c, (a)->Z, (b)->Z, w); \ t = ((a)->Z_is_one ^ (b)->Z_is_one) & (c); \ (a)->Z_is_one ^= (t); \ (b)->Z_is_one ^= (t); \ } while(0) /*- * The ladder step, with branches, is * * k[i] == 0: S = add(R, S), R = dbl(R) * k[i] == 1: R = add(S, R), S = dbl(S) * * Swapping R, S conditionally on k[i] leaves you with state * * k[i] == 0: T, U = R, S * k[i] == 1: T, U = S, R * * Then perform the ECC ops. * * U = add(T, U) * T = dbl(T) * * Which leaves you with state * * k[i] == 0: U = add(R, S), T = dbl(R) * k[i] == 1: U = add(S, R), T = dbl(S) * * Swapping T, U conditionally on k[i] leaves you with state * * k[i] == 0: R, S = T, U * k[i] == 1: R, S = U, T * * Which leaves you with state * * k[i] == 0: S = add(R, S), R = dbl(R) * k[i] == 1: R = add(S, R), S = dbl(S) * * So we get the same logic, but instead of a branch it's a * conditional swap, followed by ECC ops, then another conditional swap. * * Optimization: The end of iteration i and start of i-1 looks like * * ... * CSWAP(k[i], R, S) * ECC * CSWAP(k[i], R, S) * (next iteration) * CSWAP(k[i-1], R, S) * ECC * CSWAP(k[i-1], R, S) * ... * * So instead of two contiguous swaps, you can merge the condition * bits and do a single swap. * * k[i] k[i-1] Outcome * 0 0 No Swap * 0 1 Swap * 1 0 Swap * 1 1 No Swap * * This is XOR. pbit tracks the previous bit of k. */ for (i = cardinality_bits - 1; i >= 0; i--) { kbit = BN_is_bit_set(k, i) ^ pbit; EC_POINT_CSWAP(kbit, r, s, group_top, Z_is_one); if (!EC_POINT_add(group, s, r, s, ctx)) goto err; if (!EC_POINT_dbl(group, r, r, ctx)) goto err; /* * pbit logic merges this cswap with that of the * next iteration */ pbit ^= kbit; } /* one final cswap to move the right value into r */ EC_POINT_CSWAP(pbit, r, s, group_top, Z_is_one); #undef EC_POINT_CSWAP ret = 1; err: EC_POINT_free(s); BN_CTX_end(ctx); BN_CTX_free(new_ctx); return ret; }
165,329
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: SchedulerObject::setAttribute(std::string key, std::string name, std::string value, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster < 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "SetAttribute: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (isSubmissionChange(name.c_str())) { text = "Changes to submission name not allowed"; return false; } if (isKeyword(name.c_str())) { text = "Attribute name is reserved: " + name; return false; } if (!isValidAttributeName(name,text)) { return false; } if (::SetAttribute(id.cluster, id.proc, name.c_str(), value.c_str())) { text = "Failed to set attribute " + name + " to " + value; return false; } return true; } Commit Message: CWE ID: CWE-20
SchedulerObject::setAttribute(std::string key, std::string name, std::string value, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster <= 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "SetAttribute: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (isSubmissionChange(name.c_str())) { text = "Changes to submission name not allowed"; return false; } if (isKeyword(name.c_str())) { text = "Attribute name is reserved: " + name; return false; } if (!isValidAttributeName(name,text)) { return false; } if (::SetAttribute(id.cluster, id.proc, name.c_str(), value.c_str())) { text = "Failed to set attribute " + name + " to " + value; return false; } return true; }
164,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: fbOver (CARD32 x, CARD32 y) { PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height); CARD32 fbOver (CARD32 x, CARD32 y) { CARD16 a = ~x >> 24; CARD16 t; CARD32 m,n,o,p; m = FbOverU(x,y,0,a,t); n = FbOverU(x,y,8,a,t); o = FbOverU(x,y,16,a,t); p = FbOverU(x,y,24,a,t); return m|n|o|p; } CARD32 fbOver24 (CARD32 x, CARD32 y) { CARD16 a = ~x >> 24; CARD16 t; CARD32 m,n,o; m = FbOverU(x,y,0,a,t); n = FbOverU(x,y,8,a,t); o = FbOverU(x,y,16,a,t); return m|n|o; } CARD32 fbIn (CARD32 x, CARD8 y) { CARD16 a = y; CARD16 t; CARD32 m,n,o,p; m = FbInU(x,0,a,t); n = FbInU(x,8,a,t); o = FbInU(x,16,a,t); p = FbInU(x,24,a,t); return m|n|o|p; } #define genericCombine24(a,b,c,d) (((a)*(c)+(b)*(d))) /* * This macro does src IN mask OVER dst when src and dst are 0888. * If src has alpha, this will not work */ #define inOver0888(alpha, source, destval, dest) { \ CARD32 dstrb=destval&0xFF00FF; CARD32 dstag=(destval>>8)&0xFF00FF; \ CARD32 drb=((source&0xFF00FF)-dstrb)*alpha; CARD32 dag=(((source>>8)&0xFF00FF)-dstag)*alpha; \ WRITE(dest, ((((drb>>8) + dstrb) & 0x00FF00FF) | ((((dag>>8) + dstag) << 8) & 0xFF00FF00))); \ } /* * This macro does src IN mask OVER dst when src and dst are 0565 and * mask is a 5-bit alpha value. Again, if src has alpha, this will not * work. */ #define inOver0565(alpha, source, destval, dest) { \ CARD16 dstrb = destval & 0xf81f; CARD16 dstg = destval & 0x7e0; \ CARD32 drb = ((source&0xf81f)-dstrb)*alpha; CARD32 dg=((source & 0x7e0)-dstg)*alpha; \ WRITE(dest, ((((drb>>5) + dstrb)&0xf81f) | (((dg>>5) + dstg) & 0x7e0))); \ } #define inOver2x0565(alpha, source, destval, dest) { \ CARD32 dstrb = destval & 0x07e0f81f; CARD32 dstg = (destval & 0xf81f07e0)>>5; \ CARD32 drb = ((source&0x07e0f81f)-dstrb)*alpha; CARD32 dg=(((source & 0xf81f07e0)>>5)-dstg)*alpha; \ WRITE(dest, ((((drb>>5) + dstrb)&0x07e0f81f) | ((((dg>>5) + dstg)<<5) & 0xf81f07e0))); \ } #if IMAGE_BYTE_ORDER == LSBFirst #define setupPackedReader(count,temp,where,workingWhere,workingVal) count=(long)where; \ temp=count&3; \ where-=temp; \ workingWhere=(CARD32 *)where; \ workingVal=READ(workingWhere++); \ count=4-temp; \ workingVal>>=(8*temp) #define readPacked(where,x,y,z) {if(!(x)) { (x)=4; y = READ(z++); } where=(y)&0xff; (y)>>=8; (x)--;} #define readPackedSource(where) readPacked(where,ws,workingSource,wsrc) #define readPackedDest(where) readPacked(where,wd,workingiDest,widst) #define writePacked(what) workingoDest>>=8; workingoDest|=(what<<24); ww--; if(!ww) { ww=4; WRITE (wodst++, workingoDest); } #else #warning "I havn't tested fbCompositeTrans_0888xnx0888() on big endian yet!" #define setupPackedReader(count,temp,where,workingWhere,workingVal) count=(long)where; \ temp=count&3; \ where-=temp; \ workingWhere=(CARD32 *)where; \ workingVal=READ(workingWhere++); \ count=4-temp; \ workingVal<<=(8*temp) #define readPacked(where,x,y,z) {if(!(x)) { (x)=4; y = READ(z++); } where=(y)>>24; (y)<<=8; (x)--;} #define readPackedSource(where) readPacked(where,ws,workingSource,wsrc) #define readPackedDest(where) readPacked(where,wd,workingiDest,widst) #define writePacked(what) workingoDest<<=8; workingoDest|=what; ww--; if(!ww) { ww=4; WRITE(wodst++, workingoDest); } #endif /* * Naming convention: * * opSRCxMASKxDST */ void fbCompositeSolidMask_nx8x8888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD32 *dstLine, *dst, d, dstMask; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w; fbComposeGetSolid(pSrc, src, pDst->format); dstMask = FbFullMask (pDst->pDrawable->depth); srca = src >> 24; if (src == 0) return; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { m = READ(mask++); if (m == 0xff) { if (srca == 0xff) WRITE(dst, src & dstMask); else WRITE(dst, fbOver (src, READ(dst)) & dstMask); } else if (m) { d = fbIn (src, m); WRITE(dst, fbOver (d, READ(dst)) & dstMask); } dst++; } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSolidMask_nx8888x8888C (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD32 *dstLine, *dst, d, dstMask; CARD32 *maskLine, *mask, ma; FbStride dstStride, maskStride; CARD16 w; CARD32 m, n, o, p; fbComposeGetSolid(pSrc, src, pDst->format); dstMask = FbFullMask (pDst->pDrawable->depth); srca = src >> 24; if (src == 0) return; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { ma = READ(mask++); if (ma == 0xffffffff) { if (srca == 0xff) WRITE(dst, src & dstMask); else WRITE(dst, fbOver (src, READ(dst)) & dstMask); } else if (ma) { d = READ(dst); #define FbInOverC(src,srca,msk,dst,i,result) { \ CARD16 __a = FbGet8(msk,i); \ CARD32 __t, __ta; \ CARD32 __i; \ __t = FbIntMult (FbGet8(src,i), __a,__i); \ __ta = (CARD8) ~FbIntMult (srca, __a,__i); \ __t = __t + FbIntMult(FbGet8(dst,i),__ta,__i); \ __t = (CARD32) (CARD8) (__t | (-(__t >> 8))); \ result = __t << (i); \ } FbInOverC (src, srca, ma, d, 0, m); FbInOverC (src, srca, ma, d, 8, n); FbInOverC (src, srca, ma, d, 16, o); FbInOverC (src, srca, ma, d, 24, p); WRITE(dst, m|n|o|p); } dst++; } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } #define srcAlphaCombine24(a,b) genericCombine24(a,b,srca,srcia) void fbCompositeSolidMask_nx8x0888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca, srcia; CARD8 *dstLine, *dst, *edst; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w; CARD32 rs,gs,bs,rd,gd,bd; fbComposeGetSolid(pSrc, src, pDst->format); srca = src >> 24; srcia = 255-srca; if (src == 0) return; rs=src&0xff; gs=(src>>8)&0xff; bs=(src>>16)&0xff; fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); while (height--) { /* fixme: cleanup unused */ unsigned long wt, wd; CARD32 workingiDest; CARD32 *widst; edst = dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; #ifndef NO_MASKED_PACKED_READ setupPackedReader(wd,wt,edst,widst,workingiDest); #endif while (w--) { #ifndef NO_MASKED_PACKED_READ readPackedDest(rd); readPackedDest(gd); readPackedDest(bd); #else rd = READ(edst++); gd = READ(edst++); bd = READ(edst++); #endif m = READ(mask++); if (m == 0xff) { if (srca == 0xff) { WRITE(dst++, rs); WRITE(dst++, gs); WRITE(dst++, bs); } else { WRITE(dst++, (srcAlphaCombine24(rs, rd)>>8)); WRITE(dst++, (srcAlphaCombine24(gs, gd)>>8)); WRITE(dst++, (srcAlphaCombine24(bs, bd)>>8)); } } else if (m) { int na=(srca*(int)m)>>8; int nia=255-na; WRITE(dst++, (genericCombine24(rs, rd, na, nia)>>8)); WRITE(dst++, (genericCombine24(gs, gd, na, nia)>>8)); WRITE(dst++, (genericCombine24(bs, bd, na, nia)>>8)); } else { dst+=3; } } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSolidMask_nx8x0565 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca8, srca5; CARD16 *dstLine, *dst; CARD16 d; CARD32 t; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w,src16; fbComposeGetSolid(pSrc, src, pDst->format); if (src == 0) return; srca8 = (src >> 24); srca5 = (srca8 >> 3); src16 = cvt8888to0565(src); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { m = READ(mask++); if (m == 0) dst++; else if (srca5 == (0xff >> 3)) { if (m == 0xff) WRITE(dst++, src16); else { d = READ(dst); m >>= 3; inOver0565 (m, src16, d, dst++); } } else { d = READ(dst); if (m == 0xff) { t = fbOver24 (src, cvt0565to0888 (d)); } else { t = fbIn (src, m); t = fbOver (t, cvt0565to0888 (d)); } WRITE(dst++, cvt8888to0565 (t)); } } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } static void fbCompositeSolidMask_nx8888x0565 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca8, srca5; CARD16 *dstLine, *dst; CARD16 d; CARD32 *maskLine, *mask; CARD32 t; CARD8 m; FbStride dstStride, maskStride; CARD16 w, src16; fbComposeGetSolid(pSrc, src, pDst->format); if (src == 0) return; srca8 = src >> 24; srca5 = srca8 >> 3; src16 = cvt8888to0565(src); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { m = READ(mask++) >> 24; if (m == 0) dst++; else if (srca5 == (0xff >> 3)) { if (m == 0xff) WRITE(dst++, src16); else { d = READ(dst); m >>= 3; inOver0565 (m, src16, d, dst++); } } else { if (m == 0xff) { d = READ(dst); t = fbOver24 (src, cvt0565to0888 (d)); WRITE(dst++, cvt8888to0565 (t)); } else { d = READ(dst); t = fbIn (src, m); t = fbOver (t, cvt0565to0888 (d)); WRITE(dst++, cvt8888to0565 (t)); } } } } } void fbCompositeSolidMask_nx8888x0565C (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD16 src16; CARD16 *dstLine, *dst; CARD32 d; CARD32 *maskLine, *mask, ma; FbStride dstStride, maskStride; CARD16 w; CARD32 m, n, o; fbComposeGetSolid(pSrc, src, pDst->format); srca = src >> 24; if (src == 0) return; src16 = cvt8888to0565(src); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { ma = READ(mask++); if (ma == 0xffffffff) { if (srca == 0xff) { WRITE(dst, src16); } else { d = READ(dst); d = fbOver24 (src, cvt0565to0888(d)); WRITE(dst, cvt8888to0565(d)); } } else if (ma) { d = READ(dst); d = cvt0565to0888(d); FbInOverC (src, srca, ma, d, 0, m); FbInOverC (src, srca, ma, d, 8, n); FbInOverC (src, srca, ma, d, 16, o); d = m|n|o; WRITE(dst, cvt8888to0565(d)); } dst++; } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSrc_8888x8888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 *dstLine, *dst, dstMask; CARD32 *srcLine, *src, s; FbStride dstStride, srcStride; CARD8 a; CARD16 w; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); dstMask = FbFullMask (pDst->pDrawable->depth); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); a = s >> 24; if (a == 0xff) WRITE(dst, s & dstMask); else if (a) WRITE(dst, fbOver (s, READ(dst)) & dstMask); dst++; } } fbFinishAccess (pSrc->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSrc_8888x0888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst; CARD32 d; CARD32 *srcLine, *src, s; CARD8 a; FbStride dstStride, srcStride; CARD16 w; fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3); fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); a = s >> 24; if (a) { if (a == 0xff) d = s; else d = fbOver24 (s, Fetch24(dst)); Store24(dst,d); } dst += 3; } } fbFinishAccess (pSrc->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSrc_8888x0565 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD16 *dstLine, *dst; CARD32 d; CARD32 *srcLine, *src, s; CARD8 a; FbStride dstStride, srcStride; CARD16 w; fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); a = s >> 24; if (a) { if (a == 0xff) d = s; else { d = READ(dst); d = fbOver24 (s, cvt0565to0888(d)); } WRITE(dst, cvt8888to0565(d)); } dst++; } } fbFinishAccess (pDst->pDrawable); fbFinishAccess (pSrc->pDrawable); } void fbCompositeSrcAdd_8000x8000 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst; CARD8 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; CARD8 s, d; CARD16 t; fbComposeGetStart (pSrc, xSrc, ySrc, CARD8, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); if (s) { if (s != 0xff) { d = READ(dst); t = d + s; s = t | (0 - (t >> 8)); } WRITE(dst, s); } dst++; } } fbFinishAccess (pDst->pDrawable); fbFinishAccess (pSrc->pDrawable); } void fbCompositeSrcAdd_8888x8888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 *dstLine, *dst; CARD32 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; CARD32 s, d; CARD16 t; CARD32 m,n,o,p; fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); if (s) { if (s != 0xffffffff) { d = READ(dst); if (d) { m = FbAdd(s,d,0,t); n = FbAdd(s,d,8,t); o = FbAdd(s,d,16,t); p = FbAdd(s,d,24,t); s = m|n|o|p; } } WRITE(dst, s); } dst++; } } fbFinishAccess (pDst->pDrawable); fbFinishAccess (pSrc->pDrawable); } static void fbCompositeSrcAdd_8888x8x8 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst; CARD8 *maskLine, *mask; FbStride dstStride, maskStride; CARD16 w; CARD32 src; CARD8 sa; fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); fbComposeGetSolid (pSrc, src, pDst->format); sa = (src >> 24); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { CARD16 tmp; CARD16 a; CARD32 m, d; CARD32 r; a = READ(mask++); d = READ(dst); m = FbInU (sa, 0, a, tmp); r = FbAdd (m, d, 0, tmp); WRITE(dst++, r); } } fbFinishAccess(pDst->pDrawable); fbFinishAccess(pMask->pDrawable); } void fbCompositeSrcAdd_1000x1000 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { FbBits *dstBits, *srcBits; FbStride dstStride, srcStride; int dstBpp, srcBpp; int dstXoff, dstYoff; int srcXoff, srcYoff; fbGetDrawable(pSrc->pDrawable, srcBits, srcStride, srcBpp, srcXoff, srcYoff); fbGetDrawable(pDst->pDrawable, dstBits, dstStride, dstBpp, dstXoff, dstYoff); fbBlt (srcBits + srcStride * (ySrc + srcYoff), srcStride, xSrc + srcXoff, dstBits + dstStride * (yDst + dstYoff), dstStride, xDst + dstXoff, width, height, GXor, FB_ALLONES, srcBpp, FALSE, FALSE); fbFinishAccess(pDst->pDrawable); fbFinishAccess(pSrc->pDrawable); } void fbCompositeSolidMask_nx1xn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { FbBits *dstBits; FbStip *maskBits; FbStride dstStride, maskStride; int dstBpp, maskBpp; int dstXoff, dstYoff; int maskXoff, maskYoff; FbBits src; fbComposeGetSolid(pSrc, src, pDst->format); fbGetStipDrawable (pMask->pDrawable, maskBits, maskStride, maskBpp, maskXoff, maskYoff); fbGetDrawable (pDst->pDrawable, dstBits, dstStride, dstBpp, dstXoff, dstYoff); switch (dstBpp) { case 32: break; case 24: break; case 16: src = cvt8888to0565(src); break; } src = fbReplicatePixel (src, dstBpp); fbBltOne (maskBits + maskStride * (yMask + maskYoff), maskStride, xMask + maskXoff, dstBits + dstStride * (yDst + dstYoff), dstStride, (xDst + dstXoff) * dstBpp, dstBpp, width * dstBpp, height, 0x0, src, FB_ALLONES, 0x0); fbFinishAccess (pDst->pDrawable); fbFinishAccess (pMask->pDrawable); } # define mod(a,b) ((b) == 1 ? 0 : (a) >= 0 ? (a) % (b) : (b) - (-a) % (b)) /* * Apply a constant alpha value in an over computation */ static void fbCompositeSrcSrc_nxn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height); static void fbCompositeTrans_0565xnx0565(CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD16 *dstLine, *dst; CARD16 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; FbBits mask; CARD8 maskAlpha; CARD16 s_16, d_16; CARD32 s_32, d_32; fbComposeGetSolid (pMask, mask, pDst->format); maskAlpha = mask >> 27; if (!maskAlpha) return; if (maskAlpha == 0xff) { fbCompositeSrcSrc_nxn (PictOpSrc, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height); return; } fbComposeGetStart (pSrc, xSrc, ySrc, CARD16, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); while (height--) { CARD32 *isrc, *idst; dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; if(((long)src&1)==1) { s_16 = READ(src++); d_16 = READ(dst); inOver0565(maskAlpha, s_16, d_16, dst++); w--; } isrc=(CARD32 *)src; if(((long)dst&1)==0) { idst=(CARD32 *)dst; while (w>1) { s_32 = READ(isrc++); d_32 = READ(idst); inOver2x0565(maskAlpha, s_32, d_32, idst++); w-=2; } dst=(CARD16 *)idst; } else { while (w > 1) { s_32 = READ(isrc++); #if IMAGE_BYTE_ORDER == LSBFirst s_16=s_32&0xffff; #else s_16=s_32>>16; #endif d_16 = READ(dst); inOver0565 (maskAlpha, s_16, d_16, dst++); #if IMAGE_BYTE_ORDER == LSBFirst s_16=s_32>>16; #else s_16=s_32&0xffff; #endif d_16 = READ(dst); inOver0565(maskAlpha, s_16, d_16, dst++); w-=2; } } src=(CARD16 *)isrc; if(w!=0) { s_16 = READ(src); d_16 = READ(dst); inOver0565(maskAlpha, s_16, d_16, dst); } } fbFinishAccess (pSrc->pDrawable); fbFinishAccess (pDst->pDrawable); } /* macros for "i can't believe it's not fast" packed pixel handling */ #define alphamaskCombine24(a,b) genericCombine24(a,b,maskAlpha,maskiAlpha) static void fbCompositeTrans_0888xnx0888(CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst,*idst; CARD8 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; FbBits mask; CARD16 maskAlpha,maskiAlpha; fbComposeGetSolid (pMask, mask, pDst->format); maskAlpha = mask >> 24; maskiAlpha= 255-maskAlpha; if (!maskAlpha) return; /* if (maskAlpha == 0xff) { fbCompositeSrc_0888x0888 (op, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height); return; } */ fbComposeGetStart (pSrc, xSrc, ySrc, CARD8, srcStride, srcLine, 3); fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3); { unsigned long ws,wt; CARD32 workingSource; CARD32 *wsrc, *wdst, *widst; CARD32 rs, rd, nd; CARD8 *isrc; /* are xSrc and xDst at the same alignment? if not, we need to be complicated :) */ /* if(0==0) */ if ((((xSrc * 3) & 3) != ((xDst * 3) & 3)) || ((srcStride & 3) != (dstStride & 3))) { while (height--) { dst = dstLine; dstLine += dstStride; isrc = src = srcLine; srcLine += srcStride; w = width*3; setupPackedReader(ws,wt,isrc,wsrc,workingSource); /* get to word aligned */ switch(~(long)dst&3) { case 1: readPackedSource(rs); /* *dst++=alphamaskCombine24(rs, *dst)>>8; */ rd = READ(dst); /* make gcc happy. hope it doens't cost us too much performance*/ WRITE(dst++, alphamaskCombine24(rs, rd) >> 8); w--; if(w==0) break; case 2: readPackedSource(rs); rd = READ(dst); WRITE(dst++, alphamaskCombine24(rs, rd) >> 8); w--; if(w==0) break; case 3: readPackedSource(rs); rd = READ(dst); WRITE(dst++,alphamaskCombine24(rs, rd) >> 8); w--; if(w==0) break; } wdst=(CARD32 *)dst; while (w>3) { rs=READ(wsrc++); /* FIXME: write a special readPackedWord macro, which knows how to * halfword combine */ #if IMAGE_BYTE_ORDER == LSBFirst rd=READ(wdst); readPackedSource(nd); readPackedSource(rs); nd|=rs<<8; readPackedSource(rs); nd|=rs<<16; readPackedSource(rs); nd|=rs<<24; #else readPackedSource(nd); nd<<=24; readPackedSource(rs); nd|=rs<<16; readPackedSource(rs); nd|=rs<<8; readPackedSource(rs); nd|=rs; #endif inOver0888(maskAlpha, nd, rd, wdst++); w-=4; } src=(CARD8 *)wdst; switch(w) { case 3: readPackedSource(rs); rd=READ(dst); WRITE(dst++,alphamaskCombine24(rs, rd)>>8); case 2: readPackedSource(rs); rd = READ(dst); WRITE(dst++, alphamaskCombine24(rs, rd)>>8); case 1: readPackedSource(rs); rd = READ(dst); WRITE(dst++, alphamaskCombine24(rs, rd)>>8); } } } else { while (height--) { idst=dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width*3; /* get to word aligned */ switch(~(long)src&3) { case 1: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); w--; if(w==0) break; case 2: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); w--; if(w==0) break; case 3: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); w--; if(w==0) break; } wsrc=(CARD32 *)src; widst=(CARD32 *)dst; while(w>3) { rs = READ(wsrc++); rd = READ(widst); inOver0888 (maskAlpha, rs, rd, widst++); w-=4; } src=(CARD8 *)wsrc; dst=(CARD8 *)widst; switch(w) { case 3: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); case 2: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); case 1: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); } } } } } /* * Simple bitblt */ static void fbCompositeSrcSrc_nxn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { FbBits *dst; FbBits *src; FbStride dstStride, srcStride; int srcXoff, srcYoff; int dstXoff, dstYoff; int srcBpp; int dstBpp; Bool reverse = FALSE; Bool upsidedown = FALSE; fbGetDrawable(pSrc->pDrawable,src,srcStride,srcBpp,srcXoff,srcYoff); fbGetDrawable(pDst->pDrawable,dst,dstStride,dstBpp,dstXoff,dstYoff); fbBlt (src + (ySrc + srcYoff) * srcStride, srcStride, (xSrc + srcXoff) * srcBpp, dst + (yDst + dstYoff) * dstStride, dstStride, (xDst + dstXoff) * dstBpp, (width) * dstBpp, (height), GXcopy, FB_ALLONES, dstBpp, reverse, upsidedown); fbFinishAccess(pSrc->pDrawable); fbFinishAccess(pDst->pDrawable); } /* * Solid fill void fbCompositeSolidSrc_nxn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { } */ #define SCANLINE_BUFFER_LENGTH 2048 static void fbCompositeRectWrapper (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 _scanline_buffer[SCANLINE_BUFFER_LENGTH * 3]; CARD32 *scanline_buffer = _scanline_buffer; FbComposeData data; data.op = op; data.src = pSrc; data.mask = pMask; data.dest = pDst; data.xSrc = xSrc; data.ySrc = ySrc; data.xMask = xMask; } void fbComposite (CARD8 op, PicturePtr pSrc, PicturePtr pMask, case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8x8888mmx; else CARD16 width, CARD16 height) { RegionRec region; int n; BoxPtr pbox; CompositeFunc func = NULL; Bool srcRepeat = pSrc->pDrawable && pSrc->repeatType == RepeatNormal; Bool maskRepeat = FALSE; Bool srcTransform = pSrc->transform != 0; break; Bool srcAlphaMap = pSrc->alphaMap != 0; Bool maskAlphaMap = FALSE; Bool dstAlphaMap = pDst->alphaMap != 0; int x_msk, y_msk, x_src, y_src, x_dst, y_dst; int w, h, w_this, h_this; #ifdef USE_MMX static Bool mmx_setup = FALSE; func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif } #endif xDst += pDst->pDrawable->x; yDst += pDst->pDrawable->y; if (pSrc->pDrawable) { xSrc += pSrc->pDrawable->x; ySrc += pSrc->pDrawable->y; } if (srcRepeat && srcTransform && pSrc->pDrawable->width == 1 && pSrc->pDrawable->height == 1) else if (pMask && pMask->pDrawable) { xMask += pMask->pDrawable->x; yMask += pMask->pDrawable->y; maskRepeat = pMask->repeatType == RepeatNormal; if (pMask->filter == PictFilterConvolution) } else { switch (pDst->format) { case PICT_r5g6b5: func = fbCompositeSolidMask_nx8888x0565; break; default: break; } } break; case PICT_a8b8g8r8: if (pMask->componentAlpha) { switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif func = fbCompositeSolidMask_nx8888x8888C; break; case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x0565Cmmx; else #endif func = fbCompositeSolidMask_nx8888x0565C; break; default: break; } } else { switch (pDst->format) { case PICT_b5g6r5: func = fbCompositeSolidMask_nx8888x0565; break; default: break; } } break; case PICT_a1: switch (pDst->format) { case PICT_r5g6b5: case PICT_b5g6r5: case PICT_r8g8b8: case PICT_b8g8r8: case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: { FbBits src; fbComposeGetSolid(pSrc, src, pDst->format); if ((src & 0xff000000) == 0xff000000) func = fbCompositeSolidMask_nx1xn; break; } default: break; } break; default: break; } Commit Message: CWE ID: CWE-189
fbOver (CARD32 x, CARD32 y) { PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height); CARD32 fbOver (CARD32 x, CARD32 y) { CARD16 a = ~x >> 24; CARD16 t; CARD32 m,n,o,p; m = FbOverU(x,y,0,a,t); n = FbOverU(x,y,8,a,t); o = FbOverU(x,y,16,a,t); p = FbOverU(x,y,24,a,t); return m|n|o|p; } CARD32 fbOver24 (CARD32 x, CARD32 y) { CARD16 a = ~x >> 24; CARD16 t; CARD32 m,n,o; m = FbOverU(x,y,0,a,t); n = FbOverU(x,y,8,a,t); o = FbOverU(x,y,16,a,t); return m|n|o; } CARD32 fbIn (CARD32 x, CARD8 y) { CARD16 a = y; CARD16 t; CARD32 m,n,o,p; m = FbInU(x,0,a,t); n = FbInU(x,8,a,t); o = FbInU(x,16,a,t); p = FbInU(x,24,a,t); return m|n|o|p; } #define genericCombine24(a,b,c,d) (((a)*(c)+(b)*(d))) /* * This macro does src IN mask OVER dst when src and dst are 0888. * If src has alpha, this will not work */ #define inOver0888(alpha, source, destval, dest) { \ CARD32 dstrb=destval&0xFF00FF; CARD32 dstag=(destval>>8)&0xFF00FF; \ CARD32 drb=((source&0xFF00FF)-dstrb)*alpha; CARD32 dag=(((source>>8)&0xFF00FF)-dstag)*alpha; \ WRITE(dest, ((((drb>>8) + dstrb) & 0x00FF00FF) | ((((dag>>8) + dstag) << 8) & 0xFF00FF00))); \ } /* * This macro does src IN mask OVER dst when src and dst are 0565 and * mask is a 5-bit alpha value. Again, if src has alpha, this will not * work. */ #define inOver0565(alpha, source, destval, dest) { \ CARD16 dstrb = destval & 0xf81f; CARD16 dstg = destval & 0x7e0; \ CARD32 drb = ((source&0xf81f)-dstrb)*alpha; CARD32 dg=((source & 0x7e0)-dstg)*alpha; \ WRITE(dest, ((((drb>>5) + dstrb)&0xf81f) | (((dg>>5) + dstg) & 0x7e0))); \ } #define inOver2x0565(alpha, source, destval, dest) { \ CARD32 dstrb = destval & 0x07e0f81f; CARD32 dstg = (destval & 0xf81f07e0)>>5; \ CARD32 drb = ((source&0x07e0f81f)-dstrb)*alpha; CARD32 dg=(((source & 0xf81f07e0)>>5)-dstg)*alpha; \ WRITE(dest, ((((drb>>5) + dstrb)&0x07e0f81f) | ((((dg>>5) + dstg)<<5) & 0xf81f07e0))); \ } #if IMAGE_BYTE_ORDER == LSBFirst #define setupPackedReader(count,temp,where,workingWhere,workingVal) count=(long)where; \ temp=count&3; \ where-=temp; \ workingWhere=(CARD32 *)where; \ workingVal=READ(workingWhere++); \ count=4-temp; \ workingVal>>=(8*temp) #define readPacked(where,x,y,z) {if(!(x)) { (x)=4; y = READ(z++); } where=(y)&0xff; (y)>>=8; (x)--;} #define readPackedSource(where) readPacked(where,ws,workingSource,wsrc) #define readPackedDest(where) readPacked(where,wd,workingiDest,widst) #define writePacked(what) workingoDest>>=8; workingoDest|=(what<<24); ww--; if(!ww) { ww=4; WRITE (wodst++, workingoDest); } #else #warning "I havn't tested fbCompositeTrans_0888xnx0888() on big endian yet!" #define setupPackedReader(count,temp,where,workingWhere,workingVal) count=(long)where; \ temp=count&3; \ where-=temp; \ workingWhere=(CARD32 *)where; \ workingVal=READ(workingWhere++); \ count=4-temp; \ workingVal<<=(8*temp) #define readPacked(where,x,y,z) {if(!(x)) { (x)=4; y = READ(z++); } where=(y)>>24; (y)<<=8; (x)--;} #define readPackedSource(where) readPacked(where,ws,workingSource,wsrc) #define readPackedDest(where) readPacked(where,wd,workingiDest,widst) #define writePacked(what) workingoDest<<=8; workingoDest|=what; ww--; if(!ww) { ww=4; WRITE(wodst++, workingoDest); } #endif /* * Naming convention: * * opSRCxMASKxDST */ void fbCompositeSolidMask_nx8x8888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD32 *dstLine, *dst, d, dstMask; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w; fbComposeGetSolid(pSrc, src, pDst->format); dstMask = FbFullMask (pDst->pDrawable->depth); srca = src >> 24; if (src == 0) return; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { m = READ(mask++); if (m == 0xff) { if (srca == 0xff) WRITE(dst, src & dstMask); else WRITE(dst, fbOver (src, READ(dst)) & dstMask); } else if (m) { d = fbIn (src, m); WRITE(dst, fbOver (d, READ(dst)) & dstMask); } dst++; } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSolidMask_nx8888x8888C (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD32 *dstLine, *dst, d, dstMask; CARD32 *maskLine, *mask, ma; FbStride dstStride, maskStride; CARD16 w; CARD32 m, n, o, p; fbComposeGetSolid(pSrc, src, pDst->format); dstMask = FbFullMask (pDst->pDrawable->depth); srca = src >> 24; if (src == 0) return; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { ma = READ(mask++); if (ma == 0xffffffff) { if (srca == 0xff) WRITE(dst, src & dstMask); else WRITE(dst, fbOver (src, READ(dst)) & dstMask); } else if (ma) { d = READ(dst); #define FbInOverC(src,srca,msk,dst,i,result) { \ CARD16 __a = FbGet8(msk,i); \ CARD32 __t, __ta; \ CARD32 __i; \ __t = FbIntMult (FbGet8(src,i), __a,__i); \ __ta = (CARD8) ~FbIntMult (srca, __a,__i); \ __t = __t + FbIntMult(FbGet8(dst,i),__ta,__i); \ __t = (CARD32) (CARD8) (__t | (-(__t >> 8))); \ result = __t << (i); \ } FbInOverC (src, srca, ma, d, 0, m); FbInOverC (src, srca, ma, d, 8, n); FbInOverC (src, srca, ma, d, 16, o); FbInOverC (src, srca, ma, d, 24, p); WRITE(dst, m|n|o|p); } dst++; } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } #define srcAlphaCombine24(a,b) genericCombine24(a,b,srca,srcia) void fbCompositeSolidMask_nx8x0888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca, srcia; CARD8 *dstLine, *dst, *edst; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w; CARD32 rs,gs,bs,rd,gd,bd; fbComposeGetSolid(pSrc, src, pDst->format); srca = src >> 24; srcia = 255-srca; if (src == 0) return; rs=src&0xff; gs=(src>>8)&0xff; bs=(src>>16)&0xff; fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); while (height--) { /* fixme: cleanup unused */ unsigned long wt, wd; CARD32 workingiDest; CARD32 *widst; edst = dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; #ifndef NO_MASKED_PACKED_READ setupPackedReader(wd,wt,edst,widst,workingiDest); #endif while (w--) { #ifndef NO_MASKED_PACKED_READ readPackedDest(rd); readPackedDest(gd); readPackedDest(bd); #else rd = READ(edst++); gd = READ(edst++); bd = READ(edst++); #endif m = READ(mask++); if (m == 0xff) { if (srca == 0xff) { WRITE(dst++, rs); WRITE(dst++, gs); WRITE(dst++, bs); } else { WRITE(dst++, (srcAlphaCombine24(rs, rd)>>8)); WRITE(dst++, (srcAlphaCombine24(gs, gd)>>8)); WRITE(dst++, (srcAlphaCombine24(bs, bd)>>8)); } } else if (m) { int na=(srca*(int)m)>>8; int nia=255-na; WRITE(dst++, (genericCombine24(rs, rd, na, nia)>>8)); WRITE(dst++, (genericCombine24(gs, gd, na, nia)>>8)); WRITE(dst++, (genericCombine24(bs, bd, na, nia)>>8)); } else { dst+=3; } } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSolidMask_nx8x0565 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca8, srca5; CARD16 *dstLine, *dst; CARD16 d; CARD32 t; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w,src16; fbComposeGetSolid(pSrc, src, pDst->format); if (src == 0) return; srca8 = (src >> 24); srca5 = (srca8 >> 3); src16 = cvt8888to0565(src); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { m = READ(mask++); if (m == 0) dst++; else if (srca5 == (0xff >> 3)) { if (m == 0xff) WRITE(dst++, src16); else { d = READ(dst); m >>= 3; inOver0565 (m, src16, d, dst++); } } else { d = READ(dst); if (m == 0xff) { t = fbOver24 (src, cvt0565to0888 (d)); } else { t = fbIn (src, m); t = fbOver (t, cvt0565to0888 (d)); } WRITE(dst++, cvt8888to0565 (t)); } } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } static void fbCompositeSolidMask_nx8888x0565 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca8, srca5; CARD16 *dstLine, *dst; CARD16 d; CARD32 *maskLine, *mask; CARD32 t; CARD8 m; FbStride dstStride, maskStride; CARD16 w, src16; fbComposeGetSolid(pSrc, src, pDst->format); if (src == 0) return; srca8 = src >> 24; srca5 = srca8 >> 3; src16 = cvt8888to0565(src); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { m = READ(mask++) >> 24; if (m == 0) dst++; else if (srca5 == (0xff >> 3)) { if (m == 0xff) WRITE(dst++, src16); else { d = READ(dst); m >>= 3; inOver0565 (m, src16, d, dst++); } } else { if (m == 0xff) { d = READ(dst); t = fbOver24 (src, cvt0565to0888 (d)); WRITE(dst++, cvt8888to0565 (t)); } else { d = READ(dst); t = fbIn (src, m); t = fbOver (t, cvt0565to0888 (d)); WRITE(dst++, cvt8888to0565 (t)); } } } } } void fbCompositeSolidMask_nx8888x0565C (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD16 src16; CARD16 *dstLine, *dst; CARD32 d; CARD32 *maskLine, *mask, ma; FbStride dstStride, maskStride; CARD16 w; CARD32 m, n, o; fbComposeGetSolid(pSrc, src, pDst->format); srca = src >> 24; if (src == 0) return; src16 = cvt8888to0565(src); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { ma = READ(mask++); if (ma == 0xffffffff) { if (srca == 0xff) { WRITE(dst, src16); } else { d = READ(dst); d = fbOver24 (src, cvt0565to0888(d)); WRITE(dst, cvt8888to0565(d)); } } else if (ma) { d = READ(dst); d = cvt0565to0888(d); FbInOverC (src, srca, ma, d, 0, m); FbInOverC (src, srca, ma, d, 8, n); FbInOverC (src, srca, ma, d, 16, o); d = m|n|o; WRITE(dst, cvt8888to0565(d)); } dst++; } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSrc_8888x8888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 *dstLine, *dst, dstMask; CARD32 *srcLine, *src, s; FbStride dstStride, srcStride; CARD8 a; CARD16 w; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); dstMask = FbFullMask (pDst->pDrawable->depth); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); a = s >> 24; if (a == 0xff) WRITE(dst, s & dstMask); else if (a) WRITE(dst, fbOver (s, READ(dst)) & dstMask); dst++; } } fbFinishAccess (pSrc->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSrc_8888x0888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst; CARD32 d; CARD32 *srcLine, *src, s; CARD8 a; FbStride dstStride, srcStride; CARD16 w; fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3); fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); a = s >> 24; if (a) { if (a == 0xff) d = s; else d = fbOver24 (s, Fetch24(dst)); Store24(dst,d); } dst += 3; } } fbFinishAccess (pSrc->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSrc_8888x0565 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD16 *dstLine, *dst; CARD32 d; CARD32 *srcLine, *src, s; CARD8 a; FbStride dstStride, srcStride; CARD16 w; fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); a = s >> 24; if (a) { if (a == 0xff) d = s; else { d = READ(dst); d = fbOver24 (s, cvt0565to0888(d)); } WRITE(dst, cvt8888to0565(d)); } dst++; } } fbFinishAccess (pDst->pDrawable); fbFinishAccess (pSrc->pDrawable); } void fbCompositeSrcAdd_8000x8000 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst; CARD8 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; CARD8 s, d; CARD16 t; fbComposeGetStart (pSrc, xSrc, ySrc, CARD8, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); if (s) { if (s != 0xff) { d = READ(dst); t = d + s; s = t | (0 - (t >> 8)); } WRITE(dst, s); } dst++; } } fbFinishAccess (pDst->pDrawable); fbFinishAccess (pSrc->pDrawable); } void fbCompositeSrcAdd_8888x8888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 *dstLine, *dst; CARD32 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; CARD32 s, d; CARD16 t; CARD32 m,n,o,p; fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); if (s) { if (s != 0xffffffff) { d = READ(dst); if (d) { m = FbAdd(s,d,0,t); n = FbAdd(s,d,8,t); o = FbAdd(s,d,16,t); p = FbAdd(s,d,24,t); s = m|n|o|p; } } WRITE(dst, s); } dst++; } } fbFinishAccess (pDst->pDrawable); fbFinishAccess (pSrc->pDrawable); } static void fbCompositeSrcAdd_8888x8x8 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst; CARD8 *maskLine, *mask; FbStride dstStride, maskStride; CARD16 w; CARD32 src; CARD8 sa; fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); fbComposeGetSolid (pSrc, src, pDst->format); sa = (src >> 24); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { CARD16 tmp; CARD16 a; CARD32 m, d; CARD32 r; a = READ(mask++); d = READ(dst); m = FbInU (sa, 0, a, tmp); r = FbAdd (m, d, 0, tmp); WRITE(dst++, r); } } fbFinishAccess(pDst->pDrawable); fbFinishAccess(pMask->pDrawable); } void fbCompositeSrcAdd_1000x1000 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { FbBits *dstBits, *srcBits; FbStride dstStride, srcStride; int dstBpp, srcBpp; int dstXoff, dstYoff; int srcXoff, srcYoff; fbGetDrawable(pSrc->pDrawable, srcBits, srcStride, srcBpp, srcXoff, srcYoff); fbGetDrawable(pDst->pDrawable, dstBits, dstStride, dstBpp, dstXoff, dstYoff); fbBlt (srcBits + srcStride * (ySrc + srcYoff), srcStride, xSrc + srcXoff, dstBits + dstStride * (yDst + dstYoff), dstStride, xDst + dstXoff, width, height, GXor, FB_ALLONES, srcBpp, FALSE, FALSE); fbFinishAccess(pDst->pDrawable); fbFinishAccess(pSrc->pDrawable); } void fbCompositeSolidMask_nx1xn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { FbBits *dstBits; FbStip *maskBits; FbStride dstStride, maskStride; int dstBpp, maskBpp; int dstXoff, dstYoff; int maskXoff, maskYoff; FbBits src; fbComposeGetSolid(pSrc, src, pDst->format); fbGetStipDrawable (pMask->pDrawable, maskBits, maskStride, maskBpp, maskXoff, maskYoff); fbGetDrawable (pDst->pDrawable, dstBits, dstStride, dstBpp, dstXoff, dstYoff); switch (dstBpp) { case 32: break; case 24: break; case 16: src = cvt8888to0565(src); break; } src = fbReplicatePixel (src, dstBpp); fbBltOne (maskBits + maskStride * (yMask + maskYoff), maskStride, xMask + maskXoff, dstBits + dstStride * (yDst + dstYoff), dstStride, (xDst + dstXoff) * dstBpp, dstBpp, width * dstBpp, height, 0x0, src, FB_ALLONES, 0x0); fbFinishAccess (pDst->pDrawable); fbFinishAccess (pMask->pDrawable); } # define mod(a,b) ((b) == 1 ? 0 : (a) >= 0 ? (a) % (b) : (b) - (-a) % (b)) /* * Apply a constant alpha value in an over computation */ static void fbCompositeSrcSrc_nxn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height); static void fbCompositeTrans_0565xnx0565(CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD16 *dstLine, *dst; CARD16 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; FbBits mask; CARD8 maskAlpha; CARD16 s_16, d_16; CARD32 s_32, d_32; fbComposeGetSolid (pMask, mask, pDst->format); maskAlpha = mask >> 27; if (!maskAlpha) return; if (maskAlpha == 0xff) { fbCompositeSrcSrc_nxn (PictOpSrc, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height); return; } fbComposeGetStart (pSrc, xSrc, ySrc, CARD16, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); while (height--) { CARD32 *isrc, *idst; dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; if(((long)src&1)==1) { s_16 = READ(src++); d_16 = READ(dst); inOver0565(maskAlpha, s_16, d_16, dst++); w--; } isrc=(CARD32 *)src; if(((long)dst&1)==0) { idst=(CARD32 *)dst; while (w>1) { s_32 = READ(isrc++); d_32 = READ(idst); inOver2x0565(maskAlpha, s_32, d_32, idst++); w-=2; } dst=(CARD16 *)idst; } else { while (w > 1) { s_32 = READ(isrc++); #if IMAGE_BYTE_ORDER == LSBFirst s_16=s_32&0xffff; #else s_16=s_32>>16; #endif d_16 = READ(dst); inOver0565 (maskAlpha, s_16, d_16, dst++); #if IMAGE_BYTE_ORDER == LSBFirst s_16=s_32>>16; #else s_16=s_32&0xffff; #endif d_16 = READ(dst); inOver0565(maskAlpha, s_16, d_16, dst++); w-=2; } } src=(CARD16 *)isrc; if(w!=0) { s_16 = READ(src); d_16 = READ(dst); inOver0565(maskAlpha, s_16, d_16, dst); } } fbFinishAccess (pSrc->pDrawable); fbFinishAccess (pDst->pDrawable); } /* macros for "i can't believe it's not fast" packed pixel handling */ #define alphamaskCombine24(a,b) genericCombine24(a,b,maskAlpha,maskiAlpha) static void fbCompositeTrans_0888xnx0888(CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst,*idst; CARD8 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; FbBits mask; CARD16 maskAlpha,maskiAlpha; fbComposeGetSolid (pMask, mask, pDst->format); maskAlpha = mask >> 24; maskiAlpha= 255-maskAlpha; if (!maskAlpha) return; /* if (maskAlpha == 0xff) { fbCompositeSrc_0888x0888 (op, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height); return; } */ fbComposeGetStart (pSrc, xSrc, ySrc, CARD8, srcStride, srcLine, 3); fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3); { unsigned long ws,wt; CARD32 workingSource; CARD32 *wsrc, *wdst, *widst; CARD32 rs, rd, nd; CARD8 *isrc; /* are xSrc and xDst at the same alignment? if not, we need to be complicated :) */ /* if(0==0) */ if ((((xSrc * 3) & 3) != ((xDst * 3) & 3)) || ((srcStride & 3) != (dstStride & 3))) { while (height--) { dst = dstLine; dstLine += dstStride; isrc = src = srcLine; srcLine += srcStride; w = width*3; setupPackedReader(ws,wt,isrc,wsrc,workingSource); /* get to word aligned */ switch(~(long)dst&3) { case 1: readPackedSource(rs); /* *dst++=alphamaskCombine24(rs, *dst)>>8; */ rd = READ(dst); /* make gcc happy. hope it doens't cost us too much performance*/ WRITE(dst++, alphamaskCombine24(rs, rd) >> 8); w--; if(w==0) break; case 2: readPackedSource(rs); rd = READ(dst); WRITE(dst++, alphamaskCombine24(rs, rd) >> 8); w--; if(w==0) break; case 3: readPackedSource(rs); rd = READ(dst); WRITE(dst++,alphamaskCombine24(rs, rd) >> 8); w--; if(w==0) break; } wdst=(CARD32 *)dst; while (w>3) { rs=READ(wsrc++); /* FIXME: write a special readPackedWord macro, which knows how to * halfword combine */ #if IMAGE_BYTE_ORDER == LSBFirst rd=READ(wdst); readPackedSource(nd); readPackedSource(rs); nd|=rs<<8; readPackedSource(rs); nd|=rs<<16; readPackedSource(rs); nd|=rs<<24; #else readPackedSource(nd); nd<<=24; readPackedSource(rs); nd|=rs<<16; readPackedSource(rs); nd|=rs<<8; readPackedSource(rs); nd|=rs; #endif inOver0888(maskAlpha, nd, rd, wdst++); w-=4; } src=(CARD8 *)wdst; switch(w) { case 3: readPackedSource(rs); rd=READ(dst); WRITE(dst++,alphamaskCombine24(rs, rd)>>8); case 2: readPackedSource(rs); rd = READ(dst); WRITE(dst++, alphamaskCombine24(rs, rd)>>8); case 1: readPackedSource(rs); rd = READ(dst); WRITE(dst++, alphamaskCombine24(rs, rd)>>8); } } } else { while (height--) { idst=dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width*3; /* get to word aligned */ switch(~(long)src&3) { case 1: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); w--; if(w==0) break; case 2: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); w--; if(w==0) break; case 3: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); w--; if(w==0) break; } wsrc=(CARD32 *)src; widst=(CARD32 *)dst; while(w>3) { rs = READ(wsrc++); rd = READ(widst); inOver0888 (maskAlpha, rs, rd, widst++); w-=4; } src=(CARD8 *)wsrc; dst=(CARD8 *)widst; switch(w) { case 3: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); case 2: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); case 1: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); } } } } } /* * Simple bitblt */ static void fbCompositeSrcSrc_nxn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { FbBits *dst; FbBits *src; FbStride dstStride, srcStride; int srcXoff, srcYoff; int dstXoff, dstYoff; int srcBpp; int dstBpp; Bool reverse = FALSE; Bool upsidedown = FALSE; fbGetDrawable(pSrc->pDrawable,src,srcStride,srcBpp,srcXoff,srcYoff); fbGetDrawable(pDst->pDrawable,dst,dstStride,dstBpp,dstXoff,dstYoff); fbBlt (src + (ySrc + srcYoff) * srcStride, srcStride, (xSrc + srcXoff) * srcBpp, dst + (yDst + dstYoff) * dstStride, dstStride, (xDst + dstXoff) * dstBpp, (width) * dstBpp, (height), GXcopy, FB_ALLONES, dstBpp, reverse, upsidedown); fbFinishAccess(pSrc->pDrawable); fbFinishAccess(pDst->pDrawable); } /* * Solid fill void fbCompositeSolidSrc_nxn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { } */ #define SCANLINE_BUFFER_LENGTH 2048 static void fbCompositeRectWrapper (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 _scanline_buffer[SCANLINE_BUFFER_LENGTH * 3]; CARD32 *scanline_buffer = _scanline_buffer; FbComposeData data; data.op = op; data.src = pSrc; data.mask = pMask; data.dest = pDst; data.xSrc = xSrc; data.ySrc = ySrc; data.xMask = xMask; } void fbWalkCompositeRegion (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height, Bool srcRepeat, Bool maskRepeat, CompositeFunc compositeRect) { RegionRec region; int n; BoxPtr pbox; int w, h, w_this, h_this; int x_msk, y_msk, x_src, y_src, x_dst, y_dst; xDst += pDst->pDrawable->x; yDst += pDst->pDrawable->y; if (pSrc->pDrawable) { xSrc += pSrc->pDrawable->x; ySrc += pSrc->pDrawable->y; } if (pMask && pMask->pDrawable) { xMask += pMask->pDrawable->x; yMask += pMask->pDrawable->y; } if (!miComputeCompositeRegion (&region, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height)) return; n = REGION_NUM_RECTS (&region); pbox = REGION_RECTS (&region); while (n--) { h = pbox->y2 - pbox->y1; y_src = pbox->y1 - yDst + ySrc; y_msk = pbox->y1 - yDst + yMask; y_dst = pbox->y1; while (h) { h_this = h; w = pbox->x2 - pbox->x1; x_src = pbox->x1 - xDst + xSrc; x_msk = pbox->x1 - xDst + xMask; x_dst = pbox->x1; if (maskRepeat) { y_msk = mod (y_msk - pMask->pDrawable->y, pMask->pDrawable->height); if (h_this > pMask->pDrawable->height - y_msk) h_this = pMask->pDrawable->height - y_msk; y_msk += pMask->pDrawable->y; } if (srcRepeat) { y_src = mod (y_src - pSrc->pDrawable->y, pSrc->pDrawable->height); if (h_this > pSrc->pDrawable->height - y_src) h_this = pSrc->pDrawable->height - y_src; y_src += pSrc->pDrawable->y; } while (w) { w_this = w; if (maskRepeat) { x_msk = mod (x_msk - pMask->pDrawable->x, pMask->pDrawable->width); if (w_this > pMask->pDrawable->width - x_msk) w_this = pMask->pDrawable->width - x_msk; x_msk += pMask->pDrawable->x; } if (srcRepeat) { x_src = mod (x_src - pSrc->pDrawable->x, pSrc->pDrawable->width); if (w_this > pSrc->pDrawable->width - x_src) w_this = pSrc->pDrawable->width - x_src; x_src += pSrc->pDrawable->x; } (*compositeRect) (op, pSrc, pMask, pDst, x_src, y_src, x_msk, y_msk, x_dst, y_dst, w_this, h_this); w -= w_this; x_src += w_this; x_msk += w_this; x_dst += w_this; } h -= h_this; y_src += h_this; y_msk += h_this; y_dst += h_this; } pbox++; } REGION_UNINIT (pDst->pDrawable->pScreen, &region); } void fbComposite (CARD8 op, PicturePtr pSrc, PicturePtr pMask, case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8x8888mmx; else CARD16 width, CARD16 height) { Bool srcRepeat = pSrc->pDrawable && pSrc->repeatType == RepeatNormal; Bool maskRepeat = FALSE; Bool srcTransform = pSrc->transform != 0; break; Bool srcAlphaMap = pSrc->alphaMap != 0; Bool maskAlphaMap = FALSE; Bool dstAlphaMap = pDst->alphaMap != 0; CompositeFunc func = NULL; #ifdef USE_MMX static Bool mmx_setup = FALSE; func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif } #endif if (srcRepeat && srcTransform && pSrc->pDrawable->width == 1 && pSrc->pDrawable->height == 1) else if (pMask && pMask->pDrawable) { maskRepeat = pMask->repeatType == RepeatNormal; if (pMask->filter == PictFilterConvolution) } else { switch (pDst->format) { case PICT_r5g6b5: func = fbCompositeSolidMask_nx8888x0565; break; default: break; } } break; case PICT_a8b8g8r8: if (pMask->componentAlpha) { switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif func = fbCompositeSolidMask_nx8888x8888C; break; case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x0565Cmmx; else #endif func = fbCompositeSolidMask_nx8888x0565C; break; default: break; } } else { switch (pDst->format) { case PICT_b5g6r5: func = fbCompositeSolidMask_nx8888x0565; break; default: break; } } break; case PICT_a1: switch (pDst->format) { case PICT_r5g6b5: case PICT_b5g6r5: case PICT_r8g8b8: case PICT_b8g8r8: case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: { FbBits src; fbComposeGetSolid(pSrc, src, pDst->format); if ((src & 0xff000000) == 0xff000000) func = fbCompositeSolidMask_nx1xn; break; } default: break; } break; default: break; }
165,129
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 build_ntlmssp_negotiate_blob(unsigned char *pbuffer, struct cifs_ses *ses) { NEGOTIATE_MESSAGE *sec_blob = (NEGOTIATE_MESSAGE *)pbuffer; __u32 flags; memset(pbuffer, 0, sizeof(NEGOTIATE_MESSAGE)); memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8); sec_blob->MessageType = NtLmNegotiate; /* BB is NTLMV2 session security format easier to use here? */ flags = NTLMSSP_NEGOTIATE_56 | NTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE | NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC; if (ses->server->sign) { flags |= NTLMSSP_NEGOTIATE_SIGN; if (!ses->server->session_estab || ses->ntlmssp->sesskey_per_smbsess) flags |= NTLMSSP_NEGOTIATE_KEY_XCH; } sec_blob->NegotiateFlags = cpu_to_le32(flags); sec_blob->WorkstationName.BufferOffset = 0; sec_blob->WorkstationName.Length = 0; sec_blob->WorkstationName.MaximumLength = 0; /* Domain name is sent on the Challenge not Negotiate NTLMSSP request */ sec_blob->DomainName.BufferOffset = 0; sec_blob->DomainName.Length = 0; sec_blob->DomainName.MaximumLength = 0; } Commit Message: CIFS: Enable encryption during session setup phase In order to allow encryption on SMB connection we need to exchange a session key and generate encryption and decryption keys. Signed-off-by: Pavel Shilovsky <[email protected]> CWE ID: CWE-476
void build_ntlmssp_negotiate_blob(unsigned char *pbuffer, struct cifs_ses *ses) { NEGOTIATE_MESSAGE *sec_blob = (NEGOTIATE_MESSAGE *)pbuffer; __u32 flags; memset(pbuffer, 0, sizeof(NEGOTIATE_MESSAGE)); memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8); sec_blob->MessageType = NtLmNegotiate; /* BB is NTLMV2 session security format easier to use here? */ flags = NTLMSSP_NEGOTIATE_56 | NTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE | NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC | NTLMSSP_NEGOTIATE_SEAL; if (ses->server->sign) flags |= NTLMSSP_NEGOTIATE_SIGN; if (!ses->server->session_estab || ses->ntlmssp->sesskey_per_smbsess) flags |= NTLMSSP_NEGOTIATE_KEY_XCH; sec_blob->NegotiateFlags = cpu_to_le32(flags); sec_blob->WorkstationName.BufferOffset = 0; sec_blob->WorkstationName.Length = 0; sec_blob->WorkstationName.MaximumLength = 0; /* Domain name is sent on the Challenge not Negotiate NTLMSSP request */ sec_blob->DomainName.BufferOffset = 0; sec_blob->DomainName.Length = 0; sec_blob->DomainName.MaximumLength = 0; }
169,360
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: testing::AssertionResult ScriptAllowedExclusivelyOnTab( const Extension* extension, const std::set<GURL>& allowed_urls, int tab_id) { std::vector<std::string> errors; for (const GURL& url : urls_) { bool allowed = IsAllowedScript(extension, url, tab_id); if (allowed && !allowed_urls.count(url)) errors.push_back("Script unexpectedly disallowed on " + url.spec()); else if (!allowed && allowed_urls.count(url)) errors.push_back("Script unexpectedly allowed on " + url.spec()); } if (!errors.empty()) return testing::AssertionFailure() << base::JoinString(errors, "\n"); return testing::AssertionSuccess(); } Commit Message: [Extensions] Restrict tabs.captureVisibleTab() Modify the permissions for tabs.captureVisibleTab(). Instead of just checking for <all_urls> and assuming its safe, do the following: - If the page is a "normal" web page (e.g., http/https), allow the capture if the extension has activeTab granted or <all_urls>. - If the page is a file page (file:///), allow the capture if the extension has file access *and* either of the <all_urls> or activeTab permissions. - If the page is a chrome:// page, allow the capture only if the extension has activeTab granted. Bug: 810220 Change-Id: I1e2f71281e2f331d641ba0e435df10d66d721304 Reviewed-on: https://chromium-review.googlesource.com/981195 Commit-Queue: Devlin <[email protected]> Reviewed-by: Karan Bhatia <[email protected]> Cr-Commit-Position: refs/heads/master@{#548891} CWE ID: CWE-20
testing::AssertionResult ScriptAllowedExclusivelyOnTab( const Extension* extension, const std::set<GURL>& allowed_urls, int tab_id) { std::vector<std::string> errors; for (const GURL& url : urls_) { AccessType access = GetExtensionAccess(extension, url, tab_id); AccessType expected_access = allowed_urls.count(url) ? ALLOWED_SCRIPT_ONLY : DISALLOWED; if (access != expected_access) { errors.push_back( base::StringPrintf("Error for url '%s': expected %d, found %d", url.spec().c_str(), expected_access, access)); } } if (!errors.empty()) return testing::AssertionFailure() << base::JoinString(errors, "\n"); return testing::AssertionSuccess(); }
173,233
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: AcpiDsCreateOperands ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *FirstArg) { ACPI_STATUS Status = AE_OK; ACPI_PARSE_OBJECT *Arg; ACPI_PARSE_OBJECT *Arguments[ACPI_OBJ_NUM_OPERANDS]; UINT32 ArgCount = 0; UINT32 Index = WalkState->NumOperands; UINT32 i; ACPI_FUNCTION_TRACE_PTR (DsCreateOperands, FirstArg); /* Get all arguments in the list */ Arg = FirstArg; while (Arg) { if (Index >= ACPI_OBJ_NUM_OPERANDS) { return_ACPI_STATUS (AE_BAD_DATA); } Arguments[Index] = Arg; WalkState->Operands [Index] = NULL; /* Move on to next argument, if any */ Arg = Arg->Common.Next; ArgCount++; Index++; } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "NumOperands %d, ArgCount %d, Index %d\n", WalkState->NumOperands, ArgCount, Index)); /* Create the interpreter arguments, in reverse order */ Index--; for (i = 0; i < ArgCount; i++) { Arg = Arguments[Index]; WalkState->OperandIndex = (UINT8) Index; Status = AcpiDsCreateOperand (WalkState, Arg, Index); if (ACPI_FAILURE (Status)) { goto Cleanup; } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Created Arg #%u (%p) %u args total\n", Index, Arg, ArgCount)); Index--; } return_ACPI_STATUS (Status); Cleanup: /* * We must undo everything done above; meaning that we must * pop everything off of the operand stack and delete those * objects */ AcpiDsObjStackPopAndDelete (ArgCount, WalkState); ACPI_EXCEPTION ((AE_INFO, Status, "While creating Arg %u", Index)); return_ACPI_STATUS (Status); } Commit Message: acpi: acpica: fix acpi operand cache leak in dswstate.c I found an ACPI cache leak in ACPI early termination and boot continuing case. When early termination occurs due to malicious ACPI table, Linux kernel terminates ACPI function and continues to boot process. While kernel terminates ACPI function, kmem_cache_destroy() reports Acpi-Operand cache leak. Boot log of ACPI operand cache leak is as follows: >[ 0.585957] ACPI: Added _OSI(Module Device) >[ 0.587218] ACPI: Added _OSI(Processor Device) >[ 0.588530] ACPI: Added _OSI(3.0 _SCP Extensions) >[ 0.589790] ACPI: Added _OSI(Processor Aggregator Device) >[ 0.591534] ACPI Error: Illegal I/O port address/length above 64K: C806E00000004002/0x2 (20170303/hwvalid-155) >[ 0.594351] ACPI Exception: AE_LIMIT, Unable to initialize fixed events (20170303/evevent-88) >[ 0.597858] ACPI: Unable to start the ACPI Interpreter >[ 0.599162] ACPI Error: Could not remove SCI handler (20170303/evmisc-281) >[ 0.601836] kmem_cache_destroy Acpi-Operand: Slab cache still has objects >[ 0.603556] CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.12.0-rc5 #26 >[ 0.605159] Hardware name: innotek GmbH VirtualBox/VirtualBox, BIOS VirtualBox 12/01/2006 >[ 0.609177] Call Trace: >[ 0.610063] ? dump_stack+0x5c/0x81 >[ 0.611118] ? kmem_cache_destroy+0x1aa/0x1c0 >[ 0.612632] ? acpi_sleep_proc_init+0x27/0x27 >[ 0.613906] ? acpi_os_delete_cache+0xa/0x10 >[ 0.617986] ? acpi_ut_delete_caches+0x3f/0x7b >[ 0.619293] ? acpi_terminate+0xa/0x14 >[ 0.620394] ? acpi_init+0x2af/0x34f >[ 0.621616] ? __class_create+0x4c/0x80 >[ 0.623412] ? video_setup+0x7f/0x7f >[ 0.624585] ? acpi_sleep_proc_init+0x27/0x27 >[ 0.625861] ? do_one_initcall+0x4e/0x1a0 >[ 0.627513] ? kernel_init_freeable+0x19e/0x21f >[ 0.628972] ? rest_init+0x80/0x80 >[ 0.630043] ? kernel_init+0xa/0x100 >[ 0.631084] ? ret_from_fork+0x25/0x30 >[ 0.633343] vgaarb: loaded >[ 0.635036] EDAC MC: Ver: 3.0.0 >[ 0.638601] PCI: Probing PCI hardware >[ 0.639833] PCI host bridge to bus 0000:00 >[ 0.641031] pci_bus 0000:00: root bus resource [io 0x0000-0xffff] > ... Continue to boot and log is omitted ... I analyzed this memory leak in detail and found acpi_ds_obj_stack_pop_and_ delete() function miscalculated the top of the stack. acpi_ds_obj_stack_push() function uses walk_state->operand_index for start position of the top, but acpi_ds_obj_stack_pop_and_delete() function considers index 0 for it. Therefore, this causes acpi operand memory leak. This cache leak causes a security threat because an old kernel (<= 4.9) shows memory locations of kernel functions in stack dump. Some malicious users could use this information to neutralize kernel ASLR. I made a patch to fix ACPI operand cache leak. Signed-off-by: Seunghun Han <[email protected]> CWE ID: CWE-200
AcpiDsCreateOperands ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *FirstArg) { ACPI_STATUS Status = AE_OK; ACPI_PARSE_OBJECT *Arg; ACPI_PARSE_OBJECT *Arguments[ACPI_OBJ_NUM_OPERANDS]; UINT32 ArgCount = 0; UINT32 Index = WalkState->NumOperands; UINT32 PrevNumOperands = WalkState->NumOperands; UINT32 NewNumOperands; UINT32 i; ACPI_FUNCTION_TRACE_PTR (DsCreateOperands, FirstArg); /* Get all arguments in the list */ Arg = FirstArg; while (Arg) { if (Index >= ACPI_OBJ_NUM_OPERANDS) { return_ACPI_STATUS (AE_BAD_DATA); } Arguments[Index] = Arg; WalkState->Operands [Index] = NULL; /* Move on to next argument, if any */ Arg = Arg->Common.Next; ArgCount++; Index++; } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "NumOperands %d, ArgCount %d, Index %d\n", WalkState->NumOperands, ArgCount, Index)); /* Create the interpreter arguments, in reverse order */ NewNumOperands = Index; Index--; for (i = 0; i < ArgCount; i++) { Arg = Arguments[Index]; WalkState->OperandIndex = (UINT8) Index; Status = AcpiDsCreateOperand (WalkState, Arg, Index); if (ACPI_FAILURE (Status)) { goto Cleanup; } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Created Arg #%u (%p) %u args total\n", Index, Arg, ArgCount)); Index--; } return_ACPI_STATUS (Status); Cleanup: /* * We must undo everything done above; meaning that we must * pop everything off of the operand stack and delete those * objects */ WalkState->NumOperands = i; AcpiDsObjStackPopAndDelete (NewNumOperands, WalkState); /* Restore operand count */ WalkState->NumOperands = PrevNumOperands; ACPI_EXCEPTION ((AE_INFO, Status, "While creating Arg %u", Index)); return_ACPI_STATUS (Status); }
167,788
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 tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr) { struct tun_struct *tun; struct tun_file *tfile = file->private_data; struct net_device *dev; int err; if (tfile->detached) return -EINVAL; dev = __dev_get_by_name(net, ifr->ifr_name); if (dev) { if (ifr->ifr_flags & IFF_TUN_EXCL) return -EBUSY; if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops) tun = netdev_priv(dev); else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops) tun = netdev_priv(dev); else return -EINVAL; if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) != !!(tun->flags & IFF_MULTI_QUEUE)) return -EINVAL; if (tun_not_capable(tun)) return -EPERM; err = security_tun_dev_open(tun->security); if (err < 0) return err; err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER); if (err < 0) return err; if (tun->flags & IFF_MULTI_QUEUE && (tun->numqueues + tun->numdisabled > 1)) { /* One or more queue has already been attached, no need * to initialize the device again. */ return 0; } } else { char *name; unsigned long flags = 0; int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ? MAX_TAP_QUEUES : 1; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EPERM; err = security_tun_dev_create(); if (err < 0) return err; /* Set dev type */ if (ifr->ifr_flags & IFF_TUN) { /* TUN device */ flags |= IFF_TUN; name = "tun%d"; } else if (ifr->ifr_flags & IFF_TAP) { /* TAP device */ flags |= IFF_TAP; name = "tap%d"; } else return -EINVAL; if (*ifr->ifr_name) name = ifr->ifr_name; dev = alloc_netdev_mqs(sizeof(struct tun_struct), name, NET_NAME_UNKNOWN, tun_setup, queues, queues); if (!dev) return -ENOMEM; dev_net_set(dev, net); dev->rtnl_link_ops = &tun_link_ops; dev->ifindex = tfile->ifindex; dev->sysfs_groups[0] = &tun_attr_group; tun = netdev_priv(dev); tun->dev = dev; tun->flags = flags; tun->txflt.count = 0; tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr); tun->align = NET_SKB_PAD; tun->filter_attached = false; tun->sndbuf = tfile->socket.sk->sk_sndbuf; tun->rx_batched = 0; tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats); if (!tun->pcpu_stats) { err = -ENOMEM; goto err_free_dev; } spin_lock_init(&tun->lock); err = security_tun_dev_alloc_security(&tun->security); if (err < 0) goto err_free_stat; tun_net_init(dev); tun_flow_init(tun); dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX; dev->features = dev->hw_features | NETIF_F_LLTX; dev->vlan_features = dev->features & ~(NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX); INIT_LIST_HEAD(&tun->disabled); err = tun_attach(tun, file, false); if (err < 0) goto err_free_flow; err = register_netdevice(tun->dev); if (err < 0) goto err_detach; } netif_carrier_on(tun->dev); tun_debug(KERN_INFO, tun, "tun_set_iff\n"); tun->flags = (tun->flags & ~TUN_FEATURES) | (ifr->ifr_flags & TUN_FEATURES); /* Make sure persistent devices do not get stuck in * xoff state. */ if (netif_running(tun->dev)) netif_tx_wake_all_queues(tun->dev); strcpy(ifr->ifr_name, tun->dev->name); return 0; err_detach: tun_detach_all(dev); /* register_netdevice() already called tun_free_netdev() */ goto err_free_dev; err_free_flow: tun_flow_uninit(tun); security_tun_dev_free_security(tun->security); err_free_stat: free_percpu(tun->pcpu_stats); err_free_dev: free_netdev(dev); return err; } Commit Message: tun: call dev_get_valid_name() before register_netdevice() register_netdevice() could fail early when we have an invalid dev name, in which case ->ndo_uninit() is not called. For tun device, this is a problem because a timer etc. are already initialized and it expects ->ndo_uninit() to clean them up. We could move these initializations into a ->ndo_init() so that register_netdevice() knows better, however this is still complicated due to the logic in tun_detach(). Therefore, I choose to just call dev_get_valid_name() before register_netdevice(), which is quicker and much easier to audit. And for this specific case, it is already enough. Fixes: 96442e42429e ("tuntap: choose the txq based on rxq") Reported-by: Dmitry Alexeev <[email protected]> Cc: Jason Wang <[email protected]> Cc: "Michael S. Tsirkin" <[email protected]> Signed-off-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-476
static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr) { struct tun_struct *tun; struct tun_file *tfile = file->private_data; struct net_device *dev; int err; if (tfile->detached) return -EINVAL; dev = __dev_get_by_name(net, ifr->ifr_name); if (dev) { if (ifr->ifr_flags & IFF_TUN_EXCL) return -EBUSY; if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops) tun = netdev_priv(dev); else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops) tun = netdev_priv(dev); else return -EINVAL; if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) != !!(tun->flags & IFF_MULTI_QUEUE)) return -EINVAL; if (tun_not_capable(tun)) return -EPERM; err = security_tun_dev_open(tun->security); if (err < 0) return err; err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER); if (err < 0) return err; if (tun->flags & IFF_MULTI_QUEUE && (tun->numqueues + tun->numdisabled > 1)) { /* One or more queue has already been attached, no need * to initialize the device again. */ return 0; } } else { char *name; unsigned long flags = 0; int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ? MAX_TAP_QUEUES : 1; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EPERM; err = security_tun_dev_create(); if (err < 0) return err; /* Set dev type */ if (ifr->ifr_flags & IFF_TUN) { /* TUN device */ flags |= IFF_TUN; name = "tun%d"; } else if (ifr->ifr_flags & IFF_TAP) { /* TAP device */ flags |= IFF_TAP; name = "tap%d"; } else return -EINVAL; if (*ifr->ifr_name) name = ifr->ifr_name; dev = alloc_netdev_mqs(sizeof(struct tun_struct), name, NET_NAME_UNKNOWN, tun_setup, queues, queues); if (!dev) return -ENOMEM; err = dev_get_valid_name(net, dev, name); if (err) goto err_free_dev; dev_net_set(dev, net); dev->rtnl_link_ops = &tun_link_ops; dev->ifindex = tfile->ifindex; dev->sysfs_groups[0] = &tun_attr_group; tun = netdev_priv(dev); tun->dev = dev; tun->flags = flags; tun->txflt.count = 0; tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr); tun->align = NET_SKB_PAD; tun->filter_attached = false; tun->sndbuf = tfile->socket.sk->sk_sndbuf; tun->rx_batched = 0; tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats); if (!tun->pcpu_stats) { err = -ENOMEM; goto err_free_dev; } spin_lock_init(&tun->lock); err = security_tun_dev_alloc_security(&tun->security); if (err < 0) goto err_free_stat; tun_net_init(dev); tun_flow_init(tun); dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX; dev->features = dev->hw_features | NETIF_F_LLTX; dev->vlan_features = dev->features & ~(NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX); INIT_LIST_HEAD(&tun->disabled); err = tun_attach(tun, file, false); if (err < 0) goto err_free_flow; err = register_netdevice(tun->dev); if (err < 0) goto err_detach; } netif_carrier_on(tun->dev); tun_debug(KERN_INFO, tun, "tun_set_iff\n"); tun->flags = (tun->flags & ~TUN_FEATURES) | (ifr->ifr_flags & TUN_FEATURES); /* Make sure persistent devices do not get stuck in * xoff state. */ if (netif_running(tun->dev)) netif_tx_wake_all_queues(tun->dev); strcpy(ifr->ifr_name, tun->dev->name); return 0; err_detach: tun_detach_all(dev); /* register_netdevice() already called tun_free_netdev() */ goto err_free_dev; err_free_flow: tun_flow_uninit(tun); security_tun_dev_free_security(tun->security); err_free_stat: free_percpu(tun->pcpu_stats); err_free_dev: free_netdev(dev); return err; }
169,854
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 IndexedDBTransaction::Abort(const IndexedDBDatabaseError& error) { IDB_TRACE1("IndexedDBTransaction::Abort", "txn.id", id()); DCHECK(!processing_event_queue_); if (state_ == FINISHED) return; UMA_HISTOGRAM_ENUMERATION("WebCore.IndexedDB.TransactionAbortReason", ExceptionCodeToUmaEnum(error.code()), UmaIDBExceptionExclusiveMaxValue); timeout_timer_.Stop(); state_ = FINISHED; should_process_queue_ = false; if (backing_store_transaction_begun_) transaction_->Rollback(); while (!abort_task_stack_.empty()) abort_task_stack_.pop().Run(); preemptive_task_queue_.clear(); pending_preemptive_events_ = 0; task_queue_.clear(); CloseOpenCursors(); transaction_->Reset(); database_->transaction_coordinator().DidFinishTransaction(this); #ifndef NDEBUG DCHECK(!database_->transaction_coordinator().IsActive(this)); #endif if (callbacks_.get()) callbacks_->OnAbort(*this, error); database_->TransactionFinished(this, false); connection_->RemoveTransaction(id_); } Commit Message: [IndexedDB] Fixing early destruction of connection during forceclose Patch is as small as possible for merging. Bug: 842990 Change-Id: I9968ffee1bf3279e61e1ec13e4d541f713caf12f Reviewed-on: https://chromium-review.googlesource.com/1062935 Commit-Queue: Daniel Murphy <[email protected]> Commit-Queue: Victor Costan <[email protected]> Reviewed-by: Victor Costan <[email protected]> Cr-Commit-Position: refs/heads/master@{#559383} CWE ID:
void IndexedDBTransaction::Abort(const IndexedDBDatabaseError& error) { IDB_TRACE1("IndexedDBTransaction::Abort", "txn.id", id()); DCHECK(!processing_event_queue_); if (state_ == FINISHED) return; UMA_HISTOGRAM_ENUMERATION("WebCore.IndexedDB.TransactionAbortReason", ExceptionCodeToUmaEnum(error.code()), UmaIDBExceptionExclusiveMaxValue); timeout_timer_.Stop(); state_ = FINISHED; should_process_queue_ = false; if (backing_store_transaction_begun_) transaction_->Rollback(); while (!abort_task_stack_.empty()) abort_task_stack_.pop().Run(); preemptive_task_queue_.clear(); pending_preemptive_events_ = 0; task_queue_.clear(); CloseOpenCursors(); transaction_->Reset(); database_->transaction_coordinator().DidFinishTransaction(this); #ifndef NDEBUG DCHECK(!database_->transaction_coordinator().IsActive(this)); #endif if (callbacks_.get()) callbacks_->OnAbort(*this, error); database_->TransactionFinished(this, false); // Note: During force-close situations, the connection can be destroyed during // the |IndexedDBDatabase::TransactionFinished| call if (connection_) connection_->RemoveTransaction(id_); }
173,219
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 assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, const struct assoc_array_ops *ops, const void *index_key, struct assoc_array_walk_result *result) { struct assoc_array_shortcut *shortcut, *new_s0; struct assoc_array_node *node, *new_n0, *new_n1, *side; struct assoc_array_ptr *ptr; unsigned long dissimilarity, base_seg, blank; size_t keylen; bool have_meta; int level, diff; int slot, next_slot, free_slot, i, j; node = result->terminal_node.node; level = result->terminal_node.level; edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot; pr_devel("-->%s()\n", __func__); /* We arrived at a node which doesn't have an onward node or shortcut * pointer that we have to follow. This means that (a) the leaf we * want must go here (either by insertion or replacement) or (b) we * need to split this node and insert in one of the fragments. */ free_slot = -1; /* Firstly, we have to check the leaves in this node to see if there's * a matching one we should replace in place. */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; if (!ptr) { free_slot = i; continue; } if (assoc_array_ptr_is_leaf(ptr) && ops->compare_object(assoc_array_ptr_to_leaf(ptr), index_key)) { pr_devel("replace in slot %d\n", i); edit->leaf_p = &node->slots[i]; edit->dead_leaf = node->slots[i]; pr_devel("<--%s() = ok [replace]\n", __func__); return true; } } /* If there is a free slot in this node then we can just insert the * leaf here. */ if (free_slot >= 0) { pr_devel("insert in free slot %d\n", free_slot); edit->leaf_p = &node->slots[free_slot]; edit->adjust_count_on = node; pr_devel("<--%s() = ok [insert]\n", __func__); return true; } /* The node has no spare slots - so we're either going to have to split * it or insert another node before it. * * Whatever, we're going to need at least two new nodes - so allocate * those now. We may also need a new shortcut, but we deal with that * when we need it. */ new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); if (!new_n0) return false; edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); new_n1 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); if (!new_n1) return false; edit->new_meta[1] = assoc_array_node_to_ptr(new_n1); /* We need to find out how similar the leaves are. */ pr_devel("no spare slots\n"); have_meta = false; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; if (assoc_array_ptr_is_meta(ptr)) { edit->segment_cache[i] = 0xff; have_meta = true; continue; } base_seg = ops->get_object_key_chunk( assoc_array_ptr_to_leaf(ptr), level); base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK; } if (have_meta) { pr_devel("have meta\n"); goto split_node; } /* The node contains only leaves */ dissimilarity = 0; base_seg = edit->segment_cache[0]; for (i = 1; i < ASSOC_ARRAY_FAN_OUT; i++) dissimilarity |= edit->segment_cache[i] ^ base_seg; pr_devel("only leaves; dissimilarity=%lx\n", dissimilarity); if ((dissimilarity & ASSOC_ARRAY_FAN_MASK) == 0) { /* The old leaves all cluster in the same slot. We will need * to insert a shortcut if the new node wants to cluster with them. */ if ((edit->segment_cache[ASSOC_ARRAY_FAN_OUT] ^ base_seg) == 0) goto all_leaves_cluster_together; /* Otherwise we can just insert a new node ahead of the old * one. */ goto present_leaves_cluster_but_not_new_leaf; } split_node: pr_devel("split node\n"); /* We need to split the current node; we know that the node doesn't * simply contain a full set of leaves that cluster together (it * contains meta pointers and/or non-clustering leaves). * * We need to expel at least two leaves out of a set consisting of the * leaves in the node and the new leaf. * * We need a new node (n0) to replace the current one and a new node to * take the expelled nodes (n1). */ edit->set[0].to = assoc_array_node_to_ptr(new_n0); new_n0->back_pointer = node->back_pointer; new_n0->parent_slot = node->parent_slot; new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); new_n1->parent_slot = -1; /* Need to calculate this */ do_split_node: pr_devel("do_split_node\n"); new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; new_n1->nr_leaves_on_branch = 0; /* Begin by finding two matching leaves. There have to be at least two * that match - even if there are meta pointers - because any leaf that * would match a slot with a meta pointer in it must be somewhere * behind that meta pointer and cannot be here. Further, given N * remaining leaf slots, we now have N+1 leaves to go in them. */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { slot = edit->segment_cache[i]; if (slot != 0xff) for (j = i + 1; j < ASSOC_ARRAY_FAN_OUT + 1; j++) if (edit->segment_cache[j] == slot) goto found_slot_for_multiple_occupancy; } found_slot_for_multiple_occupancy: pr_devel("same slot: %x %x [%02x]\n", i, j, slot); BUG_ON(i >= ASSOC_ARRAY_FAN_OUT); BUG_ON(j >= ASSOC_ARRAY_FAN_OUT + 1); BUG_ON(slot >= ASSOC_ARRAY_FAN_OUT); new_n1->parent_slot = slot; /* Metadata pointers cannot change slot */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) if (assoc_array_ptr_is_meta(node->slots[i])) new_n0->slots[i] = node->slots[i]; else new_n0->slots[i] = NULL; BUG_ON(new_n0->slots[slot] != NULL); new_n0->slots[slot] = assoc_array_node_to_ptr(new_n1); /* Filter the leaf pointers between the new nodes */ free_slot = -1; next_slot = 0; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { if (assoc_array_ptr_is_meta(node->slots[i])) continue; if (edit->segment_cache[i] == slot) { new_n1->slots[next_slot++] = node->slots[i]; new_n1->nr_leaves_on_branch++; } else { do { free_slot++; } while (new_n0->slots[free_slot] != NULL); new_n0->slots[free_slot] = node->slots[i]; } } pr_devel("filtered: f=%x n=%x\n", free_slot, next_slot); if (edit->segment_cache[ASSOC_ARRAY_FAN_OUT] != slot) { do { free_slot++; } while (new_n0->slots[free_slot] != NULL); edit->leaf_p = &new_n0->slots[free_slot]; edit->adjust_count_on = new_n0; } else { edit->leaf_p = &new_n1->slots[next_slot++]; edit->adjust_count_on = new_n1; } BUG_ON(next_slot <= 1); edit->set_backpointers_to = assoc_array_node_to_ptr(new_n0); for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { if (edit->segment_cache[i] == 0xff) { ptr = node->slots[i]; BUG_ON(assoc_array_ptr_is_leaf(ptr)); if (assoc_array_ptr_is_node(ptr)) { side = assoc_array_ptr_to_node(ptr); edit->set_backpointers[i] = &side->back_pointer; } else { shortcut = assoc_array_ptr_to_shortcut(ptr); edit->set_backpointers[i] = &shortcut->back_pointer; } } } ptr = node->back_pointer; if (!ptr) edit->set[0].ptr = &edit->array->root; else if (assoc_array_ptr_is_node(ptr)) edit->set[0].ptr = &assoc_array_ptr_to_node(ptr)->slots[node->parent_slot]; else edit->set[0].ptr = &assoc_array_ptr_to_shortcut(ptr)->next_node; edit->excised_meta[0] = assoc_array_node_to_ptr(node); pr_devel("<--%s() = ok [split node]\n", __func__); return true; present_leaves_cluster_but_not_new_leaf: /* All the old leaves cluster in the same slot, but the new leaf wants * to go into a different slot, so we create a new node to hold the new * leaf and a pointer to a new node holding all the old leaves. */ pr_devel("present leaves cluster but not new leaf\n"); new_n0->back_pointer = node->back_pointer; new_n0->parent_slot = node->parent_slot; new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); new_n1->parent_slot = edit->segment_cache[0]; new_n1->nr_leaves_on_branch = node->nr_leaves_on_branch; edit->adjust_count_on = new_n0; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) new_n1->slots[i] = node->slots[i]; new_n0->slots[edit->segment_cache[0]] = assoc_array_node_to_ptr(new_n0); edit->leaf_p = &new_n0->slots[edit->segment_cache[ASSOC_ARRAY_FAN_OUT]]; edit->set[0].ptr = &assoc_array_ptr_to_node(node->back_pointer)->slots[node->parent_slot]; edit->set[0].to = assoc_array_node_to_ptr(new_n0); edit->excised_meta[0] = assoc_array_node_to_ptr(node); pr_devel("<--%s() = ok [insert node before]\n", __func__); return true; all_leaves_cluster_together: /* All the leaves, new and old, want to cluster together in this node * in the same slot, so we have to replace this node with a shortcut to * skip over the identical parts of the key and then place a pair of * nodes, one inside the other, at the end of the shortcut and * distribute the keys between them. * * Firstly we need to work out where the leaves start diverging as a * bit position into their keys so that we know how big the shortcut * needs to be. * * We only need to make a single pass of N of the N+1 leaves because if * any keys differ between themselves at bit X then at least one of * them must also differ with the base key at bit X or before. */ pr_devel("all leaves cluster together\n"); diff = INT_MAX; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { int x = ops->diff_objects(assoc_array_ptr_to_leaf(node->slots[i]), index_key); if (x < diff) { BUG_ON(x < 0); diff = x; } } BUG_ON(diff == INT_MAX); BUG_ON(diff < level + ASSOC_ARRAY_LEVEL_STEP); keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE); keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; new_s0 = kzalloc(sizeof(struct assoc_array_shortcut) + keylen * sizeof(unsigned long), GFP_KERNEL); if (!new_s0) return false; edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s0); edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0); new_s0->back_pointer = node->back_pointer; new_s0->parent_slot = node->parent_slot; new_s0->next_node = assoc_array_node_to_ptr(new_n0); new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0); new_n0->parent_slot = 0; new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); new_n1->parent_slot = -1; /* Need to calculate this */ new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK; pr_devel("skip_to_level = %d [diff %d]\n", level, diff); BUG_ON(level <= 0); for (i = 0; i < keylen; i++) new_s0->index_key[i] = ops->get_key_chunk(index_key, i * ASSOC_ARRAY_KEY_CHUNK_SIZE); blank = ULONG_MAX << (level & ASSOC_ARRAY_KEY_CHUNK_MASK); pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, level, blank); new_s0->index_key[keylen - 1] &= ~blank; /* This now reduces to a node splitting exercise for which we'll need * to regenerate the disparity table. */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; base_seg = ops->get_object_key_chunk(assoc_array_ptr_to_leaf(ptr), level); base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK; } base_seg = ops->get_key_chunk(index_key, level); base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg & ASSOC_ARRAY_FAN_MASK; goto do_split_node; } Commit Message: assoc_array: Fix a buggy node-splitting case This fixes CVE-2017-12193. Fix a case in the assoc_array implementation in which a new leaf is added that needs to go into a node that happens to be full, where the existing leaves in that node cluster together at that level to the exclusion of new leaf. What needs to happen is that the existing leaves get moved out to a new node, N1, at level + 1 and the existing node needs replacing with one, N0, that has pointers to the new leaf and to N1. The code that tries to do this gets this wrong in two ways: (1) The pointer that should've pointed from N0 to N1 is set to point recursively to N0 instead. (2) The backpointer from N0 needs to be set correctly in the case N0 is either the root node or reached through a shortcut. Fix this by removing this path and using the split_node path instead, which achieves the same end, but in a more general way (thanks to Eric Biggers for spotting the redundancy). The problem manifests itself as: BUG: unable to handle kernel NULL pointer dereference at 0000000000000010 IP: assoc_array_apply_edit+0x59/0xe5 Fixes: 3cb989501c26 ("Add a generic associative array implementation.") Reported-and-tested-by: WU Fan <[email protected]> Signed-off-by: David Howells <[email protected]> Cc: [email protected] [v3.13-rc1+] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-476
static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, const struct assoc_array_ops *ops, const void *index_key, struct assoc_array_walk_result *result) { struct assoc_array_shortcut *shortcut, *new_s0; struct assoc_array_node *node, *new_n0, *new_n1, *side; struct assoc_array_ptr *ptr; unsigned long dissimilarity, base_seg, blank; size_t keylen; bool have_meta; int level, diff; int slot, next_slot, free_slot, i, j; node = result->terminal_node.node; level = result->terminal_node.level; edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot; pr_devel("-->%s()\n", __func__); /* We arrived at a node which doesn't have an onward node or shortcut * pointer that we have to follow. This means that (a) the leaf we * want must go here (either by insertion or replacement) or (b) we * need to split this node and insert in one of the fragments. */ free_slot = -1; /* Firstly, we have to check the leaves in this node to see if there's * a matching one we should replace in place. */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; if (!ptr) { free_slot = i; continue; } if (assoc_array_ptr_is_leaf(ptr) && ops->compare_object(assoc_array_ptr_to_leaf(ptr), index_key)) { pr_devel("replace in slot %d\n", i); edit->leaf_p = &node->slots[i]; edit->dead_leaf = node->slots[i]; pr_devel("<--%s() = ok [replace]\n", __func__); return true; } } /* If there is a free slot in this node then we can just insert the * leaf here. */ if (free_slot >= 0) { pr_devel("insert in free slot %d\n", free_slot); edit->leaf_p = &node->slots[free_slot]; edit->adjust_count_on = node; pr_devel("<--%s() = ok [insert]\n", __func__); return true; } /* The node has no spare slots - so we're either going to have to split * it or insert another node before it. * * Whatever, we're going to need at least two new nodes - so allocate * those now. We may also need a new shortcut, but we deal with that * when we need it. */ new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); if (!new_n0) return false; edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); new_n1 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); if (!new_n1) return false; edit->new_meta[1] = assoc_array_node_to_ptr(new_n1); /* We need to find out how similar the leaves are. */ pr_devel("no spare slots\n"); have_meta = false; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; if (assoc_array_ptr_is_meta(ptr)) { edit->segment_cache[i] = 0xff; have_meta = true; continue; } base_seg = ops->get_object_key_chunk( assoc_array_ptr_to_leaf(ptr), level); base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK; } if (have_meta) { pr_devel("have meta\n"); goto split_node; } /* The node contains only leaves */ dissimilarity = 0; base_seg = edit->segment_cache[0]; for (i = 1; i < ASSOC_ARRAY_FAN_OUT; i++) dissimilarity |= edit->segment_cache[i] ^ base_seg; pr_devel("only leaves; dissimilarity=%lx\n", dissimilarity); if ((dissimilarity & ASSOC_ARRAY_FAN_MASK) == 0) { /* The old leaves all cluster in the same slot. We will need * to insert a shortcut if the new node wants to cluster with them. */ if ((edit->segment_cache[ASSOC_ARRAY_FAN_OUT] ^ base_seg) == 0) goto all_leaves_cluster_together; /* Otherwise all the old leaves cluster in the same slot, but * the new leaf wants to go into a different slot - so we * create a new node (n0) to hold the new leaf and a pointer to * a new node (n1) holding all the old leaves. * * This can be done by falling through to the node splitting * path. */ pr_devel("present leaves cluster but not new leaf\n"); } split_node: pr_devel("split node\n"); /* We need to split the current node. The node must contain anything * from a single leaf (in the one leaf case, this leaf will cluster * with the new leaf) and the rest meta-pointers, to all leaves, some * of which may cluster. * * It won't contain the case in which all the current leaves plus the * new leaves want to cluster in the same slot. * * We need to expel at least two leaves out of a set consisting of the * leaves in the node and the new leaf. The current meta pointers can * just be copied as they shouldn't cluster with any of the leaves. * * We need a new node (n0) to replace the current one and a new node to * take the expelled nodes (n1). */ edit->set[0].to = assoc_array_node_to_ptr(new_n0); new_n0->back_pointer = node->back_pointer; new_n0->parent_slot = node->parent_slot; new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); new_n1->parent_slot = -1; /* Need to calculate this */ do_split_node: pr_devel("do_split_node\n"); new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; new_n1->nr_leaves_on_branch = 0; /* Begin by finding two matching leaves. There have to be at least two * that match - even if there are meta pointers - because any leaf that * would match a slot with a meta pointer in it must be somewhere * behind that meta pointer and cannot be here. Further, given N * remaining leaf slots, we now have N+1 leaves to go in them. */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { slot = edit->segment_cache[i]; if (slot != 0xff) for (j = i + 1; j < ASSOC_ARRAY_FAN_OUT + 1; j++) if (edit->segment_cache[j] == slot) goto found_slot_for_multiple_occupancy; } found_slot_for_multiple_occupancy: pr_devel("same slot: %x %x [%02x]\n", i, j, slot); BUG_ON(i >= ASSOC_ARRAY_FAN_OUT); BUG_ON(j >= ASSOC_ARRAY_FAN_OUT + 1); BUG_ON(slot >= ASSOC_ARRAY_FAN_OUT); new_n1->parent_slot = slot; /* Metadata pointers cannot change slot */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) if (assoc_array_ptr_is_meta(node->slots[i])) new_n0->slots[i] = node->slots[i]; else new_n0->slots[i] = NULL; BUG_ON(new_n0->slots[slot] != NULL); new_n0->slots[slot] = assoc_array_node_to_ptr(new_n1); /* Filter the leaf pointers between the new nodes */ free_slot = -1; next_slot = 0; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { if (assoc_array_ptr_is_meta(node->slots[i])) continue; if (edit->segment_cache[i] == slot) { new_n1->slots[next_slot++] = node->slots[i]; new_n1->nr_leaves_on_branch++; } else { do { free_slot++; } while (new_n0->slots[free_slot] != NULL); new_n0->slots[free_slot] = node->slots[i]; } } pr_devel("filtered: f=%x n=%x\n", free_slot, next_slot); if (edit->segment_cache[ASSOC_ARRAY_FAN_OUT] != slot) { do { free_slot++; } while (new_n0->slots[free_slot] != NULL); edit->leaf_p = &new_n0->slots[free_slot]; edit->adjust_count_on = new_n0; } else { edit->leaf_p = &new_n1->slots[next_slot++]; edit->adjust_count_on = new_n1; } BUG_ON(next_slot <= 1); edit->set_backpointers_to = assoc_array_node_to_ptr(new_n0); for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { if (edit->segment_cache[i] == 0xff) { ptr = node->slots[i]; BUG_ON(assoc_array_ptr_is_leaf(ptr)); if (assoc_array_ptr_is_node(ptr)) { side = assoc_array_ptr_to_node(ptr); edit->set_backpointers[i] = &side->back_pointer; } else { shortcut = assoc_array_ptr_to_shortcut(ptr); edit->set_backpointers[i] = &shortcut->back_pointer; } } } ptr = node->back_pointer; if (!ptr) edit->set[0].ptr = &edit->array->root; else if (assoc_array_ptr_is_node(ptr)) edit->set[0].ptr = &assoc_array_ptr_to_node(ptr)->slots[node->parent_slot]; else edit->set[0].ptr = &assoc_array_ptr_to_shortcut(ptr)->next_node; edit->excised_meta[0] = assoc_array_node_to_ptr(node); pr_devel("<--%s() = ok [split node]\n", __func__); return true; all_leaves_cluster_together: /* All the leaves, new and old, want to cluster together in this node * in the same slot, so we have to replace this node with a shortcut to * skip over the identical parts of the key and then place a pair of * nodes, one inside the other, at the end of the shortcut and * distribute the keys between them. * * Firstly we need to work out where the leaves start diverging as a * bit position into their keys so that we know how big the shortcut * needs to be. * * We only need to make a single pass of N of the N+1 leaves because if * any keys differ between themselves at bit X then at least one of * them must also differ with the base key at bit X or before. */ pr_devel("all leaves cluster together\n"); diff = INT_MAX; for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { int x = ops->diff_objects(assoc_array_ptr_to_leaf(node->slots[i]), index_key); if (x < diff) { BUG_ON(x < 0); diff = x; } } BUG_ON(diff == INT_MAX); BUG_ON(diff < level + ASSOC_ARRAY_LEVEL_STEP); keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE); keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; new_s0 = kzalloc(sizeof(struct assoc_array_shortcut) + keylen * sizeof(unsigned long), GFP_KERNEL); if (!new_s0) return false; edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s0); edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0); new_s0->back_pointer = node->back_pointer; new_s0->parent_slot = node->parent_slot; new_s0->next_node = assoc_array_node_to_ptr(new_n0); new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0); new_n0->parent_slot = 0; new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); new_n1->parent_slot = -1; /* Need to calculate this */ new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK; pr_devel("skip_to_level = %d [diff %d]\n", level, diff); BUG_ON(level <= 0); for (i = 0; i < keylen; i++) new_s0->index_key[i] = ops->get_key_chunk(index_key, i * ASSOC_ARRAY_KEY_CHUNK_SIZE); blank = ULONG_MAX << (level & ASSOC_ARRAY_KEY_CHUNK_MASK); pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, level, blank); new_s0->index_key[keylen - 1] &= ~blank; /* This now reduces to a node splitting exercise for which we'll need * to regenerate the disparity table. */ for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { ptr = node->slots[i]; base_seg = ops->get_object_key_chunk(assoc_array_ptr_to_leaf(ptr), level); base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK; } base_seg = ops->get_key_chunk(index_key, level); base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg & ASSOC_ARRAY_FAN_MASK; goto do_split_node; }
167,986
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int init_ssl_connection(SSL *con) { int i; const char *str; X509 *peer; long verify_error; MS_STATIC char buf[BUFSIZ]; #ifndef OPENSSL_NO_KRB5 char *client_princ; #endif #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) const unsigned char *next_proto_neg; unsigned next_proto_neg_len; #endif unsigned char *exportedkeymat; i = SSL_accept(con); #ifdef CERT_CB_TEST_RETRY { while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP && SSL_state(con) == SSL3_ST_SR_CLNT_HELLO_C) { fprintf(stderr, "LOOKUP from certificate callback during accept\n"); i = SSL_accept(con); } } #endif #ifndef OPENSSL_NO_SRP while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP during accept %s\n", srp_callback_parm.login); srp_callback_parm.user = SRP_VBASE_get_by_user(srp_callback_parm.vb, srp_callback_parm.login); if (srp_callback_parm.user) BIO_printf(bio_s_out, "LOOKUP done %s\n", while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP during accept %s\n", srp_callback_parm.login); srp_callback_parm.user = SRP_VBASE_get_by_user(srp_callback_parm.vb, srp_callback_parm.login); if (srp_callback_parm.user) BIO_printf(bio_s_out, "LOOKUP done %s\n", srp_callback_parm.user->info); return (1); } BIO_printf(bio_err, "ERROR\n"); verify_error = SSL_get_verify_result(con); if (verify_error != X509_V_OK) { BIO_printf(bio_err, "verify error:%s\n", X509_verify_cert_error_string(verify_error)); } /* Always print any error messages */ ERR_print_errors(bio_err); return (0); } if (s_brief) print_ssl_summary(bio_err, con); PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con)); peer = SSL_get_peer_certificate(con); if (peer != NULL) { BIO_printf(bio_s_out, "Client certificate\n"); PEM_write_bio_X509(bio_s_out, peer); X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf); BIO_printf(bio_s_out, "subject=%s\n", buf); X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf); BIO_printf(bio_s_out, "issuer=%s\n", buf); X509_free(peer); } if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL) BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf); str = SSL_CIPHER_get_name(SSL_get_current_cipher(con)); ssl_print_sigalgs(bio_s_out, con); #ifndef OPENSSL_NO_EC ssl_print_point_formats(bio_s_out, con); ssl_print_curves(bio_s_out, con, 0); #endif BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)"); #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len); if (next_proto_neg) { BIO_printf(bio_s_out, "NEXTPROTO is "); BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len); BIO_printf(bio_s_out, "\n"); } #endif #ifndef OPENSSL_NO_SRTP { SRTP_PROTECTION_PROFILE *srtp_profile = SSL_get_selected_srtp_profile(con); if (srtp_profile) BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n", srtp_profile->name); } #endif if (SSL_cache_hit(con)) BIO_printf(bio_s_out, "Reused session-id\n"); if (SSL_ctrl(con, SSL_CTRL_GET_FLAGS, 0, NULL) & TLS1_FLAGS_TLS_PADDING_BUG) BIO_printf(bio_s_out, "Peer has incorrect TLSv1 block padding\n"); #ifndef OPENSSL_NO_KRB5 client_princ = kssl_ctx_get0_client_princ(SSL_get0_kssl_ctx(con)); if (client_princ != NULL) { BIO_printf(bio_s_out, "Kerberos peer principal is %s\n", client_princ); } #endif /* OPENSSL_NO_KRB5 */ BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n", SSL_get_secure_renegotiation_support(con) ? "" : " NOT"); if (keymatexportlabel != NULL) { BIO_printf(bio_s_out, "Keying material exporter:\n"); BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel); BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen); exportedkeymat = OPENSSL_malloc(keymatexportlen); if (exportedkeymat != NULL) { if (!SSL_export_keying_material(con, exportedkeymat, keymatexportlen, keymatexportlabel, strlen(keymatexportlabel), NULL, 0, 0)) { BIO_printf(bio_s_out, " Error\n"); } else { BIO_printf(bio_s_out, " Keying material: "); for (i = 0; i < keymatexportlen; i++) BIO_printf(bio_s_out, "%02X", exportedkeymat[i]); BIO_printf(bio_s_out, "\n"); } OPENSSL_free(exportedkeymat); } } return (1); } Commit Message: CWE ID: CWE-399
static int init_ssl_connection(SSL *con) { int i; const char *str; X509 *peer; long verify_error; MS_STATIC char buf[BUFSIZ]; #ifndef OPENSSL_NO_KRB5 char *client_princ; #endif #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) const unsigned char *next_proto_neg; unsigned next_proto_neg_len; #endif unsigned char *exportedkeymat; i = SSL_accept(con); #ifdef CERT_CB_TEST_RETRY { while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP && SSL_state(con) == SSL3_ST_SR_CLNT_HELLO_C) { fprintf(stderr, "LOOKUP from certificate callback during accept\n"); i = SSL_accept(con); } } #endif #ifndef OPENSSL_NO_SRP while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP during accept %s\n", srp_callback_parm.login); srp_callback_parm.user = SRP_VBASE_get_by_user(srp_callback_parm.vb, srp_callback_parm.login); if (srp_callback_parm.user) BIO_printf(bio_s_out, "LOOKUP done %s\n", while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP during accept %s\n", srp_callback_parm.login); SRP_user_pwd_free(srp_callback_parm.user); srp_callback_parm.user = SRP_VBASE_get1_by_user(srp_callback_parm.vb, srp_callback_parm.login); if (srp_callback_parm.user) BIO_printf(bio_s_out, "LOOKUP done %s\n", srp_callback_parm.user->info); return (1); } BIO_printf(bio_err, "ERROR\n"); verify_error = SSL_get_verify_result(con); if (verify_error != X509_V_OK) { BIO_printf(bio_err, "verify error:%s\n", X509_verify_cert_error_string(verify_error)); } /* Always print any error messages */ ERR_print_errors(bio_err); return (0); } if (s_brief) print_ssl_summary(bio_err, con); PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con)); peer = SSL_get_peer_certificate(con); if (peer != NULL) { BIO_printf(bio_s_out, "Client certificate\n"); PEM_write_bio_X509(bio_s_out, peer); X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf); BIO_printf(bio_s_out, "subject=%s\n", buf); X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf); BIO_printf(bio_s_out, "issuer=%s\n", buf); X509_free(peer); } if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL) BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf); str = SSL_CIPHER_get_name(SSL_get_current_cipher(con)); ssl_print_sigalgs(bio_s_out, con); #ifndef OPENSSL_NO_EC ssl_print_point_formats(bio_s_out, con); ssl_print_curves(bio_s_out, con, 0); #endif BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)"); #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len); if (next_proto_neg) { BIO_printf(bio_s_out, "NEXTPROTO is "); BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len); BIO_printf(bio_s_out, "\n"); } #endif #ifndef OPENSSL_NO_SRTP { SRTP_PROTECTION_PROFILE *srtp_profile = SSL_get_selected_srtp_profile(con); if (srtp_profile) BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n", srtp_profile->name); } #endif if (SSL_cache_hit(con)) BIO_printf(bio_s_out, "Reused session-id\n"); if (SSL_ctrl(con, SSL_CTRL_GET_FLAGS, 0, NULL) & TLS1_FLAGS_TLS_PADDING_BUG) BIO_printf(bio_s_out, "Peer has incorrect TLSv1 block padding\n"); #ifndef OPENSSL_NO_KRB5 client_princ = kssl_ctx_get0_client_princ(SSL_get0_kssl_ctx(con)); if (client_princ != NULL) { BIO_printf(bio_s_out, "Kerberos peer principal is %s\n", client_princ); } #endif /* OPENSSL_NO_KRB5 */ BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n", SSL_get_secure_renegotiation_support(con) ? "" : " NOT"); if (keymatexportlabel != NULL) { BIO_printf(bio_s_out, "Keying material exporter:\n"); BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel); BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen); exportedkeymat = OPENSSL_malloc(keymatexportlen); if (exportedkeymat != NULL) { if (!SSL_export_keying_material(con, exportedkeymat, keymatexportlen, keymatexportlabel, strlen(keymatexportlabel), NULL, 0, 0)) { BIO_printf(bio_s_out, " Error\n"); } else { BIO_printf(bio_s_out, " Keying material: "); for (i = 0; i < keymatexportlen; i++) BIO_printf(bio_s_out, "%02X", exportedkeymat[i]); BIO_printf(bio_s_out, "\n"); } OPENSSL_free(exportedkeymat); } } return (1); }
165,247
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 ipc_addid(struct ipc_ids *ids, struct kern_ipc_perm *new, int size) { kuid_t euid; kgid_t egid; int id; int next_id = ids->next_id; if (size > IPCMNI) size = IPCMNI; if (ids->in_use >= size) return -ENOSPC; idr_preload(GFP_KERNEL); spin_lock_init(&new->lock); new->deleted = false; rcu_read_lock(); spin_lock(&new->lock); id = idr_alloc(&ids->ipcs_idr, new, (next_id < 0) ? 0 : ipcid_to_idx(next_id), 0, GFP_NOWAIT); idr_preload_end(); if (id < 0) { spin_unlock(&new->lock); rcu_read_unlock(); return id; } ids->in_use++; current_euid_egid(&euid, &egid); new->cuid = new->uid = euid; new->gid = new->cgid = egid; if (next_id < 0) { new->seq = ids->seq++; if (ids->seq > IPCID_SEQ_MAX) ids->seq = 0; } else { new->seq = ipcid_to_seqx(next_id); ids->next_id = -1; } new->id = ipc_buildid(id, new->seq); return id; } Commit Message: Initialize msg/shm IPC objects before doing ipc_addid() As reported by Dmitry Vyukov, we really shouldn't do ipc_addid() before having initialized the IPC object state. Yes, we initialize the IPC object in a locked state, but with all the lockless RCU lookup work, that IPC object lock no longer means that the state cannot be seen. We already did this for the IPC semaphore code (see commit e8577d1f0329: "ipc/sem.c: fully initialize sem_array before making it visible") but we clearly forgot about msg and shm. Reported-by: Dmitry Vyukov <[email protected]> Cc: Manfred Spraul <[email protected]> Cc: Davidlohr Bueso <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362
int ipc_addid(struct ipc_ids *ids, struct kern_ipc_perm *new, int size) { kuid_t euid; kgid_t egid; int id; int next_id = ids->next_id; if (size > IPCMNI) size = IPCMNI; if (ids->in_use >= size) return -ENOSPC; idr_preload(GFP_KERNEL); spin_lock_init(&new->lock); new->deleted = false; rcu_read_lock(); spin_lock(&new->lock); current_euid_egid(&euid, &egid); new->cuid = new->uid = euid; new->gid = new->cgid = egid; id = idr_alloc(&ids->ipcs_idr, new, (next_id < 0) ? 0 : ipcid_to_idx(next_id), 0, GFP_NOWAIT); idr_preload_end(); if (id < 0) { spin_unlock(&new->lock); rcu_read_unlock(); return id; } ids->in_use++; if (next_id < 0) { new->seq = ids->seq++; if (ids->seq > IPCID_SEQ_MAX) ids->seq = 0; } else { new->seq = ipcid_to_seqx(next_id); ids->next_id = -1; } new->id = ipc_buildid(id, new->seq); return id; }
166,580
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 MockNetworkTransaction::RestartWithAuth( const AuthCredentials& credentials, const CompletionCallback& callback) { if (!IsReadyToRestartForAuth()) return ERR_FAILED; HttpRequestInfo auth_request_info = *request_; auth_request_info.extra_headers.AddHeaderFromString("Authorization: Bar"); return StartInternal(&auth_request_info, callback, BoundNetLog()); } Commit Message: Replace fixed string uses of AddHeaderFromString Uses of AddHeaderFromString() with a static string may as well be replaced with SetHeader(). Do so. BUG=None Review-Url: https://codereview.chromium.org/2236933005 Cr-Commit-Position: refs/heads/master@{#418161} CWE ID: CWE-119
int MockNetworkTransaction::RestartWithAuth( const AuthCredentials& credentials, const CompletionCallback& callback) { if (!IsReadyToRestartForAuth()) return ERR_FAILED; HttpRequestInfo auth_request_info = *request_; auth_request_info.extra_headers.SetHeader("Authorization", "Bar"); return StartInternal(&auth_request_info, callback, BoundNetLog()); }
171,601
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: GahpServer::Reaper(Service *,int pid,int status) { /* This should be much better.... for now, if our Gahp Server goes away for any reason, we EXCEPT. */ GahpServer *dead_server = NULL; GahpServer *next_server = NULL; GahpServersById.startIterations(); while ( GahpServersById.iterate( next_server ) != 0 ) { if ( pid == next_server->m_gahp_pid ) { dead_server = next_server; break; } } std::string buf; sprintf( buf, "Gahp Server (pid=%d) ", pid ); if( WIFSIGNALED(status) ) { sprintf_cat( buf, "died due to %s", daemonCore->GetExceptionString(status) ); } else { sprintf_cat( buf, "exited with status %d", WEXITSTATUS(status) ); } if ( dead_server ) { sprintf_cat( buf, " unexpectedly" ); EXCEPT( buf.c_str() ); } else { sprintf_cat( buf, "\n" ); dprintf( D_ALWAYS, buf.c_str() ); } } Commit Message: CWE ID: CWE-134
GahpServer::Reaper(Service *,int pid,int status) { /* This should be much better.... for now, if our Gahp Server goes away for any reason, we EXCEPT. */ GahpServer *dead_server = NULL; GahpServer *next_server = NULL; GahpServersById.startIterations(); while ( GahpServersById.iterate( next_server ) != 0 ) { if ( pid == next_server->m_gahp_pid ) { dead_server = next_server; break; } } std::string buf; sprintf( buf, "Gahp Server (pid=%d) ", pid ); if( WIFSIGNALED(status) ) { sprintf_cat( buf, "died due to %s", daemonCore->GetExceptionString(status) ); } else { sprintf_cat( buf, "exited with status %d", WEXITSTATUS(status) ); } if ( dead_server ) { sprintf_cat( buf, " unexpectedly" ); EXCEPT( "%s", buf.c_str() ); } else { sprintf_cat( buf, "\n" ); dprintf( D_ALWAYS, "%s", buf.c_str() ); } }
165,373
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: WtsSessionProcessDelegate::Core::Core( scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, const FilePath& binary_path, bool launch_elevated, const std::string& channel_security) : main_task_runner_(main_task_runner), io_task_runner_(io_task_runner), binary_path_(binary_path), channel_security_(channel_security), launch_elevated_(launch_elevated), stopping_(false) { DCHECK(main_task_runner_->BelongsToCurrentThread()); } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
WtsSessionProcessDelegate::Core::Core( scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, const FilePath& binary_path, bool launch_elevated, const std::string& channel_security) : main_task_runner_(main_task_runner), io_task_runner_(io_task_runner), binary_path_(binary_path), channel_security_(channel_security), get_named_pipe_client_pid_(NULL), launch_elevated_(launch_elevated), stopping_(false) { DCHECK(main_task_runner_->BelongsToCurrentThread()); }
171,555
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_@_set(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_@(pp); this->next->set(this->next, that, pp, pi); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_@_set(PNG_CONST image_transform *this,
173,602
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 ParseCommon(map_string_t *settings, const char *conf_filename) { const char *value; value = get_map_string_item_or_NULL(settings, "WatchCrashdumpArchiveDir"); if (value) { g_settings_sWatchCrashdumpArchiveDir = xstrdup(value); remove_map_string_item(settings, "WatchCrashdumpArchiveDir"); } value = get_map_string_item_or_NULL(settings, "MaxCrashReportsSize"); if (value) { char *end; errno = 0; unsigned long ul = strtoul(value, &end, 10); if (errno || end == value || *end != '\0' || ul > INT_MAX) error_msg("Error parsing %s setting: '%s'", "MaxCrashReportsSize", value); else g_settings_nMaxCrashReportsSize = ul; remove_map_string_item(settings, "MaxCrashReportsSize"); } value = get_map_string_item_or_NULL(settings, "DumpLocation"); if (value) { g_settings_dump_location = xstrdup(value); remove_map_string_item(settings, "DumpLocation"); } else g_settings_dump_location = xstrdup(DEFAULT_DUMP_LOCATION); value = get_map_string_item_or_NULL(settings, "DeleteUploaded"); if (value) { g_settings_delete_uploaded = string_to_bool(value); remove_map_string_item(settings, "DeleteUploaded"); } value = get_map_string_item_or_NULL(settings, "AutoreportingEnabled"); if (value) { g_settings_autoreporting = string_to_bool(value); remove_map_string_item(settings, "AutoreportingEnabled"); } value = get_map_string_item_or_NULL(settings, "AutoreportingEvent"); if (value) { g_settings_autoreporting_event = xstrdup(value); remove_map_string_item(settings, "AutoreportingEvent"); } else g_settings_autoreporting_event = xstrdup("report_uReport"); value = get_map_string_item_or_NULL(settings, "ShortenedReporting"); if (value) { g_settings_shortenedreporting = string_to_bool(value); remove_map_string_item(settings, "ShortenedReporting"); } else g_settings_shortenedreporting = 0; GHashTableIter iter; const char *name; /*char *value; - already declared */ init_map_string_iter(&iter, settings); while (next_map_string_iter(&iter, &name, &value)) { error_msg("Unrecognized variable '%s' in '%s'", name, conf_filename); } } Commit Message: make the dump directories owned by root by default It was discovered that the abrt event scripts create a user-readable copy of a sosreport file in abrt problem directories, and include excerpts of /var/log/messages selected by the user-controlled process name, leading to an information disclosure. This issue was discovered by Florian Weimer of Red Hat Product Security. Related: #1212868 Signed-off-by: Jakub Filak <[email protected]> CWE ID: CWE-200
static void ParseCommon(map_string_t *settings, const char *conf_filename) { const char *value; value = get_map_string_item_or_NULL(settings, "WatchCrashdumpArchiveDir"); if (value) { g_settings_sWatchCrashdumpArchiveDir = xstrdup(value); remove_map_string_item(settings, "WatchCrashdumpArchiveDir"); } value = get_map_string_item_or_NULL(settings, "MaxCrashReportsSize"); if (value) { char *end; errno = 0; unsigned long ul = strtoul(value, &end, 10); if (errno || end == value || *end != '\0' || ul > INT_MAX) error_msg("Error parsing %s setting: '%s'", "MaxCrashReportsSize", value); else g_settings_nMaxCrashReportsSize = ul; remove_map_string_item(settings, "MaxCrashReportsSize"); } value = get_map_string_item_or_NULL(settings, "DumpLocation"); if (value) { g_settings_dump_location = xstrdup(value); remove_map_string_item(settings, "DumpLocation"); } else g_settings_dump_location = xstrdup(DEFAULT_DUMP_LOCATION); value = get_map_string_item_or_NULL(settings, "DeleteUploaded"); if (value) { g_settings_delete_uploaded = string_to_bool(value); remove_map_string_item(settings, "DeleteUploaded"); } value = get_map_string_item_or_NULL(settings, "AutoreportingEnabled"); if (value) { g_settings_autoreporting = string_to_bool(value); remove_map_string_item(settings, "AutoreportingEnabled"); } value = get_map_string_item_or_NULL(settings, "AutoreportingEvent"); if (value) { g_settings_autoreporting_event = xstrdup(value); remove_map_string_item(settings, "AutoreportingEvent"); } else g_settings_autoreporting_event = xstrdup("report_uReport"); value = get_map_string_item_or_NULL(settings, "ShortenedReporting"); if (value) { g_settings_shortenedreporting = string_to_bool(value); remove_map_string_item(settings, "ShortenedReporting"); } else g_settings_shortenedreporting = 0; value = get_map_string_item_or_NULL(settings, "PrivateReports"); if (value) { g_settings_privatereports = string_to_bool(value); remove_map_string_item(settings, "PrivateReports"); } GHashTableIter iter; const char *name; /*char *value; - already declared */ init_map_string_iter(&iter, settings); while (next_map_string_iter(&iter, &name, &value)) { error_msg("Unrecognized variable '%s' in '%s'", name, conf_filename); } }
170,150
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 OMX::binderDied(const wp<IBinder> &the_late_who) { OMXNodeInstance *instance; { Mutex::Autolock autoLock(mLock); ssize_t index = mLiveNodes.indexOfKey(the_late_who); CHECK(index >= 0); instance = mLiveNodes.editValueAt(index); mLiveNodes.removeItemsAt(index); index = mDispatchers.indexOfKey(instance->nodeID()); CHECK(index >= 0); mDispatchers.removeItemsAt(index); invalidateNodeID_l(instance->nodeID()); } instance->onObserverDied(mMaster); } Commit Message: Add VPX output buffer size check and handle dead observers more gracefully Bug: 27597103 Change-Id: Id7acb25d5ef69b197da15ec200a9e4f9e7b03518 CWE ID: CWE-264
void OMX::binderDied(const wp<IBinder> &the_late_who) { OMXNodeInstance *instance; { Mutex::Autolock autoLock(mLock); ssize_t index = mLiveNodes.indexOfKey(the_late_who); if (index < 0) { ALOGE("b/27597103, nonexistent observer on binderDied"); android_errorWriteLog(0x534e4554, "27597103"); return; } instance = mLiveNodes.editValueAt(index); mLiveNodes.removeItemsAt(index); index = mDispatchers.indexOfKey(instance->nodeID()); CHECK(index >= 0); mDispatchers.removeItemsAt(index); invalidateNodeID_l(instance->nodeID()); } instance->onObserverDied(mMaster); }
173,881
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: PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view) : content::RenderViewObserver(render_view), content::RenderViewObserverTracker<PrintWebViewHelper>(render_view), print_web_view_(NULL), is_preview_enabled_(IsPrintPreviewEnabled()), is_scripted_print_throttling_disabled_(IsPrintThrottlingDisabled()), is_print_ready_metafile_sent_(false), ignore_css_margins_(false), user_cancelled_scripted_print_count_(0), is_scripted_printing_blocked_(false), notify_browser_of_print_failure_(true), print_for_preview_(false) { } Commit Message: Guard against the same PrintWebViewHelper being re-entered. BUG=159165 Review URL: https://chromiumcodereview.appspot.com/11367076 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@165821 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view) : content::RenderViewObserver(render_view), content::RenderViewObserverTracker<PrintWebViewHelper>(render_view), print_web_view_(NULL), is_preview_enabled_(IsPrintPreviewEnabled()), is_scripted_print_throttling_disabled_(IsPrintThrottlingDisabled()), is_print_ready_metafile_sent_(false), ignore_css_margins_(false), user_cancelled_scripted_print_count_(0), is_scripted_printing_blocked_(false), notify_browser_of_print_failure_(true), print_for_preview_(false), print_node_in_progress_(false) { }
170,698
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void TearDown() { content::GetContentClient()->set_browser(old_browser_client_); } 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
virtual void TearDown() { content::GetContentClient()->set_browser(old_browser_client_); content::SetContentClient(old_client_); }
171,012
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 virtio_net_load(QEMUFile *f, void *opaque, int version_id) { VirtIONet *n = opaque; VirtIODevice *vdev = VIRTIO_DEVICE(n); int ret, i, link_down; if (version_id < 2 || version_id > VIRTIO_NET_VM_VERSION) return -EINVAL; ret = virtio_load(vdev, f); if (ret) { return ret; } qemu_get_buffer(f, n->mac, ETH_ALEN); n->vqs[0].tx_waiting = qemu_get_be32(f); virtio_net_set_mrg_rx_bufs(n, qemu_get_be32(f)); if (version_id >= 3) n->status = qemu_get_be16(f); if (version_id >= 4) { if (version_id < 8) { n->promisc = qemu_get_be32(f); n->allmulti = qemu_get_be32(f); } else { n->promisc = qemu_get_byte(f); n->allmulti = qemu_get_byte(f); } } if (version_id >= 5) { n->mac_table.in_use = qemu_get_be32(f); /* MAC_TABLE_ENTRIES may be different from the saved image */ if (n->mac_table.in_use <= MAC_TABLE_ENTRIES) { qemu_get_buffer(f, n->mac_table.macs, n->mac_table.in_use * ETH_ALEN); } else if (n->mac_table.in_use) { uint8_t *buf = g_malloc0(n->mac_table.in_use); qemu_get_buffer(f, buf, n->mac_table.in_use * ETH_ALEN); g_free(buf); n->mac_table.multi_overflow = n->mac_table.uni_overflow = 1; n->mac_table.in_use = 0; } } if (version_id >= 6) qemu_get_buffer(f, (uint8_t *)n->vlans, MAX_VLAN >> 3); if (version_id >= 7) { if (qemu_get_be32(f) && !peer_has_vnet_hdr(n)) { error_report("virtio-net: saved image requires vnet_hdr=on"); return -1; } } if (version_id >= 9) { n->mac_table.multi_overflow = qemu_get_byte(f); n->mac_table.uni_overflow = qemu_get_byte(f); } if (version_id >= 10) { n->alluni = qemu_get_byte(f); n->nomulti = qemu_get_byte(f); n->nouni = qemu_get_byte(f); n->nobcast = qemu_get_byte(f); } if (version_id >= 11) { if (qemu_get_byte(f) && !peer_has_ufo(n)) { error_report("virtio-net: saved image requires TUN_F_UFO support"); return -1; } } if (n->max_queues > 1) { if (n->max_queues != qemu_get_be16(f)) { error_report("virtio-net: different max_queues "); return -1; } n->curr_queues = qemu_get_be16(f); for (i = 1; i < n->curr_queues; i++) { n->vqs[i].tx_waiting = qemu_get_be32(f); } n->curr_guest_offloads = virtio_net_supported_guest_offloads(n); } if (peer_has_vnet_hdr(n)) { virtio_net_apply_guest_offloads(n); } virtio_net_set_queues(n); /* Find the first multicast entry in the saved MAC filter */ for (i = 0; i < n->mac_table.in_use; i++) { if (n->mac_table.macs[i * ETH_ALEN] & 1) { break; } } n->mac_table.first_multi = i; /* nc.link_down can't be migrated, so infer link_down according * to link status bit in n->status */ link_down = (n->status & VIRTIO_NET_S_LINK_UP) == 0; for (i = 0; i < n->max_queues; i++) { qemu_get_subqueue(n->nic, i)->link_down = link_down; } return 0; } Commit Message: CWE ID: CWE-119
static int virtio_net_load(QEMUFile *f, void *opaque, int version_id) { VirtIONet *n = opaque; VirtIODevice *vdev = VIRTIO_DEVICE(n); int ret, i, link_down; if (version_id < 2 || version_id > VIRTIO_NET_VM_VERSION) return -EINVAL; ret = virtio_load(vdev, f); if (ret) { return ret; } qemu_get_buffer(f, n->mac, ETH_ALEN); n->vqs[0].tx_waiting = qemu_get_be32(f); virtio_net_set_mrg_rx_bufs(n, qemu_get_be32(f)); if (version_id >= 3) n->status = qemu_get_be16(f); if (version_id >= 4) { if (version_id < 8) { n->promisc = qemu_get_be32(f); n->allmulti = qemu_get_be32(f); } else { n->promisc = qemu_get_byte(f); n->allmulti = qemu_get_byte(f); } } if (version_id >= 5) { n->mac_table.in_use = qemu_get_be32(f); /* MAC_TABLE_ENTRIES may be different from the saved image */ if (n->mac_table.in_use <= MAC_TABLE_ENTRIES) { qemu_get_buffer(f, n->mac_table.macs, n->mac_table.in_use * ETH_ALEN); } else if (n->mac_table.in_use) { uint8_t *buf = g_malloc0(n->mac_table.in_use); qemu_get_buffer(f, buf, n->mac_table.in_use * ETH_ALEN); g_free(buf); n->mac_table.multi_overflow = n->mac_table.uni_overflow = 1; n->mac_table.in_use = 0; } } if (version_id >= 6) qemu_get_buffer(f, (uint8_t *)n->vlans, MAX_VLAN >> 3); if (version_id >= 7) { if (qemu_get_be32(f) && !peer_has_vnet_hdr(n)) { error_report("virtio-net: saved image requires vnet_hdr=on"); return -1; } } if (version_id >= 9) { n->mac_table.multi_overflow = qemu_get_byte(f); n->mac_table.uni_overflow = qemu_get_byte(f); } if (version_id >= 10) { n->alluni = qemu_get_byte(f); n->nomulti = qemu_get_byte(f); n->nouni = qemu_get_byte(f); n->nobcast = qemu_get_byte(f); } if (version_id >= 11) { if (qemu_get_byte(f) && !peer_has_ufo(n)) { error_report("virtio-net: saved image requires TUN_F_UFO support"); return -1; } } if (n->max_queues > 1) { if (n->max_queues != qemu_get_be16(f)) { error_report("virtio-net: different max_queues "); return -1; } n->curr_queues = qemu_get_be16(f); if (n->curr_queues > n->max_queues) { error_report("virtio-net: curr_queues %x > max_queues %x", n->curr_queues, n->max_queues); return -1; } for (i = 1; i < n->curr_queues; i++) { n->vqs[i].tx_waiting = qemu_get_be32(f); } n->curr_guest_offloads = virtio_net_supported_guest_offloads(n); } if (peer_has_vnet_hdr(n)) { virtio_net_apply_guest_offloads(n); } virtio_net_set_queues(n); /* Find the first multicast entry in the saved MAC filter */ for (i = 0; i < n->mac_table.in_use; i++) { if (n->mac_table.macs[i * ETH_ALEN] & 1) { break; } } n->mac_table.first_multi = i; /* nc.link_down can't be migrated, so infer link_down according * to link status bit in n->status */ link_down = (n->status & VIRTIO_NET_S_LINK_UP) == 0; for (i = 0; i < n->max_queues; i++) { qemu_get_subqueue(n->nic, i)->link_down = link_down; } return 0; }
165,362
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 CrosLibrary::TestApi::SetNetworkLibrary( NetworkLibrary* library, bool own) { library_->network_lib_.SetImpl(library, own); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
void CrosLibrary::TestApi::SetNetworkLibrary(
170,642
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Con_Dump_f (void) { int l, x, i; short *line; fileHandle_t f; int bufferlen; char *buffer; char filename[MAX_QPATH]; if (Cmd_Argc() != 2) { Com_Printf ("usage: condump <filename>\n"); return; } Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) ); COM_DefaultExtension( filename, sizeof( filename ), ".txt" ); f = FS_FOpenFileWrite( filename ); if (!f) { Com_Printf ("ERROR: couldn't open %s.\n", filename); return; } Com_Printf ("Dumped console text to %s.\n", filename ); for (l = con.current - con.totallines + 1 ; l <= con.current ; l++) { line = con.text + (l%con.totallines)*con.linewidth; for (x=0 ; x<con.linewidth ; x++) if ((line[x] & 0xff) != ' ') break; if (x != con.linewidth) break; } #ifdef _WIN32 bufferlen = con.linewidth + 3 * sizeof ( char ); #else bufferlen = con.linewidth + 2 * sizeof ( char ); #endif buffer = Hunk_AllocateTempMemory( bufferlen ); buffer[bufferlen-1] = 0; for ( ; l <= con.current ; l++) { line = con.text + (l%con.totallines)*con.linewidth; for(i=0; i<con.linewidth; i++) buffer[i] = line[i] & 0xff; for (x=con.linewidth-1 ; x>=0 ; x--) { if (buffer[x] == ' ') buffer[x] = 0; else break; } #ifdef _WIN32 Q_strcat(buffer, bufferlen, "\r\n"); #else Q_strcat(buffer, bufferlen, "\n"); #endif FS_Write(buffer, strlen(buffer), f); } Hunk_FreeTempMemory( buffer ); FS_FCloseFile( f ); } Commit Message: Merge some file writing extension checks from OpenJK. Thanks Ensiform. https://github.com/JACoders/OpenJK/commit/05928a57f9e4aae15a3bd0 https://github.com/JACoders/OpenJK/commit/ef124fd0fc48af164581176 CWE ID: CWE-269
void Con_Dump_f (void) { int l, x, i; short *line; fileHandle_t f; int bufferlen; char *buffer; char filename[MAX_QPATH]; if (Cmd_Argc() != 2) { Com_Printf ("usage: condump <filename>\n"); return; } Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) ); COM_DefaultExtension( filename, sizeof( filename ), ".txt" ); if (!COM_CompareExtension(filename, ".txt")) { Com_Printf("Con_Dump_f: Only the \".txt\" extension is supported by this command!\n"); return; } f = FS_FOpenFileWrite( filename ); if (!f) { Com_Printf ("ERROR: couldn't open %s.\n", filename); return; } Com_Printf ("Dumped console text to %s.\n", filename ); for (l = con.current - con.totallines + 1 ; l <= con.current ; l++) { line = con.text + (l%con.totallines)*con.linewidth; for (x=0 ; x<con.linewidth ; x++) if ((line[x] & 0xff) != ' ') break; if (x != con.linewidth) break; } #ifdef _WIN32 bufferlen = con.linewidth + 3 * sizeof ( char ); #else bufferlen = con.linewidth + 2 * sizeof ( char ); #endif buffer = Hunk_AllocateTempMemory( bufferlen ); buffer[bufferlen-1] = 0; for ( ; l <= con.current ; l++) { line = con.text + (l%con.totallines)*con.linewidth; for(i=0; i<con.linewidth; i++) buffer[i] = line[i] & 0xff; for (x=con.linewidth-1 ; x>=0 ; x--) { if (buffer[x] == ' ') buffer[x] = 0; else break; } #ifdef _WIN32 Q_strcat(buffer, bufferlen, "\r\n"); #else Q_strcat(buffer, bufferlen, "\n"); #endif FS_Write(buffer, strlen(buffer), f); } Hunk_FreeTempMemory( buffer ); FS_FCloseFile( f ); }
170,076