project
stringclasses
765 values
commit_id
stringlengths
6
81
func
stringlengths
19
482k
vul
int64
0
1
CVE ID
stringlengths
13
16
CWE ID
stringclasses
13 values
CWE Name
stringclasses
13 values
CWE Description
stringclasses
13 values
Potential Mitigation
stringclasses
11 values
__index_level_0__
int64
0
23.9k
linux
15fab63e1e57be9fdb5eec1bbc5916e9825e9acb
static inline void pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { buf->ops->get(pipe, buf); }
1
CVE-2019-11487
CWE-416
Use After Free
The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer.
Phase: Architecture and Design Strategy: Language Selection Choose a language that provides automatic memory management. Phase: Implementation Strategy: Attack Surface Reduction When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy. Effectiveness: Defense in Depth Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution.
5,429
Chrome
303d78445257d1eec726c4ebadb3517cb16c8c09
void ExpandableContainerView::UpdateArrowToggle(bool expanded) { gfx::ImageSkia icon = gfx::CreateVectorIcon( expanded ? kCaretUpIcon : kCaretDownIcon, gfx::kChromeIconGrey); arrow_toggle_->SetImage(views::Button::STATE_NORMAL, &icon); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,224
ImageMagick6
e3417aebe17cbe274b7361aa92c83226ca5b646b
static Image *ReadSVGImage(const ImageInfo *image_info,ExceptionInfo *exception) { char filename[MaxTextExtent]; FILE *file; Image *image, *next; int status, unique_file; ssize_t n; SVGInfo *svg_info; unsigned char message[MaxTextExtent]; xmlSAXHandler sax_modules; xmlSAXHandlerPtr sax_handler; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if ((fabs(image->x_resolution) < MagickEpsilon) || (fabs(image->y_resolution) < MagickEpsilon)) { GeometryInfo geometry_info; int flags; flags=ParseGeometry(SVGDensityGeometry,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } if (LocaleCompare(image_info->magick,"MSVG") != 0) { Image *svg_image; svg_image=RenderSVGImage(image_info,image,exception); if (svg_image != (Image *) NULL) { image=DestroyImageList(image); return(svg_image); } { #if defined(MAGICKCORE_RSVG_DELEGATE) #if defined(MAGICKCORE_CAIRO_DELEGATE) cairo_surface_t *cairo_surface; cairo_t *cairo_image; MagickBooleanType apply_density; MemoryInfo *pixel_info; register unsigned char *p; RsvgDimensionData dimension_info; unsigned char *pixels; #else GdkPixbuf *pixel_buffer; register const guchar *p; #endif GError *error; PixelPacket fill_color; register ssize_t x; register PixelPacket *q; RsvgHandle *svg_handle; ssize_t y; svg_handle=rsvg_handle_new(); if (svg_handle == (RsvgHandle *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); rsvg_handle_set_base_uri(svg_handle,image_info->filename); if ((fabs(image->x_resolution) > MagickEpsilon) && (fabs(image->y_resolution) > MagickEpsilon)) rsvg_handle_set_dpi_x_y(svg_handle,image->x_resolution, image->y_resolution); while ((n=ReadBlob(image,MaxTextExtent-1,message)) != 0) { message[n]='\0'; error=(GError *) NULL; (void) rsvg_handle_write(svg_handle,message,n,&error); if (error != (GError *) NULL) g_error_free(error); } error=(GError *) NULL; rsvg_handle_close(svg_handle,&error); if (error != (GError *) NULL) g_error_free(error); #if defined(MAGICKCORE_CAIRO_DELEGATE) apply_density=MagickTrue; rsvg_handle_get_dimensions(svg_handle,&dimension_info); if ((image->x_resolution > 0.0) && (image->y_resolution > 0.0)) { RsvgDimensionData dpi_dimension_info; /* We should not apply the density when the internal 'factor' is 'i'. This can be checked by using the trick below. */ rsvg_handle_set_dpi_x_y(svg_handle,image->x_resolution*256, image->y_resolution*256); rsvg_handle_get_dimensions(svg_handle,&dpi_dimension_info); if ((dpi_dimension_info.width != dimension_info.width) || (dpi_dimension_info.height != dimension_info.height)) apply_density=MagickFalse; rsvg_handle_set_dpi_x_y(svg_handle,image->x_resolution, image->y_resolution); } if (image_info->size != (char *) NULL) { (void) GetGeometry(image_info->size,(ssize_t *) NULL, (ssize_t *) NULL,&image->columns,&image->rows); if ((image->columns != 0) || (image->rows != 0)) { image->x_resolution=DefaultSVGDensity*image->columns/ dimension_info.width; image->y_resolution=DefaultSVGDensity*image->rows/ dimension_info.height; if (fabs(image->x_resolution) < MagickEpsilon) image->x_resolution=image->y_resolution; else if (fabs(image->y_resolution) < MagickEpsilon) image->y_resolution=image->x_resolution; else image->x_resolution=image->y_resolution=MagickMin( image->x_resolution,image->y_resolution); apply_density=MagickTrue; } } if (apply_density != MagickFalse) { image->columns=image->x_resolution*dimension_info.width/ DefaultSVGDensity; image->rows=image->y_resolution*dimension_info.height/ DefaultSVGDensity; } else { image->columns=dimension_info.width; image->rows=dimension_info.height; } pixel_info=(MemoryInfo *) NULL; #else pixel_buffer=rsvg_handle_get_pixbuf(svg_handle); rsvg_handle_free(svg_handle); image->columns=gdk_pixbuf_get_width(pixel_buffer); image->rows=gdk_pixbuf_get_height(pixel_buffer); #endif image->matte=MagickTrue; if (image_info->ping == MagickFalse) { #if defined(MAGICKCORE_CAIRO_DELEGATE) size_t stride; #endif status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { #if !defined(MAGICKCORE_CAIRO_DELEGATE) g_object_unref(G_OBJECT(pixel_buffer)); #endif g_object_unref(svg_handle); InheritException(exception,&image->exception); ThrowReaderException(MissingDelegateError, "NoDecodeDelegateForThisImageFormat"); } #if defined(MAGICKCORE_CAIRO_DELEGATE) stride=4*image->columns; #if defined(MAGICKCORE_PANGOCAIRO_DELEGATE) stride=(size_t) cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, (int) image->columns); #endif pixel_info=AcquireVirtualMemory(stride,image->rows*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { g_object_unref(svg_handle); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); #endif (void) SetImageBackgroundColor(image); #if defined(MAGICKCORE_CAIRO_DELEGATE) cairo_surface=cairo_image_surface_create_for_data(pixels, CAIRO_FORMAT_ARGB32,(int) image->columns,(int) image->rows,(int) stride); if ((cairo_surface == (cairo_surface_t *) NULL) || (cairo_surface_status(cairo_surface) != CAIRO_STATUS_SUCCESS)) { if (cairo_surface != (cairo_surface_t *) NULL) cairo_surface_destroy(cairo_surface); pixel_info=RelinquishVirtualMemory(pixel_info); g_object_unref(svg_handle); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } cairo_image=cairo_create(cairo_surface); cairo_set_operator(cairo_image,CAIRO_OPERATOR_CLEAR); cairo_paint(cairo_image); cairo_set_operator(cairo_image,CAIRO_OPERATOR_OVER); if (apply_density != MagickFalse) cairo_scale(cairo_image,image->x_resolution/DefaultSVGDensity, image->y_resolution/DefaultSVGDensity); rsvg_handle_render_cairo(svg_handle,cairo_image); cairo_destroy(cairo_image); cairo_surface_destroy(cairo_surface); g_object_unref(svg_handle); p=pixels; #else p=gdk_pixbuf_get_pixels(pixel_buffer); #endif for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { #if defined(MAGICKCORE_CAIRO_DELEGATE) fill_color.blue=ScaleCharToQuantum(*p++); fill_color.green=ScaleCharToQuantum(*p++); fill_color.red=ScaleCharToQuantum(*p++); #else fill_color.red=ScaleCharToQuantum(*p++); fill_color.green=ScaleCharToQuantum(*p++); fill_color.blue=ScaleCharToQuantum(*p++); #endif fill_color.opacity=QuantumRange-ScaleCharToQuantum(*p++); #if defined(MAGICKCORE_CAIRO_DELEGATE) { double gamma; gamma=1.0-QuantumScale*fill_color.opacity; gamma=PerceptibleReciprocal(gamma); fill_color.blue*=gamma; fill_color.green*=gamma; fill_color.red*=gamma; } #endif MagickCompositeOver(&fill_color,fill_color.opacity,q, (MagickRealType) q->opacity,q); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } #if defined(MAGICKCORE_CAIRO_DELEGATE) if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); #else g_object_unref(G_OBJECT(pixel_buffer)); #endif (void) CloseBlob(image); for (next=GetFirstImageInList(image); next != (Image *) NULL; ) { (void) CopyMagickString(next->filename,image->filename,MaxTextExtent); (void) CopyMagickString(next->magick,image->magick,MaxTextExtent); next=GetNextImageInList(next); } return(GetFirstImageInList(image)); #endif } } /* Open draw file. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"w"); if ((unique_file == -1) || (file == (FILE *) NULL)) { (void) CopyMagickString(image->filename,filename,MaxTextExtent); ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", image->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Parse SVG file. */ svg_info=AcquireSVGInfo(); if (svg_info == (SVGInfo *) NULL) { (void) fclose(file); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } svg_info->file=file; svg_info->exception=exception; svg_info->image=image; svg_info->image_info=image_info; svg_info->bounds.width=image->columns; svg_info->bounds.height=image->rows; svg_info->svgDepth=0; if (image_info->size != (char *) NULL) (void) CloneString(&svg_info->size,image_info->size); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"begin SAX"); (void) xmlSubstituteEntitiesDefault(1); (void) memset(&sax_modules,0,sizeof(sax_modules)); sax_modules.internalSubset=SVGInternalSubset; sax_modules.isStandalone=SVGIsStandalone; sax_modules.hasInternalSubset=SVGHasInternalSubset; sax_modules.hasExternalSubset=SVGHasExternalSubset; sax_modules.resolveEntity=SVGResolveEntity; sax_modules.getEntity=SVGGetEntity; sax_modules.entityDecl=SVGEntityDeclaration; sax_modules.notationDecl=SVGNotationDeclaration; sax_modules.attributeDecl=SVGAttributeDeclaration; sax_modules.elementDecl=SVGElementDeclaration; sax_modules.unparsedEntityDecl=SVGUnparsedEntityDeclaration; sax_modules.setDocumentLocator=SVGSetDocumentLocator; sax_modules.startDocument=SVGStartDocument; sax_modules.endDocument=SVGEndDocument; sax_modules.startElement=SVGStartElement; sax_modules.endElement=SVGEndElement; sax_modules.reference=SVGReference; sax_modules.characters=SVGCharacters; sax_modules.ignorableWhitespace=SVGIgnorableWhitespace; sax_modules.processingInstruction=SVGProcessingInstructions; sax_modules.comment=SVGComment; sax_modules.warning=SVGWarning; sax_modules.error=SVGError; sax_modules.fatalError=SVGError; sax_modules.getParameterEntity=SVGGetParameterEntity; sax_modules.cdataBlock=SVGCDataBlock; sax_modules.externalSubset=SVGExternalSubset; sax_handler=(&sax_modules); n=ReadBlob(image,MaxTextExtent-1,message); message[n]='\0'; if (n > 0) { svg_info->parser=xmlCreatePushParserCtxt(sax_handler,svg_info,(char *) message,n,image->filename); (void) xmlCtxtUseOptions(svg_info->parser,XML_PARSE_HUGE); while ((n=ReadBlob(image,MaxTextExtent-1,message)) != 0) { message[n]='\0'; status=xmlParseChunk(svg_info->parser,(char *) message,(int) n,0); if (status != 0) break; } } (void) xmlParseChunk(svg_info->parser,(char *) message,0,1); SVGEndDocument(svg_info); xmlFreeParserCtxt(svg_info->parser); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"end SAX"); (void) fclose(file); (void) CloseBlob(image); image->columns=svg_info->width; image->rows=svg_info->height; if (exception->severity >= ErrorException) { svg_info=DestroySVGInfo(svg_info); (void) RelinquishUniqueFileResource(filename); image=DestroyImage(image); return((Image *) NULL); } if (image_info->ping == MagickFalse) { ImageInfo *read_info; /* Draw image. */ image=DestroyImage(image); image=(Image *) NULL; read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); (void) FormatLocaleString(read_info->filename,MaxTextExtent,"mvg:%s", filename); image=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) (void) CopyMagickString(image->filename,image_info->filename, MaxTextExtent); } /* Relinquish resources. */ if (image != (Image *) NULL) { if (svg_info->title != (char *) NULL) (void) SetImageProperty(image,"svg:title",svg_info->title); if (svg_info->comment != (char *) NULL) (void) SetImageProperty(image,"svg:comment",svg_info->comment); } svg_info=DestroySVGInfo(svg_info); (void) RelinquishUniqueFileResource(filename); for (next=GetFirstImageInList(image); next != (Image *) NULL; ) { (void) CopyMagickString(next->filename,image->filename,MaxTextExtent); (void) CopyMagickString(next->magick,image->magick,MaxTextExtent); next=GetNextImageInList(next); } return(GetFirstImageInList(image)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,999
openexr
c3ed4a1db1f39bf4524a644cb2af81dc8cfab33f
FastHufDecoder::enabled() { #if defined(__INTEL_COMPILER) || defined(__GNUC__) // // Enabled for ICC, GCC: // __i386__ -> x86 // __x86_64__ -> 64-bit x86 // #if defined (__i386__) || defined(__x86_64__) return true; #else return false; #endif #elif defined (_MSC_VER) // // Enabled for Visual Studio: // _M_IX86 -> x86 // _M_X64 -> 64bit x86 #if defined (_M_IX86) || defined(_M_X64) return true; #else return false; #endif #else // // Unknown compiler - Be safe and disable. // return false; #endif }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,862
Chrome
7da6c3419fd172405bcece1ae4ec6ec8316cd345
void RenderWidgetHostImpl::DidNavigate(uint32_t next_source_id) { current_content_source_id_ = next_source_id; did_receive_first_frame_after_navigation_ = false; if (enable_surface_synchronization_) { visual_properties_ack_pending_ = false; viz::LocalSurfaceId old_surface_id = view_->GetLocalSurfaceId(); if (view_) view_->DidNavigate(); viz::LocalSurfaceId new_surface_id = view_->GetLocalSurfaceId(); if (old_surface_id == new_surface_id) return; } else { if (last_received_content_source_id_ >= current_content_source_id_) return; } if (!new_content_rendering_timeout_) return; new_content_rendering_timeout_->Start(new_content_rendering_delay_); }
1
CVE-2018-17467
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
Phase: Architecture and Design Strategy: Attack Surface Reduction Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111] Phase: Architecture and Design Strategy: Libraries or Frameworks Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). Phases: Architecture and Design; Implementation Strategy: Attack Surface Reduction Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Effectiveness: High Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings. Phase: Implementation When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined. Phase: Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow. Phase: Implementation Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained. Phase: Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content. Phase: Implementation When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
7,728
gnupg
6be61daac047d8e6aa941eb103f8e71a1d4e3c75
append_quoted (struct stringbuf *sb, const unsigned char *value, size_t length, int skip) { unsigned char tmp[4]; const unsigned char *s = value; size_t n = 0; for (;;) { for (value = s; n+skip < length; n++, s++) { s += skip; n += skip; if (*s < ' ' || *s > 126 || strchr (",+\"\\<>;", *s) ) break; } if (s != value) put_stringbuf_mem_skip (sb, value, s-value, skip); if (n+skip >= length) return; /* ready */ s += skip; n += skip; if ( *s < ' ' || *s > 126 ) { snprintf (tmp, sizeof tmp, "\\%02X", *s); put_stringbuf_mem (sb, tmp, 3); } else { tmp[0] = '\\'; tmp[1] = *s; put_stringbuf_mem (sb, tmp, 2); } n++; s++; } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,107
Chrome
bc1f34b9be509f1404f0bb1ba1947614d5f0bcd1
void MediaInterfaceProxy::OnConnectionError() { DVLOG(1) << __FUNCTION__; DCHECK(thread_checker_.CalledOnValidThread()); interface_factory_ptr_.reset(); }
1
CVE-2015-1280
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
8,175
Chrome
3475f5e448ddf5e48888f3d0563245cc46e3c98b
bool Launcher::IsShowingMenu() const { return launcher_view_->IsShowingMenu(); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,682
rsyslog
afdccceefa30306cf720a27efd5a29bcc5a916c9
if(udpLstnSocks != NULL) { net.closeUDPListenSockets(udpLstnSocks); udpLstnSocks = NULL; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,608
xserver
94f11ca5cf011ef123bd222cabeaef6f424d76ac
tbGetBuffer(unsigned size) { struct textBuffer *tb; tb = &textBuffer[textBufferIndex]; textBufferIndex = (textBufferIndex + 1) % NUM_BUFFER; if (size > tb->size) { free(tb->buffer); tb->buffer = xnfalloc(size); tb->size = size; } return tb->buffer; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,847
libjpeg-turbo
6709e4a0cfa44d4f54ee8ad05753d4aa9260cb91
get_scaled_rgb_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading raw-byte-format PPM files with any maxval */ { ppm_source_ptr source = (ppm_source_ptr) sinfo; register JSAMPROW ptr; register U_CHAR * bufferptr; register JSAMPLE *rescale = source->rescale; JDIMENSION col; if (! ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width)) ERREXIT(cinfo, JERR_INPUT_EOF); ptr = source->pub.buffer[0]; bufferptr = source->iobuffer; for (col = cinfo->image_width; col > 0; col--) { *ptr++ = rescale[UCH(*bufferptr++)]; *ptr++ = rescale[UCH(*bufferptr++)]; *ptr++ = rescale[UCH(*bufferptr++)]; } return 1; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,617
ghostscript
e698d5c11d27212aa1098bc5b1673a3378563092
jbig2_sd_new(Jbig2Ctx *ctx, int n_symbols) { Jbig2SymbolDict *new = NULL; if (n_symbols < 0) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "Negative number of symbols in symbol dict: %d", n_symbols); return NULL; } new = jbig2_new(ctx, Jbig2SymbolDict, 1); if (new != NULL) { new->glyphs = jbig2_new(ctx, Jbig2Image *, n_symbols); new->n_symbols = n_symbols; } else { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "unable to allocate new empty symbol dict"); return NULL; } if (new->glyphs != NULL) { memset(new->glyphs, 0, n_symbols * sizeof(Jbig2Image *)); } else { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "unable to allocate glyphs for new empty symbol dict"); jbig2_free(ctx->allocator, new); return NULL; } return new; }
1
CVE-2016-9601
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
3,517
Chrome
ee86799b2b90cd65e31a42e65fef44c58691285d
htmlParseDoc(const xmlChar *cur, const char *encoding) { return(htmlSAXParseDoc(cur, encoding, NULL, NULL)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,508
Chrome
1dab554a7e795dac34313e2f7dbe4325628d12d4
void RestoreForeignTab(const SessionTab& tab) { StartTabCreation(); Browser* current_browser = browser_ ? browser_ : BrowserList::GetLastActiveWithProfile(profile_); RestoreTab(tab, current_browser->tab_count(), current_browser, true); NotifySessionServiceOfRestoredTabs(current_browser, current_browser->tab_count()); FinishedTabCreation(true, true); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,104
linux
d8316f3991d207fe32881a9ac20241be8fa2bad0
static void vhost_net_ubuf_put_wait_and_free(struct vhost_net_ubuf_ref *ubufs) { vhost_net_ubuf_put_and_wait(ubufs); kfree(ubufs); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,047
Android
04839626ed859623901ebd3a5fd483982186b59d
EBMLHeader::~EBMLHeader() { delete[] m_docType; }
1
CVE-2016-1621
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
6,969
linux
d1442d85cc30ea75f7d399474ca738e0bc96f715
static int em_jmp_far(struct x86_emulate_ctxt *ctxt) { int rc; unsigned short sel; memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2); rc = load_segment_descriptor(ctxt, sel, VCPU_SREG_CS); if (rc != X86EMUL_CONTINUE) return rc; ctxt->_eip = 0; memcpy(&ctxt->_eip, ctxt->src.valptr, ctxt->op_bytes); return X86EMUL_CONTINUE; }
1
CVE-2014-3647
CWE-264
Permissions, Privileges, and Access Controls
Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
Not Found in CWE Page
7,936
linux
1b53cf9815bb4744958d41f3795d5d5a1d365e2d
int fscrypt_setup_filename(struct inode *dir, const struct qstr *iname, int lookup, struct fscrypt_name *fname) { int ret = 0, bigname = 0; memset(fname, 0, sizeof(struct fscrypt_name)); fname->usr_fname = iname; if (!dir->i_sb->s_cop->is_encrypted(dir) || fscrypt_is_dot_dotdot(iname)) { fname->disk_name.name = (unsigned char *)iname->name; fname->disk_name.len = iname->len; return 0; } ret = fscrypt_get_crypt_info(dir); if (ret && ret != -EOPNOTSUPP) return ret; if (dir->i_crypt_info) { ret = fscrypt_fname_alloc_buffer(dir, iname->len, &fname->crypto_buf); if (ret) return ret; ret = fname_encrypt(dir, iname, &fname->crypto_buf); if (ret) goto errout; fname->disk_name.name = fname->crypto_buf.name; fname->disk_name.len = fname->crypto_buf.len; return 0; } if (!lookup) return -ENOKEY; /* * We don't have the key and we are doing a lookup; decode the * user-supplied name */ if (iname->name[0] == '_') bigname = 1; if ((bigname && (iname->len != 33)) || (!bigname && (iname->len > 43))) return -ENOENT; fname->crypto_buf.name = kmalloc(32, GFP_KERNEL); if (fname->crypto_buf.name == NULL) return -ENOMEM; ret = digest_decode(iname->name + bigname, iname->len - bigname, fname->crypto_buf.name); if (ret < 0) { ret = -ENOENT; goto errout; } fname->crypto_buf.len = ret; if (bigname) { memcpy(&fname->hash, fname->crypto_buf.name, 4); memcpy(&fname->minor_hash, fname->crypto_buf.name + 4, 4); } else { fname->disk_name.name = fname->crypto_buf.name; fname->disk_name.len = fname->crypto_buf.len; } return 0; errout: fscrypt_fname_free_buffer(&fname->crypto_buf); return ret; }
1
CVE-2017-7374
CWE-416
Use After Free
The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer.
Phase: Architecture and Design Strategy: Language Selection Choose a language that provides automatic memory management. Phase: Implementation Strategy: Attack Surface Reduction When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy. Effectiveness: Defense in Depth Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution.
1,956
Chrome
58936737b65052775b67b1409b87edbbbc09f72b
bool BlobURLRequestJob::ReadItem() { if (remaining_bytes_ == 0) return true; if (current_item_index_ >= blob_data_->items().size()) { NotifyFailure(net::ERR_FAILED); return false; } int bytes_to_read = ComputeBytesToRead(); if (bytes_to_read == 0) { AdvanceItem(); return ReadItem(); } const BlobData::Item& item = blob_data_->items().at(current_item_index_); if (item.type() == BlobData::Item::TYPE_BYTES) return ReadBytesItem(item, bytes_to_read); if (IsFileType(item.type())) { return ReadFileItem(GetFileStreamReader(current_item_index_), bytes_to_read); } NOTREACHED(); return false; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,058
libsass
f2db04883e5fff4e03777dcc1eb60d4373c45be1
Complex_Selector_Obj Parser::parse_complex_selector(bool chroot) { NESTING_GUARD(nestings); String_Obj reference; lex < block_comment >(); advanceToNextToken(); Complex_Selector_Obj sel = SASS_MEMORY_NEW(Complex_Selector, pstate); if (peek < end_of_file >()) return {}; // parse the left hand side Compound_Selector_Obj lhs; // special case if it starts with combinator ([+~>]) if (!peek_css< class_char < selector_combinator_ops > >()) { // parse the left hand side lhs = parse_compound_selector(); } // parse combinator between lhs and rhs Complex_Selector::Combinator combinator = Complex_Selector::ANCESTOR_OF; if (lex< exactly<'+'> >()) combinator = Complex_Selector::ADJACENT_TO; else if (lex< exactly<'~'> >()) combinator = Complex_Selector::PRECEDES; else if (lex< exactly<'>'> >()) combinator = Complex_Selector::PARENT_OF; else if (lex< sequence < exactly<'/'>, negate < exactly < '*' > > > >()) { // comments are allowed, but not spaces? combinator = Complex_Selector::REFERENCE; if (!lex < re_reference_combinator >()) return {}; reference = SASS_MEMORY_NEW(String_Constant, pstate, lexed); if (!lex < exactly < '/' > >()) return {}; // ToDo: error msg? } if (!lhs && combinator == Complex_Selector::ANCESTOR_OF) return {}; // lex < block_comment >(); sel->head(lhs); sel->combinator(combinator); sel->media_block(last_media_block); if (combinator == Complex_Selector::REFERENCE) sel->reference(reference); // has linfeed after combinator? sel->has_line_break(peek_newline()); // sel->has_line_feed(has_line_feed); // check if we got the abort condition (ToDo: optimize) if (!peek_css< class_char < complex_selector_delims > >()) { // parse next selector in sequence sel->tail(parse_complex_selector(true)); } // add a parent selector if we are not in a root // also skip adding parent ref if we only have refs if (!sel->has_parent_ref() && !chroot) { // create the objects to wrap parent selector reference Compound_Selector_Obj head = SASS_MEMORY_NEW(Compound_Selector, pstate); Parent_Selector* parent = SASS_MEMORY_NEW(Parent_Selector, pstate, false); parent->media_block(last_media_block); head->media_block(last_media_block); // add simple selector head->append(parent); // selector may not have any head yet if (!sel->head()) { sel->head(head); } // otherwise we need to create a new complex selector and set the old one as its tail else { sel = SASS_MEMORY_NEW(Complex_Selector, pstate, Complex_Selector::ANCESTOR_OF, head, sel); sel->media_block(last_media_block); } // peek for linefeed and remember result on head // if (peek_newline()) head->has_line_break(true); } sel->update_pstate(pstate); // complex selector return sel; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,541
FFmpeg
00e8181bd97c834fe60751b0c511d4bb97875f78
static int ac3_sync(uint64_t state, AACAC3ParseContext *hdr_info, int *need_next_header, int *new_frame_start) { int err; union { uint64_t u64; uint8_t u8[8 + AV_INPUT_BUFFER_PADDING_SIZE]; } tmp = { av_be2ne64(state) }; AC3HeaderInfo hdr; GetBitContext gbc; init_get_bits(&gbc, tmp.u8+8-AC3_HEADER_SIZE, 54); err = ff_ac3_parse_header(&gbc, &hdr); if(err < 0) return 0; hdr_info->sample_rate = hdr.sample_rate; hdr_info->bit_rate = hdr.bit_rate; hdr_info->channels = hdr.channels; hdr_info->channel_layout = hdr.channel_layout; hdr_info->samples = hdr.num_blocks * 256; hdr_info->service_type = hdr.bitstream_mode; if (hdr.bitstream_mode == 0x7 && hdr.channels > 1) hdr_info->service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE; if(hdr.bitstream_id>10) hdr_info->codec_id = AV_CODEC_ID_EAC3; else if (hdr_info->codec_id == AV_CODEC_ID_NONE) hdr_info->codec_id = AV_CODEC_ID_AC3; *new_frame_start = (hdr.frame_type != EAC3_FRAME_TYPE_DEPENDENT); *need_next_header = *new_frame_start || (hdr.frame_type != EAC3_FRAME_TYPE_AC3_CONVERT); return hdr.frame_size; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,746
openssl
efbe126e3ebb9123ac9d058aa2bb044261342aaa
static int tls_construct_cke_dhe(SSL *s, unsigned char **p, int *len, int *al) { #ifndef OPENSSL_NO_DH DH *dh_clnt = NULL; const BIGNUM *pub_key; EVP_PKEY *ckey = NULL, *skey = NULL; skey = s->s3->peer_tmp; if (skey == NULL) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR); return 0; } ckey = ssl_generate_pkey(skey); dh_clnt = EVP_PKEY_get0_DH(ckey); if (dh_clnt == NULL || ssl_derive(s, ckey, skey) == 0) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR); EVP_PKEY_free(ckey); return 0; } /* send off the data */ DH_get0_key(dh_clnt, &pub_key, NULL); *len = BN_num_bytes(pub_key); s2n(*len, *p); BN_bn2bin(pub_key, *p); *len += 2; EVP_PKEY_free(ckey); return 1; #else SSLerr(SSL_F_TLS_CONSTRUCT_CKE_DHE, ERR_R_INTERNAL_ERROR); *al = SSL_AD_INTERNAL_ERROR; return 0; #endif }
1
CVE-2017-3730
CWE-476
NULL Pointer Dereference
The product dereferences a pointer that it expects to be valid but is NULL.
Phase: Implementation If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented. Phase: Requirements Select a programming language that is not susceptible to these issues. Phase: Implementation Check the results of all functions that return a value and verify that the value is non-null before acting upon it. Effectiveness: Moderate Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665). Phase: Architecture and Design Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values. Phase: Implementation Explicitly initialize all variables and other data stores, either during declaration or just before the first usage.
8,869
Chrome
d59a4441697f6253e7dc3f7ae5caad6e5fd2c778
static sk_sp<SkImage> unPremulSkImageToPremul(SkImage* input) { SkImageInfo info = SkImageInfo::Make(input->width(), input->height(), kN32_SkColorType, kPremul_SkAlphaType); RefPtr<Uint8Array> dstPixels = copySkImageData(input, info); if (!dstPixels) return nullptr; return newSkImageFromRaster( info, std::move(dstPixels), static_cast<size_t>(input->width()) * info.bytesPerPixel()); }
1
CVE-2016-5209
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]. Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
1,344
exempi
65a8492832b7335ffabd01f5f64d89dec757c260
void ValueChunk::changesAndSize( RIFF_MetaHandler* handler ) { if ( this->newValue.size() != this->oldValue.size() ) { this->hasChange = true; } else if ( strncmp ( this->oldValue.c_str(), this->newValue.c_str(), this->newValue.size() ) != 0 ) { this->hasChange = true; } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,860
git
f66cf96d7c613a8129436a5d76ef7b74ee302436
static void bootstrap_attr_stack(void) { if (!attr_stack) { struct attr_stack *elem; elem = read_attr_from_array(builtin_attr); elem->origin = NULL; elem->prev = attr_stack; attr_stack = elem; if (!is_bare_repository()) { elem = read_attr(GITATTRIBUTES_FILE, 1); elem->origin = strdup(""); elem->prev = attr_stack; attr_stack = elem; debug_push(elem); } elem = read_attr_from_file(git_path(INFOATTRIBUTES_FILE), 1); if (!elem) elem = xcalloc(1, sizeof(*elem)); elem->origin = NULL; elem->prev = attr_stack; attr_stack = elem; } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,918
Android
24d7c408c52143bce7b49de82f3913fd8d1219cf
void WT_Interpolate (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame) { EAS_PCM *pOutputBuffer; EAS_I32 phaseInc; EAS_I32 phaseFrac; EAS_I32 acc0; const EAS_SAMPLE *pSamples; const EAS_SAMPLE *loopEnd; EAS_I32 samp1; EAS_I32 samp2; EAS_I32 numSamples; /* initialize some local variables */ numSamples = pWTIntFrame->numSamples; if (numSamples <= 0) { ALOGE("b/26366256"); return; } pOutputBuffer = pWTIntFrame->pAudioBuffer; loopEnd = (const EAS_SAMPLE*) pWTVoice->loopEnd + 1; pSamples = (const EAS_SAMPLE*) pWTVoice->phaseAccum; /*lint -e{713} truncation is OK */ phaseFrac = pWTVoice->phaseFrac; phaseInc = pWTIntFrame->frame.phaseIncrement; /* fetch adjacent samples */ #if defined(_8_BIT_SAMPLES) /*lint -e{701} <avoid multiply for performance>*/ samp1 = pSamples[0] << 8; /*lint -e{701} <avoid multiply for performance>*/ samp2 = pSamples[1] << 8; #else samp1 = pSamples[0]; samp2 = pSamples[1]; #endif while (numSamples--) { /* linear interpolation */ acc0 = samp2 - samp1; acc0 = acc0 * phaseFrac; /*lint -e{704} <avoid divide>*/ acc0 = samp1 + (acc0 >> NUM_PHASE_FRAC_BITS); /* save new output sample in buffer */ /*lint -e{704} <avoid divide>*/ *pOutputBuffer++ = (EAS_I16)(acc0 >> 2); /* increment phase */ phaseFrac += phaseInc; /*lint -e{704} <avoid divide>*/ acc0 = phaseFrac >> NUM_PHASE_FRAC_BITS; /* next sample */ if (acc0 > 0) { /* advance sample pointer */ pSamples += acc0; phaseFrac = (EAS_I32)((EAS_U32)phaseFrac & PHASE_FRAC_MASK); /* check for loop end */ acc0 = (EAS_I32) (pSamples - loopEnd); if (acc0 >= 0) pSamples = (const EAS_SAMPLE*) pWTVoice->loopStart + acc0; /* fetch new samples */ #if defined(_8_BIT_SAMPLES) /*lint -e{701} <avoid multiply for performance>*/ samp1 = pSamples[0] << 8; /*lint -e{701} <avoid multiply for performance>*/ samp2 = pSamples[1] << 8; #else samp1 = pSamples[0]; samp2 = pSamples[1]; #endif } } /* save pointer and phase */ pWTVoice->phaseAccum = (EAS_U32) pSamples; pWTVoice->phaseFrac = (EAS_U32) phaseFrac; }
1
CVE-2016-0838
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
6,598
php-src
7245bff300d3fa8bacbef7897ff080a6f1c23eba?w=1
SPL_METHOD(SplFileObject, current) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!intern->u.file.current_line && !intern->u.file.current_zval) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } if (intern->u.file.current_line && (!SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || !intern->u.file.current_zval)) { RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1); } else if (intern->u.file.current_zval) { RETURN_ZVAL(intern->u.file.current_zval, 1, 0); } RETURN_FALSE; } /* }}} */ /* {{{ proto int SplFileObject::key()
1
CVE-2016-5770
CWE-190
Integer Overflow or Wraparound
The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number.
Phase: Requirements Ensure that all protocols are strictly defined, such that all out-of-bounds behavior can be identified simply, and require strict conformance to the protocol. Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. If possible, choose a language or compiler that performs automatic bounds checking. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Use libraries or frameworks that make it easier to handle numbers without unexpected consequences. Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [REF-106] Phase: Implementation Strategy: Input Validation Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range. Use unsigned integers where possible. This makes it easier to perform validation for integer overflows. When signed integers are required, ensure that the range check includes minimum values as well as maximum values. Phase: Implementation Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [REF-7] Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation. Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Phase: Implementation Strategy: Compilation or Build Hardening Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system.
977
linux
e4f3aa2e1e67bb48dfbaaf1cad59013d5a5bc276
static int cdrom_slot_status(struct cdrom_device_info *cdi, int slot) { struct cdrom_changer_info *info; int ret; cd_dbg(CD_CHANGER, "entering cdrom_slot_status()\n"); if (cdi->sanyo_slot) return CDS_NO_INFO; info = kmalloc(sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; if ((ret = cdrom_read_mech_status(cdi, info))) goto out_free; if (info->slots[slot].disc_present) ret = CDS_DISC_OK; else ret = CDS_NO_DISC; out_free: kfree(info); return ret; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,952
linux
726bc6b092da4c093eb74d13c07184b18c1af0f1
static int sctp_getsockopt_assoc_stats(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_assoc_stats sas; struct sctp_association *asoc = NULL; /* User must provide at least the assoc id */ if (len < sizeof(sctp_assoc_t)) return -EINVAL; if (copy_from_user(&sas, optval, len)) return -EFAULT; asoc = sctp_id2assoc(sk, sas.sas_assoc_id); if (!asoc) return -EINVAL; sas.sas_rtxchunks = asoc->stats.rtxchunks; sas.sas_gapcnt = asoc->stats.gapcnt; sas.sas_outofseqtsns = asoc->stats.outofseqtsns; sas.sas_osacks = asoc->stats.osacks; sas.sas_isacks = asoc->stats.isacks; sas.sas_octrlchunks = asoc->stats.octrlchunks; sas.sas_ictrlchunks = asoc->stats.ictrlchunks; sas.sas_oodchunks = asoc->stats.oodchunks; sas.sas_iodchunks = asoc->stats.iodchunks; sas.sas_ouodchunks = asoc->stats.ouodchunks; sas.sas_iuodchunks = asoc->stats.iuodchunks; sas.sas_idupchunks = asoc->stats.idupchunks; sas.sas_opackets = asoc->stats.opackets; sas.sas_ipackets = asoc->stats.ipackets; /* New high max rto observed, will return 0 if not a single * RTO update took place. obs_rto_ipaddr will be bogus * in such a case */ sas.sas_maxrto = asoc->stats.max_obs_rto; memcpy(&sas.sas_obs_rto_ipaddr, &asoc->stats.obs_rto_ipaddr, sizeof(struct sockaddr_storage)); /* Mark beginning of a new observation period */ asoc->stats.max_obs_rto = asoc->rto_min; /* Allow the struct to grow and fill in as much as possible */ len = min_t(size_t, len, sizeof(sas)); if (put_user(len, optlen)) return -EFAULT; SCTP_DEBUG_PRINTK("sctp_getsockopt_assoc_stat(%d): %d\n", len, sas.sas_assoc_id); if (copy_to_user(optval, &sas, len)) return -EFAULT; return 0; }
1
CVE-2013-1828
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
Phase: Architecture and Design Strategy: Attack Surface Reduction Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111] Phase: Architecture and Design Strategy: Libraries or Frameworks Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). Phases: Architecture and Design; Implementation Strategy: Attack Surface Reduction Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Effectiveness: High Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings. Phase: Implementation When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined. Phase: Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow. Phase: Implementation Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained. Phase: Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content. Phase: Implementation When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
7,329
linux
9804501fa1228048857910a6bf23e085aade37cc
void __init aarp_proto_init(void) { aarp_dl = register_snap_client(aarp_snap_id, aarp_rcv); if (!aarp_dl) printk(KERN_CRIT "Unable to register AARP with SNAP.\n"); timer_setup(&aarp_timer, aarp_expire_timeout, 0); aarp_timer.expires = jiffies + sysctl_aarp_expiry_time; add_timer(&aarp_timer); register_netdevice_notifier(&aarp_notifier); }
1
CVE-2019-19227
CWE-476
NULL Pointer Dereference
The product dereferences a pointer that it expects to be valid but is NULL.
Phase: Implementation If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented. Phase: Requirements Select a programming language that is not susceptible to these issues. Phase: Implementation Check the results of all functions that return a value and verify that the value is non-null before acting upon it. Effectiveness: Moderate Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665). Phase: Architecture and Design Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values. Phase: Implementation Explicitly initialize all variables and other data stores, either during declaration or just before the first usage.
9,036
polarssl
43c3b28ca6d22f51951e2bd563df039a9f4289ab
static int ssl_parse_signature_algorithms_ext( ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t sig_alg_list_size; const unsigned char *p; const unsigned char *end = buf + len; const int *md_cur; sig_alg_list_size = ( ( buf[0] << 8 ) | ( buf[1] ) ); if( sig_alg_list_size + 2 != len || sig_alg_list_size % 2 != 0 ) { SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* * For now, ignore the SignatureAlgorithm part and rely on offered * ciphersuites only for that part. To be fixed later. * * So, just look at the HashAlgorithm part. */ for( md_cur = md_list(); *md_cur != POLARSSL_MD_NONE; md_cur++ ) { for( p = buf + 2; p < end; p += 2 ) { if( *md_cur == (int) ssl_md_alg_from_hash( p[0] ) ) { ssl->handshake->sig_alg = p[0]; goto have_sig_alg; } } } /* Some key echanges do not need signatures at all */ SSL_DEBUG_MSG( 3, ( "no signature_algorithm in common" ) ); return( 0 ); have_sig_alg: SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext: %d", ssl->handshake->sig_alg ) ); return( 0 ); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,000
oniguruma
d3e402928b6eb3327f8f7d59a9edfa622fec557b
match_at(regex_t* reg, const UChar* str, const UChar* end, const UChar* in_right_range, const UChar* sstart, UChar* sprev, MatchArg* msa) { #if defined(USE_DIRECT_THREADED_CODE) static Operation FinishCode[] = { { .opaddr=&&L_FINISH } }; #else static Operation FinishCode[] = { { OP_FINISH } }; #endif #ifdef USE_THREADED_CODE static const void *opcode_to_label[] = { &&L_FINISH, &&L_END, &&L_EXACT1, &&L_EXACT2, &&L_EXACT3, &&L_EXACT4, &&L_EXACT5, &&L_EXACTN, &&L_EXACTMB2N1, &&L_EXACTMB2N2, &&L_EXACTMB2N3, &&L_EXACTMB2N, &&L_EXACTMB3N, &&L_EXACTMBN, &&L_EXACT1_IC, &&L_EXACTN_IC, &&L_CCLASS, &&L_CCLASS_MB, &&L_CCLASS_MIX, &&L_CCLASS_NOT, &&L_CCLASS_MB_NOT, &&L_CCLASS_MIX_NOT, &&L_ANYCHAR, &&L_ANYCHAR_ML, &&L_ANYCHAR_STAR, &&L_ANYCHAR_ML_STAR, &&L_ANYCHAR_STAR_PEEK_NEXT, &&L_ANYCHAR_ML_STAR_PEEK_NEXT, &&L_WORD, &&L_WORD_ASCII, &&L_NO_WORD, &&L_NO_WORD_ASCII, &&L_WORD_BOUNDARY, &&L_NO_WORD_BOUNDARY, &&L_WORD_BEGIN, &&L_WORD_END, &&L_TEXT_SEGMENT_BOUNDARY, &&L_BEGIN_BUF, &&L_END_BUF, &&L_BEGIN_LINE, &&L_END_LINE, &&L_SEMI_END_BUF, &&L_BEGIN_POSITION, &&L_BACKREF1, &&L_BACKREF2, &&L_BACKREF_N, &&L_BACKREF_N_IC, &&L_BACKREF_MULTI, &&L_BACKREF_MULTI_IC, &&L_BACKREF_WITH_LEVEL, &&L_BACKREF_WITH_LEVEL_IC, &&L_BACKREF_CHECK, &&L_BACKREF_CHECK_WITH_LEVEL, &&L_MEMORY_START, &&L_MEMORY_START_PUSH, &&L_MEMORY_END_PUSH, &&L_MEMORY_END_PUSH_REC, &&L_MEMORY_END, &&L_MEMORY_END_REC, &&L_FAIL, &&L_JUMP, &&L_PUSH, &&L_PUSH_SUPER, &&L_POP_OUT, #ifdef USE_OP_PUSH_OR_JUMP_EXACT &&L_PUSH_OR_JUMP_EXACT1, #endif &&L_PUSH_IF_PEEK_NEXT, &&L_REPEAT, &&L_REPEAT_NG, &&L_REPEAT_INC, &&L_REPEAT_INC_NG, &&L_REPEAT_INC_SG, &&L_REPEAT_INC_NG_SG, &&L_EMPTY_CHECK_START, &&L_EMPTY_CHECK_END, &&L_EMPTY_CHECK_END_MEMST, &&L_EMPTY_CHECK_END_MEMST_PUSH, &&L_PREC_READ_START, &&L_PREC_READ_END, &&L_PREC_READ_NOT_START, &&L_PREC_READ_NOT_END, &&L_ATOMIC_START, &&L_ATOMIC_END, &&L_LOOK_BEHIND, &&L_LOOK_BEHIND_NOT_START, &&L_LOOK_BEHIND_NOT_END, &&L_CALL, &&L_RETURN, &&L_PUSH_SAVE_VAL, &&L_UPDATE_VAR, #ifdef USE_CALLOUT &&L_CALLOUT_CONTENTS, &&L_CALLOUT_NAME, #endif }; #endif int i, n, num_mem, best_len, pop_level; LengthType tlen, tlen2; MemNumType mem; RelAddrType addr; UChar *s, *q, *ps, *sbegin; UChar *right_range; int is_alloca; char *alloc_base; StackType *stk_base, *stk, *stk_end; StackType *stkp; /* used as any purpose. */ StackIndex si; StackIndex *repeat_stk; StackIndex *mem_start_stk, *mem_end_stk; UChar* keep; #ifdef USE_RETRY_LIMIT_IN_MATCH unsigned long retry_limit_in_match; unsigned long retry_in_match_counter; #endif #ifdef USE_CALLOUT int of; #endif Operation* p = reg->ops; OnigOptionType option = reg->options; OnigEncoding encode = reg->enc; OnigCaseFoldType case_fold_flag = reg->case_fold_flag; #ifdef ONIG_DEBUG_MATCH static unsigned int counter = 1; #endif #ifdef USE_DIRECT_THREADED_CODE if (IS_NULL(msa)) { for (i = 0; i < reg->ops_used; i++) { const void* addr; addr = opcode_to_label[reg->ocs[i]]; p->opaddr = addr; p++; } return ONIG_NORMAL; } #endif #ifdef USE_CALLOUT msa->mp->match_at_call_counter++; #endif #ifdef USE_RETRY_LIMIT_IN_MATCH retry_limit_in_match = msa->retry_limit_in_match; #endif pop_level = reg->stack_pop_level; num_mem = reg->num_mem; STACK_INIT(INIT_MATCH_STACK_SIZE); UPDATE_FOR_STACK_REALLOC; for (i = 1; i <= num_mem; i++) { mem_start_stk[i] = mem_end_stk[i] = INVALID_STACK_INDEX; } #ifdef ONIG_DEBUG_MATCH fprintf(stderr, "match_at: str: %p, end: %p, start: %p, sprev: %p\n", str, end, sstart, sprev); fprintf(stderr, "size: %d, start offset: %d\n", (int )(end - str), (int )(sstart - str)); #endif best_len = ONIG_MISMATCH; keep = s = (UChar* )sstart; STACK_PUSH_BOTTOM(STK_ALT, FinishCode); /* bottom stack */ INIT_RIGHT_RANGE; #ifdef USE_RETRY_LIMIT_IN_MATCH retry_in_match_counter = 0; #endif BYTECODE_INTERPRETER_START { CASE_OP(END) n = (int )(s - sstart); if (n > best_len) { OnigRegion* region; #ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE if (IS_FIND_LONGEST(option)) { if (n > msa->best_len) { msa->best_len = n; msa->best_s = (UChar* )sstart; } else goto end_best_len; } #endif best_len = n; region = msa->region; if (region) { if (keep > s) keep = s; #ifdef USE_POSIX_API_REGION_OPTION if (IS_POSIX_REGION(msa->options)) { posix_regmatch_t* rmt = (posix_regmatch_t* )region; rmt[0].rm_so = (regoff_t )(keep - str); rmt[0].rm_eo = (regoff_t )(s - str); for (i = 1; i <= num_mem; i++) { if (mem_end_stk[i] != INVALID_STACK_INDEX) { if (MEM_STATUS_AT(reg->bt_mem_start, i)) rmt[i].rm_so = (regoff_t )(STACK_AT(mem_start_stk[i])->u.mem.pstr - str); else rmt[i].rm_so = (regoff_t )((UChar* )((void* )(mem_start_stk[i])) - str); rmt[i].rm_eo = (regoff_t )((MEM_STATUS_AT(reg->bt_mem_end, i) ? STACK_AT(mem_end_stk[i])->u.mem.pstr : (UChar* )((void* )mem_end_stk[i])) - str); } else { rmt[i].rm_so = rmt[i].rm_eo = ONIG_REGION_NOTPOS; } } } else { #endif /* USE_POSIX_API_REGION_OPTION */ region->beg[0] = (int )(keep - str); region->end[0] = (int )(s - str); for (i = 1; i <= num_mem; i++) { if (mem_end_stk[i] != INVALID_STACK_INDEX) { if (MEM_STATUS_AT(reg->bt_mem_start, i)) region->beg[i] = (int )(STACK_AT(mem_start_stk[i])->u.mem.pstr - str); else region->beg[i] = (int )((UChar* )((void* )mem_start_stk[i]) - str); region->end[i] = (int )((MEM_STATUS_AT(reg->bt_mem_end, i) ? STACK_AT(mem_end_stk[i])->u.mem.pstr : (UChar* )((void* )mem_end_stk[i])) - str); } else { region->beg[i] = region->end[i] = ONIG_REGION_NOTPOS; } } #ifdef USE_CAPTURE_HISTORY if (reg->capture_history != 0) { int r; OnigCaptureTreeNode* node; if (IS_NULL(region->history_root)) { region->history_root = node = history_node_new(); CHECK_NULL_RETURN_MEMERR(node); } else { node = region->history_root; history_tree_clear(node); } node->group = 0; node->beg = (int )(keep - str); node->end = (int )(s - str); stkp = stk_base; r = make_capture_history_tree(region->history_root, &stkp, stk, (UChar* )str, reg); if (r < 0) { best_len = r; /* error code */ goto finish; } } #endif /* USE_CAPTURE_HISTORY */ #ifdef USE_POSIX_API_REGION_OPTION } /* else IS_POSIX_REGION() */ #endif } /* if (region) */ } /* n > best_len */ #ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE end_best_len: #endif SOP_OUT; if (IS_FIND_CONDITION(option)) { if (IS_FIND_NOT_EMPTY(option) && s == sstart) { best_len = ONIG_MISMATCH; goto fail; /* for retry */ } if (IS_FIND_LONGEST(option) && DATA_ENSURE_CHECK1) { goto fail; /* for retry */ } } /* default behavior: return first-matching result. */ goto finish; CASE_OP(EXACT1) DATA_ENSURE(1); ps = p->exact.s; if (*ps != *s) goto fail; s++; INC_OP; NEXT_OUT; CASE_OP(EXACT1_IC) { int len; UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN]; DATA_ENSURE(1); len = ONIGENC_MBC_CASE_FOLD(encode, /* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */ case_fold_flag, &s, end, lowbuf); DATA_ENSURE(0); q = lowbuf; ps = p->exact.s; while (len-- > 0) { if (*ps != *q) goto fail; ps++; q++; } } INC_OP; NEXT_OUT; CASE_OP(EXACT2) DATA_ENSURE(2); ps = p->exact.s; if (*ps != *s) goto fail; ps++; s++; if (*ps != *s) goto fail; sprev = s; s++; INC_OP; JUMP_OUT; CASE_OP(EXACT3) DATA_ENSURE(3); ps = p->exact.s; if (*ps != *s) goto fail; ps++; s++; if (*ps != *s) goto fail; ps++; s++; if (*ps != *s) goto fail; sprev = s; s++; INC_OP; JUMP_OUT; CASE_OP(EXACT4) DATA_ENSURE(4); ps = p->exact.s; if (*ps != *s) goto fail; ps++; s++; if (*ps != *s) goto fail; ps++; s++; if (*ps != *s) goto fail; ps++; s++; if (*ps != *s) goto fail; sprev = s; s++; INC_OP; JUMP_OUT; CASE_OP(EXACT5) DATA_ENSURE(5); ps = p->exact.s; if (*ps != *s) goto fail; ps++; s++; if (*ps != *s) goto fail; ps++; s++; if (*ps != *s) goto fail; ps++; s++; if (*ps != *s) goto fail; ps++; s++; if (*ps != *s) goto fail; sprev = s; s++; INC_OP; JUMP_OUT; CASE_OP(EXACTN) tlen = p->exact_n.n; DATA_ENSURE(tlen); ps = p->exact_n.s; while (tlen-- > 0) { if (*ps++ != *s++) goto fail; } sprev = s - 1; INC_OP; JUMP_OUT; CASE_OP(EXACTN_IC) { int len; UChar *q, *endp, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN]; tlen = p->exact_n.n; ps = p->exact_n.s; endp = ps + tlen; while (ps < endp) { sprev = s; DATA_ENSURE(1); len = ONIGENC_MBC_CASE_FOLD(encode, /* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */ case_fold_flag, &s, end, lowbuf); DATA_ENSURE(0); q = lowbuf; while (len-- > 0) { if (*ps != *q) goto fail; ps++; q++; } } } INC_OP; JUMP_OUT; CASE_OP(EXACTMB2N1) DATA_ENSURE(2); ps = p->exact.s; if (*ps != *s) goto fail; ps++; s++; if (*ps != *s) goto fail; s++; INC_OP; NEXT_OUT; CASE_OP(EXACTMB2N2) DATA_ENSURE(4); ps = p->exact.s; if (*ps != *s) goto fail; ps++; s++; if (*ps != *s) goto fail; ps++; s++; sprev = s; if (*ps != *s) goto fail; ps++; s++; if (*ps != *s) goto fail; s++; INC_OP; JUMP_OUT; CASE_OP(EXACTMB2N3) DATA_ENSURE(6); ps = p->exact.s; if (*ps != *s) goto fail; ps++; s++; if (*ps != *s) goto fail; ps++; s++; if (*ps != *s) goto fail; ps++; s++; if (*ps != *s) goto fail; ps++; s++; sprev = s; if (*ps != *s) goto fail; ps++; s++; if (*ps != *s) goto fail; ps++; s++; INC_OP; JUMP_OUT; CASE_OP(EXACTMB2N) tlen = p->exact_n.n; DATA_ENSURE(tlen * 2); ps = p->exact_n.s; while (tlen-- > 0) { if (*ps != *s) goto fail; ps++; s++; if (*ps != *s) goto fail; ps++; s++; } sprev = s - 2; INC_OP; JUMP_OUT; CASE_OP(EXACTMB3N) tlen = p->exact_n.n; DATA_ENSURE(tlen * 3); ps = p->exact_n.s; while (tlen-- > 0) { if (*ps != *s) goto fail; ps++; s++; if (*ps != *s) goto fail; ps++; s++; if (*ps != *s) goto fail; ps++; s++; } sprev = s - 3; INC_OP; JUMP_OUT; CASE_OP(EXACTMBN) tlen = p->exact_len_n.len; /* mb byte len */ tlen2 = p->exact_len_n.n; /* number of chars */ tlen2 *= tlen; DATA_ENSURE(tlen2); ps = p->exact_len_n.s; while (tlen2-- > 0) { if (*ps != *s) goto fail; ps++; s++; } sprev = s - tlen; INC_OP; JUMP_OUT; CASE_OP(CCLASS) DATA_ENSURE(1); if (BITSET_AT(p->cclass.bsp, *s) == 0) goto fail; s++; INC_OP; NEXT_OUT; CASE_OP(CCLASS_MB) DATA_ENSURE(1); if (! ONIGENC_IS_MBC_HEAD(encode, s)) goto fail; cclass_mb: { OnigCodePoint code; UChar *ss; int mb_len; DATA_ENSURE(1); mb_len = enclen(encode, s); DATA_ENSURE(mb_len); ss = s; s += mb_len; code = ONIGENC_MBC_TO_CODE(encode, ss, s); if (! onig_is_in_code_range(p->cclass_mb.mb, code)) goto fail; } INC_OP; NEXT_OUT; CASE_OP(CCLASS_MIX) DATA_ENSURE(1); if (ONIGENC_IS_MBC_HEAD(encode, s)) { goto cclass_mb; } else { if (BITSET_AT(p->cclass_mix.bsp, *s) == 0) goto fail; s++; } INC_OP; NEXT_OUT; CASE_OP(CCLASS_NOT) DATA_ENSURE(1); if (BITSET_AT(p->cclass.bsp, *s) != 0) goto fail; s += enclen(encode, s); INC_OP; NEXT_OUT; CASE_OP(CCLASS_MB_NOT) DATA_ENSURE(1); if (! ONIGENC_IS_MBC_HEAD(encode, s)) { s++; goto cc_mb_not_success; } cclass_mb_not: { OnigCodePoint code; UChar *ss; int mb_len = enclen(encode, s); if (! DATA_ENSURE_CHECK(mb_len)) { DATA_ENSURE(1); s = (UChar* )end; goto cc_mb_not_success; } ss = s; s += mb_len; code = ONIGENC_MBC_TO_CODE(encode, ss, s); if (onig_is_in_code_range(p->cclass_mb.mb, code)) goto fail; } cc_mb_not_success: INC_OP; NEXT_OUT; CASE_OP(CCLASS_MIX_NOT) DATA_ENSURE(1); if (ONIGENC_IS_MBC_HEAD(encode, s)) { goto cclass_mb_not; } else { if (BITSET_AT(p->cclass_mix.bsp, *s) != 0) goto fail; s++; } INC_OP; NEXT_OUT; CASE_OP(ANYCHAR) DATA_ENSURE(1); n = enclen(encode, s); DATA_ENSURE(n); if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail; s += n; INC_OP; NEXT_OUT; CASE_OP(ANYCHAR_ML) DATA_ENSURE(1); n = enclen(encode, s); DATA_ENSURE(n); s += n; INC_OP; NEXT_OUT; CASE_OP(ANYCHAR_STAR) INC_OP; while (DATA_ENSURE_CHECK1) { STACK_PUSH_ALT(p, s, sprev); n = enclen(encode, s); DATA_ENSURE(n); if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail; sprev = s; s += n; } JUMP_OUT; CASE_OP(ANYCHAR_ML_STAR) INC_OP; while (DATA_ENSURE_CHECK1) { STACK_PUSH_ALT(p, s, sprev); n = enclen(encode, s); if (n > 1) { DATA_ENSURE(n); sprev = s; s += n; } else { sprev = s; s++; } } JUMP_OUT; CASE_OP(ANYCHAR_STAR_PEEK_NEXT) { UChar c; c = p->anychar_star_peek_next.c; INC_OP; while (DATA_ENSURE_CHECK1) { if (c == *s) { STACK_PUSH_ALT(p, s, sprev); } n = enclen(encode, s); DATA_ENSURE(n); if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail; sprev = s; s += n; } } NEXT_OUT; CASE_OP(ANYCHAR_ML_STAR_PEEK_NEXT) { UChar c; c = p->anychar_star_peek_next.c; INC_OP; while (DATA_ENSURE_CHECK1) { if (c == *s) { STACK_PUSH_ALT(p, s, sprev); } n = enclen(encode, s); if (n > 1) { DATA_ENSURE(n); sprev = s; s += n; } else { sprev = s; s++; } } } NEXT_OUT; CASE_OP(WORD) DATA_ENSURE(1); if (! ONIGENC_IS_MBC_WORD(encode, s, end)) goto fail; s += enclen(encode, s); INC_OP; NEXT_OUT; CASE_OP(WORD_ASCII) DATA_ENSURE(1); if (! ONIGENC_IS_MBC_WORD_ASCII(encode, s, end)) goto fail; s += enclen(encode, s); INC_OP; NEXT_OUT; CASE_OP(NO_WORD) DATA_ENSURE(1); if (ONIGENC_IS_MBC_WORD(encode, s, end)) goto fail; s += enclen(encode, s); INC_OP; NEXT_OUT; CASE_OP(NO_WORD_ASCII) DATA_ENSURE(1); if (ONIGENC_IS_MBC_WORD_ASCII(encode, s, end)) goto fail; s += enclen(encode, s); INC_OP; NEXT_OUT; CASE_OP(WORD_BOUNDARY) { ModeType mode; mode = p->word_boundary.mode; if (ON_STR_BEGIN(s)) { DATA_ENSURE(1); if (! IS_MBC_WORD_ASCII_MODE(encode, s, end, mode)) goto fail; } else if (ON_STR_END(s)) { if (! IS_MBC_WORD_ASCII_MODE(encode, sprev, end, mode)) goto fail; } else { if (IS_MBC_WORD_ASCII_MODE(encode, s, end, mode) == IS_MBC_WORD_ASCII_MODE(encode, sprev, end, mode)) goto fail; } } INC_OP; JUMP_OUT; CASE_OP(NO_WORD_BOUNDARY) { ModeType mode; mode = p->word_boundary.mode; if (ON_STR_BEGIN(s)) { if (DATA_ENSURE_CHECK1 && IS_MBC_WORD_ASCII_MODE(encode, s, end, mode)) goto fail; } else if (ON_STR_END(s)) { if (IS_MBC_WORD_ASCII_MODE(encode, sprev, end, mode)) goto fail; } else { if (IS_MBC_WORD_ASCII_MODE(encode, s, end, mode) != IS_MBC_WORD_ASCII_MODE(encode, sprev, end, mode)) goto fail; } } INC_OP; JUMP_OUT; #ifdef USE_WORD_BEGIN_END CASE_OP(WORD_BEGIN) { ModeType mode; mode = p->word_boundary.mode; if (DATA_ENSURE_CHECK1 && IS_MBC_WORD_ASCII_MODE(encode, s, end, mode)) { if (ON_STR_BEGIN(s) || !IS_MBC_WORD_ASCII_MODE(encode, sprev, end, mode)) { INC_OP; JUMP_OUT; } } } goto fail; CASE_OP(WORD_END) { ModeType mode; mode = p->word_boundary.mode; if (!ON_STR_BEGIN(s) && IS_MBC_WORD_ASCII_MODE(encode, sprev, end, mode)) { if (ON_STR_END(s) || ! IS_MBC_WORD_ASCII_MODE(encode, s, end, mode)) { INC_OP; JUMP_OUT; } } } goto fail; #endif CASE_OP(TEXT_SEGMENT_BOUNDARY) { int is_break; switch (p->text_segment_boundary.type) { case EXTENDED_GRAPHEME_CLUSTER_BOUNDARY: is_break = onigenc_egcb_is_break_position(encode, s, sprev, str, end); break; #ifdef USE_UNICODE_WORD_BREAK case WORD_BOUNDARY: is_break = onigenc_wb_is_break_position(encode, s, sprev, str, end); break; #endif default: goto bytecode_error; break; } if (p->text_segment_boundary.not != 0) is_break = ! is_break; if (is_break != 0) { INC_OP; JUMP_OUT; } else { goto fail; } } CASE_OP(BEGIN_BUF) if (! ON_STR_BEGIN(s)) goto fail; INC_OP; JUMP_OUT; CASE_OP(END_BUF) if (! ON_STR_END(s)) goto fail; INC_OP; JUMP_OUT; CASE_OP(BEGIN_LINE) if (ON_STR_BEGIN(s)) { if (IS_NOTBOL(msa->options)) goto fail; INC_OP; JUMP_OUT; } else if (ONIGENC_IS_MBC_NEWLINE(encode, sprev, end) && !ON_STR_END(s)) { INC_OP; JUMP_OUT; } goto fail; CASE_OP(END_LINE) if (ON_STR_END(s)) { #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) { #endif if (IS_NOTEOL(msa->options)) goto fail; INC_OP; JUMP_OUT; #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE } #endif } else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) { INC_OP; JUMP_OUT; } #ifdef USE_CRNL_AS_LINE_TERMINATOR else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) { INC_OP; JUMP_OUT; } #endif goto fail; CASE_OP(SEMI_END_BUF) if (ON_STR_END(s)) { #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) { #endif if (IS_NOTEOL(msa->options)) goto fail; INC_OP; JUMP_OUT; #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE } #endif } else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end) && ON_STR_END(s + enclen(encode, s))) { INC_OP; JUMP_OUT; } #ifdef USE_CRNL_AS_LINE_TERMINATOR else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) { UChar* ss = s + enclen(encode, s); ss += enclen(encode, ss); if (ON_STR_END(ss)) { INC_OP; JUMP_OUT; } } #endif goto fail; CASE_OP(BEGIN_POSITION) if (s != msa->start) goto fail; INC_OP; JUMP_OUT; CASE_OP(MEMORY_START_PUSH) mem = p->memory_start.num; STACK_PUSH_MEM_START(mem, s); INC_OP; JUMP_OUT; CASE_OP(MEMORY_START) mem = p->memory_start.num; mem_start_stk[mem] = (StackIndex )((void* )s); INC_OP; JUMP_OUT; CASE_OP(MEMORY_END_PUSH) mem = p->memory_end.num; STACK_PUSH_MEM_END(mem, s); INC_OP; JUMP_OUT; CASE_OP(MEMORY_END) mem = p->memory_end.num; mem_end_stk[mem] = (StackIndex )((void* )s); INC_OP; JUMP_OUT; #ifdef USE_CALL CASE_OP(MEMORY_END_PUSH_REC) mem = p->memory_end.num; STACK_GET_MEM_START(mem, stkp); /* should be before push mem-end. */ si = GET_STACK_INDEX(stkp); STACK_PUSH_MEM_END(mem, s); mem_start_stk[mem] = si; INC_OP; JUMP_OUT; CASE_OP(MEMORY_END_REC) mem = p->memory_end.num; mem_end_stk[mem] = (StackIndex )((void* )s); STACK_GET_MEM_START(mem, stkp); if (MEM_STATUS_AT(reg->bt_mem_start, mem)) mem_start_stk[mem] = GET_STACK_INDEX(stkp); else mem_start_stk[mem] = (StackIndex )((void* )stkp->u.mem.pstr); STACK_PUSH_MEM_END_MARK(mem); INC_OP; JUMP_OUT; #endif CASE_OP(BACKREF1) mem = 1; goto backref; CASE_OP(BACKREF2) mem = 2; goto backref; CASE_OP(BACKREF_N) mem = p->backref_n.n1; backref: { int len; UChar *pstart, *pend; if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail; if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail; if (MEM_STATUS_AT(reg->bt_mem_start, mem)) pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr; else pstart = (UChar* )((void* )mem_start_stk[mem]); pend = (MEM_STATUS_AT(reg->bt_mem_end, mem) ? STACK_AT(mem_end_stk[mem])->u.mem.pstr : (UChar* )((void* )mem_end_stk[mem])); n = (int )(pend - pstart); if (n != 0) { DATA_ENSURE(n); sprev = s; STRING_CMP(s, pstart, n); while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; } } INC_OP; JUMP_OUT; CASE_OP(BACKREF_N_IC) mem = p->backref_n.n1; { int len; UChar *pstart, *pend; if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail; if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail; if (MEM_STATUS_AT(reg->bt_mem_start, mem)) pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr; else pstart = (UChar* )((void* )mem_start_stk[mem]); pend = (MEM_STATUS_AT(reg->bt_mem_end, mem) ? STACK_AT(mem_end_stk[mem])->u.mem.pstr : (UChar* )((void* )mem_end_stk[mem])); n = (int )(pend - pstart); if (n != 0) { DATA_ENSURE(n); sprev = s; STRING_CMP_IC(case_fold_flag, pstart, &s, n); while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; } } INC_OP; JUMP_OUT; CASE_OP(BACKREF_MULTI) { int len, is_fail; UChar *pstart, *pend, *swork; tlen = p->backref_general.num; for (i = 0; i < tlen; i++) { mem = tlen == 1 ? p->backref_general.n1 : p->backref_general.ns[i]; if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue; if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue; if (MEM_STATUS_AT(reg->bt_mem_start, mem)) pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr; else pstart = (UChar* )((void* )mem_start_stk[mem]); pend = (MEM_STATUS_AT(reg->bt_mem_end, mem) ? STACK_AT(mem_end_stk[mem])->u.mem.pstr : (UChar* )((void* )mem_end_stk[mem])); n = (int )(pend - pstart); if (n != 0) { DATA_ENSURE(n); sprev = s; swork = s; STRING_CMP_VALUE(swork, pstart, n, is_fail); if (is_fail) continue; s = swork; while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; } break; /* success */ } if (i == tlen) goto fail; } INC_OP; JUMP_OUT; CASE_OP(BACKREF_MULTI_IC) { int len, is_fail; UChar *pstart, *pend, *swork; tlen = p->backref_general.num; for (i = 0; i < tlen; i++) { mem = tlen == 1 ? p->backref_general.n1 : p->backref_general.ns[i]; if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue; if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue; if (MEM_STATUS_AT(reg->bt_mem_start, mem)) pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr; else pstart = (UChar* )((void* )mem_start_stk[mem]); pend = (MEM_STATUS_AT(reg->bt_mem_end, mem) ? STACK_AT(mem_end_stk[mem])->u.mem.pstr : (UChar* )((void* )mem_end_stk[mem])); n = (int )(pend - pstart); if (n != 0) { DATA_ENSURE(n); sprev = s; swork = s; STRING_CMP_VALUE_IC(case_fold_flag, pstart, &swork, n, is_fail); if (is_fail) continue; s = swork; while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; } break; /* success */ } if (i == tlen) goto fail; } INC_OP; JUMP_OUT; #ifdef USE_BACKREF_WITH_LEVEL CASE_OP(BACKREF_WITH_LEVEL_IC) n = 1; /* ignore case */ goto backref_with_level; CASE_OP(BACKREF_WITH_LEVEL) { int len; int level; MemNumType* mems; UChar* ssave; n = 0; backref_with_level: level = p->backref_general.nest_level; tlen = p->backref_general.num; mems = tlen == 1 ? &(p->backref_general.n1) : p->backref_general.ns; ssave = s; if (backref_match_at_nested_level(reg, stk, stk_base, n, case_fold_flag, level, (int )tlen, mems, &s, end)) { if (ssave != s) { sprev = ssave; while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; } } else goto fail; } INC_OP; JUMP_OUT; #endif CASE_OP(BACKREF_CHECK) { MemNumType* mems; tlen = p->backref_general.num; mems = tlen == 1 ? &(p->backref_general.n1) : p->backref_general.ns; for (i = 0; i < tlen; i++) { mem = mems[i]; if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue; if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue; break; /* success */ } if (i == tlen) goto fail; } INC_OP; JUMP_OUT; #ifdef USE_BACKREF_WITH_LEVEL CASE_OP(BACKREF_CHECK_WITH_LEVEL) { LengthType level; MemNumType* mems; level = p->backref_general.nest_level; tlen = p->backref_general.num; mems = tlen == 1 ? &(p->backref_general.n1) : p->backref_general.ns; if (backref_check_at_nested_level(reg, stk, stk_base, (int )level, (int )tlen, mems) == 0) goto fail; } INC_OP; JUMP_OUT; #endif CASE_OP(EMPTY_CHECK_START) mem = p->empty_check_start.mem; /* mem: null check id */ STACK_PUSH_EMPTY_CHECK_START(mem, s); INC_OP; JUMP_OUT; CASE_OP(EMPTY_CHECK_END) { int is_empty; mem = p->empty_check_end.mem; /* mem: null check id */ STACK_EMPTY_CHECK(is_empty, mem, s); INC_OP; if (is_empty) { #ifdef ONIG_DEBUG_MATCH fprintf(stderr, "EMPTY_CHECK_END: skip id:%d, s:%p\n", (int )mem, s); #endif empty_check_found: /* empty loop founded, skip next instruction */ #if defined(ONIG_DEBUG) && !defined(USE_DIRECT_THREADED_CODE) switch (p->opcode) { case OP_JUMP: case OP_PUSH: case OP_REPEAT_INC: case OP_REPEAT_INC_NG: case OP_REPEAT_INC_SG: case OP_REPEAT_INC_NG_SG: INC_OP; break; default: goto unexpected_bytecode_error; break; } #else INC_OP; #endif } } JUMP_OUT; #ifdef USE_STUBBORN_CHECK_CAPTURES_IN_EMPTY_REPEAT CASE_OP(EMPTY_CHECK_END_MEMST) { int is_empty; mem = p->empty_check_end.mem; /* mem: null check id */ STACK_EMPTY_CHECK_MEM(is_empty, mem, s, reg); INC_OP; if (is_empty) { #ifdef ONIG_DEBUG_MATCH fprintf(stderr, "EMPTY_CHECK_END_MEM: skip id:%d, s:%p\n", (int)mem, s); #endif if (is_empty == -1) goto fail; goto empty_check_found; } } JUMP_OUT; #endif #ifdef USE_CALL CASE_OP(EMPTY_CHECK_END_MEMST_PUSH) { int is_empty; mem = p->empty_check_end.mem; /* mem: null check id */ #ifdef USE_STUBBORN_CHECK_CAPTURES_IN_EMPTY_REPEAT STACK_EMPTY_CHECK_MEM_REC(is_empty, mem, s, reg); #else STACK_EMPTY_CHECK_REC(is_empty, mem, s); #endif INC_OP; if (is_empty) { #ifdef ONIG_DEBUG_MATCH fprintf(stderr, "EMPTY_CHECK_END_MEM_PUSH: skip id:%d, s:%p\n", (int )mem, s); #endif if (is_empty == -1) goto fail; goto empty_check_found; } else { STACK_PUSH_EMPTY_CHECK_END(mem); } } JUMP_OUT; #endif CASE_OP(JUMP) addr = p->jump.addr; p += addr; CHECK_INTERRUPT_JUMP_OUT; CASE_OP(PUSH) addr = p->push.addr; STACK_PUSH_ALT(p + addr, s, sprev); INC_OP; JUMP_OUT; CASE_OP(PUSH_SUPER) addr = p->push.addr; STACK_PUSH_SUPER_ALT(p + addr, s, sprev); INC_OP; JUMP_OUT; CASE_OP(POP_OUT) STACK_POP_ONE; /* for stop backtrack */ /* CHECK_RETRY_LIMIT_IN_MATCH; */ INC_OP; JUMP_OUT; #ifdef USE_OP_PUSH_OR_JUMP_EXACT CASE_OP(PUSH_OR_JUMP_EXACT1) { UChar c; addr = p->push_or_jump_exact1.addr; c = p->push_or_jump_exact1.c; if (DATA_ENSURE_CHECK1 && c == *s) { STACK_PUSH_ALT(p + addr, s, sprev); INC_OP; JUMP_OUT; } } p += addr; JUMP_OUT; #endif CASE_OP(PUSH_IF_PEEK_NEXT) { UChar c; addr = p->push_if_peek_next.addr; c = p->push_if_peek_next.c; if (c == *s) { STACK_PUSH_ALT(p + addr, s, sprev); INC_OP; JUMP_OUT; } } INC_OP; JUMP_OUT; CASE_OP(REPEAT) mem = p->repeat.id; /* mem: OP_REPEAT ID */ addr = p->repeat.addr; STACK_ENSURE(1); repeat_stk[mem] = GET_STACK_INDEX(stk); STACK_PUSH_REPEAT(mem, p + 1); if (reg->repeat_range[mem].lower == 0) { STACK_PUSH_ALT(p + addr, s, sprev); } INC_OP; JUMP_OUT; CASE_OP(REPEAT_NG) mem = p->repeat.id; /* mem: OP_REPEAT ID */ addr = p->repeat.addr; STACK_ENSURE(1); repeat_stk[mem] = GET_STACK_INDEX(stk); STACK_PUSH_REPEAT(mem, p + 1); if (reg->repeat_range[mem].lower == 0) { STACK_PUSH_ALT(p + 1, s, sprev); p += addr; } else INC_OP; JUMP_OUT; CASE_OP(REPEAT_INC) mem = p->repeat_inc.id; /* mem: OP_REPEAT ID */ si = repeat_stk[mem]; stkp = STACK_AT(si); repeat_inc: stkp->u.repeat.count++; if (stkp->u.repeat.count >= reg->repeat_range[mem].upper) { /* end of repeat. Nothing to do. */ INC_OP; } else if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) { INC_OP; STACK_PUSH_ALT(p, s, sprev); p = STACK_AT(si)->u.repeat.pcode; /* Don't use stkp after PUSH. */ } else { p = stkp->u.repeat.pcode; } STACK_PUSH_REPEAT_INC(si); CHECK_INTERRUPT_JUMP_OUT; CASE_OP(REPEAT_INC_SG) mem = p->repeat_inc.id; /* mem: OP_REPEAT ID */ STACK_GET_REPEAT(mem, stkp); si = GET_STACK_INDEX(stkp); goto repeat_inc; CASE_OP(REPEAT_INC_NG) mem = p->repeat_inc.id; /* mem: OP_REPEAT ID */ si = repeat_stk[mem]; stkp = STACK_AT(si); repeat_inc_ng: stkp->u.repeat.count++; if (stkp->u.repeat.count < reg->repeat_range[mem].upper) { if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) { Operation* pcode = stkp->u.repeat.pcode; STACK_PUSH_REPEAT_INC(si); STACK_PUSH_ALT(pcode, s, sprev); INC_OP; } else { p = stkp->u.repeat.pcode; STACK_PUSH_REPEAT_INC(si); } } else if (stkp->u.repeat.count == reg->repeat_range[mem].upper) { STACK_PUSH_REPEAT_INC(si); INC_OP; } CHECK_INTERRUPT_JUMP_OUT; CASE_OP(REPEAT_INC_NG_SG) mem = p->repeat_inc.id; /* mem: OP_REPEAT ID */ STACK_GET_REPEAT(mem, stkp); si = GET_STACK_INDEX(stkp); goto repeat_inc_ng; CASE_OP(PREC_READ_START) STACK_PUSH_PREC_READ_START(s, sprev); INC_OP; JUMP_OUT; CASE_OP(PREC_READ_END) STACK_GET_PREC_READ_START(stkp); s = stkp->u.state.pstr; sprev = stkp->u.state.pstr_prev; STACK_PUSH(STK_PREC_READ_END,0,0,0); INC_OP; JUMP_OUT; CASE_OP(PREC_READ_NOT_START) addr = p->prec_read_not_start.addr; STACK_PUSH_ALT_PREC_READ_NOT(p + addr, s, sprev); INC_OP; JUMP_OUT; CASE_OP(PREC_READ_NOT_END) STACK_POP_TIL_ALT_PREC_READ_NOT; goto fail; CASE_OP(ATOMIC_START) STACK_PUSH_TO_VOID_START; INC_OP; JUMP_OUT; CASE_OP(ATOMIC_END) STACK_EXEC_TO_VOID(stkp); INC_OP; JUMP_OUT; CASE_OP(LOOK_BEHIND) tlen = p->look_behind.len; s = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen); if (IS_NULL(s)) goto fail; sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s); INC_OP; JUMP_OUT; CASE_OP(LOOK_BEHIND_NOT_START) addr = p->look_behind_not_start.addr; tlen = p->look_behind_not_start.len; q = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen); if (IS_NULL(q)) { /* too short case -> success. ex. /(?<!XXX)a/.match("a") If you want to change to fail, replace following line. */ p += addr; /* goto fail; */ } else { STACK_PUSH_ALT_LOOK_BEHIND_NOT(p + addr, s, sprev); s = q; sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s); INC_OP; } JUMP_OUT; CASE_OP(LOOK_BEHIND_NOT_END) STACK_POP_TIL_ALT_LOOK_BEHIND_NOT; INC_OP; goto fail; #ifdef USE_CALL CASE_OP(CALL) addr = p->call.addr; INC_OP; STACK_PUSH_CALL_FRAME(p); p = reg->ops + addr; JUMP_OUT; CASE_OP(RETURN) STACK_RETURN(p); STACK_PUSH_RETURN; JUMP_OUT; #endif CASE_OP(PUSH_SAVE_VAL) { SaveType type; type = p->push_save_val.type; mem = p->push_save_val.id; /* mem: save id */ switch ((enum SaveType )type) { case SAVE_KEEP: STACK_PUSH_SAVE_VAL(mem, type, s); break; case SAVE_S: STACK_PUSH_SAVE_VAL_WITH_SPREV(mem, type, s); break; case SAVE_RIGHT_RANGE: STACK_PUSH_SAVE_VAL(mem, SAVE_RIGHT_RANGE, right_range); break; } } INC_OP; JUMP_OUT; CASE_OP(UPDATE_VAR) { UpdateVarType type; enum SaveType save_type; type = p->update_var.type; mem = p->update_var.id; /* mem: save id */ switch ((enum UpdateVarType )type) { case UPDATE_VAR_KEEP_FROM_STACK_LAST: STACK_GET_SAVE_VAL_TYPE_LAST(SAVE_KEEP, keep); break; case UPDATE_VAR_S_FROM_STACK: STACK_GET_SAVE_VAL_TYPE_LAST_ID_WITH_SPREV(SAVE_S, mem, s); break; case UPDATE_VAR_RIGHT_RANGE_FROM_S_STACK: save_type = SAVE_S; goto get_save_val_type_last_id; break; case UPDATE_VAR_RIGHT_RANGE_FROM_STACK: save_type = SAVE_RIGHT_RANGE; get_save_val_type_last_id: STACK_GET_SAVE_VAL_TYPE_LAST_ID(save_type, mem, right_range); break; case UPDATE_VAR_RIGHT_RANGE_INIT: INIT_RIGHT_RANGE; break; } } INC_OP; JUMP_OUT; #ifdef USE_CALLOUT CASE_OP(CALLOUT_CONTENTS) of = ONIG_CALLOUT_OF_CONTENTS; mem = p->callout_contents.num; goto callout_common_entry; BREAK_OUT; CASE_OP(CALLOUT_NAME) { int call_result; int name_id; int in; CalloutListEntry* e; OnigCalloutFunc func; OnigCalloutArgs args; of = ONIG_CALLOUT_OF_NAME; name_id = p->callout_name.id; mem = p->callout_name.num; callout_common_entry: e = onig_reg_callout_list_at(reg, mem); in = e->in; if (of == ONIG_CALLOUT_OF_NAME) { func = onig_get_callout_start_func(reg, mem); } else { name_id = ONIG_NON_NAME_ID; func = msa->mp->progress_callout_of_contents; } if (IS_NOT_NULL(func) && (in & ONIG_CALLOUT_IN_PROGRESS) != 0) { CALLOUT_BODY(func, ONIG_CALLOUT_IN_PROGRESS, name_id, (int )mem, msa->mp->callout_user_data, args, call_result); switch (call_result) { case ONIG_CALLOUT_FAIL: goto fail; break; case ONIG_CALLOUT_SUCCESS: goto retraction_callout2; break; default: /* error code */ if (call_result > 0) { call_result = ONIGERR_INVALID_ARGUMENT; } best_len = call_result; goto finish; break; } } else { retraction_callout2: if ((in & ONIG_CALLOUT_IN_RETRACTION) != 0) { if (of == ONIG_CALLOUT_OF_NAME) { if (IS_NOT_NULL(func)) { STACK_PUSH_CALLOUT_NAME(name_id, mem, func); } } else { func = msa->mp->retraction_callout_of_contents; if (IS_NOT_NULL(func)) { STACK_PUSH_CALLOUT_CONTENTS(mem, func); } } } } } INC_OP; JUMP_OUT; #endif CASE_OP(FINISH) goto finish; #ifdef ONIG_DEBUG_STATISTICS fail: SOP_OUT; goto fail2; #endif CASE_OP(FAIL) #ifdef ONIG_DEBUG_STATISTICS fail2: #else fail: #endif STACK_POP; p = stk->u.state.pcode; s = stk->u.state.pstr; sprev = stk->u.state.pstr_prev; CHECK_RETRY_LIMIT_IN_MATCH; JUMP_OUT; DEFAULT_OP goto bytecode_error; } BYTECODE_INTERPRETER_END; finish: STACK_SAVE; return best_len; #ifdef ONIG_DEBUG stack_error: STACK_SAVE; return ONIGERR_STACK_BUG; #endif bytecode_error: STACK_SAVE; return ONIGERR_UNDEFINED_BYTECODE; #if defined(ONIG_DEBUG) && !defined(USE_DIRECT_THREADED_CODE) unexpected_bytecode_error: STACK_SAVE; return ONIGERR_UNEXPECTED_BYTECODE; #endif #ifdef USE_RETRY_LIMIT_IN_MATCH retry_limit_in_match_over: STACK_SAVE; return ONIGERR_RETRY_LIMIT_IN_MATCH_OVER; #endif }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,514
libxml2
1098c30a040e72a4654968547f415be4e4c40fe7
xmlXIncludeIncludeNode(xmlXIncludeCtxtPtr ctxt, int nr) { xmlNodePtr cur, end, list, tmp; if (ctxt == NULL) return(-1); if ((nr < 0) || (nr >= ctxt->incNr)) return(-1); cur = ctxt->incTab[nr]->ref; if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL)) return(-1); list = ctxt->incTab[nr]->inc; ctxt->incTab[nr]->inc = NULL; ctxt->incTab[nr]->emptyFb = 0; /* * Check against the risk of generating a multi-rooted document */ if ((cur->parent != NULL) && (cur->parent->type != XML_ELEMENT_NODE)) { int nb_elem = 0; tmp = list; while (tmp != NULL) { if (tmp->type == XML_ELEMENT_NODE) nb_elem++; tmp = tmp->next; } if (nb_elem > 1) { xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref, XML_XINCLUDE_MULTIPLE_ROOT, "XInclude error: would result in multiple root nodes\n", NULL); xmlFreeNodeList(list); return(-1); } } if (ctxt->parseFlags & XML_PARSE_NOXINCNODE) { /* * Add the list of nodes */ while (list != NULL) { end = list; list = list->next; xmlAddPrevSibling(cur, end); } xmlUnlinkNode(cur); xmlFreeNode(cur); } else { xmlNodePtr child, next; /* * Change the current node as an XInclude start one, and add an * XInclude end one */ if (ctxt->incTab[nr]->fallback) xmlUnsetProp(cur, BAD_CAST "href"); cur->type = XML_XINCLUDE_START; /* Remove fallback children */ for (child = cur->children; child != NULL; child = next) { next = child->next; xmlUnlinkNode(child); xmlFreeNode(child); } end = xmlNewDocNode(cur->doc, cur->ns, cur->name, NULL); if (end == NULL) { xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref, XML_XINCLUDE_BUILD_FAILED, "failed to build node\n", NULL); xmlFreeNodeList(list); return(-1); } end->type = XML_XINCLUDE_END; xmlAddNextSibling(cur, end); /* * Add the list of nodes */ while (list != NULL) { cur = list; list = list->next; xmlAddPrevSibling(end, cur); } } return(0); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,468
WavPack
36a24c7881427d2e1e4dc1cef58f19eee0d13aec
int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t infilesize, total_samples; DFFFileHeader dff_file_header; DFFChunkHeader dff_chunk_header; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&dff_file_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) || bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) { error_line ("%s is not a valid .DFF file (by total size)!", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("file header indicated length = %lld", dff_file_header.ckDataSize); #endif while (1) { if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) || bcount != sizeof (DFFChunkHeader)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (debug_logging_mode) error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize); if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) { uint32_t version; if (dff_chunk_header.ckDataSize != sizeof (version) || !DoReadFile (infile, &version, sizeof (version), &bcount) || bcount != sizeof (version)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &version, sizeof (version))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&version, "L"); if (debug_logging_mode) error_line ("dsdiff file version = 0x%08x", version); } else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) { char *prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize); if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) || bcount != dff_chunk_header.ckDataSize) { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (prop_chunk); return WAVPACK_SOFT_ERROR; } if (!strncmp (prop_chunk, "SND ", 4)) { char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize; uint16_t numChannels, chansSpecified, chanMask = 0; uint32_t sampleRate; while (eptr - cptr >= sizeof (dff_chunk_header)) { memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header)); cptr += sizeof (dff_chunk_header); WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (eptr - cptr >= dff_chunk_header.ckDataSize) { if (!strncmp (dff_chunk_header.ckID, "FS ", 4) && dff_chunk_header.ckDataSize == 4) { memcpy (&sampleRate, cptr, sizeof (sampleRate)); WavpackBigEndianToNative (&sampleRate, "L"); cptr += dff_chunk_header.ckDataSize; if (debug_logging_mode) error_line ("got sample rate of %u Hz", sampleRate); } else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) { memcpy (&numChannels, cptr, sizeof (numChannels)); WavpackBigEndianToNative (&numChannels, "S"); cptr += sizeof (numChannels); chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4; while (chansSpecified--) { if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4)) chanMask |= 0x1; else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4)) chanMask |= 0x2; else if (!strncmp (cptr, "LS ", 4)) chanMask |= 0x10; else if (!strncmp (cptr, "RS ", 4)) chanMask |= 0x20; else if (!strncmp (cptr, "C ", 4)) chanMask |= 0x4; else if (!strncmp (cptr, "LFE ", 4)) chanMask |= 0x8; else if (debug_logging_mode) error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]); cptr += 4; } if (debug_logging_mode) error_line ("%d channels, mask = 0x%08x", numChannels, chanMask); } else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) { if (strncmp (cptr, "DSD ", 4)) { error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!", cptr [0], cptr [1], cptr [2], cptr [3]); free (prop_chunk); return WAVPACK_SOFT_ERROR; } cptr += dff_chunk_header.ckDataSize; } else { if (debug_logging_mode) error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); cptr += dff_chunk_header.ckDataSize; } } else { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } } if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this DSDIFF file already has channel order information!"); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (chanMask) config->channel_mask = chanMask; config->bits_per_sample = 8; config->bytes_per_sample = 1; config->num_channels = numChannels; config->sample_rate = sampleRate / 8; config->qmode |= QMODE_DSD_MSB_FIRST; } else if (debug_logging_mode) error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes", prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize); free (prop_chunk); } else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) { total_samples = dff_chunk_header.ckDataSize / config->num_channels; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1); char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (debug_logging_mode) error_line ("setting configuration with %lld samples", total_samples); if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; }
1
CVE-2018-7253
CWE-125
Out-of-bounds Read
The product reads data past the end, or before the beginning, of the intended buffer.
Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs. Phase: Architecture and Design Strategy: Language Selection Use a language that provides appropriate memory abstractions.
7,366
php-src
22736b7c56d678f142d5dd21f4996e5819507a2b
_cdf_tole4(uint32_t sv) { uint32_t rv; uint8_t *s = (uint8_t *)(void *)&sv; uint8_t *d = (uint8_t *)(void *)&rv; d[0] = s[3]; d[1] = s[2]; d[2] = s[1]; d[3] = s[0]; return rv; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,170
unixODBC
45ef78e037f578b15fc58938a3a3251655e71d6f#diff-d52750c7ba4e594410438569d8e2963aL24
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; }
1
CVE-2018-7485
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
7,137
Chrome
92afc45a43336c468720a3143e7f2adfa882fa78
void ExtractIMEInfo(const input_method::InputMethodDescriptor& ime, const input_method::InputMethodUtil& util, ash::IMEInfo* info) { info->id = ime.id(); info->name = util.GetInputMethodLongName(ime); info->short_name = util.GetInputMethodShortName(ime); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,429
OpenSC
8fe377e93b4b56060e5bbfb6f3142ceaeca744fa
auth_select_file(struct sc_card *card, const struct sc_path *in_path, struct sc_file **file_out) { struct sc_path path; struct sc_file *tmp_file = NULL; size_t offs, ii; int rv; LOG_FUNC_CALLED(card->ctx); assert(card != NULL && in_path != NULL); memcpy(&path, in_path, sizeof(struct sc_path)); sc_log(card->ctx, "in_path; type=%d, path=%s, out %p", in_path->type, sc_print_path(in_path), file_out); sc_log(card->ctx, "current path; type=%d, path=%s", auth_current_df->path.type, sc_print_path(&auth_current_df->path)); if (auth_current_ef) sc_log(card->ctx, "current file; type=%d, path=%s", auth_current_ef->path.type, sc_print_path(&auth_current_ef->path)); if (path.type == SC_PATH_TYPE_PARENT || path.type == SC_PATH_TYPE_FILE_ID) { sc_file_free(auth_current_ef); auth_current_ef = NULL; rv = iso_ops->select_file(card, &path, &tmp_file); LOG_TEST_RET(card->ctx, rv, "select file failed"); if (!tmp_file) return SC_ERROR_OBJECT_NOT_FOUND; if (path.type == SC_PATH_TYPE_PARENT) { memcpy(&tmp_file->path, &auth_current_df->path, sizeof(struct sc_path)); if (tmp_file->path.len > 2) tmp_file->path.len -= 2; sc_file_free(auth_current_df); sc_file_dup(&auth_current_df, tmp_file); } else { if (tmp_file->type == SC_FILE_TYPE_DF) { sc_concatenate_path(&tmp_file->path, &auth_current_df->path, &path); sc_file_free(auth_current_df); sc_file_dup(&auth_current_df, tmp_file); } else { sc_file_free(auth_current_ef); sc_file_dup(&auth_current_ef, tmp_file); sc_concatenate_path(&auth_current_ef->path, &auth_current_df->path, &path); } } if (file_out) sc_file_dup(file_out, tmp_file); sc_file_free(tmp_file); } else if (path.type == SC_PATH_TYPE_DF_NAME) { rv = iso_ops->select_file(card, &path, NULL); if (rv) { sc_file_free(auth_current_ef); auth_current_ef = NULL; } LOG_TEST_RET(card->ctx, rv, "select file failed"); } else { for (offs = 0; offs < path.len && offs < auth_current_df->path.len; offs += 2) if (path.value[offs] != auth_current_df->path.value[offs] || path.value[offs + 1] != auth_current_df->path.value[offs + 1]) break; sc_log(card->ctx, "offs %"SC_FORMAT_LEN_SIZE_T"u", offs); if (offs && offs < auth_current_df->path.len) { size_t deep = auth_current_df->path.len - offs; sc_log(card->ctx, "deep %"SC_FORMAT_LEN_SIZE_T"u", deep); for (ii=0; ii<deep; ii+=2) { struct sc_path tmp_path; memcpy(&tmp_path, &auth_current_df->path, sizeof(struct sc_path)); tmp_path.type = SC_PATH_TYPE_PARENT; rv = auth_select_file (card, &tmp_path, file_out); LOG_TEST_RET(card->ctx, rv, "select file failed"); } } if (path.len - offs > 0) { struct sc_path tmp_path; memset(&tmp_path, 0, sizeof(struct sc_path)); tmp_path.type = SC_PATH_TYPE_FILE_ID; tmp_path.len = 2; for (ii=0; ii < path.len - offs; ii+=2) { memcpy(tmp_path.value, path.value + offs + ii, 2); rv = auth_select_file(card, &tmp_path, file_out); LOG_TEST_RET(card->ctx, rv, "select file failed"); } } else if (path.len - offs == 0 && file_out) { if (sc_compare_path(&path, &auth_current_df->path)) sc_file_dup(file_out, auth_current_df); else if (auth_current_ef) sc_file_dup(file_out, auth_current_ef); else LOG_TEST_RET(card->ctx, SC_ERROR_INTERNAL, "No current EF"); } } LOG_FUNC_RETURN(card->ctx, 0); }
1
CVE-2018-16427
CWE-125
Out-of-bounds Read
The product reads data past the end, or before the beginning, of the intended buffer.
Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs. Phase: Architecture and Design Strategy: Language Selection Use a language that provides appropriate memory abstractions.
9,398
Chrome
dc7b094a338c6c521f918f478e993f0f74bbea0d
static void IBusBusConnectedCallback(IBusBus* bus, gpointer user_data) { LOG(WARNING) << "IBus connection is recovered."; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->MaybeRestoreConnections(); }
1
CVE-2011-2804
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
Not Found in CWE Page
2,482
optee_os
b60e1cee406a1ff521145ab9534370dfb85dd592
TEE_Result syscall_cryp_obj_populate(unsigned long obj, struct utee_attribute *usr_attrs, unsigned long attr_count) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; const struct tee_cryp_obj_type_props *type_props; TEE_Attribute *attrs = NULL; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* Must be a transient object */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_PARAMETERS; /* Must not be initialized already */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_PARAMETERS; type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) return TEE_ERROR_NOT_IMPLEMENTED; attrs = malloc(sizeof(TEE_Attribute) * attr_count); if (!attrs) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_attrs, attr_count, attrs); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_check_attr(ATTR_USAGE_POPULATE, type_props, attrs, attr_count); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_obj_populate_type(o, type_props, attrs, attr_count); if (res == TEE_SUCCESS) o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; out: free(attrs); return res; }
1
CVE-2019-1010296
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
4,645
tensorflow
9a133d73ae4b4664d22bd1aa6d654fec13c52ee1
explicit DeleteSessionTensorOp(OpKernelConstruction* context) : OpKernel(context) {}
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,821
ghostpdl
863ada11f9a942a622a581312e2be022d9e2a6f7
mj_raster_cmd(int c_id, int in_size, byte* in, byte* buf2, gx_device_printer* pdev, gp_file* prn_stream) { int band_size = 1; /* 1, 8, or 24 */ byte *out = buf2; int width = in_size; int count; byte* in_end = in + in_size; static char colour_number[] = "\004\001\002\000"; /* color ID for MJ700V2C */ byte *inp = in; byte *outp = out; register byte *p, *q; /* specifying a colour */ gp_fputs("\033r",prn_stream); /* secape sequence to specify a color */ gp_fputc(colour_number[c_id], prn_stream); /* end of specifying a colour */ /* Following codes for compression are borrowed from gdevescp.c */ for( p = inp, q = inp + 1 ; q < in_end ; ) { if( *p != *q ) { p += 2; q += 2; } else { /* ** Check behind us, just in case: */ if( p > inp && *p == *(p-1) ) p--; /* ** walk forward, looking for matches: */ for( q++ ; *q == *p && q < in_end ; q++ ) { if( (q-p) >= 128 ) { if( p > inp ) { count = p - inp; while( count > 128 ) { *outp++ = '\177'; memcpy(outp, inp, 128); /* data */ inp += 128; outp += 128; count -= 128; } *outp++ = (char) (count - 1); /* count */ memcpy(outp, inp, count); /* data */ outp += count; } *outp++ = '\201'; /* Repeat 128 times */ *outp++ = *p; p += 128; inp = p; } } if( (q - p) > 2 ) { /* output this sequence */ if( p > inp ) { count = p - inp; while( count > 128 ) { *outp++ = '\177'; memcpy(outp, inp, 128); /* data */ inp += 128; outp += 128; count -= 128; } *outp++ = (char) (count - 1); /* byte count */ memcpy(outp, inp, count); /* data */ outp += count; } count = q - p; *outp++ = (char) (256 - count + 1); *outp++ = *p; p += count; inp = p; } else /* add to non-repeating data list */ p = q; if( q < in_end ) q++; } } /* ** copy remaining part of line: */ if( inp < in_end ) { count = in_end - inp; /* ** If we've had a long run of varying data followed by a ** sequence of repeated data and then hit the end of line, ** it's possible to get data counts > 128. */ while( count > 128 ) { *outp++ = '\177'; memcpy(outp, inp, 128); /* data */ inp += 128; outp += 128; count -= 128; } *outp++ = (char) (count - 1); /* byte count */ memcpy(outp, inp, count); /* data */ outp += count; } /* ** Output data: */ gp_fwrite("\033.\001", 1, 3, prn_stream); if(pdev->y_pixels_per_inch == 720) gp_fputc('\005', prn_stream); else if(pdev->y_pixels_per_inch == 180) gp_fputc('\024', prn_stream); else /* pdev->y_pixels_per_inch == 360 */ gp_fputc('\012', prn_stream); if(pdev->x_pixels_per_inch == 720) gp_fputc('\005', prn_stream); else if(pdev->x_pixels_per_inch == 180) gp_fputc('\024', prn_stream); else /* pdev->x_pixels_per_inch == 360 */ gp_fputc('\012', prn_stream); gp_fputc(band_size, prn_stream); gp_fputc((width << 3) & 0xff, prn_stream); gp_fputc( width >> 5, prn_stream); gp_fwrite(out, 1, (outp - out), prn_stream); gp_fputc('\r', prn_stream); return 0; }
1
CVE-2020-16292
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]. Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
3,431
gpac
98b727637e32d1d4824101d8947e2dbd573d4fc8
static void gf_m2ts_process_pat(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *ses, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status) { GF_M2TS_Program *prog; GF_M2TS_SECTION_ES *pmt; u32 i, nb_progs, evt_type; u32 nb_sections; u32 data_size; unsigned char *data; GF_M2TS_Section *section; /*wait for the last section */ if (!(status&GF_M2TS_TABLE_END)) return; /*skip if already received*/ if (status&GF_M2TS_TABLE_REPEAT) { if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PAT_REPEAT, NULL); return; } nb_sections = gf_list_count(sections); if (nb_sections > 1) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("PAT on multiple sections not supported\n")); } section = (GF_M2TS_Section *)gf_list_get(sections, 0); data = section->data; data_size = section->data_size; if (!(status&GF_M2TS_TABLE_UPDATE) && gf_list_count(ts->programs)) { if (ts->pat->demux_restarted) { ts->pat->demux_restarted = 0; } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("Multiple different PAT on single TS found, ignoring new PAT declaration (table id %d - extended table id %d)\n", table_id, ex_table_id)); } return; } nb_progs = data_size / 4; for (i=0; i<nb_progs; i++) { u16 number, pid; number = (data[0]<<8) | data[1]; pid = (data[2]&0x1f)<<8 | data[3]; data += 4; if (number==0) { if (!ts->nit) { ts->nit = gf_m2ts_section_filter_new(gf_m2ts_process_nit, 0); } } else if (!pid) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("Broken PAT found reserved PID 0, ignoring\n", pid)); } else if (! ts->ess[pid]) { GF_SAFEALLOC(prog, GF_M2TS_Program); if (!prog) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("Fail to allocate program for pid %d\n", pid)); return; } prog->streams = gf_list_new(); prog->pmt_pid = pid; prog->number = number; prog->ts = ts; gf_list_add(ts->programs, prog); GF_SAFEALLOC(pmt, GF_M2TS_SECTION_ES); if (!pmt) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("Fail to allocate pmt filter for pid %d\n", pid)); return; } pmt->flags = GF_M2TS_ES_IS_SECTION; gf_list_add(prog->streams, pmt); pmt->pid = prog->pmt_pid; pmt->program = prog; ts->ess[pmt->pid] = (GF_M2TS_ES *)pmt; pmt->sec = gf_m2ts_section_filter_new(gf_m2ts_process_pmt, 0); } } evt_type = (status&GF_M2TS_TABLE_UPDATE) ? GF_M2TS_EVT_PAT_UPDATE : GF_M2TS_EVT_PAT_FOUND; if (ts->on_event) ts->on_event(ts, evt_type, NULL); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,895
gpac
ce01bd15f711d4575b7424b54b3a395ec64c1784
GF_Err dump_isom_scene(char *file, char *inName, Bool is_final_name, GF_SceneDumpFormat dump_mode, Bool do_log, Bool no_odf_conv) { GF_Err e; GF_SceneManager *ctx; GF_SceneGraph *sg; GF_SceneLoader load; GF_FileType ftype; gf_log_cbk prev_logs = NULL; FILE *logs = NULL; sg = gf_sg_new(); ctx = gf_sm_new(sg); memset(&load, 0, sizeof(GF_SceneLoader)); load.fileName = file; load.ctx = ctx; load.swf_import_flags = swf_flags; if (dump_mode == GF_SM_DUMP_SVG) { load.swf_import_flags |= GF_SM_SWF_USE_SVG; load.svgOutFile = inName; } load.swf_flatten_limit = swf_flatten_angle; ftype = get_file_type_by_ext(file); if (ftype == GF_FILE_TYPE_ISO_MEDIA) { load.isom = gf_isom_open(file, GF_ISOM_OPEN_READ, NULL); if (!load.isom) { e = gf_isom_last_error(NULL); fprintf(stderr, "Error opening file: %s\n", gf_error_to_string(e)); gf_sm_del(ctx); gf_sg_del(sg); return e; } if (no_odf_conv) gf_isom_disable_odf_conversion(load.isom, GF_TRUE); } else if (ftype==GF_FILE_TYPE_LSR_SAF) { load.isom = gf_isom_open("saf_conv", GF_ISOM_WRITE_EDIT, NULL); #ifndef GPAC_DISABLE_MEDIA_IMPORT if (load.isom) { GF_Fraction _frac = {0,0}; e = import_file(load.isom, file, 0, _frac, 0, NULL, NULL, 0); } else #else fprintf(stderr, "Warning: GPAC was compiled without Media Import support\n"); #endif e = gf_isom_last_error(NULL); if (e) { fprintf(stderr, "Error importing file: %s\n", gf_error_to_string(e)); gf_sm_del(ctx); gf_sg_del(sg); if (load.isom) gf_isom_delete(load.isom); return e; } } if (do_log) { char szLog[GF_MAX_PATH]; sprintf(szLog, "%s_dec.logs", inName); logs = gf_fopen(szLog, "wt"); gf_log_set_tool_level(GF_LOG_CODING, GF_LOG_DEBUG); prev_logs = gf_log_set_callback(logs, scene_coding_log); } e = gf_sm_load_init(&load); if (!e) e = gf_sm_load_run(&load); gf_sm_load_done(&load); if (logs) { gf_log_set_tool_level(GF_LOG_CODING, GF_LOG_ERROR); gf_log_set_callback(NULL, prev_logs); gf_fclose(logs); } if (!e && dump_mode != GF_SM_DUMP_SVG) { u32 count = gf_list_count(ctx->streams); if (count) fprintf(stderr, "Scene loaded - dumping %d systems streams\n", count); else fprintf(stderr, "Scene loaded - dumping root scene\n"); e = gf_sm_dump(ctx, inName, is_final_name, dump_mode); } gf_sm_del(ctx); gf_sg_del(sg); if (e) fprintf(stderr, "Error loading scene: %s\n", gf_error_to_string(e)); if (load.isom) gf_isom_delete(load.isom); return e; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,210
jasper
d42b2388f7f8e0332c846675133acea151fc557a
jas_matrix_t *jas_matrix_create(int numrows, int numcols) { jas_matrix_t *matrix; int i; size_t size; matrix = 0; if (numrows < 0 || numcols < 0) { goto error; } if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) { goto error; } matrix->flags_ = 0; matrix->numrows_ = numrows; matrix->numcols_ = numcols; matrix->rows_ = 0; matrix->maxrows_ = numrows; matrix->data_ = 0; matrix->datasize_ = 0; if (!jas_safe_size_mul(numrows, numcols, &size)) { goto error; } matrix->datasize_ = size; if (matrix->maxrows_ > 0) { if (!(matrix->rows_ = jas_alloc2(matrix->maxrows_, sizeof(jas_seqent_t *)))) { goto error; } } if (matrix->datasize_ > 0) { if (!(matrix->data_ = jas_alloc2(matrix->datasize_, sizeof(jas_seqent_t)))) { goto error; } } for (i = 0; i < numrows; ++i) { matrix->rows_[i] = &matrix->data_[i * matrix->numcols_]; } for (i = 0; i < matrix->datasize_; ++i) { matrix->data_[i] = 0; } matrix->xstart_ = 0; matrix->ystart_ = 0; matrix->xend_ = matrix->numcols_; matrix->yend_ = matrix->numrows_; return matrix; error: if (matrix) { jas_matrix_destroy(matrix); } return 0; }
1
CVE-2016-9557
CWE-190
Integer Overflow or Wraparound
The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number.
Phase: Requirements Ensure that all protocols are strictly defined, such that all out-of-bounds behavior can be identified simply, and require strict conformance to the protocol. Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. If possible, choose a language or compiler that performs automatic bounds checking. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Use libraries or frameworks that make it easier to handle numbers without unexpected consequences. Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [REF-106] Phase: Implementation Strategy: Input Validation Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range. Use unsigned integers where possible. This makes it easier to perform validation for integer overflows. When signed integers are required, ensure that the range check includes minimum values as well as maximum values. Phase: Implementation Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [REF-7] Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation. Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Phase: Implementation Strategy: Compilation or Build Hardening Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system.
8,476
augeas
051c73a9a7ffe9e525f6f0a1b8f5198ff8cc6752
static int filter_matches(struct tree *xfm, const char *path) { int found = 0; list_for_each(f, xfm->children) { if (is_incl(f) && fnmatch(f->value, path, fnm_flags) == 0) { found = 1; break; } } if (! found) return 0; list_for_each(f, xfm->children) { if (is_excl(f) && (fnmatch(f->value, path, fnm_flags) == 0)) return 0; } return 1; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,330
Chrome
a4b20ed4917f1f6fc83b6375a48e2c3895d43a8a
GLvoid StubGLGenBuffers(GLsizei n, GLuint* buffers) { glGenBuffersARB(n, buffers); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,760
Chrome
c995d4fe5e96f4d6d4a88b7867279b08e72d2579
bool DataReductionProxySettings::IsDataReductionProxyEnabled() const { if (base::FeatureList::IsEnabled(network::features::kNetworkService) && !params::IsEnabledWithNetworkService()) { return false; } return IsDataSaverEnabledByUser(); }
1
CVE-2016-5199
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
3,849
Android
04e8cd58f075bec5892e369c8deebca9c67e855c
VOID ixheaacd_dct2_64(WORD32 *x, WORD32 *X, ia_qmf_dec_tables_struct *qmf_dec_tables_ptr, WORD16 *filter_states) { ixheaacd_pretwdct2(x, X); ixheaacd_sbr_imdct_using_fft(qmf_dec_tables_ptr->w1024, 32, X, x, qmf_dec_tables_ptr->dig_rev_table2_128, qmf_dec_tables_ptr->dig_rev_table2_128, qmf_dec_tables_ptr->dig_rev_table2_128, qmf_dec_tables_ptr->dig_rev_table2_128); ixheaacd_fftposttw(x, qmf_dec_tables_ptr); ixheaacd_posttwdct2(x, filter_states, qmf_dec_tables_ptr); return; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,827
libxkbcommon
38e1766bc6e20108948aec8a0b222a4bad0254e9
ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr, const char **elem_rtrn, const char **field_rtrn, ExprDef **index_rtrn) { switch (expr->expr.op) { case EXPR_IDENT: *elem_rtrn = NULL; *field_rtrn = xkb_atom_text(ctx, expr->ident.ident); *index_rtrn = NULL; return true; case EXPR_FIELD_REF: *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field); *index_rtrn = NULL; return true; case EXPR_ARRAY_REF: *elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->array_ref.field); *index_rtrn = expr->array_ref.entry; return true; default: break; } log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op); return false; }
1
CVE-2018-15861
CWE-476
NULL Pointer Dereference
The product dereferences a pointer that it expects to be valid but is NULL.
Phase: Implementation If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented. Phase: Requirements Select a programming language that is not susceptible to these issues. Phase: Implementation Check the results of all functions that return a value and verify that the value is non-null before acting upon it. Effectiveness: Moderate Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665). Phase: Architecture and Design Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values. Phase: Implementation Explicitly initialize all variables and other data stores, either during declaration or just before the first usage.
4,606
FreeRDP
6b2bc41935e53b0034fe5948aeeab4f32e80f30f
static BOOL window_order_supported(const rdpSettings* settings, UINT32 fieldFlags) { const UINT32 mask = (WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE | WINDOW_ORDER_FIELD_RP_CONTENT | WINDOW_ORDER_FIELD_ROOT_PARENT); BOOL dresult; if (!settings) return FALSE; /* See [MS-RDPERP] 2.2.1.1.2 Window List Capability Set */ dresult = settings->AllowUnanouncedOrdersFromServer; switch (settings->RemoteWndSupportLevel) { case WINDOW_LEVEL_SUPPORTED_EX: return TRUE; case WINDOW_LEVEL_SUPPORTED: return ((fieldFlags & mask) == 0) || dresult; case WINDOW_LEVEL_NOT_SUPPORTED: return dresult; default: return dresult; } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,365
php-src
c14eb8de974fc8a4d74f3515424c293bc7a40fba
static int exif_process_IFD_in_MAKERNOTE(image_info_type *ImageInfo, char * value_ptr, int value_len, char *offset_base, size_t IFDlength, size_t displacement) { size_t i; int de, section_index = SECTION_MAKERNOTE; int NumDirEntries, old_motorola_intel; #ifdef KALLE_0 int offset_diff; #endif const maker_note_type *maker_note; char *dir_start; int data_len; for (i=0; i<=sizeof(maker_note_array)/sizeof(maker_note_type); i++) { if (i==sizeof(maker_note_array)/sizeof(maker_note_type)) { #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "No maker note data found. Detected maker: %s (length = %d)", ImageInfo->make, strlen(ImageInfo->make)); #endif /* unknown manufacturer, not an error, use it as a string */ return TRUE; } maker_note = maker_note_array+i; /*exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "check (%s,%s)", maker_note->make?maker_note->make:"", maker_note->model?maker_note->model:"");*/ if (maker_note->make && (!ImageInfo->make || strcmp(maker_note->make, ImageInfo->make))) continue; if (maker_note->model && (!ImageInfo->model || strcmp(maker_note->model, ImageInfo->model))) continue; if (maker_note->id_string && value_len >= maker_note->id_string_len && strncmp(maker_note->id_string, value_ptr, maker_note->id_string_len)) continue; break; } if (value_len < 2 || maker_note->offset >= value_len - 1) { /* Do not go past the value end */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "IFD data too short: 0x%04X offset 0x%04X", value_len, maker_note->offset); return FALSE; } dir_start = value_ptr + maker_note->offset; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process %s @x%04X + 0x%04X=%d: %s", exif_get_sectionname(section_index), (int)dir_start-(int)offset_base+maker_note->offset+displacement, value_len, value_len, exif_char_dump(value_ptr, value_len, (int)dir_start-(int)offset_base+maker_note->offset+displacement)); #endif ImageInfo->sections_found |= FOUND_MAKERNOTE; old_motorola_intel = ImageInfo->motorola_intel; switch (maker_note->byte_order) { case MN_ORDER_INTEL: ImageInfo->motorola_intel = 0; break; case MN_ORDER_MOTOROLA: ImageInfo->motorola_intel = 1; break; default: case MN_ORDER_NORMAL: break; } NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); switch (maker_note->offset_mode) { case MN_OFFSET_MAKER: offset_base = value_ptr; data_len = value_len; break; #ifdef KALLE_0 case MN_OFFSET_GUESS: if (maker_note->offset + 10 + 4 >= value_len) { /* Can not read dir_start+10 since it's beyond value end */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "IFD data too short: 0x%04X", value_len); return FALSE; } offset_diff = 2 + NumDirEntries*12 + 4 - php_ifd_get32u(dir_start+10, ImageInfo->motorola_intel); #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Using automatic offset correction: 0x%04X", ((int)dir_start-(int)offset_base+maker_note->offset+displacement) + offset_diff); #endif if (offset_diff < 0 || offset_diff >= value_len ) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "IFD data bad offset: 0x%04X length 0x%04X", offset_diff, value_len); return FALSE; } offset_base = value_ptr + offset_diff; data_len = value_len - offset_diff; break; #endif default: case MN_OFFSET_NORMAL: data_len = value_len; break; } if ((2+NumDirEntries*12) > value_len) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size: 2 + 0x%04X*12 = 0x%04X > 0x%04X", NumDirEntries, 2+NumDirEntries*12, value_len); return FALSE; } if ((dir_start - value_ptr) > value_len - (2+NumDirEntries*12)) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size: 0x%04X > 0x%04X", (dir_start - value_ptr) + (2+NumDirEntries*12), value_len); return FALSE; } for (de=0;de<NumDirEntries;de++) { size_t offset = 2 + 12 * de; if (!exif_process_IFD_TAG(ImageInfo, dir_start + offset, offset_base, data_len - offset, displacement, section_index, 0, maker_note->tag_table)) { return FALSE; } } ImageInfo->motorola_intel = old_motorola_intel; /* NextDirOffset (must be NULL) = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);*/ #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(SECTION_MAKERNOTE)); #endif return TRUE; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,983
dbus
c3223ba6c401ba81df1305851312a47c485e6cd7
_dbus_header_byteswap (DBusHeader *header, int new_order) { if (header->byte_order == new_order) return; _dbus_marshal_byteswap (&_dbus_header_signature_str, 0, header->byte_order, new_order, &header->data, 0); header->byte_order = new_order; }
1
CVE-2011-2200
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
Phase: Architecture and Design Strategy: Attack Surface Reduction Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111] Phase: Architecture and Design Strategy: Libraries or Frameworks Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). Phases: Architecture and Design; Implementation Strategy: Attack Surface Reduction Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Effectiveness: High Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings. Phase: Implementation When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined. Phase: Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow. Phase: Implementation Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained. Phase: Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content. Phase: Implementation When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
1,418
linux
415e3d3e90ce9e18727e8843ae343eda5a58fad6
static int unix_attach_fds(struct scm_cookie *scm, struct sk_buff *skb) { int i; unsigned char max_level = 0; int unix_sock_count = 0; if (too_many_unix_fds(current)) return -ETOOMANYREFS; for (i = scm->fp->count - 1; i >= 0; i--) { struct sock *sk = unix_get_socket(scm->fp->fp[i]); if (sk) { unix_sock_count++; max_level = max(max_level, unix_sk(sk)->recursion_level); } } if (unlikely(max_level > MAX_RECURSION_LEVEL)) return -ETOOMANYREFS; /* * Need to duplicate file references for the sake of garbage * collection. Otherwise a socket in the fps might become a * candidate for GC while the skb is not yet queued. */ UNIXCB(skb).fp = scm_fp_dup(scm->fp); if (!UNIXCB(skb).fp) return -ENOMEM; for (i = scm->fp->count - 1; i >= 0; i--) unix_inflight(scm->fp->fp[i]); return max_level; }
1
CVE-2016-2550
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
Not Found in CWE Page
896
openssl
cca1cd9a3447dd067503e4a85ebd1679ee78a48e
unsigned char *kssl_skip_confound(krb5_enctype etype, unsigned char *a) { int i, conlen; size_t cklen; static size_t *cksumlens = NULL; unsigned char *test_auth; conlen = (etype)? 8: 0; if (!cksumlens && !(cksumlens = populate_cksumlens())) return NULL; for (i=0; (cklen = cksumlens[i]) != 0; i++) { test_auth = a + conlen + cklen; if (kssl_test_confound(test_auth)) return test_auth; } return NULL; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,406
jerryscript
03a8c630f015f63268639d3ed3bf82cff6fa77d8
lexer_parse_number (parser_context_t *context_p) /**< context */ { const uint8_t *source_p = context_p->source_p; const uint8_t *source_end_p = context_p->source_end_p; bool can_be_float = false; size_t length; context_p->token.type = LEXER_LITERAL; context_p->token.literal_is_reserved = false; context_p->token.extra_value = LEXER_NUMBER_DECIMAL; context_p->token.lit_location.char_p = source_p; context_p->token.lit_location.type = LEXER_NUMBER_LITERAL; context_p->token.lit_location.has_escape = false; if (source_p[0] == LIT_CHAR_0 && source_p + 1 < source_end_p) { if (LEXER_TO_ASCII_LOWERCASE (source_p[1]) == LIT_CHAR_LOWERCASE_X) { context_p->token.extra_value = LEXER_NUMBER_HEXADECIMAL; source_p += 2; if (source_p >= source_end_p || !lit_char_is_hex_digit (source_p[0])) { parser_raise_error (context_p, PARSER_ERR_INVALID_HEX_DIGIT); } do { source_p++; } while (source_p < source_end_p && lit_char_is_hex_digit (source_p[0])); } else if (source_p[1] >= LIT_CHAR_0 && source_p[1] <= LIT_CHAR_7) { context_p->token.extra_value = LEXER_NUMBER_OCTAL; if (context_p->status_flags & PARSER_IS_STRICT) { parser_raise_error (context_p, PARSER_ERR_OCTAL_NUMBER_NOT_ALLOWED); } do { source_p++; } while (source_p < source_end_p && source_p[0] >= LIT_CHAR_0 && source_p[0] <= LIT_CHAR_7); if (source_p < source_end_p && source_p[0] >= LIT_CHAR_8 && source_p[0] <= LIT_CHAR_9) { parser_raise_error (context_p, PARSER_ERR_INVALID_NUMBER); } } else if (source_p[1] >= LIT_CHAR_8 && source_p[1] <= LIT_CHAR_9) { parser_raise_error (context_p, PARSER_ERR_INVALID_NUMBER); } else { can_be_float = true; source_p++; } } else { do { source_p++; } while (source_p < source_end_p && source_p[0] >= LIT_CHAR_0 && source_p[0] <= LIT_CHAR_9); can_be_float = true; } if (can_be_float) { if (source_p < source_end_p && source_p[0] == LIT_CHAR_DOT) { source_p++; while (source_p < source_end_p && source_p[0] >= LIT_CHAR_0 && source_p[0] <= LIT_CHAR_9) { source_p++; } } if (source_p < source_end_p && LEXER_TO_ASCII_LOWERCASE (source_p[0]) == LIT_CHAR_LOWERCASE_E) { source_p++; if (source_p < source_end_p && (source_p[0] == LIT_CHAR_PLUS || source_p[0] == LIT_CHAR_MINUS)) { source_p++; } if (source_p >= source_end_p || source_p[0] < LIT_CHAR_0 || source_p[0] > LIT_CHAR_9) { parser_raise_error (context_p, PARSER_ERR_MISSING_EXPONENT); } do { source_p++; } while (source_p < source_end_p && source_p[0] >= LIT_CHAR_0 && source_p[0] <= LIT_CHAR_9); } } if (source_p < source_end_p && (lit_char_is_identifier_start (source_p) || source_p[0] == LIT_CHAR_BACKSLASH)) { parser_raise_error (context_p, PARSER_ERR_IDENTIFIER_AFTER_NUMBER); } length = (size_t) (source_p - context_p->source_p); if (length > PARSER_MAXIMUM_IDENT_LENGTH) { parser_raise_error (context_p, PARSER_ERR_NUMBER_TOO_LONG); } context_p->token.lit_location.length = (uint16_t) length; PARSER_PLUS_EQUAL_LC (context_p->column, length); context_p->source_p = source_p; } /* lexer_parse_number */
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,649
sleuthkit
459ae818fc8dae717549810150de4d191ce158f1
yaffscache_chunk_compare(YaffsCacheChunk *curr, uint32_t addee_obj_id, TSK_OFF_T addee_offset, uint32_t addee_seq_number) { if (curr->ycc_obj_id == addee_obj_id) { if (curr->ycc_seq_number == addee_seq_number) { if (curr->ycc_offset == addee_offset) { return 0; } else if (curr->ycc_offset < addee_offset) { return -1; } else { return 1; } } else if (curr->ycc_seq_number < addee_seq_number) { return -1; } else { return 1; } } else if (curr->ycc_obj_id < addee_obj_id) { return -1; } else { return 1; } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,765
yara
992480c30f75943e9cd6245bb2015c7737f9b661
int _yr_scan_match_callback( uint8_t* match_data, int32_t match_length, int flags, void* args) { CALLBACK_ARGS* callback_args = (CALLBACK_ARGS*) args; YR_STRING* string = callback_args->string; YR_MATCH* new_match; int result = ERROR_SUCCESS; int tidx = callback_args->context->tidx; size_t match_offset = match_data - callback_args->data; match_length += callback_args->forward_matches; if (callback_args->full_word) { if (flags & RE_FLAGS_WIDE) { if (match_offset >= 2 && *(match_data - 1) == 0 && isalnum(*(match_data - 2))) return ERROR_SUCCESS; if (match_offset + match_length + 1 < callback_args->data_size && *(match_data + match_length + 1) == 0 && isalnum(*(match_data + match_length))) return ERROR_SUCCESS; } else { if (match_offset >= 1 && isalnum(*(match_data - 1))) return ERROR_SUCCESS; if (match_offset + match_length < callback_args->data_size && isalnum(*(match_data + match_length))) return ERROR_SUCCESS; } } if (STRING_IS_CHAIN_PART(string)) { result = _yr_scan_verify_chained_string_match( string, callback_args->context, match_data, callback_args->data_base, match_offset, match_length); } else { if (string->matches[tidx].count == 0) { FAIL_ON_ERROR(yr_arena_write_data( callback_args->context->matching_strings_arena, &string, sizeof(string), NULL)); } FAIL_ON_ERROR(yr_arena_allocate_memory( callback_args->context->matches_arena, sizeof(YR_MATCH), (void**) &new_match)); new_match->data_length = yr_min(match_length, MAX_MATCH_DATA); FAIL_ON_ERROR(yr_arena_write_data( callback_args->context->matches_arena, match_data, new_match->data_length, (void**) &new_match->data)); if (result == ERROR_SUCCESS) { new_match->base = callback_args->data_base; new_match->offset = match_offset; new_match->match_length = match_length; new_match->prev = NULL; new_match->next = NULL; FAIL_ON_ERROR(_yr_scan_add_match_to_list( new_match, &string->matches[tidx], STRING_IS_GREEDY_REGEXP(string))); } } return result; }
1
CVE-2017-9465
CWE-125
Out-of-bounds Read
The product reads data past the end, or before the beginning, of the intended buffer.
Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs. Phase: Architecture and Design Strategy: Language Selection Use a language that provides appropriate memory abstractions.
5,502
exiv2
c0ecc2ae36f34462be98623deb85ba1747ae2175
void CiffDirectory::readDirectory(const byte* pData, uint32_t size, ByteOrder byteOrder) { if (size < 4) throw Error(kerCorruptedMetadata); uint32_t o = getULong(pData + size - 4, byteOrder); if ( o > size-2 ) throw Error(kerCorruptedMetadata); uint16_t count = getUShort(pData + o, byteOrder); #ifdef DEBUG std::cout << "Directory at offset " << std::dec << o <<", " << count << " entries \n"; #endif o += 2; if ( static_cast<uint32_t>(count) * 10 > size-o ) throw Error(kerCorruptedMetadata); for (uint16_t i = 0; i < count; ++i) { uint16_t tag = getUShort(pData + o, byteOrder); CiffComponent::AutoPtr m; switch (CiffComponent::typeId(tag)) { case directory: m = CiffComponent::AutoPtr(new CiffDirectory); break; default: m = CiffComponent::AutoPtr(new CiffEntry); break; } m->setDir(this->tag()); m->read(pData, size, o, byteOrder); add(m); o += 10; } } // CiffDirectory::readDirectory
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,520
Chrome
98095c718d7580b5d6715e5bfd8698234ecb4470
void WebGL2RenderingContextBase::framebufferTextureLayer(GLenum target, GLenum attachment, WebGLTexture* texture, GLint level, GLint layer) { if (isContextLost() || !ValidateFramebufferFuncParameters( "framebufferTextureLayer", target, attachment)) return; if (texture && !texture->Validate(ContextGroup(), this)) { SynthesizeGLError(GL_INVALID_VALUE, "framebufferTextureLayer", "no texture or texture not from this context"); return; } GLenum textarget = texture ? texture->GetTarget() : 0; if (texture) { if (textarget != GL_TEXTURE_3D && textarget != GL_TEXTURE_2D_ARRAY) { SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer", "invalid texture type"); return; } if (!ValidateTexFuncLayer("framebufferTextureLayer", textarget, layer)) return; if (!ValidateTexFuncLevel("framebufferTextureLayer", textarget, level)) return; } WebGLFramebuffer* framebuffer_binding = GetFramebufferBinding(target); if (!framebuffer_binding || !framebuffer_binding->Object()) { SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer", "no framebuffer bound"); return; } if (framebuffer_binding && framebuffer_binding->Opaque()) { SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer", "opaque framebuffer bound"); return; } framebuffer_binding->SetAttachmentForBoundFramebuffer( target, attachment, textarget, texture, level, layer); ApplyStencilTest(); }
1
CVE-2018-6154
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
3,434
linux
0926f91083f34d047abc74f1ca4fa6a9c161f7db
int mlx4_register_mac(struct mlx4_dev *dev, u8 port, u64 mac, int *index) { struct mlx4_mac_table *table = &mlx4_priv(dev)->port[port].mac_table; int i, err = 0; int free = -1; mlx4_dbg(dev, "Registering MAC: 0x%llx\n", (unsigned long long) mac); mutex_lock(&table->mutex); for (i = 0; i < MLX4_MAX_MAC_NUM - 1; i++) { if (free < 0 && !table->refs[i]) { free = i; continue; } if (mac == (MLX4_MAC_MASK & be64_to_cpu(table->entries[i]))) { /* MAC already registered, increase refernce count */ *index = i; ++table->refs[i]; goto out; } } if (free < 0) { err = -ENOMEM; goto out; } mlx4_dbg(dev, "Free MAC index is %d\n", free); if (table->total == table->max) { /* No free mac entries */ err = -ENOSPC; goto out; } /* Register new MAC */ table->refs[free] = 1; table->entries[free] = cpu_to_be64(mac | MLX4_MAC_VALID); err = mlx4_set_port_mac_table(dev, port, table->entries); if (unlikely(err)) { mlx4_err(dev, "Failed adding MAC: 0x%llx\n", (unsigned long long) mac); table->refs[free] = 0; table->entries[free] = 0; goto out; } *index = free; ++table->total; out: mutex_unlock(&table->mutex); return err; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,187
linux
263b4509ec4d47e0da3e753f85a39ea12d1eff24
int nfs_writepage(struct page *page, struct writeback_control *wbc) { int ret; ret = nfs_writepage_locked(page, wbc); unlock_page(page); return ret; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,048
libarchive
bfcfe6f04ed20db2504db8a254d1f40a1d84eb28
read_header(struct archive_read *a, struct archive_entry *entry, char head_type) { const void *h; const char *p, *endp; struct rar *rar; struct rar_header rar_header; struct rar_file_header file_header; int64_t header_size; unsigned filename_size, end; char *filename; char *strp; char packed_size[8]; char unp_size[8]; int ttime; struct archive_string_conv *sconv, *fn_sconv; unsigned long crc32_val; int ret = (ARCHIVE_OK), ret2; rar = (struct rar *)(a->format->data); /* Setup a string conversion object for non-rar-unicode filenames. */ sconv = rar->opt_sconv; if (sconv == NULL) { if (!rar->init_default_conversion) { rar->sconv_default = archive_string_default_conversion_for_read( &(a->archive)); rar->init_default_conversion = 1; } sconv = rar->sconv_default; } if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; memcpy(&rar_header, p, sizeof(rar_header)); rar->file_flags = archive_le16dec(rar_header.flags); header_size = archive_le16dec(rar_header.size); if (header_size < (int64_t)sizeof(file_header) + 7) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } crc32_val = crc32(0, (const unsigned char *)p + 2, 7 - 2); __archive_read_consume(a, 7); if (!(rar->file_flags & FHD_SOLID)) { rar->compression_method = 0; rar->packed_size = 0; rar->unp_size = 0; rar->mtime = 0; rar->ctime = 0; rar->atime = 0; rar->arctime = 0; rar->mode = 0; memset(&rar->salt, 0, sizeof(rar->salt)); rar->atime = 0; rar->ansec = 0; rar->ctime = 0; rar->cnsec = 0; rar->mtime = 0; rar->mnsec = 0; rar->arctime = 0; rar->arcnsec = 0; } else { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR solid archive support unavailable."); return (ARCHIVE_FATAL); } if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) return (ARCHIVE_FATAL); /* File Header CRC check. */ crc32_val = crc32(crc32_val, h, (unsigned)(header_size - 7)); if ((crc32_val & 0xffff) != archive_le16dec(rar_header.crc)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Header CRC error"); return (ARCHIVE_FATAL); } /* If no CRC error, Go on parsing File Header. */ p = h; endp = p + header_size - 7; memcpy(&file_header, p, sizeof(file_header)); p += sizeof(file_header); rar->compression_method = file_header.method; ttime = archive_le32dec(file_header.file_time); rar->mtime = get_time(ttime); rar->file_crc = archive_le32dec(file_header.file_crc); if (rar->file_flags & FHD_PASSWORD) { archive_entry_set_is_data_encrypted(entry, 1); rar->has_encrypted_entries = 1; archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR encryption support unavailable."); /* Since it is only the data part itself that is encrypted we can at least extract information about the currently processed entry and don't need to return ARCHIVE_FATAL here. */ /*return (ARCHIVE_FATAL);*/ } if (rar->file_flags & FHD_LARGE) { memcpy(packed_size, file_header.pack_size, 4); memcpy(packed_size + 4, p, 4); /* High pack size */ p += 4; memcpy(unp_size, file_header.unp_size, 4); memcpy(unp_size + 4, p, 4); /* High unpack size */ p += 4; rar->packed_size = archive_le64dec(&packed_size); rar->unp_size = archive_le64dec(&unp_size); } else { rar->packed_size = archive_le32dec(file_header.pack_size); rar->unp_size = archive_le32dec(file_header.unp_size); } if (rar->packed_size < 0 || rar->unp_size < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid sizes specified."); return (ARCHIVE_FATAL); } rar->bytes_remaining = rar->packed_size; /* TODO: RARv3 subblocks contain comments. For now the complete block is * consumed at the end. */ if (head_type == NEWSUB_HEAD) { size_t distance = p - (const char *)h; header_size += rar->packed_size; /* Make sure we have the extended data. */ if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; endp = p + header_size - 7; p += distance; } filename_size = archive_le16dec(file_header.name_size); if (p + filename_size > endp) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid filename size"); return (ARCHIVE_FATAL); } if (rar->filename_allocated < filename_size * 2 + 2) { char *newptr; size_t newsize = filename_size * 2 + 2; newptr = realloc(rar->filename, newsize); if (newptr == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->filename = newptr; rar->filename_allocated = newsize; } filename = rar->filename; memcpy(filename, p, filename_size); filename[filename_size] = '\0'; if (rar->file_flags & FHD_UNICODE) { if (filename_size != strlen(filename)) { unsigned char highbyte, flagbits, flagbyte; unsigned fn_end, offset; end = filename_size; fn_end = filename_size * 2; filename_size = 0; offset = (unsigned)strlen(filename) + 1; highbyte = *(p + offset++); flagbits = 0; flagbyte = 0; while (offset < end && filename_size < fn_end) { if (!flagbits) { flagbyte = *(p + offset++); flagbits = 8; } flagbits -= 2; switch((flagbyte >> flagbits) & 3) { case 0: filename[filename_size++] = '\0'; filename[filename_size++] = *(p + offset++); break; case 1: filename[filename_size++] = highbyte; filename[filename_size++] = *(p + offset++); break; case 2: filename[filename_size++] = *(p + offset + 1); filename[filename_size++] = *(p + offset); offset += 2; break; case 3: { char extra, high; uint8_t length = *(p + offset++); if (length & 0x80) { extra = *(p + offset++); high = (char)highbyte; } else extra = high = 0; length = (length & 0x7f) + 2; while (length && filename_size < fn_end) { unsigned cp = filename_size >> 1; filename[filename_size++] = high; filename[filename_size++] = p[cp] + extra; length--; } } break; } } if (filename_size > fn_end) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid filename"); return (ARCHIVE_FATAL); } filename[filename_size++] = '\0'; /* * Do not increment filename_size here as the computations below * add the space for the terminating NUL explicitly. */ filename[filename_size] = '\0'; /* Decoded unicode form is UTF-16BE, so we have to update a string * conversion object for it. */ if (rar->sconv_utf16be == NULL) { rar->sconv_utf16be = archive_string_conversion_from_charset( &a->archive, "UTF-16BE", 1); if (rar->sconv_utf16be == NULL) return (ARCHIVE_FATAL); } fn_sconv = rar->sconv_utf16be; strp = filename; while (memcmp(strp, "\x00\x00", 2)) { if (!memcmp(strp, "\x00\\", 2)) *(strp + 1) = '/'; strp += 2; } p += offset; } else { /* * If FHD_UNICODE is set but no unicode data, this file name form * is UTF-8, so we have to update a string conversion object for * it accordingly. */ if (rar->sconv_utf8 == NULL) { rar->sconv_utf8 = archive_string_conversion_from_charset( &a->archive, "UTF-8", 1); if (rar->sconv_utf8 == NULL) return (ARCHIVE_FATAL); } fn_sconv = rar->sconv_utf8; while ((strp = strchr(filename, '\\')) != NULL) *strp = '/'; p += filename_size; } } else { fn_sconv = sconv; while ((strp = strchr(filename, '\\')) != NULL) *strp = '/'; p += filename_size; } /* Split file in multivolume RAR. No more need to process header. */ if (rar->filename_save && filename_size == rar->filename_save_size && !memcmp(rar->filename, rar->filename_save, filename_size + 1)) { __archive_read_consume(a, header_size - 7); rar->cursor++; if (rar->cursor >= rar->nodes) { rar->nodes++; if ((rar->dbo = realloc(rar->dbo, sizeof(*rar->dbo) * rar->nodes)) == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->dbo[rar->cursor].header_size = header_size; rar->dbo[rar->cursor].start_offset = -1; rar->dbo[rar->cursor].end_offset = -1; } if (rar->dbo[rar->cursor].start_offset < 0) { rar->dbo[rar->cursor].start_offset = a->filter->position; rar->dbo[rar->cursor].end_offset = rar->dbo[rar->cursor].start_offset + rar->packed_size; } return ret; } rar->filename_save = (char*)realloc(rar->filename_save, filename_size + 1); memcpy(rar->filename_save, rar->filename, filename_size + 1); rar->filename_save_size = filename_size; /* Set info for seeking */ free(rar->dbo); if ((rar->dbo = calloc(1, sizeof(*rar->dbo))) == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->dbo[0].header_size = header_size; rar->dbo[0].start_offset = -1; rar->dbo[0].end_offset = -1; rar->cursor = 0; rar->nodes = 1; if (rar->file_flags & FHD_SALT) { if (p + 8 > endp) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } memcpy(rar->salt, p, 8); p += 8; } if (rar->file_flags & FHD_EXTTIME) { if (read_exttime(p, rar, endp) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } } __archive_read_consume(a, header_size - 7); rar->dbo[0].start_offset = a->filter->position; rar->dbo[0].end_offset = rar->dbo[0].start_offset + rar->packed_size; switch(file_header.host_os) { case OS_MSDOS: case OS_OS2: case OS_WIN32: rar->mode = archive_le32dec(file_header.file_attr); if (rar->mode & FILE_ATTRIBUTE_DIRECTORY) rar->mode = AE_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH; else rar->mode = AE_IFREG; rar->mode |= S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; break; case OS_UNIX: case OS_MAC_OS: case OS_BEOS: rar->mode = archive_le32dec(file_header.file_attr); break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unknown file attributes from RAR file's host OS"); return (ARCHIVE_FATAL); } rar->bytes_uncopied = rar->bytes_unconsumed = 0; rar->lzss.position = rar->offset = 0; rar->offset_seek = 0; rar->dictionary_size = 0; rar->offset_outgoing = 0; rar->br.cache_avail = 0; rar->br.avail_in = 0; rar->crc_calculated = 0; rar->entry_eof = 0; rar->valid = 1; rar->is_ppmd_block = 0; rar->start_new_table = 1; free(rar->unp_buffer); rar->unp_buffer = NULL; rar->unp_offset = 0; rar->unp_buffer_size = UNP_BUFFER_SIZE; memset(rar->lengthtable, 0, sizeof(rar->lengthtable)); __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context); rar->ppmd_valid = rar->ppmd_eod = 0; /* Don't set any archive entries for non-file header types */ if (head_type == NEWSUB_HEAD) return ret; archive_entry_set_mtime(entry, rar->mtime, rar->mnsec); archive_entry_set_ctime(entry, rar->ctime, rar->cnsec); archive_entry_set_atime(entry, rar->atime, rar->ansec); archive_entry_set_size(entry, rar->unp_size); archive_entry_set_mode(entry, rar->mode); if (archive_entry_copy_pathname_l(entry, filename, filename_size, fn_sconv)) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Pathname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Pathname cannot be converted from %s to current locale.", archive_string_conversion_charset_name(fn_sconv)); ret = (ARCHIVE_WARN); } if (((rar->mode) & AE_IFMT) == AE_IFLNK) { /* Make sure a symbolic-link file does not have its body. */ rar->bytes_remaining = 0; archive_entry_set_size(entry, 0); /* Read a symbolic-link name. */ if ((ret2 = read_symlink_stored(a, entry, sconv)) < (ARCHIVE_WARN)) return ret2; if (ret > ret2) ret = ret2; } if (rar->bytes_remaining == 0) rar->entry_eof = 1; return ret; }
1
CVE-2018-1000878
CWE-416
Use After Free
The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer.
Phase: Architecture and Design Strategy: Language Selection Choose a language that provides automatic memory management. Phase: Implementation Strategy: Attack Surface Reduction When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy. Effectiveness: Defense in Depth Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution.
6,972
jasper
6cd1e1d8aff56d0d86d4e7d1e7e3e4dd1c64b55d
static int jpc_enc_encodemainbody(jpc_enc_t *enc) { int tileno; int tilex; int tiley; int i; jpc_sot_t *sot; jpc_enc_tcmpt_t *comp; jpc_enc_tcmpt_t *endcomps; jpc_enc_band_t *band; jpc_enc_band_t *endbands; jpc_enc_rlvl_t *lvl; int rlvlno; jpc_qcc_t *qcc; jpc_cod_t *cod; int adjust; int j; int absbandno; long numbytes; long tilehdrlen; long tilelen; jpc_enc_tile_t *tile; jpc_enc_cp_t *cp; double rho; int lyrno; int cmptno; int samestepsizes; jpc_enc_ccp_t *ccps; jpc_enc_tccp_t *tccp; int bandno; uint_fast32_t x; uint_fast32_t y; int mingbits; int actualnumbps; jpc_fix_t mxmag; jpc_fix_t mag; int numgbits; cp = enc->cp; /* Avoid compile warnings. */ numbytes = 0; for (tileno = 0; tileno < JAS_CAST(int, cp->numtiles); ++tileno) { tilex = tileno % cp->numhtiles; tiley = tileno / cp->numhtiles; if (!(enc->curtile = jpc_enc_tile_create(enc->cp, enc->image, tileno))) { jas_eprintf("cannot create tile\n"); return -1; } tile = enc->curtile; if (jas_getdbglevel() >= 10) { jpc_enc_dump(enc); } endcomps = &tile->tcmpts[tile->numtcmpts]; for (cmptno = 0, comp = tile->tcmpts; cmptno < tile->numtcmpts; ++cmptno, ++comp) { if (!cp->ccps[cmptno].sgnd) { adjust = 1 << (cp->ccps[cmptno].prec - 1); for (i = 0; i < jas_matrix_numrows(comp->data); ++i) { for (j = 0; j < jas_matrix_numcols(comp->data); ++j) { *jas_matrix_getref(comp->data, i, j) -= adjust; } } } } if (!tile->intmode) { endcomps = &tile->tcmpts[tile->numtcmpts]; for (comp = tile->tcmpts; comp != endcomps; ++comp) { jas_matrix_asl(comp->data, JPC_FIX_FRACBITS); } } switch (tile->mctid) { case JPC_MCT_RCT: assert(jas_image_numcmpts(enc->image) == 3); jpc_rct(tile->tcmpts[0].data, tile->tcmpts[1].data, tile->tcmpts[2].data); break; case JPC_MCT_ICT: assert(jas_image_numcmpts(enc->image) == 3); jpc_ict(tile->tcmpts[0].data, tile->tcmpts[1].data, tile->tcmpts[2].data); break; default: break; } for (i = 0; i < jas_image_numcmpts(enc->image); ++i) { comp = &tile->tcmpts[i]; jpc_tsfb_analyze(comp->tsfb, comp->data); } endcomps = &tile->tcmpts[tile->numtcmpts]; for (cmptno = 0, comp = tile->tcmpts; comp != endcomps; ++cmptno, ++comp) { mingbits = 0; absbandno = 0; /* All bands must have a corresponding quantizer step size, even if they contain no samples and are never coded. */ /* Some bands may not be hit by the loop below, so we must initialize all of the step sizes to a sane value. */ memset(comp->stepsizes, 0, sizeof(comp->stepsizes)); for (rlvlno = 0, lvl = comp->rlvls; rlvlno < comp->numrlvls; ++rlvlno, ++lvl) { if (!lvl->bands) { absbandno += rlvlno ? 3 : 1; continue; } endbands = &lvl->bands[lvl->numbands]; for (band = lvl->bands; band != endbands; ++band) { if (!band->data) { ++absbandno; continue; } actualnumbps = 0; mxmag = 0; for (y = 0; y < JAS_CAST(uint_fast32_t, jas_matrix_numrows(band->data)); ++y) { for (x = 0; x < JAS_CAST(uint_fast32_t, jas_matrix_numcols(band->data)); ++x) { mag = JAS_ABS(jas_matrix_get(band->data, y, x)); if (mag > mxmag) { mxmag = mag; } } } if (tile->intmode) { actualnumbps = jpc_fix_firstone(mxmag) + 1; } else { actualnumbps = jpc_fix_firstone(mxmag) + 1 - JPC_FIX_FRACBITS; } numgbits = actualnumbps - (cp->ccps[cmptno].prec - 1 + band->analgain); #if 0 jas_eprintf("%d %d mag=%d actual=%d numgbits=%d\n", cp->ccps[cmptno].prec, band->analgain, mxmag, actualnumbps, numgbits); #endif if (numgbits > mingbits) { mingbits = numgbits; } if (!tile->intmode) { band->absstepsize = jpc_fix_div(jpc_inttofix(1 << (band->analgain + 1)), band->synweight); } else { band->absstepsize = jpc_inttofix(1); } const uint_fast32_t stepsize = jpc_abstorelstepsize( band->absstepsize, cp->ccps[cmptno].prec + band->analgain); if (stepsize == UINT_FAST32_MAX) return -1; band->stepsize = stepsize; band->numbps = cp->tccp.numgbits + JPC_QCX_GETEXPN(band->stepsize) - 1; if ((!tile->intmode) && band->data) { jpc_quantize(band->data, band->absstepsize); } comp->stepsizes[absbandno] = band->stepsize; ++absbandno; } } assert(JPC_FIX_FRACBITS >= JPC_NUMEXTRABITS); if (!tile->intmode) { jas_matrix_divpow2(comp->data, JPC_FIX_FRACBITS - JPC_NUMEXTRABITS); } else { jas_matrix_asl(comp->data, JPC_NUMEXTRABITS); } #if 0 jas_eprintf("mingbits %d\n", mingbits); #endif if (mingbits > cp->tccp.numgbits) { jas_eprintf("error: too few guard bits (need at least %d)\n", mingbits); return -1; } } if (!(enc->tmpstream = jas_stream_memopen(0, 0))) { jas_eprintf("cannot open tmp file\n"); return -1; } /* Write the tile header. */ if (!(enc->mrk = jpc_ms_create(JPC_MS_SOT))) { return -1; } sot = &enc->mrk->parms.sot; sot->len = 0; sot->tileno = tileno; sot->partno = 0; sot->numparts = 1; if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) { jas_eprintf("cannot write SOT marker\n"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; /************************************************************************/ /************************************************************************/ /************************************************************************/ tccp = &cp->tccp; for (cmptno = 0; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno) { comp = &tile->tcmpts[cmptno]; if (comp->numrlvls != tccp->maxrlvls) { if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) { return -1; } /* XXX = this is not really correct. we are using comp #0's precint sizes and other characteristics */ comp = &tile->tcmpts[0]; cod = &enc->mrk->parms.cod; cod->compparms.csty = 0; cod->compparms.numdlvls = comp->numrlvls - 1; cod->prg = tile->prg; cod->numlyrs = tile->numlyrs; cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(comp->cblkwidthexpn); cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(comp->cblkheightexpn); cod->compparms.cblksty = comp->cblksty; cod->compparms.qmfbid = comp->qmfbid; cod->mctrans = (tile->mctid != JPC_MCT_NONE); for (i = 0; i < comp->numrlvls; ++i) { cod->compparms.rlvls[i].parwidthval = comp->rlvls[i].prcwidthexpn; cod->compparms.rlvls[i].parheightval = comp->rlvls[i].prcheightexpn; } if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) { return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; } } for (cmptno = 0, comp = tile->tcmpts; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno, ++comp) { ccps = &cp->ccps[cmptno]; if (JAS_CAST(int, ccps->numstepsizes) == comp->numstepsizes) { samestepsizes = 1; for (bandno = 0; bandno < JAS_CAST(int, ccps->numstepsizes); ++bandno) { if (ccps->stepsizes[bandno] != comp->stepsizes[bandno]) { samestepsizes = 0; break; } } } else { samestepsizes = 0; } if (!samestepsizes) { if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) { return -1; } qcc = &enc->mrk->parms.qcc; qcc->compno = cmptno; qcc->compparms.numguard = cp->tccp.numgbits; qcc->compparms.qntsty = (comp->qmfbid == JPC_COX_INS) ? JPC_QCX_SEQNT : JPC_QCX_NOQNT; qcc->compparms.numstepsizes = comp->numstepsizes; qcc->compparms.stepsizes = comp->stepsizes; if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) { return -1; } qcc->compparms.stepsizes = 0; jpc_ms_destroy(enc->mrk); enc->mrk = 0; } } /* Write a SOD marker to indicate the end of the tile header. */ if (!(enc->mrk = jpc_ms_create(JPC_MS_SOD))) { return -1; } if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) { jas_eprintf("cannot write SOD marker\n"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; tilehdrlen = jas_stream_getrwcount(enc->tmpstream); assert(tilehdrlen >= 0); /************************************************************************/ /************************************************************************/ /************************************************************************/ if (jpc_enc_enccblks(enc)) { abort(); return -1; } cp = enc->cp; rho = (double) (tile->brx - tile->tlx) * (tile->bry - tile->tly) / ((cp->refgrdwidth - cp->imgareatlx) * (cp->refgrdheight - cp->imgareatly)); tile->rawsize = cp->rawsize * rho; for (lyrno = 0; lyrno < tile->numlyrs - 1; ++lyrno) { tile->lyrsizes[lyrno] = tile->rawsize * jpc_fixtodbl( cp->tcp.ilyrrates[lyrno]); } #if !defined(__clang__) // WARNING: // Some versions of Clang (e.g., 3.7.1 and 3.8.1) appear to generate // incorrect code for the following line. tile->lyrsizes[tile->numlyrs - 1] = (cp->totalsize != UINT_FAST32_MAX) ? (rho * enc->mainbodysize) : UINT_FAST32_MAX; #else if (cp->totalsize != UINT_FAST32_MAX) { tile->lyrsizes[tile->numlyrs - 1] = (rho * enc->mainbodysize); } else { tile->lyrsizes[tile->numlyrs - 1] = UINT_FAST32_MAX; } #endif //jas_eprintf("TESTING %ld %ld\n", cp->totalsize != UINT_FAST32_MAX, tile->lyrsizes[0]); for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) { if (tile->lyrsizes[lyrno] != UINT_FAST32_MAX) { if (JAS_CAST(uint_fast32_t, tilehdrlen) <= tile->lyrsizes[lyrno]) { tile->lyrsizes[lyrno] -= tilehdrlen; } else { tile->lyrsizes[lyrno] = 0; } } } if (rateallocate(enc, tile->numlyrs, tile->lyrsizes)) { return -1; } #if 0 jas_eprintf("ENCODE TILE DATA\n"); #endif if (jpc_enc_encodetiledata(enc)) { jas_eprintf("dotile failed\n"); return -1; } /************************************************************************/ /************************************************************************/ /************************************************************************/ /************************************************************************/ /************************************************************************/ /************************************************************************/ tilelen = jas_stream_tell(enc->tmpstream); if (jas_stream_seek(enc->tmpstream, 6, SEEK_SET) < 0) { return -1; } jpc_putuint32(enc->tmpstream, tilelen); if (jas_stream_seek(enc->tmpstream, 0, SEEK_SET) < 0) { return -1; } if (jpc_putdata(enc->out, enc->tmpstream, -1)) { return -1; } enc->len += tilelen; jas_stream_close(enc->tmpstream); enc->tmpstream = 0; jpc_enc_tile_destroy(enc->curtile); enc->curtile = 0; } return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,906
Android
44749eb4f273f0eb681d0fa013e3beef754fa687
SoftAMR::SoftAMR( const char *name, const OMX_CALLBACKTYPE *callbacks, OMX_PTR appData, OMX_COMPONENTTYPE **component) : SimpleSoftOMXComponent(name, callbacks, appData, component), mMode(MODE_NARROW), mState(NULL), mDecoderBuf(NULL), mDecoderCookie(NULL), mInputBufferCount(0), mAnchorTimeUs(0), mNumSamplesOutput(0), mSignalledError(false), mOutputPortSettingsChange(NONE) { if (!strcmp(name, "OMX.google.amrwb.decoder")) { mMode = MODE_WIDE; } else { CHECK(!strcmp(name, "OMX.google.amrnb.decoder")); } initPorts(); CHECK_EQ(initDecoder(), (status_t)OK); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,453
tensorflow
5f7975d09eac0f10ed8a17dbb6f5964977725adc
TEST(FloatPoolingOpTest, MaxPoolActivationRelu1) { FloatPoolingOpModel m(BuiltinOperator_MAX_POOL_2D, /*input=*/{TensorType_FLOAT32, {1, 2, 4, 1}}, /*filter_width=*/2, /*filter_height=*/2, /*output=*/{TensorType_FLOAT32, {}}, Padding_VALID, 2, 2, ActivationFunctionType_RELU_N1_TO_1); m.SetInput({ -2.75, -6, 0.2, 0.4, // -3, -2, -0.3, 0.7, // }); m.Invoke(); EXPECT_THAT(m.GetOutput(), ElementsAreArray({-1.0, 0.7})); m.SetInput({ -2.75, -6, -2, -4, // -3, -2, 10, -7, // }); m.Invoke(); EXPECT_THAT(m.GetOutput(), ElementsAreArray({-1.0, 1.0})); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,053
linux
2dcab598484185dea7ec22219c76dcdd59e3cb90
static int sctp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { int retval = 0; pr_debug("%s: sk:%p, optname:%d\n", __func__, sk, optname); /* I can hardly begin to describe how wrong this is. This is * so broken as to be worse than useless. The API draft * REALLY is NOT helpful here... I am not convinced that the * semantics of setsockopt() with a level OTHER THAN SOL_SCTP * are at all well-founded. */ if (level != SOL_SCTP) { struct sctp_af *af = sctp_sk(sk)->pf->af; retval = af->setsockopt(sk, level, optname, optval, optlen); goto out_nounlock; } lock_sock(sk); switch (optname) { case SCTP_SOCKOPT_BINDX_ADD: /* 'optlen' is the size of the addresses buffer. */ retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval, optlen, SCTP_BINDX_ADD_ADDR); break; case SCTP_SOCKOPT_BINDX_REM: /* 'optlen' is the size of the addresses buffer. */ retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval, optlen, SCTP_BINDX_REM_ADDR); break; case SCTP_SOCKOPT_CONNECTX_OLD: /* 'optlen' is the size of the addresses buffer. */ retval = sctp_setsockopt_connectx_old(sk, (struct sockaddr __user *)optval, optlen); break; case SCTP_SOCKOPT_CONNECTX: /* 'optlen' is the size of the addresses buffer. */ retval = sctp_setsockopt_connectx(sk, (struct sockaddr __user *)optval, optlen); break; case SCTP_DISABLE_FRAGMENTS: retval = sctp_setsockopt_disable_fragments(sk, optval, optlen); break; case SCTP_EVENTS: retval = sctp_setsockopt_events(sk, optval, optlen); break; case SCTP_AUTOCLOSE: retval = sctp_setsockopt_autoclose(sk, optval, optlen); break; case SCTP_PEER_ADDR_PARAMS: retval = sctp_setsockopt_peer_addr_params(sk, optval, optlen); break; case SCTP_DELAYED_SACK: retval = sctp_setsockopt_delayed_ack(sk, optval, optlen); break; case SCTP_PARTIAL_DELIVERY_POINT: retval = sctp_setsockopt_partial_delivery_point(sk, optval, optlen); break; case SCTP_INITMSG: retval = sctp_setsockopt_initmsg(sk, optval, optlen); break; case SCTP_DEFAULT_SEND_PARAM: retval = sctp_setsockopt_default_send_param(sk, optval, optlen); break; case SCTP_DEFAULT_SNDINFO: retval = sctp_setsockopt_default_sndinfo(sk, optval, optlen); break; case SCTP_PRIMARY_ADDR: retval = sctp_setsockopt_primary_addr(sk, optval, optlen); break; case SCTP_SET_PEER_PRIMARY_ADDR: retval = sctp_setsockopt_peer_primary_addr(sk, optval, optlen); break; case SCTP_NODELAY: retval = sctp_setsockopt_nodelay(sk, optval, optlen); break; case SCTP_RTOINFO: retval = sctp_setsockopt_rtoinfo(sk, optval, optlen); break; case SCTP_ASSOCINFO: retval = sctp_setsockopt_associnfo(sk, optval, optlen); break; case SCTP_I_WANT_MAPPED_V4_ADDR: retval = sctp_setsockopt_mappedv4(sk, optval, optlen); break; case SCTP_MAXSEG: retval = sctp_setsockopt_maxseg(sk, optval, optlen); break; case SCTP_ADAPTATION_LAYER: retval = sctp_setsockopt_adaptation_layer(sk, optval, optlen); break; case SCTP_CONTEXT: retval = sctp_setsockopt_context(sk, optval, optlen); break; case SCTP_FRAGMENT_INTERLEAVE: retval = sctp_setsockopt_fragment_interleave(sk, optval, optlen); break; case SCTP_MAX_BURST: retval = sctp_setsockopt_maxburst(sk, optval, optlen); break; case SCTP_AUTH_CHUNK: retval = sctp_setsockopt_auth_chunk(sk, optval, optlen); break; case SCTP_HMAC_IDENT: retval = sctp_setsockopt_hmac_ident(sk, optval, optlen); break; case SCTP_AUTH_KEY: retval = sctp_setsockopt_auth_key(sk, optval, optlen); break; case SCTP_AUTH_ACTIVE_KEY: retval = sctp_setsockopt_active_key(sk, optval, optlen); break; case SCTP_AUTH_DELETE_KEY: retval = sctp_setsockopt_del_key(sk, optval, optlen); break; case SCTP_AUTO_ASCONF: retval = sctp_setsockopt_auto_asconf(sk, optval, optlen); break; case SCTP_PEER_ADDR_THLDS: retval = sctp_setsockopt_paddr_thresholds(sk, optval, optlen); break; case SCTP_RECVRCVINFO: retval = sctp_setsockopt_recvrcvinfo(sk, optval, optlen); break; case SCTP_RECVNXTINFO: retval = sctp_setsockopt_recvnxtinfo(sk, optval, optlen); break; case SCTP_PR_SUPPORTED: retval = sctp_setsockopt_pr_supported(sk, optval, optlen); break; case SCTP_DEFAULT_PRINFO: retval = sctp_setsockopt_default_prinfo(sk, optval, optlen); break; default: retval = -ENOPROTOOPT; break; } release_sock(sk); out_nounlock: return retval; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,185
Chrome
c71d8045ce0592cf3f4290744ab57b23c1d1b4c6
bool RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session, TargetRegistry* registry) { if (!ShouldAllowSession(session)) return false; protocol::EmulationHandler* emulation_handler = new protocol::EmulationHandler(); session->AddHandler(base::WrapUnique(new protocol::BrowserHandler())); session->AddHandler(base::WrapUnique(new protocol::DOMHandler())); session->AddHandler(base::WrapUnique(emulation_handler)); session->AddHandler(base::WrapUnique(new protocol::InputHandler())); session->AddHandler(base::WrapUnique(new protocol::InspectorHandler())); session->AddHandler(base::WrapUnique(new protocol::IOHandler( GetIOContext()))); session->AddHandler(base::WrapUnique(new protocol::MemoryHandler())); session->AddHandler(base::WrapUnique(new protocol::NetworkHandler( GetId(), frame_tree_node_ ? frame_tree_node_->devtools_frame_token() : base::UnguessableToken(), GetIOContext()))); session->AddHandler(base::WrapUnique(new protocol::SchemaHandler())); session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler())); session->AddHandler(base::WrapUnique(new protocol::StorageHandler())); session->AddHandler(base::WrapUnique(new protocol::TargetHandler( session->client()->MayDiscoverTargets() ? protocol::TargetHandler::AccessMode::kRegular : protocol::TargetHandler::AccessMode::kAutoAttachOnly, GetId(), registry))); session->AddHandler( base::WrapUnique(new protocol::PageHandler(emulation_handler))); session->AddHandler(base::WrapUnique(new protocol::SecurityHandler())); if (!frame_tree_node_ || !frame_tree_node_->parent()) { session->AddHandler(base::WrapUnique( new protocol::TracingHandler(frame_tree_node_, GetIOContext()))); } if (sessions().empty()) { bool use_video_capture_api = true; #ifdef OS_ANDROID if (!CompositorImpl::IsInitialized()) use_video_capture_api = false; #endif if (!use_video_capture_api) frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder()); GrantPolicy(); #if defined(OS_ANDROID) GetWakeLock()->RequestWakeLock(); #endif } return true; }
1
CVE-2018-18344
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
Phase: Architecture and Design Strategy: Attack Surface Reduction Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111] Phase: Architecture and Design Strategy: Libraries or Frameworks Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). Phases: Architecture and Design; Implementation Strategy: Attack Surface Reduction Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Effectiveness: High Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings. Phase: Implementation When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined. Phase: Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow. Phase: Implementation Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained. Phase: Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content. Phase: Implementation When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
3,601
shadowsocks-libev
c67d275803dc6ea22c558d06b1f7ba9f94cd8de3
check_port(struct manager_ctx *manager, struct server *server) { bool both_tcp_udp = manager->mode == TCP_AND_UDP; int fd_count = manager->host_num * (both_tcp_udp ? 2 : 1); int bind_err = 0; int *sock_fds = (int *)ss_malloc(fd_count * sizeof(int)); memset(sock_fds, 0, fd_count * sizeof(int)); /* try to bind each interface */ for (int i = 0; i < manager->host_num; i++) { LOGI("try to bind interface: %s, port: %s", manager->hosts[i], server->port); if (manager->mode == UDP_ONLY) { sock_fds[i] = create_and_bind(manager->hosts[i], server->port, IPPROTO_UDP); } else { sock_fds[i] = create_and_bind(manager->hosts[i], server->port, IPPROTO_TCP); } if (both_tcp_udp) { sock_fds[i + manager->host_num] = create_and_bind(manager->hosts[i], server->port, IPPROTO_UDP); } if (sock_fds[i] == -1 || (both_tcp_udp && sock_fds[i + manager->host_num] == -1)) { bind_err = -1; break; } } /* clean socks */ for (int i = 0; i < fd_count; i++) { if (sock_fds[i] > 0) { close(sock_fds[i]); } } ss_free(sock_fds); return bind_err == -1 ? -1 : 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,913
linux
9344a972961d1a6d2c04d9008b13617bcb6ec2ef
static int rfcomm_sock_accept(struct socket *sock, struct socket *newsock, int flags) { DECLARE_WAITQUEUE(wait, current); struct sock *sk = sock->sk, *nsk; long timeo; int err = 0; lock_sock(sk); if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; goto done; } timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK); BT_DBG("sk %p timeo %ld", sk, timeo); /* Wait for an incoming connection. (wake-one). */ add_wait_queue_exclusive(sk_sleep(sk), &wait); while (1) { set_current_state(TASK_INTERRUPTIBLE); if (sk->sk_state != BT_LISTEN) { err = -EBADFD; break; } nsk = bt_accept_dequeue(sk, newsock); if (nsk) break; if (!timeo) { err = -EAGAIN; break; } if (signal_pending(current)) { err = sock_intr_errno(timeo); break; } release_sock(sk); timeo = schedule_timeout(timeo); lock_sock(sk); } __set_current_state(TASK_RUNNING); remove_wait_queue(sk_sleep(sk), &wait); if (err) goto done; newsock->state = SS_CONNECTED; BT_DBG("new socket %p", nsk); done: release_sock(sk); return err; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,976
tcpdump
f4b9e24c7384d882a7f434cc7413925bf871d63e
rpl_dio_print(netdissect_options *ndo, const u_char *bp, u_int length) { const struct nd_rpl_dio *dio = (const struct nd_rpl_dio *)bp; const char *dagid_str; ND_TCHECK(*dio); dagid_str = ip6addr_string (ndo, dio->rpl_dagid); ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,rank:%u,%smop:%s,prf:%u]", dagid_str, dio->rpl_dtsn, dio->rpl_instanceid, EXTRACT_16BITS(&dio->rpl_dagrank), RPL_DIO_GROUNDED(dio->rpl_mopprf) ? "grounded,":"", tok2str(rpl_mop_values, "mop%u", RPL_DIO_MOP(dio->rpl_mopprf)), RPL_DIO_PRF(dio->rpl_mopprf))); if(ndo->ndo_vflag > 1) { const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)&dio[1]; rpl_dio_printopt(ndo, opt, length); } return; trunc: ND_PRINT((ndo," [|truncated]")); return; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,920
linux
98da7d08850fb8bdeb395d6368ed15753304aa0c
SYSCALL_DEFINE1(uselib, const char __user *, library) { struct linux_binfmt *fmt; struct file *file; struct filename *tmp = getname(library); int error = PTR_ERR(tmp); static const struct open_flags uselib_flags = { .open_flag = O_LARGEFILE | O_RDONLY | __FMODE_EXEC, .acc_mode = MAY_READ | MAY_EXEC, .intent = LOOKUP_OPEN, .lookup_flags = LOOKUP_FOLLOW, }; if (IS_ERR(tmp)) goto out; file = do_filp_open(AT_FDCWD, tmp, &uselib_flags); putname(tmp); error = PTR_ERR(file); if (IS_ERR(file)) goto out; error = -EINVAL; if (!S_ISREG(file_inode(file)->i_mode)) goto exit; error = -EACCES; if (path_noexec(&file->f_path)) goto exit; fsnotify_open(file); error = -ENOEXEC; read_lock(&binfmt_lock); list_for_each_entry(fmt, &formats, lh) { if (!fmt->load_shlib) continue; if (!try_module_get(fmt->module)) continue; read_unlock(&binfmt_lock); error = fmt->load_shlib(file); read_lock(&binfmt_lock); put_binfmt(fmt); if (error != -ENOEXEC) break; } read_unlock(&binfmt_lock); exit: fput(file); out: return error; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,913
linux
f8bd2258e2d520dff28c855658bd24bdafb5102d
static int count_free(struct page *page) { return page->objects - page->inuse; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,394
linux
717adfdaf14704fd3ec7fa2c04520c0723247eac
static int hid_debug_events_open(struct inode *inode, struct file *file) { int err = 0; struct hid_debug_list *list; unsigned long flags; if (!(list = kzalloc(sizeof(struct hid_debug_list), GFP_KERNEL))) { err = -ENOMEM; goto out; } if (!(list->hid_debug_buf = kzalloc(sizeof(char) * HID_DEBUG_BUFSIZE, GFP_KERNEL))) { err = -ENOMEM; kfree(list); goto out; } list->hdev = (struct hid_device *) inode->i_private; file->private_data = list; mutex_init(&list->read_mutex); spin_lock_irqsave(&list->hdev->debug_list_lock, flags); list_add_tail(&list->node, &list->hdev->debug_list); spin_unlock_irqrestore(&list->hdev->debug_list_lock, flags); out: return err; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,898
linux-2.6
94ad374a0751f40d25e22e036c37f7263569d24c
void __lock_page_nosync(struct page *page) { DEFINE_WAIT_BIT(wait, &page->flags, PG_locked); __wait_on_bit_lock(page_waitqueue(page), &wait, __sleep_on_page_lock, TASK_UNINTERRUPTIBLE); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,581
Android
a33f6725d7e9f92330f995ce2dcf4faa33f6433f
static void ihevcd_fill_outargs(codec_t *ps_codec, ivd_video_decode_ip_t *ps_dec_ip, ivd_video_decode_op_t *ps_dec_op) { ps_dec_op->u4_error_code = ihevcd_map_error((IHEVCD_ERROR_T)ps_codec->i4_error_code); ps_dec_op->u4_num_bytes_consumed = ps_dec_ip->u4_num_Bytes - ps_codec->i4_bytes_remaining; if(ps_codec->i4_sps_done) { ps_dec_op->u4_pic_wd = ps_codec->i4_disp_wd; ps_dec_op->u4_pic_ht = ps_codec->i4_disp_ht; } else { ps_dec_op->u4_pic_wd = 0; ps_dec_op->u4_pic_ht = 0; } ps_dec_op->e_pic_type = ps_codec->e_dec_pic_type; ps_dec_op->u4_frame_decoded_flag = ps_codec->i4_pic_present; ps_dec_op->u4_new_seq = 0; ps_dec_op->u4_output_present = 0; ps_dec_op->u4_progressive_frame_flag = 1; ps_dec_op->u4_is_ref_flag = 1; ps_dec_op->e_output_format = ps_codec->e_chroma_fmt; ps_dec_op->u4_is_ref_flag = 1; ps_dec_op->e4_fld_type = IV_FLD_TYPE_DEFAULT; ps_dec_op->u4_ts = (UWORD32)(-1); ps_dec_op->u4_disp_buf_id = ps_codec->i4_disp_buf_id; if(ps_codec->i4_flush_mode) { ps_dec_op->u4_num_bytes_consumed = 0; /*In the case of flush ,since no frame is decoded set pic type as invalid*/ ps_dec_op->u4_is_ref_flag = 0; ps_dec_op->e_pic_type = IV_NA_FRAME; ps_dec_op->u4_frame_decoded_flag = 0; } /* If there is a display buffer */ if(ps_codec->ps_disp_buf) { pic_buf_t *ps_disp_buf = ps_codec->ps_disp_buf; ps_dec_op->u4_output_present = 1; ps_dec_op->u4_ts = ps_disp_buf->u4_ts; if((ps_codec->i4_flush_mode == 0) && (ps_codec->s_parse.i4_end_of_frame == 0)) ps_dec_op->u4_output_present = 0; ps_dec_op->s_disp_frm_buf.u4_y_wd = ps_codec->i4_disp_wd; ps_dec_op->s_disp_frm_buf.u4_y_ht = ps_codec->i4_disp_ht; if(ps_codec->i4_share_disp_buf) { ps_dec_op->s_disp_frm_buf.pv_y_buf = ps_disp_buf->pu1_luma; if(ps_codec->e_chroma_fmt != IV_YUV_420P) { ps_dec_op->s_disp_frm_buf.pv_u_buf = ps_disp_buf->pu1_chroma; ps_dec_op->s_disp_frm_buf.pv_v_buf = NULL; } else { WORD32 i; UWORD8 *pu1_u_dst = NULL, *pu1_v_dst = NULL; for(i = 0; i < ps_codec->i4_share_disp_buf_cnt; i++) { WORD32 diff = ps_disp_buf->pu1_luma - ps_codec->s_disp_buffer[i].pu1_bufs[0]; if(diff == (ps_codec->i4_strd * PAD_TOP + PAD_LEFT)) { pu1_u_dst = ps_codec->s_disp_buffer[i].pu1_bufs[1]; pu1_u_dst += (ps_codec->i4_strd * PAD_TOP) / 4 + (PAD_LEFT / 2); pu1_v_dst = ps_codec->s_disp_buffer[i].pu1_bufs[2]; pu1_v_dst += (ps_codec->i4_strd * PAD_TOP) / 4 + (PAD_LEFT / 2); break; } } ps_dec_op->s_disp_frm_buf.pv_u_buf = pu1_u_dst; ps_dec_op->s_disp_frm_buf.pv_v_buf = pu1_v_dst; } ps_dec_op->s_disp_frm_buf.u4_y_strd = ps_codec->i4_strd; } else { ps_dec_op->s_disp_frm_buf.pv_y_buf = ps_dec_ip->s_out_buffer.pu1_bufs[0]; ps_dec_op->s_disp_frm_buf.pv_u_buf = ps_dec_ip->s_out_buffer.pu1_bufs[1]; ps_dec_op->s_disp_frm_buf.pv_v_buf = ps_dec_ip->s_out_buffer.pu1_bufs[2]; ps_dec_op->s_disp_frm_buf.u4_y_strd = ps_codec->i4_disp_strd; } if((IV_YUV_420SP_VU == ps_codec->e_chroma_fmt) || (IV_YUV_420SP_UV == ps_codec->e_chroma_fmt)) { ps_dec_op->s_disp_frm_buf.u4_u_strd = ps_dec_op->s_disp_frm_buf.u4_y_strd; ps_dec_op->s_disp_frm_buf.u4_v_strd = 0; ps_dec_op->s_disp_frm_buf.u4_u_wd = ps_dec_op->s_disp_frm_buf.u4_y_wd; ps_dec_op->s_disp_frm_buf.u4_v_wd = 0; ps_dec_op->s_disp_frm_buf.u4_u_ht = ps_dec_op->s_disp_frm_buf.u4_y_ht / 2; ps_dec_op->s_disp_frm_buf.u4_v_ht = 0; } else if(IV_YUV_420P == ps_codec->e_chroma_fmt) { ps_dec_op->s_disp_frm_buf.u4_u_strd = ps_dec_op->s_disp_frm_buf.u4_y_strd / 2; ps_dec_op->s_disp_frm_buf.u4_v_strd = ps_dec_op->s_disp_frm_buf.u4_y_strd / 2; ps_dec_op->s_disp_frm_buf.u4_u_wd = ps_dec_op->s_disp_frm_buf.u4_y_wd / 2; ps_dec_op->s_disp_frm_buf.u4_v_wd = ps_dec_op->s_disp_frm_buf.u4_y_wd / 2; ps_dec_op->s_disp_frm_buf.u4_u_ht = ps_dec_op->s_disp_frm_buf.u4_y_ht / 2; ps_dec_op->s_disp_frm_buf.u4_v_ht = ps_dec_op->s_disp_frm_buf.u4_y_ht / 2; } } else if(ps_codec->i4_flush_mode) { ps_dec_op->u4_error_code = IHEVCD_END_OF_SEQUENCE; /* Come out of flush mode */ ps_codec->i4_flush_mode = 0; } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,746
libtasn1
f979435823a02f842c41d49cd41cc81f25b5d677
asn1_der_decoding2 (asn1_node *element, const void *ider, int *max_ider_len, unsigned int flags, char *errorDescription) { asn1_node node, p, p2, p3; char temp[128]; int counter, len2, len3, len4, move, ris, tlen; asn1_node ptail = NULL; unsigned char class; unsigned long tag; int tag_len; int indefinite, result, total_len = *max_ider_len, ider_len = *max_ider_len; const unsigned char *der = ider; node = *element; if (errorDescription != NULL) errorDescription[0] = 0; if (node == NULL) return ASN1_ELEMENT_NOT_FOUND; if (node->type & CONST_OPTION) { result = ASN1_GENERIC_ERROR; warn(); goto cleanup; } counter = 0; move = DOWN; p = node; while (1) { tag_len = 0; ris = ASN1_SUCCESS; if (move != UP) { if (p->type & CONST_SET) { p2 = _asn1_get_up (p); len2 = p2->tmp_ival; if (len2 == -1) { if (HAVE_TWO(ider_len) && !der[counter] && !der[counter + 1]) { p = p2; move = UP; counter += 2; DECR_LEN(ider_len, 2); continue; } } else if (counter == len2) { p = p2; move = UP; continue; } else if (counter > len2) { result = ASN1_DER_ERROR; warn(); goto cleanup; } p2 = p2->down; while (p2) { if ((p2->type & CONST_SET) && (p2->type & CONST_NOT_USED)) { ris = extract_tag_der_recursive (p2, der + counter, ider_len, &len2, flags); if (ris == ASN1_SUCCESS) { p2->type &= ~CONST_NOT_USED; p = p2; break; } } p2 = p2->right; } if (p2 == NULL) { result = ASN1_DER_ERROR; warn(); goto cleanup; } } /* the position in the DER structure this starts */ p->start = counter; p->end = total_len - 1; if ((p->type & CONST_OPTION) || (p->type & CONST_DEFAULT)) { p2 = _asn1_get_up (p); len2 = p2->tmp_ival; if (counter == len2) { if (p->right) { p2 = p->right; move = RIGHT; } else move = UP; if (p->type & CONST_OPTION) asn1_delete_structure (&p); p = p2; continue; } } if (type_field (p->type) == ASN1_ETYPE_CHOICE) { while (p->down) { ris = extract_tag_der_recursive (p->down, der + counter, ider_len, &len2, flags); if (ris == ASN1_SUCCESS) { delete_unneeded_choice_fields(p->down); break; } else if (ris == ASN1_ERROR_TYPE_ANY) { result = ASN1_ERROR_TYPE_ANY; warn(); goto cleanup; } else { p2 = p->down; asn1_delete_structure (&p2); } } if (p->down == NULL) { if (!(p->type & CONST_OPTION)) { result = ASN1_DER_ERROR; warn(); goto cleanup; } } else if (type_field (p->type) != ASN1_ETYPE_CHOICE) p = p->down; p->start = counter; } if ((p->type & CONST_OPTION) || (p->type & CONST_DEFAULT)) { p2 = _asn1_get_up (p); len2 = p2->tmp_ival; if ((len2 != -1) && (counter > len2)) ris = ASN1_TAG_ERROR; } if (ris == ASN1_SUCCESS) ris = extract_tag_der_recursive (p, der + counter, ider_len, &tag_len, flags); if (ris != ASN1_SUCCESS) { if (p->type & CONST_OPTION) { p->type |= CONST_NOT_USED; move = RIGHT; } else if (p->type & CONST_DEFAULT) { _asn1_set_value (p, NULL, 0); move = RIGHT; } else { if (errorDescription != NULL) _asn1_error_description_tag_error (p, errorDescription); result = ASN1_TAG_ERROR; warn(); goto cleanup; } } else { DECR_LEN(ider_len, tag_len); counter += tag_len; } } if (ris == ASN1_SUCCESS) { switch (type_field (p->type)) { case ASN1_ETYPE_NULL: DECR_LEN(ider_len, 1); if (der[counter]) { result = ASN1_DER_ERROR; warn(); goto cleanup; } counter++; move = RIGHT; break; case ASN1_ETYPE_BOOLEAN: DECR_LEN(ider_len, 2); if (der[counter++] != 1) { result = ASN1_DER_ERROR; warn(); goto cleanup; } if (der[counter++] == 0) _asn1_set_value (p, "F", 1); else _asn1_set_value (p, "T", 1); move = RIGHT; break; case ASN1_ETYPE_INTEGER: case ASN1_ETYPE_ENUMERATED: len2 = asn1_get_length_der (der + counter, ider_len, &len3); if (len2 < 0) { result = ASN1_DER_ERROR; warn(); goto cleanup; } DECR_LEN(ider_len, len3+len2); _asn1_set_value (p, der + counter, len3 + len2); counter += len3 + len2; move = RIGHT; break; case ASN1_ETYPE_OBJECT_ID: result = _asn1_get_objectid_der (der + counter, ider_len, &len2, temp, sizeof (temp)); if (result != ASN1_SUCCESS) { warn(); goto cleanup; } DECR_LEN(ider_len, len2); tlen = strlen (temp); if (tlen > 0) _asn1_set_value (p, temp, tlen + 1); counter += len2; move = RIGHT; break; case ASN1_ETYPE_GENERALIZED_TIME: case ASN1_ETYPE_UTC_TIME: result = _asn1_get_time_der (type_field (p->type), der + counter, ider_len, &len2, temp, sizeof (temp) - 1, flags); if (result != ASN1_SUCCESS) { warn(); goto cleanup; } DECR_LEN(ider_len, len2); tlen = strlen (temp); if (tlen > 0) _asn1_set_value (p, temp, tlen); counter += len2; move = RIGHT; break; case ASN1_ETYPE_OCTET_STRING: result = _asn1_get_octet_string (p, der + counter, ider_len, &len3, flags); if (result != ASN1_SUCCESS) { warn(); goto cleanup; } DECR_LEN(ider_len, len3); counter += len3; move = RIGHT; break; case ASN1_ETYPE_GENERALSTRING: case ASN1_ETYPE_NUMERIC_STRING: case ASN1_ETYPE_IA5_STRING: case ASN1_ETYPE_TELETEX_STRING: case ASN1_ETYPE_PRINTABLE_STRING: case ASN1_ETYPE_UNIVERSAL_STRING: case ASN1_ETYPE_BMP_STRING: case ASN1_ETYPE_UTF8_STRING: case ASN1_ETYPE_VISIBLE_STRING: case ASN1_ETYPE_BIT_STRING: len2 = asn1_get_length_der (der + counter, ider_len, &len3); if (len2 < 0) { result = ASN1_DER_ERROR; warn(); goto cleanup; } DECR_LEN(ider_len, len3+len2); _asn1_set_value (p, der + counter, len3 + len2); counter += len3 + len2; move = RIGHT; break; case ASN1_ETYPE_SEQUENCE: case ASN1_ETYPE_SET: if (move == UP) { len2 = p->tmp_ival; p->tmp_ival = 0; if (len2 == -1) { /* indefinite length method */ DECR_LEN(ider_len, 2); if ((der[counter]) || der[counter + 1]) { result = ASN1_DER_ERROR; warn(); goto cleanup; } counter += 2; } else { /* definite length method */ if (len2 != counter) { result = ASN1_DER_ERROR; warn(); goto cleanup; } } move = RIGHT; } else { /* move==DOWN || move==RIGHT */ len3 = asn1_get_length_der (der + counter, ider_len, &len2); if (IS_ERR(len3, flags)) { result = ASN1_DER_ERROR; warn(); goto cleanup; } DECR_LEN(ider_len, len2); counter += len2; if (len3 > 0) { p->tmp_ival = counter + len3; move = DOWN; } else if (len3 == 0) { p2 = p->down; while (p2) { if (type_field (p2->type) != ASN1_ETYPE_TAG) { p3 = p2->right; asn1_delete_structure (&p2); p2 = p3; } else p2 = p2->right; } move = RIGHT; } else { /* indefinite length method */ p->tmp_ival = -1; move = DOWN; } } break; case ASN1_ETYPE_SEQUENCE_OF: case ASN1_ETYPE_SET_OF: if (move == UP) { len2 = p->tmp_ival; if (len2 == -1) { /* indefinite length method */ if (!HAVE_TWO(ider_len) || ((der[counter]) || der[counter + 1])) { _asn1_append_sequence_set (p, &ptail); p = ptail; move = RIGHT; continue; } p->tmp_ival = 0; ptail = NULL; /* finished decoding this structure */ DECR_LEN(ider_len, 2); counter += 2; } else { /* definite length method */ if (len2 > counter) { _asn1_append_sequence_set (p, &ptail); p = ptail; move = RIGHT; continue; } p->tmp_ival = 0; ptail = NULL; /* finished decoding this structure */ if (len2 != counter) { result = ASN1_DER_ERROR; warn(); goto cleanup; } } } else { /* move==DOWN || move==RIGHT */ len3 = asn1_get_length_der (der + counter, ider_len, &len2); if (IS_ERR(len3, flags)) { result = ASN1_DER_ERROR; warn(); goto cleanup; } DECR_LEN(ider_len, len2); counter += len2; if (len3) { if (len3 > 0) { /* definite length method */ p->tmp_ival = counter + len3; } else { /* indefinite length method */ p->tmp_ival = -1; } p2 = p->down; while ((type_field (p2->type) == ASN1_ETYPE_TAG) || (type_field (p2->type) == ASN1_ETYPE_SIZE)) p2 = p2->right; if (p2->right == NULL) _asn1_append_sequence_set (p, &ptail); p = p2; } } move = RIGHT; break; case ASN1_ETYPE_ANY: /* Check indefinite lenth method in an EXPLICIT TAG */ if (!(flags & ASN1_DECODE_FLAG_STRICT_DER) && (p->type & CONST_TAG) && tag_len == 2 && (der[counter - 1] == 0x80)) indefinite = 1; else indefinite = 0; if (asn1_get_tag_der (der + counter, ider_len, &class, &len2, &tag) != ASN1_SUCCESS) { result = ASN1_DER_ERROR; warn(); goto cleanup; } DECR_LEN(ider_len, len2); len4 = asn1_get_length_der (der + counter + len2, ider_len, &len3); if (IS_ERR(len4, flags)) { result = ASN1_DER_ERROR; warn(); goto cleanup; } if (len4 != -1) /* definite */ { len2 += len4; DECR_LEN(ider_len, len4+len3); _asn1_set_value_lv (p, der + counter, len2 + len3); counter += len2 + len3; } else /* == -1 */ { /* indefinite length */ ider_len += len2; /* undo DECR_LEN */ if (counter == 0) { result = ASN1_DER_ERROR; warn(); goto cleanup; } result = _asn1_get_indefinite_length_string (der + counter, ider_len, &len2); if (result != ASN1_SUCCESS) { warn(); goto cleanup; } DECR_LEN(ider_len, len2); _asn1_set_value_lv (p, der + counter, len2); counter += len2; } /* Check if a couple of 0x00 are present due to an EXPLICIT TAG with an indefinite length method. */ if (indefinite) { DECR_LEN(ider_len, 2); if (!der[counter] && !der[counter + 1]) { counter += 2; } else { result = ASN1_DER_ERROR; warn(); goto cleanup; } } move = RIGHT; break; default: move = (move == UP) ? RIGHT : DOWN; break; } } if (p) { p->end = counter - 1; } if (p == node && move != DOWN) break; if (move == DOWN) { if (p->down) p = p->down; else move = RIGHT; } if ((move == RIGHT) && !(p->type & CONST_SET)) { if (p->right) p = p->right; else move = UP; } if (move == UP) p = _asn1_get_up (p); } _asn1_delete_not_used (*element); if ((ider_len < 0) || (!(flags & ASN1_DECODE_FLAG_ALLOW_PADDING) && (ider_len != 0))) { warn(); result = ASN1_DER_ERROR; goto cleanup; } *max_ider_len = total_len - ider_len; return ASN1_SUCCESS; cleanup: asn1_delete_structure (element); return result; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,005
Bento4
4d3f0bebd5f8518fd775f671c12bea58c68e814e
AP4_AvccAtom::WriteFields(AP4_ByteStream& stream) { return stream.Write(m_RawBytes.GetData(), m_RawBytes.GetDataSize()); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,312
linux
01ca667133d019edc9f0a1f70a272447c84ec41f
static bool fm10k_alloc_mapped_page(struct fm10k_ring *rx_ring, struct fm10k_rx_buffer *bi) { struct page *page = bi->page; dma_addr_t dma; /* Only page will be NULL if buffer was consumed */ if (likely(page)) return true; /* alloc new page for storage */ page = dev_alloc_page(); if (unlikely(!page)) { rx_ring->rx_stats.alloc_failed++; return false; } /* map page for use */ dma = dma_map_page(rx_ring->dev, page, 0, PAGE_SIZE, DMA_FROM_DEVICE); /* if mapping failed free memory back to system since * there isn't much point in holding memory we can't use */ if (dma_mapping_error(rx_ring->dev, dma)) { __free_page(page); rx_ring->rx_stats.alloc_failed++; return false; } bi->dma = dma; bi->page = page; bi->page_offset = 0; return true; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,687
Chrome
04aaacb936a08d70862d6d9d7e8354721ae46be8
void Reinitialize(ReinitTestCase test_case) { feature_list_.InitAndEnableFeature(network::features::kNetworkService); ASSERT_TRUE(temp_directory_.CreateUniqueTempDir()); AppCacheDatabase db(temp_directory_.GetPath().AppendASCII("Index")); EXPECT_TRUE(db.LazyOpen(true)); if (test_case == CORRUPT_CACHE_ON_INSTALL || test_case == CORRUPT_CACHE_ON_LOAD_EXISTING) { const std::string kCorruptData("deadbeef"); base::FilePath disk_cache_directory = temp_directory_.GetPath().AppendASCII("Cache"); ASSERT_TRUE(base::CreateDirectory(disk_cache_directory)); base::FilePath index_file = disk_cache_directory.AppendASCII("index"); EXPECT_EQ(static_cast<int>(kCorruptData.length()), base::WriteFile(index_file, kCorruptData.data(), kCorruptData.length())); base::FilePath entry_file = disk_cache_directory.AppendASCII("01234567_0"); EXPECT_EQ(static_cast<int>(kCorruptData.length()), base::WriteFile(entry_file, kCorruptData.data(), kCorruptData.length())); } if (test_case == CORRUPT_CACHE_ON_LOAD_EXISTING) { AppCacheDatabase db(temp_directory_.GetPath().AppendASCII("Index")); GURL manifest_url = GetMockUrl("manifest"); AppCacheDatabase::GroupRecord group_record; group_record.group_id = 1; group_record.manifest_url = manifest_url; group_record.origin = url::Origin::Create(manifest_url); EXPECT_TRUE(db.InsertGroup(&group_record)); AppCacheDatabase::CacheRecord cache_record; cache_record.cache_id = 1; cache_record.group_id = 1; cache_record.online_wildcard = false; cache_record.update_time = kZeroTime; cache_record.cache_size = kDefaultEntrySize; EXPECT_TRUE(db.InsertCache(&cache_record)); AppCacheDatabase::EntryRecord entry_record; entry_record.cache_id = 1; entry_record.url = manifest_url; entry_record.flags = AppCacheEntry::MANIFEST; entry_record.response_id = 1; entry_record.response_size = kDefaultEntrySize; EXPECT_TRUE(db.InsertEntry(&entry_record)); } service_.reset(new AppCacheServiceImpl(nullptr)); auto loader_factory_getter = base::MakeRefCounted<URLLoaderFactoryGetter>(); loader_factory_getter->SetNetworkFactoryForTesting( &mock_url_loader_factory_, /* is_corb_enabled = */ true); service_->set_url_loader_factory_getter(loader_factory_getter.get()); service_->Initialize(temp_directory_.GetPath()); mock_quota_manager_proxy_ = new MockQuotaManagerProxy(); service_->quota_manager_proxy_ = mock_quota_manager_proxy_; delegate_.reset(new MockStorageDelegate(this)); observer_.reset(new MockServiceObserver(this)); service_->AddObserver(observer_.get()); FlushAllTasks(); base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&AppCacheStorageImplTest::Continue_Reinitialize, base::Unretained(this), test_case)); }
1
CVE-2019-5837
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
Phase: Architecture and Design Strategy: Separation of Privilege Compartmentalize the system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area. Ensure that appropriate compartmentalization is built into the system design, and the compartmentalization allows for and reinforces privilege separation functionality. Architects and designers should rely on the principle of least privilege to decide the appropriate time to use privileges and the time to drop privileges.
7,782
Chrome
5385c44d9634d00b1cec2abf0fe7290d4205c7b0
void ResourceDispatcherHostImpl::PauseRequest(int child_id, int request_id, bool pause) { GlobalRequestID global_id(child_id, request_id); PendingRequestList::iterator i = pending_requests_.find(global_id); if (i == pending_requests_.end()) { DVLOG(1) << "Pausing a request that wasn't found"; return; } ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(i->second); int pause_count = info->pause_count() + (pause ? 1 : -1); if (pause_count < 0) { NOTREACHED(); // Unbalanced call to pause. return; } info->set_pause_count(pause_count); VLOG(1) << "To pause (" << pause << "): " << i->second->url().spec(); if (info->pause_count() == 0) { MessageLoop::current()->PostTask(FROM_HERE, base::Bind( &ResourceDispatcherHostImpl::ResumeRequest, weak_factory_.GetWeakPtr(), global_id)); } }
1
CVE-2011-3106
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
5,909
Pillow
cbdce6c5d054fccaf4af34b47f212355c64ace7a
ImagingLibTiffDecode( Imaging im, ImagingCodecState state, UINT8 *buffer, Py_ssize_t bytes) { TIFFSTATE *clientstate = (TIFFSTATE *)state->context; char *filename = "tempfile.tif"; char *mode = "r"; TIFF *tiff; uint16 photometric = 0; // init to not PHOTOMETRIC_YCBCR int isYCbCr = 0; /* buffer is the encoded file, bytes is the length of the encoded file */ /* it all ends up in state->buffer, which is a uint8* from Imaging.h */ TRACE(("in decoder: bytes %d\n", bytes)); TRACE( ("State: count %d, state %d, x %d, y %d, ystep %d\n", state->count, state->state, state->x, state->y, state->ystep)); TRACE( ("State: xsize %d, ysize %d, xoff %d, yoff %d \n", state->xsize, state->ysize, state->xoff, state->yoff)); TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes)); TRACE( ("Buffer: %p: %c%c%c%c\n", buffer, (char)buffer[0], (char)buffer[1], (char)buffer[2], (char)buffer[3])); TRACE( ("State->Buffer: %c%c%c%c\n", (char)state->buffer[0], (char)state->buffer[1], (char)state->buffer[2], (char)state->buffer[3])); TRACE( ("Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \n", im->mode, im->type, im->bands, im->xsize, im->ysize)); TRACE( ("Image: image8 %p, image32 %p, image %p, block %p \n", im->image8, im->image32, im->image, im->block)); TRACE(("Image: pixelsize: %d, linesize %d \n", im->pixelsize, im->linesize)); dump_state(clientstate); clientstate->size = bytes; clientstate->eof = clientstate->size; clientstate->loc = 0; clientstate->data = (tdata_t)buffer; clientstate->flrealloc = 0; dump_state(clientstate); TIFFSetWarningHandler(NULL); TIFFSetWarningHandlerExt(NULL); if (clientstate->fp) { TRACE(("Opening using fd: %d\n", clientstate->fp)); lseek(clientstate->fp, 0, SEEK_SET); // Sometimes, I get it set to the end. tiff = TIFFFdOpen(fd_to_tiff_fd(clientstate->fp), filename, mode); } else { TRACE(("Opening from string\n")); tiff = TIFFClientOpen( filename, mode, (thandle_t)clientstate, _tiffReadProc, _tiffWriteProc, _tiffSeekProc, _tiffCloseProc, _tiffSizeProc, _tiffMapProc, _tiffUnmapProc); } if (!tiff) { TRACE(("Error, didn't get the tiff\n")); state->errcode = IMAGING_CODEC_BROKEN; return -1; } if (clientstate->ifd) { int rv; uint32 ifdoffset = clientstate->ifd; TRACE(("reading tiff ifd %u\n", ifdoffset)); rv = TIFFSetSubDirectory(tiff, ifdoffset); if (!rv) { TRACE(("error in TIFFSetSubDirectory")); goto decode_err; } } TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric); isYCbCr = photometric == PHOTOMETRIC_YCBCR; if (TIFFIsTiled(tiff)) { INT32 x, y, tile_y; UINT32 tile_width, tile_length, current_tile_length, current_line, current_tile_width, row_byte_size; UINT8 *new_data; TIFFGetField(tiff, TIFFTAG_TILEWIDTH, &tile_width); TIFFGetField(tiff, TIFFTAG_TILELENGTH, &tile_length); /* overflow check for row_byte_size calculation */ if ((UINT32)INT_MAX / state->bits < tile_width) { state->errcode = IMAGING_CODEC_MEMORY; goto decode_err; } if (isYCbCr) { row_byte_size = tile_width * 4; /* sanity check, we use this value in shuffle below */ if (im->pixelsize != 4) { state->errcode = IMAGING_CODEC_BROKEN; goto decode_err; } } else { // We could use TIFFTileSize, but for YCbCr data it returns subsampled data // size row_byte_size = (tile_width * state->bits + 7) / 8; } /* overflow check for realloc */ if (INT_MAX / row_byte_size < tile_length) { state->errcode = IMAGING_CODEC_MEMORY; goto decode_err; } state->bytes = row_byte_size * tile_length; if (TIFFTileSize(tiff) > state->bytes) { // If the strip size as expected by LibTiff isn't what we're expecting, // abort. state->errcode = IMAGING_CODEC_MEMORY; goto decode_err; } /* realloc to fit whole tile */ /* malloc check above */ new_data = realloc(state->buffer, state->bytes); if (!new_data) { state->errcode = IMAGING_CODEC_MEMORY; goto decode_err; } state->buffer = new_data; TRACE(("TIFFTileSize: %d\n", state->bytes)); for (y = state->yoff; y < state->ysize; y += tile_length) { for (x = state->xoff; x < state->xsize; x += tile_width) { /* Sanity Check. Apparently in some cases, the TiffReadRGBA* functions have a different view of the size of the tiff than we're getting from other functions. So, we need to check here. */ if (!TIFFCheckTile(tiff, x, y, 0, 0)) { TRACE(("Check Tile Error, Tile at %dx%d\n", x, y)); state->errcode = IMAGING_CODEC_BROKEN; goto decode_err; } if (isYCbCr) { /* To avoid dealing with YCbCr subsampling, let libtiff handle it */ if (!TIFFReadRGBATile(tiff, x, y, (UINT32 *)state->buffer)) { TRACE(("Decode Error, Tile at %dx%d\n", x, y)); state->errcode = IMAGING_CODEC_BROKEN; goto decode_err; } } else { if (TIFFReadTile(tiff, (tdata_t)state->buffer, x, y, 0, 0) == -1) { TRACE(("Decode Error, Tile at %dx%d\n", x, y)); state->errcode = IMAGING_CODEC_BROKEN; goto decode_err; } } TRACE(("Read tile at %dx%d; \n\n", x, y)); current_tile_width = min((INT32)tile_width, state->xsize - x); current_tile_length = min((INT32)tile_length, state->ysize - y); // iterate over each line in the tile and stuff data into image for (tile_y = 0; tile_y < current_tile_length; tile_y++) { TRACE( ("Writing tile data at %dx%d using tile_width: %d; \n", tile_y + y, x, current_tile_width)); // UINT8 * bbb = state->buffer + tile_y * row_byte_size; // TRACE(("chars: %x%x%x%x\n", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], // ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); /* * For some reason the TIFFReadRGBATile() function * chooses the lower left corner as the origin. * Vertically mirror by shuffling the scanlines * backwards */ if (isYCbCr) { current_line = tile_length - tile_y - 1; } else { current_line = tile_y; } state->shuffle( (UINT8 *)im->image[tile_y + y] + x * im->pixelsize, state->buffer + current_line * row_byte_size, current_tile_width); } } } } else { if (!isYCbCr) { _decodeStrip(im, state, tiff); } else { _decodeStripYCbCr(im, state, tiff); } } decode_err: TIFFClose(tiff); TRACE(("Done Decoding, Returning \n")); // Returning -1 here to force ImageFile.load to break, rather than // even think about looping back around. return -1; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,853
ImageMagick6
210474b2fac6a661bfa7ed563213920e93e76395
static Image *ReadDPXImage(const ImageInfo *image_info,ExceptionInfo *exception) { char magick[4], value[MaxTextExtent]; DPXInfo dpx; Image *image; MagickBooleanType status; MagickOffsetType offset; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t extent, samples_per_pixel; ssize_t count, n, row, y; unsigned char component_type; /* 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); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read DPX file header. */ offset=0; count=ReadBlob(image,4,(unsigned char *) magick); offset+=count; if ((count != 4) || ((LocaleNCompare(magick,"SDPX",4) != 0) && (LocaleNCompare((char *) magick,"XPDS",4) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->endian=LSBEndian; if (LocaleNCompare(magick,"SDPX",4) == 0) image->endian=MSBEndian; (void) memset(&dpx,0,sizeof(dpx)); dpx.file.image_offset=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(dpx.file.version),(unsigned char *) dpx.file.version); (void) FormatImageProperty(image,"dpx:file.version","%.8s",dpx.file.version); dpx.file.file_size=ReadBlobLong(image); if (0 && dpx.file.file_size > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset+=4; dpx.file.ditto_key=ReadBlobLong(image); offset+=4; if (dpx.file.ditto_key != ~0U) (void) FormatImageProperty(image,"dpx:file.ditto.key","%u", dpx.file.ditto_key); dpx.file.generic_size=ReadBlobLong(image); if (0 && dpx.file.generic_size > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset+=4; dpx.file.industry_size=ReadBlobLong(image); if (0 && dpx.file.industry_size > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset+=4; dpx.file.user_size=ReadBlobLong(image); if (0 && dpx.file.user_size > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset+=4; offset+=ReadBlob(image,sizeof(dpx.file.filename),(unsigned char *) dpx.file.filename); (void) FormatImageProperty(image,"dpx:file.filename","%.100s", dpx.file.filename); (void) FormatImageProperty(image,"document","%.100s",dpx.file.filename); offset+=ReadBlob(image,sizeof(dpx.file.timestamp),(unsigned char *) dpx.file.timestamp); if (*dpx.file.timestamp != '\0') (void) FormatImageProperty(image,"dpx:file.timestamp","%.24s", dpx.file.timestamp); offset+=ReadBlob(image,sizeof(dpx.file.creator),(unsigned char *) dpx.file.creator); if (*dpx.file.creator == '\0') { char *url; url=GetMagickHomeURL(); (void) FormatImageProperty(image,"dpx:file.creator","%.100s",url); (void) FormatImageProperty(image,"software","%.100s",url); url=DestroyString(url); } else { (void) FormatImageProperty(image,"dpx:file.creator","%.100s", dpx.file.creator); (void) FormatImageProperty(image,"software","%.100s",dpx.file.creator); } offset+=ReadBlob(image,sizeof(dpx.file.project),(unsigned char *) dpx.file.project); if (*dpx.file.project != '\0') { (void) FormatImageProperty(image,"dpx:file.project","%.200s", dpx.file.project); (void) FormatImageProperty(image,"comment","%.100s",dpx.file.project); } offset+=ReadBlob(image,sizeof(dpx.file.copyright),(unsigned char *) dpx.file.copyright); if (*dpx.file.copyright != '\0') { (void) FormatImageProperty(image,"dpx:file.copyright","%.200s", dpx.file.copyright); (void) FormatImageProperty(image,"copyright","%.100s", dpx.file.copyright); } dpx.file.encrypt_key=ReadBlobLong(image); offset+=4; if (dpx.file.encrypt_key != ~0U) (void) FormatImageProperty(image,"dpx:file.encrypt_key","%u", dpx.file.encrypt_key); offset+=ReadBlob(image,sizeof(dpx.file.reserve),(unsigned char *) dpx.file.reserve); /* Read DPX image header. */ dpx.image.orientation=ReadBlobShort(image); if (dpx.image.orientation > 7) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset+=2; if (dpx.image.orientation != (unsigned short) ~0) (void) FormatImageProperty(image,"dpx:image.orientation","%d", dpx.image.orientation); switch (dpx.image.orientation) { default: case 0: image->orientation=TopLeftOrientation; break; case 1: image->orientation=TopRightOrientation; break; case 2: image->orientation=BottomLeftOrientation; break; case 3: image->orientation=BottomRightOrientation; break; case 4: image->orientation=LeftTopOrientation; break; case 5: image->orientation=RightTopOrientation; break; case 6: image->orientation=LeftBottomOrientation; break; case 7: image->orientation=RightBottomOrientation; break; } dpx.image.number_elements=ReadBlobShort(image); if ((dpx.image.number_elements < 1) || (dpx.image.number_elements > MaxNumberImageElements)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset+=2; dpx.image.pixels_per_line=ReadBlobLong(image); offset+=4; image->columns=dpx.image.pixels_per_line; dpx.image.lines_per_element=ReadBlobLong(image); offset+=4; image->rows=dpx.image.lines_per_element; for (i=0; i < 8; i++) { char property[MaxTextExtent]; dpx.image.image_element[i].data_sign=ReadBlobLong(image); offset+=4; dpx.image.image_element[i].low_data=ReadBlobLong(image); offset+=4; dpx.image.image_element[i].low_quantity=ReadBlobFloat(image); offset+=4; dpx.image.image_element[i].high_data=ReadBlobLong(image); offset+=4; dpx.image.image_element[i].high_quantity=ReadBlobFloat(image); offset+=4; dpx.image.image_element[i].descriptor=(unsigned char) ReadBlobByte(image); offset++; dpx.image.image_element[i].transfer_characteristic=(unsigned char) ReadBlobByte(image); (void) FormatLocaleString(property,MaxTextExtent, "dpx:image.element[%lu].transfer-characteristic",(long) i); (void) FormatImageProperty(image,property,"%s", GetImageTransferCharacteristic((DPXTransferCharacteristic) dpx.image.image_element[i].transfer_characteristic)); offset++; dpx.image.image_element[i].colorimetric=(unsigned char) ReadBlobByte(image); offset++; dpx.image.image_element[i].bit_size=(unsigned char) ReadBlobByte(image); offset++; dpx.image.image_element[i].packing=ReadBlobShort(image); if (dpx.image.image_element[i].packing > 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset+=2; dpx.image.image_element[i].encoding=ReadBlobShort(image); offset+=2; dpx.image.image_element[i].data_offset=ReadBlobLong(image); offset+=4; dpx.image.image_element[i].end_of_line_padding=ReadBlobLong(image); offset+=4; dpx.image.image_element[i].end_of_image_padding=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(dpx.image.image_element[i].description), (unsigned char *) dpx.image.image_element[i].description); } (void) SetImageColorspace(image,RGBColorspace); offset+=ReadBlob(image,sizeof(dpx.image.reserve),(unsigned char *) dpx.image.reserve); if (dpx.file.image_offset >= 1664U) { /* Read DPX orientation header. */ dpx.orientation.x_offset=ReadBlobLong(image); offset+=4; if (dpx.orientation.x_offset != ~0U) (void) FormatImageProperty(image,"dpx:orientation.x_offset","%u", dpx.orientation.x_offset); dpx.orientation.y_offset=ReadBlobLong(image); offset+=4; if (dpx.orientation.y_offset != ~0U) (void) FormatImageProperty(image,"dpx:orientation.y_offset","%u", dpx.orientation.y_offset); dpx.orientation.x_center=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.orientation.x_center) != MagickFalse) (void) FormatImageProperty(image,"dpx:orientation.x_center","%g", dpx.orientation.x_center); dpx.orientation.y_center=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.orientation.y_center) != MagickFalse) (void) FormatImageProperty(image,"dpx:orientation.y_center","%g", dpx.orientation.y_center); dpx.orientation.x_size=ReadBlobLong(image); offset+=4; if (dpx.orientation.x_size != ~0U) (void) FormatImageProperty(image,"dpx:orientation.x_size","%u", dpx.orientation.x_size); dpx.orientation.y_size=ReadBlobLong(image); offset+=4; if (dpx.orientation.y_size != ~0U) (void) FormatImageProperty(image,"dpx:orientation.y_size","%u", dpx.orientation.y_size); offset+=ReadBlob(image,sizeof(dpx.orientation.filename),(unsigned char *) dpx.orientation.filename); if (*dpx.orientation.filename != '\0') (void) FormatImageProperty(image,"dpx:orientation.filename","%.100s", dpx.orientation.filename); offset+=ReadBlob(image,sizeof(dpx.orientation.timestamp),(unsigned char *) dpx.orientation.timestamp); if (*dpx.orientation.timestamp != '\0') (void) FormatImageProperty(image,"dpx:orientation.timestamp","%.24s", dpx.orientation.timestamp); offset+=ReadBlob(image,sizeof(dpx.orientation.device),(unsigned char *) dpx.orientation.device); if (*dpx.orientation.device != '\0') (void) FormatImageProperty(image,"dpx:orientation.device","%.32s", dpx.orientation.device); offset+=ReadBlob(image,sizeof(dpx.orientation.serial),(unsigned char *) dpx.orientation.serial); if (*dpx.orientation.serial != '\0') (void) FormatImageProperty(image,"dpx:orientation.serial","%.32s", dpx.orientation.serial); for (i=0; i < 4; i++) { dpx.orientation.border[i]=ReadBlobShort(image); offset+=2; } if ((dpx.orientation.border[0] != (unsigned short) (~0)) && (dpx.orientation.border[1] != (unsigned short) (~0))) (void) FormatImageProperty(image,"dpx:orientation.border","%dx%d%+d%+d", dpx.orientation.border[0],dpx.orientation.border[1], dpx.orientation.border[2],dpx.orientation.border[3]); for (i=0; i < 2; i++) { dpx.orientation.aspect_ratio[i]=ReadBlobLong(image); offset+=4; } if ((dpx.orientation.aspect_ratio[0] != ~0U) && (dpx.orientation.aspect_ratio[1] != ~0U)) (void) FormatImageProperty(image,"dpx:orientation.aspect_ratio", "%ux%u",dpx.orientation.aspect_ratio[0], dpx.orientation.aspect_ratio[1]); offset+=ReadBlob(image,sizeof(dpx.orientation.reserve),(unsigned char *) dpx.orientation.reserve); } if (dpx.file.image_offset >= 1920U) { /* Read DPX film header. */ offset+=ReadBlob(image,sizeof(dpx.film.id),(unsigned char *) dpx.film.id); if (*dpx.film.id != '\0') (void) FormatImageProperty(image,"dpx:film.id","%.2s",dpx.film.id); offset+=ReadBlob(image,sizeof(dpx.film.type),(unsigned char *) dpx.film.type); if (*dpx.film.type != '\0') (void) FormatImageProperty(image,"dpx:film.type","%.2s",dpx.film.type); offset+=ReadBlob(image,sizeof(dpx.film.offset),(unsigned char *) dpx.film.offset); if (*dpx.film.offset != '\0') (void) FormatImageProperty(image,"dpx:film.offset","%.2s", dpx.film.offset); offset+=ReadBlob(image,sizeof(dpx.film.prefix),(unsigned char *) dpx.film.prefix); if (*dpx.film.prefix != '\0') (void) FormatImageProperty(image,"dpx:film.prefix","%.6s", dpx.film.prefix); offset+=ReadBlob(image,sizeof(dpx.film.count),(unsigned char *) dpx.film.count); if (*dpx.film.count != '\0') (void) FormatImageProperty(image,"dpx:film.count","%.4s", dpx.film.count); offset+=ReadBlob(image,sizeof(dpx.film.format),(unsigned char *) dpx.film.format); if (*dpx.film.format != '\0') (void) FormatImageProperty(image,"dpx:film.format","%.4s", dpx.film.format); dpx.film.frame_position=ReadBlobLong(image); offset+=4; if (dpx.film.frame_position != ~0U) (void) FormatImageProperty(image,"dpx:film.frame_position","%u", dpx.film.frame_position); dpx.film.sequence_extent=ReadBlobLong(image); offset+=4; if (dpx.film.sequence_extent != ~0U) (void) FormatImageProperty(image,"dpx:film.sequence_extent","%u", dpx.film.sequence_extent); dpx.film.held_count=ReadBlobLong(image); offset+=4; if (dpx.film.held_count != ~0U) (void) FormatImageProperty(image,"dpx:film.held_count","%u", dpx.film.held_count); dpx.film.frame_rate=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.film.frame_rate) != MagickFalse) (void) FormatImageProperty(image,"dpx:film.frame_rate","%g", dpx.film.frame_rate); dpx.film.shutter_angle=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.film.shutter_angle) != MagickFalse) (void) FormatImageProperty(image,"dpx:film.shutter_angle","%g", dpx.film.shutter_angle); offset+=ReadBlob(image,sizeof(dpx.film.frame_id),(unsigned char *) dpx.film.frame_id); if (*dpx.film.frame_id != '\0') (void) FormatImageProperty(image,"dpx:film.frame_id","%.32s", dpx.film.frame_id); offset+=ReadBlob(image,sizeof(dpx.film.slate),(unsigned char *) dpx.film.slate); if (*dpx.film.slate != '\0') (void) FormatImageProperty(image,"dpx:film.slate","%.100s", dpx.film.slate); offset+=ReadBlob(image,sizeof(dpx.film.reserve),(unsigned char *) dpx.film.reserve); } if (dpx.file.image_offset >= 2048U) { /* Read DPX television header. */ dpx.television.time_code=(unsigned int) ReadBlobLong(image); offset+=4; TimeCodeToString(dpx.television.time_code,value); (void) SetImageProperty(image,"dpx:television.time.code",value); dpx.television.user_bits=(unsigned int) ReadBlobLong(image); offset+=4; TimeCodeToString(dpx.television.user_bits,value); (void) SetImageProperty(image,"dpx:television.user.bits",value); dpx.television.interlace=(unsigned char) ReadBlobByte(image); offset++; if (dpx.television.interlace != 0) (void) FormatImageProperty(image,"dpx:television.interlace","%.20g", (double) dpx.television.interlace); dpx.television.field_number=(unsigned char) ReadBlobByte(image); offset++; if (dpx.television.field_number != 0) (void) FormatImageProperty(image,"dpx:television.field_number","%.20g", (double) dpx.television.field_number); dpx.television.video_signal=(unsigned char) ReadBlobByte(image); offset++; if (dpx.television.video_signal != 0) (void) FormatImageProperty(image,"dpx:television.video_signal","%.20g", (double) dpx.television.video_signal); dpx.television.padding=(unsigned char) ReadBlobByte(image); offset++; if (dpx.television.padding != 0) (void) FormatImageProperty(image,"dpx:television.padding","%d", dpx.television.padding); dpx.television.horizontal_sample_rate=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.television.horizontal_sample_rate) != MagickFalse) (void) FormatImageProperty(image, "dpx:television.horizontal_sample_rate","%g", dpx.television.horizontal_sample_rate); dpx.television.vertical_sample_rate=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.television.vertical_sample_rate) != MagickFalse) (void) FormatImageProperty(image,"dpx:television.vertical_sample_rate", "%g",dpx.television.vertical_sample_rate); dpx.television.frame_rate=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.television.frame_rate) != MagickFalse) (void) FormatImageProperty(image,"dpx:television.frame_rate","%g", dpx.television.frame_rate); dpx.television.time_offset=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.television.time_offset) != MagickFalse) (void) FormatImageProperty(image,"dpx:television.time_offset","%g", dpx.television.time_offset); dpx.television.gamma=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.television.gamma) != MagickFalse) (void) FormatImageProperty(image,"dpx:television.gamma","%g", dpx.television.gamma); dpx.television.black_level=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.television.black_level) != MagickFalse) (void) FormatImageProperty(image,"dpx:television.black_level","%g", dpx.television.black_level); dpx.television.black_gain=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.television.black_gain) != MagickFalse) (void) FormatImageProperty(image,"dpx:television.black_gain","%g", dpx.television.black_gain); dpx.television.break_point=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.television.break_point) != MagickFalse) (void) FormatImageProperty(image,"dpx:television.break_point","%g", dpx.television.break_point); dpx.television.white_level=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.television.white_level) != MagickFalse) (void) FormatImageProperty(image,"dpx:television.white_level","%g", dpx.television.white_level); dpx.television.integration_times=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(dpx.television.integration_times) != MagickFalse) (void) FormatImageProperty(image,"dpx:television.integration_times", "%g",dpx.television.integration_times); offset+=ReadBlob(image,sizeof(dpx.television.reserve),(unsigned char *) dpx.television.reserve); } if (dpx.file.image_offset > 2080U) { /* Read DPX user header. */ offset+=ReadBlob(image,sizeof(dpx.user.id),(unsigned char *) dpx.user.id); if (*dpx.user.id != '\0') (void) FormatImageProperty(image,"dpx:user.id","%.32s",dpx.user.id); if ((dpx.file.user_size != ~0U) && ((size_t) dpx.file.user_size > sizeof(dpx.user.id))) { StringInfo *profile; if (dpx.file.user_size > GetBlobSize(image)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); profile=BlobToStringInfo((const void *) NULL, dpx.file.user_size-sizeof(dpx.user.id)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); offset+=ReadBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); if (EOFBlob(image) != MagickFalse) (void) SetImageProfile(image,"dpx:user-data",profile); profile=DestroyStringInfo(profile); } } for ( ; offset < (MagickOffsetType) dpx.file.image_offset; offset++) if (ReadBlobByte(image) == EOF) break; if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); 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)); } status=ResetImagePixels(image,exception); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (n=0; n < (ssize_t) dpx.image.number_elements; n++) { /* Convert DPX raster image to pixel packets. */ if ((dpx.image.image_element[n].data_offset != ~0U) && (dpx.image.image_element[n].data_offset != 0U)) { MagickOffsetType data_offset; data_offset=(MagickOffsetType) dpx.image.image_element[n].data_offset; if (data_offset < offset) offset=SeekBlob(image,data_offset,SEEK_SET); else for ( ; offset < data_offset; offset++) if (ReadBlobByte(image) == EOF) break; if (offset != data_offset) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } SetPrimaryChromaticity((DPXColorimetric) dpx.image.image_element[n].colorimetric,&image->chromaticity); image->depth=dpx.image.image_element[n].bit_size; if ((image->depth == 0) || (image->depth > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); samples_per_pixel=1; quantum_type=GrayQuantum; component_type=dpx.image.image_element[n].descriptor; switch (component_type) { case CbYCrY422ComponentType: { samples_per_pixel=2; quantum_type=CbYCrYQuantum; break; } case CbYACrYA4224ComponentType: case CbYCr444ComponentType: { samples_per_pixel=3; quantum_type=CbYCrQuantum; break; } case RGBComponentType: { samples_per_pixel=3; quantum_type=RGBQuantum; break; } case ABGRComponentType: case RGBAComponentType: { image->matte=MagickTrue; samples_per_pixel=4; quantum_type=RGBAQuantum; break; } default: break; } switch (component_type) { case CbYCrY422ComponentType: case CbYACrYA4224ComponentType: case CbYCr444ComponentType: { (void) SetImageColorspace(image,Rec709YCbCrColorspace); break; } case LumaComponentType: { (void) SetImageColorspace(image,GRAYColorspace); break; } default: { (void) SetImageColorspace(image,RGBColorspace); if (dpx.image.image_element[n].transfer_characteristic == LogarithmicColorimetric) (void) SetImageColorspace(image,LogColorspace); if (dpx.image.image_element[n].transfer_characteristic == PrintingDensityColorimetric) (void) SetImageColorspace(image,LogColorspace); break; } } extent=GetBytesPerRow(image->columns,samples_per_pixel,image->depth, dpx.image.image_element[n].packing == 0 ? MagickFalse : MagickTrue); /* DPX any-bit pixel format. */ row=0; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumQuantum(quantum_info,32); SetQuantumPack(quantum_info,dpx.image.image_element[n].packing == 0 ? MagickTrue : MagickFalse); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register PixelPacket *q; size_t length; ssize_t count, offset; pixels=(const unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row, image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) length; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); if (y < (ssize_t) image->rows) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); SetQuantumImageType(image,quantum_type); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); if ((i+1) < (ssize_t) dpx.image.number_elements) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,432
linux
3f190e3aec212fc8c61e202c51400afa7384d4bc
static int cxusb_dualdig4_rev2_frontend_attach(struct dvb_usb_adapter *adap) { struct dib0700_adapter_state *state = adap->priv; if (usb_set_interface(adap->dev->udev, 0, 1) < 0) err("set interface failed"); cxusb_ctrl_msg(adap->dev, CMD_DIGITAL, NULL, 0, NULL, 0); cxusb_bluebird_gpio_pulse(adap->dev, 0x02, 1); if (!dvb_attach(dib7000p_attach, &state->dib7000p_ops)) return -ENODEV; if (state->dib7000p_ops.i2c_enumeration(&adap->dev->i2c_adap, 1, 18, &cxusb_dualdig4_rev2_config) < 0) { printk(KERN_WARNING "Unable to enumerate dib7000p\n"); return -ENODEV; } adap->fe_adap[0].fe = state->dib7000p_ops.init(&adap->dev->i2c_adap, 0x80, &cxusb_dualdig4_rev2_config); if (adap->fe_adap[0].fe == NULL) return -EIO; return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,455
libmatroska
0a2d3e3644a7453b6513db2f9bc270f77943573f
KaxBlockBlob::operator const KaxInternalBlock &() const { assert(Block.group); #if MATROSKA_VERSION >= 2 if (bUseSimpleBlock) return *Block.simpleblock; else #endif return *Block.group; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,913
u-boot
5d14ee4e53a81055d34ba280cb8fd90330f22a96
static int rpc_lookup_reply(int prog, uchar *pkt, unsigned len) { struct rpc_t rpc_pkt; memcpy(&rpc_pkt.u.data[0], pkt, len); debug("%s\n", __func__); if (ntohl(rpc_pkt.u.reply.id) > rpc_id) return -NFS_RPC_ERR; else if (ntohl(rpc_pkt.u.reply.id) < rpc_id) return -NFS_RPC_DROP; if (rpc_pkt.u.reply.rstatus || rpc_pkt.u.reply.verifier || rpc_pkt.u.reply.astatus) return -1; switch (prog) { case PROG_MOUNT: nfs_server_mount_port = ntohl(rpc_pkt.u.reply.data[0]); break; case PROG_NFS: nfs_server_port = ntohl(rpc_pkt.u.reply.data[0]); break; } return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,194
Chrome
02c8303512ebed345011f7b545e2f418799be2f0
void LocalFileSystem::deleteFileSystem(ExecutionContext* context, FileSystemType type, PassOwnPtr<AsyncFileSystemCallbacks> callbacks) { RefPtrWillBeRawPtr<ExecutionContext> contextPtr(context); ASSERT(context); ASSERT_WITH_SECURITY_IMPLICATION(context->isDocument()); RefPtr<CallbackWrapper> wrapper = adoptRef(new CallbackWrapper(callbacks)); requestFileSystemAccessInternal(context, bind(&LocalFileSystem::deleteFileSystemInternal, this, contextPtr, type, wrapper), bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper)); }
1
CVE-2013-0917
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
6,840
tensorflow
045deec1cbdebb27d817008ad5df94d96a08b1bf
bool IsIdentityConsumingSwitch(const MutableGraphView& graph, const NodeDef& node) { if ((IsIdentity(node) || IsIdentityNSingleInput(node)) && node.input_size() > 0) { TensorId tensor_id = ParseTensorName(node.input(0)); if (IsTensorIdControlling(tensor_id)) { return false; } NodeDef* input_node = graph.GetNode(tensor_id.node()); return IsSwitch(*input_node); } return false; }
1
CVE-2022-23589
CWE-476
NULL Pointer Dereference
The product dereferences a pointer that it expects to be valid but is NULL.
Phase: Implementation If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented. Phase: Requirements Select a programming language that is not susceptible to these issues. Phase: Implementation Check the results of all functions that return a value and verify that the value is non-null before acting upon it. Effectiveness: Moderate Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665). Phase: Architecture and Design Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values. Phase: Implementation Explicitly initialize all variables and other data stores, either during declaration or just before the first usage.
4,183
linux
ce683e5f9d045e5d67d1312a42b359cb2ab2a13c
check_compat_entry_size_and_hooks(struct compat_arpt_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 || (unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_arpt_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!arp_checkentry(&e->arp)) return -EINVAL; ret = xt_compat_check_entry_offsets(e, e->target_offset, e->next_offset); if (ret) return ret; off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry); entry_offset = (void *)e - (void *)base; t = compat_arpt_get_target(e); target = xt_request_find_target(NFPROTO_ARP, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto out; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off); if (ret) goto release_target; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; release_target: module_put(t->u.kernel.target->me); out: return ret; }
1
CVE-2016-4997
CWE-264
Permissions, Privileges, and Access Controls
Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
Not Found in CWE Page
3,678
qemu
7aa2bcad0ca837dd6d4bf4fa38a80314b4a6b755
static int ne2000_buffer_full(NE2000State *s) { int avail, index, boundary; index = s->curpag << 8; boundary = s->boundary << 8; if (index < boundary) avail = boundary - index; else avail = (s->stop - s->start) - (index - boundary); if (avail < (MAX_ETH_FRAME_SIZE + 4)) return 1; return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,911
Chrome
e89cfcb9090e8c98129ae9160c513f504db74599
void BrowserCommandController::TabDetachedAt(TabContents* contents, int index) { RemoveInterstitialObservers(contents); }
1
CVE-2012-5148
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
Phase: Architecture and Design Strategy: Attack Surface Reduction Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111] Phase: Architecture and Design Strategy: Libraries or Frameworks Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). Phases: Architecture and Design; Implementation Strategy: Attack Surface Reduction Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Effectiveness: High Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings. Phase: Implementation When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined. Phase: Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow. Phase: Implementation Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained. Phase: Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content. Phase: Implementation When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
4,873
Chrome
6ed26f014f76f10e76e80636027a2db9dcbe1664
void BaseRenderingContext2D::drawImage(ScriptState* script_state, CanvasImageSource* image_source, double sx, double sy, double sw, double sh, double dx, double dy, double dw, double dh, ExceptionState& exception_state) { if (!DrawingCanvas()) return; double start_time = 0; Optional<CustomCountHistogram> timer; if (!IsPaint2D()) { start_time = WTF::MonotonicallyIncreasingTime(); if (GetImageBuffer() && GetImageBuffer()->IsAccelerated()) { if (image_source->IsVideoElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_video_gpu, ("Blink.Canvas.DrawImage.Video.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_video_gpu); } else if (image_source->IsCanvasElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_canvas_gpu, ("Blink.Canvas.DrawImage.Canvas.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_canvas_gpu); } else if (image_source->IsSVGSource()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_svggpu, ("Blink.Canvas.DrawImage.SVG.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_svggpu); } else if (image_source->IsImageBitmap()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_image_bitmap_gpu, ("Blink.Canvas.DrawImage.ImageBitmap.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_image_bitmap_gpu); } else if (image_source->IsOffscreenCanvas()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_offscreencanvas_gpu, ("Blink.Canvas.DrawImage.OffscreenCanvas.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_offscreencanvas_gpu); } else { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_others_gpu, ("Blink.Canvas.DrawImage.Others.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_others_gpu); } } else { if (image_source->IsVideoElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_video_cpu, ("Blink.Canvas.DrawImage.Video.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_video_cpu); } else if (image_source->IsCanvasElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_canvas_cpu, ("Blink.Canvas.DrawImage.Canvas.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_canvas_cpu); } else if (image_source->IsSVGSource()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_svgcpu, ("Blink.Canvas.DrawImage.SVG.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_svgcpu); } else if (image_source->IsImageBitmap()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_image_bitmap_cpu, ("Blink.Canvas.DrawImage.ImageBitmap.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_image_bitmap_cpu); } else if (image_source->IsOffscreenCanvas()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_offscreencanvas_cpu, ("Blink.Canvas.DrawImage.OffscreenCanvas.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_offscreencanvas_cpu); } else { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_others_cpu, ("Blink.Canvas.DrawImage.Others.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_others_cpu); } } } scoped_refptr<Image> image; FloatSize default_object_size(Width(), Height()); SourceImageStatus source_image_status = kInvalidSourceImageStatus; if (!image_source->IsVideoElement()) { AccelerationHint hint = (HasImageBuffer() && GetImageBuffer()->IsAccelerated()) ? kPreferAcceleration : kPreferNoAcceleration; image = image_source->GetSourceImageForCanvas(&source_image_status, hint, kSnapshotReasonDrawImage, default_object_size); if (source_image_status == kUndecodableSourceImageStatus) { exception_state.ThrowDOMException( kInvalidStateError, "The HTMLImageElement provided is in the 'broken' state."); } if (!image || !image->width() || !image->height()) return; } else { if (!static_cast<HTMLVideoElement*>(image_source)->HasAvailableVideoFrame()) return; } if (!std::isfinite(dx) || !std::isfinite(dy) || !std::isfinite(dw) || !std::isfinite(dh) || !std::isfinite(sx) || !std::isfinite(sy) || !std::isfinite(sw) || !std::isfinite(sh) || !dw || !dh || !sw || !sh) return; FloatRect src_rect = NormalizeRect(FloatRect(sx, sy, sw, sh)); FloatRect dst_rect = NormalizeRect(FloatRect(dx, dy, dw, dh)); FloatSize image_size = image_source->ElementSize(default_object_size); ClipRectsToImageRect(FloatRect(FloatPoint(), image_size), &src_rect, &dst_rect); image_source->AdjustDrawRects(&src_rect, &dst_rect); if (src_rect.IsEmpty()) return; DisableDeferralReason reason = kDisableDeferralReasonUnknown; if (ShouldDisableDeferral(image_source, &reason)) DisableDeferral(reason); else if (image->IsTextureBacked()) DisableDeferral(kDisableDeferralDrawImageWithTextureBackedSourceImage); ValidateStateStack(); WillDrawImage(image_source); ValidateStateStack(); ImageBuffer* buffer = GetImageBuffer(); if (buffer && buffer->IsAccelerated() && !image_source->IsAccelerated()) { float src_area = src_rect.Width() * src_rect.Height(); if (src_area > CanvasHeuristicParameters::kDrawImageTextureUploadHardSizeLimit) { this->DisableAcceleration(); } else if (src_area > CanvasHeuristicParameters:: kDrawImageTextureUploadSoftSizeLimit) { SkRect bounds = dst_rect; SkMatrix ctm = DrawingCanvas()->getTotalMatrix(); ctm.mapRect(&bounds); float dst_area = dst_rect.Width() * dst_rect.Height(); if (src_area > dst_area * CanvasHeuristicParameters:: kDrawImageTextureUploadSoftSizeLimitScaleThreshold) { this->DisableAcceleration(); } } } ValidateStateStack(); if (OriginClean() && WouldTaintOrigin(image_source, ExecutionContext::From(script_state))) { SetOriginTainted(); ClearResolvedFilters(); } Draw( [this, &image_source, &image, &src_rect, dst_rect]( PaintCanvas* c, const PaintFlags* flags) // draw lambda { DrawImageInternal(c, image_source, image.get(), src_rect, dst_rect, flags); }, [this, &dst_rect](const SkIRect& clip_bounds) // overdraw test lambda { return RectContainsTransformedRect(dst_rect, clip_bounds); }, dst_rect, CanvasRenderingContext2DState::kImagePaintType, image_source->IsOpaque() ? CanvasRenderingContext2DState::kOpaqueImage : CanvasRenderingContext2DState::kNonOpaqueImage); ValidateStateStack(); if (!IsPaint2D()) { DCHECK(start_time); timer->Count((WTF::MonotonicallyIncreasingTime() - start_time) * WTF::Time::kMicrosecondsPerSecond); } }
1
CVE-2018-6077
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
Phase: Architecture and Design Strategy: Separation of Privilege Compartmentalize the system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area. Ensure that appropriate compartmentalization is built into the system design, and the compartmentalization allows for and reinforces privilege separation functionality. Architects and designers should rely on the principle of least privilege to decide the appropriate time to use privileges and the time to drop privileges.
7,327
linux
f227e3ec3b5cad859ad15666874405e8c1bbc1d4
void add_interrupt_randomness(int irq, int irq_flags) { struct entropy_store *r; struct fast_pool *fast_pool = this_cpu_ptr(&irq_randomness); struct pt_regs *regs = get_irq_regs(); unsigned long now = jiffies; cycles_t cycles = random_get_entropy(); __u32 c_high, j_high; __u64 ip; unsigned long seed; int credit = 0; if (cycles == 0) cycles = get_reg(fast_pool, regs); c_high = (sizeof(cycles) > 4) ? cycles >> 32 : 0; j_high = (sizeof(now) > 4) ? now >> 32 : 0; fast_pool->pool[0] ^= cycles ^ j_high ^ irq; fast_pool->pool[1] ^= now ^ c_high; ip = regs ? instruction_pointer(regs) : _RET_IP_; fast_pool->pool[2] ^= ip; fast_pool->pool[3] ^= (sizeof(ip) > 4) ? ip >> 32 : get_reg(fast_pool, regs); fast_mix(fast_pool); add_interrupt_bench(cycles); if (unlikely(crng_init == 0)) { if ((fast_pool->count >= 64) && crng_fast_load((char *) fast_pool->pool, sizeof(fast_pool->pool))) { fast_pool->count = 0; fast_pool->last = now; } return; } if ((fast_pool->count < 64) && !time_after(now, fast_pool->last + HZ)) return; r = &input_pool; if (!spin_trylock(&r->lock)) return; fast_pool->last = now; __mix_pool_bytes(r, &fast_pool->pool, sizeof(fast_pool->pool)); /* * If we have architectural seed generator, produce a seed and * add it to the pool. For the sake of paranoia don't let the * architectural seed generator dominate the input from the * interrupt noise. */ if (arch_get_random_seed_long(&seed)) { __mix_pool_bytes(r, &seed, sizeof(seed)); credit = 1; } spin_unlock(&r->lock); fast_pool->count = 0; /* award one bit for the contents of the fast pool */ credit_entropy_bits(r, credit + 1); }
1
CVE-2020-16166
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
Phase: Architecture and Design Strategy: Separation of Privilege Compartmentalize the system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area. Ensure that appropriate compartmentalization is built into the system design, and the compartmentalization allows for and reinforces privilege separation functionality. Architects and designers should rely on the principle of least privilege to decide the appropriate time to use privileges and the time to drop privileges.
2,335
linux
cc7a0bb058b85ea03db87169c60c7cfdd5d34678
static ssize_t add_slot_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t nbytes) { char drc_name[MAX_DRC_NAME_LEN]; char *end; int rc; if (nbytes >= MAX_DRC_NAME_LEN) return 0; strscpy(drc_name, buf, nbytes + 1); end = strchr(drc_name, '\n'); if (end) *end = '\0'; rc = dlpar_add_slot(drc_name); if (rc) return rc; return nbytes; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,782
krb5
a7886f0ed1277c69142b14a2c6629175a6331edc
init_ctx_new(OM_uint32 *minor_status, spnego_gss_cred_id_t spcred, gss_ctx_id_t *ctx, send_token_flag *tokflag) { OM_uint32 ret; spnego_gss_ctx_id_t sc = NULL; sc = create_spnego_ctx(); if (sc == NULL) return GSS_S_FAILURE; /* determine negotiation mech set */ ret = get_negotiable_mechs(minor_status, spcred, GSS_C_INITIATE, &sc->mech_set); if (ret != GSS_S_COMPLETE) goto cleanup; /* Set an initial internal mech to make the first context token. */ sc->internal_mech = &sc->mech_set->elements[0]; if (put_mech_set(sc->mech_set, &sc->DER_mechTypes) < 0) { ret = GSS_S_FAILURE; goto cleanup; } /* * The actual context is not yet determined, set the output * context handle to refer to the spnego context itself. */ sc->ctx_handle = GSS_C_NO_CONTEXT; *ctx = (gss_ctx_id_t)sc; sc = NULL; *tokflag = INIT_TOKEN_SEND; ret = GSS_S_CONTINUE_NEEDED; cleanup: release_spnego_ctx(&sc); return ret; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,851
libgit2
3316f666566f768eb8aa8de521a5262524dc3424
static int commit_error(git_commit_list_node *commit, const char *msg) { char commit_oid[GIT_OID_HEXSZ + 1]; git_oid_fmt(commit_oid, &commit->oid); commit_oid[GIT_OID_HEXSZ] = '\0'; git_error_set(GIT_ERROR_ODB, "failed to parse commit %s - %s", commit_oid, msg); return -1; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,980
liblouis
2e4772befb2b1c37cb4b9d6572945115ee28630a
compileRule(FileInfo *file, TranslationTableHeader **table, DisplayTableHeader **displayTable, const MacroList **inScopeMacros) { CharsString token; TranslationTableOpcode opcode; CharsString ruleChars; CharsString ruleDots; CharsString cells; CharsString scratchPad; CharsString emphClass; TranslationTableCharacterAttributes after = 0; TranslationTableCharacterAttributes before = 0; int noback, nofor, nocross; noback = nofor = nocross = 0; doOpcode: if (!getToken(file, &token, NULL)) return 1; /* blank line */ if (token.chars[0] == '#' || token.chars[0] == '<') return 1; /* comment */ if (file->lineNumber == 1 && (eqasc2uni((unsigned char *)"ISO", token.chars, 3) || eqasc2uni((unsigned char *)"UTF-8", token.chars, 5))) { if (table) compileHyphenation(file, &token, table); else /* ignore the whole file */ while (_lou_getALine(file)) ; return 1; } opcode = getOpcode(file, &token); switch (opcode) { case CTO_Macro: { const Macro *macro; #ifdef ENABLE_MACROS if (!inScopeMacros) { compileError(file, "Defining macros only allowed in table files."); return 0; } if (compileMacro(file, &macro)) { *inScopeMacros = cons_macro(macro, *inScopeMacros); return 1; } return 0; #else compileError(file, "Macro feature is disabled."); return 0; #endif } case CTO_IncludeFile: { CharsString includedFile; if (!getToken(file, &token, "include file name")) return 0; if (!parseChars(file, &includedFile, &token)) return 0; return includeFile(file, &includedFile, table, displayTable); } case CTO_NoBack: if (nofor) { compileError(file, "%s already specified.", _lou_findOpcodeName(CTO_NoFor)); return 0; } noback = 1; goto doOpcode; case CTO_NoFor: if (noback) { compileError(file, "%s already specified.", _lou_findOpcodeName(CTO_NoBack)); return 0; } nofor = 1; goto doOpcode; case CTO_Space: return compileCharDef( file, opcode, CTC_Space, noback, nofor, table, displayTable); case CTO_Digit: return compileCharDef( file, opcode, CTC_Digit, noback, nofor, table, displayTable); case CTO_LitDigit: return compileCharDef( file, opcode, CTC_LitDigit, noback, nofor, table, displayTable); case CTO_Punctuation: return compileCharDef( file, opcode, CTC_Punctuation, noback, nofor, table, displayTable); case CTO_Math: return compileCharDef(file, opcode, CTC_Math, noback, nofor, table, displayTable); case CTO_Sign: return compileCharDef(file, opcode, CTC_Sign, noback, nofor, table, displayTable); case CTO_Letter: return compileCharDef( file, opcode, CTC_Letter, noback, nofor, table, displayTable); case CTO_UpperCase: return compileCharDef( file, opcode, CTC_UpperCase, noback, nofor, table, displayTable); case CTO_LowerCase: return compileCharDef( file, opcode, CTC_LowerCase, noback, nofor, table, displayTable); case CTO_Grouping: return compileGrouping(file, noback, nofor, table, displayTable); case CTO_Display: if (!displayTable) return 1; // ignore if (!getRuleCharsText(file, &ruleChars)) return 0; if (!getRuleDotsPattern(file, &ruleDots)) return 0; if (ruleChars.length != 1 || ruleDots.length != 1) { compileError(file, "Exactly one character and one cell are required."); return 0; } return putCharDotsMapping( file, ruleChars.chars[0], ruleDots.chars[0], displayTable); case CTO_UpLow: case CTO_None: { // check if token is a macro name if (inScopeMacros) { const MacroList *macros = *inScopeMacros; while (macros) { const Macro *m = macros->head; if (token.length == strlen(m->name) && eqasc2uni((unsigned char *)m->name, token.chars, token.length)) { if (!inScopeMacros) { compileError(file, "Calling macros only allowed in table files."); return 0; } FileInfo tmpFile; memset(&tmpFile, 0, sizeof(tmpFile)); tmpFile.fileName = file->fileName; tmpFile.sourceFile = file->sourceFile; tmpFile.lineNumber = file->lineNumber; tmpFile.encoding = noEncoding; tmpFile.status = 0; tmpFile.linepos = 0; tmpFile.linelen = 0; int argument_count = 0; CharsString *arguments = malloc(m->argument_count * sizeof(CharsString)); while (argument_count < m->argument_count) { if (getToken(file, &token, "macro argument")) arguments[argument_count++] = token; else break; } if (argument_count < m->argument_count) { compileError(file, "Expected %d arguments", m->argument_count); return 0; } int i = 0; int subst = 0; int next = subst < m->substitution_count ? m->substitutions[2 * subst] : m->definition_length; for (;;) { while (i < next) { widechar c = m->definition[i++]; if (c == '\n') { if (!compileRule(&tmpFile, table, displayTable, inScopeMacros)) { _lou_logMessage(LOU_LOG_ERROR, "result of macro expansion was: %s", _lou_showString( tmpFile.line, tmpFile.linelen, 0)); return 0; } tmpFile.linepos = 0; tmpFile.linelen = 0; } else if (tmpFile.linelen >= MAXSTRING) { compileError(file, "Line exceeds %d characters (post macro " "expansion)", MAXSTRING); return 0; } else tmpFile.line[tmpFile.linelen++] = c; } if (subst < m->substitution_count) { CharsString arg = arguments[m->substitutions[2 * subst + 1] - 1]; for (int j = 0; j < arg.length; j++) tmpFile.line[tmpFile.linelen++] = arg.chars[j]; subst++; next = subst < m->substitution_count ? m->substitutions[2 * subst] : m->definition_length; } else { if (!compileRule( &tmpFile, table, displayTable, inScopeMacros)) { _lou_logMessage(LOU_LOG_ERROR, "result of macro expansion was: %s", _lou_showString( tmpFile.line, tmpFile.linelen, 0)); return 0; } break; } } return 1; } macros = macros->tail; } } if (opcode == CTO_UpLow) { compileError(file, "The uplow opcode is deprecated."); return 0; } compileError(file, "opcode %s not defined.", _lou_showString(token.chars, token.length, 0)); return 0; } /* now only opcodes follow that don't modify the display table */ default: if (!table) return 1; switch (opcode) { case CTO_Locale: compileWarning(file, "The locale opcode is not implemented. Use the locale meta data " "instead."); return 1; case CTO_Undefined: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->undefined; if (!compileBrailleIndicator(file, "undefined character opcode", CTO_Undefined, &ruleOffset, noback, nofor, table)) return 0; (*table)->undefined = ruleOffset; return 1; } case CTO_Match: { int ok = 0; widechar *patterns = NULL; TranslationTableRule *rule; TranslationTableOffset ruleOffset; CharsString ptn_before, ptn_after; TranslationTableOffset patternsOffset; int len, mrk; size_t patternsByteSize = sizeof(*patterns) * 27720; patterns = (widechar *)malloc(patternsByteSize); if (!patterns) _lou_outOfMemory(); memset(patterns, 0xffff, patternsByteSize); noback = 1; getCharacters(file, &ptn_before); getRuleCharsText(file, &ruleChars); getCharacters(file, &ptn_after); getRuleDotsPattern(file, &ruleDots); if (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, &ruleOffset, &rule, noback, nofor, table)) goto CTO_Match_cleanup; if (ptn_before.chars[0] == '-' && ptn_before.length == 1) len = _lou_pattern_compile( &ptn_before.chars[0], 0, &patterns[1], 13841, *table, file); else len = _lou_pattern_compile(&ptn_before.chars[0], ptn_before.length, &patterns[1], 13841, *table, file); if (!len) goto CTO_Match_cleanup; mrk = patterns[0] = len + 1; _lou_pattern_reverse(&patterns[1]); if (ptn_after.chars[0] == '-' && ptn_after.length == 1) len = _lou_pattern_compile( &ptn_after.chars[0], 0, &patterns[mrk], 13841, *table, file); else len = _lou_pattern_compile(&ptn_after.chars[0], ptn_after.length, &patterns[mrk], 13841, *table, file); if (!len) goto CTO_Match_cleanup; len += mrk; if (!allocateSpaceInTranslationTable( file, &patternsOffset, len * sizeof(widechar), table)) goto CTO_Match_cleanup; // allocateSpaceInTranslationTable may have moved table, so make sure rule is // still valid rule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset]; memcpy(&(*table)->ruleArea[patternsOffset], patterns, len * sizeof(widechar)); rule->patterns = patternsOffset; ok = 1; CTO_Match_cleanup: free(patterns); return ok; } case CTO_BackMatch: { int ok = 0; widechar *patterns = NULL; TranslationTableRule *rule; TranslationTableOffset ruleOffset; CharsString ptn_before, ptn_after; TranslationTableOffset patternOffset; int len, mrk; size_t patternsByteSize = sizeof(*patterns) * 27720; patterns = (widechar *)malloc(patternsByteSize); if (!patterns) _lou_outOfMemory(); memset(patterns, 0xffff, patternsByteSize); nofor = 1; getCharacters(file, &ptn_before); getRuleCharsText(file, &ruleChars); getCharacters(file, &ptn_after); getRuleDotsPattern(file, &ruleDots); if (!addRule(file, opcode, &ruleChars, &ruleDots, 0, 0, &ruleOffset, &rule, noback, nofor, table)) goto CTO_BackMatch_cleanup; if (ptn_before.chars[0] == '-' && ptn_before.length == 1) len = _lou_pattern_compile( &ptn_before.chars[0], 0, &patterns[1], 13841, *table, file); else len = _lou_pattern_compile(&ptn_before.chars[0], ptn_before.length, &patterns[1], 13841, *table, file); if (!len) goto CTO_BackMatch_cleanup; mrk = patterns[0] = len + 1; _lou_pattern_reverse(&patterns[1]); if (ptn_after.chars[0] == '-' && ptn_after.length == 1) len = _lou_pattern_compile( &ptn_after.chars[0], 0, &patterns[mrk], 13841, *table, file); else len = _lou_pattern_compile(&ptn_after.chars[0], ptn_after.length, &patterns[mrk], 13841, *table, file); if (!len) goto CTO_BackMatch_cleanup; len += mrk; if (!allocateSpaceInTranslationTable( file, &patternOffset, len * sizeof(widechar), table)) goto CTO_BackMatch_cleanup; // allocateSpaceInTranslationTable may have moved table, so make sure rule is // still valid rule = (TranslationTableRule *)&(*table)->ruleArea[ruleOffset]; memcpy(&(*table)->ruleArea[patternOffset], patterns, len * sizeof(widechar)); rule->patterns = patternOffset; ok = 1; CTO_BackMatch_cleanup: free(patterns); return ok; } case CTO_CapsLetter: case CTO_BegCapsWord: case CTO_EndCapsWord: case CTO_BegCaps: case CTO_EndCaps: case CTO_BegCapsPhrase: case CTO_EndCapsPhrase: case CTO_LenCapsPhrase: /* these 8 general purpose opcodes are compiled further down to more specific * internal opcodes: * - modeletter * - begmodeword * - endmodeword * - begmode * - endmode * - begmodephrase * - endmodephrase * - lenmodephrase */ case CTO_ModeLetter: case CTO_BegModeWord: case CTO_EndModeWord: case CTO_BegMode: case CTO_EndMode: case CTO_BegModePhrase: case CTO_EndModePhrase: case CTO_LenModePhrase: { TranslationTableCharacterAttributes mode; int i; switch (opcode) { case CTO_CapsLetter: case CTO_BegCapsWord: case CTO_EndCapsWord: case CTO_BegCaps: case CTO_EndCaps: case CTO_BegCapsPhrase: case CTO_EndCapsPhrase: case CTO_LenCapsPhrase: mode = CTC_UpperCase; i = 0; opcode += (CTO_ModeLetter - CTO_CapsLetter); break; default: if (!getToken(file, &token, "attribute name")) return 0; if (!(*table)->characterClasses && !allocateCharacterClasses(*table)) { return 0; } const CharacterClass *characterClass = findCharacterClass(&token, *table); if (!characterClass) { characterClass = addCharacterClass(file, token.chars, token.length, *table, 1); if (!characterClass) return 0; } mode = characterClass->attribute; if (!(mode == CTC_UpperCase || mode == CTC_Digit) && mode >= CTC_Space && mode <= CTC_LitDigit) { compileError(file, "mode must be \"uppercase\", \"digit\", or a custom " "attribute name."); return 0; } /* check if this mode is already defined and if the number of modes does * not exceed the maximal number */ if (mode == CTC_UpperCase) i = 0; else { for (i = 1; i < MAX_MODES && (*table)->modes[i].value; i++) { if ((*table)->modes[i].mode == mode) { break; } } if (i == MAX_MODES) { compileError(file, "Max number of modes (%i) reached", MAX_MODES); return 0; } } } if (!(*table)->modes[i].value) (*table)->modes[i] = (EmphasisClass){ plain_text, mode, 0x1 << (MAX_EMPH_CLASSES + i), MAX_EMPH_CLASSES + i }; switch (opcode) { case CTO_BegModePhrase: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][begPhraseOffset]; if (!compileBrailleIndicator(file, "first word capital sign", CTO_BegCapsPhraseRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][begPhraseOffset] = ruleOffset; return 1; } case CTO_EndModePhrase: { TranslationTableOffset ruleOffset; switch (compileBeforeAfter(file)) { case 1: // before if ((*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseAfterOffset]) { compileError( file, "Capital sign after last word already defined."); return 0; } // not passing pointer because compileBrailleIndicator may reallocate // table ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i] [endPhraseBeforeOffset]; if (!compileBrailleIndicator(file, "capital sign before last word", CTO_EndCapsPhraseBeforeRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseBeforeOffset] = ruleOffset; return 1; case 2: // after if ((*table)->emphRules[MAX_EMPH_CLASSES + i] [endPhraseBeforeOffset]) { compileError( file, "Capital sign before last word already defined."); return 0; } // not passing pointer because compileBrailleIndicator may reallocate // table ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i] [endPhraseAfterOffset]; if (!compileBrailleIndicator(file, "capital sign after last word", CTO_EndCapsPhraseAfterRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][endPhraseAfterOffset] = ruleOffset; return 1; default: // error compileError(file, "Invalid lastword indicator location."); return 0; } return 0; } case CTO_BegMode: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][begOffset]; if (!compileBrailleIndicator(file, "first letter capital sign", CTO_BegCapsRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][begOffset] = ruleOffset; return 1; } case CTO_EndMode: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][endOffset]; if (!compileBrailleIndicator(file, "last letter capital sign", CTO_EndCapsRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][endOffset] = ruleOffset; return 1; } case CTO_ModeLetter: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][letterOffset]; if (!compileBrailleIndicator(file, "single letter capital sign", CTO_CapsLetterRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][letterOffset] = ruleOffset; return 1; } case CTO_BegModeWord: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][begWordOffset]; if (!compileBrailleIndicator(file, "capital word", CTO_BegCapsWordRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][begWordOffset] = ruleOffset; return 1; } case CTO_EndModeWord: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[MAX_EMPH_CLASSES + i][endWordOffset]; if (!compileBrailleIndicator(file, "capital word stop", CTO_EndCapsWordRule + (8 * i), &ruleOffset, noback, nofor, table)) return 0; (*table)->emphRules[MAX_EMPH_CLASSES + i][endWordOffset] = ruleOffset; return 1; } case CTO_LenModePhrase: return (*table)->emphRules[MAX_EMPH_CLASSES + i][lenPhraseOffset] = compileNumber(file); default: break; } break; } /* these 8 general purpose emphasis opcodes are compiled further down to more * specific internal opcodes: * - emphletter * - begemphword * - endemphword * - begemph * - endemph * - begemphphrase * - endemphphrase * - lenemphphrase */ case CTO_EmphClass: if (!getToken(file, &emphClass, "emphasis class")) { compileError(file, "emphclass must be followed by a valid class name."); return 0; } int k, i; char *s = malloc(sizeof(char) * (emphClass.length + 1)); for (k = 0; k < emphClass.length; k++) s[k] = (char)emphClass.chars[k]; s[k++] = '\0'; for (i = 0; i < MAX_EMPH_CLASSES && (*table)->emphClassNames[i]; i++) if (strcmp(s, (*table)->emphClassNames[i]) == 0) { _lou_logMessage(LOU_LOG_WARN, "Duplicate emphasis class: %s", s); warningCount++; free(s); return 1; } if (i == MAX_EMPH_CLASSES) { _lou_logMessage(LOU_LOG_ERROR, "Max number of emphasis classes (%i) reached", MAX_EMPH_CLASSES); errorCount++; free(s); return 0; } switch (i) { /* For backwards compatibility (i.e. because programs will assume * the first 3 typeform bits are `italic', `underline' and `bold') * we require that the first 3 emphclass definitions are (in that * order): * * emphclass italic * emphclass underline * emphclass bold * * While it would be possible to use the emphclass opcode only for * defining _additional_ classes (not allowing for them to be called * italic, underline or bold), thereby reducing the amount of * boilerplate, we deliberately choose not to do that in order to * not give italic, underline and bold any special status. The * hope is that eventually all programs will use liblouis for * emphasis the recommended way (i.e. by looking up the supported * typeforms in the documentation or API) so that we can drop this * restriction. */ case 0: if (strcmp(s, "italic") != 0) { _lou_logMessage(LOU_LOG_ERROR, "First emphasis class must be \"italic\" but got " "%s", s); errorCount++; free(s); return 0; } break; case 1: if (strcmp(s, "underline") != 0) { _lou_logMessage(LOU_LOG_ERROR, "Second emphasis class must be \"underline\" but " "got " "%s", s); errorCount++; free(s); return 0; } break; case 2: if (strcmp(s, "bold") != 0) { _lou_logMessage(LOU_LOG_ERROR, "Third emphasis class must be \"bold\" but got " "%s", s); errorCount++; free(s); return 0; } break; } (*table)->emphClassNames[i] = s; (*table)->emphClasses[i] = (EmphasisClass){ emph_1 << i, /* relies on the order of typeforms emph_1..emph_10 */ 0, 0x1 << i, i }; return 1; case CTO_EmphLetter: case CTO_BegEmphWord: case CTO_EndEmphWord: case CTO_BegEmph: case CTO_EndEmph: case CTO_BegEmphPhrase: case CTO_EndEmphPhrase: case CTO_LenEmphPhrase: case CTO_EmphModeChars: case CTO_NoEmphChars: { if (!getToken(file, &token, "emphasis class")) return 0; if (!parseChars(file, &emphClass, &token)) return 0; char *s = malloc(sizeof(char) * (emphClass.length + 1)); int k, i; for (k = 0; k < emphClass.length; k++) s[k] = (char)emphClass.chars[k]; s[k++] = '\0'; for (i = 0; i < MAX_EMPH_CLASSES && (*table)->emphClassNames[i]; i++) if (strcmp(s, (*table)->emphClassNames[i]) == 0) break; if (i == MAX_EMPH_CLASSES || !(*table)->emphClassNames[i]) { _lou_logMessage(LOU_LOG_ERROR, "Emphasis class %s not declared", s); errorCount++; free(s); return 0; } int ok = 0; switch (opcode) { case CTO_EmphLetter: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][letterOffset]; if (!compileBrailleIndicator(file, "single letter", CTO_Emph1LetterRule + letterOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][letterOffset] = ruleOffset; ok = 1; break; } case CTO_BegEmphWord: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][begWordOffset]; if (!compileBrailleIndicator(file, "word", CTO_Emph1LetterRule + begWordOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][begWordOffset] = ruleOffset; ok = 1; break; } case CTO_EndEmphWord: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][endWordOffset]; if (!compileBrailleIndicator(file, "word stop", CTO_Emph1LetterRule + endWordOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][endWordOffset] = ruleOffset; ok = 1; break; } case CTO_BegEmph: { /* fail if both begemph and any of begemphphrase or begemphword are * defined */ if ((*table)->emphRules[i][begWordOffset] || (*table)->emphRules[i][begPhraseOffset]) { compileError(file, "Cannot define emphasis for both no context and word or " "phrase context, i.e. cannot have both begemph and " "begemphword or begemphphrase."); break; } // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][begOffset]; if (!compileBrailleIndicator(file, "first letter", CTO_Emph1LetterRule + begOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][begOffset] = ruleOffset; ok = 1; break; } case CTO_EndEmph: { if ((*table)->emphRules[i][endWordOffset] || (*table)->emphRules[i][endPhraseBeforeOffset] || (*table)->emphRules[i][endPhraseAfterOffset]) { compileError(file, "Cannot define emphasis for both no context and word or " "phrase context, i.e. cannot have both endemph and " "endemphword or endemphphrase."); break; } // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][endOffset]; if (!compileBrailleIndicator(file, "last letter", CTO_Emph1LetterRule + endOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][endOffset] = ruleOffset; ok = 1; break; } case CTO_BegEmphPhrase: { // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][begPhraseOffset]; if (!compileBrailleIndicator(file, "first word", CTO_Emph1LetterRule + begPhraseOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][begPhraseOffset] = ruleOffset; ok = 1; break; } case CTO_EndEmphPhrase: switch (compileBeforeAfter(file)) { case 1: { // before if ((*table)->emphRules[i][endPhraseAfterOffset]) { compileError(file, "last word after already defined."); break; } // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][endPhraseBeforeOffset]; if (!compileBrailleIndicator(file, "last word before", CTO_Emph1LetterRule + endPhraseBeforeOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][endPhraseBeforeOffset] = ruleOffset; ok = 1; break; } case 2: { // after if ((*table)->emphRules[i][endPhraseBeforeOffset]) { compileError(file, "last word before already defined."); break; } // not passing pointer because compileBrailleIndicator may reallocate // table TranslationTableOffset ruleOffset = (*table)->emphRules[i][endPhraseAfterOffset]; if (!compileBrailleIndicator(file, "last word after", CTO_Emph1LetterRule + endPhraseAfterOffset + (8 * i), &ruleOffset, noback, nofor, table)) break; (*table)->emphRules[i][endPhraseAfterOffset] = ruleOffset; ok = 1; break; } default: // error compileError(file, "Invalid lastword indicator location."); break; } break; case CTO_LenEmphPhrase: if (((*table)->emphRules[i][lenPhraseOffset] = compileNumber(file))) ok = 1; break; case CTO_EmphModeChars: { if (!getRuleCharsText(file, &ruleChars)) break; widechar *emphmodechars = (*table)->emphModeChars[i]; int len; for (len = 0; len < EMPHMODECHARSSIZE && emphmodechars[len]; len++) ; if (len + ruleChars.length > EMPHMODECHARSSIZE) { compileError(file, "More than %d characters", EMPHMODECHARSSIZE); break; } ok = 1; for (int k = 0; k < ruleChars.length; k++) { if (!getChar(ruleChars.chars[k], *table, NULL)) { compileError(file, "Emphasis mode character undefined"); ok = 0; break; } emphmodechars[len++] = ruleChars.chars[k]; } break; } case CTO_NoEmphChars: { if (!getRuleCharsText(file, &ruleChars)) break; widechar *noemphchars = (*table)->noEmphChars[i]; int len; for (len = 0; len < NOEMPHCHARSSIZE && noemphchars[len]; len++) ; if (len + ruleChars.length > NOEMPHCHARSSIZE) { compileError(file, "More than %d characters", NOEMPHCHARSSIZE); break; } ok = 1; for (int k = 0; k < ruleChars.length; k++) { if (!getChar(ruleChars.chars[k], *table, NULL)) { compileError(file, "Character undefined"); ok = 0; break; } noemphchars[len++] = ruleChars.chars[k]; } break; } default: break; } free(s); return ok; } case CTO_LetterSign: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->letterSign; if (!compileBrailleIndicator(file, "letter sign", CTO_LetterRule, &ruleOffset, noback, nofor, table)) return 0; (*table)->letterSign = ruleOffset; return 1; } case CTO_NoLetsignBefore: if (!getRuleCharsText(file, &ruleChars)) return 0; if (((*table)->noLetsignBeforeCount + ruleChars.length) > LETSIGNBEFORESIZE) { compileError(file, "More than %d characters", LETSIGNBEFORESIZE); return 0; } for (int k = 0; k < ruleChars.length; k++) (*table)->noLetsignBefore[(*table)->noLetsignBeforeCount++] = ruleChars.chars[k]; return 1; case CTO_NoLetsign: if (!getRuleCharsText(file, &ruleChars)) return 0; if (((*table)->noLetsignCount + ruleChars.length) > LETSIGNSIZE) { compileError(file, "More than %d characters", LETSIGNSIZE); return 0; } for (int k = 0; k < ruleChars.length; k++) (*table)->noLetsign[(*table)->noLetsignCount++] = ruleChars.chars[k]; return 1; case CTO_NoLetsignAfter: if (!getRuleCharsText(file, &ruleChars)) return 0; if (((*table)->noLetsignAfterCount + ruleChars.length) > LETSIGNAFTERSIZE) { compileError(file, "More than %d characters", LETSIGNAFTERSIZE); return 0; } for (int k = 0; k < ruleChars.length; k++) (*table)->noLetsignAfter[(*table)->noLetsignAfterCount++] = ruleChars.chars[k]; return 1; case CTO_NumberSign: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->numberSign; if (!compileBrailleIndicator(file, "number sign", CTO_NumberRule, &ruleOffset, noback, nofor, table)) return 0; (*table)->numberSign = ruleOffset; return 1; } case CTO_NumericModeChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Numeric mode character undefined: %s", _lou_showString(&ruleChars.chars[k], 1, 0)); return 0; } c->attributes |= CTC_NumericMode; (*table)->usesNumericMode = 1; } return 1; case CTO_MidEndNumericModeChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Midendnumeric mode character undefined"); return 0; } c->attributes |= CTC_MidEndNumericMode; (*table)->usesNumericMode = 1; } return 1; case CTO_NumericNoContractChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Numeric no contraction character undefined"); return 0; } c->attributes |= CTC_NumericNoContract; (*table)->usesNumericMode = 1; } return 1; case CTO_NoContractSign: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->noContractSign; if (!compileBrailleIndicator(file, "no contractions sign", CTO_NoContractRule, &ruleOffset, noback, nofor, table)) return 0; (*table)->noContractSign = ruleOffset; return 1; } case CTO_SeqDelimiter: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Sequence delimiter character undefined"); return 0; } c->attributes |= CTC_SeqDelimiter; (*table)->usesSequences = 1; } return 1; case CTO_SeqBeforeChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Sequence before character undefined"); return 0; } c->attributes |= CTC_SeqBefore; } return 1; case CTO_SeqAfterChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Sequence after character undefined"); return 0; } c->attributes |= CTC_SeqAfter; } return 1; case CTO_SeqAfterPattern: if (!getRuleCharsText(file, &ruleChars)) return 0; if (((*table)->seqPatternsCount + ruleChars.length + 1) > SEQPATTERNSIZE) { compileError(file, "More than %d characters", SEQPATTERNSIZE); return 0; } for (int k = 0; k < ruleChars.length; k++) (*table)->seqPatterns[(*table)->seqPatternsCount++] = ruleChars.chars[k]; (*table)->seqPatterns[(*table)->seqPatternsCount++] = 0; return 1; case CTO_SeqAfterExpression: if (!getRuleCharsText(file, &ruleChars)) return 0; for ((*table)->seqAfterExpressionLength = 0; (*table)->seqAfterExpressionLength < ruleChars.length; (*table)->seqAfterExpressionLength++) (*table)->seqAfterExpression[(*table)->seqAfterExpressionLength] = ruleChars.chars[(*table)->seqAfterExpressionLength]; (*table)->seqAfterExpression[(*table)->seqAfterExpressionLength] = 0; return 1; case CTO_CapsModeChars: if (!getRuleCharsText(file, &ruleChars)) return 0; for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!c) { compileError(file, "Capital mode character undefined"); return 0; } c->attributes |= CTC_CapsMode; (*table)->hasCapsModeChars = 1; } return 1; case CTO_BegComp: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->begComp; if (!compileBrailleIndicator(file, "begin computer braille", CTO_BegCompRule, &ruleOffset, noback, nofor, table)) return 0; (*table)->begComp = ruleOffset; return 1; } case CTO_EndComp: { // not passing pointer because compileBrailleIndicator may reallocate table TranslationTableOffset ruleOffset = (*table)->endComp; if (!compileBrailleIndicator(file, "end computer braslle", CTO_EndCompRule, &ruleOffset, noback, nofor, table)) return 0; (*table)->endComp = ruleOffset; return 1; } case CTO_NoCross: if (nocross) { compileError( file, "%s already specified.", _lou_findOpcodeName(CTO_NoCross)); return 0; } nocross = 1; goto doOpcode; case CTO_Syllable: (*table)->syllables = 1; case CTO_Always: case CTO_LargeSign: case CTO_WholeWord: case CTO_PartWord: case CTO_JoinNum: case CTO_JoinableWord: case CTO_LowWord: case CTO_SuffixableWord: case CTO_PrefixableWord: case CTO_BegWord: case CTO_BegMidWord: case CTO_MidWord: case CTO_MidEndWord: case CTO_EndWord: case CTO_PrePunc: case CTO_PostPunc: case CTO_BegNum: case CTO_MidNum: case CTO_EndNum: case CTO_Repeated: case CTO_RepWord: if (!getRuleCharsText(file, &ruleChars)) return 0; if (!getRuleDotsPattern(file, &ruleDots)) return 0; if (ruleDots.length == 0) // check that all characters in a rule with `=` as second operand are // defined (or based on another character) for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!(c && (c->definitionRule || c->basechar))) { compileError(file, "Character %s is not defined", _lou_showString(&ruleChars.chars[k], 1, 0)); return 0; } } TranslationTableRule *r; if (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, &r, noback, nofor, table)) return 0; if (nocross) r->nocross = 1; return 1; // if (opcode == CTO_MidNum) // { // TranslationTableCharacter *c = getChar(ruleChars.chars[0]); // if(c) // c->attributes |= CTC_NumericMode; // } case CTO_RepEndWord: if (!getRuleCharsText(file, &ruleChars)) return 0; CharsString dots; if (!getToken(file, &dots, "dots,dots operand")) return 0; int len = dots.length; for (int k = 0; k < len - 1; k++) { if (dots.chars[k] == ',') { dots.length = k; if (!parseDots(file, &ruleDots, &dots)) return 0; ruleDots.chars[ruleDots.length++] = ','; k++; if (k == len - 1 && dots.chars[k] == '=') { // check that all characters are defined (or based on another // character) for (int l = 0; l < ruleChars.length; l++) { TranslationTableCharacter *c = getChar(ruleChars.chars[l], *table, NULL); if (!(c && (c->definitionRule || c->basechar))) { compileError(file, "Character %s is not defined", _lou_showString(&ruleChars.chars[l], 1, 0)); return 0; } } } else { CharsString x, y; x.length = 0; while (k < len) x.chars[x.length++] = dots.chars[k++]; if (parseDots(file, &y, &x)) for (int l = 0; l < y.length; l++) ruleDots.chars[ruleDots.length++] = y.chars[l]; } return addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL, noback, nofor, table); } } return 0; case CTO_CompDots: case CTO_Comp6: { TranslationTableOffset ruleOffset; if (!getRuleCharsText(file, &ruleChars)) return 0; if (ruleChars.length != 1) { compileError(file, "first operand must be 1 character"); return 0; } if (nofor || noback) { compileWarning(file, "nofor and noback not allowed on comp6 rules"); } if (!getRuleDotsPattern(file, &ruleDots)) return 0; if (!addRule(file, opcode, &ruleChars, &ruleDots, after, before, &ruleOffset, NULL, noback, nofor, table)) return 0; return 1; } case CTO_ExactDots: if (!getRuleCharsText(file, &ruleChars)) return 0; if (ruleChars.chars[0] != '@') { compileError(file, "The operand must begin with an at sign (@)"); return 0; } for (int k = 1; k < ruleChars.length; k++) scratchPad.chars[k - 1] = ruleChars.chars[k]; scratchPad.length = ruleChars.length - 1; if (!parseDots(file, &ruleDots, &scratchPad)) return 0; return addRule(file, opcode, &ruleChars, &ruleDots, before, after, NULL, NULL, noback, nofor, table); case CTO_CapsNoCont: { TranslationTableOffset ruleOffset; ruleChars.length = 1; ruleChars.chars[0] = 'a'; if (!addRule(file, CTO_CapsNoContRule, &ruleChars, NULL, after, before, &ruleOffset, NULL, noback, nofor, table)) return 0; (*table)->capsNoCont = ruleOffset; return 1; } case CTO_Replace: if (getRuleCharsText(file, &ruleChars)) { if (atEndOfLine(file)) ruleDots.length = ruleDots.chars[0] = 0; else { getRuleDotsText(file, &ruleDots); if (ruleDots.chars[0] == '#') ruleDots.length = ruleDots.chars[0] = 0; else if (ruleDots.chars[0] == '\\' && ruleDots.chars[1] == '#') memmove(&ruleDots.chars[0], &ruleDots.chars[1], ruleDots.length-- * CHARSIZE); } } for (int k = 0; k < ruleChars.length; k++) putChar(file, ruleChars.chars[k], table, NULL); for (int k = 0; k < ruleDots.length; k++) putChar(file, ruleDots.chars[k], table, NULL); return addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL, noback, nofor, table); case CTO_Correct: (*table)->corrections = 1; goto doPass; case CTO_Pass2: if ((*table)->numPasses < 2) (*table)->numPasses = 2; goto doPass; case CTO_Pass3: if ((*table)->numPasses < 3) (*table)->numPasses = 3; goto doPass; case CTO_Pass4: if ((*table)->numPasses < 4) (*table)->numPasses = 4; doPass: case CTO_Context: if (!(nofor || noback)) { compileError(file, "%s or %s must be specified.", _lou_findOpcodeName(CTO_NoFor), _lou_findOpcodeName(CTO_NoBack)); return 0; } return compilePassOpcode(file, opcode, noback, nofor, table); case CTO_Contraction: case CTO_NoCont: case CTO_CompBrl: case CTO_Literal: if (!getRuleCharsText(file, &ruleChars)) return 0; // check that all characters in a compbrl, contraction, // nocont or literal rule are defined (or based on another // character) for (int k = 0; k < ruleChars.length; k++) { TranslationTableCharacter *c = getChar(ruleChars.chars[k], *table, NULL); if (!(c && (c->definitionRule || c->basechar))) { compileError(file, "Character %s is not defined", _lou_showString(&ruleChars.chars[k], 1, 0)); return 0; } } return addRule(file, opcode, &ruleChars, NULL, after, before, NULL, NULL, noback, nofor, table); case CTO_MultInd: { ruleChars.length = 0; if (!getToken(file, &token, "multiple braille indicators") || !parseDots(file, &cells, &token)) return 0; while (getToken(file, &token, "multind opcodes")) { opcode = getOpcode(file, &token); if (opcode == CTO_None) { compileError(file, "opcode %s not defined.", _lou_showString(token.chars, token.length, 0)); return 0; } if (!(opcode >= CTO_CapsLetter && opcode < CTO_MultInd)) { compileError(file, "Not a braille indicator opcode."); return 0; } ruleChars.chars[ruleChars.length++] = (widechar)opcode; if (atEndOfLine(file)) break; } return addRule(file, CTO_MultInd, &ruleChars, &cells, after, before, NULL, NULL, noback, nofor, table); } case CTO_Class: compileWarning(file, "class is deprecated, use attribute instead"); case CTO_Attribute: { if (nofor || noback) { compileWarning( file, "nofor and noback not allowed before class/attribute"); } if ((opcode == CTO_Class && (*table)->usesAttributeOrClass == 1) || (opcode == CTO_Attribute && (*table)->usesAttributeOrClass == 2)) { compileError(file, "attribute and class rules must not be both present in a table"); return 0; } if (opcode == CTO_Class) (*table)->usesAttributeOrClass = 2; else (*table)->usesAttributeOrClass = 1; if (!getToken(file, &token, "attribute name")) { compileError(file, "Expected %s", "attribute name"); return 0; } if (!(*table)->characterClasses && !allocateCharacterClasses(*table)) { return 0; } TranslationTableCharacterAttributes attribute = 0; { int attrNumber = -1; switch (token.chars[0]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': attrNumber = token.chars[0] - '0'; break; } if (attrNumber >= 0) { if (opcode == CTO_Class) { compileError(file, "Invalid class name: may not contain digits, use " "attribute instead of class"); return 0; } if (token.length > 1 || attrNumber > 7) { compileError(file, "Invalid attribute name: must be a digit between 0 and 7 " "or a word containing only letters"); return 0; } if (!(*table)->numberedAttributes[attrNumber]) // attribute not used before yet: assign it a value (*table)->numberedAttributes[attrNumber] = getNextNumberedAttribute(*table); attribute = (*table)->numberedAttributes[attrNumber]; } else { const CharacterClass *namedAttr = findCharacterClass(&token, *table); if (!namedAttr) { // no class with that name: create one namedAttr = addCharacterClass( file, &token.chars[0], token.length, *table, 1); if (!namedAttr) return 0; } // there is a class with that name or a new class was successfully // created attribute = namedAttr->attribute; if (attribute == CTC_UpperCase || attribute == CTC_LowerCase) attribute |= CTC_Letter; } } CharsString characters; if (!getCharacters(file, &characters)) return 0; for (int i = 0; i < characters.length; i++) { // get the character from the table, or if it is not defined yet, // define it TranslationTableCharacter *character = putChar(file, characters.chars[i], table, NULL); // set the attribute character->attributes |= attribute; // also set the attribute on the associated dots (if any) if (character->basechar) character = (TranslationTableCharacter *)&(*table) ->ruleArea[character->basechar]; if (character->definitionRule) { TranslationTableRule *defRule = (TranslationTableRule *)&(*table) ->ruleArea[character->definitionRule]; if (defRule->dotslen == 1) { TranslationTableCharacter *dots = getDots(defRule->charsdots[defRule->charslen], *table); if (dots) dots->attributes |= attribute; } } } return 1; } { TranslationTableCharacterAttributes *attributes; const CharacterClass *class; case CTO_After: attributes = &after; goto doBeforeAfter; case CTO_Before: attributes = &before; doBeforeAfter: if (!(*table)->characterClasses) { if (!allocateCharacterClasses(*table)) return 0; } if (!getToken(file, &token, "attribute name")) return 0; if (!(class = findCharacterClass(&token, *table))) { compileError(file, "attribute not defined"); return 0; } *attributes |= class->attribute; goto doOpcode; } case CTO_Base: if (nofor || noback) { compileWarning(file, "nofor and noback not allowed before base"); } if (!getToken(file, &token, "attribute name")) { compileError( file, "base opcode must be followed by a valid attribute name."); return 0; } if (!(*table)->characterClasses && !allocateCharacterClasses(*table)) { return 0; } const CharacterClass *mode = findCharacterClass(&token, *table); if (!mode) { mode = addCharacterClass(file, token.chars, token.length, *table, 1); if (!mode) return 0; } if (!(mode->attribute == CTC_UpperCase || mode->attribute == CTC_Digit) && mode->attribute >= CTC_Space && mode->attribute <= CTC_LitDigit) { compileError(file, "base opcode must be followed by \"uppercase\", \"digit\", or a " "custom attribute name."); return 0; } if (!getRuleCharsText(file, &token)) return 0; if (token.length != 1) { compileError(file, "Exactly one character followed by one base character is " "required."); return 0; } TranslationTableOffset characterOffset; TranslationTableCharacter *character = putChar(file, token.chars[0], table, &characterOffset); if (!getRuleCharsText(file, &token)) return 0; if (token.length != 1) { compileError(file, "Exactly one base character is required."); return 0; } if (character->definitionRule) { TranslationTableRule *prevRule = (TranslationTableRule *)&(*table) ->ruleArea[character->definitionRule]; _lou_logMessage(LOU_LOG_DEBUG, "%s:%d: Character already defined (%s). The base rule will take " "precedence.", file->fileName, file->lineNumber, printSource(file, prevRule->sourceFile, prevRule->sourceLine)); character->definitionRule = 0; } TranslationTableOffset basechar; putChar(file, token.chars[0], table, &basechar); // putChar may have moved table, so make sure character is still valid character = (TranslationTableCharacter *)&(*table)->ruleArea[characterOffset]; if (character->basechar) { if (character->basechar == basechar && character->mode == mode->attribute) { _lou_logMessage(LOU_LOG_DEBUG, "%s:%d: Duplicate base rule.", file->fileName, file->lineNumber); } else { _lou_logMessage(LOU_LOG_DEBUG, "%s:%d: A different base rule already exists for this " "character (%s). The new rule will take precedence.", file->fileName, file->lineNumber, printSource( file, character->sourceFile, character->sourceLine)); } } character->basechar = basechar; character->mode = mode->attribute; character->sourceFile = file->sourceFile; character->sourceLine = file->lineNumber; /* some other processing is done at the end of the compilation, in * finalizeTable() */ return 1; case CTO_EmpMatchBefore: before |= CTC_EmpMatch; goto doOpcode; case CTO_EmpMatchAfter: after |= CTC_EmpMatch; goto doOpcode; case CTO_SwapCc: case CTO_SwapCd: case CTO_SwapDd: return compileSwap(file, opcode, noback, nofor, table); case CTO_Hyphen: case CTO_DecPoint: // case CTO_Apostrophe: // case CTO_Initial: if (!getRuleCharsText(file, &ruleChars)) return 0; if (!getRuleDotsPattern(file, &ruleDots)) return 0; if (ruleChars.length != 1 || ruleDots.length < 1) { compileError(file, "One Unicode character and at least one cell are " "required."); return 0; } return addRule(file, opcode, &ruleChars, &ruleDots, after, before, NULL, NULL, noback, nofor, table); // if (opcode == CTO_DecPoint) // { // TranslationTableCharacter *c = // getChar(ruleChars.chars[0]); // if(c) // c->attributes |= CTC_NumericMode; // } default: compileError(file, "unimplemented opcode."); return 0; } } return 0; }
1
CVE-2022-31783
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]. Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
7,099
Android
e86d3cfd2bc28dac421092106751e5638d54a848
WORD32 check_app_out_buf_size(dec_struct_t *ps_dec) { UWORD32 au4_min_out_buf_size[IVD_VIDDEC_MAX_IO_BUFFERS]; UWORD32 u4_min_num_out_bufs, i; UWORD32 pic_wd, pic_ht; if(0 == ps_dec->u4_share_disp_buf) { pic_wd = ps_dec->u2_disp_width; pic_ht = ps_dec->u2_disp_height; } else { /* In case of shared mode, do not check validity of ps_dec->ps_out_buffer */ return (IV_SUCCESS); } if(ps_dec->u4_app_disp_width > pic_wd) pic_wd = ps_dec->u4_app_disp_width; u4_min_num_out_bufs = ih264d_get_outbuf_size(pic_wd, pic_ht, ps_dec->u1_chroma_format, &au4_min_out_buf_size[0]); if(ps_dec->ps_out_buffer->u4_num_bufs < u4_min_num_out_bufs) return IV_FAIL; for(i = 0; i < u4_min_num_out_bufs; i++) { if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] < au4_min_out_buf_size[i]) return (IV_FAIL); } return (IV_SUCCESS); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,562
libpng
1bef8e97995c33123665582e57d3ed40b57d5978
png_set_chunk_malloc_max (png_structrp png_ptr, png_alloc_size_t user_chunk_malloc_max) { if (png_ptr != NULL) png_ptr->user_chunk_malloc_max = user_chunk_malloc_max; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,767
libvncserver
a64c3b37af9a6c8f8009d7516874b8d266b42bae
HandleRFBServerMessage(rfbClient* client) { rfbServerToClientMsg msg; if (client->serverPort==-1) client->vncRec->readTimestamp = TRUE; if (!ReadFromRFBServer(client, (char *)&msg, 1)) return FALSE; switch (msg.type) { case rfbSetColourMapEntries: { /* TODO: int i; uint16_t rgb[3]; XColor xc; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbSetColourMapEntriesMsg - 1)) return FALSE; msg.scme.firstColour = rfbClientSwap16IfLE(msg.scme.firstColour); msg.scme.nColours = rfbClientSwap16IfLE(msg.scme.nColours); for (i = 0; i < msg.scme.nColours; i++) { if (!ReadFromRFBServer(client, (char *)rgb, 6)) return FALSE; xc.pixel = msg.scme.firstColour + i; xc.red = rfbClientSwap16IfLE(rgb[0]); xc.green = rfbClientSwap16IfLE(rgb[1]); xc.blue = rfbClientSwap16IfLE(rgb[2]); xc.flags = DoRed|DoGreen|DoBlue; XStoreColor(dpy, cmap, &xc); } */ break; } case rfbFramebufferUpdate: { rfbFramebufferUpdateRectHeader rect; int linesToRead; int bytesPerLine; int i; if (!ReadFromRFBServer(client, ((char *)&msg.fu) + 1, sz_rfbFramebufferUpdateMsg - 1)) return FALSE; msg.fu.nRects = rfbClientSwap16IfLE(msg.fu.nRects); for (i = 0; i < msg.fu.nRects; i++) { if (!ReadFromRFBServer(client, (char *)&rect, sz_rfbFramebufferUpdateRectHeader)) return FALSE; rect.encoding = rfbClientSwap32IfLE(rect.encoding); if (rect.encoding == rfbEncodingLastRect) break; rect.r.x = rfbClientSwap16IfLE(rect.r.x); rect.r.y = rfbClientSwap16IfLE(rect.r.y); rect.r.w = rfbClientSwap16IfLE(rect.r.w); rect.r.h = rfbClientSwap16IfLE(rect.r.h); if (rect.encoding == rfbEncodingXCursor || rect.encoding == rfbEncodingRichCursor) { if (!HandleCursorShape(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h, rect.encoding)) { return FALSE; } continue; } if (rect.encoding == rfbEncodingPointerPos) { if (!client->HandleCursorPos(client,rect.r.x, rect.r.y)) { return FALSE; } continue; } if (rect.encoding == rfbEncodingKeyboardLedState) { /* OK! We have received a keyboard state message!!! */ client->KeyboardLedStateEnabled = 1; if (client->HandleKeyboardLedState!=NULL) client->HandleKeyboardLedState(client, rect.r.x, 0); /* stash it for the future */ client->CurrentKeyboardLedState = rect.r.x; continue; } if (rect.encoding == rfbEncodingNewFBSize) { client->width = rect.r.w; client->height = rect.r.h; client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, rect.r.w, rect.r.h, FALSE); rfbClientLog("Got new framebuffer size: %dx%d\n", rect.r.w, rect.r.h); continue; } /* rect.r.w=byte count */ if (rect.encoding == rfbEncodingSupportedMessages) { int loop; if (!ReadFromRFBServer(client, (char *)&client->supportedMessages, sz_rfbSupportedMessages)) return FALSE; /* msgs is two sets of bit flags of supported messages client2server[] and server2client[] */ /* currently ignored by this library */ rfbClientLog("client2server supported messages (bit flags)\n"); for (loop=0;loop<32;loop+=8) rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop, client->supportedMessages.client2server[loop], client->supportedMessages.client2server[loop+1], client->supportedMessages.client2server[loop+2], client->supportedMessages.client2server[loop+3], client->supportedMessages.client2server[loop+4], client->supportedMessages.client2server[loop+5], client->supportedMessages.client2server[loop+6], client->supportedMessages.client2server[loop+7]); rfbClientLog("server2client supported messages (bit flags)\n"); for (loop=0;loop<32;loop+=8) rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop, client->supportedMessages.server2client[loop], client->supportedMessages.server2client[loop+1], client->supportedMessages.server2client[loop+2], client->supportedMessages.server2client[loop+3], client->supportedMessages.server2client[loop+4], client->supportedMessages.server2client[loop+5], client->supportedMessages.server2client[loop+6], client->supportedMessages.server2client[loop+7]); continue; } /* rect.r.w=byte count, rect.r.h=# of encodings */ if (rect.encoding == rfbEncodingSupportedEncodings) { char *buffer; buffer = malloc(rect.r.w); if (!ReadFromRFBServer(client, buffer, rect.r.w)) { free(buffer); return FALSE; } /* buffer now contains rect.r.h # of uint32_t encodings that the server supports */ /* currently ignored by this library */ free(buffer); continue; } /* rect.r.w=byte count */ if (rect.encoding == rfbEncodingServerIdentity) { char *buffer; buffer = malloc(rect.r.w+1); if (!ReadFromRFBServer(client, buffer, rect.r.w)) { free(buffer); return FALSE; } buffer[rect.r.w]=0; /* null terminate, just in case */ rfbClientLog("Connected to Server \"%s\"\n", buffer); free(buffer); continue; } /* rfbEncodingUltraZip is a collection of subrects. x = # of subrects, and h is always 0 */ if (rect.encoding != rfbEncodingUltraZip) { if ((rect.r.x + rect.r.w > client->width) || (rect.r.y + rect.r.h > client->height)) { rfbClientLog("Rect too large: %dx%d at (%d, %d)\n", rect.r.w, rect.r.h, rect.r.x, rect.r.y); return FALSE; } /* UltraVNC with scaling, will send rectangles with a zero W or H * if ((rect.encoding != rfbEncodingTight) && (rect.r.h * rect.r.w == 0)) { rfbClientLog("Zero size rect - ignoring (encoding=%d (0x%08x) %dx, %dy, %dw, %dh)\n", rect.encoding, rect.encoding, rect.r.x, rect.r.y, rect.r.w, rect.r.h); continue; } */ /* If RichCursor encoding is used, we should prevent collisions between framebuffer updates and cursor drawing operations. */ client->SoftCursorLockArea(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h); } switch (rect.encoding) { case rfbEncodingRaw: { int y=rect.r.y, h=rect.r.h; bytesPerLine = rect.r.w * client->format.bitsPerPixel / 8; /* RealVNC 4.x-5.x on OSX can induce bytesPerLine==0, usually during GPU accel. */ /* Regardless of cause, do not divide by zero. */ linesToRead = bytesPerLine ? (RFB_BUFFER_SIZE / bytesPerLine) : 0; while (linesToRead && h > 0) { if (linesToRead > h) linesToRead = h; if (!ReadFromRFBServer(client, client->buffer,bytesPerLine * linesToRead)) return FALSE; client->GotBitmap(client, (uint8_t *)client->buffer, rect.r.x, y, rect.r.w,linesToRead); h -= linesToRead; y += linesToRead; } break; } case rfbEncodingCopyRect: { rfbCopyRect cr; if (!ReadFromRFBServer(client, (char *)&cr, sz_rfbCopyRect)) return FALSE; cr.srcX = rfbClientSwap16IfLE(cr.srcX); cr.srcY = rfbClientSwap16IfLE(cr.srcY); /* If RichCursor encoding is used, we should extend our "cursor lock area" (previously set to destination rectangle) to the source rectangle as well. */ client->SoftCursorLockArea(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h); client->GotCopyRect(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h, rect.r.x, rect.r.y); break; } case rfbEncodingRRE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingCoRRE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleCoRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleCoRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleCoRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingHextile: { switch (client->format.bitsPerPixel) { case 8: if (!HandleHextile8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleHextile16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleHextile32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingUltra: { switch (client->format.bitsPerPixel) { case 8: if (!HandleUltra8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleUltra16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleUltra32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingUltraZip: { switch (client->format.bitsPerPixel) { case 8: if (!HandleUltraZip8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleUltraZip16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleUltraZip32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingTRLE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleTRLE8(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; break; case 16: if (client->si.format.greenMax > 0x1F) { if (!HandleTRLE16(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else { if (!HandleTRLE15(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } break; case 32: { uint32_t maxColor = (client->format.redMax << client->format.redShift) | (client->format.greenMax << client->format.greenShift) | (client->format.blueMax << client->format.blueShift); if ((client->format.bigEndian && (maxColor & 0xff) == 0) || (!client->format.bigEndian && (maxColor & 0xff000000) == 0)) { if (!HandleTRLE24(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (!client->format.bigEndian && (maxColor & 0xff) == 0) { if (!HandleTRLE24Up(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (client->format.bigEndian && (maxColor & 0xff000000) == 0) { if (!HandleTRLE24Down(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (!HandleTRLE32(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; break; } } break; } #ifdef LIBVNCSERVER_HAVE_LIBZ case rfbEncodingZlib: { switch (client->format.bitsPerPixel) { case 8: if (!HandleZlib8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleZlib16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleZlib32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } #ifdef LIBVNCSERVER_HAVE_LIBJPEG case rfbEncodingTight: { switch (client->format.bitsPerPixel) { case 8: if (!HandleTight8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleTight16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleTight32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } #endif case rfbEncodingZRLE: /* Fail safe for ZYWRLE unsupport VNC server. */ client->appData.qualityLevel = 9; /* fall through */ case rfbEncodingZYWRLE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleZRLE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (client->si.format.greenMax > 0x1F) { if (!HandleZRLE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else { if (!HandleZRLE15(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } break; case 32: { uint32_t maxColor=(client->format.redMax<<client->format.redShift)| (client->format.greenMax<<client->format.greenShift)| (client->format.blueMax<<client->format.blueShift); if ((client->format.bigEndian && (maxColor&0xff)==0) || (!client->format.bigEndian && (maxColor&0xff000000)==0)) { if (!HandleZRLE24(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (!client->format.bigEndian && (maxColor&0xff)==0) { if (!HandleZRLE24Up(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (client->format.bigEndian && (maxColor&0xff000000)==0) { if (!HandleZRLE24Down(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (!HandleZRLE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } } break; } #endif default: { rfbBool handled = FALSE; rfbClientProtocolExtension* e; for(e = rfbClientExtensions; !handled && e; e = e->next) if(e->handleEncoding && e->handleEncoding(client, &rect)) handled = TRUE; if(!handled) { rfbClientLog("Unknown rect encoding %d\n", (int)rect.encoding); return FALSE; } } } /* Now we may discard "soft cursor locks". */ client->SoftCursorUnlockScreen(client); client->GotFrameBufferUpdate(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h); } if (!SendIncrementalFramebufferUpdateRequest(client)) return FALSE; if (client->FinishedFrameBufferUpdate) client->FinishedFrameBufferUpdate(client); break; } case rfbBell: { client->Bell(client); break; } case rfbServerCutText: { char *buffer; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbServerCutTextMsg - 1)) return FALSE; msg.sct.length = rfbClientSwap32IfLE(msg.sct.length); if (msg.sct.length > 1<<20) { rfbClientErr("Ignoring too big cut text length sent by server: %u B > 1 MB\n", (unsigned int)msg.sct.length); return FALSE; } buffer = malloc((uint64_t)msg.sct.length+1); if (!ReadFromRFBServer(client, buffer, msg.sct.length)) { free(buffer); return FALSE; } buffer[msg.sct.length] = 0; if (client->GotXCutText) client->GotXCutText(client, buffer, msg.sct.length); free(buffer); break; } case rfbTextChat: { char *buffer=NULL; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbTextChatMsg- 1)) return FALSE; msg.tc.length = rfbClientSwap32IfLE(msg.sct.length); switch(msg.tc.length) { case rfbTextChatOpen: rfbClientLog("Received TextChat Open\n"); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatOpen, NULL); break; case rfbTextChatClose: rfbClientLog("Received TextChat Close\n"); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatClose, NULL); break; case rfbTextChatFinished: rfbClientLog("Received TextChat Finished\n"); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatFinished, NULL); break; default: buffer=malloc(msg.tc.length+1); if (!ReadFromRFBServer(client, buffer, msg.tc.length)) { free(buffer); return FALSE; } /* Null Terminate <just in case> */ buffer[msg.tc.length]=0; rfbClientLog("Received TextChat \"%s\"\n", buffer); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)msg.tc.length, buffer); free(buffer); break; } break; } case rfbXvp: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbXvpMsg -1)) return FALSE; SetClient2Server(client, rfbXvp); /* technically, we only care what we can *send* to the server * but, we set Server2Client Just in case it ever becomes useful */ SetServer2Client(client, rfbXvp); if(client->HandleXvpMsg) client->HandleXvpMsg(client, msg.xvp.version, msg.xvp.code); break; } case rfbResizeFrameBuffer: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbResizeFrameBufferMsg -1)) return FALSE; client->width = rfbClientSwap16IfLE(msg.rsfb.framebufferWidth); client->height = rfbClientSwap16IfLE(msg.rsfb.framebufferHeigth); client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE); rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height); break; } case rfbPalmVNCReSizeFrameBuffer: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbPalmVNCReSizeFrameBufferMsg -1)) return FALSE; client->width = rfbClientSwap16IfLE(msg.prsfb.buffer_w); client->height = rfbClientSwap16IfLE(msg.prsfb.buffer_h); client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE); rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height); break; } default: { rfbBool handled = FALSE; rfbClientProtocolExtension* e; for(e = rfbClientExtensions; !handled && e; e = e->next) if(e->handleMessage && e->handleMessage(client, &msg)) handled = TRUE; if(!handled) { char buffer[256]; rfbClientLog("Unknown message type %d from VNC server\n",msg.type); ReadFromRFBServer(client, buffer, 256); return FALSE; } } } return TRUE; }
1
CVE-2018-20748
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]. Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
3,430